qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
1,478,697 | I frequently see python code similar to
```
for line in open(filename):
do_something(line)
```
When does filename get closed with this code?
Would it be better to write
```
with open(filename) as f:
for line in f.readlines():
do_something(line)
``` | 2009/09/25 | [
"https://Stackoverflow.com/questions/1478697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/173922/"
] | `filename` would be closed when it falls out of scope. That normally would be the end of the method.
Yes, it's better to use `with`.
>
> Once you have a file object, you perform all file I/O by calling methods of this object. [...] When you are done with the file, you should finish by calling the `close` method on the object, to close the connection to the file:
>
>
>
> ```
> input.close()
>
> ```
>
> In short scripts, people often omit this step, as Python automatically closes the file when a file object is reclaimed during garbage collection (which in mainstream Python means the file is closed just about at once, although other important Python implementations, such as Jython and IronPython, have other, more relaxed garbage collection strategies). Nevertheless, it is good programming practice to close your files as soon as possible, and it is especially a good idea in larger programs, which otherwise may be at more risk of having excessive numbers of uselessly open files lying about. Note that `try`/`finally` is particularly well suited to ensuing that a file gets closed, even when a function terminates due to an uncaught exception.
>
>
>
*[Python Cookbook, Page 59.](http://books.google.com.ar/books?id=1Shx_VXS6ioC&pg=PA59&lpg=PA59&dq=garbage+collection+python+file+open&source=bl&ots=BB6-bAT8Q2&sig=w3L8P8EOVDQ-HS6NlBWdXdiN-kk&hl=es&ei=GgO9SvaJIdWPtgfU-8yKAw&sa=X&oi=book_result&ct=result&resnum=2#v=onepage&q=garbage%20collection%20python%20file%20open&f=false)* | Drop `.readlines()`. It is redundant and undesirable for large files (due to memory consumption). The variant with `'with'` block always closes file.
```
with open(filename) as file_:
for line in file_:
do_something(line)
```
When file will be closed in the bare `'for'`-loop variant depends on Python implementation. |
1,478,697 | I frequently see python code similar to
```
for line in open(filename):
do_something(line)
```
When does filename get closed with this code?
Would it be better to write
```
with open(filename) as f:
for line in f.readlines():
do_something(line)
``` | 2009/09/25 | [
"https://Stackoverflow.com/questions/1478697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/173922/"
] | Drop `.readlines()`. It is redundant and undesirable for large files (due to memory consumption). The variant with `'with'` block always closes file.
```
with open(filename) as file_:
for line in file_:
do_something(line)
```
When file will be closed in the bare `'for'`-loop variant depends on Python implementation. | python is garbage-collected - cpython has reference counting and a backup cycle detecting garbage collector.
File objects close their file handle when the are deleted/finalized.
Thus the file will be eventually closed, and in cpython will closed as soon as the for loop finishes. |
16,574,731 | This was a question on my assignment:
Which of the following is not an acceptable way of indicating comments? Why?
* /\*\* comment \*/
* /\* comment \*/
* // comment
* // comment comment
* /\*comment comment \*/
In all honestly, they all look fine to me. But I was thinking that it could be /\*\* comment \*/ because it's not multi-lined in the example but that's its purpose--documentation. What do you think?
This is the only question that's giving me a hard time. Any help would be appreciated! Thank you. | 2013/05/15 | [
"https://Stackoverflow.com/questions/16574731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2383999/"
] | The first bullet:
```
/** comment */
```
This type of comment is for documentation. Source:
<http://journals.ecs.soton.ac.uk/java/tutorial/getStarted/application/comments.html>
Just pointing this out since it's different from the other types of comments. You could be right about the multi-line comment though. | You should put this in a java file and compile each one then see which one gives you the error. You don't have to reason about it to guess the answer. |
16,574,731 | This was a question on my assignment:
Which of the following is not an acceptable way of indicating comments? Why?
* /\*\* comment \*/
* /\* comment \*/
* // comment
* // comment comment
* /\*comment comment \*/
In all honestly, they all look fine to me. But I was thinking that it could be /\*\* comment \*/ because it's not multi-lined in the example but that's its purpose--documentation. What do you think?
This is the only question that's giving me a hard time. Any help would be appreciated! Thank you. | 2013/05/15 | [
"https://Stackoverflow.com/questions/16574731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2383999/"
] | The Java language specification states that there are two kinds of comments, "//" and "/\* ... \*/".
<http://docs.oracle.com/javase/specs/jls/se5.0/html/lexical.html#3.7>
It is a trick question. But since /\*\* ... \*/ is used by JavaDoc tools to create JavaDocs, I would say the first choice is not an acceptable answer. | You should put this in a java file and compile each one then see which one gives you the error. You don't have to reason about it to guess the answer. |
16,574,731 | This was a question on my assignment:
Which of the following is not an acceptable way of indicating comments? Why?
* /\*\* comment \*/
* /\* comment \*/
* // comment
* // comment comment
* /\*comment comment \*/
In all honestly, they all look fine to me. But I was thinking that it could be /\*\* comment \*/ because it's not multi-lined in the example but that's its purpose--documentation. What do you think?
This is the only question that's giving me a hard time. Any help would be appreciated! Thank you. | 2013/05/15 | [
"https://Stackoverflow.com/questions/16574731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2383999/"
] | In terms of grammar, none of the above ways of indicating comments is not acceptable.
However, to make other people easier to understand your code, then I would suggest
to follow some of the major coding styles.
For example, the [Oracle coding style](http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html)
is one of the popular coding styles for Java.
In its coding style, there are two types of comments. The first is implementation comment,
which uses /\* \*/ for block comments and // for single line comments.
```
/*
* Here is a block comment.
*/
// Here is a single line comment.
```
The second type is the documentation comment, which usually uses /\*\* \*/ styled comment and
only appears right before the class, function, and variable definitions. For example:
```
/**
* Documentation for some class.
*/
public class someClass {
/**
* Documentation for the constructor.
* @param someParam blah blah blah
*/
public someClass(int someParam) {
...
}
...
}
``` | You should put this in a java file and compile each one then see which one gives you the error. You don't have to reason about it to guess the answer. |
16,574,731 | This was a question on my assignment:
Which of the following is not an acceptable way of indicating comments? Why?
* /\*\* comment \*/
* /\* comment \*/
* // comment
* // comment comment
* /\*comment comment \*/
In all honestly, they all look fine to me. But I was thinking that it could be /\*\* comment \*/ because it's not multi-lined in the example but that's its purpose--documentation. What do you think?
This is the only question that's giving me a hard time. Any help would be appreciated! Thank you. | 2013/05/15 | [
"https://Stackoverflow.com/questions/16574731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2383999/"
] | In terms of grammar, none of the above ways of indicating comments is not acceptable.
However, to make other people easier to understand your code, then I would suggest
to follow some of the major coding styles.
For example, the [Oracle coding style](http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html)
is one of the popular coding styles for Java.
In its coding style, there are two types of comments. The first is implementation comment,
which uses /\* \*/ for block comments and // for single line comments.
```
/*
* Here is a block comment.
*/
// Here is a single line comment.
```
The second type is the documentation comment, which usually uses /\*\* \*/ styled comment and
only appears right before the class, function, and variable definitions. For example:
```
/**
* Documentation for some class.
*/
public class someClass {
/**
* Documentation for the constructor.
* @param someParam blah blah blah
*/
public someClass(int someParam) {
...
}
...
}
``` | The first bullet:
```
/** comment */
```
This type of comment is for documentation. Source:
<http://journals.ecs.soton.ac.uk/java/tutorial/getStarted/application/comments.html>
Just pointing this out since it's different from the other types of comments. You could be right about the multi-line comment though. |
16,574,731 | This was a question on my assignment:
Which of the following is not an acceptable way of indicating comments? Why?
* /\*\* comment \*/
* /\* comment \*/
* // comment
* // comment comment
* /\*comment comment \*/
In all honestly, they all look fine to me. But I was thinking that it could be /\*\* comment \*/ because it's not multi-lined in the example but that's its purpose--documentation. What do you think?
This is the only question that's giving me a hard time. Any help would be appreciated! Thank you. | 2013/05/15 | [
"https://Stackoverflow.com/questions/16574731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2383999/"
] | In terms of grammar, none of the above ways of indicating comments is not acceptable.
However, to make other people easier to understand your code, then I would suggest
to follow some of the major coding styles.
For example, the [Oracle coding style](http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html)
is one of the popular coding styles for Java.
In its coding style, there are two types of comments. The first is implementation comment,
which uses /\* \*/ for block comments and // for single line comments.
```
/*
* Here is a block comment.
*/
// Here is a single line comment.
```
The second type is the documentation comment, which usually uses /\*\* \*/ styled comment and
only appears right before the class, function, and variable definitions. For example:
```
/**
* Documentation for some class.
*/
public class someClass {
/**
* Documentation for the constructor.
* @param someParam blah blah blah
*/
public someClass(int someParam) {
...
}
...
}
``` | The Java language specification states that there are two kinds of comments, "//" and "/\* ... \*/".
<http://docs.oracle.com/javase/specs/jls/se5.0/html/lexical.html#3.7>
It is a trick question. But since /\*\* ... \*/ is used by JavaDoc tools to create JavaDocs, I would say the first choice is not an acceptable answer. |
57,446,117 | I have a table like this:
```
email (primary-key) | first_contact_date | last_contact_date | due_date | status
```
The user can upload an excel spreadsheet - from a different application - into the table. The excel contains:
```
email | first_contact_date | last_contact_date
```
Once loaded, the user can alter (update) status and due date.
However, about once a week the user will upload the latest excel spreadsheet which contains new AND old records. In other words, some of the rows already exist in the table and have been worked on.
For this reason, we cannot delete the existing records. Instead:
* if the record is new, insert
* if the record already exists in the table (ie email exists) then we need to update the last\_contact\_date
The excel spreadsheet can contain between 1,000 and 50,000 rows.
What is the most efficient approach to insert the records into Oracle?? Within mySQL I simply used batch insert with "on duplicate update" but Oracle does not have this function.
What is the best approach to take??
Any help appreciated. | 2019/08/10 | [
"https://Stackoverflow.com/questions/57446117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2028316/"
] | Try it with the `new` keyword, like follows:
```
let hours = (new Date(date)).getHours();.
```
Contrary to popular belief, the `new` keyword is more than just sugar: it means that to prototype is bounded to `this.__proto__`, instead of just returned as an object that is called while evaluation. In this case, `.getHours` is a [prototype function](https://link.medium.com/Z5DrvtvG3Y), so if we don't invoke `Date()` with `new`, it's not going to be properly binded. This is the main issue you were facing - `Date` creates a date object with or without `new`, but it won't necessarily be binded with the prototype functions.
I feel like you already understood that you *needed* to create a Date object, but just missed this keyword. However, in short, if Firebase Functions is being called via `get`/`post`, there's two ways of passing it data:
1. Query parameters - strings and boolean only
2. `request.body` - in normal encoding (i.e not `.../form-data`), only default datatypes (no invoked constructors): strings, integers, booleans, arrays and floats.
See, none of these formats allow you to pass date objects, so we need to use `new Date(data.date)` to get the date, currently a string, as a date *type*. | The date that reaches your function is not an instance of Date; as you can see in the logs it's a stringified representation of it, that's why the method is not available, and also why you have to 'reconstruct' it, as suggested by Geza Kerecsenyi.
---
>
> Remember that your data is traversing the Internet from your code to Firebase, so actual instances can't be sent, but some sort of data exchange format, like strings, or JSON, and the like, this is why the Date you created in your app doesn't actually reach the Firebase function.
>
>
> |
70,365,973 | I am having column of datatype xml in my database.
sample value shown below.
```
<Responses>
<Response>
<task></task>
</Response>
<Response>
<task></task>
</Response>
<Response>
<task></task>
</Response>
</Responses>
```
So from the above xml I need to extract each node and need to save it as different row in another table. From the above example there will be 3 rows. | 2021/12/15 | [
"https://Stackoverflow.com/questions/70365973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4705981/"
] | try using the xml column, query. you will need to cast a string column to xml then use query. see ([SQL Server - returning xml child nodes for xml column](https://stackoverflow.com/questions/12690689/sql-server-returning-xml-child-nodes-for-xml-column))
```
declare @tmp as table (ID UNIQUEIDENTIFIER,
CreatedDate DATETIME,
XmlData XML)
declare @xml as xml='<Responses>
<Response>
<task>1</task>
</Response>
<Response>
<task>2</task>
</Response>
<Response>
<task>3</task>
</Response>
</Responses>'
insert into @tmp(CreatedDate,XmlData) values(GetDate(),@xml)
select XmlData.query('Responses/Response/task') task from @tmp
```
output:
```
<task>1</task><task>2</task><task>3</task>
```
using xml path nodes and value
```
select X.Y.value('(task)[1]','int') task from @tmp t
cross apply t.XmlData.nodes('Responses/Response') as X(Y)
```
output
```
task
1
2
3
``` | Try following :
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string xml = @"<Responses>
<Response>
<task></task>
</Response>
<Response>
<task></task>
</Response>
<Response>
<task></task>
</Response>
</Responses>";
StringReader reader = new StringReader(xml);
DataSet ds = new DataSet();
ds.ReadXml(reader);
}
}
}
``` |
70,365,973 | I am having column of datatype xml in my database.
sample value shown below.
```
<Responses>
<Response>
<task></task>
</Response>
<Response>
<task></task>
</Response>
<Response>
<task></task>
</Response>
</Responses>
```
So from the above xml I need to extract each node and need to save it as different row in another table. From the above example there will be 3 rows. | 2021/12/15 | [
"https://Stackoverflow.com/questions/70365973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4705981/"
] | You can use the following SQL XQuery solution:
`.query` will give you a whole XML node, rather than `.value` which only gives you a single inner value.
```sql
SELECT x.task.query('.') task
FROM @tmp t
CROSS APPLY t.XmlData.nodes('Responses/Response/task') x(task);
```
[db<>fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=c1f371b6dc74d4948440ce7d0b421498)
**Output:**
| task |
| --- |
| `<task>1</task>` |
| `<task>2</task>` |
| `<task>3</task>` | | Try following :
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string xml = @"<Responses>
<Response>
<task></task>
</Response>
<Response>
<task></task>
</Response>
<Response>
<task></task>
</Response>
</Responses>";
StringReader reader = new StringReader(xml);
DataSet ds = new DataSet();
ds.ReadXml(reader);
}
}
}
``` |
19,078,613 | **Problem Description**
I wanted to ask about how to use a list Exbando Objects in knockout.js,am using Rob Conrey's Massive and all returned results are dynamic, that's fine with me it suits my needs but when it comes to sending results to knockout i just don't know what to do with it.
**Goal**
Access object properties like obj.Name, obj.Brand etc...
**Sample Code**
*View:*
```
<div data-bind="foreach: Products">
<p>Product name: <strong data-bind="text: Name"></strong></p>
</div>
```
*Controller:*
```
public JsonResult GetProducts()
{
Products products = new Products();
var Model = products.GetAllProducts();
return Json(Model, JsonRequestBehavior.AllowGet);
}
```
The result of calling GetProducts is:
>
> [[{"Key":"Id","Value":1},{"Key":"Name","Value":"Badass Boots"},{"Key":"Brand","Value":"Nike"},{"Key":"Description","Value":"Super cool boots that can make you fly (Not Really!)."}, etc...]]
>
>
>
*Script File:*
```
function ProductListViewModel() {
// Data
var self = this;
self.Products = ko.observableArray([]);
$.getJSON("/Home/GetProducts", function (data) {
self.Products(data);
});
}
```
JavaScript error on running the application:
>
> Uncaught ReferenceError: Unable to parse bindings. Bindings value: text: Name Message: Name is not defined
>
>
>
**Screen Shot 1:**

**Screen Shot 2:**
 | 2013/09/29 | [
"https://Stackoverflow.com/questions/19078613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801549/"
] | It looks like the problem is because you are trying to set the value of your ko.observableArray to a json array. Not sure that this will work. Typically this is how I would do it:
```
function ProductListViewModel() {
// Data
var self = this;
self.Products = ko.observableArray([]);
$.getJSON("/Home/GetProducts", function (data) {
ko.utils.arrayForEach(data, function(item) {
self.Products.push({
Name : item.Name
});
});
});
```
}
Use knockout's arrayForEach function to iterate through your json array, and push each object into your observableArray. | As in your JSON I see the sequence of `Key` and `Value`, so you have to specify the filed name which knockout has to query for to get the relative value and put it on the screen.
So change `<strong data-bind="text: Name">` to `<strong data-bind="text: Key">` and this *should* work for you. |
19,078,613 | **Problem Description**
I wanted to ask about how to use a list Exbando Objects in knockout.js,am using Rob Conrey's Massive and all returned results are dynamic, that's fine with me it suits my needs but when it comes to sending results to knockout i just don't know what to do with it.
**Goal**
Access object properties like obj.Name, obj.Brand etc...
**Sample Code**
*View:*
```
<div data-bind="foreach: Products">
<p>Product name: <strong data-bind="text: Name"></strong></p>
</div>
```
*Controller:*
```
public JsonResult GetProducts()
{
Products products = new Products();
var Model = products.GetAllProducts();
return Json(Model, JsonRequestBehavior.AllowGet);
}
```
The result of calling GetProducts is:
>
> [[{"Key":"Id","Value":1},{"Key":"Name","Value":"Badass Boots"},{"Key":"Brand","Value":"Nike"},{"Key":"Description","Value":"Super cool boots that can make you fly (Not Really!)."}, etc...]]
>
>
>
*Script File:*
```
function ProductListViewModel() {
// Data
var self = this;
self.Products = ko.observableArray([]);
$.getJSON("/Home/GetProducts", function (data) {
self.Products(data);
});
}
```
JavaScript error on running the application:
>
> Uncaught ReferenceError: Unable to parse bindings. Bindings value: text: Name Message: Name is not defined
>
>
>
**Screen Shot 1:**

**Screen Shot 2:**
 | 2013/09/29 | [
"https://Stackoverflow.com/questions/19078613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801549/"
] | An `ExpandoObject` generally speaking is for all intents and purposes, a dictionary. When serialized as JSON here, it is treated as a dictionary and becomes a collection of key/value pairs (not all serializers behave this way, but the one you're using does). It is not an object you can access members by name, you'll have to convert it into a representation where you can (or serialize it as one in the first place).
Doing the conversion is not the worst thing in the world:
```
function Product(item) {
var self = this;
// assuming item is an array of key/value pairs
ko.utils.arrayForEach(item, function(pair) {
// doesn't necessarily have to be mapped as an observable
self[pair.Key] = ko.observable(pair.Value);
});
}
```
With this, you can then map the results to your array of products:
```
$.getJSON("/Home/GetProducts", function (data) {
self.Products(ko.utils.arrayMap(data, function(item) {
return new Product(item);
}));
});
``` | As in your JSON I see the sequence of `Key` and `Value`, so you have to specify the filed name which knockout has to query for to get the relative value and put it on the screen.
So change `<strong data-bind="text: Name">` to `<strong data-bind="text: Key">` and this *should* work for you. |
19,078,613 | **Problem Description**
I wanted to ask about how to use a list Exbando Objects in knockout.js,am using Rob Conrey's Massive and all returned results are dynamic, that's fine with me it suits my needs but when it comes to sending results to knockout i just don't know what to do with it.
**Goal**
Access object properties like obj.Name, obj.Brand etc...
**Sample Code**
*View:*
```
<div data-bind="foreach: Products">
<p>Product name: <strong data-bind="text: Name"></strong></p>
</div>
```
*Controller:*
```
public JsonResult GetProducts()
{
Products products = new Products();
var Model = products.GetAllProducts();
return Json(Model, JsonRequestBehavior.AllowGet);
}
```
The result of calling GetProducts is:
>
> [[{"Key":"Id","Value":1},{"Key":"Name","Value":"Badass Boots"},{"Key":"Brand","Value":"Nike"},{"Key":"Description","Value":"Super cool boots that can make you fly (Not Really!)."}, etc...]]
>
>
>
*Script File:*
```
function ProductListViewModel() {
// Data
var self = this;
self.Products = ko.observableArray([]);
$.getJSON("/Home/GetProducts", function (data) {
self.Products(data);
});
}
```
JavaScript error on running the application:
>
> Uncaught ReferenceError: Unable to parse bindings. Bindings value: text: Name Message: Name is not defined
>
>
>
**Screen Shot 1:**

**Screen Shot 2:**
 | 2013/09/29 | [
"https://Stackoverflow.com/questions/19078613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801549/"
] | An `ExpandoObject` generally speaking is for all intents and purposes, a dictionary. When serialized as JSON here, it is treated as a dictionary and becomes a collection of key/value pairs (not all serializers behave this way, but the one you're using does). It is not an object you can access members by name, you'll have to convert it into a representation where you can (or serialize it as one in the first place).
Doing the conversion is not the worst thing in the world:
```
function Product(item) {
var self = this;
// assuming item is an array of key/value pairs
ko.utils.arrayForEach(item, function(pair) {
// doesn't necessarily have to be mapped as an observable
self[pair.Key] = ko.observable(pair.Value);
});
}
```
With this, you can then map the results to your array of products:
```
$.getJSON("/Home/GetProducts", function (data) {
self.Products(ko.utils.arrayMap(data, function(item) {
return new Product(item);
}));
});
``` | It looks like the problem is because you are trying to set the value of your ko.observableArray to a json array. Not sure that this will work. Typically this is how I would do it:
```
function ProductListViewModel() {
// Data
var self = this;
self.Products = ko.observableArray([]);
$.getJSON("/Home/GetProducts", function (data) {
ko.utils.arrayForEach(data, function(item) {
self.Products.push({
Name : item.Name
});
});
});
```
}
Use knockout's arrayForEach function to iterate through your json array, and push each object into your observableArray. |
40,153,971 | I have a lot of satellite data that is consists of two-dimension.
(I convert H5 to 2d array data that not include latitude information
I made Lat/Lon information data additionally.)
I know real Lat/Lon coordination and **grid coordination** in one data.
**How can I partially read 2d satellite file in Python?**
"numpy.fromfile" was usually used to read binary file.
if I use option as count in numpy.fromfile, I can read binary file partially.
However I want to skip front records in one data for **save memory**.
for example, i have 3x3 2d data as follow:
>
> **python**
>
>
> a= [[1,2,3]
> [4,5,6]
> [7,8,9]]
>
>
>
I just read a[3][0] in Python. (result = 7)
When I read file in Fortran, I used "recl, rec".
>
> **Fortran**
>
>
> open(1, file='exsmaple.bin', access='direct', recl=4) ! recl=4 means 4 btype
>
>
> read(1, rec=lat\*x-lon) filename
>
>
> close(1)
>
>
>
lat means position of latitude in data.
(lat = 3 in above exsample ; start number is 1 in Fortran.)
lon means position of longitude in data.
(lon = 1 in above exsample ; start number is 1 in Fortran.)
x is no. rows.
(x = 3, above example, array is 3x3)
I can read file, and use only 4 byte of memory.
I want to know similar method in Python.
Please give me special information to save time and memory.
Thank you for reading my question.
**2016.10.28.
Solution**
>
> **python**
> Data = [1,2,3,4,5,6,7,8,9], dtype = int8, filename=name
>
>
> a = np.memmap(name, dtype='int8', mode='r', shape=(1), offset=6)
>
>
> print a[0]
>
>
> result : **7**
>
>
> | 2016/10/20 | [
"https://Stackoverflow.com/questions/40153971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5121617/"
] | You can't do what you've described - the best you can do is to create a new Enum that uses the same set of values. You will then need to cast to the "real" enum whenever you use it.
You could use T4 templates or similar to generate the attributed enum for you - it would be much safer that way as it would be very easy to map the wrong values, making for some very subtle bugs!
Linqpad Query
-------------
```
enum PrimaryColor
{
Red,
Blue,
Green
}
enum AttributedPrimaryColor
{
[MyAttribute]
Red = PrimaryColor.Red,
[MyAttribute]
Blue = PrimaryColor.Blue,
[MyAttribute]
Green = PrimaryColor.Green
}
static void PrintColor(PrimaryColor color)
{
Console.WriteLine(color);
}
void Main()
{
// We have to perform a cast to PrimaryColor here.
// As they both have the same base type (int in this case)
// this cast will be fine.
PrintColor((PrimaryColor)AttributedPrimaryColor.Red);
}
``` | You can do something like this, but it will be tedious.
The idea is to use your project settings to allow the change when you import the enum in a new project.
First, you will need 2 attributes:
```
// This one is to indicate the format of the keys in your settings
public class EnumAttribute : Attribute
{
public EnumAttribute(string key)
{
Key = key;
}
public string Key { get; }
}
// This one is to give an id to your enum field
[AttributeUsage(AttributeTargets.Field)]
public class EnumValueAttribute : Attribute
{
public EnumValueAttribute(int id)
{
Id = id;
}
public int Id { get; }
}
```
Then, this method:
```
// This method will get your attribute value from your enum value
public object GetEnumAttributeValue<TEnum>(TEnum value)
{
var enumAttribute = (EnumAttribute)typeof(TEnum)
.GetCustomAttributes(typeof(EnumAttribute), false)
.First();
var valueAttribute = (EnumValueAttribute)typeof(TEnum).GetMember(value.ToString())
.First()
.GetCustomAttributes(typeof(EnumValueAttribute), false)
.First();
return Settings.Default[String.Format(enumAttribute.Key, valueAttribute.Id)];
}
```
*I did not check if the type is correct, not even if it finds any attributes. You will have to do it, otherwise you will get an exception if you don't provide the right type.*
Now, your enum will look like that:
```
[Enum("Key{0}")]
public enum MyEnum
{
[EnumValue(0)] First,
[EnumValue(1)] Second
}
```
Finally, in your project settings, you will have to add as many lines as the number of members in your enum.
You will have to name each line with the same pattern as the parameter given to EnumAttribute. Here, it's "Key{0}", so:
1. Key0: Your first value
2. Key1: Your second value
3. etc...
Like this, you only have to change your settings values (NOT THE KEY) to import your enum and change your attributes to a project to another.
Usage:
```
/*Wherever you put your method*/.GetEnumAttributeValue(MyEnum.First);
```
It will return you "Your first value". |
40,153,971 | I have a lot of satellite data that is consists of two-dimension.
(I convert H5 to 2d array data that not include latitude information
I made Lat/Lon information data additionally.)
I know real Lat/Lon coordination and **grid coordination** in one data.
**How can I partially read 2d satellite file in Python?**
"numpy.fromfile" was usually used to read binary file.
if I use option as count in numpy.fromfile, I can read binary file partially.
However I want to skip front records in one data for **save memory**.
for example, i have 3x3 2d data as follow:
>
> **python**
>
>
> a= [[1,2,3]
> [4,5,6]
> [7,8,9]]
>
>
>
I just read a[3][0] in Python. (result = 7)
When I read file in Fortran, I used "recl, rec".
>
> **Fortran**
>
>
> open(1, file='exsmaple.bin', access='direct', recl=4) ! recl=4 means 4 btype
>
>
> read(1, rec=lat\*x-lon) filename
>
>
> close(1)
>
>
>
lat means position of latitude in data.
(lat = 3 in above exsample ; start number is 1 in Fortran.)
lon means position of longitude in data.
(lon = 1 in above exsample ; start number is 1 in Fortran.)
x is no. rows.
(x = 3, above example, array is 3x3)
I can read file, and use only 4 byte of memory.
I want to know similar method in Python.
Please give me special information to save time and memory.
Thank you for reading my question.
**2016.10.28.
Solution**
>
> **python**
> Data = [1,2,3,4,5,6,7,8,9], dtype = int8, filename=name
>
>
> a = np.memmap(name, dtype='int8', mode='r', shape=(1), offset=6)
>
>
> print a[0]
>
>
> result : **7**
>
>
> | 2016/10/20 | [
"https://Stackoverflow.com/questions/40153971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5121617/"
] | Attributes are compile-time additions (metadata) to code. You can not modify them when using the compiled code assembly.
(Or perhaps you could if you are a diehard low-level IL wizard, but I certainly am not...)
If your `enum` values require modification or parameters at various places, then you should consider other solutions, e.g. a `Dictionary` or even a Database Table.
E.g. using a `Dictionary`:
```
var values = new Dictionary<MyEnum, int>()
{
{ MyEnum.First, 25 },
{ MyEnum.Second, 42 }
};
var valueForSecond = values[MyEnum.Second]; // returns 42
``` | You can do something like this, but it will be tedious.
The idea is to use your project settings to allow the change when you import the enum in a new project.
First, you will need 2 attributes:
```
// This one is to indicate the format of the keys in your settings
public class EnumAttribute : Attribute
{
public EnumAttribute(string key)
{
Key = key;
}
public string Key { get; }
}
// This one is to give an id to your enum field
[AttributeUsage(AttributeTargets.Field)]
public class EnumValueAttribute : Attribute
{
public EnumValueAttribute(int id)
{
Id = id;
}
public int Id { get; }
}
```
Then, this method:
```
// This method will get your attribute value from your enum value
public object GetEnumAttributeValue<TEnum>(TEnum value)
{
var enumAttribute = (EnumAttribute)typeof(TEnum)
.GetCustomAttributes(typeof(EnumAttribute), false)
.First();
var valueAttribute = (EnumValueAttribute)typeof(TEnum).GetMember(value.ToString())
.First()
.GetCustomAttributes(typeof(EnumValueAttribute), false)
.First();
return Settings.Default[String.Format(enumAttribute.Key, valueAttribute.Id)];
}
```
*I did not check if the type is correct, not even if it finds any attributes. You will have to do it, otherwise you will get an exception if you don't provide the right type.*
Now, your enum will look like that:
```
[Enum("Key{0}")]
public enum MyEnum
{
[EnumValue(0)] First,
[EnumValue(1)] Second
}
```
Finally, in your project settings, you will have to add as many lines as the number of members in your enum.
You will have to name each line with the same pattern as the parameter given to EnumAttribute. Here, it's "Key{0}", so:
1. Key0: Your first value
2. Key1: Your second value
3. etc...
Like this, you only have to change your settings values (NOT THE KEY) to import your enum and change your attributes to a project to another.
Usage:
```
/*Wherever you put your method*/.GetEnumAttributeValue(MyEnum.First);
```
It will return you "Your first value". |
40,153,971 | I have a lot of satellite data that is consists of two-dimension.
(I convert H5 to 2d array data that not include latitude information
I made Lat/Lon information data additionally.)
I know real Lat/Lon coordination and **grid coordination** in one data.
**How can I partially read 2d satellite file in Python?**
"numpy.fromfile" was usually used to read binary file.
if I use option as count in numpy.fromfile, I can read binary file partially.
However I want to skip front records in one data for **save memory**.
for example, i have 3x3 2d data as follow:
>
> **python**
>
>
> a= [[1,2,3]
> [4,5,6]
> [7,8,9]]
>
>
>
I just read a[3][0] in Python. (result = 7)
When I read file in Fortran, I used "recl, rec".
>
> **Fortran**
>
>
> open(1, file='exsmaple.bin', access='direct', recl=4) ! recl=4 means 4 btype
>
>
> read(1, rec=lat\*x-lon) filename
>
>
> close(1)
>
>
>
lat means position of latitude in data.
(lat = 3 in above exsample ; start number is 1 in Fortran.)
lon means position of longitude in data.
(lon = 1 in above exsample ; start number is 1 in Fortran.)
x is no. rows.
(x = 3, above example, array is 3x3)
I can read file, and use only 4 byte of memory.
I want to know similar method in Python.
Please give me special information to save time and memory.
Thank you for reading my question.
**2016.10.28.
Solution**
>
> **python**
> Data = [1,2,3,4,5,6,7,8,9], dtype = int8, filename=name
>
>
> a = np.memmap(name, dtype='int8', mode='r', shape=(1), offset=6)
>
>
> print a[0]
>
>
> result : **7**
>
>
> | 2016/10/20 | [
"https://Stackoverflow.com/questions/40153971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5121617/"
] | You can't do what you've described - the best you can do is to create a new Enum that uses the same set of values. You will then need to cast to the "real" enum whenever you use it.
You could use T4 templates or similar to generate the attributed enum for you - it would be much safer that way as it would be very easy to map the wrong values, making for some very subtle bugs!
Linqpad Query
-------------
```
enum PrimaryColor
{
Red,
Blue,
Green
}
enum AttributedPrimaryColor
{
[MyAttribute]
Red = PrimaryColor.Red,
[MyAttribute]
Blue = PrimaryColor.Blue,
[MyAttribute]
Green = PrimaryColor.Green
}
static void PrintColor(PrimaryColor color)
{
Console.WriteLine(color);
}
void Main()
{
// We have to perform a cast to PrimaryColor here.
// As they both have the same base type (int in this case)
// this cast will be fine.
PrintColor((PrimaryColor)AttributedPrimaryColor.Red);
}
``` | Attributes are compile-time additions (metadata) to code. You can not modify them when using the compiled code assembly.
(Or perhaps you could if you are a diehard low-level IL wizard, but I certainly am not...)
If your `enum` values require modification or parameters at various places, then you should consider other solutions, e.g. a `Dictionary` or even a Database Table.
E.g. using a `Dictionary`:
```
var values = new Dictionary<MyEnum, int>()
{
{ MyEnum.First, 25 },
{ MyEnum.Second, 42 }
};
var valueForSecond = values[MyEnum.Second]; // returns 42
``` |
59,017,326 | I am fighting with SFINAE trying to have many functions that requires just to have access to the type T with operator `[]`.
So far I have the following code that compiles and works fine with Visual Studio 2017:
```
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <list>
#include <array>
#include <map>
#include <set>
using namespace std;
template <typename T, typename X = std::enable_if_t <std::is_array<T>::value || std::is_pointer<T>::value> >
void DoIt(T& c)
{}
template <typename T, typename std::enable_if_t< std::is_same<std::random_access_iterator_tag,
typename std::iterator_traits<typename T::iterator>::iterator_category>::value, bool> = true >
void DoIt(T& c)
{}
int main()
{
int* a;
const int* ac;
int b[10];
array<int,6> c;
vector<int> d;
string s;
DoIt(a); // Ok, compile pass
DoIt(ac); // Ok, compile pass
DoIt(b); // Ok, compile pass
DoIt(c); // Ok, compile pass
DoIt(d); // Ok, compile pass
DoIt(s); // Ok, compile pass
int i;
float f;
map<int, int> m;
//DoIt(f); // Ok, compile fails
//DoIt(i); // Ok, compile fails
// DoIt(m); // Ok, compile fails
return 0;
}
```
Now I need the following :
1. How to combine both SFINAE conditions checking for array & pointer and random access operator into one check?
I have many functions and it is not convenient and too much code to have two declarations. But I somehow failed to combine the conditions in a single `std::enable_if_t` or in a template structure.
2. Is it possible above to be extended and to check also and for the container type, so that for example:
```
vector<int> a;
vector<string> b;
int* c;
string* d;
DoIt(a); // must pass
DoIt(c); // must pass
DoIt(b); // must fail
DoIt(d); // must fail
``` | 2019/11/24 | [
"https://Stackoverflow.com/questions/59017326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1165590/"
] | >
> How to combine both SFINAE conditions checking for array & pointer and random access operator into one check? I
>
>
>
The simplest way that come in my mind is check if you can write `c[0u]`
```
template <typename T>
auto DoIt(T& c) -> decltype( c[0u], void() )
{}
```
Not a perfect solution: works with types accepting an unsigned integer for as argument for `operator[]` (`std::vector`s, `std::array`s, C-style arrays, pointers, `std::map`s with an integer key) but fails with maps with keys incompatibles with unsigned integers.
You can reduce this problem adding a template parameter for the key type (defaulting it to `std::size_t`)
```
template <typename K = std::size_t, typename T>
auto DoIt(T& c) -> decltype( c[std::declval<K>()], void() )
{}
```
so works as follows
```
std::array<int,6> c;
DoIt(c); // Ok, compile pass, no needs to explicit the key type
std::map<std::string, int> m;
DoIt(m); // compilation error: std::size_t is a wrong key type
DoIt<std::string>(m); // Ok, compile: std::string is a good key type
```
If you want enable the function checking also the type returned by the operator `[]`... well... conceptually is simple but require a little typewriting
I propose the following `DoIt2()` function where you have to explicit the required type for operator `[]` and `std::size_t` remain the default type for the argument of the operator (but you can explicit a different type)
```
template <typename V, typename K = std::size_t, typename T>
std::enable_if_t<
std::is_same_v<V,
std::remove_const_t<
std::remove_reference_t<
decltype(std::declval<T>()[std::declval<K>()])>>>>
DoIt2 (T &)
{}
```
The idea is simple: get the type of `std::declval<T>()[std::declval<K>()]`, remove reference (if present), remove `const` (if present) and check if the resulting type is equal to `V` (the requested type)
You can use `DoIt2()` as follows
```
std::vector<int> v1;
std::vector<float> v2;
DoIt2<int>(v1); // compile
//DoIt2<int>(v2); // compilation error
//DoIt2<float>(v1); // compilation error
DoIt2<float>(v2); // compile
std::map<int, std::string> m1;
std::map<std::string, float> m2;
DoIt2<std::string, int>(m1);
DoIt2<float, std::string>(m2);
``` | When you have a bunch of conditional SFINAE that you want to apply, I usually try to split them up in smaller helper structs.
In yoyur example it would look something like this.
```
template <typename T, typename U = void>
struct random_access : std::false_type {};
template <typename T>
struct random_access<T, std::enable_if_t<std::is_same_v<std::random_access_iterator_tag,
typename std::iterator_traits<typename T::iterator>::iterator_category>>> : std::true_type {};
template <typename T>
struct random_access<T, std::enable_if_t<std::is_pointer_v<T> || std::is_array_v<T>>> : std::true_type {};
template <typename T>
constexpr bool random_access_v = random_access<T>::value;
template <typename T, typename U = void>
struct contains_container : std::false_type {};
template <typename T>
struct contains_container<T, std::enable_if_t<std::is_same_v<std::void_t<decltype(std::declval<T&>()[0][0])>, void>>> : std::true_type {};
template <typename T>
constexpr bool contains_container_v = contains_container<T>::value;
template <typename T, std::enable_if_t<random_access_v<T> && !contains_container_v<T>, bool> = true>
void DoIt(T&) {}
```
The `contains_container` was my attemp at solving our second part. Not sure if this is exactly what you were looking for, but it checks if two layers of `operator[]` can be applied to `T`. That would make your second examples pass. |
3,519,859 | If $d\_1$ and $d\_2$ are topologically equivalent metrics
show that $d=max\{2d\_1,d\_2\}$ is topologically
equivalent to both $d\_1$ and $d\_2$
I can show one direction$(\tau \_1\subseteq\tau )$ by choosing $\delta=min\{r\_1,r\_2\}$,
but to prove other direction $(\tau \subseteq\tau \_1)$,
how should I choose $\delta$? | 2020/01/23 | [
"https://math.stackexchange.com/questions/3519859",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/568605/"
] | If you assume that $x \ll 1$, you can develop using the binomial expansion to get, as @InterstellarProbe wrote
$$y = \sum\_{k=1}^n\dbinom{n}{k}(-1)^{k+1}x^{k-1}$$
Now, using series reversion, you could get
$$x=t+\frac{(n-2)}{3} t^2+\frac{(n-2) (5 n-7)}{36} t^3+\frac{(n-2)(17 n^2-44 n+29)}{270} t^4+\cdots$$ where
$$t=-\frac{2 (y-n)}{(n-1) n}$$
Let us try for $n=7$ and $y=4$; this would give the *approximate*
$$x=\frac{12478}{64827}\approx 0.1925$$ while the exact solution, obtained by Newton method, is $\approx 0.1954$.
For sure, under this assumption and using more terms, we should have better. | Let's try to turn this into a polynomial equation. By the Binomial Theorem:
$$(1-x)^n = \sum\_{k=0}^n\dbinom{n}{k}(-1)^kx^k$$
Simplifying:
$$\dfrac{1-(1-x)^n}{x} = \sum\_{k=1}^n\dbinom{n}{k}(-1)^{k+1}x^{k-1}$$
Thus:
$$y = \sum\_{k=1}^n\dbinom{n}{k}(-1)^{k+1}x^{k-1}$$
For $n>5$, this is a polynomial of degree $5$ or higher. Such a polynomial is not guaranteed to be solvable. For $n>2$, you are going to have radicals in the solution for $x$. And for $n=4$ or $n=5$, the cubic and quartic equations have solutions that are very messy (easier to solve algorithmically than with a general formula).
That said, there is no general formula for the inverse function. You can use numerical analysis to find roots of the polynomial that arises, but there is no closed form. |
9,270,490 | I'm encountering some major performance problems with simple SQL queries generated by the Entity Framework (4.2) running against SQL Server 2008 R2. In some situations (but not all), EF uses the following syntax:
```
exec sp_executesql 'DYNAMIC-SQL-QUERY-HERE', @param1...
```
In other situations is simply executes the raw SQL with the provided parameters baked into the query. The problem I'm encountering is that queries executed with the sp\_executesql are ignoring all indexes on my target tables, resulting in an extremely poor performing query (confirmed by examining the execution plan in SSMS).
After a bit of research, it sounds like the issue might be caused by 'parameter sniffing'. If I append the OPTION(RECOMPILE) query hint like so:
```
exec sp_executesql 'DYNAMIC-SQL-QUERY-HERE OPTION(RECOMPILE)', @param1...
```
The indexes on the target tables are used and the query executes extremely quickly. I've also tried toggling on the trace flag used to disable parameter sniffing (4136) on the database instance (<http://support.microsoft.com/kb/980653>), however this didn't appear to have any effect whatsoever.
This leaves me with a few questions:
1. Is there anyway to append the OPTION(RECOMPILE) query hint to the SQL generated by Entity Framework?
2. Is there anyway to prevent Entity Framework from using exec sp\_executesql, and instead simply run the raw SQL?
3. Is anyone else running into this problem? Any other hints/tips?
**Additional Information:**
1. I did restart the database instance through SSMS, however, I will try restarting the service from the service management console.
2. Parameterization is set to SIMPLE (is\_parameterization\_forced: 0)
3. Optimize for adhoc workloads has the following settings
* value: 0
* minimum: 0
* maximum: 1
* value\_in\_use: 0
* is\_dynamic: 1
* is\_advanced: 1
I should also mention that if I restart the SQL Server Service via the service management console AFTER enabling trace flag 4136 with the below script, appears to actually clear the trace flag...perhaps I should be doing this a different way...
```
DBCC TRACEON(4136,-1)
``` | 2012/02/14 | [
"https://Stackoverflow.com/questions/9270490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100905/"
] | At this point I would recommend:
---
Set the optimize for ad hoc workloads setting to true.
```
EXEC sp_configure 'show advanced', 1;
GO
RECONFIGURE WITH OVERRIDE;
GO
EXEC sp_configure 'optimize for ad hoc', 1;
GO
RECONFIGURE WITH OVERRIDE
GO
EXEC sp_configure 'show advanced', 0;
GO
RECONFIGURE WITH OVERRIDE;
GO
```
---
If after some time this setting doesn't seem to have helped, only then would I try the additional support of the trace flag. These are usually reserved as a last resort. Set the trace flag using the command line via SQL Server Configuration Manager, as opposed to in a query window and using the global flag. See <http://msdn.microsoft.com/en-us/library/ms187329.aspx> | **tl;dr**
`update statistics`
---
We had a `delete` query with one parameter (the primary key) that took ~7 seconds to complete when called through EF and `sp_executesql`. Running the query manually, with the parameter embedded in the first argument to `sp_executesql` made the query run quickly (~0.2 seconds). Adding `option (recompile)` also worked. Of course, those two workarounds aren't available to us since were using EF.
Probably due to cascading foreign key constraints, the execution plan for the long running query was, uhmm..., huge. When I looked at the execution plan in SSMS I noticed that the arrows between the different steps in some cases were wider than others, possibly indicating that SQL Server had trouble making the right decisions. That led me to thinking about statistics. I looked at the steps in the execution plan to see what table was involved in the suspect steps. Then I ran `update statistics Table` for that table. Then I re-ran the bad query. And I re-ran it again. And again just to make sure. It worked. Our perf was back to normal. (Still somewhat worse than non-`sp_executesql` performance, but hey!)
It turned out that this was only a problem in our development environment. (And it was a big problem because it made our integration tests take forever.) In our production environment, we had a job running that updated all statistics on a regular basis. |
6,180,051 | What's the best way to send a `POST` request with `NSURLConnection`.
I see how the facebook-ios-sdk does it:
<https://github.com/facebook/facebook-ios-sdk/blob/master/src/FBRequest.m#L298-304>
<https://github.com/facebook/facebook-ios-sdk/blob/master/src/FBRequest.m#L109-165>
But, that seems like a lot of code. Is that how it's done? Or, is there a better way? I'd like to keep the support for posting binary data, like images & files. | 2011/05/30 | [
"https://Stackoverflow.com/questions/6180051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242933/"
] | Facebook's code is as complicated as it is because they're sending the data with a `multipart/form-data` content type. You are free to use a simpler content type, like `application/octet-stream` for raw binary data. | You can try <http://getsharekit.com/>. Using this you can share in many social networks. Also you can share in a specific network also. If you refer to the documents there you can see how to send the images from a URL. |
46,010,496 | I have 2 DateTimes, I need to calculate the difference between them in hours **in decimal format**. The hard part is making sure the result is storing the value to 2 decimal places.
```
$datetime1 = new DateTime("2017-09-01 23:00:00");
$datetime2 = new DateTime();
$difference = $datetime2->diff($datetime1);
```
But the result is just a whole number which loses too much accuracy for me. How to keep the value to 2 decimal places? | 2017/09/02 | [
"https://Stackoverflow.com/questions/46010496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8337916/"
] | `DateTime::diff` returns [`DaterInterval`](http://php.net/manual/en/class.dateinterval.php) that has a whole number for each individual time related property.
The `days` property does not account for increments less than a day, as they are accumulated to and removed from the lesser properties and then is rounded down.
So `$diff->h` will never be greater than `23`. While `$diff->s` and `$diff->i` will never be greater than `59`. Where days will contain the total days within the `year` and `month` properties. Not to be confused with `$diff->d`, which is the incremental number of days.
In order to determine the total hours using diff, you just need to perform math on each of the properties to retrieve the number of hours of the property.
Example: <https://3v4l.org/KhBQC>
```
$datetime1 = new DateTime('2017-09-01 23:00:00');
$datetime2 = new DateTime('2017-09-02 01:34:00');
$diff = $datetime2->diff($datetime1);
$hours = round($diff->s / 3600 + $diff->i / 60 + $diff->h + $diff->days * 24, 2);
echo $hours; //2.57
```
In php 7.1 you can also account for `microseconds` by adding `$diff->f / 3.6e+9`.
---
A more simplistic approach would be to subtract the unix timestamps, to retrieve the total number of seconds between the two dates. Then divide the remaining seconds by the number of seconds in an hour (3600).
Example: <https://3v4l.org/SbjEU>
```
$datetime1 = new DateTime('2017-09-01 23:00:00');
$datetime2 = new DateTime('2017-09-02 01:34:00');
$hours = round(($datetime2->getTimestamp() - $datetime1->getTimestamp()) / 3600, 2);
echo $hours; //2.57
``` | 2 decimal places:
```
$datetime1 = new DateTime("2017-09-01 23:00:00");
$datetime2 = new DateTime();
$epoch1 = $datetime1->getTimestamp();
$epoch2 = $datetime2->getTimestamp();
$diff = $epoch1 - $epoch2;
echo number_format( $diff / 3600, '2' );
``` |
35,841,196 | I'm trying to build a simple game in Java. Ran into the problem of the JTextPanel not updating until after the game loop terminates, which of course, isn't a good experience for the player.
I'm unfamiliar with multithreading but trying to figure it out. I can run separate code now in multiple threads, but I can't get my head around how to have the Threads interact. It's highly likely I'm missing something simple, but I can't find it by searching, so I throw myself at your mercy. I'm hanging by a thread...
Controller class and main thread. I need the gamePanel and the game to run separately. I've tried to run the Game class in a separate thread, but the game code isn't running in the gamePanel.
Controller:
```
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Controller_LetterFall{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new MainFrame();
}
});
}
}
```
And the MainFrame Class. I try to run gameplay() in a new thread.
```
package wordFall;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame extends JFrame implements Runnable {
private GamePlay game;
private TextPanel gamePanel;
private Header header;
private Player player;
private Dictionary dictionary;
private GamePlay game;
public MainFrame(){
super("Game");
// Set the size of the frame.
setSize(400,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
// Establish default player.
player = new Player();
dictionary = new Dictionary();
game = new GamePlay();
header = new Header();
gamePanel = new TextPanel();
add(header, BorderLayout.NORTH);
add(gamePanel, BorderLayout.CENTER);
this.game.setBoardInterface(
new BoardInterface(){
@Override
public void redraw(String text) {
gamePanel.appendText(text);
}
});
}
@Override
public void run() {
game.play();
System.out.println("The game is over.");
}
}
```
Any help would be appreciated. | 2016/03/07 | [
"https://Stackoverflow.com/questions/35841196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450008/"
] | if you use code quality management tool like sonarcube you will see that catched exceptions must be rethrown or logged with LOG.error. I recommend you and your team to use [sonarqube](http://www.sonarqube.org/) | In most cases, the log level in a catch block should be error. But the level of log: error, warn or info is not related to the location of it in code (catch block), but the relevance of the information.
I think the use of exceptions may be misused in your project. But it is difficult to judge without knowing the context ... |
56,399,830 | I cannot import javax.servlet even though I have already added the package in my gradle dependencies.
Here's my gradle dependency:
```
dependencies {
providedCompile group: 'javax.servlet', name: 'javax.servlet-api',
...
...
}
```
I've also tried:
```
dependencies {
compile "javax.servlet:servlet-api:3.0.1"
}
```
But when I import it using:
```
import javax.servlet.http.HttpServletResponse;
```
I get the error: Cannot resolve symbol "HttpServletResponse". | 2019/05/31 | [
"https://Stackoverflow.com/questions/56399830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8285512/"
] | You really should only open files with Append Data.
[Difference between FILE\_WRITE\_DATA and FILE\_APPEND\_DATA](https://stackoverflow.com/questions/20093571/difference-between-file-write-data-and-file-append-data).
`echo` and other methods cannot append data with only Append Data access(There are other complicated access inside. according to your test), but why not create a "Append" command(like `echo`) directly using `CreateFile`? Access Privileges can be strictly controlled with `CreateFile`.
Append.cpp:
```
#include <windows.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
if (argc != 3)
return 0;
//cout << argv[1] << "," << argv[2] << endl;
HANDLE hFile = CreateFile(argv[2], FILE_APPEND_DATA, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
WriteFile(hFile,argv[1],strlen(argv[1]),0,0);
CloseHandle(hFile);
}
```
Then copy the Append.exe to the folder where you want to execute `echo` or "C:\Windows\System32". Use the it like command:
```
Append foo x:\pathto\folder\thefile.txt
``` | Figured it out, at least for PowerShell/.NET. The .NET `FileStream` object offers a constructor which takes a `FileSystemRights` enum parameter, which lets you explicitly limit the underlying `CreateFile` call not to require `Generic Write`.
```
> (1..3) | %{
> Write-Host $_
> $f = New-Object -TypeName 'IO.FileStream' `
> -ArgumentList $private:file,`
> ([IO.FileMode]::Append),`
> ([Security.AccessControl.FileSystemRights]::AppendData),`
> ([IO.FileShare]::Read),`
> 4KB,`
> ([IO.FileOptions]::None)
> $f = New-Object -TypeName 'IO.StreamWriter' `
> -ArgumentList $f
> $f.WriteLine("foo")
> $f.Dispose()
> }
1
2
3
```
No options that I know of for VBScript or Batch (beyond [Drake's suggestion](https://stackoverflow.com/a/56423674/415523) of rolling one's own COM type or append.exe, which calls `CreateFile` directly via C++/Win32). |
1,340,613 | In Excel, I have a table where I want to list all unique values from a column in a different a row of a different sheet. Here is an example of the data I have:
[](https://i.stack.imgur.com/086kU.png)
I want to fill in cells in the other sheet so that it gives all of the different options for the favorite fruit. It would look something like this:
Apple | Banana | Grapefruit | Orange
How do I loop through the options (shown below) to make this happen?
[](https://i.stack.imgur.com/NEwZs.png) | 2018/07/16 | [
"https://superuser.com/questions/1340613",
"https://superuser.com",
"https://superuser.com/users/885788/"
] | Check this [article](https://www.spreadsheetweb.com/get-unique-items-from-list/) that explains to get *unique* values from a list. Differently, it creates a vertical list however, formula will work as horizontal as well.
However; you should add | characters by yourself, I mean by using another formula.
Unique list formula is
```
=LOOKUP(2,1/(COUNTIF($D$2:D2,$B$3:$B$9)=0),$B$3:$B$9)
```
which
* $D$2:D2 is one cell at left (or above if you want vertical list)
* $B$3:$B$9 is the range that contains all values (your actual data)
After tying formula, all you need to do is copy the formula to right cells. | If I understand your goal correctly, try this:
1. Copy the fruit column & paste it somewhere else (away from the rest of the data).
2. Select the data you just copied and use Data->Remove Duplicates. This will remove any duplicates.
3. Select the data that's left, Copy, and click on the leftmost cell of where you want the data to appear.
4. Go to *Home*->*Paste*->*Paste Special*. Choose *Transpose* and *Values*. Click OK. |
8,956,006 | I am using javascript. I wanted to ask how can i pass variable link to the .load() function of javascript.
```
var current_link = location.href;
$('#alerts_div').load(current_link '#alerts_div');//to pass div content in page load
```
But this is not working? can anyone help please? | 2012/01/21 | [
"https://Stackoverflow.com/questions/8956006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1015882/"
] | Why don't you use ListView instead?
```
LayoutInflater inflater = inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for(String[] episode : episodes) {
View view = inflater.inflate(R.layout.episode_list_item, null);
mTitle = (TextView) view.findViewById(R.id.episode_list_item_title);
mTitle.setText(episode[2]);
listView.addView(view);
}
``` | I am assuming you have a few `TextView`s in your `LinearLayout`. One point is they can't have the same `id`s. So suppose you have 4 `TextView` , then give each different `id`s, say `tv1`, `tv2` etc.
Now in your `onCreate` method, initialize all these textViews as:
>
> `myTextView1= (TextView)findViewByid(R.id.tv1);`
>
>
>
etc etc...
In the function where you get the "episodes" try this:
>
> `myTextView1.setText(episodes[0]);
>
>
> myTextView2.setText(episodes[1]);
>
>
>
You don't have to use any `inflater` because its already there in the activities `layout` file, which is automatically done in `onCreate`. |
8,956,006 | I am using javascript. I wanted to ask how can i pass variable link to the .load() function of javascript.
```
var current_link = location.href;
$('#alerts_div').load(current_link '#alerts_div');//to pass div content in page load
```
But this is not working? can anyone help please? | 2012/01/21 | [
"https://Stackoverflow.com/questions/8956006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1015882/"
] | I am assuming you have a few `TextView`s in your `LinearLayout`. One point is they can't have the same `id`s. So suppose you have 4 `TextView` , then give each different `id`s, say `tv1`, `tv2` etc.
Now in your `onCreate` method, initialize all these textViews as:
>
> `myTextView1= (TextView)findViewByid(R.id.tv1);`
>
>
>
etc etc...
In the function where you get the "episodes" try this:
>
> `myTextView1.setText(episodes[0]);
>
>
> myTextView2.setText(episodes[1]);
>
>
>
You don't have to use any `inflater` because its already there in the activities `layout` file, which is automatically done in `onCreate`. | Change the lines
```
inflater.inflate(R.layout.episode_list_item, listView);
eTitle = (TextView) findViewById(R.id.episode_list_item_title);
```
into lines:
```
eTitle =inflater.inflate(R.layout.episode_list_item, listView, false);
listView.addChild(eTitle );
```
The one-line construct of `View eTitle =inflater.inflate(R.layout.episode_list_item, listView, true);` simply never really works in practice.
And aqs is right (the second time a day I am making a compliment to him), create id's dynamically, your xml layouts for eTitle should be free of id if you wait for many of them. |
8,956,006 | I am using javascript. I wanted to ask how can i pass variable link to the .load() function of javascript.
```
var current_link = location.href;
$('#alerts_div').load(current_link '#alerts_div');//to pass div content in page load
```
But this is not working? can anyone help please? | 2012/01/21 | [
"https://Stackoverflow.com/questions/8956006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1015882/"
] | I am assuming you have a few `TextView`s in your `LinearLayout`. One point is they can't have the same `id`s. So suppose you have 4 `TextView` , then give each different `id`s, say `tv1`, `tv2` etc.
Now in your `onCreate` method, initialize all these textViews as:
>
> `myTextView1= (TextView)findViewByid(R.id.tv1);`
>
>
>
etc etc...
In the function where you get the "episodes" try this:
>
> `myTextView1.setText(episodes[0]);
>
>
> myTextView2.setText(episodes[1]);
>
>
>
You don't have to use any `inflater` because its already there in the activities `layout` file, which is automatically done in `onCreate`. | I believe you're forgetting to capture the view that's being inflated and then looking WITHIN that view for the new control.
Here's your original code:
```
inflater.inflate(R.layout.episode_list_item, listView);
eTitle = (TextView) findViewById(R.id.episode_list_item_title);
```
I think Your code should look more like this (finding the view contained by the inflated view):
```
View new_view = inflater.inflate(R.layout.episode_list_item, listView, false);
eTitle = (TextView) new_view.findViewById(R.id.episode_list_item_title);
eTitle.setText(episode[2]);
listView.addView(new_view);
```
This is what got my code working as expected.
Hope that helps!
John |
8,956,006 | I am using javascript. I wanted to ask how can i pass variable link to the .load() function of javascript.
```
var current_link = location.href;
$('#alerts_div').load(current_link '#alerts_div');//to pass div content in page load
```
But this is not working? can anyone help please? | 2012/01/21 | [
"https://Stackoverflow.com/questions/8956006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1015882/"
] | Why don't you use ListView instead?
```
LayoutInflater inflater = inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for(String[] episode : episodes) {
View view = inflater.inflate(R.layout.episode_list_item, null);
mTitle = (TextView) view.findViewById(R.id.episode_list_item_title);
mTitle.setText(episode[2]);
listView.addView(view);
}
``` | Change the lines
```
inflater.inflate(R.layout.episode_list_item, listView);
eTitle = (TextView) findViewById(R.id.episode_list_item_title);
```
into lines:
```
eTitle =inflater.inflate(R.layout.episode_list_item, listView, false);
listView.addChild(eTitle );
```
The one-line construct of `View eTitle =inflater.inflate(R.layout.episode_list_item, listView, true);` simply never really works in practice.
And aqs is right (the second time a day I am making a compliment to him), create id's dynamically, your xml layouts for eTitle should be free of id if you wait for many of them. |
8,956,006 | I am using javascript. I wanted to ask how can i pass variable link to the .load() function of javascript.
```
var current_link = location.href;
$('#alerts_div').load(current_link '#alerts_div');//to pass div content in page load
```
But this is not working? can anyone help please? | 2012/01/21 | [
"https://Stackoverflow.com/questions/8956006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1015882/"
] | Why don't you use ListView instead?
```
LayoutInflater inflater = inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for(String[] episode : episodes) {
View view = inflater.inflate(R.layout.episode_list_item, null);
mTitle = (TextView) view.findViewById(R.id.episode_list_item_title);
mTitle.setText(episode[2]);
listView.addView(view);
}
``` | I believe you're forgetting to capture the view that's being inflated and then looking WITHIN that view for the new control.
Here's your original code:
```
inflater.inflate(R.layout.episode_list_item, listView);
eTitle = (TextView) findViewById(R.id.episode_list_item_title);
```
I think Your code should look more like this (finding the view contained by the inflated view):
```
View new_view = inflater.inflate(R.layout.episode_list_item, listView, false);
eTitle = (TextView) new_view.findViewById(R.id.episode_list_item_title);
eTitle.setText(episode[2]);
listView.addView(new_view);
```
This is what got my code working as expected.
Hope that helps!
John |
976,365 | I have an homework question but I'm having hard time to understand the context. Here is the question:
>
> 3. Assume that you are using 3-digit number system with base r = 4 (and n = 3). Assume also that you are using four’s complement scheme
> to represent signed integers and for subtraction operation.
>
>
> a. Show the range of integers that can be represented 4s complement
> signed number system.
>
>
>
In the (a), I tried to use formula that I derived from 2's complement but it seems that somehow it's not correct.
$$[-4^{n-1},4^{n-1}-1]$$
This formula gives `[-16,15]` but shouldn't the numbers whose leading digit is 0 and 1 be positive? That gives positive numbers from 0 to 31, but I don't know what to do with the negative ones. | 2014/10/16 | [
"https://math.stackexchange.com/questions/976365",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/27091/"
] | Based on wiki's entry on [Method of complements](http://en.wikipedia.org/wiki/Method_of_complements).
* The **radix complement** of an n digit number $y$ in radix $b$ is $b^n-y$.
* The **diminished radix complement** is $( b^n - 1 )-y$.
* The **two's complement** refers to the radix complement of a number in base $2$.
* The **ones' complement** refers to the diminished radix complement of a number in base $2$.
* The **four's complement** refers to the radix complement of a number in base $4$.
* The **fours' complement** refers to the diminished radix complement of a number in base $5$.
Assuming you have copied down the method of complements correctly and it is indeed four's
complement we are talking about, a $n$-digit negative number $-x$ will be represented by
the string corresponds to $4^n - x$. For example, the number $-1$ will be represented as
a string with $n$ characters of '$3$'.
In general, the legal range for numbers will be $[-\frac{4^n}{2}, \frac{4^n}{2} - 1 ]$.
In certain sense, working with numbers in four's complement is like
working with ordinary integers under modulus arithmetic with modulus equal to $4^n$. | This is the idea of the $r$'s complement scheme.
Namely, say we have some base $r$ in which we have $n$-digit numbers. Normally these numbers would be identified with $[0,r^n-1]$, e.g. $r=2,n=4$ gives you numbers
>
> 0000 to 1111
>
>
>
which are (in base 10) equal to $[0,31]=[0,r^n-1]$.
But, when we use $r$'s complement scheme, the first digit of our number in base $r$ will indicate the sign of that number, e.g. again with $r=2, n=4$:
>
> 1010
>
>
>
will be equal to -1. This should explain your interval $[-16,15]$ |
35,293,460 | I want to create a `factory` that always returns the `json` object retrieved from a webservice:
```
angular.module('test').factory('myService', myService);
myService.$inject = ['$http'];
function myService($http) {
var urlBase;
return {
getContent: function(id) {
return $http.get(urlBase).then(function(response) {
return response.data;
});
}
};
}
```
When I call `MyService.getContent();`, I'm not getting the `JSON` object, but an object with `$$state` and `__proto__`.
Why? How can I fore the factory to directly return the content only?
Note: I know I could write
`MyService.getContent().then(function(response) {
console.log(response);
});`
but this way I'd always have to repeat the `then... function` statement when I access the factory. | 2016/02/09 | [
"https://Stackoverflow.com/questions/35293460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1194415/"
] | You can't return the result of an asynchronous function. Your `return response.data;` statement is just exiting the promise `.then()` callback. You should modify your function like so:
```
getContent: function(id) {
return $http.get(urlBase);
}
```
And then call it like this:
```
MyService.getContent().then(function (response) {
// do something with the response
});
``` | That is because you are returning a promise that has already been resolve and not the promise instance. Just returning
```
$http.get(urlBase)
```
from your getContent function should do the trick :) |
6,034,467 | Web Developer here and need some advice on how to achieve what must be a common requirement in Windows Forms.
I have a windows client app that calls a business object in a separate project to perform some long running tasks. Difference to other examples is that the process live in another class library i.e. Business.LongRunningTask();
I have a list box in the client that I would like to have logged to by the task. I can run the process on the UI thread passsing in the instance of the textbox and calling Application.DoEvents() when I log to the textbox from within the task. All fine, but not elegant and would prefer not to call Application.DoEvents();
If I run the long running process on a separate thread using delegates I cannot access the textbox or delegates created in the windows client form which rules out BeginInvoke calls.
Surely this is bad design on my part and would appreciate some feedback. | 2011/05/17 | [
"https://Stackoverflow.com/questions/6034467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62282/"
] | You're looking for the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) class.
To execute a time-consuming operation in the background, create a `BackgroundWorker` and listen for events that report the progress of your operation and signal when your operation is finished.
You can find a complete example here: <http://msdn.microsoft.com/en-us/library/b2zk6580(v=VS.100).aspx#Y1351> | >
> I can run the process on the UI thread
> passsing in the instance of the
> textbox and calling
> Application.DoEvents() when I log to
> the textbox from within the task.
>
>
>
Yes, you could also pass in an instance of ILoggingINnterface that you have used to put in the code to write to the text box FROM WITHIN THE UI and thus have taken care of all the nice BginInvoke stuff ;)
>
> If I run the long running process on a
> separate thread using delegates I
> cannot access the textbox or delegates
> created in the windows client form
> which rules out BeginInvoke calls.
>
>
>
Ah. No. You just most invoke back to the dispatcher thread then you can access all the UI elemente you like. |
6,034,467 | Web Developer here and need some advice on how to achieve what must be a common requirement in Windows Forms.
I have a windows client app that calls a business object in a separate project to perform some long running tasks. Difference to other examples is that the process live in another class library i.e. Business.LongRunningTask();
I have a list box in the client that I would like to have logged to by the task. I can run the process on the UI thread passsing in the instance of the textbox and calling Application.DoEvents() when I log to the textbox from within the task. All fine, but not elegant and would prefer not to call Application.DoEvents();
If I run the long running process on a separate thread using delegates I cannot access the textbox or delegates created in the windows client form which rules out BeginInvoke calls.
Surely this is bad design on my part and would appreciate some feedback. | 2011/05/17 | [
"https://Stackoverflow.com/questions/6034467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62282/"
] | You're looking for the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) class.
To execute a time-consuming operation in the background, create a `BackgroundWorker` and listen for events that report the progress of your operation and signal when your operation is finished.
You can find a complete example here: <http://msdn.microsoft.com/en-us/library/b2zk6580(v=VS.100).aspx#Y1351> | Yeah, avoid `Application.DoEvents()`.
To marshall the call back onto the UI thread, call `this.Invoke(YourDelegate)` |
6,034,467 | Web Developer here and need some advice on how to achieve what must be a common requirement in Windows Forms.
I have a windows client app that calls a business object in a separate project to perform some long running tasks. Difference to other examples is that the process live in another class library i.e. Business.LongRunningTask();
I have a list box in the client that I would like to have logged to by the task. I can run the process on the UI thread passsing in the instance of the textbox and calling Application.DoEvents() when I log to the textbox from within the task. All fine, but not elegant and would prefer not to call Application.DoEvents();
If I run the long running process on a separate thread using delegates I cannot access the textbox or delegates created in the windows client form which rules out BeginInvoke calls.
Surely this is bad design on my part and would appreciate some feedback. | 2011/05/17 | [
"https://Stackoverflow.com/questions/6034467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62282/"
] | You're looking for the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) class.
To execute a time-consuming operation in the background, create a `BackgroundWorker` and listen for events that report the progress of your operation and signal when your operation is finished.
You can find a complete example here: <http://msdn.microsoft.com/en-us/library/b2zk6580(v=VS.100).aspx#Y1351> | To access UI elements from a different thread, you can use control.Invoke to call a delegate on the owning thread.
I used this at one point to create a live log screen which was updated from a timer while a different worker thread was running. Heres a simplified version:
```
public class DifferentClassLibrary
{
public delegate void StringDataDelegate(string data);
public event StringDataDelegate UpdatedData;
public void DoStuff()
{
if (UpdatedData != null)
{
Thread.Sleep(10000);
UpdatedData("data");
}
}
}
```
And in the winform:
```
public void UpdateTextBoxCallback(string data)
{
if (uiTextBoxLiveLogView.InvokeRequired)
{
uiTextBoxLiveLogView.Invoke(new DifferentClassLibrary.StringDataDelegate(UpdateTextBoxCallback), data);
}
else
{
uiTextBoxLiveLogView.Text += data;
}
}
void Main()
{
DifferentClassLibrary test = new DifferentClassLibrary();
test.UpdatedData += UpdateTextBoxCallback;
Thread thread = new Thread(new ThreadStart(test.DoStuff));
thread.Start();
}
``` |
14,892,148 | I have created one listview of some names,what i need is when i will click selected row it will go to that page only,on click on different row it will move to the same class but different content.I think it will move by question id.could anybody help me how to pass the question id Or any other method to do this..
here is my code..
```
private OnItemClickListener mlist = new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
}
};
``` | 2013/02/15 | [
"https://Stackoverflow.com/questions/14892148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can try something like this -
```
private OnItemClickListener mlist = new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
if(Some condition)
{
Intent i= new Intent(YourActivity.this,ActivityOne.class);
// To pass data
i.putExtra("SomeId", someValue);
startActivity(i);
}
else if(Some other condition)
{
Intent i= new Intent(YourActivity.this,SecondActivityTwo.class);
startActivity(i);
}
else
{
// Do something else--
}
}
};
```
And in the other activity -
```
String identifier = getIntent().getExtras().getString("SomeId");
``` | Here I've given an example assuming you have user list and clicking on item you want to show user profile...
In List\_Act activity...
```
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = mInflater.inflate(R.layout.rowitem,parent,false);
convertView.setTag(UserId);
}
private OnItemClickListener mlist = new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent i=new Intent(List_Act.this, Profile_Act.class);
int UserId = ((View)v.getParent()).getTag();
i.putExtra("UserId", UserId); //Setting variable you want to pass to another activity
startActivity(i);
}
};
```
in Profile\_Act activity in onCreate()
```
String UserId = getIntent().getExtras().getString("UserId"); //retrieving value in another activity
```
now you'll have UserId variable set and you can use it... |
45,085,143 | I have a simple OmniFaces 1.8.3 view-scoped bean **successfully deployed** on WebSphere 7 (7.0.50) along with OpenWebBeans 1.2.8 (and Mojarra 2.1.27 BTW):
```
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.inject.Named;
import org.omnifaces.cdi.ViewScoped;
...
@Named
@ViewScoped
public class CashValueCalculationManager implements Serializable {
private static final long serialVersionUID = 1L;
@EJB
private CashValueCalculationService cashValueCalculationService;
// the list of entities to be shown in a datatable
private List<CashValueCalculation> entities;
@PostConstruct
public void init() {
// displays "this.cashValueCalculationService = null" in the log
System.out.println("this.cashValueCalculationService = " + this.cashValueCalculationService);
// load list of entities on init
try {
this.loadViewData();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<CashValueCalculation> getEntities() {
return this.entities;
}
protected CashValueCalculationService getEntityService() {
return this.cashValueCalculationService;
}
protected void loadViewData() throws Exception {
// NPE here!
List<CashValueCalculation> cashValueCalculations = this.getEntityService().findAll();
this.entities = cashValueCalculations;
}
}
```
When opening the view of the bean however, the bean gets initialized running the `@PostConstruct` method to load all entities (just a handful), but this fails with a `NullPointerException` in loadViewData(). The returned service is null... this basically gets confirmed by the log in which I also find the line
```
this.cashValueCalculationService = null
```
The `CashValueCalculationService` interface is annotated with `@Local` and the implementation `CashValueCalculationServiceBean` is annotated with `@Stateless`:
```
@Local
public interface CashValueCalculationService extends EntityService<Integer, CashValueCalculation> {
// super interface has findAll()
}
```
Bean:
```
@Stateless
public class CashValueCalculationServiceBean extends BaseEntityServiceBean<Integer, CashValueCalculation> implements CashValueCalculationService {
// super class has findAll() implementation
}
```
I had this successfully being injected into JSF managed beans before trying the OmniFaces/CDI/OpenWebBeans on WebSphere 7 craze.
When app gets deployed on the server the following log entries appear:
```
.
.
.
[13.07.17 16:56:13:889 CEST] 00000013 WebContainerL I OpenWebBeans Container is starting...
[13.07.17 16:56:13:894 CEST] 00000013 PluginLoader I Adding OpenWebBeansPlugin : [OpenWebBeansJsfPlugin]
[13.07.17 16:56:13:899 CEST] 00000013 AbstractMetaD I added beans.xml marker: wsjar:file:/C:/IBM/WebSphere7.0/AppServer/profiles/CLDSrv7050/installedApps/srv-cld-helNode03Cell/CLD.ear/lib/omnifaces-1.8.3.jar!/META-INF/beans.xml
[13.07.17 16:56:13:901 CEST] 00000013 AbstractMetaD I added beans.xml marker: file:/C:/IBM/WebSphere7.0/AppServer/profiles/CLDSrv7050/installedApps/srv-cld-helNode03Cell/CLD.ear/cld-web.war/WEB-INF/beans.xml
[13.07.17 16:56:15:051 CEST] 00000013 AbstractMetaD W Ignoring class [org.omnifaces.facesviews.FacesViewsInitializer] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.ServletContainerInitializer
[13.07.17 16:56:15:322 CEST] 00000013 AbstractMetaD W Ignoring class [org.omnifaces.component.output.cache.CacheInitializerListener] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.FilterRegistration
[13.07.17 16:56:15:328 CEST] 00000013 AbstractMetaD W Ignoring class [org.omnifaces.util.Platform] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.ServletRegistration
[13.07.17 16:56:15:581 CEST] 00000013 AbstractMetaD W Ignoring class [org.omnifaces.facesviews.FacesViewsInitializer] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.ServletContainerInitializer
[13.07.17 16:56:15:586 CEST] 00000013 AbstractMetaD W Ignoring class [org.omnifaces.component.output.cache.CacheInitializerListener] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.FilterRegistration
[13.07.17 16:56:15:588 CEST] 00000013 AbstractMetaD W Ignoring class [org.omnifaces.util.Platform] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.ServletRegistration
[13.07.17 16:56:16:438 CEST] 00000013 AbstractMetaD W Ignoring class [org.omnifaces.facesviews.FacesViewsInitializer] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.ServletContainerInitializer
[13.07.17 16:56:16:443 CEST] 00000013 AbstractMetaD W Ignoring class [org.omnifaces.component.output.cache.CacheInitializerListener] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.FilterRegistration
[13.07.17 16:56:16:446 CEST] 00000013 AbstractMetaD W Ignoring class [org.omnifaces.util.Platform] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.ServletRegistration
[13.07.17 16:56:17:199 CEST] 00000013 BeansDeployer I All injection points were validated successfully.
[13.07.17 16:56:17:236 CEST] 00000013 WebContainerL I OpenWebBeans Container has started, it took [3345] ms.
[13.07.17 16:56:17:291 CEST] 00000013 config I Mojarra 2.1.27 ( 20140108-1632 https://svn.java.net/svn/mojarra~svn/tags/2.1.27@12764) für Kontext '/cld' wird initialisiert.
[13.07.17 16:56:17:739 CEST] 00000013 application I JSF1048: PostConstruct/PreDestroy-Annotationen vorhanden. Verwaltete Bean-Methoden, die mit diesen Annotationen markiert sind, lassen die entsprechenden Annotationen verarbeiten.
[13.07.17 16:56:19:334 CEST] 00000013 config W JSF1067: Ressource /WEB-INF/common-ui.taglib.xml, die von der Konfigurationsoption javax.faces.CONFIG_FILES angegeben wird, kann nicht gefunden werden. Die Ressource wird ignoriert.
[13.07.17 16:56:19:336 CEST] 00000013 config W JSF1067: Ressource /WEB-INF/common-functions.taglib.xml, die von der Konfigurationsoption javax.faces.CONFIG_FILES angegeben wird, kann nicht gefunden werden. Die Ressource wird ignoriert.
[13.07.17 16:56:19:475 CEST] 00000013 PostConstruct I Running on PrimeFaces 6.0.15
[13.07.17 16:56:19:478 CEST] 00000013 VersionLogger I Using OmniFaces version 1.8.3
[13.07.17 16:56:19:497 CEST] 00000013 lifecycle I JSF1027: [null Die ELResolvers für JSF wurden nicht im JSP-Container registriert.
.
.
.
```
The entries
```
Ignoring class [org.omnifaces.facesviews.FacesViewsInitializer] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.ServletContainerInitializer
Ignoring class [org.omnifaces.component.output.cache.CacheInitializerListener] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.FilterRegistration
Ignoring class [org.omnifaces.util.Platform] because it could not be loaded: java.lang.NoClassDefFoundError: javax.servlet.ServletRegistration
```
appear to the most interesting ones.
**But what do they actually mean?**
Of course, it's somewhat clear, the `servlet.api` classes are missing.
```
<dependency org="javax.servlet" name="servlet-api" rev="2.5" />
```
(Sorry this is Ant/Ivy syntax)
However adding `javax-servlet-api-2.5.jar` to the deployment totally breaks the app when logging in, saying "FacesServlet is not a Servlet class":
In HTML:
```
Original Exception:
Error message: javax.servlet.UnavailableException: SRVE0201E: Servlet [javax.faces.webapp.FacesServlet] is not a servlet class.
Error code: 404
Target servlet: Faces Servlet
Stacktrace:
javax.servlet.UnavailableException: SRVE0201E: Servlet [javax.faces.webapp.FacesServlet] is not a servlet class.
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:535)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:503)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:181)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3954)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:942)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1592)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:453)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:515)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:306)
at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:83)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1646)
```
I had to translate the error message as best as I could. WebSphere 7 BTW is a Servlet 2.5 container, so the problem might be classloader-related... ?
**BIG QUESTION(s):**
Why is this setup failing to inject EJBs via `@EJB` on the basically usable scenario (without the `javax.servlet` dependency)? The bean and bean manager seem to be present, so why isn't it able to inject via `@EJB`?
How do you possibly cure this? Can it be done at all? | 2017/07/13 | [
"https://Stackoverflow.com/questions/45085143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396732/"
] | Try this
```html
private headers = new Headers({'Content-Type': 'application/json;'});
update(formModel): Promise<ShortFormModel> {
let options: RequestOptions = new RequestOptions();
options.headers = this.headers;
return this.http
.post(this.preCheckUrl, JSON.stringify(formModel), options)
.toPromise()
.then(res => {
res.json().data as ShortFormModel;
})
.catch(
(error: any): Promise<any>=> {
this.router.navigate(['/error', error]);
return Promise.reject(error.message || error);
}
)
```
The `Headers` need to be added as part of the `RequestOptions` directive. | I feel very silly but the root cause was because I did not disable
```
InMemoryWebApiModule.forRoot(InMemoryDataService)
```
that I was using for dev before services were ready.
The solution I went with is pretty much out of angular's tutorial:
short-form.component
```
onSubmit(shortForm: any) {
if (!shortForm) { return; }
const formModel = this.shortForm.value;
this.shortFormService.create(formModel)
.subscribe(res => {
this.router.navigate(['/apply'])
})
}
```
short-form.service
```
create(shortForm: any): Observable<ShortFormModel> {
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(this.preCheckUrl, shortForm, options)
.map(this.extractData)
.catch(this.handleError);
}
``` |
33,118,889 | I am trying to implement Google Analytics (GA) in my iOS apps. I have two different targets that have different tracking-ids for GA. GA requires a `GoogleService-Info.plist` (cannot be renamed) file to be placed in the root of the app folder structure. This file contains the tracking-id. However, since I have two different targets I need to have two different tracking-ids.
I cannot have two file named to files with the same name with different targets.
So, is there a way to either copy another file into the root in the build process. Have tried this and similar but does not seem to work:
[](https://i.stack.imgur.com/VVjk9.png)
Any suggestions? | 2015/10/14 | [
"https://Stackoverflow.com/questions/33118889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/511299/"
] | **The script:**
```
PLIST_FILE="CustomGoogleService-Info.plist"
PLIST_PATH="${PROJECT_DIR}/path/To/Plist/Here/${PLIST_FILE}"
cp "${PLIST_PATH}" "${CONFIGURATION_BUILD_DIR}/${CONTENTS_FOLDER_PATH}/GoogleService-Info.plist"
```
Instructions:
* Add this script to the end of your `Build Phases`
* Change name `CustomGoogleService-Info.plist` to your own
* Change `pathToPlistHere` to the correct path where `CustomGoogleService-Info.plist` is located (starting from your project directory)
* You should not have `GoogleService-Info.plist` file in your project - the script will create it for you.
* Grab a coffee while it is running
You may be interested in reading [Apple's Xcode Build Setting Reference](http://help.apple.com/xcode/mac/8.0/#/itcaec37c2a6)
**Alternatively:**
You could have 2 files with the name `GoogleService-Info.plist`, but keep each in separate directory. Then you could add each to the corresponding target. Without any script. | I did correctly all along, however `Destination` should be set to `Wrapper` and subpath empty. No need to have them in the target either.
This one explained the Destination options: [xcode copy files build phase - what do the destination options mean exactly?](https://stackoverflow.com/questions/19156490/xcode-copy-files-build-phase-what-do-the-destination-options-mean-exactly) |
9,220,340 | Im looking for a very general method of providing an alternative site to a Javascript heavy site (a link going to the old static site).
My current implementation is:
```
//<Some JS/HTML>
$(document).ready(function() {
//<Some JS Code>
$('#error').attr('style','display: none;');
});
//<Some html>
<div id="error">
<span>If you can see this, that means something went very very wrong. Click <a href="somelink.php">Here</a> to use the old portal. Please contact some@email.com with this error and provide as much information as possible, thank you :) </span>
</div>
```
My current problem is that this is visible while the site is loading :(. Is there a better method?
I know i can try and add lots of trys and catchs (theres already several), but the problem is the primary clients are going to be using a mixture of clients between. FF2-FF3, all version in between, and IE5-IE6. The IE5 im just placing a messagebox and redirection if they try to load the site, im not even going to try and make that compatible.
And these old browsers just are not compatible with certain things.... I know i could add in an .onerror, but FF didn't add compatibility until FF6 which is to new for most of the clients. (although strangely, IE5.5 has it)
NOTE: Im just jQuery 1.7.1
The basic flow of the current operation is just when it finishes loading the initial javascript it hides the div. | 2012/02/09 | [
"https://Stackoverflow.com/questions/9220340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130968/"
] | You can use mainly CSS with a JS helper for this.
Put this JS code as close to the top of the document as you dare, preferibly after the charset declaration. You will need to include jQuery before this line or you can use standard JS (`document.getElementByID('html-tag').className='js';`, this assumes you've given the `html` tag an id of `html-tag`):
```
$('html').addClass('js');
```
Then you can write your CSS to take into account the fact that JS may or may not be available:
```
#error {
display : block;/*if no JavaScript is available then show this element*/
}
.js #error {
display : none;/*if JavaScript is available then hide this element*/
}
```
Here is a demo: <http://jsfiddle.net/x4tjL/> (JSFiddle seems to be having problems right now, here is a JSBin: <http://jsbin.com/ahezuc/edit#preview>)
Update
------
Putting the JavaScript code as near the top of the document and not wrapping the code in a `document.ready` event handler allows you to minimize the "flash" of content that is common when trying to hide/show content based on JS. | A simple solution would be to detect all incompatible browsers and show the message to upgrade their browser or to redirect to non js site, something like:
```
for IE5 and 6
if ($.browser.msie && $.browser.version <= 6){
//show my message here
}
``` |
55,962,891 | is there a way to refer to a specific column relative to a specific data frame in python like there is in R (data.frame$data)? | 2019/05/03 | [
"https://Stackoverflow.com/questions/55962891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11445124/"
] | Usually with `[]` => `data.frame["data"]`
Or for object like with `.` => `data.frame.data` | You can generally use pandas to mimic R. You can use [] as below.
my\_column = df['columnName'] |
391,104 | I have some trouble with proper understanding of $H\_0^1(0,1)$ space. Consider the following space $$H\_D = \{u\in H^1(0,1): u(0) = u(1) = 0\}.$$ What can we say about the connection between $H\_D$ and $H^1\_0(0,1)$. Is $H\_D$ in $H^1\_0(0,1)$? In literature stays, that functions in $H\_0^1(0,l)$ are interpreted as $$''u = 0\; \text{on}\; \partial\Omega''.$$ | 2013/05/14 | [
"https://math.stackexchange.com/questions/391104",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/42857/"
] | Do you know anything about the [trace operator](http://en.wikipedia.org/wiki/Trace_%28Sobolev_space%29)? There is a theorem that says that if $U$ is a bounded domain and $\partial U$ is $C^1$ and $u \in W^{1,p}$, then
$$
u \in W\_0^{1,p}(U) \iff Tu=0 \text{ on } \partial U,
$$
where $T$ is the trace operator. You want $p = 2$ here. | In one-dimensions, Sobolev functions have a well-defined continuous representative. Therefore, they are well-defined at every point of their domain. |
11,326,405 | I'm using Django for our project. And I have created a form using Django forms. In one of the form i need to check a variable and based on the value of the variable i need to add or remove an element.
I'm passing this variable to the form when the object is initialized.
ie `form=MyForm(flag)`
And in the forms class i'm doing this
```
class MyInfoForm(forms.Form):
def __init__(self, *args,**kwargs):
self.flag= kwargs.pop('flag', None)
super(MyInfoForm, self).__init__(*args, **kwargs)
print self.flag
Firstname = forms.CharField(label=u' First name :', max_length=30)
```
In the init function i have printed the flag and its working fine. But how can i access the variable out side *init*
I tried
```
class MyInfoForm(forms.Form):
myFlag=None
def __init__(self, *args,**kwargs):
self.flag= kwargs.pop('flag', None)
myFlag=self.flag
super(MyInfoForm, self).__init__(*args, **kwargs)
print self.flag
Firstname = forms.CharField(label=u' First name :', max_length=30)
print myFlag
```
But its not working. | 2012/07/04 | [
"https://Stackoverflow.com/questions/11326405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/513101/"
] | The `class` statement is an executable statement that:
1. creates a namespaces
2. execute, sequentially, all code at the top-level of the class statement block
3. call the appropriate metaclass (defaulting to `type`) with the classname, namespace, and list of parent classes
4. bind the newly created `class` object to the classname in the enclosing (usually the module) namespace
To make a long story short you just cannot access instance attributes from within the `class` statement body, since neither the instance nor even the class itself exist yet.
If what you want is to update / add / remove fields on a per instance basis and according to some argument passed to the form's initializer, the correct solution is to first call the parent's initializer (to make sure your form's instance fields are correctly initialized) then do whatever you have to do, ie:
```
class MyInfoForm(forms.Form):
firstname = forms.CharField(label=u' First name :', max_length=30)
def __init__(self, *args,**kwargs):
self.flag= kwargs.pop('flag', None)
super(MyInfoForm, self).__init__(*args, **kwargs)
if self.flag:
# XXX IMPORTANT :
# you want to access self.fields['fieldname']
# NOT self.fieldname
self.fields["firstname"].label = "Yadda"
``` | ```
print MyInfoForm.myFlag
```
how abou this? |
11,326,405 | I'm using Django for our project. And I have created a form using Django forms. In one of the form i need to check a variable and based on the value of the variable i need to add or remove an element.
I'm passing this variable to the form when the object is initialized.
ie `form=MyForm(flag)`
And in the forms class i'm doing this
```
class MyInfoForm(forms.Form):
def __init__(self, *args,**kwargs):
self.flag= kwargs.pop('flag', None)
super(MyInfoForm, self).__init__(*args, **kwargs)
print self.flag
Firstname = forms.CharField(label=u' First name :', max_length=30)
```
In the init function i have printed the flag and its working fine. But how can i access the variable out side *init*
I tried
```
class MyInfoForm(forms.Form):
myFlag=None
def __init__(self, *args,**kwargs):
self.flag= kwargs.pop('flag', None)
myFlag=self.flag
super(MyInfoForm, self).__init__(*args, **kwargs)
print self.flag
Firstname = forms.CharField(label=u' First name :', max_length=30)
print myFlag
```
But its not working. | 2012/07/04 | [
"https://Stackoverflow.com/questions/11326405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/513101/"
] | The `class` statement is an executable statement that:
1. creates a namespaces
2. execute, sequentially, all code at the top-level of the class statement block
3. call the appropriate metaclass (defaulting to `type`) with the classname, namespace, and list of parent classes
4. bind the newly created `class` object to the classname in the enclosing (usually the module) namespace
To make a long story short you just cannot access instance attributes from within the `class` statement body, since neither the instance nor even the class itself exist yet.
If what you want is to update / add / remove fields on a per instance basis and according to some argument passed to the form's initializer, the correct solution is to first call the parent's initializer (to make sure your form's instance fields are correctly initialized) then do whatever you have to do, ie:
```
class MyInfoForm(forms.Form):
firstname = forms.CharField(label=u' First name :', max_length=30)
def __init__(self, *args,**kwargs):
self.flag= kwargs.pop('flag', None)
super(MyInfoForm, self).__init__(*args, **kwargs)
if self.flag:
# XXX IMPORTANT :
# you want to access self.fields['fieldname']
# NOT self.fieldname
self.fields["firstname"].label = "Yadda"
``` | This depends... should the scope of flag be the class, or the instance of the class?
If the scope should be the instance (this is what it seems like from your first try), then you access it by doing:
```
instance = MyInfoForm(flag)
...
instance.flag
```
If, on the other hand, the variable flag belongs to the class (meaning, there is only one value for flag for every instance of MyInfoForm), then you can access it by doing:
```
MyInfoForm.myFlag #using your second attempt
```
Also... You're declaring the variable as `myFlag`, and trying to print `myflag`. Variable names are case sensitive. |
31,179,134 | I have tried:
```
wx.ToolTip.Enable(False)
wx.ToolTip_Enable(False)
```
and
```
wx.ToolTip.Enable(flag=False)
```
none of theses instructions are rejected and yet none of them work
I'm using `Linux Mint 17` `wx.python 2.8.12.1 (gtk2-unicode)` `python 2.7` | 2015/07/02 | [
"https://Stackoverflow.com/questions/31179134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4637585/"
] | you need to echo the variable:
```
$scope.var = "<? echo $var; ?>"
```
or in a shorter way:
```
$scope.var = "<?=$var; ?>"
```
technicly both are the same. | I would suggest exposing a public API from your PHP application and then calling it using the [$http](https://docs.angularjs.org/api/ng/service/$http) service in angular-js.
```
$http.get('APIURL', {cache: true})
.success(function(data){...})
.error(function(data){});
``` |
32,920,574 | This should be something really simple but I just can't get it.
I want to pass a particular field value to controller function through onclick by form submit.
```
<form action="<?php echo base_url();>data/pass" method="post">
<select name="name1" id="name1" onclick="" class="m-wrap" >
<option selected="selected" disabled="disabled">Select</option>
<option value="1">by year</option>
</select>
<form>
``` | 2015/10/03 | [
"https://Stackoverflow.com/questions/32920574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4899166/"
] | change your code like this
```
<form action="<?php echo base_url();?>data/pass" method="post">
<select name="name1" id="name1" onchange="this.form.submit()" class="m-wrap" >
<option selected="selected" disabled="disabled">Select</option>
<option value="1">by year</option>
</select>
<form>
``` | ```
<form id="form-id" method="post">
<select name="name1" id="name1" class="m-wrap" >
<option selected="selected" disabled="disabled">Select</option>
<option value="1">by year</option>
</select>
<button type="submit" >Onclick</button>
<form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
$(document).ready(function(){
$('#form-id').ajaxForm({
type : 'POST',
dataType: 'json',
url: "<?php echo base_url();>data/pass ",
success: function(res)
{
//Your code success
}
});
</script>``
```
You Can use this form |
2,090,654 | I am attempting to setup a sample dynamic web project in Eclipse using Java EE, Spring and Maven (using Nexus repository manager). I was wondering if anybody knows the "best practice" directory structure that I should setup for an enterprise web app in Eclipse? Should I just stick with the default structure that is setup for me? I ask because looking around the internet I see wide variation (for instance, where the WEB-INF and META-INF folders are..if there is a 'war' directory etc.). Thanks! | 2010/01/19 | [
"https://Stackoverflow.com/questions/2090654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253664/"
] | If you use Maven, I'd warmly recommend to just follow **Maven's convention**. This is the "best practice" in Maven's world (and I don't see any good reasons to not do so, not following this advice will lead to more work).
One easy way to create a webapp project is to use the maven-archetype-webapp:
```
mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp \
-DgroupId=com.mycompany.app \
-DartifactId=my-webapp \
-Dversion=1.0-SNAPSHOT
```
(You can paste this command "as is" in a Linux shell; on Windows, type everything on single line without the `"\"`.)
And this is the structure you'll get:
```
my-webapp
|-- pom.xml
`-- src
`-- main
|-- resources
`-- webapp
|-- WEB-INF
| `-- web.xml
`-- index.jsp
```
This layout is compliant with Eclipse WTP (whatever plugin you're using for the Eclipse integration). Just import this project into Eclipse and there you go.
If you have more specific question, feel free to ask (for example, most of time you don't have to worry about the `META-INF` directory, but put it under `src/main/resources` if really you need to have it). | If you're using Maven, it's best to follow [their convention](http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html).
If you're using Spring, you don't need an EAR. A WAR will do just fine.
A WAR file has a definite standard that you must follow. As long as you can generate a proper WAR file, you can use any directory structure for your source code that makes sense to you.
I use something like this:
```
/project
+---/src (.java)
+---/test (TestNG .java here)
+---/test-lib (testNG JAR, Spring test JAR, etc.)
+---/resources (log4j.xml, etc.)
+---/web (root of web content here)
+---+---/WEB-INF
+---+---+---/classes (compile .java to this directory)
+---+---+---/lib (JAR files)
```
I use IntelliJ, so it creates an exploded WAR file as output for me.
I have an Ant build.xml that generally follows the IntelliJ directory structure. You're welcome to crib it if you find it useful.
```
<?xml version="1.0" encoding="UTF-8"?>
<project name="xslt-converter" basedir="." default="package">
<property name="version" value="1.6"/>
<property name="haltonfailure" value="no"/>
<property name="out" value="out"/>
<property name="production.src" value="src"/>
<property name="production.lib" value="lib"/>
<property name="production.resources" value="config"/>
<property name="production.classes" value="${out}/production/${ant.project.name}"/>
<property name="test.src" value="test"/>
<property name="test.lib" value="lib"/>
<property name="test.resources" value="config"/>
<property name="test.classes" value="${out}/test/${ant.project.name}"/>
<property name="exploded" value="out/exploded/${ant.project.name}"/>
<property name="exploded.classes" value="${exploded}/WEB-INF/classes"/>
<property name="exploded.lib" value="${exploded}/WEB-INF/lib"/>
<property name="reports.out" value="${out}/reports"/>
<property name="junit.out" value="${reports.out}/junit"/>
<property name="testng.out" value="${reports.out}/testng"/>
<path id="production.class.path">
<pathelement location="${production.classes}"/>
<pathelement location="${production.resources}"/>
<fileset dir="${production.lib}">
<include name="**/*.jar"/>
<exclude name="**/junit*.jar"/>
<exclude name="**/*test*.jar"/>
</fileset>
</path>
<path id="test.class.path">
<path refid="production.class.path"/>
<pathelement location="${test.classes}"/>
<pathelement location="${test.resources}"/>
<fileset dir="${test.lib}">
<include name="**/junit*.jar"/>
<include name="**/*test*.jar"/>
</fileset>
</path>
<path id="testng.class.path">
<fileset dir="${test.lib}">
<include name="**/testng*.jar"/>
</fileset>
</path>
<available file="${out}" property="outputExists"/>
<target name="clean" description="remove all generated artifacts" if="outputExists">
<delete dir="${out}" includeEmptyDirs="true"/>
<delete dir="${reports.out}" includeEmptyDirs="true"/>
</target>
<target name="create" description="create the output directories" unless="outputExists">
<mkdir dir="${production.classes}"/>
<mkdir dir="${test.classes}"/>
<mkdir dir="${reports.out}"/>
<mkdir dir="${junit.out}"/>
<mkdir dir="${testng.out}"/>
<mkdir dir="${exploded.classes}"/>
<mkdir dir="${exploded.lib}"/>
</target>
<target name="compile" description="compile all .java source files" depends="create">
<!-- Debug output
<property name="production.class.path" refid="production.class.path"/>
<echo message="${production.class.path}"/>
-->
<javac srcdir="src" destdir="${out}/production/${ant.project.name}" debug="on" source="${version}">
<classpath refid="production.class.path"/>
<include name="**/*.java"/>
<exclude name="**/*Test.java"/>
</javac>
<javac srcdir="${test.src}" destdir="${out}/test/${ant.project.name}" debug="on" source="${version}">
<classpath refid="test.class.path"/>
<include name="**/*Test.java"/>
</javac>
</target>
<target name="junit-test" description="run all junit tests" depends="compile">
<!-- Debug output
<property name="test.class.path" refid="test.class.path"/>
<echo message="${test.class.path}"/>
-->
<junit printsummary="yes" haltonfailure="${haltonfailure}">
<classpath refid="test.class.path"/>
<formatter type="xml"/>
<batchtest fork="yes" todir="${junit.out}">
<fileset dir="${test.src}">
<include name="**/*Test.java"/>
</fileset>
</batchtest>
</junit>
<junitreport todir="${junit.out}">
<fileset dir="${junit.out}">
<include name="TEST-*.xml"/>
</fileset>
<report todir="${junit.out}" format="frames"/>
</junitreport>
</target>
<taskdef resource="testngtasks" classpathref="testng.class.path"/>
<target name="testng-test" description="run all testng tests" depends="compile">
<!-- Debug output
<property name="test.class.path" refid="test.class.path"/>
<echo message="${test.class.path}"/>
-->
<testng classpathref="test.class.path" outputDir="${testng.out}" haltOnFailure="${haltonfailure}" verbose="2" parallel="methods" threadcount="50">
<classfileset dir="${out}/test/${ant.project.name}" includes="**/*.class"/>
</testng>
</target>
<target name="exploded" description="create exploded deployment" depends="testng-test">
<copy todir="${exploded.classes}">
<fileset dir="${production.classes}"/>
</copy>
<copy todir="${exploded.lib}">
<fileset dir="${production.lib}"/>
</copy>
</target>
<target name="package" description="create package file" depends="exploded">
<jar destfile="${out}/${ant.project.name}.jar" basedir="${production.classes}" includes="**/*.class"/>
</target>
</project>
``` |
1,054,383 | For several months, I have been successfully connected to the net via a static IP with my machine that is running ubuntu (16.04.3). I recently had to reinstall the OS, and now on the same machine, the system is ignoring my DNS settings. The DNS server hasn't changed, nor has the machine's static IP address changed. Furthermore, I can ping the DNS IP addresses with no problem from the ubuntu device. As a double check, other machines that I own and which reside on the same network have no trouble with DNS using the same addresses.
For the purpose of this discussion, assume the following hypothetical settings:
```
Hostname: host-o-rama-bama.com
Static IP: 10.20.30.40
Gateway: 10.20.30.1
Netmask: 255.255.255.0
DNS server: 100.110.120.130
DNS server: 100.110.120.140
```
Using the Ubuntu Network Manager, I configured these settings as follows:
```
General
* Automatically connect to this network when it is available: Yes
* All users may connect to this network: Yes
Ethernet
* Device: enp2s0f1
* Wake on LAN: Default
802.1x security
(None)
DCB
(None)
IPV4 Settings
* Method: Manual
* Address: 10.20.30.40
* Netmask: 255.255.255.0
* Gateway: 10.20.30.1
* DNS Servers: 100.110.120.130,100.110.120.140
* Search Domains: host-o-rama-bama.com
IPV6 Settings
* Method: Ignore
```
After starting the network ...
```
# ifconfig
enp2s0f1 Link encap:Ethernet HWaddr 80:fa:5b:4c:02:07
inet addr:10.20.30.40 Bcast:10.20.30.255 Mask:255.255.255.0
inet6 addr: fe80::82fa:5bff:fe4c:207/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:63252 errors:0 dropped:0 overruns:0 frame:0
TX packets:40966 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:53814860 (53.8 MB) TX bytes:5441842 (5.4 MB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:7029 errors:0 dropped:0 overruns:0 frame:0
TX packets:7029 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:650606 (650.6 KB) TX bytes:650606 (650.6 KB)
```
At this point, I can ping each of my DNS servers via their IP addresses.
Furthermore, remote sites can ping my ubuntu host both by its static IP address and also by the name `host-o-rama-bama.com`, which is already set up on the DNS servers. I can even ssh into my host both via its IP address and its DNS name.
However, I cannot see any domain names from the ubuntu machine, but , I can indeed access anywhere I want on the net via ssh, telnet, http, ping, etc. as long as I use the IP address.
In `/etc/resolvconf/resolv.conf.d/base`, I put the following, and then I ran `resolvconf -u` ...
```
domain host-o-rama-bama.com
search host-o-rama-bama.com
nameserver 100.110.120.130
nameserver 100.110.120.140
```
However, after running it, the DNS is still not working.
I put the following into `/etc/network/interfaces` ...
```
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback
auto enp2s0f1
iface enp2s0f1 inet static
address 10.20.30.40
netmask 255.255.255.0
gateway 10.20.30.1
dns-nameserver 100.110.120.130
dns-nameserver 100.110.120.140
dns-search host-o-rama-bama.com
```
I then did the following:
```
# ifdown enp2s0f1
# ifup enp2s0f1
```
Nothing changed. The DNS is still not working.
I then commented out everything in `/etc/network/interfaces` from the `auto enp2s0f1` line to the bottom of the file and then did this ...
```
# ifdown -a
# ifup -a
```
Still no DNS.
I then tried this ...
```
# /etc/init.d/network-manager stop
# /etc/init.d/network-manager start
```
The DNS is still not working.
Then, I did this:
```
# service networking restart
```
... and still no DNS.
What am I missing?
Thank you in advance. | 2018/07/12 | [
"https://askubuntu.com/questions/1054383",
"https://askubuntu.com",
"https://askubuntu.com/users/849049/"
] | Gnome3 disables the touchpad while typing by default. You can disable that feature using the gnome tweak tool.
The entry for the touchpad is under *Keyboard & Mouse* in the tool.
To get the tool either install it via `sudo apt install gnome-tweak-tool` in the terminal or search for `Gnome Tweaks` in the Ubuntu software store. | Open a terminal and type this command:
```
gsettings set org.gnome.desktop.peripherals.touchpad "disable-while-typing" false
```
To disable again type:
```
gsettings set org.gnome.desktop.peripherals.touchpad "disable-while-typing" true
```
If you like a short form (alias), I suggest the following. The next 3 lines will add an alias your `.bashrc`. Copy this and add these into your terminal.
```
echo "# Alias for en-/disabeling the Touchpad
echo "alias dit=\"gsettings set org.gnome.desktop.peripherals.touchpad "disable-while-typing" true\"" >> ~/.bashrc
echo "alias ent=\"gsettings set org.gnome.desktop.peripherals.touchpad "disable-while-typing" false\"" >> ~/.bashrc
```
Verify that the 3 lines are written into your .bashrc by
```
tail ~/.bashrc
```
Now resource your `.bashrc` by
```
source ~/.bashrc
```
Now by typing
```
dit
```
you will disable your touchpad while typing,
```
ent
```
will enable your touchpad while writing. |
52,548,552 | I am trying to run Selenium using python, and I was successful in starting the browser and entering user name and password, but I was not able to run xpath for login button.
```
Python Script
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
mydriver = webdriver.Chrome(executable_path=r"C:\Mypath\chromedriver.exe")
baseurl = "http://www.gcrit.com/build3/admin/"
mydriver.get(baseurl)
username = "admin"
xpaths = { 'usernameTxtBox' : "//input[@name='username']",
'passwordTxtBox' : "//input[@name='password']",
'submitButton' : "//input[@name='login']"
} mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).send_keys(username)
password = "admin@123"
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)
All other steps run fine except this one:
mydriver.find_element_by_xpath(xpaths['loginButton']).click()
```
I am getting this error message
```
mydriver.find_element_by_xpath(xpaths['loginButton']).click()
KeyError: 'loginButton'
I tried getting the Xpath from element as well but I got the same error. @id="tdb1"]
```
HTML of Login Button (It would be helpful to know any efficient way of identifying elements) :
```
<button id="tdb1" type="submit" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary ui-priority-secondary" role="button" aria-disabled="false"><span class="ui-button-icon-primary ui-icon ui-icon-key"></span><span class="ui-button-text">Login</span></button>
``` | 2018/09/28 | [
"https://Stackoverflow.com/questions/52548552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8117146/"
] | The problem is not with your project, but with the PC you are trying to build it on. Maybe you have disabled updates, because apparently you still have Windows 10 Anniversary Update (14393) which is very old (current version is April 2018 Update (17134). To build apps with Fall Creators Update SDK (which is the first that supports .NET Standard 2.0.), you first have to update at least to that version of the operating system.
Go to system Settings, Update & Security and check for updates. There must be a lot of them waiting for you already. If not, use Windows 10 Update Assistant from [here](https://www.microsoft.com/en-us/software-download/windows10). | Go to Solution explorer and double tap the properties
[](https://i.stack.imgur.com/67F2W.png)
Then please select application options and select minimum build version based on your current OS build version. It works for me.
[](https://i.stack.imgur.com/YhCvI.png) |
6,007,463 | In CreateFile() has DesiredAccess Like GENERIC\_READ, GENERIC\_WRITE, FILE\_READ\_ATTRIBUTES, etc.
My question is what is the minimum/exact permissions needed to solely delete a file in the system?
Thanks | 2011/05/15 | [
"https://Stackoverflow.com/questions/6007463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/324827/"
] | If you just want to delete a file, use the [`DeleteFile`](http://msdn.microsoft.com/en-us/library/aa363915%28v=vs.85%29.aspx) function.
It's documentation details what permissions you need, and a few things you should know, like:
>
> If you request delete permission at the time you create a file, you can delete or rename the file with that handle, but not with any other handle.
>
>
>
There is good information in that documentation page, including a link to [File Security and Access Rights](http://msdn.microsoft.com/en-us/library/aa364399%28v=vs.85%29.aspx).
Look at the [`ACCESS_MASK`](http://msdn.microsoft.com/en-us/library/aa374892%28v=vs.85%29.aspx) page linked from the `OpenFile` documentation page for the actual delete access right flag - it's simply called `DELETE`.
But a word of warning: this type of check is always racy. The file permissions can change between your access right check and a subsequent delete. ([Time of check/time of use](http://en.wikipedia.org/wiki/Time-of-check-to-time-of-use).) | You only need `DELETE` access, I believe. It's not a file access right, it's a standard access right.
It's not easily found that these standard access rights are allowed, but the [MSDN page](http://msdn.microsoft.com/en-us/library/gg258116%28v=vs.85%29.aspx) on file access rights states:
>
> The valid access rights for files and directories include the DELETE, READ\_CONTROL, WRITE\_DAC, WRITE\_OWNER, and SYNCHRONIZE standard access rights.
>
>
> |
6,949,864 | My code:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid --get data, put into a temp table
ALTER TABLE #t
DROP COLUMN CID -- remove primary key column CID
INSERT INTO CTABLE SELECT * FROM #t -- insert record to table
DROP TABLE #t -- drop temp table
```
The error is:
```
Msg 8101,
An explicit value for the identity column in table 'CTABLE' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
```
And I did set
```
SET IDENTITY_INSERT CTABLE OFF
GO
``` | 2011/08/04 | [
"https://Stackoverflow.com/questions/6949864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807463/"
] | ```
DECLARE
@cid INT,
@o INT,
@t NVARCHAR(255),
@c NVARCHAR(MAX),
@sql NVARCHAR(MAX);
SELECT
@cid = 10,
@t = N'dbo.CTABLE',
@o = OBJECT_ID(@t);
SELECT @c = STRING_AGG(QUOTENAME(name), ',')
FROM sys.columns
WHERE [object_id] = @o
AND is_identity = 0;
SET @sql = 'SELECT ' + @c + ' INTO #t
FROM ' + @t + ' WHERE CID = @cid;
INSERT ' + @t + '('+ @c + ')
SELECT ' + @c + ' FROM #t;'
PRINT @sql;
-- exec sp_executeSQL @sql,
-- N'@cid int',
-- @cid = @cid;
```
However it seems much easier to just build the following SQL and avoid the #temp table altogether:
```
SET @sql = 'INSERT ' + @t + '(' + @c + ')
SELECT ' + @c + ' FROM ' + @t + '
WHERE CID = @cid;';
PRINT @sql;
-- exec sp_executeSQL @sql,
-- N'@cid int',
-- @cid = @cid;
``` | Try specifying the columns:
```
INSERT INTO CTABLE
(col2, col3, col4)
SELECT col2, col3, col4
FROM #t
```
Seems like it might be thinking you are trying to insert into the PK field since you are not explicitly defining the columns to insert into. If Identity insert is off and you specify the non-pk columns then you shouldn't get that error. |
6,949,864 | My code:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid --get data, put into a temp table
ALTER TABLE #t
DROP COLUMN CID -- remove primary key column CID
INSERT INTO CTABLE SELECT * FROM #t -- insert record to table
DROP TABLE #t -- drop temp table
```
The error is:
```
Msg 8101,
An explicit value for the identity column in table 'CTABLE' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
```
And I did set
```
SET IDENTITY_INSERT CTABLE OFF
GO
``` | 2011/08/04 | [
"https://Stackoverflow.com/questions/6949864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807463/"
] | Try this:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid
ALTER TABLE #t
DROP COLUMN CID
INSERT CTABLE --Notice that INTO is removed here.
SELECT top(1) * FROM #t
DROP TABLE #t
```
Test Script(Tested in SQL 2005):
```
CREATE TABLE #TestIDNT
(
ID INT IDENTITY(1,1) PRIMARY KEY,
TITLE VARCHAR(20)
)
INSERT #TestIDNT
SELECT 'Cybenate'
``` | If using SQL Server Management Studio and your problems you have too many fields to type them all out except the identity column, then right click on the table and click "Script table as" / "Select To" / "New Query Window".
This will provide a list of fields that you can copy & paste into your own query and then just remove the identity column. |
6,949,864 | My code:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid --get data, put into a temp table
ALTER TABLE #t
DROP COLUMN CID -- remove primary key column CID
INSERT INTO CTABLE SELECT * FROM #t -- insert record to table
DROP TABLE #t -- drop temp table
```
The error is:
```
Msg 8101,
An explicit value for the identity column in table 'CTABLE' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
```
And I did set
```
SET IDENTITY_INSERT CTABLE OFF
GO
``` | 2011/08/04 | [
"https://Stackoverflow.com/questions/6949864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807463/"
] | Try this:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid
ALTER TABLE #t
DROP COLUMN CID
INSERT CTABLE --Notice that INTO is removed here.
SELECT top(1) * FROM #t
DROP TABLE #t
```
Test Script(Tested in SQL 2005):
```
CREATE TABLE #TestIDNT
(
ID INT IDENTITY(1,1) PRIMARY KEY,
TITLE VARCHAR(20)
)
INSERT #TestIDNT
SELECT 'Cybenate'
``` | Here's an example to dynamically build a list of columns - excluding the primary key columns - and execute the INSERT
```
declare @tablename nvarchar(100), @column nvarchar(100), @cid int, @sql nvarchar(max)
set @tablename = N'ctable'
set @cid = 1
set @sql = N''
declare example cursor for
select column_name
from information_schema.columns
where table_name = @tablename
and column_name not in (
select column_name
from information_schema.key_column_usage
where constraint_name in (select constraint_name from information_schema.table_constraints)
and table_name = @tablename
)
open example
fetch next from example into @column
while @@fetch_status = 0
begin
set @sql = @sql + N'[' + @column + N'],'
fetch next from example into @column
end
set @sql = substring(@sql, 1, len(@sql)-1)
close example
deallocate example
set @sql = N'insert into ' + @tablename + '(' + @sql + N') select top(1) ' + @sql + ' from #t'
--select @sql
exec sp_executesql @sql
``` |
6,949,864 | My code:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid --get data, put into a temp table
ALTER TABLE #t
DROP COLUMN CID -- remove primary key column CID
INSERT INTO CTABLE SELECT * FROM #t -- insert record to table
DROP TABLE #t -- drop temp table
```
The error is:
```
Msg 8101,
An explicit value for the identity column in table 'CTABLE' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
```
And I did set
```
SET IDENTITY_INSERT CTABLE OFF
GO
``` | 2011/08/04 | [
"https://Stackoverflow.com/questions/6949864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807463/"
] | Here's an example to dynamically build a list of columns - excluding the primary key columns - and execute the INSERT
```
declare @tablename nvarchar(100), @column nvarchar(100), @cid int, @sql nvarchar(max)
set @tablename = N'ctable'
set @cid = 1
set @sql = N''
declare example cursor for
select column_name
from information_schema.columns
where table_name = @tablename
and column_name not in (
select column_name
from information_schema.key_column_usage
where constraint_name in (select constraint_name from information_schema.table_constraints)
and table_name = @tablename
)
open example
fetch next from example into @column
while @@fetch_status = 0
begin
set @sql = @sql + N'[' + @column + N'],'
fetch next from example into @column
end
set @sql = substring(@sql, 1, len(@sql)-1)
close example
deallocate example
set @sql = N'insert into ' + @tablename + '(' + @sql + N') select top(1) ' + @sql + ' from #t'
--select @sql
exec sp_executesql @sql
``` | Try invoking the INSERT statement with EXEC:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid
ALTER TABLE #t
DROP COLUMN CID
EXEC('INSERT INTO CTABLE SELECT top(1) * FROM #t')
DROP TABLE #t
``` |
6,949,864 | My code:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid --get data, put into a temp table
ALTER TABLE #t
DROP COLUMN CID -- remove primary key column CID
INSERT INTO CTABLE SELECT * FROM #t -- insert record to table
DROP TABLE #t -- drop temp table
```
The error is:
```
Msg 8101,
An explicit value for the identity column in table 'CTABLE' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
```
And I did set
```
SET IDENTITY_INSERT CTABLE OFF
GO
``` | 2011/08/04 | [
"https://Stackoverflow.com/questions/6949864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807463/"
] | ```
DECLARE
@cid INT,
@o INT,
@t NVARCHAR(255),
@c NVARCHAR(MAX),
@sql NVARCHAR(MAX);
SELECT
@cid = 10,
@t = N'dbo.CTABLE',
@o = OBJECT_ID(@t);
SELECT @c = STRING_AGG(QUOTENAME(name), ',')
FROM sys.columns
WHERE [object_id] = @o
AND is_identity = 0;
SET @sql = 'SELECT ' + @c + ' INTO #t
FROM ' + @t + ' WHERE CID = @cid;
INSERT ' + @t + '('+ @c + ')
SELECT ' + @c + ' FROM #t;'
PRINT @sql;
-- exec sp_executeSQL @sql,
-- N'@cid int',
-- @cid = @cid;
```
However it seems much easier to just build the following SQL and avoid the #temp table altogether:
```
SET @sql = 'INSERT ' + @t + '(' + @c + ')
SELECT ' + @c + ' FROM ' + @t + '
WHERE CID = @cid;';
PRINT @sql;
-- exec sp_executeSQL @sql,
-- N'@cid int',
-- @cid = @cid;
``` | Try invoking the INSERT statement with EXEC:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid
ALTER TABLE #t
DROP COLUMN CID
EXEC('INSERT INTO CTABLE SELECT top(1) * FROM #t')
DROP TABLE #t
``` |
6,949,864 | My code:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid --get data, put into a temp table
ALTER TABLE #t
DROP COLUMN CID -- remove primary key column CID
INSERT INTO CTABLE SELECT * FROM #t -- insert record to table
DROP TABLE #t -- drop temp table
```
The error is:
```
Msg 8101,
An explicit value for the identity column in table 'CTABLE' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
```
And I did set
```
SET IDENTITY_INSERT CTABLE OFF
GO
``` | 2011/08/04 | [
"https://Stackoverflow.com/questions/6949864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807463/"
] | If using SQL Server Management Studio and your problems you have too many fields to type them all out except the identity column, then right click on the table and click "Script table as" / "Select To" / "New Query Window".
This will provide a list of fields that you can copy & paste into your own query and then just remove the identity column. | You can't do this:
```
INSERT INTO CTABLE SELECT top(1) * FROM #t
```
Because the column listings aren't the same. You've dropped the PK column from #t, so you have 1 less column in #t than in CTABLE. This is the equivalent of the following:
```
INSERT INTO CTABLE(pk, col1, col2, col3, ...)
select top(1) col1, col2, col3, ...
from #t
```
This wouldn't work for obvious reasons. Similarly, you aren't going to be able to specify the \* wildcard to do the insert if you're not inserting all of the columns. The only way to do the insert without including the PK is to specify every column. You can generate a list of columns through dynamic sql, but you'll have to specify them one way or another. |
6,949,864 | My code:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid --get data, put into a temp table
ALTER TABLE #t
DROP COLUMN CID -- remove primary key column CID
INSERT INTO CTABLE SELECT * FROM #t -- insert record to table
DROP TABLE #t -- drop temp table
```
The error is:
```
Msg 8101,
An explicit value for the identity column in table 'CTABLE' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
```
And I did set
```
SET IDENTITY_INSERT CTABLE OFF
GO
``` | 2011/08/04 | [
"https://Stackoverflow.com/questions/6949864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807463/"
] | Here's an example to dynamically build a list of columns - excluding the primary key columns - and execute the INSERT
```
declare @tablename nvarchar(100), @column nvarchar(100), @cid int, @sql nvarchar(max)
set @tablename = N'ctable'
set @cid = 1
set @sql = N''
declare example cursor for
select column_name
from information_schema.columns
where table_name = @tablename
and column_name not in (
select column_name
from information_schema.key_column_usage
where constraint_name in (select constraint_name from information_schema.table_constraints)
and table_name = @tablename
)
open example
fetch next from example into @column
while @@fetch_status = 0
begin
set @sql = @sql + N'[' + @column + N'],'
fetch next from example into @column
end
set @sql = substring(@sql, 1, len(@sql)-1)
close example
deallocate example
set @sql = N'insert into ' + @tablename + '(' + @sql + N') select top(1) ' + @sql + ' from #t'
--select @sql
exec sp_executesql @sql
``` | You can't do this:
```
INSERT INTO CTABLE SELECT top(1) * FROM #t
```
Because the column listings aren't the same. You've dropped the PK column from #t, so you have 1 less column in #t than in CTABLE. This is the equivalent of the following:
```
INSERT INTO CTABLE(pk, col1, col2, col3, ...)
select top(1) col1, col2, col3, ...
from #t
```
This wouldn't work for obvious reasons. Similarly, you aren't going to be able to specify the \* wildcard to do the insert if you're not inserting all of the columns. The only way to do the insert without including the PK is to specify every column. You can generate a list of columns through dynamic sql, but you'll have to specify them one way or another. |
6,949,864 | My code:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid --get data, put into a temp table
ALTER TABLE #t
DROP COLUMN CID -- remove primary key column CID
INSERT INTO CTABLE SELECT * FROM #t -- insert record to table
DROP TABLE #t -- drop temp table
```
The error is:
```
Msg 8101,
An explicit value for the identity column in table 'CTABLE' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
```
And I did set
```
SET IDENTITY_INSERT CTABLE OFF
GO
``` | 2011/08/04 | [
"https://Stackoverflow.com/questions/6949864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807463/"
] | If using SQL Server Management Studio and your problems you have too many fields to type them all out except the identity column, then right click on the table and click "Script table as" / "Select To" / "New Query Window".
This will provide a list of fields that you can copy & paste into your own query and then just remove the identity column. | Try invoking the INSERT statement with EXEC:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid
ALTER TABLE #t
DROP COLUMN CID
EXEC('INSERT INTO CTABLE SELECT top(1) * FROM #t')
DROP TABLE #t
``` |
6,949,864 | My code:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid --get data, put into a temp table
ALTER TABLE #t
DROP COLUMN CID -- remove primary key column CID
INSERT INTO CTABLE SELECT * FROM #t -- insert record to table
DROP TABLE #t -- drop temp table
```
The error is:
```
Msg 8101,
An explicit value for the identity column in table 'CTABLE' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
```
And I did set
```
SET IDENTITY_INSERT CTABLE OFF
GO
``` | 2011/08/04 | [
"https://Stackoverflow.com/questions/6949864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807463/"
] | Try this:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid
ALTER TABLE #t
DROP COLUMN CID
INSERT CTABLE --Notice that INTO is removed here.
SELECT top(1) * FROM #t
DROP TABLE #t
```
Test Script(Tested in SQL 2005):
```
CREATE TABLE #TestIDNT
(
ID INT IDENTITY(1,1) PRIMARY KEY,
TITLE VARCHAR(20)
)
INSERT #TestIDNT
SELECT 'Cybenate'
``` | You can't do this:
```
INSERT INTO CTABLE SELECT top(1) * FROM #t
```
Because the column listings aren't the same. You've dropped the PK column from #t, so you have 1 less column in #t than in CTABLE. This is the equivalent of the following:
```
INSERT INTO CTABLE(pk, col1, col2, col3, ...)
select top(1) col1, col2, col3, ...
from #t
```
This wouldn't work for obvious reasons. Similarly, you aren't going to be able to specify the \* wildcard to do the insert if you're not inserting all of the columns. The only way to do the insert without including the PK is to specify every column. You can generate a list of columns through dynamic sql, but you'll have to specify them one way or another. |
6,949,864 | My code:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid --get data, put into a temp table
ALTER TABLE #t
DROP COLUMN CID -- remove primary key column CID
INSERT INTO CTABLE SELECT * FROM #t -- insert record to table
DROP TABLE #t -- drop temp table
```
The error is:
```
Msg 8101,
An explicit value for the identity column in table 'CTABLE' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
```
And I did set
```
SET IDENTITY_INSERT CTABLE OFF
GO
``` | 2011/08/04 | [
"https://Stackoverflow.com/questions/6949864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807463/"
] | Try this:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid
ALTER TABLE #t
DROP COLUMN CID
INSERT CTABLE --Notice that INTO is removed here.
SELECT top(1) * FROM #t
DROP TABLE #t
```
Test Script(Tested in SQL 2005):
```
CREATE TABLE #TestIDNT
(
ID INT IDENTITY(1,1) PRIMARY KEY,
TITLE VARCHAR(20)
)
INSERT #TestIDNT
SELECT 'Cybenate'
``` | Try invoking the INSERT statement with EXEC:
```
SELECT * INTO #t FROM CTABLE WHERE CID = @cid
ALTER TABLE #t
DROP COLUMN CID
EXEC('INSERT INTO CTABLE SELECT top(1) * FROM #t')
DROP TABLE #t
``` |
19,707,436 | I'm having trouble getting path substitution working correctly. I have a bunch of source files in `SOURCES`:
```
@echo $(SOURCES)
foo.c bar.cpp bah.cxx
```
And I want a list of object files:
```
# Imaginary only because nothing works
@echo $(OBJECTS)
foo.o bar.o bah.o
```
I'm trying to build the list of `OBJECTS` with `patsubst`. First, this produces a list of source files and object files. Besides being wrong, it causes a duplicate of `_main` which fails a link.
```
OBJECTS = $(patsubst %.c, %.o, ${SOURCES}) $(patsubst %.cc, %.o, ${SOURCES}) \
$(patsubst %.cpp, %.o, ${SOURCES}) $(patsubst %.cxx, %.o, ${SOURCES})
```
Second, this performs no substitutions. Not only is it wrong, I get back the original list in `SOURCES`.
```
OBJECTS = $(patsubst %.c %.cc %.cpp %.cxx, %.o, ${SOURCES})
```
Third, this produces the original list of source files:
```
OBJECTS = $(patsubst %.*, %.o, ${SOURCES})
```
I also tried using the following, which seems to multiply the files like rabbits:
```
OBJECTS = $(SOURCES:.c=.o) $(SOURCES:.cc=.o) \
$(SOURCES:.cpp=.o) $(SOURCES:.cxx=.o)
```
How does one perform a simple substitution of extensions when using a portable make? | 2013/10/31 | [
"https://Stackoverflow.com/questions/19707436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608639/"
] | Tom's answer is correct. Etan's will work too. A shorter solution would be:
```
$(addsuffix .o,$(basename $(SOURCES))
``` | If you have a filter-like function you can use that. Otherwise you can do it in stages:
```
SOURCES := foo.c bar.cpp bah.cxx
O := $(SOURCES)
$(info $(O))
O := $(patsubst %.c,%.o,$(O))
$(info $(O))
O := $(patsubst %.cpp,%.o,$(O))
$(info $(O))
O := $(patsubst %.cxx,%.o,$(O))
$(info $(O))
```
The problem with your first (and third since that is effectively identical) attempt is that patsubst leaves untouched any words in the input that do not match the pattern. So when you built OBJECTS up from multiple calls to patsubst you were duplicating (in each piece) all the SOURCSE entries that didn't match that pattern.
The problem with the second is that patsubst doesn't take multiple patterns so nothing matches that erroneous pattern and so you get SOURCES back entirely unmodified. |
19,707,436 | I'm having trouble getting path substitution working correctly. I have a bunch of source files in `SOURCES`:
```
@echo $(SOURCES)
foo.c bar.cpp bah.cxx
```
And I want a list of object files:
```
# Imaginary only because nothing works
@echo $(OBJECTS)
foo.o bar.o bah.o
```
I'm trying to build the list of `OBJECTS` with `patsubst`. First, this produces a list of source files and object files. Besides being wrong, it causes a duplicate of `_main` which fails a link.
```
OBJECTS = $(patsubst %.c, %.o, ${SOURCES}) $(patsubst %.cc, %.o, ${SOURCES}) \
$(patsubst %.cpp, %.o, ${SOURCES}) $(patsubst %.cxx, %.o, ${SOURCES})
```
Second, this performs no substitutions. Not only is it wrong, I get back the original list in `SOURCES`.
```
OBJECTS = $(patsubst %.c %.cc %.cpp %.cxx, %.o, ${SOURCES})
```
Third, this produces the original list of source files:
```
OBJECTS = $(patsubst %.*, %.o, ${SOURCES})
```
I also tried using the following, which seems to multiply the files like rabbits:
```
OBJECTS = $(SOURCES:.c=.o) $(SOURCES:.cc=.o) \
$(SOURCES:.cpp=.o) $(SOURCES:.cxx=.o)
```
How does one perform a simple substitution of extensions when using a portable make? | 2013/10/31 | [
"https://Stackoverflow.com/questions/19707436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608639/"
] | Tom's answer is correct. Etan's will work too. A shorter solution would be:
```
$(addsuffix .o,$(basename $(SOURCES))
``` | First, I don't think patsubst is portable. It is a GNU make feature.
I think one answer to your question is nested subsitutions, like:
```
$(patsubst %c,%.o,$(patsubst %.cc,%.o,$(patsubst .....)))
``` |
32,925,134 | I have an array like the one below:
```
$products = array();
$products["Archery"] = array(
"name" => "Archery",
"img" => "img/wire/100-Archery.jpg",
"desc" => "Archer aiming to shoot",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Artist"] = array(
"name" => "Artist",
"img" => "img/wire/101-Artist.jpg",
"desc" => "Artist with palette & easel",
"prices" => array($price3,$price6),
"paypal" => $paypal5,
"sizes" => array($size1, $size2)
);
$products["Badminton"] = array(
"name" => "Badminton",
"img" => "img/wire/102-Badminton.jpg",
"desc" => "About to hit bird above head",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Stance"] = array(
"name" => "BASEBALL -Bat - Stance",
"img" => "img/wire/103a-Baseball-Stance.jpg",
"desc" => "Waiting for pitch",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Swing"] = array(
"name" => "BASEBALL - Bat - Swing",
"img" => "img/wire/103b-Baseball-Swing.jpg",
"desc" => "Just hit ball",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
```
I have a page that loads a single product from this array, and I'm trying to make "prev" and "next" buttons that will link to the adjacent products in the array. My PHP skills are rudimentary, and I've had no luck trying to accomplish this with the prev() and next() functions. What's the easiest way to find the adjacent elements in the array? (If I'm on the "Artist" page how would I link to, "Archery" and, "Badminton.") | 2015/10/03 | [
"https://Stackoverflow.com/questions/32925134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842381/"
] | array yp\_next ( string $domain , string $map , string $key )
Returns the next key-value pair in the named map after the specified key.
<http://php.net/manual/en/function.yp-next.php> | Sounds like what you need is javascript. It will be able to do the switch the products on the client side, so you can store the variable from a for loop and when the button is clicked, you can call a function to switch it to the next one |
32,925,134 | I have an array like the one below:
```
$products = array();
$products["Archery"] = array(
"name" => "Archery",
"img" => "img/wire/100-Archery.jpg",
"desc" => "Archer aiming to shoot",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Artist"] = array(
"name" => "Artist",
"img" => "img/wire/101-Artist.jpg",
"desc" => "Artist with palette & easel",
"prices" => array($price3,$price6),
"paypal" => $paypal5,
"sizes" => array($size1, $size2)
);
$products["Badminton"] = array(
"name" => "Badminton",
"img" => "img/wire/102-Badminton.jpg",
"desc" => "About to hit bird above head",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Stance"] = array(
"name" => "BASEBALL -Bat - Stance",
"img" => "img/wire/103a-Baseball-Stance.jpg",
"desc" => "Waiting for pitch",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Swing"] = array(
"name" => "BASEBALL - Bat - Swing",
"img" => "img/wire/103b-Baseball-Swing.jpg",
"desc" => "Just hit ball",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
```
I have a page that loads a single product from this array, and I'm trying to make "prev" and "next" buttons that will link to the adjacent products in the array. My PHP skills are rudimentary, and I've had no luck trying to accomplish this with the prev() and next() functions. What's the easiest way to find the adjacent elements in the array? (If I'm on the "Artist" page how would I link to, "Archery" and, "Badminton.") | 2015/10/03 | [
"https://Stackoverflow.com/questions/32925134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842381/"
] | array yp\_next ( string $domain , string $map , string $key )
Returns the next key-value pair in the named map after the specified key.
<http://php.net/manual/en/function.yp-next.php> | You cannot do next() and prev() on an associative array. What you need is another array structure, like this:
```
$products = array();
$products[0] = array(
"name" => "Archery",
"img" => "img/wire/100-Archery.jpg",
"desc" => "Archer aiming to shoot",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products[1] = array(
"name" => "Artist",
"img" => "img/wire/101-Artist.jpg",
"desc" => "Artist with palette & easel",
"prices" => array($price3,$price6),
"paypal" => $paypal5,
"sizes" => array($size1, $size2)
);
$products[2] = array(
"name" => "Badminton",
"img" => "img/wire/102-Badminton.jpg",
"desc" => "About to hit bird above head",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products[3] = array(
"name" => "BASEBALL -Bat - Stance",
"img" => "img/wire/103a-Baseball-Stance.jpg",
"desc" => "Waiting for pitch",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products[4] = array(
"name" => "BASEBALL - Bat - Swing",
"img" => "img/wire/103b-Baseball-Swing.jpg",
"desc" => "Just hit ball",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
```
You are still able to iterate through this structure and get the name of the current item from key "name". |
32,925,134 | I have an array like the one below:
```
$products = array();
$products["Archery"] = array(
"name" => "Archery",
"img" => "img/wire/100-Archery.jpg",
"desc" => "Archer aiming to shoot",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Artist"] = array(
"name" => "Artist",
"img" => "img/wire/101-Artist.jpg",
"desc" => "Artist with palette & easel",
"prices" => array($price3,$price6),
"paypal" => $paypal5,
"sizes" => array($size1, $size2)
);
$products["Badminton"] = array(
"name" => "Badminton",
"img" => "img/wire/102-Badminton.jpg",
"desc" => "About to hit bird above head",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Stance"] = array(
"name" => "BASEBALL -Bat - Stance",
"img" => "img/wire/103a-Baseball-Stance.jpg",
"desc" => "Waiting for pitch",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Swing"] = array(
"name" => "BASEBALL - Bat - Swing",
"img" => "img/wire/103b-Baseball-Swing.jpg",
"desc" => "Just hit ball",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
```
I have a page that loads a single product from this array, and I'm trying to make "prev" and "next" buttons that will link to the adjacent products in the array. My PHP skills are rudimentary, and I've had no luck trying to accomplish this with the prev() and next() functions. What's the easiest way to find the adjacent elements in the array? (If I'm on the "Artist" page how would I link to, "Archery" and, "Badminton.") | 2015/10/03 | [
"https://Stackoverflow.com/questions/32925134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842381/"
] | You could traverse the array to find the current key, and then go one element more. A tested example:
```
$current_page = 'Artist'; // as an example
$prev = $next = false; // the keys you're trying to find
$last = false; // store the value of the last iteration in case the next element matches
// flag if we've found the current element so that we can store the key on the next iteration
// we can't just use $last here because if the element is found on the first iteration it'll still be false
$found = false;
foreach ($products as $key => $value) {
// if we found the current key in the previous iteration
if ($found) {
$next = $key;
break; // no need to continue
}
// this is the current key
if ($key == $current_page) {
$found = true;
$prev = $last;
}
$last = $key; // store this iteration's key for possible use in the next iteration
}
```
At the end of this script, $prev and $next will either contain the key of the previous/next item or be false (if the current item is not found or we're at the very beginning/end of the array and no prev/next is available). | Sounds like what you need is javascript. It will be able to do the switch the products on the client side, so you can store the variable from a for loop and when the button is clicked, you can call a function to switch it to the next one |
32,925,134 | I have an array like the one below:
```
$products = array();
$products["Archery"] = array(
"name" => "Archery",
"img" => "img/wire/100-Archery.jpg",
"desc" => "Archer aiming to shoot",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Artist"] = array(
"name" => "Artist",
"img" => "img/wire/101-Artist.jpg",
"desc" => "Artist with palette & easel",
"prices" => array($price3,$price6),
"paypal" => $paypal5,
"sizes" => array($size1, $size2)
);
$products["Badminton"] = array(
"name" => "Badminton",
"img" => "img/wire/102-Badminton.jpg",
"desc" => "About to hit bird above head",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Stance"] = array(
"name" => "BASEBALL -Bat - Stance",
"img" => "img/wire/103a-Baseball-Stance.jpg",
"desc" => "Waiting for pitch",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Swing"] = array(
"name" => "BASEBALL - Bat - Swing",
"img" => "img/wire/103b-Baseball-Swing.jpg",
"desc" => "Just hit ball",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
```
I have a page that loads a single product from this array, and I'm trying to make "prev" and "next" buttons that will link to the adjacent products in the array. My PHP skills are rudimentary, and I've had no luck trying to accomplish this with the prev() and next() functions. What's the easiest way to find the adjacent elements in the array? (If I'm on the "Artist" page how would I link to, "Archery" and, "Badminton.") | 2015/10/03 | [
"https://Stackoverflow.com/questions/32925134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842381/"
] | Based on your array data you can use the following function. I used the array\_keys() function to make an array with only the keys of the initial array and all the work is done using the new array.
```
function custom_array_pagination($data = array()) {
$current_page = 'Baseball-Bat-Swing'; //$current_page = $_GET['product']; //Change to this when you have set up your final code
$data_keys = array_keys($data); //This is the array all the work is done
$s = '';
if (!in_array($current_page, $data_keys)) { //If there is no such element as the $_GET element in the array
return $s;
}
$is_first = false;
$is_last = false;
$found_prev = false;
$found_next = false;
$next_text = '';
if ($current_page == $data_keys[0]) {
$is_first = true;
}
if ($current_page == end($data_keys)) {
$is_last = true;
}
$s .= '<ul class="pagination">';
if ($is_first) { //If it is the first element then show only text
$s .= '<li class="first">First'.'</li>';
} else {
$s .= '<li class="first"><a href="'.$data_keys[0].'">First</a>'.'</li>';
}
foreach($data_keys as $key => $value) {
if ($is_first && !$found_prev) { //If it is the first element then show only text
$found_prev = true;
$s .= '<li class="prev">Prev'.'</li>';
} else {
if (!$found_prev) { //If prev has not been found yet
$prev = $data_keys[array_search($current_page, $data_keys) - 1];
$found_prev = true;
$s .= '<li class="prev"><a href="'.$prev.'">Prev</a>'.'</li>';
}
}
if ($current_page == $value) {
$s .= '<li class="current">'.$data[$value]['name'].'</li>';
} else {
$s .= '<li class="current"><a href="'.$value.'">'.$data[$value]['name'].'</a>'.'</li>';
}
if ($is_last && !$found_next) { //If it is the last element then show only text
$found_next = true;
$next_text = '<li class="next">Next'.'</li>';
} else {
if (!$found_next) { //If next has not been found yet
if ($value == $data_keys[count($data_keys) - 1]) { //If this value is the last value in the table
$found_next = true;
$next = $data_keys[array_search($current_page, $data_keys) + 1];
$next_text = '<li class="next"><a href="'.$next.'">Next</a>'.'</li>';
}
}
}
}
$s .= $next_text;
if ($is_last) { //If it is the last element then show only text
$s .= '<li class="last">Last</li>';
} else {
$s .= '<li class="last"><a href="'.$data_keys[count($data_keys) - 1].'">Last</a>'.'</li>';
}
return $s;
}
```
You can use the function like this:
```
echo custom_array_pagination($products);
``` | Sounds like what you need is javascript. It will be able to do the switch the products on the client side, so you can store the variable from a for loop and when the button is clicked, you can call a function to switch it to the next one |
32,925,134 | I have an array like the one below:
```
$products = array();
$products["Archery"] = array(
"name" => "Archery",
"img" => "img/wire/100-Archery.jpg",
"desc" => "Archer aiming to shoot",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Artist"] = array(
"name" => "Artist",
"img" => "img/wire/101-Artist.jpg",
"desc" => "Artist with palette & easel",
"prices" => array($price3,$price6),
"paypal" => $paypal5,
"sizes" => array($size1, $size2)
);
$products["Badminton"] = array(
"name" => "Badminton",
"img" => "img/wire/102-Badminton.jpg",
"desc" => "About to hit bird above head",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Stance"] = array(
"name" => "BASEBALL -Bat - Stance",
"img" => "img/wire/103a-Baseball-Stance.jpg",
"desc" => "Waiting for pitch",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Swing"] = array(
"name" => "BASEBALL - Bat - Swing",
"img" => "img/wire/103b-Baseball-Swing.jpg",
"desc" => "Just hit ball",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
```
I have a page that loads a single product from this array, and I'm trying to make "prev" and "next" buttons that will link to the adjacent products in the array. My PHP skills are rudimentary, and I've had no luck trying to accomplish this with the prev() and next() functions. What's the easiest way to find the adjacent elements in the array? (If I'm on the "Artist" page how would I link to, "Archery" and, "Badminton.") | 2015/10/03 | [
"https://Stackoverflow.com/questions/32925134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842381/"
] | You could traverse the array to find the current key, and then go one element more. A tested example:
```
$current_page = 'Artist'; // as an example
$prev = $next = false; // the keys you're trying to find
$last = false; // store the value of the last iteration in case the next element matches
// flag if we've found the current element so that we can store the key on the next iteration
// we can't just use $last here because if the element is found on the first iteration it'll still be false
$found = false;
foreach ($products as $key => $value) {
// if we found the current key in the previous iteration
if ($found) {
$next = $key;
break; // no need to continue
}
// this is the current key
if ($key == $current_page) {
$found = true;
$prev = $last;
}
$last = $key; // store this iteration's key for possible use in the next iteration
}
```
At the end of this script, $prev and $next will either contain the key of the previous/next item or be false (if the current item is not found or we're at the very beginning/end of the array and no prev/next is available). | You cannot do next() and prev() on an associative array. What you need is another array structure, like this:
```
$products = array();
$products[0] = array(
"name" => "Archery",
"img" => "img/wire/100-Archery.jpg",
"desc" => "Archer aiming to shoot",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products[1] = array(
"name" => "Artist",
"img" => "img/wire/101-Artist.jpg",
"desc" => "Artist with palette & easel",
"prices" => array($price3,$price6),
"paypal" => $paypal5,
"sizes" => array($size1, $size2)
);
$products[2] = array(
"name" => "Badminton",
"img" => "img/wire/102-Badminton.jpg",
"desc" => "About to hit bird above head",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products[3] = array(
"name" => "BASEBALL -Bat - Stance",
"img" => "img/wire/103a-Baseball-Stance.jpg",
"desc" => "Waiting for pitch",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products[4] = array(
"name" => "BASEBALL - Bat - Swing",
"img" => "img/wire/103b-Baseball-Swing.jpg",
"desc" => "Just hit ball",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
```
You are still able to iterate through this structure and get the name of the current item from key "name". |
32,925,134 | I have an array like the one below:
```
$products = array();
$products["Archery"] = array(
"name" => "Archery",
"img" => "img/wire/100-Archery.jpg",
"desc" => "Archer aiming to shoot",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Artist"] = array(
"name" => "Artist",
"img" => "img/wire/101-Artist.jpg",
"desc" => "Artist with palette & easel",
"prices" => array($price3,$price6),
"paypal" => $paypal5,
"sizes" => array($size1, $size2)
);
$products["Badminton"] = array(
"name" => "Badminton",
"img" => "img/wire/102-Badminton.jpg",
"desc" => "About to hit bird above head",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Stance"] = array(
"name" => "BASEBALL -Bat - Stance",
"img" => "img/wire/103a-Baseball-Stance.jpg",
"desc" => "Waiting for pitch",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Swing"] = array(
"name" => "BASEBALL - Bat - Swing",
"img" => "img/wire/103b-Baseball-Swing.jpg",
"desc" => "Just hit ball",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
```
I have a page that loads a single product from this array, and I'm trying to make "prev" and "next" buttons that will link to the adjacent products in the array. My PHP skills are rudimentary, and I've had no luck trying to accomplish this with the prev() and next() functions. What's the easiest way to find the adjacent elements in the array? (If I'm on the "Artist" page how would I link to, "Archery" and, "Badminton.") | 2015/10/03 | [
"https://Stackoverflow.com/questions/32925134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842381/"
] | Based on your array data you can use the following function. I used the array\_keys() function to make an array with only the keys of the initial array and all the work is done using the new array.
```
function custom_array_pagination($data = array()) {
$current_page = 'Baseball-Bat-Swing'; //$current_page = $_GET['product']; //Change to this when you have set up your final code
$data_keys = array_keys($data); //This is the array all the work is done
$s = '';
if (!in_array($current_page, $data_keys)) { //If there is no such element as the $_GET element in the array
return $s;
}
$is_first = false;
$is_last = false;
$found_prev = false;
$found_next = false;
$next_text = '';
if ($current_page == $data_keys[0]) {
$is_first = true;
}
if ($current_page == end($data_keys)) {
$is_last = true;
}
$s .= '<ul class="pagination">';
if ($is_first) { //If it is the first element then show only text
$s .= '<li class="first">First'.'</li>';
} else {
$s .= '<li class="first"><a href="'.$data_keys[0].'">First</a>'.'</li>';
}
foreach($data_keys as $key => $value) {
if ($is_first && !$found_prev) { //If it is the first element then show only text
$found_prev = true;
$s .= '<li class="prev">Prev'.'</li>';
} else {
if (!$found_prev) { //If prev has not been found yet
$prev = $data_keys[array_search($current_page, $data_keys) - 1];
$found_prev = true;
$s .= '<li class="prev"><a href="'.$prev.'">Prev</a>'.'</li>';
}
}
if ($current_page == $value) {
$s .= '<li class="current">'.$data[$value]['name'].'</li>';
} else {
$s .= '<li class="current"><a href="'.$value.'">'.$data[$value]['name'].'</a>'.'</li>';
}
if ($is_last && !$found_next) { //If it is the last element then show only text
$found_next = true;
$next_text = '<li class="next">Next'.'</li>';
} else {
if (!$found_next) { //If next has not been found yet
if ($value == $data_keys[count($data_keys) - 1]) { //If this value is the last value in the table
$found_next = true;
$next = $data_keys[array_search($current_page, $data_keys) + 1];
$next_text = '<li class="next"><a href="'.$next.'">Next</a>'.'</li>';
}
}
}
}
$s .= $next_text;
if ($is_last) { //If it is the last element then show only text
$s .= '<li class="last">Last</li>';
} else {
$s .= '<li class="last"><a href="'.$data_keys[count($data_keys) - 1].'">Last</a>'.'</li>';
}
return $s;
}
```
You can use the function like this:
```
echo custom_array_pagination($products);
``` | You cannot do next() and prev() on an associative array. What you need is another array structure, like this:
```
$products = array();
$products[0] = array(
"name" => "Archery",
"img" => "img/wire/100-Archery.jpg",
"desc" => "Archer aiming to shoot",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products[1] = array(
"name" => "Artist",
"img" => "img/wire/101-Artist.jpg",
"desc" => "Artist with palette & easel",
"prices" => array($price3,$price6),
"paypal" => $paypal5,
"sizes" => array($size1, $size2)
);
$products[2] = array(
"name" => "Badminton",
"img" => "img/wire/102-Badminton.jpg",
"desc" => "About to hit bird above head",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products[3] = array(
"name" => "BASEBALL -Bat - Stance",
"img" => "img/wire/103a-Baseball-Stance.jpg",
"desc" => "Waiting for pitch",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
$products[4] = array(
"name" => "BASEBALL - Bat - Swing",
"img" => "img/wire/103b-Baseball-Swing.jpg",
"desc" => "Just hit ball",
"prices" => array($price1,$price3),
"paypal" => $paypal2,
"sizes" => array($size1, $size2)
);
```
You are still able to iterate through this structure and get the name of the current item from key "name". |
160,542 | In a U-shaped tube, water and oil are separated by a movable membrane. What is the ratio of the heights $\frac{h1}{h2}$ (density of the oil $ρ\_{oil}$ = 0.92 $\frac{g}{cm^3}$)?

I tried solving by saying that the pressure at the membrane should be the same so
$$P\_{H\_2O} = P\_{oil}$$
$$=> P\_0 + \rho\_{H\_2O} \cdot g \cdot h\_1 = P\_0 + \rho\_{oil} \cdot g \cdot h\_2$$
where $P\_0$ is the atmospheric pressure.
then i got
$$\frac{h\_1}{h\_2} = \frac{\rho\_1}{\rho\_2} = 0.92$$
But my friend argues that the Net force on the membrane should be equal and he got the answer like following,
$$A\_1 \cdot P\_1 = A\_2 \cdot P\_2$$
After substituting the formula and values he got,
$$=> \frac{h\_1}{h\_2} = 0.92 \frac{D^2}{d^2}$$
So all i want to ask is, which method is correct??
Thanks. | 2015/01/20 | [
"https://physics.stackexchange.com/questions/160542",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/65843/"
] | Your friend is correct in that the net force on the membrane should be zero. And the force from each side of the membrane is the pressure times the area.
The area of the membrane is the same on each side. It is not the case that one side of the membrane is of size $D$ and the other side is of size $d$. So his formula is incorrect. | $P\_1 =\gamma\_{water} \cdot h\_1$
$P\_2= \gamma\_{oil} \cdot h\_2$
$\gamma\_{water} \cdot h\_1 \cdot A = \gamma\_{oil} \cdot h\_2 \cdot A$
$\gamma\_{water} \cdot h\_1 = \gamma\_{oil} \cdot h\_2 $
$\frac{\gamma\_{water} \cdot h\_1} {\gamma\_{oil} \cdot h\_2} = 1$
$\frac{h\_1} {h\_2} = \frac{\gamma\_{oil}} {\gamma\_{water}} = 0.92$
Sorry to say your friend is incorrect because the diameter of concern would be at the interface. There is only one diameter there. |
13,526,280 | I have a function in my object.
I want to access this function's variable from another function.Can anyone help me?
Here is my sample code.
Any help would be greatly appreciated. Thanks.
```
var drops= {
hoverClass: "hoverme",
greedy: true,
accept: "#mini",
drop: function(event,ui){
var droppedOn2 = $(this);
var dropped2 = $(ui.draggable);
alert(droppedOn2.attr('id')); alert(dropped2.attr('id'));
$(dropped2).appendTo(droppedOn2).draggable();
},
over: function(event, ui){
console.log("buraya geliyorum > " + this.id);
}
};
$('#hebelek').sortable({
connectWith: '#hebelek',
cursor: 'pointer'
}).droppable({
accept: '#gridIcon1-2, #gridIcon2-2, #widgetIcon',
activeClass: 'highlight',
drop: function(event, ui) {
var ilk = drops.droppedOn2;
var droppedOn = $(this);
var dropped = $(ui.draggable).clone();
var fileName = dropped.attr('id');
alert(droppedOn.attr('id')); alert(fileName);
if (fileName == "gridIcon1-2"){
$(grid1_2Div).appendTo(droppedOn).find('.gridcell').droppable(drops)
};
if (fileName == "gridIcon2-2") {
$(grid2_2Div).appendTo(droppedOn).find('.gridcell').droppable(drops)
};
if ((fileName == "widgetIcon") && (droppedOn.attr('id') == "hebelek")) {
$(widgetDiv).appendTo("I WANT TO USE DROOPEDON2 ON HERE")
};
}
});
``` | 2012/11/23 | [
"https://Stackoverflow.com/questions/13526280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755495/"
] | Create a common scope for both functions (function wrapper will do), and create a variable in the same scope, like so:
```
(function () {
var x = 5,
f1 = function(){
console.log(x);
},
f2 = function(){
console.log(x);
};
})();
``` | You cannot. Variables are scoped to the function in which they are declared. If you want to access a variable from two different functions you can declare it outside of both functions and access it from within them. For example:
```
var sharedVariable = 'something';
function a() {
sharedVariable = 'a';
}
function b() {
alert(sharedVariable);
}
``` |
13,526,280 | I have a function in my object.
I want to access this function's variable from another function.Can anyone help me?
Here is my sample code.
Any help would be greatly appreciated. Thanks.
```
var drops= {
hoverClass: "hoverme",
greedy: true,
accept: "#mini",
drop: function(event,ui){
var droppedOn2 = $(this);
var dropped2 = $(ui.draggable);
alert(droppedOn2.attr('id')); alert(dropped2.attr('id'));
$(dropped2).appendTo(droppedOn2).draggable();
},
over: function(event, ui){
console.log("buraya geliyorum > " + this.id);
}
};
$('#hebelek').sortable({
connectWith: '#hebelek',
cursor: 'pointer'
}).droppable({
accept: '#gridIcon1-2, #gridIcon2-2, #widgetIcon',
activeClass: 'highlight',
drop: function(event, ui) {
var ilk = drops.droppedOn2;
var droppedOn = $(this);
var dropped = $(ui.draggable).clone();
var fileName = dropped.attr('id');
alert(droppedOn.attr('id')); alert(fileName);
if (fileName == "gridIcon1-2"){
$(grid1_2Div).appendTo(droppedOn).find('.gridcell').droppable(drops)
};
if (fileName == "gridIcon2-2") {
$(grid2_2Div).appendTo(droppedOn).find('.gridcell').droppable(drops)
};
if ((fileName == "widgetIcon") && (droppedOn.attr('id') == "hebelek")) {
$(widgetDiv).appendTo("I WANT TO USE DROOPEDON2 ON HERE")
};
}
});
``` | 2012/11/23 | [
"https://Stackoverflow.com/questions/13526280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755495/"
] | Create a common scope for both functions (function wrapper will do), and create a variable in the same scope, like so:
```
(function () {
var x = 5,
f1 = function(){
console.log(x);
},
f2 = function(){
console.log(x);
};
})();
``` | To make a variable calculated in function A visible in function B, you have three choices:
1. make it a global,
2. make it an object property, or
3. pass it as a parameter when calling B from A.
```
function A()
{
var rand_num = calculate_random_number();
B(rand_num);
}
function B(r)
{
use_rand_num(r);
}
``` |
17,105,624 | I was wondering if it is possible to change CSS with a link. What I'm trying to do is I want to change the `display:none` so it shows the page and hides another so it looks like your going to another page but it's already been loaded. Is it possible?
If it's possible with JavaScript or jQuery, how do I put it in HTML? Can OnClick change display:none to display:block? | 2013/06/14 | [
"https://Stackoverflow.com/questions/17105624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2485292/"
] | You could use `:target` pseudo-class I think.
You could something like this:
```
<a href="#books">Show books</a>
<a href="#tv">Show TV</a>
<section id="books"></section>
<section id="tv"></section>
```
And CSS:
```
section {
display: none;
}
*:target {
display: block;
}
```
There are a few good examples on <https://developer.mozilla.org/en-US/docs/Web/CSS/:target>
But I think, is most cases, using **JavaScript** would be a better solution.
**Edit**: added universal selector like [Alexxus](https://stackoverflow.com/users/1574088/alexxus) suggested. | If you can use jQuery then you could do a very simple click event like below...
`<a id="some_link" href="#">click here</a>`
```
$('#some_link').click(function(event){
event.preventDefault();
$('#page_two').show();
$('#page_one').hide();
});
```
The prevent default is there to stop the link reloading the page. |
17,105,624 | I was wondering if it is possible to change CSS with a link. What I'm trying to do is I want to change the `display:none` so it shows the page and hides another so it looks like your going to another page but it's already been loaded. Is it possible?
If it's possible with JavaScript or jQuery, how do I put it in HTML? Can OnClick change display:none to display:block? | 2013/06/14 | [
"https://Stackoverflow.com/questions/17105624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2485292/"
] | You could use `:target` pseudo-class I think.
You could something like this:
```
<a href="#books">Show books</a>
<a href="#tv">Show TV</a>
<section id="books"></section>
<section id="tv"></section>
```
And CSS:
```
section {
display: none;
}
*:target {
display: block;
}
```
There are a few good examples on <https://developer.mozilla.org/en-US/docs/Web/CSS/:target>
But I think, is most cases, using **JavaScript** would be a better solution.
**Edit**: added universal selector like [Alexxus](https://stackoverflow.com/users/1574088/alexxus) suggested. | You can easily change visibility with jQuery. To hide an element you can use [`hide()`](http://api.jquery.com/hide/). To make an element visible you can use [`show()`](http://api.jquery.com/show/).
Or you can use [`toggle()`](http://api.jquery.com/toggle/) which simply toggles the visibility.
If you have to change more than the visibility of an element, you can use the jQuery [`css()`](http://api.jquery.com/css/) function.
Or you can use [`addClass()`](http://api.jquery.com/addclass/) and [`removeClass()`](http://api.jquery.com/removeclass/) to add or remove the css classes of an element. |
17,105,624 | I was wondering if it is possible to change CSS with a link. What I'm trying to do is I want to change the `display:none` so it shows the page and hides another so it looks like your going to another page but it's already been loaded. Is it possible?
If it's possible with JavaScript or jQuery, how do I put it in HTML? Can OnClick change display:none to display:block? | 2013/06/14 | [
"https://Stackoverflow.com/questions/17105624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2485292/"
] | You could use `:target` pseudo-class I think.
You could something like this:
```
<a href="#books">Show books</a>
<a href="#tv">Show TV</a>
<section id="books"></section>
<section id="tv"></section>
```
And CSS:
```
section {
display: none;
}
*:target {
display: block;
}
```
There are a few good examples on <https://developer.mozilla.org/en-US/docs/Web/CSS/:target>
But I think, is most cases, using **JavaScript** would be a better solution.
**Edit**: added universal selector like [Alexxus](https://stackoverflow.com/users/1574088/alexxus) suggested. | In fact, despite the comments saying otherwise, there *are* ways of doing what you want in pure CSS.
The best trick relies on having hidden radio buttons, and having the label for the radio button as the button that the user clicks. This could be styled as a button or a tab, or however else you want to present it.
In your CSS, you then use the `:checked` selector to toggle the visibility, etc.
There are a few other techniques as well, but that's probably the best for most cases.
[Here's a site that demonstrates it in action and explains it in more detail](http://www.mdawson.net/csstips/purecsstabs.php).
The only caveat I would raise is possible compatibility issues with older browsers. If you need to support browsers as old as IE7, then it's a near certainty that you won't be able to use any pure CSS technique, and will have to rely on javascript.
That's not to say the javascript solutions are a bad thing -- you may find that they're exactly what you want, especially if you want to do additional stuff like actually loading the content when the buttons are clicked, rather than just toggling visibility. CSS alone definitely won't do that.
Hope that helps. |
17,105,624 | I was wondering if it is possible to change CSS with a link. What I'm trying to do is I want to change the `display:none` so it shows the page and hides another so it looks like your going to another page but it's already been loaded. Is it possible?
If it's possible with JavaScript or jQuery, how do I put it in HTML? Can OnClick change display:none to display:block? | 2013/06/14 | [
"https://Stackoverflow.com/questions/17105624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2485292/"
] | If you can use jQuery then you could do a very simple click event like below...
`<a id="some_link" href="#">click here</a>`
```
$('#some_link').click(function(event){
event.preventDefault();
$('#page_two').show();
$('#page_one').hide();
});
```
The prevent default is there to stop the link reloading the page. | You can easily change visibility with jQuery. To hide an element you can use [`hide()`](http://api.jquery.com/hide/). To make an element visible you can use [`show()`](http://api.jquery.com/show/).
Or you can use [`toggle()`](http://api.jquery.com/toggle/) which simply toggles the visibility.
If you have to change more than the visibility of an element, you can use the jQuery [`css()`](http://api.jquery.com/css/) function.
Or you can use [`addClass()`](http://api.jquery.com/addclass/) and [`removeClass()`](http://api.jquery.com/removeclass/) to add or remove the css classes of an element. |
17,105,624 | I was wondering if it is possible to change CSS with a link. What I'm trying to do is I want to change the `display:none` so it shows the page and hides another so it looks like your going to another page but it's already been loaded. Is it possible?
If it's possible with JavaScript or jQuery, how do I put it in HTML? Can OnClick change display:none to display:block? | 2013/06/14 | [
"https://Stackoverflow.com/questions/17105624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2485292/"
] | If you can use jQuery then you could do a very simple click event like below...
`<a id="some_link" href="#">click here</a>`
```
$('#some_link').click(function(event){
event.preventDefault();
$('#page_two').show();
$('#page_one').hide();
});
```
The prevent default is there to stop the link reloading the page. | In fact, despite the comments saying otherwise, there *are* ways of doing what you want in pure CSS.
The best trick relies on having hidden radio buttons, and having the label for the radio button as the button that the user clicks. This could be styled as a button or a tab, or however else you want to present it.
In your CSS, you then use the `:checked` selector to toggle the visibility, etc.
There are a few other techniques as well, but that's probably the best for most cases.
[Here's a site that demonstrates it in action and explains it in more detail](http://www.mdawson.net/csstips/purecsstabs.php).
The only caveat I would raise is possible compatibility issues with older browsers. If you need to support browsers as old as IE7, then it's a near certainty that you won't be able to use any pure CSS technique, and will have to rely on javascript.
That's not to say the javascript solutions are a bad thing -- you may find that they're exactly what you want, especially if you want to do additional stuff like actually loading the content when the buttons are clicked, rather than just toggling visibility. CSS alone definitely won't do that.
Hope that helps. |
17,105,624 | I was wondering if it is possible to change CSS with a link. What I'm trying to do is I want to change the `display:none` so it shows the page and hides another so it looks like your going to another page but it's already been loaded. Is it possible?
If it's possible with JavaScript or jQuery, how do I put it in HTML? Can OnClick change display:none to display:block? | 2013/06/14 | [
"https://Stackoverflow.com/questions/17105624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2485292/"
] | You can easily change visibility with jQuery. To hide an element you can use [`hide()`](http://api.jquery.com/hide/). To make an element visible you can use [`show()`](http://api.jquery.com/show/).
Or you can use [`toggle()`](http://api.jquery.com/toggle/) which simply toggles the visibility.
If you have to change more than the visibility of an element, you can use the jQuery [`css()`](http://api.jquery.com/css/) function.
Or you can use [`addClass()`](http://api.jquery.com/addclass/) and [`removeClass()`](http://api.jquery.com/removeclass/) to add or remove the css classes of an element. | In fact, despite the comments saying otherwise, there *are* ways of doing what you want in pure CSS.
The best trick relies on having hidden radio buttons, and having the label for the radio button as the button that the user clicks. This could be styled as a button or a tab, or however else you want to present it.
In your CSS, you then use the `:checked` selector to toggle the visibility, etc.
There are a few other techniques as well, but that's probably the best for most cases.
[Here's a site that demonstrates it in action and explains it in more detail](http://www.mdawson.net/csstips/purecsstabs.php).
The only caveat I would raise is possible compatibility issues with older browsers. If you need to support browsers as old as IE7, then it's a near certainty that you won't be able to use any pure CSS technique, and will have to rely on javascript.
That's not to say the javascript solutions are a bad thing -- you may find that they're exactly what you want, especially if you want to do additional stuff like actually loading the content when the buttons are clicked, rather than just toggling visibility. CSS alone definitely won't do that.
Hope that helps. |
72,447,284 | I'm trying to write some python to listen to signals.
Using dbus-monitor, as shown below, I can filter the signals I want.
```
dbus-monitor "type='signal',sender='org.kde.KWin',path='/ColorCorrect',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged'"
signal time=1653997355.732016 sender=:1.4 -> destination=(null destination) serial=13165 path=/ColorCorrect; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
string "org.kde.kwin.ColorCorrect"
array [
dict entry(
string "enabled"
variant boolean false
)
]
array [
]
```
But when I try the same thing with python, see below, nothing gets printed.
```
import dbus
from gi.repository import GLib
from dbus.mainloop.glib import DBusGMainLoop
def signal_handler(*args, **kwargs):
for i, arg in enumerate(args):
print("arg:%d %s" % (i, str(arg)))
print('kwargs:')
print(kwargs)
print('---end----')
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
# register your signal callback
bus.add_signal_receiver(signal_handler,
bus_name='org.kde.KWin',
interface_keyword='org.freedesktop.DBus.Properties',
member_keyword='PropertiesChanged',
path_keyword='/ColorCorrect'
# message_keyword='msg')
)
loop = GLib.MainLoop()
loop.run()
``` | 2022/05/31 | [
"https://Stackoverflow.com/questions/72447284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18704408/"
] | Try this
In your student model
```
public function state()
{
return $this->belongsTo(State::class, 'state_id');
}
```
now you can fetch student details with the state
```
public function show($id)
{
$student = Student::with('state')->find($id);
//for access the state name
//$student->state->state_name
}
``` | Maybe this helps you:
Students.php
```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Student extends Model
{
use HasFactory;
protected $fillable = ["id", "name", "state_id"];
public function state()
{
return $this->belongsTo(User::class, 'user_id');
}
}
```
StudentController.php
```
public function show($id)
{
$student = Student::where('id', $id)->with('state')->get();
}
``` |
72,447,284 | I'm trying to write some python to listen to signals.
Using dbus-monitor, as shown below, I can filter the signals I want.
```
dbus-monitor "type='signal',sender='org.kde.KWin',path='/ColorCorrect',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged'"
signal time=1653997355.732016 sender=:1.4 -> destination=(null destination) serial=13165 path=/ColorCorrect; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
string "org.kde.kwin.ColorCorrect"
array [
dict entry(
string "enabled"
variant boolean false
)
]
array [
]
```
But when I try the same thing with python, see below, nothing gets printed.
```
import dbus
from gi.repository import GLib
from dbus.mainloop.glib import DBusGMainLoop
def signal_handler(*args, **kwargs):
for i, arg in enumerate(args):
print("arg:%d %s" % (i, str(arg)))
print('kwargs:')
print(kwargs)
print('---end----')
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
# register your signal callback
bus.add_signal_receiver(signal_handler,
bus_name='org.kde.KWin',
interface_keyword='org.freedesktop.DBus.Properties',
member_keyword='PropertiesChanged',
path_keyword='/ColorCorrect'
# message_keyword='msg')
)
loop = GLib.MainLoop()
loop.run()
``` | 2022/05/31 | [
"https://Stackoverflow.com/questions/72447284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18704408/"
] | Student Modal
```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
public function state()
{
return $this->belongsTo( State::class );
}
}
```
Get Students With State
```
$students = Student::query()->with( 'state' )->get()
```
Search Students By State Name
```
$state = 'Dhaka';
$students = Student::query()->whereHas( 'state', function ( $query ) use ( $state ) {
$query->where( 'state_name', 'like', "%{$state}%" );
} )->paginate( 10 );
``` | Maybe this helps you:
Students.php
```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Student extends Model
{
use HasFactory;
protected $fillable = ["id", "name", "state_id"];
public function state()
{
return $this->belongsTo(User::class, 'user_id');
}
}
```
StudentController.php
```
public function show($id)
{
$student = Student::where('id', $id)->with('state')->get();
}
``` |
72,447,284 | I'm trying to write some python to listen to signals.
Using dbus-monitor, as shown below, I can filter the signals I want.
```
dbus-monitor "type='signal',sender='org.kde.KWin',path='/ColorCorrect',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged'"
signal time=1653997355.732016 sender=:1.4 -> destination=(null destination) serial=13165 path=/ColorCorrect; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
string "org.kde.kwin.ColorCorrect"
array [
dict entry(
string "enabled"
variant boolean false
)
]
array [
]
```
But when I try the same thing with python, see below, nothing gets printed.
```
import dbus
from gi.repository import GLib
from dbus.mainloop.glib import DBusGMainLoop
def signal_handler(*args, **kwargs):
for i, arg in enumerate(args):
print("arg:%d %s" % (i, str(arg)))
print('kwargs:')
print(kwargs)
print('---end----')
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
# register your signal callback
bus.add_signal_receiver(signal_handler,
bus_name='org.kde.KWin',
interface_keyword='org.freedesktop.DBus.Properties',
member_keyword='PropertiesChanged',
path_keyword='/ColorCorrect'
# message_keyword='msg')
)
loop = GLib.MainLoop()
loop.run()
``` | 2022/05/31 | [
"https://Stackoverflow.com/questions/72447284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18704408/"
] | Student Modal
```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
public function state()
{
return $this->belongsTo( State::class );
}
}
```
Get Students With State
```
$students = Student::query()->with( 'state' )->get()
```
Search Students By State Name
```
$state = 'Dhaka';
$students = Student::query()->whereHas( 'state', function ( $query ) use ( $state ) {
$query->where( 'state_name', 'like', "%{$state}%" );
} )->paginate( 10 );
``` | Try this
In your student model
```
public function state()
{
return $this->belongsTo(State::class, 'state_id');
}
```
now you can fetch student details with the state
```
public function show($id)
{
$student = Student::with('state')->find($id);
//for access the state name
//$student->state->state_name
}
``` |
1,812,249 | Are there any storage optimized [Sparse Matrix](http://en.wikipedia.org/wiki/Sparse_matrix) implementations in C#? | 2009/11/28 | [
"https://Stackoverflow.com/questions/1812249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147141/"
] | There is [Math.NET](http://www.mathdotnet.com/).
It has some Spare Matrix [implementations](http://nmath.sourceforge.net/doc/numerics/MathNet.Numerics.LinearAlgebra.Sparse.html). (link is to the old Math.NET site. There is no longer an online version of the documentation). | If you are looking for high performance sparse matrix implementation check out [NMath](http://www.centerspace.net) from CenterSpace software.
Here's a partial list of functionality cut from [here](http://www.centerspace.net/products/nmath/) on CenterSpace's website.
* Full-featured structured sparse
matrix classes, including triangular,
symmetric, Hermitian, banded,
tridiagonal, symmetric banded, and
Hermitian banded.
* Functions for
converting between general matrices
and structured sparse matrix types.
* Functions for transposing structured
sparse matrices, computing inner
products, and calculating matrix
norms.
* Classes for factoring
structured sparse matrices, including
LU factorization for banded and
tridiagonal matrices, Bunch-Kaufman
factorization for symmetric and
Hermitian matrices, and Cholesky
decomposition for symmetric and
Hermitian positive definite matrices.
Once constructed, matrix
factorizations can be used to solve
linear systems and compute
determinants, inverses, and condition
numbers.
* General sparse vector and
matrix classes, and matrix
factorizations.
* Orthogonal
decomposition classes for general
matrices, including QR decomposition
and singular value decomposition
(SVD).
* Advanced least squares
factorization classes for general
matrices, including Cholesky, QR, and
SVD.
* LU factorization for general
matrices, as well as functions for
solving linear systems, computing
determinants, inverses, and condition
numbers.
Paul |
14,977,613 | Using python boto, how can I modify Http Headers?
In my S3 bucket I have a file with name "shop" and since I upload it without file extension, I have to manually set the Http Header: ContentType = text/html
I want to use a python script using boto to set this header for all files that require this. However I cannot find **a method that changes the headers**. | 2013/02/20 | [
"https://Stackoverflow.com/questions/14977613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/857848/"
] | ```
import boto
from boto.s3.connection import S3Connection
from boto.s3.key import Key
ak = " ... key"
sk = " ... key"
bucketname = " ... "
c = S3Connection(ak, sk)
def setcontenttype():
c = S3Connection(ak, sk)
bucket = c.get_bucket(bucketname)
keys = bucket.get_all_keys()
for key in keys:
ext = os.path.splitext(key.name)[1]
if ext == "" and not key.name.endswith("/"):
print key.name
k.set_contents_from_string(k.get_contents_as_string(), {"Content-Type":"text/html"}, True)
``` | ```
s3_conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = s3_conn.get_bucket(s3_bucket_name)
keys = bucket.list()
for key in keys:
key = bucket.get_key(key.name)
metadata = key.metadata
metadata['Content-Type'] = "text/html"
key.copy(s3_bucket_name, key, metadata=metadata, preserve_acl=True)
```
you have to know that it will replace older metadata, so you should copy all other meta headers (like cache-control....) |
56,642,468 | I'm using `Reactive Forms` and I want to convert the value of `formGroup` into Model class object. Please give me some solutions for it. and also I want to send only `password` fields not `confirmPasword`. I also mentioned my model class .
Service.ts
```
objRegisterModel: RegisterModel = new RegisterModel();
constructor(private fb: FormBuilder, private http: HttpClient) {}
formModel = this.fb.group({
FirstName: ['', Validators.required],
LastName: ['', Validators.required],
Emails: this.fb.group({
EmailID: ['', [Validators.required, Validators.email]],
ConfirmEmail: ['', Validators.required]
}, { validator: this.compareEmails }),
OrgName: ['', Validators.required],
OrganizationType: ['', Validators.required],
City: ['', Validators.required],
PhoneNo: ['', Validators.required],
PostalAddress: ['', Validators.required],
Passwords: this.fb.group({
Pwd: ['', Validators.required],
ConfirmPassword: ['', [Validators.required]]
}, { validator: this.comparePasswords })
});
```
Model Class
```
export class RegisterModel {
Active: number;
Address: string;
Amt: number;
CityID: number;
Country: string;
EmailID: string;
FullName: string;
ID: number;
PhoneNo: string;
PostalAddress: string;
Pwd: string;
constructor(init?: Partial<RegisterModel>) {
Object.assign(this,init);
}
}
``` | 2019/06/18 | [
"https://Stackoverflow.com/questions/56642468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8923126/"
] | As simple as this:
```
objRegisterModel: RegisterModel = this.formModel.value
```
**vote up** the answers that helped you the most! If these answers were helpful to you | First and foremost, instead of using a Class for defining `RegisterModel`, I would recommend you to use an Interface instead.
```
export interface RegisterModel {
Active: number;
Address: string;
Amt: number;
CityID: number;
Country: string;
EmailID: string;
FullName: string;
ID: number;
PhoneNo: string;
PostalAddress: string;
Pwd: string;
}
```
On your component/service that requires the above interface, we first initialise the `objRegisterModel` property.
```
objRegisterModel: RegisterModel = {} as RegisterModel;
```
To get the values of your Reactive Form `FormGroup`, you can simply do this:
```
this.formModel.value
```
If you want to get only the password, and I assuming you are referring to the `Pwd` property,
```
this.formModel.Passwords.Pwd
``` |
56,642,468 | I'm using `Reactive Forms` and I want to convert the value of `formGroup` into Model class object. Please give me some solutions for it. and also I want to send only `password` fields not `confirmPasword`. I also mentioned my model class .
Service.ts
```
objRegisterModel: RegisterModel = new RegisterModel();
constructor(private fb: FormBuilder, private http: HttpClient) {}
formModel = this.fb.group({
FirstName: ['', Validators.required],
LastName: ['', Validators.required],
Emails: this.fb.group({
EmailID: ['', [Validators.required, Validators.email]],
ConfirmEmail: ['', Validators.required]
}, { validator: this.compareEmails }),
OrgName: ['', Validators.required],
OrganizationType: ['', Validators.required],
City: ['', Validators.required],
PhoneNo: ['', Validators.required],
PostalAddress: ['', Validators.required],
Passwords: this.fb.group({
Pwd: ['', Validators.required],
ConfirmPassword: ['', [Validators.required]]
}, { validator: this.comparePasswords })
});
```
Model Class
```
export class RegisterModel {
Active: number;
Address: string;
Amt: number;
CityID: number;
Country: string;
EmailID: string;
FullName: string;
ID: number;
PhoneNo: string;
PostalAddress: string;
Pwd: string;
constructor(init?: Partial<RegisterModel>) {
Object.assign(this,init);
}
}
``` | 2019/06/18 | [
"https://Stackoverflow.com/questions/56642468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8923126/"
] | As simple as this:
```
objRegisterModel: RegisterModel = this.formModel.value
```
**vote up** the answers that helped you the most! If these answers were helpful to you | Well, your model class don't have all the fields as in form.
I consider it as your mistake, you should add all fields in the model then make and use some mapping function like
```
mapping(group: FormGroup){
Object.keys(group.control).forEach(key =>{
const abstractControl = group.get(key);
if(abstractControl && abstractControl instanceof FormGroup){
//call recursively
mapping(abstractControl);
}
else{
if(key !== 'ConfirmPassword')
this.objRegisterModel[key] = abstractControl.value;
}
}//end of forEach
}//end of func
```
Now you just need to call this function passing object of FormGroup.
Hope it helps you |
15,899 | I am often the driver for friends and family whenever we travel, whether short or long distances. This is mostly due to the fact that I have the best track record, reflexes, judgement, etc. on the road and am generally happy to do it. I am not against passengers making/answering phone calls while I am driving, but I do not like it when they have extended conversations while I am driving. It is annoying to me because I have to turn off the radio, halt my conversations with other passengers, and listen to one side of a conversation, which is frustratingly boring - especially if it goes on for more than 30 minutes.
In the US at least, the etiquette for behavior when other people are on the phone nearby is to be quiet and let them converse without interruption. It's also common etiquette to step out of a room if you have to talk on the phone, but that is not possible in the car for obvious reasons. Correct me if I'm wrong, but I don't believe there is any kind of well known rule for taking phone calls in the car.
Whenever I am in a situation like this, I feel stuck. I have tried asking them to please wrap up the conversation, but I feel petty for doing so and am usually met with a confused look. I've also tried asking them to keep it short before the answer the phone, but either they get wrapped up in their conversation and ignore me, or they act like I'm kind of unreasonable tyrant and say on the phone, "Sorry, *BlackThorn* doesn't want me to talk on the phone, so he is making me keep this short."
As the driver, I have nothing else to do in these situations, so I feel like it is reasonable to expect that phone conversations are kept short. Other passengers have the option of playing on their phones, reading a book, looking out the window (at the sights, not the road), but I am held hostage to half of the conversation whenever someone is on the phone. **How can I get my passengers to see things my way, and keep their phone calls short?**
To clarify, this behavior is *both* rude and distracting. Listening to half a conversation, as @DaveG pointed out, is distracting because your brain tries to fill in the other half of the conversation. It is also annoying, which leads to more distracted driving as I start to focus on how much I wish the passenger would hang up the phone. I'm happy to converse with them to pass the time, listen to them converse with each other, listen to the radio, or drive in silence. | 2018/06/26 | [
"https://interpersonal.stackexchange.com/questions/15899",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/5253/"
] | "How can I get my passengers to see things my way, and keep their phone calls short?"
Since you've already asked them to keep it short, after the call goes on for five minutes, carefully exit the highway and pull over the car. Then just wait quietly for them to finish, maybe even get out and talk a short walk. This action reminds them that they ARE indeed beholden to your rules, at least while you are giving them a ride in your car. Be prepared to offer an explanation e.g. "I pulled over so you could continue your phone call."
Its kind to help your friends out with rides, but you are perfectly justified in drawing the line at NOT being a taxi driver. | I worked once in a small room with a bunch of other people. Needless to say, phone calls were a huge distraction to the others in the room.
I decided that I wouldn't say anything about it. However, I would (unless it was their boss), make it hard for them to continue with a personal call in such a small space.
Without being a huge jerk, I had fun with the calls. I'd respond to their conversations. If it was a significant other, I'd do the "love you.. Love you lots.... love you more... no, love YOU more... Hang up.... no, you hang up..." Once I knew it wasn't their boss, I'd do "Hi... hello.... hi... hello..." or "What are you wearing?" or something else obnoxious. That sent the message that there were more of us in the room and that personal calls should be taken outside the room.
And if someone would hit me with, "Do you mind?" I'd respond with, "Not at all; this is kind of fun for me!"
It usually took a call or two, but after that people either left the room or kept their calls short. Now, in the car, they don't have the option to leave at 60 mph, so this needs to be tempered somewhat. |
15,899 | I am often the driver for friends and family whenever we travel, whether short or long distances. This is mostly due to the fact that I have the best track record, reflexes, judgement, etc. on the road and am generally happy to do it. I am not against passengers making/answering phone calls while I am driving, but I do not like it when they have extended conversations while I am driving. It is annoying to me because I have to turn off the radio, halt my conversations with other passengers, and listen to one side of a conversation, which is frustratingly boring - especially if it goes on for more than 30 minutes.
In the US at least, the etiquette for behavior when other people are on the phone nearby is to be quiet and let them converse without interruption. It's also common etiquette to step out of a room if you have to talk on the phone, but that is not possible in the car for obvious reasons. Correct me if I'm wrong, but I don't believe there is any kind of well known rule for taking phone calls in the car.
Whenever I am in a situation like this, I feel stuck. I have tried asking them to please wrap up the conversation, but I feel petty for doing so and am usually met with a confused look. I've also tried asking them to keep it short before the answer the phone, but either they get wrapped up in their conversation and ignore me, or they act like I'm kind of unreasonable tyrant and say on the phone, "Sorry, *BlackThorn* doesn't want me to talk on the phone, so he is making me keep this short."
As the driver, I have nothing else to do in these situations, so I feel like it is reasonable to expect that phone conversations are kept short. Other passengers have the option of playing on their phones, reading a book, looking out the window (at the sights, not the road), but I am held hostage to half of the conversation whenever someone is on the phone. **How can I get my passengers to see things my way, and keep their phone calls short?**
To clarify, this behavior is *both* rude and distracting. Listening to half a conversation, as @DaveG pointed out, is distracting because your brain tries to fill in the other half of the conversation. It is also annoying, which leads to more distracted driving as I start to focus on how much I wish the passenger would hang up the phone. I'm happy to converse with them to pass the time, listen to them converse with each other, listen to the radio, or drive in silence. | 2018/06/26 | [
"https://interpersonal.stackexchange.com/questions/15899",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/5253/"
] | **What's rude is subjective, so focus on the fact that it is a distraction to you.** Everyone can agree that it's very important that the driver focuses on driving! (whereas many people become upset when you accuse them of being rude - as you have already experienced to some degree.)
So frame your request as a safety issue, and bring it up as soon as it is relevant - when the phone rings. Don't turn down the radio for them until they ask, or at least until they agree to keep it quick. That's because it's a move to accommodate their phone call, which signals approval.
If the call goes on too long, remind them and say that the conversation is making it difficult for you to drive. You don't need to explain beyond that - again, it should be self-evident that the driver being able to drive is highest priority. However, simply saying "Please keep it short" doesn't give them a reason why, which is why some might think you're being unreasonable. (They may have no problem driving people who are chatting on the phone, or simply not be thinking of it from your point of view at all.) You don't include examples, but if you think the phrasing may be an issue, try softening it with a "sorry, but can you.." or "would you mind.." so it sounds less like an order.
As far as personal experience, I went on a number of road trips as a kid and my dad would use a variation on this (e.g. "Kids, time to be quiet, Dad really needs to concentrate right now"). No further justification needed - nobody could argue that he wasn't distracted, and even as children we understood that safe driving took precedence over everything else.
Now as a driver myself, I find anything other than a one-to-one conversation with a passenger or music incredibly distracting. I haven't had the same issue with phone calls, but I have had issues with the radio. On occasion I've had to use my position in the driver's seat to switch it off, and just apologized after with a short "Sorry, too distracting". So far everyone has been understanding, but for a repeat offender I would politely refuse to be their driver in the future. | I worked once in a small room with a bunch of other people. Needless to say, phone calls were a huge distraction to the others in the room.
I decided that I wouldn't say anything about it. However, I would (unless it was their boss), make it hard for them to continue with a personal call in such a small space.
Without being a huge jerk, I had fun with the calls. I'd respond to their conversations. If it was a significant other, I'd do the "love you.. Love you lots.... love you more... no, love YOU more... Hang up.... no, you hang up..." Once I knew it wasn't their boss, I'd do "Hi... hello.... hi... hello..." or "What are you wearing?" or something else obnoxious. That sent the message that there were more of us in the room and that personal calls should be taken outside the room.
And if someone would hit me with, "Do you mind?" I'd respond with, "Not at all; this is kind of fun for me!"
It usually took a call or two, but after that people either left the room or kept their calls short. Now, in the car, they don't have the option to leave at 60 mph, so this needs to be tempered somewhat. |
15,899 | I am often the driver for friends and family whenever we travel, whether short or long distances. This is mostly due to the fact that I have the best track record, reflexes, judgement, etc. on the road and am generally happy to do it. I am not against passengers making/answering phone calls while I am driving, but I do not like it when they have extended conversations while I am driving. It is annoying to me because I have to turn off the radio, halt my conversations with other passengers, and listen to one side of a conversation, which is frustratingly boring - especially if it goes on for more than 30 minutes.
In the US at least, the etiquette for behavior when other people are on the phone nearby is to be quiet and let them converse without interruption. It's also common etiquette to step out of a room if you have to talk on the phone, but that is not possible in the car for obvious reasons. Correct me if I'm wrong, but I don't believe there is any kind of well known rule for taking phone calls in the car.
Whenever I am in a situation like this, I feel stuck. I have tried asking them to please wrap up the conversation, but I feel petty for doing so and am usually met with a confused look. I've also tried asking them to keep it short before the answer the phone, but either they get wrapped up in their conversation and ignore me, or they act like I'm kind of unreasonable tyrant and say on the phone, "Sorry, *BlackThorn* doesn't want me to talk on the phone, so he is making me keep this short."
As the driver, I have nothing else to do in these situations, so I feel like it is reasonable to expect that phone conversations are kept short. Other passengers have the option of playing on their phones, reading a book, looking out the window (at the sights, not the road), but I am held hostage to half of the conversation whenever someone is on the phone. **How can I get my passengers to see things my way, and keep their phone calls short?**
To clarify, this behavior is *both* rude and distracting. Listening to half a conversation, as @DaveG pointed out, is distracting because your brain tries to fill in the other half of the conversation. It is also annoying, which leads to more distracted driving as I start to focus on how much I wish the passenger would hang up the phone. I'm happy to converse with them to pass the time, listen to them converse with each other, listen to the radio, or drive in silence. | 2018/06/26 | [
"https://interpersonal.stackexchange.com/questions/15899",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/5253/"
] | You are in control in this situation. You're doing them a favor by driving, so you have some say in what happens in the car. As such, set the ground rules before they have a chance to pickup the phone.
If this issue is serious enough that you're bringing it to IPS, I'm going to assume this happens fairly often and you have some regular suspects. When you're discussing going somewhere and choosing who will drive, when they inevitably choose you, warn them that you have a phone rule in the car.
>
> I'd be happy to drive you, but I have a recent new phone rule in my car. I'm fine with you making short calls, but I find that anything longer than a few minutes starts to distract me when I'm driving.
>
>
>
And if they start to protest, then simply don't drive! You're holding all the chips here. Make sure the only way they're getting in your car is if they've agreed to your rules. | I worked once in a small room with a bunch of other people. Needless to say, phone calls were a huge distraction to the others in the room.
I decided that I wouldn't say anything about it. However, I would (unless it was their boss), make it hard for them to continue with a personal call in such a small space.
Without being a huge jerk, I had fun with the calls. I'd respond to their conversations. If it was a significant other, I'd do the "love you.. Love you lots.... love you more... no, love YOU more... Hang up.... no, you hang up..." Once I knew it wasn't their boss, I'd do "Hi... hello.... hi... hello..." or "What are you wearing?" or something else obnoxious. That sent the message that there were more of us in the room and that personal calls should be taken outside the room.
And if someone would hit me with, "Do you mind?" I'd respond with, "Not at all; this is kind of fun for me!"
It usually took a call or two, but after that people either left the room or kept their calls short. Now, in the car, they don't have the option to leave at 60 mph, so this needs to be tempered somewhat. |
18,141,042 | Problem:
>
> Write 0b11001001 in decimal.
>
>
>
I tried the following:
>
> 110010012 = 1 + 8 + 64 + 128 = 201
>
>
>
but the answer is –55. Where am I going wrong? | 2013/08/09 | [
"https://Stackoverflow.com/questions/18141042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2460890/"
] | Your answer is *correct* providing that the *underlying data type* is **unsigned byte**.
If the type is a **signed byte**, then it is of range [-128..127]. You've got 201
which is *out of range* [0..127], so 201 should be interpreted as a *negative value*.
In order to find out a corresponging negative value you should convert your
code into so called *complement representation*:
<http://en.wikipedia.org/wiki/Signed_number_representations>
1. reverse each bit
2. add 1
11001001 -> 00110110 (reversed) -> 00110111 (one added)
0b00110111 is 1 + 2 + 4 + 16 + 32 = 55 decimal
So the answer for **signed byte** is -55 | I'm assuming this is a homework problem or test question? If a string of bits represents an integer, it can be interpreted as either signed (in which case the value can be positive, zero, or negative) or unsigned (in which case it's only positive or zero.)
In this instance, you provided the correct answer for an unsigned integer with an eight-bit word length, but the questioner was looking for the value of a signed integer.
Signed values are usually represented using a scheme called two's complement, described here:
<http://en.wikipedia.org/wiki/Two>'s\_complement
-55 is the value of that binary sequence interpreted as two's complement, assuming an eight-bit word length.
However, there are other schemes for encoding negative integers in binary such as one's complement, which provides a different result:
<http://en.wikipedia.org/wiki/Ones>'\_complement
Two's complement is usually preferred because there is only one representation for zero, while one's complement provides a positive and negative zero representation.
Anyway, the question seems to rely on implicit, unstated assumptions. |
55,184,079 | I'm trying to compile a python file into an APK using buildozer. After installing all dependencies (including SDK and NDK) and running `buildozer android deploy run`, I get the following error:
```
/home/caliph/.buildozer/android/platform/android-sdk
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 5 more
# Command failed: /home/caliph/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
```
My python code is a simple class in a file titled main.py:
```
__version__ = '1.1'
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
```
How can I overcome this problem and create an APK. Please help! | 2019/03/15 | [
"https://Stackoverflow.com/questions/55184079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11195319/"
] | material-ui's select component uses the mouseDown event to trigger the popover menu to appear. If you use `fireEvent.mouseDown` that should trigger the popover and then you can click your selection within the listbox that appears. see example below.
```
import React from "react";
import { render, fireEvent, within } from "react-testing-library";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import Typography from "@material-ui/core/Typography";
it('selects the correct option', () => {
const {getByRole} = render(
<>
<Select fullWidth value={selectedTab} onChange={onTabChange}>
<MenuItem value="privacy">Privacy</MenuItem>
<MenuItem value="my-account">My Account</MenuItem>
</Select>
<Typography variant="h1">{/* value set in state */}</Typography>
</>
);
fireEvent.mouseDown(getByRole('button'));
const listbox = within(getByRole('listbox'));
fireEvent.click(listbox.getByText(/my account/i));
expect(getByRole('heading')).toHaveTextContent(/my account/i);
});
``` | Using Material UI 5.10.3, this is how to simulate a click on the `Select` component, and to subsequently grab/verify the item values, and to click one of them to trigger the underlying change event:
```
import { fireEvent, render, screen, within } from '@testing-library/react';
import { MenuItem, Select } from '@mui/material';
describe('MUI Select Component', () => {
it('should have correct options an handle change', () => {
const spyOnSelectChange = jest.fn();
const { getByTestId } = render(
<div>
<Select
data-testid={'component-under-test'}
value={''}
onChange={(evt) => spyOnSelectChange(evt.target.value)}
>
<MenuItem value="menu-a">OptionA</MenuItem>
<MenuItem value="menu-b">OptionB</MenuItem>
</Select>
</div>
);
const selectCompoEl = getByTestId('component-under-test');
const button = within(selectCompoEl).getByRole('button');
fireEvent.mouseDown(button);
const listbox = within(screen.getByRole('presentation')).getByRole(
'listbox'
);
const options = within(listbox).getAllByRole('option');
const optionValues = options.map((li) => li.getAttribute('data-value'));
expect(optionValues).toEqual(['menu-a', 'menu-b']);
fireEvent.click(options[1]);
expect(spyOnSelectChange).toHaveBeenCalledWith('menu-b');
});
});
```
Also posted [here](https://github.com/testing-library/react-testing-library/issues/322#issuecomment-1236191573). |
55,184,079 | I'm trying to compile a python file into an APK using buildozer. After installing all dependencies (including SDK and NDK) and running `buildozer android deploy run`, I get the following error:
```
/home/caliph/.buildozer/android/platform/android-sdk
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 5 more
# Command failed: /home/caliph/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
```
My python code is a simple class in a file titled main.py:
```
__version__ = '1.1'
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
```
How can I overcome this problem and create an APK. Please help! | 2019/03/15 | [
"https://Stackoverflow.com/questions/55184079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11195319/"
] | This turns out to be super complicated when you are using Material-UI's `Select` with `native={false}` (which is the default). This is because the rendered input doesn't even have a `<select>` HTML element, but is instead a mix of divs, a hidden input, and some svgs. Then, when you click on the select, a presentation layer (kind of like a modal) is displayed with all of your options (which are not `<option>` HTML elements, by the way), and I believe it's the clicking of one of these options that triggers whatever you passed as the `onChange` callback to your original Material-UI `<Select>`
All that to say, if you are willing to use `<Select native={true}>`, then you'll have actual `<select>` and `<option>` HTML elements to work with, and you can fire a change event on the `<select>` as you would have expected.
Here is test code from a Code Sandbox which works:
```
import React from "react";
import { render, cleanup, fireEvent } from "react-testing-library";
import Select from "@material-ui/core/Select";
beforeEach(() => {
jest.resetAllMocks();
});
afterEach(() => {
cleanup();
});
it("calls onChange if change event fired", () => {
const mockCallback = jest.fn();
const { getByTestId } = render(
<div>
<Select
native={true}
onChange={mockCallback}
data-testid="my-wrapper"
defaultValue="1"
>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</Select>
</div>
);
const wrapperNode = getByTestId("my-wrapper")
console.log(wrapperNode)
// Dig deep to find the actual <select>
const selectNode = wrapperNode.childNodes[0].childNodes[0];
fireEvent.change(selectNode, { target: { value: "3" } });
expect(mockCallback.mock.calls).toHaveLength(1);
});
```
You'll notice that you have to dig down through the nodes to find where the actual `<select>` is once Material-UI renders out its `<Select>`. But once you find it, you can do a `fireEvent.change` on it.
The CodeSandbox can be found here:
[](https://codesandbox.io/s/423q9j039?fontsize=14) | This is what worked for me while using MUI 5.
```
userEvent.click(screen.getByLabelText(/^foo/i));
userEvent.click(screen.getByRole('option', {name: /^bar/i}));
``` |
55,184,079 | I'm trying to compile a python file into an APK using buildozer. After installing all dependencies (including SDK and NDK) and running `buildozer android deploy run`, I get the following error:
```
/home/caliph/.buildozer/android/platform/android-sdk
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 5 more
# Command failed: /home/caliph/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
```
My python code is a simple class in a file titled main.py:
```
__version__ = '1.1'
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
```
How can I overcome this problem and create an APK. Please help! | 2019/03/15 | [
"https://Stackoverflow.com/questions/55184079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11195319/"
] | ### Using `*ByLabelText()`
#### Component
```js
// demo.js
import * as React from "react";
import Box from "@mui/material/Box";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
import Typography from "@mui/material/Typography";
export default function BasicSelect() {
const [theThing, setTheThing] = React.useState("None");
const handleChange = (event) => {
setTheThing(event.target.value);
};
return (
<Box sx={{ minWidth: 120 }}>
<FormControl fullWidth>
<InputLabel id="demo-simple-select-label">Choose a thing</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={theThing}
label="Choose a thing"
onChange={handleChange}
>
<MenuItem value={"None"}>None</MenuItem>
<MenuItem value={"Meerkat"}>Meerkat</MenuItem>
<MenuItem value={"Marshmallow"}>Marshmallow</MenuItem>
</Select>
</FormControl>
<Box sx={{ padding: 2 }}>
<Typography>The thing is: {theThing}</Typography>
</Box>
</Box>
);
}
```
#### Test
```js
// demo.test.js
import "@testing-library/jest-dom";
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Demo from "./demo";
test("When I choose a thing, then the thing changes", async () => {
render(<Demo />);
// Confirm default state.
expect(await screen.findByText(/the thing is: none/i)).toBeInTheDocument();
// Click on the MUI "select" (as found by the label).
const selectLabel = /choose a thing/i;
const selectEl = await screen.findByLabelText(selectLabel);
expect(selectEl).toBeInTheDocument();
userEvent.click(selectEl);
// Locate the corresponding popup (`listbox`) of options.
const optionsPopupEl = await screen.findByRole("listbox", {
name: selectLabel
});
// Click an option in the popup.
userEvent.click(within(optionsPopupEl).getByText(/marshmallow/i));
// Confirm the outcome.
expect(
await screen.findByText(/the thing is: marshmallow/i)
).toBeInTheDocument();
});
```
[codesandbox](https://codesandbox.io/s/testing-mui-select-ogwjy?file=/demo.test.js) *Note:* Test doesn't run on codesandbox, but does run and pass on local. | This is what worked for me while using MUI 5.
```
userEvent.click(screen.getByLabelText(/^foo/i));
userEvent.click(screen.getByRole('option', {name: /^bar/i}));
``` |
55,184,079 | I'm trying to compile a python file into an APK using buildozer. After installing all dependencies (including SDK and NDK) and running `buildozer android deploy run`, I get the following error:
```
/home/caliph/.buildozer/android/platform/android-sdk
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 5 more
# Command failed: /home/caliph/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
```
My python code is a simple class in a file titled main.py:
```
__version__ = '1.1'
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
```
How can I overcome this problem and create an APK. Please help! | 2019/03/15 | [
"https://Stackoverflow.com/questions/55184079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11195319/"
] | Using Material UI 5.10.3, this is how to simulate a click on the `Select` component, and to subsequently grab/verify the item values, and to click one of them to trigger the underlying change event:
```
import { fireEvent, render, screen, within } from '@testing-library/react';
import { MenuItem, Select } from '@mui/material';
describe('MUI Select Component', () => {
it('should have correct options an handle change', () => {
const spyOnSelectChange = jest.fn();
const { getByTestId } = render(
<div>
<Select
data-testid={'component-under-test'}
value={''}
onChange={(evt) => spyOnSelectChange(evt.target.value)}
>
<MenuItem value="menu-a">OptionA</MenuItem>
<MenuItem value="menu-b">OptionB</MenuItem>
</Select>
</div>
);
const selectCompoEl = getByTestId('component-under-test');
const button = within(selectCompoEl).getByRole('button');
fireEvent.mouseDown(button);
const listbox = within(screen.getByRole('presentation')).getByRole(
'listbox'
);
const options = within(listbox).getAllByRole('option');
const optionValues = options.map((li) => li.getAttribute('data-value'));
expect(optionValues).toEqual(['menu-a', 'menu-b']);
fireEvent.click(options[1]);
expect(spyOnSelectChange).toHaveBeenCalledWith('menu-b');
});
});
```
Also posted [here](https://github.com/testing-library/react-testing-library/issues/322#issuecomment-1236191573). | This is what worked for me while using MUI 5.
```
userEvent.click(screen.getByLabelText(/^foo/i));
userEvent.click(screen.getByRole('option', {name: /^bar/i}));
``` |
55,184,079 | I'm trying to compile a python file into an APK using buildozer. After installing all dependencies (including SDK and NDK) and running `buildozer android deploy run`, I get the following error:
```
/home/caliph/.buildozer/android/platform/android-sdk
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 5 more
# Command failed: /home/caliph/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
```
My python code is a simple class in a file titled main.py:
```
__version__ = '1.1'
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
```
How can I overcome this problem and create an APK. Please help! | 2019/03/15 | [
"https://Stackoverflow.com/questions/55184079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11195319/"
] | material-ui's select component uses the mouseDown event to trigger the popover menu to appear. If you use `fireEvent.mouseDown` that should trigger the popover and then you can click your selection within the listbox that appears. see example below.
```
import React from "react";
import { render, fireEvent, within } from "react-testing-library";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import Typography from "@material-ui/core/Typography";
it('selects the correct option', () => {
const {getByRole} = render(
<>
<Select fullWidth value={selectedTab} onChange={onTabChange}>
<MenuItem value="privacy">Privacy</MenuItem>
<MenuItem value="my-account">My Account</MenuItem>
</Select>
<Typography variant="h1">{/* value set in state */}</Typography>
</>
);
fireEvent.mouseDown(getByRole('button'));
const listbox = within(getByRole('listbox'));
fireEvent.click(listbox.getByText(/my account/i));
expect(getByRole('heading')).toHaveTextContent(/my account/i);
});
``` | I have done with multiple Select in one page, try this one:
```
import { render, fireEvent, within } from '@testing-library/react'
it('Should trigger select-xxx methiod', () => {
const { getByTestId, getByRole: getByRoleParent } = component
const element = getByTestId('select-xxx');
const { getByRole } = within(element)
const select = getByRole('button')
fireEvent.mouseDown(select);
const list = within(getByRoleParent('listbox')) // get list opened by trigger fireEvent
fireEvent.click(list.getByText(/just try/i)); //select by text
})
``` |
55,184,079 | I'm trying to compile a python file into an APK using buildozer. After installing all dependencies (including SDK and NDK) and running `buildozer android deploy run`, I get the following error:
```
/home/caliph/.buildozer/android/platform/android-sdk
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 5 more
# Command failed: /home/caliph/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
```
My python code is a simple class in a file titled main.py:
```
__version__ = '1.1'
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
```
How can I overcome this problem and create an APK. Please help! | 2019/03/15 | [
"https://Stackoverflow.com/questions/55184079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11195319/"
] | Here is a working example for MUI TextField with Select option.
Sandbox: <https://codesandbox.io/s/stupefied-chandrasekhar-vq2x0?file=/src/__tests__/TextSelect.test.tsx:0-1668>
Textfield:
```
import { TextField, MenuItem, InputAdornment } from "@material-ui/core";
import { useState } from "react";
export const sampleData = [
{
name: "Vat-19",
value: 1900
},
{
name: "Vat-0",
value: 0
},
{
name: "Vat-7",
value: 700
}
];
export default function TextSelect() {
const [selected, setSelected] = useState(sampleData[0].name);
return (
<TextField
id="vatSelectTextField"
select
label="#ExampleLabel"
value={selected}
onChange={(evt) => {
setSelected(evt.target.value);
}}
variant="outlined"
color="secondary"
inputProps={{
id: "vatSelectInput"
}}
InputProps={{
startAdornment: <InputAdornment position="start">%</InputAdornment>
}}
fullWidth
>
{sampleData.map((vatOption) => (
<MenuItem key={vatOption.name} value={vatOption.name}>
{vatOption.name} - {vatOption.value / 100} %
</MenuItem>
))}
</TextField>
);
}
```
Test:
```
import { fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { act } from "react-dom/test-utils";
import TextSelect, { sampleData } from "../MuiTextSelect/TextSelect";
import "@testing-library/jest-dom";
describe("Tests TextField Select change", () => {
test("Changes the selected value", () => {
const { getAllByRole, getByRole, container } = render(<TextSelect />);
//CHECK DIV CONTAINER
let vatSelectTextField = container.querySelector(
"#vatSelectTextField"
) as HTMLDivElement;
expect(vatSelectTextField).toBeInTheDocument();
//CHECK DIV CONTAINER
let vatSelectInput = container.querySelector(
"#vatSelectInput"
) as HTMLInputElement;
expect(vatSelectInput).toBeInTheDocument();
expect(vatSelectInput.value).toEqual(sampleData[0].name);
// OPEN
fireEvent.mouseDown(vatSelectTextField);
//CHECKO OPTIONS
expect(getByRole("listbox")).not.toEqual(null);
// screen.debug(getByRole("listbox"));
//CHANGE
act(() => {
const options = getAllByRole("option");
// screen.debug(getAllByRole("option"));
fireEvent.mouseDown(options[1]);
options[1].click();
});
//CHECK CHANGED
vatSelectInput = container.querySelector(
"#vatSelectInput"
) as HTMLInputElement;
expect(vatSelectInput.value).toEqual(sampleData[1].name);
});
});
/**
* HAVE A LOOK AT
*
*
* https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Select/Select.test.js
* (ll. 117-121)
*
* https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/TextField/TextField.test.js
*
*
*/
``` | For people who have multiple Selects, make sure to add the `name` prop
```
<SelectDropdown
name="date_range"
...
>
...
</SelectDropdown>
<SelectDropdown
name="company"
...
>
...
</SelectDropdown>
```
```
// date filter
const date_range_dropdown = getByLabelText('Date Range');
fireEvent.mouseDown(date_range_dropdown);
await screen.findByRole('listbox');
fireEvent.click(
within(screen.getByRole('listbox')).getByText(/Last 30 Days/)
);
// // company filter
const company_dropdown = getByLabelText('Company');
fireEvent.mouseDown(company_dropdown);
fireEvent.click(within(getByRole('listbox')).getByText(/Uber/));
``` |
55,184,079 | I'm trying to compile a python file into an APK using buildozer. After installing all dependencies (including SDK and NDK) and running `buildozer android deploy run`, I get the following error:
```
/home/caliph/.buildozer/android/platform/android-sdk
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 5 more
# Command failed: /home/caliph/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
```
My python code is a simple class in a file titled main.py:
```
__version__ = '1.1'
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
```
How can I overcome this problem and create an APK. Please help! | 2019/03/15 | [
"https://Stackoverflow.com/questions/55184079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11195319/"
] | Here is a working example for MUI TextField with Select option.
Sandbox: <https://codesandbox.io/s/stupefied-chandrasekhar-vq2x0?file=/src/__tests__/TextSelect.test.tsx:0-1668>
Textfield:
```
import { TextField, MenuItem, InputAdornment } from "@material-ui/core";
import { useState } from "react";
export const sampleData = [
{
name: "Vat-19",
value: 1900
},
{
name: "Vat-0",
value: 0
},
{
name: "Vat-7",
value: 700
}
];
export default function TextSelect() {
const [selected, setSelected] = useState(sampleData[0].name);
return (
<TextField
id="vatSelectTextField"
select
label="#ExampleLabel"
value={selected}
onChange={(evt) => {
setSelected(evt.target.value);
}}
variant="outlined"
color="secondary"
inputProps={{
id: "vatSelectInput"
}}
InputProps={{
startAdornment: <InputAdornment position="start">%</InputAdornment>
}}
fullWidth
>
{sampleData.map((vatOption) => (
<MenuItem key={vatOption.name} value={vatOption.name}>
{vatOption.name} - {vatOption.value / 100} %
</MenuItem>
))}
</TextField>
);
}
```
Test:
```
import { fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { act } from "react-dom/test-utils";
import TextSelect, { sampleData } from "../MuiTextSelect/TextSelect";
import "@testing-library/jest-dom";
describe("Tests TextField Select change", () => {
test("Changes the selected value", () => {
const { getAllByRole, getByRole, container } = render(<TextSelect />);
//CHECK DIV CONTAINER
let vatSelectTextField = container.querySelector(
"#vatSelectTextField"
) as HTMLDivElement;
expect(vatSelectTextField).toBeInTheDocument();
//CHECK DIV CONTAINER
let vatSelectInput = container.querySelector(
"#vatSelectInput"
) as HTMLInputElement;
expect(vatSelectInput).toBeInTheDocument();
expect(vatSelectInput.value).toEqual(sampleData[0].name);
// OPEN
fireEvent.mouseDown(vatSelectTextField);
//CHECKO OPTIONS
expect(getByRole("listbox")).not.toEqual(null);
// screen.debug(getByRole("listbox"));
//CHANGE
act(() => {
const options = getAllByRole("option");
// screen.debug(getAllByRole("option"));
fireEvent.mouseDown(options[1]);
options[1].click();
});
//CHECK CHANGED
vatSelectInput = container.querySelector(
"#vatSelectInput"
) as HTMLInputElement;
expect(vatSelectInput.value).toEqual(sampleData[1].name);
});
});
/**
* HAVE A LOOK AT
*
*
* https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Select/Select.test.js
* (ll. 117-121)
*
* https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/TextField/TextField.test.js
*
*
*/
``` | Using Material UI 5.10.3, this is how to simulate a click on the `Select` component, and to subsequently grab/verify the item values, and to click one of them to trigger the underlying change event:
```
import { fireEvent, render, screen, within } from '@testing-library/react';
import { MenuItem, Select } from '@mui/material';
describe('MUI Select Component', () => {
it('should have correct options an handle change', () => {
const spyOnSelectChange = jest.fn();
const { getByTestId } = render(
<div>
<Select
data-testid={'component-under-test'}
value={''}
onChange={(evt) => spyOnSelectChange(evt.target.value)}
>
<MenuItem value="menu-a">OptionA</MenuItem>
<MenuItem value="menu-b">OptionB</MenuItem>
</Select>
</div>
);
const selectCompoEl = getByTestId('component-under-test');
const button = within(selectCompoEl).getByRole('button');
fireEvent.mouseDown(button);
const listbox = within(screen.getByRole('presentation')).getByRole(
'listbox'
);
const options = within(listbox).getAllByRole('option');
const optionValues = options.map((li) => li.getAttribute('data-value'));
expect(optionValues).toEqual(['menu-a', 'menu-b']);
fireEvent.click(options[1]);
expect(spyOnSelectChange).toHaveBeenCalledWith('menu-b');
});
});
```
Also posted [here](https://github.com/testing-library/react-testing-library/issues/322#issuecomment-1236191573). |
55,184,079 | I'm trying to compile a python file into an APK using buildozer. After installing all dependencies (including SDK and NDK) and running `buildozer android deploy run`, I get the following error:
```
/home/caliph/.buildozer/android/platform/android-sdk
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 5 more
# Command failed: /home/caliph/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
```
My python code is a simple class in a file titled main.py:
```
__version__ = '1.1'
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
```
How can I overcome this problem and create an APK. Please help! | 2019/03/15 | [
"https://Stackoverflow.com/questions/55184079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11195319/"
] | This turns out to be super complicated when you are using Material-UI's `Select` with `native={false}` (which is the default). This is because the rendered input doesn't even have a `<select>` HTML element, but is instead a mix of divs, a hidden input, and some svgs. Then, when you click on the select, a presentation layer (kind of like a modal) is displayed with all of your options (which are not `<option>` HTML elements, by the way), and I believe it's the clicking of one of these options that triggers whatever you passed as the `onChange` callback to your original Material-UI `<Select>`
All that to say, if you are willing to use `<Select native={true}>`, then you'll have actual `<select>` and `<option>` HTML elements to work with, and you can fire a change event on the `<select>` as you would have expected.
Here is test code from a Code Sandbox which works:
```
import React from "react";
import { render, cleanup, fireEvent } from "react-testing-library";
import Select from "@material-ui/core/Select";
beforeEach(() => {
jest.resetAllMocks();
});
afterEach(() => {
cleanup();
});
it("calls onChange if change event fired", () => {
const mockCallback = jest.fn();
const { getByTestId } = render(
<div>
<Select
native={true}
onChange={mockCallback}
data-testid="my-wrapper"
defaultValue="1"
>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</Select>
</div>
);
const wrapperNode = getByTestId("my-wrapper")
console.log(wrapperNode)
// Dig deep to find the actual <select>
const selectNode = wrapperNode.childNodes[0].childNodes[0];
fireEvent.change(selectNode, { target: { value: "3" } });
expect(mockCallback.mock.calls).toHaveLength(1);
});
```
You'll notice that you have to dig down through the nodes to find where the actual `<select>` is once Material-UI renders out its `<Select>`. But once you find it, you can do a `fireEvent.change` on it.
The CodeSandbox can be found here:
[](https://codesandbox.io/s/423q9j039?fontsize=14) | Here is a working example for MUI TextField with Select option.
Sandbox: <https://codesandbox.io/s/stupefied-chandrasekhar-vq2x0?file=/src/__tests__/TextSelect.test.tsx:0-1668>
Textfield:
```
import { TextField, MenuItem, InputAdornment } from "@material-ui/core";
import { useState } from "react";
export const sampleData = [
{
name: "Vat-19",
value: 1900
},
{
name: "Vat-0",
value: 0
},
{
name: "Vat-7",
value: 700
}
];
export default function TextSelect() {
const [selected, setSelected] = useState(sampleData[0].name);
return (
<TextField
id="vatSelectTextField"
select
label="#ExampleLabel"
value={selected}
onChange={(evt) => {
setSelected(evt.target.value);
}}
variant="outlined"
color="secondary"
inputProps={{
id: "vatSelectInput"
}}
InputProps={{
startAdornment: <InputAdornment position="start">%</InputAdornment>
}}
fullWidth
>
{sampleData.map((vatOption) => (
<MenuItem key={vatOption.name} value={vatOption.name}>
{vatOption.name} - {vatOption.value / 100} %
</MenuItem>
))}
</TextField>
);
}
```
Test:
```
import { fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { act } from "react-dom/test-utils";
import TextSelect, { sampleData } from "../MuiTextSelect/TextSelect";
import "@testing-library/jest-dom";
describe("Tests TextField Select change", () => {
test("Changes the selected value", () => {
const { getAllByRole, getByRole, container } = render(<TextSelect />);
//CHECK DIV CONTAINER
let vatSelectTextField = container.querySelector(
"#vatSelectTextField"
) as HTMLDivElement;
expect(vatSelectTextField).toBeInTheDocument();
//CHECK DIV CONTAINER
let vatSelectInput = container.querySelector(
"#vatSelectInput"
) as HTMLInputElement;
expect(vatSelectInput).toBeInTheDocument();
expect(vatSelectInput.value).toEqual(sampleData[0].name);
// OPEN
fireEvent.mouseDown(vatSelectTextField);
//CHECKO OPTIONS
expect(getByRole("listbox")).not.toEqual(null);
// screen.debug(getByRole("listbox"));
//CHANGE
act(() => {
const options = getAllByRole("option");
// screen.debug(getAllByRole("option"));
fireEvent.mouseDown(options[1]);
options[1].click();
});
//CHECK CHANGED
vatSelectInput = container.querySelector(
"#vatSelectInput"
) as HTMLInputElement;
expect(vatSelectInput.value).toEqual(sampleData[1].name);
});
});
/**
* HAVE A LOOK AT
*
*
* https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Select/Select.test.js
* (ll. 117-121)
*
* https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/TextField/TextField.test.js
*
*
*/
``` |
55,184,079 | I'm trying to compile a python file into an APK using buildozer. After installing all dependencies (including SDK and NDK) and running `buildozer android deploy run`, I get the following error:
```
/home/caliph/.buildozer/android/platform/android-sdk
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 5 more
# Command failed: /home/caliph/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
```
My python code is a simple class in a file titled main.py:
```
__version__ = '1.1'
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
```
How can I overcome this problem and create an APK. Please help! | 2019/03/15 | [
"https://Stackoverflow.com/questions/55184079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11195319/"
] | Using Material UI 5.10.3, this is how to simulate a click on the `Select` component, and to subsequently grab/verify the item values, and to click one of them to trigger the underlying change event:
```
import { fireEvent, render, screen, within } from '@testing-library/react';
import { MenuItem, Select } from '@mui/material';
describe('MUI Select Component', () => {
it('should have correct options an handle change', () => {
const spyOnSelectChange = jest.fn();
const { getByTestId } = render(
<div>
<Select
data-testid={'component-under-test'}
value={''}
onChange={(evt) => spyOnSelectChange(evt.target.value)}
>
<MenuItem value="menu-a">OptionA</MenuItem>
<MenuItem value="menu-b">OptionB</MenuItem>
</Select>
</div>
);
const selectCompoEl = getByTestId('component-under-test');
const button = within(selectCompoEl).getByRole('button');
fireEvent.mouseDown(button);
const listbox = within(screen.getByRole('presentation')).getByRole(
'listbox'
);
const options = within(listbox).getAllByRole('option');
const optionValues = options.map((li) => li.getAttribute('data-value'));
expect(optionValues).toEqual(['menu-a', 'menu-b']);
fireEvent.click(options[1]);
expect(spyOnSelectChange).toHaveBeenCalledWith('menu-b');
});
});
```
Also posted [here](https://github.com/testing-library/react-testing-library/issues/322#issuecomment-1236191573). | ```
import * as React from "react";
import ReactDOM from 'react-dom';
import * as TestUtils from 'react-dom/test-utils';
import { } from "mocha";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
let container;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
describe("Testing Select component", () => {
test('start empty, open and select second option', (done) => {
//render the component
ReactDOM.render(<Select
displayEmpty={true}
value={""}
onChange={(e) => {
console.log(e.target.value);
}}
disableUnderline
classes={{
root: `my-select-component`
}}
>
<MenuItem value={""}>All</MenuItem>
<MenuItem value={"1"}>1</MenuItem>
<MenuItem value={"2"}>2</MenuItem>
<MenuItem value={"3"}>3</MenuItem>
</Select>, container);
//open filter
TestUtils.Simulate.click(container.querySelector('.my-select-component'));
const secondOption = container.ownerDocument.activeElement.parentElement.querySelectorAll('li')[1];
TestUtils.Simulate.click(secondOption);
done();
});
});
``` |
55,184,079 | I'm trying to compile a python file into an APK using buildozer. After installing all dependencies (including SDK and NDK) and running `buildozer android deploy run`, I get the following error:
```
/home/caliph/.buildozer/android/platform/android-sdk
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 5 more
# Command failed: /home/caliph/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
```
My python code is a simple class in a file titled main.py:
```
__version__ = '1.1'
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
```
How can I overcome this problem and create an APK. Please help! | 2019/03/15 | [
"https://Stackoverflow.com/questions/55184079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11195319/"
] | This turns out to be super complicated when you are using Material-UI's `Select` with `native={false}` (which is the default). This is because the rendered input doesn't even have a `<select>` HTML element, but is instead a mix of divs, a hidden input, and some svgs. Then, when you click on the select, a presentation layer (kind of like a modal) is displayed with all of your options (which are not `<option>` HTML elements, by the way), and I believe it's the clicking of one of these options that triggers whatever you passed as the `onChange` callback to your original Material-UI `<Select>`
All that to say, if you are willing to use `<Select native={true}>`, then you'll have actual `<select>` and `<option>` HTML elements to work with, and you can fire a change event on the `<select>` as you would have expected.
Here is test code from a Code Sandbox which works:
```
import React from "react";
import { render, cleanup, fireEvent } from "react-testing-library";
import Select from "@material-ui/core/Select";
beforeEach(() => {
jest.resetAllMocks();
});
afterEach(() => {
cleanup();
});
it("calls onChange if change event fired", () => {
const mockCallback = jest.fn();
const { getByTestId } = render(
<div>
<Select
native={true}
onChange={mockCallback}
data-testid="my-wrapper"
defaultValue="1"
>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</Select>
</div>
);
const wrapperNode = getByTestId("my-wrapper")
console.log(wrapperNode)
// Dig deep to find the actual <select>
const selectNode = wrapperNode.childNodes[0].childNodes[0];
fireEvent.change(selectNode, { target: { value: "3" } });
expect(mockCallback.mock.calls).toHaveLength(1);
});
```
You'll notice that you have to dig down through the nodes to find where the actual `<select>` is once Material-UI renders out its `<Select>`. But once you find it, you can do a `fireEvent.change` on it.
The CodeSandbox can be found here:
[](https://codesandbox.io/s/423q9j039?fontsize=14) | I have done with multiple Select in one page, try this one:
```
import { render, fireEvent, within } from '@testing-library/react'
it('Should trigger select-xxx methiod', () => {
const { getByTestId, getByRole: getByRoleParent } = component
const element = getByTestId('select-xxx');
const { getByRole } = within(element)
const select = getByRole('button')
fireEvent.mouseDown(select);
const list = within(getByRoleParent('listbox')) // get list opened by trigger fireEvent
fireEvent.click(list.getByText(/just try/i)); //select by text
})
``` |
42,469,945 | I have two input boxes on my form.
One is a dropdown select and the other is the textbox.
I need to update the textbox value depending on what is chosen on the select box.
For example, if I choose "1" on select box, the textbox value should have "299.00" and if I choose "2", the textbox value should be "399.0"
Can you help me on editing the code? Thank you in advanced.
Here is my html code:
```
<select style="width: 25%;height:25px;margin-left:15px;" onchange="ChooseContact(this)">
<option id="extra1" value='1'>1</option>
<option id="extra2" value='2'>2</option>
</select>
<input style="width: 25%;margin-left:15px;" id="extraper">
```
and here is the javascript:
```
function ChooseContact(data) {
var x = 0;
var y = 0;
var e = obj.id.toString();
if (e == 'tb1') {
x = Number("PHP 299");
y = document.getElementById ("extraper").value = x;
}
};
```
I'm sure that my javascript is wrong. Can you help me with it? | 2017/02/26 | [
"https://Stackoverflow.com/questions/42469945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7415564/"
] | To get int value from user user:
```
int a;
scanf("%d",&a);
```
scanf uses different specifiers:
%d integer
%f Float
%d double
%c char | The \* tells scanf to read in but ignore the input. Take a look at <http://www.cplusplus.com/reference/cstdio/scanf/> . why it always prints 67 you might need to step through a debugger to see what the int is initialized with and how that changes. |
42,469,945 | I have two input boxes on my form.
One is a dropdown select and the other is the textbox.
I need to update the textbox value depending on what is chosen on the select box.
For example, if I choose "1" on select box, the textbox value should have "299.00" and if I choose "2", the textbox value should be "399.0"
Can you help me on editing the code? Thank you in advanced.
Here is my html code:
```
<select style="width: 25%;height:25px;margin-left:15px;" onchange="ChooseContact(this)">
<option id="extra1" value='1'>1</option>
<option id="extra2" value='2'>2</option>
</select>
<input style="width: 25%;margin-left:15px;" id="extraper">
```
and here is the javascript:
```
function ChooseContact(data) {
var x = 0;
var y = 0;
var e = obj.id.toString();
if (e == 'tb1') {
x = Number("PHP 299");
y = document.getElementById ("extraper").value = x;
}
};
```
I'm sure that my javascript is wrong. Can you help me with it? | 2017/02/26 | [
"https://Stackoverflow.com/questions/42469945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7415564/"
] | To get int value from user user:
```
int a;
scanf("%d",&a);
```
scanf uses different specifiers:
%d integer
%f Float
%d double
%c char | In the above program, the `scanf()` reads but does not assign the value due to the `*` format specifier. As a result, whatever is the value of a (which is not initialized) is produced as output by `printf()`. In this case, 67 is the garbage value. |
42,469,945 | I have two input boxes on my form.
One is a dropdown select and the other is the textbox.
I need to update the textbox value depending on what is chosen on the select box.
For example, if I choose "1" on select box, the textbox value should have "299.00" and if I choose "2", the textbox value should be "399.0"
Can you help me on editing the code? Thank you in advanced.
Here is my html code:
```
<select style="width: 25%;height:25px;margin-left:15px;" onchange="ChooseContact(this)">
<option id="extra1" value='1'>1</option>
<option id="extra2" value='2'>2</option>
</select>
<input style="width: 25%;margin-left:15px;" id="extraper">
```
and here is the javascript:
```
function ChooseContact(data) {
var x = 0;
var y = 0;
var e = obj.id.toString();
if (e == 'tb1') {
x = Number("PHP 299");
y = document.getElementById ("extraper").value = x;
}
};
```
I'm sure that my javascript is wrong. Can you help me with it? | 2017/02/26 | [
"https://Stackoverflow.com/questions/42469945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7415564/"
] | To get int value from user user:
```
int a;
scanf("%d",&a);
```
scanf uses different specifiers:
%d integer
%f Float
%d double
%c char | Use correct format specifiers for their respective data types
```
float %f
double %lf
int %d or %i
unsigned int %u
char %c
char * %s
long int %ld
long long int %lld
``` |
42,469,945 | I have two input boxes on my form.
One is a dropdown select and the other is the textbox.
I need to update the textbox value depending on what is chosen on the select box.
For example, if I choose "1" on select box, the textbox value should have "299.00" and if I choose "2", the textbox value should be "399.0"
Can you help me on editing the code? Thank you in advanced.
Here is my html code:
```
<select style="width: 25%;height:25px;margin-left:15px;" onchange="ChooseContact(this)">
<option id="extra1" value='1'>1</option>
<option id="extra2" value='2'>2</option>
</select>
<input style="width: 25%;margin-left:15px;" id="extraper">
```
and here is the javascript:
```
function ChooseContact(data) {
var x = 0;
var y = 0;
var e = obj.id.toString();
if (e == 'tb1') {
x = Number("PHP 299");
y = document.getElementById ("extraper").value = x;
}
};
```
I'm sure that my javascript is wrong. Can you help me with it? | 2017/02/26 | [
"https://Stackoverflow.com/questions/42469945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7415564/"
] | In the above program, the `scanf()` reads but does not assign the value due to the `*` format specifier. As a result, whatever is the value of a (which is not initialized) is produced as output by `printf()`. In this case, 67 is the garbage value. | The \* tells scanf to read in but ignore the input. Take a look at <http://www.cplusplus.com/reference/cstdio/scanf/> . why it always prints 67 you might need to step through a debugger to see what the int is initialized with and how that changes. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.