qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
30,164,479 | Here is html code for bootstrap icon, Bootstrap v3.3.4
```
<span class="glyphicon glyphicon-briefcase" aria-hidden="true"></span>
```
this html code is working fine with all browsers, i can see briefcase icon properly. But with same code after developing in MVC Platfrom i can't see briefcase icon on IE and Safari (Windows). this problem with few other icon also like `content = "\e136"`, `content = "\e142"`
Developed Code in MVC:

Simple HTML Code
 | 2015/05/11 | [
"https://Stackoverflow.com/questions/30164479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4886703/"
] | Maybe this post will answer your question : [here](https://github.com/twbs/bootstrap/issues/9962)
adding
```
<!--[if lt IE 9]>
<script src="html5shiv.js"></script>
<script src="respond.min.js"></script>
<![endif]-->
```
Could solve your problem, by the way, which IE version are you using?
EDIT: then it could be IE security issue : [here](https://stackoverflow.com/questions/25281286/bootstrap-3-2-0-glyphicons-are-not-displaying-in-internet-explorer) | You need to include
```
< !--[if lt IE 9] >
< script src="html5shiv.js">
< script src="respond.min.js">
< ![endif]-- >
```
Or
```
<link rel="stylesheet" media="screen" href="/css/glyphicons/glyphicons.min.css" >
```
OR
```
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
``` |
72,417,934 | Is there a way to melt 2 columns and take there sums as value . For example
```
df <- data.frame(A = c("x", "y", "z"), B = c(1, 2, 3), Cat1 = c(1, 4, 3), New2 = c(4, 4, 4))
```
Expected output
```
New_Col Sum
Cat1 8
New2 12
``` | 2022/05/28 | [
"https://Stackoverflow.com/questions/72417934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16935119/"
] | Or using `base R` with `colSums` after selecting the columns of interest and then convert the named vector to data.frame with `stack`
```
stack(colSums(df[c("Cat1", "New2")]))[2:1]
ind values
1 Cat1 8
2 New2 12
``` | Of course
```r
df %>%
summarise(across(starts_with('Cat'), sum)) %>%
pivot_longer(everything(), names_to = 'New_Col', values_to = 'Sum')
```
```
# A tibble: 2 × 2
New_Col Sum
<chr> <dbl>
1 Cat1 8
2 Cat2 12
``` |
19,931,756 | I know the partial submit is used in icefaces 1.x, singlesubmit in icefaces 2.x and the tag in icefaces 3.x.
May someone tell me what is the substantial difference between them?
thanks. | 2013/11/12 | [
"https://Stackoverflow.com/questions/19931756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2983595/"
] | Both partialSubmit and singleSubmit does the same thing. But in different ways.
Here is a typical form scenario:
user sees a form and starts interacting. Those forms have some fields. Some of those fields are required and are necessary to process the form. Other fields are optional.
When using partialSubmit, when a user leaves a field(onblur), iceface internally makes all other fields as non required so that the overall form can be submitted. Now since all other fields are optional and only the present field that you onblurred was required, icefaces can process the form. So it does all the validation checks and changes other elements that might have been affected and renders the whole page again with new changes. But here is the thing. The other fields that were deliberately made optional by icefaces, they also have their own validation mechnanisms. So when the form is processed, those field will show errors that they are not filled, or the password field cannot be null and all that. But since the user has not engaged other fields of the form, these errors should not be triggerred. This was the drawback of partialSubmit.
In singleSubmtit, they corrected this. In here, your field is taken and is sepately validated without affecting other fields or triggering their errors.
Hope you have understood this. If not, this link will help
```
www.icesoft.org/wiki/display/ice/single+submit
``` | <http://www.icesoft.org/wiki/display/ICE/Using+Single+Submit>
The SingleSubmit tag is a replacement by PartialSubmit, according to ICESoft information.
Cheers! |
14,246 | I have a couple questions for those more familiar. Most of my instances have been running Antelope despite having support for Barracuda.
I was looking to play around with some compresses innodb tables. My understanding is this is only available under the Barracuda format.
1. I see innodb\_file\_format is dynamic so I can just switch over with out a bounce. Are there any implications of doing this I should be aware of. All I can tell is that means new tables or subsequently altered will be created with that format. Is this all correct?
2. I was hoping to have to not go through and convert all my tables. Is is kosher to have antelope and barracude tables coexisting in the same tablespace? Even if it *works* are there any gotcha's to look out for?
From what I've read and gathered from my tests the answers are: Yes. Yes. I'm not sure.
**Update**
I've been running w/ some Dynamic and some Compressed tables in various instances since this post with out issue. Further I neglected to read <http://dev.mysql.com/doc/refman/5.5/en/innodb-file-format-identifying.html> at the time.
>
> After you enable a given innodb\_file\_format, this change applies only
> to newly created tables rather than existing ones. If you do create a
> new table, the tablespace containing the table is tagged with the
> “earliest” or “simplest” file format that is required for the table's
> features. For example, if you enable file format Barracuda, and create
> a new table that is not compressed and does not use
> ROW\_FORMAT=DYNAMIC, the new tablespace that contains the table is
> tagged as using file format Antelope.
>
>
>
So tables will be created as Antelope even if you allow Barracuda. The mixing is unavoidable unless you specify every table as row\_format dynamic or a compressed table.
There is no indication you should do a complete dump and reload when introducing your first Barracuda table (such as is recommended when [upgrading major versions of mysql](http://dev.mysql.com/doc/refman/5.5/en/upgrading-from-previous-series.html)) | 2012/03/02 | [
"https://dba.stackexchange.com/questions/14246",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/3423/"
] | So I'm answering this question almost 4 years late:
* InnoDB file formats were conceived at a time when InnoDB was independent of the MySQL Server (for example: MySQL 5.1 could run two different versions of InnoDB).
* The reason why you would not want to run Barracuda (in 2012) is that it could reduce flexibility in downgrading MySQL (i.e. after a failed upgrade, you want to move back to a version that can not read a newer format). i.e. there should be no technical reasons why Antelope is better.
* In MySQL 5.7 the `innodb_file_format` option was deprecated. Since MySQL and InnoDB are no longer independent, and thus InnoDB can use the MySQL rules of upgrades and what backwards compatibility is required. No confusing setting required!
* In MySQL 5.7, the default switched to `Barracuda/DYNAMIC`. Since all currently supported releases of MySQL can read this format, it is safe to move away from Antelope and still offer downgrade.
* On a MySQL 5.7 server, Antelope tables will be upgraded to `Barracuda/DYNAMIC` on the next table rebuild (OPTIMIZE TABLE etc). That is unless they were specifically created with `ROW_FORMAT=oldrowformat`.
* In MySQL 8.0, the option `innodb_file_format` is removed.
---
MySQL 5.7 also introduces [the option `innodb_default_row_format`](https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_default_row_format), which defaults to DYNAMIC. This addresses the point in your update. | If you really want to play with InnoDB using the Barracuda format, you should mysqldump everything to something like /root/MySQLData.sql. That makes the data file format independent.
Use another MySQL instance with a fresh ibdata1 and innodb\_file\_per\_table (optional, my personal preference). Change the file format with ibdata1 empty. Then, reload /root/MySQLData.sql and play with the data.
I have heard slight horror stories about PostgreSQL having to tweek settings to get a 8.2.4 database to work with 9.0.1 binaries. The same story could apply if we tried make both file formats reside in the same system tablespace (ibdata1) and/or `.ibd` file if we are aware of such settings.
As far as being kosher...
* Nobody should store meat and dairy in the same refrigerator
* Nobody should put a bull and an ass under the same yoke (Deuteronomy 22:10)
* Nobody should store `Antelope` and `Barracuda` inside the same ibdata1
UPDATE 2013-07-05 14:26 EDT
===========================
I just answered this question in ServerFault : [Setting MySQL INNODB Compression KEY\_BLOCK\_SIZE](https://serverfault.com/a/521143/69271). This made me look back for any questions I answered in the DBA StackExchange had discussed the `Barracuda` format and I found this old post of mine. I will place the same information here...
According to the [**MySQL Documentation**](http://dev.mysql.com/doc/refman/5.5/en/innodb-compression-internals.html) on InnoDB Compression for Barracuda
>
> **Compression and the InnoDB Buffer Pool**
>
>
> In a compressed InnoDB table, every compressed page (whether 1K, 2K,
> 4K or 8K) corresponds to an uncompressed page of 16K bytes. To access
> the data in a page, InnoDB reads the compressed page from disk if it
> is not already in the buffer pool, then uncompresses the page to its
> original 16K byte form. This section describes how InnoDB manages the
> buffer pool with respect to pages of compressed tables.
>
>
> To minimize I/O and to reduce the need to uncompress a page, at times
> the buffer pool contains both the compressed and uncompressed form of
> a database page. To make room for other required database pages,
> InnoDB may “evict” from the buffer pool an uncompressed page, while
> leaving the compressed page in memory. Or, if a page has not been
> accessed in a while, the compressed form of the page may be written to
> disk, to free space for other data. Thus, at any given time, the
> buffer pool may contain both the compressed and uncompressed forms of
> the page, or only the compressed form of the page, or neither.
>
>
> InnoDB keeps track of which pages to keep in memory and which to evict
> using a least-recently-used (LRU) list, so that “hot” or frequently
> accessed data tends to stay in memory. When compressed tables are
> accessed, InnoDB uses an adaptive LRU algorithm to achieve an
> appropriate balance of compressed and uncompressed pages in memory.
> This adaptive algorithm is sensitive to whether the system is running
> in an I/O-bound or CPU-bound manner. The goal is to avoid spending too
> much processing time uncompressing pages when the CPU is busy, and to
> avoid doing excess I/O when the CPU has spare cycles that can be used
> for uncompressing compressed pages (that may already be in memory).
> When the system is I/O-bound, the algorithm prefers to evict the
> uncompressed copy of a page rather than both copies, to make more room
> for other disk pages to become memory resident. When the system is
> CPU-bound, InnoDB prefers to evict both the compressed and
> uncompressed page, so that more memory can be used for “hot” pages and
> reducing the need to uncompress data in memory only in compressed
> form.
>
>
>
Notice that the InnoDB Buffer Pool has to load data pages and index pages read to fulfill queries. When reading a table and its indexes for the first time, the compressed page must be uncompressed to 16K. That means you will have twice as much data content in the buffer pool, the compressed and uncompressed data page.
If this duplication of data content is going on in the Buffer Pool, you need to increase [**innodb\_buffer\_pool\_size**](http://dev.mysql.com/doc/refman/5.6/en/innodb-parameters.html#sysvar_innodb_buffer_pool_size) by a small linear factor of the new compression rate. Here is how:
SCENARIO
========
* You have a DB Server with a 8G Buffer Pool
* You ran compression with `key_block_size=8`
+ `8` is `50.00%` of `16`
+ `50.00%` of `8G` is `4G`
+ raise `innodb_buffer_pool_size` to `12G` (`8G` + `4G`)
* You ran compression with `key_block_size=4`
+ `4` is `25.00%` of `16`
+ `25.00%` of `8G` is `2G`
+ raise `innodb_buffer_pool_size` to `10G` (`8G` + `2G`)
* You ran compression with `key_block_size=2`
+ `2` is `12.50%` of `16`
+ `12.50%` of `8G` is `1G`
+ raise `innodb_buffer_pool_size` to `9G` (`8G` + `1G`)
* You ran compression with `key_block_size=1`
+ `1` is `06.25%` of `16`
+ `06.25%` of `8G` is `0.5G` (`512M`)
+ raise `innodb_buffer_pool_size` to `8704M` (`8G` (`8192M`) + `512M`)
**MORAL OF THE STORY** : The InnoDB Buffer Pool just needs additional breathing room when handling compressed data and index pages. |
5,108,555 | I want to convert a List to a List so that each object on my new list includes the first element of each String[].
Do you know if this is possible to do in java?
for example:
```
public List<String[]> readFile(){
String[]array1={"A","1.3","2.4","2.3"};
String[]array2={"B","1.43","3.4","2.8"};
String[]array3={"C","5.23","2.45","2.9"};
List<String[]>ReadFile= new ArrayList<String[]>();
ReadFile.add(array1);
ReadFile.add(array2);
ReadFile.add(array3);
return ReadFile;
}
```
Now I want a method which will take the List ReadFile from above to somehow split the arrays of strings into an ID which will be the first element "A", "B", "C" and another part which would be the string array of numbers which I will put through another method to convert numbers from String to type Double. I have already got the method to convert to double but I need to be able to keep track of the ID field because the ID field will be used to identify the array of numbers.
A friend suggested that I create an Object where each objects has one part as a String ID and the other part as an array. That is the part which I do not know how to do.
Can anybody help please?
below is the method declaration which I believe I should have so the return type will be List where each array has been converted to an Object with two parts.
```
public List<Object> CreateObject(List<String[]>ReadFile){
}
```
Thanks,
Jetnori.
Hi all, Thank you for taking your time to help.
I can see the benefit of using HashTables. I am as of now trying to implement it. I know i might be sidetracking a little but just to explain what I am trying to do:
In my project I have CSV file with data about gene expression levels. The method that I use from OpenCSV to read the file returns a List(String[]) where each String[] is one row in the file. The first element of each row is variable name (recA, ybjE etc). The rest of the row will be numbers data related to that variable. I want to calculate Pearson's correlation between each of the number arrays. The method which I have got implemented already does that for me but the problem that I have now is that I had to remove the string values from my arrays before I could convert to double by iterating over the array. After I have managed to calculate the correlation between each array of doubles by still keeping the ID linked to the row, I want to be able to draw an undirected node graph between the genes that have a correlation higher than a threshold which I will set (for example correlation higher than 0.80). I don't know if i am biting more than i can chew but I have 30 days to do it and I believe that with the help of people like you guys I will get through it.
Sorry for going on for a bit.
thanks,
Jetnori. | 2011/02/24 | [
"https://Stackoverflow.com/questions/5108555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/507079/"
] | I agree with the answer Alb provided, however this is what your friend has suggested, first you need a class to represent the data. I have included a constructor that parses the data and one that accepts already parsed data, depending on how you like to think of things.
```
public class NumberList {
private double[] numbers;
private String key;
public NumberList(Strig key, double[] numbers){
this.ley = key;
this.numbers = numbers;
}
public NumberList(String[] inputList) {
key = inputList[0];
numbers = new double[inputList.length-1];
for(int i=1;i<inputList.length;i++){
numers[i-1] = Double.parseDouble(inputList[i]);
}
}
public String getKey() {
return key;
}
public double[] getNumbers() {
return numbers;
}
}
```
Then you need your function to generate the list:
```
public List<NumberList> CreateObject(List<String[]> ReadFile){
ArrayList<NumberList> returnList = new ArrayList<NumberList>(ReadFile.size());
for (String[] input : ReadFile) {
returnList.add(new NumberList(input));
}
return returnList;
}
```
Note this uses the constructor that parses the data, if you use the other constructor then the "CreateObject" function would need to include the parsing logic.
Finally on a side note the standard convention in java is that the only thing that is capitalized are class names and final static fields (which appear in all caps sepearted by underscores), so conventionally the method signature would be:
```
public List<NumberList> createObject(List<String[]> readFile){
...
}
``` | I don't understand your goal, but for 'an object with 2 parts' you might consider storing them in a Hashtable: <http://download.oracle.com/javase/6/docs/api/java/util/Hashtable.html> |
9,932,972 | I am working with a callback function going from unmanged code to my managed C# code. The callback has a parameter `void* eventData`. EventData could be several different struct types. In my C# code I define eventData as an `IntPtr` and use `Marshal.PtrToStructure` to get the struct. For most of the structs I have no issues. However, I am running into issues marshaling this one:
```
//! Structure for dose parameters
typedef struct
{
//! the dose in µGrays
float dose;
unsigned short nbParameters;
//! the corresponding parameters specified in the .ini file
struct Parameters
{
//! parameter text
const char* text;
//! parameter value
float value;
} * parameters;
} DoseParameters;
```
Here is my C# definition for the struct:
```
/// <summary>
/// Structure for dose parameters
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct DoseParameters {
//! the dose in µGrays
public float dose;
public ushort nbParameters;
//! the corresponding parameters specified in the .ini file
[StructLayout(LayoutKind.Sequential)]
public struct Parameters{
//! parameter text
public string text;
//! parameter value
public float value;
}
[MarshalAs(UnmanagedType.ByValArray)]
public Parameters[] parameters;
}
```
The dose and nbParameters values are converted correctly. It's the Parameters array that I am struggling with. The length is always one, and for that one instance, the Parameters.text is nothing intelligible, and Parameters.value is far bigger than it should be.
It seems like it is something to do with the char \* being an indeterminate length. Although, I'm new to the StructLayout/MarshalAs stuff so not too sure about it all. I've played with various MarshalAs, LayoutKind.Explicit, and FieldOffset combinations, but have had not success (obviously). I've done some searching and haven't found anything that is similar to my situation. | 2012/03/29 | [
"https://Stackoverflow.com/questions/9932972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55638/"
] | ```
return this.substr(0, index) + char + this.substr(index + char.length);
```
`char.length` is zero. You need to add `1` in this case in order to skip character. | So basically, another way would be to:
1. Convert the string to an array using `Array.from()` method.
2. Loop through the array and delete all `r` letters except for the one with index 1.
3. Convert array back to a string.
```js
let arr = Array.from("crt/r2002_2");
arr.forEach((letter, i) => { if(letter === 'r' && i !== 1) arr[i] = "" });
document.write(arr.join(""));
``` |
65,998,838 | I'm currently having an issue with updating a nested serializer field, the dict value provided is being thrown away and mapped to an empty dict on the code side
Serializer:
```
class OrganizationSerializer(QueryFieldsMixin, BaseSecuritySerializer):
class Meta:
model = Organization
fields = ("id", "name")
depth = 0
class UsersSerializer(QueryFieldsMixin, BaseSecuritySerializer):
organizations = OrganizationSerializer(many=True)
class Meta:
model = Users
fields = '__all__'
depth = 0
def update(self, instance: ReportSchedule, validated_data):
print("validated_data:", validated_data)
...
```
REST Request:
METHOD: Patch
```
{
"organizations": [{"id": 10}]
}
```
Outcome of print statement
```
validated_data: {'organizations': [OrderedDict()]}
``` | 2021/02/01 | [
"https://Stackoverflow.com/questions/65998838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647394/"
] | It's because the 'id' field in OrganizationSerializer is read\_only, you can check it yourself in python manage.py shell
```
test = OrganizationSerializer()
print(repr(test))
``` | Using tempresdisk's method above, the serializer should look like this
```
OrganizationSerializer():
id = IntegerField(label='ID', read_only=True)
...
```
Overriding that field in the serializer and removing the `read_only=True` should do the trick.
```
class OrganizationSerializer(QueryFieldsMixin, BaseSecuritySerializer):
id = IntegerField(label='ID')
class Meta:
model = Organization
fields = ("id", "name")
depth = 0
``` |
24,372,931 | I have a site running locally on MySQL i want to run it on H2 database. I have just run h2.jar file for console on the browser but whenever I Log in I have seen the list `jdbc:h2:/var/www/mysite/data/db; MODE=MySQL, information_schema and users.`I can create tables in it but don't know how to create new database?
I am using Mode = MySQL
type = H2 Database Engine in Embedded mode. | 2014/06/23 | [
"https://Stackoverflow.com/questions/24372931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2539746/"
] | From <http://www.h2database.com/html/tutorial.html#creating_new_databases>,
>
> By default, if the database specified in the URL does not yet exist, a
> new (empty) database is created automatically. The user that created
> the database automatically becomes the administrator of this database.
>
>
> | The settings of the H2 Console are stored in a configuration file called `.h2.server.properties` in your user home directory. For Windows installations, the user home directory is usually `C:\Documents and Settings\[username]` or `C:\Users\[username]`. The configuration file contains the settings of the application and picked up when the H2 Console is started.
>
> Below config to create a new database on startup:
>
>
>
1. add newline in property file.
`0=Generic H2 (Server)|org.h2.Driver|jdbc\:h2\:tcp\://localhost/~/db_name|sa`
2. open the `command prompt` go to the `\bin` directory where h2 has installed:
`e.g. cd C:\Program Files (x86)\H2\bin`
3. and run following the command
`java -cp h2-1.4.194.jar org.h2.tools.Server`.
**Other General Settings:**
`webAllowOthers`: allow other computers to connect.
`webPort`: the port of the H2 Console
`webSSL`: use encrypted TLS (HTTPS) connections. |
2,678,138 | I am trying to sign a token object using SHA1.
I am using bouncycastle as the security provider.
Whenever the program tries to sign something it gives me this error.
```
java.security.SignatureException: java.lang.IllegalArgumentException: input data too large.
```
What is the maximum size for signing something?
Do you have any suggestions about how I can sign this object? | 2010/04/20 | [
"https://Stackoverflow.com/questions/2678138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321651/"
] | The input size is limited to the size of the key. If you use a 1024 bit key, you are limited to 128 bytes.
Typically, you are signing the digest (hash value), not the actual data. | To fix that error one just need to use a larger key size. For example, if SHA 512 bit is chosen, the key could be a 1024 bit one. But you will fail with a key of the same (512) or lesser length.
BouncyCastle just gives us an unusable error message. But the std lib does its job right. Compare them:
```
// using a 512 bit key here
// leads to this error message if Sun's standard provider is used
Signature sig = Signature.getInstance("SHA512withRSA", "SunRsaSign");
rsa.initSign(privateKey);
rsa.update(data);
rsa.sign();
java.security.InvalidKeyException: Key is too short for this signature algorithm
at sun.security.rsa.RSASignature.initCommon(RSASignature.java:129)
at sun.security.rsa.RSASignature.engineInitSign(RSASignature.java:111)
at sun.security.rsa.RSASignature.engineInitSign(RSASignature.java:101)
at java.security.Signature$Delegate.engineInitSign(Signature.java:1127)
at java.security.Signature.initSign(Signature.java:511)
// using a 512 bit key here
// leads to this error message if the BounceCastle provider is used
Signature sig = Signature.getInstance("SHA512withRSA", "BC");
...
java.security.SignatureException: java.lang.IllegalArgumentException: input data too large
at org.bouncycastle.jce.provider.JDKDigestSignature.engineSign(Unknown Source)
at java.security.Signature$Delegate.engineSign(Signature.java:1160)
at java.security.Signature.sign(Signature.java:553)
``` |
46,094 | I am transitioning from mountain bike shoes to road bike shoes. *A marked difference is the limitation of versatility in cleat placement.* I prefer to have my cleat as **far up and to the inner side of my foot as possible - pretty much at the balls of my feet**. This was possible with my mountain bike shoes but no longer.
It feels weird to have the cleat so centered on my foot. I feel like I can't use my calves as strategically now. Is this because it's more efficient to have the cleat central to the foot? Looking for explanation or advice. Thanks! | 2017/04/07 | [
"https://bicycles.stackexchange.com/questions/46094",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/20588/"
] | >
> I am transitioning from mountain bike shoes to road bike shoes. A marked difference is the limitation of versatility in cleat placement. I prefer to have my cleat as far up and to the inner side of my foot as possible - pretty much at the balls of my feet.
>
>
>
Typical road shoes use three bolts holes, with the positions of those holes being static (as opposed to mountain bike that have two bolt pattern in a slot that allows for forward/aft changes). In a road setup the ability to adjust cleat position (forward/aft or inboard/outboard) comes from the design of the cleat itself. Some brands and systems offer a lot range in this regards while other less. In addition, road pedals themselves often come with different length axles which will help you fine tune the inboard/outboard position your foot (what you have been doing by shifting the cleat inboard on your mountain bike pedal and shoes). Finally, road bikes also tend to have a narrower stance (distance from the center-line to pedal; often termed the "Q-factor") relative to mountain bikes, meaning that all else being equal your feet will already be positioned closer to the center-line of the bike (relative to your mountain bike) before you even start tweaking your setup.
The take-home is that to get the same stance (distance from the center-line of the bike to the middle of your foot) the road cleat will be in a different inboard position relative to a mountain bike cleat position, so land-marking the mountain bike cleat position will not help you to get into the same final stance. Unless you are very good with measuring these types of distances you may need to start over fresh when setting up your road cleat position.
>
> It feels weird to have the cleat so centered on my foot. I feel like I can't use my calves as strategically now. Is this because it's more efficient to have the cleat central to the foot?
>
>
>
Finally, the current "thinking" for fore/aft position cleat position is to have the pedal axle between your first and fifth metatarsal, that is, just behind the "ball of your foot (which is the first metatarsal). This keeps your calves muscles more neutral (requiring them to work less), reducing fatigue and oxygen consumption. The calve muscles primarily play a postural role in cycling rather than generating any substantial power. If you are looking to generate more power, you should look into getting muscle recruitment from other muscle groups such as your glutes. | As previous poster said, a narrower Q factor on road bikes mean you may actually get the same width between your feet. Adjustment is normally in the cleats.
Also important: The cleats usually have a specific amount of float for rotation during the pedal stroke; Look KEO for example have cleats with both 0°, 4.5° and 9° float. Test which suit your knees.
Forward-aft position give different advantages and disadvantages. The traditional position with the cleat quite forward under the ball of the feet is supposed to maximize sprinting power. A position closer to the heel could give a lower total power usage and less fatigue. This is used for example by olympic winner Susanne Ljungskog (<https://en.wikipedia.org/wiki/Susanne_Ljungskog>).
I have done the same, and like it, especially for long distance brevets and when riding a recumbent. On my Northwave road shoes I actually had to drill new holes for the cleat to get this position. |
12,580,598 | I have [recently discovered and blogged about the fact](http://java.dzone.com/articles/throw-checked-exceptions) that it is possible to sneak a checked exception through the javac compiler and throw it where it mustn't be thrown. This compiles and runs in Java 6 and 7, throwing a `SQLException` without `throws` or `catch` clause:
```
public class Test {
// No throws clause here
public static void main(String[] args) {
doThrow(new SQLException());
}
static void doThrow(Exception e) {
Test.<RuntimeException> doThrow0(e);
}
static <E extends Exception> void doThrow0(Exception e) throws E {
throw (E) e;
}
}
```
The generated bytecode indicates that the JVM doesn't really care about checked / unchecked exceptions:
```
// Method descriptor #22 (Ljava/lang/Exception;)V
// Stack: 1, Locals: 1
static void doThrow(java.lang.Exception e);
0 aload_0 [e]
1 invokestatic Test.doThrow0(java.lang.Exception) : void [25]
4 return
Line numbers:
[pc: 0, line: 11]
[pc: 4, line: 12]
Local variable table:
[pc: 0, pc: 5] local: e index: 0 type: java.lang.Exception
// Method descriptor #22 (Ljava/lang/Exception;)V
// Signature: <E:Ljava/lang/Exception;>(Ljava/lang/Exception;)V^TE;
// Stack: 1, Locals: 1
static void doThrow0(java.lang.Exception e) throws java.lang.Exception;
0 aload_0 [e]
1 athrow
Line numbers:
[pc: 0, line: 16]
Local variable table:
[pc: 0, pc: 2] local: e index: 0 type: java.lang.Exception
```
The JVM accepting this is one thing. But I have some doubts whether *Java-the-language* should. Which parts of the JLS justify this behaviour? Is it a bug? Or a well-hidden "feature" of the Java language?
My feelings are:
* `doThrow0()`'s `<E>` is bound to `RuntimeException` in `doThrow()`. Hence, no `throws` clause along the lines of [JLS §11.2](http://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html#jls-11.2) is needed in `doThrow()`.
* `RuntimeException` is assignment-compatible with `Exception`, hence no cast (which would result in a `ClassCastException`) is generated by the compiler. | 2012/09/25 | [
"https://Stackoverflow.com/questions/12580598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/521799/"
] | All this amounts to exploiting the loophole that an unchecked cast to a generic type is not a compiler error. Your code is explicitly made type-unsafe if it contains such an expression. And since the checking of checked exceptions is strictly a compile-time procedure, nothing will break in the runtime.
The answer from the authors of Generics would most probably be along the lines of "If you are using unchecked casts, it's your problem".
I see something quite positive in your discovery—a break out of the stronghold of checked exceptions. Unfortunately, this can't turn existing checked-exception-poisoned APIs into something more pleasant to use.
How this can help
-----------------
At a typical layered application project of mine there will be a lot of boilerplate like this:
```
try {
... business logic stuff ...
}
catch (RuntimeException e) { throw e; }
catch (Exception e) { throw new RuntimeException(e); }
```
Why do I do it? Simple: there are no business-value exceptions to catch; any exception is a symptom of a runtime error. The exception must be propagated up the call stack towards the global exception barrier. With Lukas' fine contribution I can now write
```
try {
... business logic stuff ...
} catch (Exception e) { throwUnchecked(e); }
```
This may not seem like much, but the benefits accumulate after repeating it 100 times throughout the project.
Disclaimer
----------
In my projects there is high discipline regarding exceptions so this is a nice fit for them. **This kind of trickery is not something to adopt as a general coding principle**. Wrapping the exception is still the only safe option in many cases. | This example is documented in [The CERT Oracle Secure Coding Standard for Java](http://books.google.co.in/books?id=uLQhBkzH0DUC&pg=PA284&lpg=PA284&dq=Noncompliant+Code+Example+%28Generic+Exception%29&source=bl&ots=6BpVA0zRGW&sig=xQS5cBSwtnl9EJ1aZXSNrZ84Zzs&hl=en&sa=X&ei=zbVhUNDxGczJrAeRjYGoDg&ved=0CFEQ6AEwBg#v=onepage&q=Noncompliant%20Code%20Example%20%28Generic%20Exception%29&f=false) which documents several non compliant code examples.
**Noncompliant Code Example (Generic Exception)**
>
> An unchecked cast of a generic type with parameterized exception declaration can also result in unexpected checked exceptions. All such casts are diagnosed by the compiler unless the warnings are suppressed.
>
>
>
```
interface Thr<EXC extends Exception> {
void fn() throws EXC;
}
public class UndeclaredGen {
static void undeclaredThrow() throws RuntimeException {
@SuppressWarnings("unchecked") // Suppresses warnings
Thr<RuntimeException> thr = (Thr<RuntimeException>)(Thr)
new Thr<IOException>() {
public void fn() throws IOException {
throw new IOException();
}
};
thr.fn();
}
public static void main(String[] args) {
undeclaredThrow();
}
}
```
This works because `RuntimeException` is child class of `Exception` and you can not convert any class extending from `Exception` to `RuntimeException` but if you cast like below it will work
```
Exception e = new IOException();
throw (RuntimeException) (e);
```
The case you are doing is same as this.
Because this is explicit type casting this call will result in `ClassCastException` however compiler is allowing it.
Because of Erasure however in your case there is no cast involved and hence in your scenario it does not throw `ClassCastException`
In this case there is no way for compiler to restrict the type conversion you are doing.
However if you change method signature to below it will start complaining about it.
```
static <E extends Exception> void doThrow0(E e) throws E {
``` |
187,846 | Can these two sentences be used interchangeably?
>
> 1. He reminds me of me.
> 2. He reminds me of myself.
>
>
>
I think the second one is wrong. Am I right? | 2018/12/07 | [
"https://ell.stackexchange.com/questions/187846",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/65554/"
] | >
> Can these two sentences be used interchangeably?
>
>
>
Answer: I think not.
Between the two sentences, the second is more appropriate for formal writing. It is also the one that is widely used. See Ngram. The first sentence might sound a bit strange to some people, but it is often used in informal speech.
The first, *"he reminds me of me"*, is more likely to be used in poetry or literary work. It could be used for emphasis, or it could just be a matter of style, habit, or era. This similar post in ELU, [When to use “me” or “myself”?](https://english.stackexchange.com/questions/20151/when-to-use-me-or-myself), has some interesting details. Also take a look at this [usage note](https://www.dictionary.com/browse/myself) (when *myself* is used in place of *I/me*) in Dictionary.com.
If it is indeed used for emphasis, or if it is used stylistically, then the author has a specific reason to use it (i.e., the first version *"he reminds me of me"*). The use of "me" instead of "myself" serves a definite purpose. And therefore, in such circumstances, the two sentences are not interchangeable. The author prefers the first version; he is not indifferent between the two.
But an inexperienced user of English language (a new learner) may erroneously use them interchangeably (without having any specific reason for their choice).
This is strange: if you just search google news for *"reminds me of me"*, you will find many celebrities (actors, musicians, and athletes) use this version in their interviews. I suppose the reason for this is that (1) *"reminds me of ME!"* is more emphatic than the version with a dull "myself" or (2) they do so unknowingly (they don't know *myself* is more appropriate for a simple conversation).
>
> I think the second one is wrong. Am I right?
>
>
>
Answer: You are not. The second sentence, *"He reminds me of myself"*, is accurate.
Here are some definitions from Wikipedia:
* I - subjective pronoun - *a personal pronoun that is used as the subject of a verb*
* Me - objective pronoun - *a personal pronoun that is used typically as a grammatical object: the direct or indirect object of a verb, or the object of a preposition*
* Myself - reflexive pronoun - *a reflexive pronoun will end in ‑self or ‑selves, and refer to a previously named noun or pronoun* They can act as either objects or indirect objects (Grammarly).
Cambridge discusses reflexive pronouns [here](https://dictionary.cambridge.org/grammar/british-grammar/pronouns-reflexive-myself-themselves-etc). It says *"we often use reflexive pronouns when the subject and the object of the verb refer to the same person or thing."*
Collins says *"Myself is used as the object of a verb or preposition when the subject refers to the same person."*
>
> The 'rule' is by no means without exception: *John had his new dressing gown wrapped around him.* - Edwin Ashworth in [ELU](https://english.stackexchange.com/questions/343627/reflexive-pronoun-use-when-subject-is-a-subset-of-the-prepositional-object).
>
>
>
"Myself" is also used as an emphatic/intensive pronoun (e.g., I did the entire assignment *myself*, I swear.)
In your second sentence, "me" is the direct object pronoun of the verb "reminds" and "myself" is the object of the preposition "of".
This raises the question then, "What is the relationship between "me" and "myself" in the second sentence?"
The answer to this is in Alex\_ander's answer, *"Use 'myself' after a preposition... when the object of the preposition and the object pronoun are the same person."* This quoted material is here: [English Grammar: I, Me, Myself, and My.](http://www.englishteachermelanie.com/english-grammar-i-me-myself-and-my/) Please note that I can't verify the legitimacy of "Melanie"; I searched all her social media sites but I can't find a last name to look up her background (work experience, education, etc.)
What I understand is, "me" is the direct object here, and "myself" is the indirect object.
The second sentence is correct. Google Ngram below shows the usage between the two; it seems that the uses of "me of me" and "reminds me of me" are quite a bit lower than their counterparts with "myself".
[](https://i.stack.imgur.com/Ejd16.png)
[](https://i.stack.imgur.com/slp7u.png) | The *Cambridge Dictionary* provides a very helpful explanation of why "myself" is considered correct.
>
> Reflexive pronouns for same subject and object
> ----------------------------------------------
>
>
> We often use reflexive pronouns when the subject and the object of the verb refer to the same person or thing:
>
>
> * He cut **himself** on the broken glass.
> * She made **herself** a cup of tea and sat down in front of the television.
> * Parents often blame **themselves** for the way their children behave.
>
>
> We use a reflexive pronoun to make it clear who or what is being referred to.
>
>
> --- [*Cambridge Dictionary*](https://dictionary.cambridge.org/grammar/british-grammar/pronouns-reflexive-myself-themselves-etc) | [Archive.org](https://web.archive.org/web/20170828063741/http://dictionary.cambridge.org/grammar/british-grammar/pronouns/pronouns-reflexive-myself-themselves-etc)
>
>
>
In your examples:
>
> * Maybe: 1. He reminds me of me.
> * ✔️ **Yes:** 2. He reminds me of **myself**.
>
>
>
**Myself** is correct.
However, you may hear someone use "*He reminds me of me*" -- perhaps in movie dialogue -- because it sounds playful, unusual, colloquial (informal), and slightly incorrect on purpose. |
48,375,598 | I am building an application which uses authorization with Json Web Tokens. I'm building this application with Node.js, GraphQL and Apollo client V2 (and some other stuff, but those aren't related here). I have created a `login` resolver and a `currentUser` resolver that let me get the current user via a JWT. I later use that token and send it in my authorization headers and the results looks something like:
[](https://i.stack.imgur.com/XlEvn.png)
So that part is done! But here's what I'm having trouble with.
Me trying to explain the situation
----------------------------------
I'm using React for the frontend part of this project with the Apollo Client V2. And when I do the login mutation I do it like this. With formik I've created my `onSubmit`:
```
const response = await mutate({
variables: {
email: values.email,
password: values.password,
},
})
const token = response.data.login.jwt
localStorage.setItem('token', token)
history.push('/') // Navigating to the home page
```
And this is what I want back with the login mutation (just the token):
```
export const loginMutation = gql`
mutation($email: String!, $password: String!) {
login(email: $email, password: $password) {
jwt
}
}
`
```
To get the `currentUser`'s data I've put my `currentUser query` in my root router file. **Please apologize me for naming the component PrivateRoute. I haven't renamed it yet because I can't find a proper name for it. I'm sorry.** So in `/src/router/index.js` I have this:
```
// First the actual query
const meQuery = gql`
{
currentUser {
id
username
email
}
}
`
...
// A component that passess the currentUser as a prop, otherwise it will be null
const PRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props => {
return (
<Component
{...props}
currentUser={
rest.meQuery.currentUser ? rest.meQuery.currentUser : null
}
/>
)
}}
/>
)
}
// Another component that uses the meQuery so I later can access it if I use the PrivateRoute component.
const PrivateRoute = graphql(meQuery, { name: 'meQuery' })(PRoute)
// Using the PrivateRoute. And in my Home component I can later grap the currentUser via propsb
const App = () => (
<Router>
<div>
<PrivateRoute exact path="/" component={Home} />
...
```
In the `Home` component I grab the prop:
```
const { data: { loading, error, getAllPosts = [], currentUser } } = this.props
```
I pass it down to my `Navbar` component:
```
<Navbar currentUser={this.props.currentUser} />
```
And in the `Navbar` component I take the username if it exists:
```
const { username } = this.props.currentUser || {}
```
And then I render it.
This is what I'm having troubles with
-------------------------------------
My application is currently trying to get the `currentUser` when I get to the `/login` route. And after I've successfully loged in I get back the token, but the `currentUser query` is not being fetched again. Thefore I have to refresh my page to get the current user and all of it's values.
I have also created a little video that demonstrates what my problem is. I believe it will show you more clearly the problem than me trying to type it.
Here's the video: <https://www.youtube.com/watch?v=GyI_itthtaE>
I also want to thank you for reading my post and that you hopefully are going to help me. I have no idea why this is happening to me and I just can't seem to solve it. I've tried to write this question as best as I can, so sorry if it was confusing to read.
Thanks | 2018/01/22 | [
"https://Stackoverflow.com/questions/48375598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7284779/"
] | I think you might be able to solve this issue by setting the query's **FetchPolicy** to **"cache-and-network"**. You can read about fetch policies [here: "GraphQL query options.fetchPolicy"](https://www.apollographql.com/docs/react/basics/queries.html#graphql-config-options-fetchPolicy "GraphQL Queries - options.fetchPolicy")
in your specific case I think you can update this line
```
const PrivateRoute = graphql(meQuery, { name: 'meQuery' })(PRoute)
```
to this:
```
const PrivateRoute = graphql(meQuery, { name: 'meQuery', options: {fetchPolicy: 'cache-and-network'} })(PRoute)
```
Explanation
-----------
As stated in the documentation, the default policy is *cache-first*.
1. *currentUser* is queried the first time and it updates the cache.
2. You execute the login mutation, the **cache is not updated** without
you updating it (read about it [here: "Updating the cache after a
mutation"](https://www.apollographql.com/docs/react/basics/mutations.html#store-updates "Updating the cache after a mutation")).
3. *currentUser* query is executed again but due to the default *cache-first* policy the outdated result will be retrieved only from the cache.
From the [official documentation](https://www.apollographql.com/docs/react/basics/queries.html#graphql-config-options-fetchPolicy "GraphQL Queries - options.fetchPolicy"):
>
> **cache-first**: This is the default value where we always try reading
> data from your cache first. If all the data needed to fulfill your
> query is in the cache then that data will be returned. Apollo will
> only fetch from the network if a cached result is not available. This
> fetch policy aims to minimize the number of network requests sent when
> rendering your component.
>
>
> **cache-and-network**: This fetch policy will have Apollo first trying to read data from your cache. If all the data needed to fulfill your
> query is in the cache then that data will be returned. However,
> regardless of whether or not the full data is in your cache this
> fetchPolicy will always execute query with the network interface
> unlike cache-first which will only execute your query if the query
> data is not in your cache. This fetch policy optimizes for users
> getting a quick response while also trying to keep cached data
> consistent with your server data at the cost of extra network
> requests.
>
>
>
in addition to these two there are two more policies: 'network-only' and 'cache-only' here's the [link to the documentation](https://www.apollographql.com/docs/react/basics/queries.html#graphql-config-options-fetchPolicy "GraphQL Queries - options.fetchPolicy") | for me it worked when I refetched the currentUser query in my login mutation. I added my code below. Maybe it helps:
```
onSubmit(event) {
event.preventDefault();
const { email, password } = this.state;
this.props
.mutate({
variables: { email, password },
update: (proxy, { data }) => {
// Get Token from response and set it to the localStorage
localStorage.setItem('token', data.login.jwt);
},
refetchQueries: [{ query: currentUser }]
})
.catch((res) => {
const errors = res.graphQLErrors.map(error => error.message);
this.setState({ errors });
});
}
``` |
14,937,532 | I am working with an array of roughly 2000 elements in C++.
Each element represents the probability of that element being selected randomly.
I then have convert this array into a cumulative array, with the intention of using this to work out which element to choose when a dice is rolled.
Example array:
{1,2,3,4,5}
Example cumulative array:
{1,3,6,10,15}
I want to be able to select 3 in the cumulative array when numbers 3, 4 or 5 are rolled.
The added complexity is that my array is made up of long doubles. Here's an example of a few consecutive elements:
0.96930161525189592646367317541056252139242133125662803649902343750
0.96941377254127855667142910078837303444743156433105468750000000000
0.96944321382974149711383993199831365927821025252342224121093750000
0.96946143938926617454089618153290075497352518141269683837890625000
0.96950069444055009509463721739663810694764833897352218627929687500
0.96951751803395748961766908990966840065084397792816162109375000000
This could be a terrible way of doing weighted probabilities with this data set, so I'm open to any suggestions of better ways of working this out. | 2013/02/18 | [
"https://Stackoverflow.com/questions/14937532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1890050/"
] | You can use [`partial_sum`](http://en.cppreference.com/w/cpp/algorithm/partial_sum):
```
unsigned int SIZE = 5;
int array[SIZE] = {1,2,3,4,5};
int partials[SIZE] = {0};
partial_sum(array, array+SIZE, partials);
// partials is now {1,3,6,10,15}
```
The value you want from the array is available from the partial sums:
```
12 == array[2] + array[3] + array[4];
12 == partials[4] - partials[1];
```
The total is obviously the last value in the partial sums:
```
15 == partial[4];
``` | Ok I think I've solved this one.
I just did a binary split search, but instead of just having
```
if (arr[middle] == value)
```
I added in an OR
```
if (arr[middle] == value || (arr[middle] < value && arr[middle+1] > value))
```
This seems to handle it in the way I was hoping for. |
44,187,014 | I'm doing a footer that is separated to 3 blocks.
But they haven't equal height, and so border-right line's height isn't equal too.
screen: [Not equal height of elements](https://i.stack.imgur.com/BIHRK.png)
What to do with it? What is wrong with it?
My way to handle this problem (3 blocks of content centered in one footer block) is bad?
Code:
```
<html>
<head>
</head>
<body>
<style>
#footer {
height: auto;
width: 100%;
background-color: #55585d;
margin-top: 30px;
display: table;
}
#blocks {
margin-left: auto;
margin-right: auto;
width: 1120px;
}
.f-block {
box-sizing: border-box;
width: 373px;
float: left;
padding: 30px;
text-align: center;
border-right: 1px solid #000000;
}
</style>
<footer>
<div id="footer">
<div id="blocks">
<nav>
<div class="f-block">
asdasdaasdfghfghfghfghfghfghfghf
</div>
</nav>
<div class="f-block">asdasdaaaaaaaaaaa aaaaaaaaaaaaaa aaaaaaaaaaasada
</div>
<div class="f-block">asdasdasd aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaa aaaaaaaa
</div>
</div>
</div>
</footer>
</body>
</html>
``` | 2017/05/25 | [
"https://Stackoverflow.com/questions/44187014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7902860/"
] | `footer` and `#footer` seem redundant, so I combined those. And `.f-block` should be on your `nav` since it's adjacent to the other `.f-block`s. And adding `display: flex` to the parent will cause them to stretch their height to match their siblings.
```css
#footer {
height: auto;
width: 100%;
margin-top: 30px;
background-color: #55585d;
}
#blocks {
margin-left: auto;
margin-right: auto;
width: 1120px;
display: table;
}
.f-block, nav {
box-sizing: border-box;
width: 373px;
padding: 30px;
text-align: center;
border-right: 1px solid #000000;
display: table-cell;
}
```
```html
<footer id="footer">
<div id="blocks">
<nav>
<div>
asdasdaasdfghfghfghfghfghfghfghf
</div>
</nav>
<div class="f-block">asdasdaaaaaaaaaaa aaaaaaaaaaaaaa aaaaaaaaaaasada
</div>
<div class="f-block">asdasdasd aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaa aaaaaaaa
</div>
</div>
</footer>
``` | Issue here is content of the div. white-space is not handled properly. change it to something else.
```
<footer>
<div id="footer">
<div id="blocks">
<nav>
<div class="f-block">asdasdasd aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaa aaaaaaaa
</div>
</nav>
<div class="f-block">asdasdaaaaaaaaaaa aaaaaaaaaaaaaa aaaaaaaaaaasada
</div>
<div class="f-block">asdasdasd aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaa aaaaaaaa
</div>
</div>
</div>
</footer>
``` |
29,462,217 | I'm trying to get my fullcalendar.io event to show up at the bottom of the day instead of in the middle. I've been trying to modify different elements to vertical-align: "bottom" but nothing seems to work. Here is a link to my [**fiddle**](https://jsfiddle.net/4v65ggos/8/) that has different css overloaded calls to set the vertical-alignment to bottom for a calendar event. Currently the event is placed in the middle of the day, I want it at the bottom of the cell.
```js
$(document).ready(function() {
// page is now ready, initialize the calendar...
var eventsArray = [
{
title: 'Test1',
start: new Date()
},
{
title: 'Test2',
start: new Date(2015, 4, 21)
}
];
$('#calendar').fullCalendar({
// put your options and callbacks here
header: {
left: 'prev,next', //today',
center: 'title',
right: ''
},
defaultView: 'month',
editable: true,
allDaySlot: false,
selectable: true,
events: eventsArray
})
});
```
```css
//all the different things I've tried!!!!!!!
tbody {
vertical-align: bottom;
}
tr td.fc-event-container {
vertical-align: bottom;
}
td.fc-event-container {
vertical-align: bottom;
}
td {
vertical-align: bottom;
}
.fc-event-container {
vertical-align: bottom;
}
tr {
vertical-align: bottom;
}
```
```html
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.3.1/fullcalendar.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.3.1/fullcalendar.js"></script>
<div style="border:solid 2px red;">
<div id='calendar'></div>
</div>
```
I inspected the elements in the explorer window in Chrome and I'm not sure which element needs the vertical alignment set.
Here is a pic of the elements in Chrome.
 | 2015/04/05 | [
"https://Stackoverflow.com/questions/29462217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1186050/"
] | Two issues:
1) the containing element isn't 100% of the "cell" height (which is set by a second "skeleton" table)
2) the `vertical-align` is overriden, so we'll need to increase specificity
Here's the CSS that will set the height to 100%:
```
.fc-row .fc-content-skeleton {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.fc-content-skeleton table {
height: 100%
}
```
And finally, to increase specificity:
```
.fc-content-skeleton .fc-event-container {
vertical-align: bottom;
}
```
(Or, we could add `!important`)
An updated fiddle: <https://jsfiddle.net/4v65ggos/13/> | You can set a fixed height to the table element.
```
.fc-row table{
height:72px;
}
```
This though won't work well if the site you are working on it's **responsive**.
Make sure you apply height:100% to both elements, the table and its container.
```
.fc-content-skeleton,.fc-content-skeleton table{
height:100%;
}
``` |
46,615,083 | I'm having an issue in UWP using MVVM, where I have a `Combobox` with an `ItemsSource` bound to a collection of items in my ViewModel, and also in my VM is an item from that collection that `SelectedItem` is bound to.
I need to change both the items source and the selected item at will in my view model. The problem is, if the `SelectedItem` doesn't exist in the `ItemsSource` at any point in time, the binding for `SelectedItem` seems to break permanently.
Example:
Let's say I have a Comobox that is bound to my VM:
```
<ComoboBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />
```
Now in my ViewModel, I have:
```
public List<string> Items { get; set; } // Pretend these properties call on OnPropertyChanged
public string SelectedItem { get; set; }
public void Initialize() {
Items = new List<string> { "A", "B", "C", "D" };
SelectedItem = "B";
}
public void ChangeList() {
// This breaks the binding that the Combobox has with SelectedItem
Items = new List<string> { "E", "F", "G", "H" };
// This does nothing on the XAML side as the binding is already broken by this poing
SelectedItem = "H";
}
```
When initialized, the app will show "B" in the selected combo box. If in the code, say, I change it to "A", that will also reflect a change in the view. However, when I call `ChangeList()` the combo box will be set to blank and will ignore any changes I make in code behind.
Unfortunately in my case, setting `SelectedItem` to null before I update the source list does not fix my problem.
How would I go about changing the source and selected item in the VM? | 2017/10/06 | [
"https://Stackoverflow.com/questions/46615083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2272235/"
] | You can solve this mathematically.
To make sure that I understand what you want, I will summarize what you are asking. You want to find the smallest integer n so that:
3^3 − 39^2 + 360 + 20 ≥ 2.25^3 (1)
And any other integers bigger than n must also satisfy the equation (1).
**So here is my solution:**
(1) <=> 0.75^3 − 39^2 + 360 + 20 ≥ 0
Let f(n) = 0.75^3 − 39^2 + 360 + 20
f(n) = 0 <=> n1 = -0.05522 or n2 = 12.079 or n3 = 39.976
* If n < n1, f(n) < 0 (try this yourself)
* If n1 < n < n2, f(n) > 0 (the sign will alternate)
* If n2 < n < n3, f(n) < 0 (the sign will alternate, again)
* If n > n3, f(n) > 0
So to satisfy your requirements, the minimum value of n must be 40 | Think about it like this. After a certain point 3^3 − 39^2 + 360 + 20 will always be greater than or equal to n^3 for the simple fact that eventually 3n^3 will beat out the -39n^2. So F(n) will never dip below n^3 for an extremely large number. You don't have to put the minimum nO, just choose an extremely large number for nO, since the question is asking after a certain value for n, the statement will hold true for ever. Choose nO, for example, to be an extremely large number X, and then use an inductive proof where X is the base case. |
49,066 | I am presently using LAStools to analyse LiDAR data. Can LAStools classify the points into various features such as vegetation, roads, buildings etc? If so, how is it done? | 2013/01/25 | [
"https://gis.stackexchange.com/questions/49066",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/14594/"
] | LASTools can perform a ground classification using ["lasground"](http://www.cs.unc.edu/~isenburg/lastools/download/lasground_README.txt) and then can perform some limited feature classification using ["lasclassify"](http://www.cs.unc.edu/~isenburg/lastools/download/lasclassify_README.txt). The performance and quality of feature classification in point clouds is strongly influenced by the type of landscape collected. Some landscapes just do not lend themselves to acceptable automated results. The best feature classification is provided when the vendor performs a "hands on" approach where considerable editing is performed after a given ground/feature classification algorithm is applied.
I am not sure how many tools are implemented in the ArcGIS LAS Toolbox. You may want to look at the available [LAS commandline executable tools](http://www.cs.unc.edu/~isenburg/lastools/) for more detailed analysis.
If your data was collected in an area with forest canopy or topographic relief I would recommend using the [MCC algorithm](http://sourceforge.net/apps/trac/mcclidar/) for ground classification. This method uses a Thin Plate Spline and produces very good results. I am not overly fond of TIN based methods because of the surface bias, distortion and noise that they tend to produce. | I'm not familiar with lastools, typically a las dataset has a class column that classifies the various points, see image below:

If you cannot process in lastools, then you can definitely do this in [GRASS](http://grass.osgeo.org/grass70/manuals/v.in.lidar.html) or ArcGIS using [GeoCue](http://www.geocue.com/support/utilities.html) utility. |
118,843 | ```
b = nst[n_] :=
Length[NestWhileList[If[EvenQ[#], #/2, 3 # + 1] &,
n, # > 1 &]];
nn = 500;
With[{stps = Array[nst, nn]},
Table[Max[Take[stps, n]], {n, nn}]
]
```
I'm working with the following list and I am trying to find a fit so that it's always greater than the data rather then the normal fitting method used in the `FindFit` function:
```
FindFit[b, x + y*Log[z], {x, y}, z]
```
I like the ability to change the fitting model in the `FindFit` function but I can't figure out how to set it for what I want. Help would be appreciated. | 2016/06/19 | [
"https://mathematica.stackexchange.com/questions/118843",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/40388/"
] | Create the list `b` as you have shown.
```
nst[n_] := Length[NestWhileList[If[EvenQ[#], #/2, 3 # + 1] &, n, # > 1 &]]
b = With[{stps = Array[nst, nn]}, Table[Max[Take[stps, n]], {n, nn}]];
```
It looks like
```
ListPlot[b, PlotStyle -> Blue]
```

It is apparent that we want to locate the first point in each group of horizontal points and use that in the constraint.
Those points can be located as follows:
```
data = Transpose@Join[{Range[500], b}];
(* {{{1, 1}, {2, 2}, {3, 8}, ..., {500, 144}} *)
```
`data` is a list of `{index, b}` pairs.
Next locate the positions where there is a jump.
```
pos = Position[Differences[b], x_ /; x > 0] + 1
```
Build a list of constraints forcing the desired function to exceed the `y` value at those positions.
```
constraints =
Map[x + y*Log[#[[1]]] >= #[[2]] &, Extract[data, pos]]
(* {x + y Log[2] >= 2, x + y Log[3] >= 8, x + y Log[6] >= 9,
x + y Log[7] >= 17, x + y Log[9] >= 20, x + y Log[18] >= 21,
x + y Log[25] >= 24, x + y Log[27] >= 112, x + y Log[54] >= 113,
x + y Log[73] >= 116, x + y Log[97] >= 119, x + y Log[129] >= 122,
x + y Log[171] >= 125, x + y Log[231] >= 128, x + y Log[313] >= 131,
x + y Log[327] >= 144} *)
```
Use the constraints in `FindFit`.
```
solution =
FindFit[b, {x + y*Log[z], Sequence @@ constraints}, {x, y}, z]
(* {x -> 69.7139, y -> 12.8302} *)
```
Plot it to validate the solution
```
Show[
ListPlot[list, PlotStyle -> Blue],
Plot[Evaluate[x + y*Log[z] /. solution], {z, 1, 500},
PlotStyle -> Black]
]
```
 | I had the same idea as Jim Baldwin, as constraints are often implemented as penalty functions. Here is one that severely penalized any negative residual. The parameter `scale` might need to be adjusted to be a significant fraction of the range of the data values.
```
ClearAll[penalty];
penalty[residuals_?VectorQ, scale_: 10] :=
scale*Length@residuals*(1 - Sign@Min[residuals]);
```
Here's how to use it with `FindFit`:
```
scale = Max[b] - Min[b];
fit = FindFit[b, model = x + y*Log[z], {x, y}, z,
NormFunction -> (Norm[#1] + penalty[#1, scale] & ),
Method -> "NMinimize"]
```
It will warn that the norm is nonlinear and therefore nonlinear methods will be used.
```
Plot[model /. fit, {z, 1, Length@b},
Epilog -> {Red, Point@Table[{i, b[[i]]}, {i, Length@b}]}]
```

Check that the fitted model stays above the data:
```
model - u /. fit /. {z -> Range@Length@b, u -> b} // Min
(* 6.40443*10^-8 *)
``` |
46,453 | In a couple of jams I've been in recently there are players who play swing and jazz music but who play it as straight-eighths. Worse, they try to correct the other players who are swinging the beat because they hear it as unsteady.
What is a relatively tactful way of teaching these players how to swing in a group setting? | 2016/07/26 | [
"https://music.stackexchange.com/questions/46453",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/10635/"
] | Assuming these are informal jams, you just don't have the authority to fire incompetents. I think the only possibility is to endure the fact that the material will not be played correctly.
But do at least point out what "swing" means when they try to "correct" those who are playing it correctly. Is it tactless to teach someone the truth? | If you're playing straight and switch to playing swing, the 'and's move but the strong beats don't.
It might be that the players who are trying to play swung are pushing the strong beats around too, which would be disconcerting to the other players.
I'd suggest an exercise where everyone plays the same line (a fragment of a scale for instance) first straight and then again swung. You can also try clapping exercises like this, where you silently count the lower-case and then CLAP the upper case:
```
one-and two-and three-and four-CLAP
```
The 'ands' and the CLAP move around depending on whether your quavers are swung or not.
The other thing I tell my beginner brass band when they're playing swung quavers is to make the first note in each pair long, and to make gaps between all notes as short as they can, whilst still articulating every note and not slurring it. Without this reminder, the tendency is to play the first note of each pair too short - and the result is a very 'polite' performance. Once you lengthen the first note in each pair the performance has far more attitude and sounds much jazzier. |
20,792,724 | I have developed an email form that sends the data to a sql database. However, I noticed that there can be duplicate emails. Is there something I can add to my php or sql to prevent duplicate emails?
```
<?php
if (isset($_POST['submit']) && strlen($_POST['email'])>0 && strlen($_POST['city'])>0)
{
$good_input = true;
$email=$_POST['email'];
$city=$_POST['city'];
mysql_connect("host", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_query("INSERT INTO `launchpage` VALUES ('$email', '$city')");
}
?>
``` | 2013/12/26 | [
"https://Stackoverflow.com/questions/20792724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1691422/"
] | You could make the email the primary key for the table:
```
ALTER TABLE launchpage ADD PRIMARY KEY(email);
```
then use `REPLACE INTO` instead of `INSERT INTO`:
```
mysql_query("REPLACE INTO `launchpage` VALUES ('$email', '$city')");
```
REPLACE updates an existing record if the key exists, otherwise inserts a new record. The benefit is that the SQL query will not fail like when you try to insert on a UNIQUE index.
Before making the primary key email you'll need to get rid of the duplicates. See this post: [Delete Duplicate email addresses from Table in MYSQL](https://stackoverflow.com/questions/5935797/delete-duplicate-email-addresses-from-table-in-mysql) | You may try:
```
ALTER TABLE launchpage ADD UNIQUE (email);
``` |
10,617 | I'm aiming this question at anyone who has made it in the audio post production area. How did you get to where you are now? how did you start off and what steps did you take? It would also be good to hear from people just starting out and what you're doing towards gaining a career within audio post production. Look forward to hearing your answers. Thanks Adam. | 2011/09/30 | [
"https://sound.stackexchange.com/questions/10617",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/2368/"
] | I'd recommend checking out the [Soundworks bid on The Social Network](http://soundworkscollection.com/socialnetwork). They go into detail on how the club scene was designed with lots of layers of different distortions used. | Well I can talk to you about distortion in music mixing/engineering.
Distortion is the most useful tool of the mixing engineer, if you think about it you can only mix with distortion and EQ.
The first thing distortion does is coloring the sound and producing harmonics, The second thing is it compresses the sound in a more leveled fashion but judged by how much you distort the effect takes under consideration the actual dynamics, so, think about an envelope let's take a snare hit, the actual transient(or attack) gets really distorted and compressed, as the sound progresses and goes to sustain - decay the whole effect becomes more mellow.
Don't be afraid when distorting transients, there's no harm in it, the only thing you can trust in this is your ears.
Also distortion should be used everywhere, there's no bad distortion, even when you think a sound is trashed from it, try EQing to throw the junk/overtones away and mix it in parallel with the original signal to give that insane presence.
You have to keep in mind that any distortion effect is a non-linear effect!
Non linear in simple words mean that it can't be undone with the opposite, so for example if I take an EQ and boost 3K and right after use the same EQ but instead of boosting I use cut for the same exact amount, the sound remains unchanged right?
OK, now if you insert a non linear effect in the middle you never have the same sound again.
To explain myself, someone could say if I you use a compressor you'd also wouldn't have the same sound, well you would have the same sound but compressed, that said, distortion and non-linear effects change the core of the sound!
It's a very common practice (but not many people share it) to use EQ- non linear -EQ.
Let's use another example, let's say I really want to distort/alter a hihat, I go +30 db hi shelf -> distortion -> -30 db hi shelf (or according to taste). I managed to alter my sound in the frequency that I care about and then bring it back in a more normal (frequency-wise) state.
Distortion is super useful when mixing big bass! try this, distort your bass until you hear it going PRRRRRRRRRR, a point where you can actually hear the period of the singal, then just low pass it until you have the same effect but not the hi frequency trash. This creates a wide open and very well compressed bass.
Bass is the most sensitive area when distorting. It's the first thing that's gonna make you turn that knob back, sometimes it's your friend because if you have a nice balanced sound which just needs something extra, the bass is there to tell you when you've overdone it.
But, as we talked about pre-emphasis (or EQ - non linear - EQ) You can try pre emphasizing bass, which is actually what happens in the core of the audio transformer, try it on vocals, or on snare drums. I usually do it by really emphasizing close to 50 Hz and then taking it back.
In all of these FX chains the middle man is the non-linear friend, any type of distortion. Make your EQ and then just turn the knob to taste, it's the most intuitive knob in the studio!
Now, you might think I'm crazy, but these techniques are all over an analog studio, for example, dbx de-noiser is hi freq pre-emphasis -> compression -> Tape(non-linear) ->expansion -> hi freq de-emphasis. dbx has a lot of character, and I find it really cool! Also audio transformers core saturation is bass pre-emphasis - core saturation - de emphasis.and many many other examples.
Last super creative trick you can do, duplicate a track, distort the one, flip the phase to the other one and try to find the canceling spot with the fader (the place where you hear loss of sound and weird effects), playing a bit with this will drive you crazy when you think of the possibilities, this is called phase synthesis or at least I call it that way.
To sum everything up, distortion by itself is a self explanatory effect, when you put distortion in the middle of stuff it's the spice.
There are other very very interesting distortion effects such as crossover distortion or slew rate, but these are a bit deep for now!
The more of a friend you become with distortion the more it's going to sound better, there's that sweet spot, don't even think about it, start turning the knob, stop where you like, turn back if you think you over did it, and apply it to everything, if you have a clean mix, the distorted sound will be so full of frequencies it's just gonna jump out of the mix for fun.
Some last words. Distortion and general hi-end sound destruction is gonna make your sounds unbeatable by other stereos or cellphones or whatever, if you have a super clean sound, it's weak, a bad stereo will destroy it. If you have a hot signal (which doesn't mean the distortion is audible) it's like a signal on steroids, nothing can touch it, it fills the room, it's warm, it's punchy, it's everywhere!
Also ditch the bad distortions and super ditch the digital distortions (unless you want to go super creative), go to a studio with a good console one day, see what a neve does when you turn that line amp and start mixing.
Good luck. |
45,046,385 | Now I have the following procedure:
```
CREATE OR REPLACE FUNCTION find_city_by_name(match varchar) RETURNS TABLE(city_name varchar) LANGUAGE plpgsql as $$
BEGIN
RETURN QUERY WITH r AS (
SELECT short_name FROM geo_cities WHERE short_name ILIKE CONCAT(match, '%')
)
SELECT r.short_name FROM r;
END;
$$
```
I want return all fields (`*`) (not only `short_name`). What I need to change in my procedure? | 2017/07/12 | [
"https://Stackoverflow.com/questions/45046385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6459947/"
] | Here is a simplified (w/o `WITH` and with `language sql`) version, that I've mentioned in my comment to the adjacent answer:
```
create or replace function find_city_by_name(text)
returns table(city_name varchar, long_name varchar)
as $$
select * from geo_cities where short_name ilike $1 || '%';
$$ language sql;
```
Also, you might find it more convenient to refer to the `geo_cities` table itself defining the function's signature, using `SETOF geo_cities`:
```
create or replace function find_city_by_name(text)
returns setof geo_cities
as $$
select * from geo_cities where short_name ilike $1 || '%';
$$ language sql;
```
-- this will allow you to change the structure of `geo_cities` table w/o necessity to change the function's definition. | If you want a real row you must to explicit declare all fields in the return clausule:
```
create table geo_cities (
short_name varchar,
long_name varchar
);
insert into geo_cities values ('BERLIN', 'BERLIN'), ('BERLIN 2','BERLIN TWO');
CREATE OR REPLACE FUNCTION find_city_by_name(match varchar)
RETURNS TABLE(city_name varchar, long_name varchar)
LANGUAGE plpgsql
AS
$$
BEGIN
RETURN QUERY WITH r AS (
SELECT * FROM geo_cities WHERE short_name ILIKE CONCAT(match, '%')
)
SELECT * FROM r;
END;
$$;
select * from find_city_by_name('BERLIN');
```
See the example running at: <http://rextester.com/IKTT52978> |
73,377,986 | When we make a stored procedure call we pass input parameter of how many rows we want to get from result. Also, we want specific columns returned which is obtained through join operation on tables.
My doubt is can we return the result as table but if in that approach how to limit result rows to specific count which is passed as input parameter.
I also searched and found about using Fetch next rows only but can we use that without offset logic.
Can somebody suggest me if there is any better approach than above mentioned? | 2022/08/16 | [
"https://Stackoverflow.com/questions/73377986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16253207/"
] | A better way to do it is to use the dictionary attribute `get`. You can read on it [here](https://python-reference.readthedocs.io/en/latest/docs/dict/get.html)
```
from lxml import etree
class CleanItem():
def process_item(self, item, spider):
root = etree.fromstring(str(item['external_link_body']).split("'")[1])
dict_ = {}
dict_.update(root.attrib)
dict_.update({'text': root.text})
item['external_link_rel'] = dict_.get("rel", "null")
return item
``` | Why not just use a conditional statement?
```
from lxml import etree
class CleanItem():
def process_item(self, item, spider):
root = etree.fromstring(str(item['external_link_body']).split("'")[1])
dict_ = {}
dict_.update(root.attrib)
dict_.update({'text': root.text})
if 'rel' not in dict_: # If 'rel' is not a key in dict
dict_["rel"] = "null"
item['external_link_rel'] = dict_["rel"]
return item
item['external_link_rel'] = dict_["rel"] # else ...
return item
```
If you really wanted to use try/except clauses you could do this.
I would never recommend using try/except where it isn't necessary though.
```
def process_item(self, item, spider):
root = etree.fromstring(str(item['external_link_body']).split("'")[1])
dict_ = {}
dict_.update(root.attrib)
dict_.update({'text': root.text})
try:
item['external_link_rel'] = dict_["rel"]
return item
except KeyError:
dict_["rel"] = "null"
item['external_link_rel'] = dict_["rel"]
return item
``` |
62,129,354 | I read the answers ["unable to locate adb" using Android Studio](https://stackoverflow.com/questions/39036796/unable-to-locate-adb-using-android-studio) and [Error:Unable to locate adb within SDK in Android Studio](https://stackoverflow.com/questions/27301960/errorunable-to-locate-adb-within-sdk-in-android-studio) and it didn't solve my problem.
I use the 4.0 android-studio and Ubuntu 18.04
When I click on "launch this AVD in the emulator", I get an error message "Unable to locate adb".
I did look in the Android/Sdk/platform-tools, I have an "adb" executable.
After the "unable to locate adb" error message, the AVD still launches. But, when I try to run my react native app on it, I get the error
>
> error Failed to install the app. Make sure you have the Android development environment set up: <https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment>. Run CLI with --verbose flag for more details.
> Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
>
>
>
I'm pretty sure the react-native part is fine, but that route to the emulator is not the same as before.
It was working before. Yesterday, out of the blue, when I launched my android-studio, it "restarted" (showing me the install wizard, etc), and it seems it messed up its configuration.
EDIT: [bad way] I created a new ubuntu user, re-install android studio + react-native. I still get the error message, still the AVD launches, but now React-native can install the app on it. So, now I can work with my new user, but I did not fix the problem.
EDIT2: [good way] @jpatmore fixed the android-studio part (see his answer).
The react-native was still not working. There was probably some parameter of android-studio 3.6 still in the [my project]/android/[gradle or something]
I cloned my repo in another folder, do another "npm install", "react-native link", and it was working. | 2020/06/01 | [
"https://Stackoverflow.com/questions/62129354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424099/"
] | I started getting this error after updating Android Studio from version 3.6.3 to 4.0. It didn't stop the emulator working, but it was vaguely annoying.
I checked that adb.exe was in the folder C:\Users[username]\AppData\Local\Android\Sdk\platform-tools. I also ran it in a command-line to prove that the exe worked OK.
Finally after a bit of a struggle I found a solution:
Start the SDK Manager, File menu -> Settings -> Appearance & Behavior -> System Settings -> Android SDK, SDK Tools tab (Or click the cube with blue down arrow icon in the toolbar).
Firstly I updated the Android SDK Platform-Tools (now v30.0.2). This didn't fix the problem. I also tried manually deleting the platform tools folder and reinstalling.
Eventually I decided to click the "Edit" link next to the "Android SDK Location" box. This opens a new dialog for SDK Components Setup. How well hidden is that?!?! I had always assumed it was to edit the SDK path!
You should now see that Android SDK - (installed) has a tick in the checkbox, as do any SDK Platforms you have. Click on the Next button and your SDK will update.
Problem solved.
HTH | Looks like the installed driver is not correct. Steps to fix:
```
Delete the device from Device Manager.
Rescan for hardware changes.
"Your Device" will show up with "Unknown driver" status.
Click on "Update Driver" and go to android sdk path and there select /extras/google/usb_driver
Device Manager will find the driver and warn you about installing it. Select "Yes."
```
This time the device got installed properly.Thanks |
3,757,948 | Is there any way to open a new window or new tab using PHP without using JavaScript. | 2010/09/21 | [
"https://Stackoverflow.com/questions/3757948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273266/"
] | Short answer: **No**.
PHP is a [server side language](http://en.wikipedia.org/wiki/Server-side_scripting) (at least in the context of web development). It has absolutely no control over the client side, i.e. the browser. | No. PHP is a server-side language, meaning that it is completely done with its work before the browser has even started rendering the page. You need to use Javascript. |
8,318,269 | In android application i have a custom listview and sqlite database.
I want to display the database table value to custom listview.Please any one help me some code | 2011/11/29 | [
"https://Stackoverflow.com/questions/8318269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609050/"
] | It isn't possible to move an iframe from one place in the dom to another without it reloading.
Here is an example to show that even using native JavaScript the iFrames still reload:
<http://jsfiddle.net/pZ23B/>
```
var wrap1 = document.getElementById('wrap1');
var wrap2 = document.getElementById('wrap2');
setTimeout(function(){
document.getElementsByTagName('body')[0].appendChild(wrap1);
},10000);
``` | Whenever an iframe is appended and has a src attribute applied it fires a load action similarly to when creating an Image tag via JS. So when you remove and then append them they are completely new entities and they refresh. Its kind of how `window.location = window.location` will reload a page.
The only way I know to reposition `iframes` is via CSS. Here is an example I put together showing one way to handle this with `flex-box`:
<https://jsfiddle.net/3g73sz3k/15/>
The basic idea is to create a `flex-box` wrapper and then define an specific order for the iframes using the order attribute on each iframe wrapper.
```
<style>
.container{
display: flex;
flex-direction: column;
}
</style>
<div class="container">
<div id="wrap1" style="order: 0" class="iframe-wrapper">
<iframe id="iframe1" src="https://google.com"></iframe>
</div>
<div id="warp2" style="order: 1" class="iframe-wrapper">
<iframe id="iframe2" src="https://bing.com"></iframe>
</div>
</div>
```
As you can see in the JS fiddle these `order` styles are inline to simplify the `flip` button so rotate the `iframes`.
I sourced the solution from this StackOverflow question: [Swap DIV position with CSS only](https://stackoverflow.com/questions/17455811/swap-div-position-with-css-only)
Hope that helps. |
12,413,394 | I have this line in my .vimrc file:
```
set directory=~/.vim/swapfiles//
```
*(Note that one extra slash makes the directory names to be included instead of just file names to reduce conflict)*
The above config works fine on my Linux machine, but the problem is when I use the same file on Windows I get some warning about the file cannot be read. That's probably because vim is looking for `~/.vim/swapfiles/` directory, which Windows unfortunately don't have.
Is there any way to store my swap files on Windows somewhere *(better if it could be in `C:\Program Files\Vim\vimfiles\`)*?
---
CASE #2
-------
If you got answer for my above question, here is the another one. I also have some lines similar to this:
```
autocmd filetype python source ~/path/to/file/python.vim
```
Windows confuses at this point too. How can I patch up? | 2012/09/13 | [
"https://Stackoverflow.com/questions/12413394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/939986/"
] | If you don't want to introduce a `$MYVIM` variable as ZyX suggests, maybe an alternative is placing the runtime files in `$HOME/.vim` instead of the default `$HOME/vimfiles` on Windows. You can then use `~/.vim/...` everywhere. This also helps with synchronizing the files across multiple mixed-platform machines.
```
" On Windows, also use '.vim' instead of 'vimfiles'; this makes synchronization
" across (heterogeneous) systems easier.
if has('win32') || has('win64')
set runtimepath=$HOME/.vim,$VIM/vimfiles,$VIMRUNTIME,$VIM/vimfiles/after,$HOME/.vim/after
endif
``` | First of all, vim translates all forward slashes to backward on windows thus it won’t hurt having slashes. Just in case you think it can be a source of trouble.
Second, it is not impossible to have `~/.vim` and all other directories on windows, just some programs don’t want to work with names that start with a dot. You may just add this to runtimepath as it is not there by default on windows and move all user configuration there.
Third, in most places you have a filename you may use `$ENV_VAR`. It includes setting &rtp, &directory and using `:source`. So the solution may be the following:
```
if has('win16') || has('win95') || has('win32') || has('win64')
let $MYVIM=$HOME.'/vimfiles'
else
let $MYVIM=$HOME.'/.vim'
endif
set directory=$MYVIM/swapfiles
autocmd FileType python :source $MYVIM/after/ftplugin/python.vim
```
(though I agree with @Geoff Reedy that there should be no need in using the last line).
And last, modifying and storing something in `C:\Program Files` is not the best idea, neither for you nor for the program itself (by the way, vim won’t modify or store something there unless you told it to). It is to be modified by installation, update and uninstallation processes, not by anything else. |
12,996,692 | I'm trying to understand the usage for getter/setter methods in a class. Let's say we have a class called A with some *public* instance variables followed by a constructor with parameters where arguments were passed from another class(main) to it. Inside the constructor we let those instance variables equal what was passed.
Now if this class were to be used by another programmer, nothing would stop them from directly accessing/changing the instance variables to something that isn't valid. By making the instance variables private we can eliminate access to those variables. However if we wanted to have those instance variables updated/changed indirectly or under some specific condition or perhaps just letting the person have access to the instance variable, we would create a getter/setter pair for this purpose.
Benefits?:
1.Change instance variable only under certain valid reasons under the set() method
2.So that we can show what the instance variable actually is without giving the programmer who is using this class the ability to change it.
Is this a correct interpretation? | 2012/10/21 | [
"https://Stackoverflow.com/questions/12996692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681158/"
] | Your interpretation is correct. Also (off the top of my head):
* It allows the implementation of the class to change (eg if you wish to remove the field and replace it) without forcing consumers to interact with your class any differently.
* It allows AOP frameworks to intercept calls to your get / set method.
* You can specify permissions via annotations for access to methods. | if an instance variable is to be used only by methods defined with in its class, then it should be made it as private.If an instance variable must be within certain bounds, then it should be private and made available only through accessor methods[getter as well as Setter] Methods. |
5,986,694 | C#'s switch() statement is case-sensitive. Is there a way to toggle it so it becomes case-insensitive?
==============================
Thanks,
But , I don't like these solutions;
Because case conditions will be a variable , and I don't know if they ALL are UPPER or lower. | 2011/05/13 | [
"https://Stackoverflow.com/questions/5986694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114656/"
] | Yes - use `ToLower()` or `ToLowerInvariant()` on its operands. For example:
```
switch(month.ToLower()) {
case "jan":
case "january": // These all have to be in lowercase
// Do something
break;
}
``` | You can do something like this
```
switch(yourStringVariable.ToUpper()){
case "YOUR_CASE_COND_1":
// Do your Case1
break;
case "YOUR_CASE_COND_2":
// Do your Case 2
break;
default:
}
``` |
8,448,473 | What I have :
```
<ul id="myId">
<li>
My text
<ul class="myClass">
<li>blahblahblah</li>
</ul>
</li>
</ul>
```
What I want :
```
<ul id="myId">
<li>
<span>My text</span>
<ul class="myClass">
<li>blahblahblah</li>
</ul>
</li>
</ul>
```
I dont have access to the HTML markup, and am wanting to do this with jQuery,
Something like :
```
$('.myClass').get_the_text_ubove().wrap('<span>');
```
There must be some way of selecting 'My text' even though it has no class/id | 2011/12/09 | [
"https://Stackoverflow.com/questions/8448473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287082/"
] | Try:
```
$('#myId > li').each(
function(){
$(this.firstChild).wrap('<span></span>');
});
```
[JS Fiddle demo](http://jsfiddle.net/davidThomas/mmMXD/).
With regards to wanting to add the `class` to the `ul`:
```
$('#myId > li').each(
function(){
$(this.firstChild).wrap('<span></span>');
$(this).find('ul').addClass('myClass');
});
```
[JS Fiddle demo](http://jsfiddle.net/davidThomas/mmMXD/1/). | ```
var ul = document.getElementById("myId");
var li = ul.firstElementChild;
var text = li.firstChild;
var ul = li.childNodes[1];
ul.classList.add('myClass');
var span = document.createElement("span");
span.textContent = text.data;
li.replaceChild(span, text);
```
Old fashioned DOM to the rescue. |
64,936,440 | Good evening,
I am using python 3.9 and try to run a new FastAPI service on Windows 10 Pro based on the documentation on internet <https://www.uvicorn.org/> i executed the following statements
```
pip install uvicorn pip install uvicorn[standard]
```
create the sample file app.py
```
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
```
But when i run the code below :
```
uvicorn main:app --reload
uvicorn : The term 'uvicorn' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify t
hat the path is correct and try again.
At line:1 char:1
+ uvicorn
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (uvicorn:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
```
I also add the path of Python in the envroment settings
I also re-install Python 3.9 and make the default path for installation to c:\ProgramFiles\Python39 this path is also include now in the system enviroment and user enviroment settings.
[](https://i.stack.imgur.com/0LgMN.png)
if i run pip install uvicorn again it shows the following statement:
```
λ pip install uvicorn
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: uvicorn in c:\users\username\appdata\roaming\python\python39\site-packages (0.12.2)
Requirement already satisfied: h11>=0.8 in c:\users\username\appdata\roaming\python\python39\site-packages (from uvicorn) (0.11.0)
Requirement already satisfied: click==7.* in c:\users\username\appdata\roaming\python\python39\site-packages (from uvicorn) (7.1.2)
WARNING: You are using pip version 20.2.3; however, version 20.2.4 is available.
You should consider upgrading via the 'c:\program files\python39\python.exe -m pip install --upgrade pip' command.
```
Many thanks
Erik | 2020/11/20 | [
"https://Stackoverflow.com/questions/64936440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4232472/"
] | You can also run `uvicorn` with the following command:
```
python -m uvicorn main:app --reload
``` | I have faced the same problem when using a virtual environment in Windows, so the easiest to solve this problem is in the terminal typing with `python -m uvicorn main:app --reload` after already activate that environment with `activate xxx`. |
57,004,407 | I'm using `buildConfigField` to pass debug and release server Ip and other string literals into app.
like this:
```
buildTypes {
debug {
buildConfigField "String", "url", "\"http:\\xxxxxxx.xx\""
}
release {
buildConfigField "String", "url", "\"http:\\ppppppp.xx\""
}
}
```
But i'm having an issue that My app can communicate with multiple test servers when debug mode. Some times I point it to my local network Ip and if i'm not in workplace, I point it to a remote test server.
The issue that i'm facing right now is that I have to Type entire IP address here whenever I wanted to change configuration :
```
debug {
buildConfigField "String", "url", "\"http:\\xxxxxxx.xx\""
}
```
I have a Kotlin file with these Ip address already defined:
```
object API {
const val URL_MAIN = "http://19.544...."
const val URL_TEST_LOCAL = "http://192.16...."
const val URL_TEST_REMOTE = "http://19.554...."
}
```
Is there anyway to access this variable through gradle file instead of typing it.
Edit:
**I put these urls in Kotlin class because I need to use it's values within my project too.** | 2019/07/12 | [
"https://Stackoverflow.com/questions/57004407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6737471/"
] | You don't need to use java strings for this, Product flavors are the perfect solution
in your android block in Gradle file use it like this
```
productFlavors {
main {
dimension "app"
buildConfigField 'String', 'url', 'http://XXXXXXX'
}
test_local {
dimension "app"
buildConfigField 'String', 'url', 'http://XXXXXXX'
}
test_remote {
dimension "app"
buildConfigField 'String', 'url', 'http://XXXXXXX'
}
}
```
Use Build Variant section from the bottom left corner of Android studio
and choose which build you want to make | You can use **`BuildConfig`** class which is *auto-generated class* provides you variables that are defined by **buildConfigFields** in your gradle file.
So, you'll not need to change major stuffs but some minor things in `API` object like below:
```
object API {
const val URL_MAIN = BuildConfig.URL
}
```
Now, define this `URL` in **buildConfigField** by your build types.
```
buildConfigField "String", "URL", "\"http:\\xxxxxxx.xx\""
```
Such that for *debug* or *release* type, it can be whatever you want. |
2,172,621 | I met the share library not found on the head node of a cluster with torch. I have built the library as well as specify the correct path of the library while compiling my own program "absurdity" by g++. So it looks strange to me. Any idea? Thanks and regards!
```
[tim@user1 release]$ make
...
...
g++ -pipe -W -Wall -fopenmp -ggdb3 -O2 -I/home/tim/program_files/ICMCluster/ann_1.1.1/include -I/home/tim/program_files/ICMCluster/libsvm-2.89 -I/home/tim/program_files/ICMCluster/svm_light -o absurdity xxxxxx.o -L/home/tim/program_files/ICMCluster/ann_1.1.1/release/lib -L/home/tim/program_files/ICMCluster/libsvm-2.89/release/lib -L/home/tim/program_files/ICMCluster/svm_light/release/lib -lm -ljpeg -lpng -lz -lANN -lpthread -lsvm -lsvmlight
[tim@user1 release]$ ./absurdity
./absurdity: error while loading shared libraries: libsvmlight.so: cannot open shared object file: No such file or directory
[tim@user1 release]$ ls /home/tim/program_files/ICMCluster/svm_light/release/lib/libsvmlight.so -l
-rwxr-xr-x 1 tim Brown 121407 Jan 31 12:14 /home/tim/program_files/ICMCluster/svm_light/release/lib/libsvmlight.so
[tim@user1 release]$ LD_LIBRARY_PATH= /home/tim/program_files/ICMCluster/svm_light/release/lib:$LD_LIBRARY_PAT
[tim@user1 release]$ export LD_LIBRARY_PATH
[tim@user1 release]$ ./absurdity
./absurdity: error while loading shared libraries: libsvmlight.so: cannot open shared object file: No such file or directory
[tim@user1 release]$ ls /home/tim/program_files/ICMCluster/svm_light/release/lib
libsvmlight.a libsvmlight.so
``` | 2010/01/31 | [
"https://Stackoverflow.com/questions/2172621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156458/"
] | Copied from my answer here: <https://stackoverflow.com/a/9368199/485088>
>
> Run `ldconfig` as root to update the cache - if that still doesn't help, you need to add the path to the file `ld.so.conf` (just type it in on its own line) or better yet, add the entry to a new file (easier to delete) in directory `ld.so.conf.d`.
>
>
> | ```
sudo ldconfig
```
>
> ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib).
>
>
>
Generally package manager takes care of this while installing the new library, but not always (specially when you install library with `cmake`).
And if the output of this is empty
```
$ echo $LD_LIBRARY_PATH
```
Please set the default path
```
$ LD_LIBRARY_PATH=/usr/local/lib
``` |
53,750,958 | I have been working on a small project and I have ran into this issue. I have a txt file full of lines and I need to store them in a List. Is there any elegant way of doing it? This is my code, however, it won´t work because something is out of bonds. The txt file have 126 lines but I need only 125 of them. Thank you for your time, any help is appreciated :)
```
string[] Number = System.IO.File.ReadAllLines("Numbers.txt");
List<string> listNumbers = new List<string>(); //place where all numbers will be stored
for (int i = 0; i<125; i++)
{
listNumbers[i] = Number[i];
}
``` | 2018/12/12 | [
"https://Stackoverflow.com/questions/53750958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10782877/"
] | An `Array<string>` implements `IEnumerable<string>`, so if you use `System.Linq`, a bunch of convenient extension methods are available.
```
using System.Linq;
// ...
var listNumbers = System.IO.File
.ReadAllLines("Numbers.txt")
.Take(125)
.ToList();
``` | List has an `AddRange()` method that takes an enumerable (such as your array) and adds all the items in it, to the list. It's useful because it doesn't require LINQ, and unlike passing the array into the List constructor, it can be used if the list is constructed elsewhere/already instantiated by some other process
```
//if your list is constructed elsewhere
List<string> listNumbers = new List<string>();
//addrange can still be used to populate it
string[] lines = System.IO.File.ReadAllLines("Numbers.txt");
listNumbers.AddRange(lines);
```
A similar InsertRange can be used to put all the values from an enumerable, into the list at a particular position
If you have a requirement to only put a certain number of items into the list, the most compact method is probably to use linq:
```
var list = lines.Take(125).ToList();
```
The next most compact is to do as you have done, with a for loop |
14,868,424 | ```
$(function(){
$('.inviteClass').keypress(function() {
if(event.keyCode=='13') {
doPost();
}
});
```
Here I have one small requirement. Pressing keyboard Enter to submit the form and it is working fine in FireFox and Chrome, as well as IE 7 and 8, but it is not working in IE9 and IE 10.
Please help me. | 2013/02/14 | [
"https://Stackoverflow.com/questions/14868424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989472/"
] | **Points to note:**
1. You are missing a closing bracket.
2. Also, change the selector to `window`
3. Use `.on()` function
4. Use the `.which` property of event. See jQuery [documentation](http://api.jquery.com/event.which/)
5. The keycode is an integer - remove the quotes
6. Add a `return false;` to stop the event from bubbling to the form (and possibly submitting the form twice). See [Submitting a form on 'Enter' with jQuery?](https://stackoverflow.com/questions/699065/submitting-a-form-on-enter-with-jquery?rq=1)
**Final code:**
```
$(function() {
$(window).on('keydown', function(event) {
if(event.which == 13) {
doPost();
return false;
}
});
});
``` | you must use jQuery's event.which, also change '13' to 13 (a closing bracket was also missing):
```
$(function(){
$('.inviteClass').keypress(function(event) {
if(event.which == 13) {
doPost();
}
});
});
``` |
72,289 | I know from [here](https://answers.yahoo.com/question/index?qid=1006041614112) that a flame thrower can operate in deep space if specially built. However, I want to know if using a flamethrower on a spaceship in space could have any tactical benefits. Could a flamethrower be used to destroy or blind enemy sensors from several kilometers away, or would it burn out? Would it be possible to build a flamethrower that can reach targets several kilometers away in space? | 2017/02/26 | [
"https://worldbuilding.stackexchange.com/questions/72289",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/20775/"
] | Nope
----
### Improper Usage
Remember that the **purpose of a flamethrower is to set flammable targets on fire** like wood structures and humans and to consume oxygen from enclosed spaces. It is safe to assume that spaceships will not be made out of flammable materials. Ships are sealed so that they do not lose oxygen to space, so unless the flamethrower can penetrate the hull it will not harm the air inside the ship. There are also far more effective methods to blind enemy sensors than generating a lot of heat and IR. Space ships already are going to be able to filter out far hotter things from their sensors like near by stars.
### Distance and Velocity
For a flame thrower to travel one kilometer it would need to ignite at the end of the stream on impact otherwise it will burn its fuel off before it got to the target.
Flamethrowers also run into an issue that the fluid is not going to be moving that fast compared to other weapons so enemies will easily see it coming and avoid it. You can switch it out for an incendiary missile, which will get the payload to its target faster, but it will cease to be a flamethrower at that point.
### Armor and Shields
Space ships are going to be designed to handle far worse than what a flamethrower can dish out. Flamethrowers are a chemical based weapon and so they generate energy through chemical reaction. However, there are a large number of weapons out there that can generate far more destructive forms of energy, and as such space ship defenses will be designed to handle those types of things. So when the flamethrower hits the shields or armor at the worst it will likely only damage the paint job. | A flamethrower is, fundamentally, a device that ejects burning-hot stuff at a moderate-to-fast speed.
A rocket is a device that ejects stuff at *very* fast speeds, and the stuff it ejects tends to be burning-hot (since that's a very effective way to make fast-moving exhaust).
If for some reason a spaceship builder decided to put a flamethrower on the outside of their ship, especially if it needs a range of several kilometers, it seems likely that it would be based on a backwards-facing rocket more than a traditional earthbound flamethrower. What you'd be looking at there would be [weaponized exhaust](http://tvtropes.org/pmwiki/pmwiki.php/Main/WeaponizedExhaust) - along with some (possibly rather significant) acceleration away from the target. |
11,507 | When a try:
```
sudo apt install elementary-sdk
```
it says
```
Unable to locate package elementary-sdk
```
It's a fresh install of loki.
```
apt update
```
give me a 404 error.
```
Err:7 http://br.archive.ubuntu.com/ubuntu loki Release
404 Not Found [IP: 200.236.31.4 80]
``` | 2017/04/13 | [
"https://elementaryos.stackexchange.com/questions/11507",
"https://elementaryos.stackexchange.com",
"https://elementaryos.stackexchange.com/users/9338/"
] | This is a repository error: there is no Ubuntu version "loki", you should use "xenial" Ubuntu repositories with elementary repositories.
`/etc/apt/sources.list.d/elementary.list`:
```
deb http://ppa.launchpad.net/elementary-os/stable/ubuntu xenial main
deb-src http://ppa.launchpad.net/elementary-os/stable/ubuntu xenial main
```
`/etc/apt/sources.list.d/patches.list`:
```
deb http://ppa.launchpad.net/elementary-os/os-patches/ubuntu xenial main
deb-src http://ppa.launchpad.net/elementary-os/os-patches/ubuntu xenial main
``` | I can verify updating "hera" to "bionic" in the following source list files allowed me to install elementary-sdk just now (for Elementary OS 5.1):
```
/etc/apt/sources.list
/etc/apt/sources.list.d/elementary.list
/etc/apt/sources.list.d/patches.list
/etc/apt/sources.list.d/appcenter.list
```
This appears to be an ongoing issue the past 4 years so I've filed [a bug in GitHub](https://github.com/elementary/os/issues/316) so this gets fixed at its root. |
9,994,790 | I have to disable and enable three checkboxes.
if the user clicks on one the other will be disabled
```
<input type="checkbox" class="rambo" value='1' /> 45
<input type="checkbox" class="rambo" value='2' /> 56
<input type="checkbox" class="rambo" value='3' /> 56
```
so i need a function that gives me this via jquery
thanks for the advice | 2012/04/03 | [
"https://Stackoverflow.com/questions/9994790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1241255/"
] | Try this:
```
$(".rambo").change(function() {
var $el = $(this);
if ($el.is(":checked")) {
$el.siblings().prop("disabled",true);
}
else {
$el.siblings().prop("disabled",false);
}
});
```
[**Example fiddle**](http://jsfiddle.net/xUv9h/) | You can try:
```
$('.rambo').click( function() {
if ($(this).attr('checked')) {
$(this).siblings().attr('disabled','disabled');
} else {
$(this).siblings().removeAttr('disabled');
}
});
```
As you can see on [this jsfiddle](http://jsfiddle.net/darkajax/jz8C5/2/) |
70,504,639 | `DT_DATE` and `DT_DBTIMESTAMP` both store the year, month, date, hour, min, sec, and fractional sec.
What is the difference between `DT_DATE`, `DT_DBTIMESTAMP`?
Which of them is to be used to store the DateTime value from the SQL database? | 2021/12/28 | [
"https://Stackoverflow.com/questions/70504639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] | Plan A:
=======
You can deploy oracle services in the form of submitting yaml files directly to k8s.
Deploy
------
The following is the definition code of Oracle deployment.
This code consists of two parts, namely the deployment of Oracle deployment and its proxy service. The Oracle database deployed here is 11g r2, and the image used is `mybook2019/oracle-ee-11g:v1.0`. The two ports `1521` and `8080` are exposed through the NodePort mode, and the Oracle data is persisted through the `nfs` file system.
oracle-service.yaml
```yaml
apiVersion: v1
kind: Service
metadata:
name: oralce-svc
labels:
app: oralce
spec:
type: NodePort
ports:
- port: 1521
targetPort: 1521
name: oracle1521
- port: 8080
targetPort: 8080
name: oralce8080
selector:
app: oralce
```
oracle-deployment.yaml
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: oralce
spec:
replicas: 1
selector:
matchLabels:
app: oralce
strategy:
type: Recreate
template:
metadata:
labels:
app: oralce
spec:
containers:
- image: mybook2019/oracle-ee-11g:v1.0
name: oralce
- containerPort: 1521
name: oralce1521
- containerPort: 8080
name: oralce8080
volumeMounts:
- name: oralce-data
mountPath: /u01/app/oracle
volumes:
- name: oralce-data
nfs:
path: /home/sharenfs/oracle
server: 192.168.8.132
```
Through `kubectl` execute the following command to deploy the Oracle database in the Kubernetes cluster.
```sh
$ kubectl create -f oracle-service.yaml
$ kubectl create -f oracle-deployment.yaml
```
After the deployment is complete, you can view the ports exposed by oracle through the following command (the ports here are `1521` and `32175`)
```sh
$ kubectl get svc
```
[](https://i.stack.imgur.com/bkwEJ.png)
Check
-----
For applications in the Kubernetes cluster, the relevant information for connecting to the database is as follows:
```sh
hostname: oracle-svc.default
port: 1521
sid: EE
service name: EE.oracle.docker
username: system
password: oracle
```
For the machine where the oracle client is located, execute the following command to connect to the database.
```sh
$ sqlplus system/oracle@//oracle-svc.kube-public:1521/EE.oracle.docker
```
For applications outside the Kubernetes cluster, the relevant information used to connect to the database is as follows:
```sh
hostname: 10.0.32.165
port: 32175
sid: EE
service name: EE.oracle.docker
username: system
password: oracle
```
For the machine where the oracle client is located, execute the following command to connect to the database.
```sh
$ sqlplus system/oracle@//10.0.32.165:32175/EE.oracle.docker
```
---
Plan B:
=======
Install by helm [chart](https://github.com/oracle/docker-images/blob/main/OracleDatabase/SingleInstance/helm-charts/oracle-db/README.md)
To install the chart with the release name `db19c`:
Helm 3.x syntax
```
$ helm install db19c oracle-db-1.0.0.tgz
```
Helm 2.x syntax
```
$ helm install --name db19c oracle-db-1.0.0.tgz
```
The command deploys Oracle Database on the Kubernetes cluster in the default configuration. The configuration section lists the parameters that can be configured during installation. | It would help if you could share details regarding what you've already tried in order to deploy an Oracle database on minikube, otherwise your question appears too generic.
For any application to be deployed on a kubernetes distribution like minikube -- you need the manifests of that application (in this case Oracle database) which would describe the desired state of the application.
You can then expose that application using a service & consume it. |
35,315,090 | Update:
Now looking back more than a year later, I am giving an update hope that will help someone else.
Spring IO recommend using CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.
Since my app is an API and will be processed by a browser, so disable CSRF is not an approach.
CSRF is enabled with Spring Boot by default, you would need to add the following code to add a CSRF repository and a filter to add the CSRF token to your http requests. (The solution comes from here [Invalid CSRF Token in POST request](https://stackoverflow.com/questions/36878189/invalid-csrf-token-in-post-request?answertab=votes#tab-top) )
```
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/assets/**", "/templates/**", "/custom-fonts/**", "/api/profile/**", "/h2/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.permitAll()
.and()
.csrf().csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(csrfHeaderFilter(), SessionManagementFilter.class); // Register csrf filter.
}
```
The filter & CsrfToken Repository part:
```
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null
&& !token.equals(cookie.getValue())) {
// Token is being added to the XSRF-TOKEN cookie.
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
};
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
```
---
Original Question I asked back in Feb 2016
I working on enabeing the Global CORS support for a Spring-boot RESTful API with Spring 4.
I am following the official Spring Boot Doc(<https://spring.io/guides/gs/rest-service-cors/>) and have added this to my Application:
```
public class SomeApiApplication {
public static void main(String[] args) {
SpringApplication.run(SomeApiApplication.class, args);
}
//Enable Global CORS support for the application
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
.allowedHeaders("header1", "header2") //What is this for?
.allowCredentials(true);
}
};
}
}
```
I don't get why only GET is working, for the rest of http calls, I am getting an error message saying "Invalid CORS request". Do I miss anything in the set up? If my set up is not right, GET should not work as well. I am very confussed. | 2016/02/10 | [
"https://Stackoverflow.com/questions/35315090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5377372/"
] | I had a a similar issue, only HEAD GET and POST were working for me.
I found out that [`addCorsMappings`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/package-summary.html) has a default value for [`allowedMethods`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/CorsRegistration.html#allowedMethods-java.lang.String...-).
This code works for me:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedOrigins("http://localhost:4200");
}
};
}
}
``` | Here is my `SecurityConfig.java`. I had to mix various answers in this post to get it to work for me.
```java
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll();
// unblock post, put and delete requests
http.csrf().disable();
// enable cors
http.cors();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.addAllowedOrigin("http://localhost:3000");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
```
If you would like to allow all origins, replace `http://localhost:3000` with `*` |
11,493,711 | I'm making a pretty simple game just for fun/practice but I still want to code it well regardless of how simple it is now, in case I want to come back to it and just to learn
So, in that context, my question is:
How much overhead is involved in object allocation? And how well does the interpreter already optimize this? I'm going to be repeatedly checking object grid positions, and if they are still in the same grid square, then no updating the grid array
```
if (obj.gridPos==obj.getCurrentGridPos()){
//etc
}
```
But, should I keep an outer "work" point object that the `getCurrentGridPos()` changes each time or should it return a new point object each time?
Basically, even if the overhead of creating a point object isnt all that much to matter in this scenario, which is faster?
EDIT:
this? which will get called every object each frame
```
function getGridPos(x,y){
return new Point(Math.ceil(x/25),Math.ceil(y/25));
}
```
or
```
//outside the frame by frame update function looping through every object each frame
tempPoint= new Point()
//and each object each frame calls this, passing in tempPoint and checking that value
function makeGridPos(pt,x,y){
pt.x = Math.ceil(x/25);
pt.y = Math.ceil(y/25);
}
``` | 2012/07/15 | [
"https://Stackoverflow.com/questions/11493711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/864572/"
] | It's my understanding that garbage collection stops execution on most JS engines. If you're going to be making many objects per iteration through your game loop and letting them go out of scope that will cause slowdown when the garbage collector takes over.
For this kind of situation you might consider making a singleton to pool your objects with a method to recycle them for reuse by deleting all of their properties, resetting their `__proto__` to `Object.prototype`, and storing them in an array. You can then request recycled objects from the pool as needed, only increasing the pool size when it runs dry. | The short answer is to set one `current position` object and check against itself as you're literally going to use more memory if you create a new object every time you call `getCurrentGridPos()`.
There may be a better place for the `is this a new position` check since you should only do that check once per iteration.
It seems optimal to set the `currentGridPos` using a [RequestAnimationFrame](https://gist.github.com/1579671) and check against its current `x y z` positions before updating it so you can then trigger a `changedPosition` type event.
```
var currentPos = {
x:0,
y:0,
z:0
}
window.requestAnimationFrame(function(newPos){
if (currentPos.x != currentPos.x || currentPos.y != currentPos.y || currentPos.z != newPos.z) {
$.publish("positionChanged"); // tinypubsub https://gist.github.com/661855
}
})
```
So, just to be clear, yes I think you should keep an outer "work" point object that updates every iteration... and while it's updating you could check to see if its position has changed - this would be a more intentful way to organize the logic and ensure you don't call `getCurrentPos` more than once per iteration. |
4,060 | I need to get transaction list within theDAO system. Is it possible or it's the same case of getting the internal transactions in Ethereum?
I want to know if there is a mechanism within theDAO to get these transactions. | 2016/05/19 | [
"https://ethereum.stackexchange.com/questions/4060",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/1670/"
] | **Q**: testnet or private? Is it better to just create a private testnet?
One advantage of using the testnet is that there are testnet block explorers like <https://testnet.etherscan.io/> and <https://morden.ether.camp/> if you need to examine your blockchain.
One problem with Testnet is that there are few peers running the Testnet blockchain. When you are trying to sync to the Testnet blockchain, you may find that `geth` will sometimes lose it's peer connections, and that you may have to restart `geth --testnet` manually to kick-start the peer connections.
If you are using your own private network, you don't have to worry about syncing as you are building your own blockchain. It's a little bit harder to connect your `geth --dev` instance to Ethereum Wallet if you intend to use the Ethereum Wallet, as you have to specify the location of the `geth.ipc` file for Ethereum Wallet to communicate with `geth`.
**Q**: How to get testnet ether? Is mining testnet ether feasible? Can I get enough to test a basic contract in a day?
Run the Ethereum Wallet (Mist). Select the TEST-NET network using the menu Develop -> Network -> Testnet (Morden).
Select the menu Develop -> Start Mining (Testnet only).
Once the blockchain is synced, you should have some Testnet ethers within 20 minutes, mining using the CPU only.
**Q**: Are there testnet faucets?
There are Testnet faucets, but when I was testing a few weeks ago, I could not get these to work. It was easier to mine the Testnet and wait 20 minutes or so.
See also [How to create a temporary account for testnet with funds?](https://ethereum.stackexchange.com/questions/3360/how-to-create-a-temporary-account-for-testnet-with-funds/3361#3361) | You can mine on testnet relatively easy to earn ether. From your `geth console` run `miner.start(X)` (where X is the number of threads it should use) and let it run for a while. I think in about 30 minutes I was able to mine roughly 150 ether. But your mileage may vary
Using the testnet would probably be a little easier than setting up your own private net. I actually run a dedicated testnet node just for experimentation. |
434,229 | My customer has quite a large (the total "data" folder size is 200G) PostgreSQL database and we are working on a disaster recovery plan. We have identified three different types of disasters so far: hardware outage, too much load and unintentional data loss due to erroneously executed bad migration (like DELETE or ALTER TABLE DROP COLUMN).
First two types seem to be easy to mitigate but we can't elaborate a good mitigation plan for the third type. I proposed to use ZFS and frequent (hourly) snapshots but "ZFS" means "OpenIndiana" these days and our Ops engineers do not have much expertise in it, so using OpenIndiana imposes another risk. Colleagues try to convince me that restoring from PostgreSQL PITR backup can be as fast as restoring from a ZFS snapshot but I highly doubt that replaying, say, 50G of archived WALs can be considered "fast".
What other options are we missing? Is ZFS an only viable alternative? Can we get a fast Pg DB restore time in the Linux environment? | 2012/10/02 | [
"https://serverfault.com/questions/434229",
"https://serverfault.com",
"https://serverfault.com/users/69133/"
] | Why is FreeBSD not a viable option to run ZFS and PostgreSQL on? The FreeBSD ZFS developers works very close with the Illumos team and just recently Pawel Jakub Dawidek (The man who first ported ZFS to FreeBSD) added [SSD TRIM support for ZFS](http://lists.freebsd.org/pipermail/freebsd-current/2012-September/036777.html). This will most likely also be added to Illumos ZFS code soon.
Another advantage with FreeBSD and ZFS is the [GEOM](https://en.wikipedia.org/wiki/GEOM) framework. On Solaris, when entire disks are added to a ZFS pool, ZFS automatically enables their write cache. This is not done when ZFS only manages discrete slices of the disk, since it does not know if other slices are managed by non-write-cache safe filesystems, like UFS. The FreeBSD implementation can handle disk flushes for partitions thanks to its [GEOM](https://en.wikipedia.org/wiki/GEOM) framework, and therefore does not suffer from this limitation. | I suggest you take a look at Barman, Backup and Recovery Manager for PostgreSQL, which has been written by us and is available as open-source under GNU GPL 3 terms.
To give you an idea, we use it in production on databases larger than yours (7 Terabytes).
Version 1.0 has been released latest July.
There is an RPM version already, Debian package is on the way (Barman will be included in Ubuntu 12.10).
For more information: [www.pgbarman.org](http://www.pgbarman.org/). |
27,135,488 | In first loop I am looping through variable rgname which is [Monthly,Quarterly,Yearly]. Now,I created another method called listDir. If I pass variable value here folder = new File(reportFolderPath + reportPath + "/"+ rgname); and later to the method listDir it will return list of array like as shown below.
```
List<ReportGroup> reportGroupList = new ArrayList<ReportGroup>();
for (String rgname : reportGroupNames) {
ReportGroup rg = new ReportGroup();
rg.setReportGroupName(rgname);// Report Name such as
// Monthly,Quarterly and
// Yearly
folder = new File(reportFolderPath + reportPath + "/"+ rgname);
List<ReportInfo> reportList = new ArrayList<ReportInfo>();
List<String> reportDescription=listDir(folder);
for(String reportDescr:reportDescription){
System.out.println("*****************Test***************" +reportDescr);
rg.setReportDescr(reportDescr);
}
rg.setReportList(reportList);
reportGroupList.add(rg);
report.setReportGroupList(reportGroupList);
}
}
```
Second Method returns the arraylist:
```
public static List<String> listDir(final File folder) {
List<String> dirArray = new ArrayList<String>();
for (final File fi : folder.listFiles()) {
if (fi.isDirectory()) {
dirArray.add(fi.getName());
}
}
return dirArray;
}
```
The Output should be like this:
```
Monthly
-Jan
-Feb
-Continue
Quarterly
-First Quarter
-Second continue
```
Second method returns this value and this is what it prints when doing System.out.println(reportDescription);
```
[539_January_2013, 540_February_2013, 541_March_2013, 542_April_2013, 543_May_2013, 544_June_2013, 545_July_2013, 546_August_2013, 547_September_2013, 548_October_2013, 549_November_2013, 550_December_2013, 587_January_2014]
[551_First_Quarter_2013, 554_Second_Quarter_2013, 557_Third_Quarter_2013, 560_Fourth_Quarter_2013]
[123_Year_2010]
``` | 2014/11/25 | [
"https://Stackoverflow.com/questions/27135488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3025316/"
] | As found out in the [chat](https://chat.stackoverflow.com/rooms/65651/discussion-between-tom-and-lokesh), the problematic line is this:
```
rg.setReportDescr(reportDescr);
```
As I assumed in the comments before, this *is* a standard setter method which will overwrite the old data with the new one. Therefore the last remaining data is the last element of the list:
```
public void setReportDescr(String reportDescr) {
this.reportDescr = reportDescr;
}
```
An easy way to fix this, is to pass the whole list to the `ReportGroup` instance:
```
List<String> reportDescriptions=listDir(folder);
rg.setReportDescriptions(reportDescriptions); // changed method name a bit
rg.setReportList(reportList);
reportGroupList.add(rg);
```
In the class `ReportGroup`, the line `String reportDescr;` should be changed to:
```
List<String> reportDescr;
```
And the getter and setter methods should be changed accordingly:
```
public List<String> getReportDescriptions() { // changed method name a bit
return reportDescr;
}
public void setReportDescriptions(List<String> reportDescr) { // changed method name a bit
this.reportDescr = reportDescr;
}
``` | Your code is very confusing!
I'm not sure what the goal is here, but it seems like you are overwriting the folder such that only the last month is being printed out. You can try creating a new File each time and adding that to its own list. Then you can iterate through that. Here is some code, although it's not doing what you want it to do, but you can use it to give you an idea of what to do next:
```
List<String> monthsList = new ArrayList<String>();
monthsList.add("January");
monthsList.add("June");
monthsList.add("December");
List<File> folderList = new ArrayList<File>();
for(String month : monthsList)
{
File folder = new File("C:\\temp\\"+month);
if(!folder.exists())
{
folder.mkdir();
}
folderList.add(folder);
}
List<String> dirArray = new ArrayList<String>();
for (final File fi : folderList)
{
if(fi.isDirectory())
{
dirArray.add(fi.getAbsolutePath());
}
}
for(String directory : dirArray)
{
System.out.println("*****************Test***************\n" + directory);
}
``` |
18,374 | Let $K$ be a field and $L$ an extension of $K$. I wonder how much larger the multiplicative group $L^\times$ of $L$ is than the multiplicative group $K^\times$ of $K$.
I know that if $L=K(t)$ and $t$ is transcendental over $K$, then $L^\times/K^\times$ is isomorphic to the direct product of an infinite number of copies of the integers: Indeed, any (monic) rational function can be uniquely written as the product of a finite number of powers of irreducible polynomials.
In particular, $L^\times/K^\times$ is not finitely generated.
What happens when $L=K(t)$ and $t$ is algebraic over $K$? I can handle the case when $K$ is finite, but what happens in the infinite case?
Even for $L=Q(\sqrt{2})$ it's not immediate to me if $L^\times/K^\times$ is finitely generated or not. | 2010/03/16 | [
"https://mathoverflow.net/questions/18374",
"https://mathoverflow.net",
"https://mathoverflow.net/users/3380/"
] | To add to Franz's nice answer:
Let $\mathcal{C}$ be the collection of groups isomorphic to the direct sum of a free abelian group of countable rank with a finite abelian group.
In the case where $L/K$ is a nontrivial finite separable extension of global fields, each of the following groups is in $\mathcal{C}$ (and the first two are free):
1) The group of fractional ideals of $K$ (or divisors in the function field case)
2) The group of principal fractional ideals of $K$
3) $K^\times$
4) $L^\times/K^\times$
**Proof:** The first three can be proved in succession by using infinitude of primes, finiteness of class groups, and the Dirichlet unit theorem.
4) As suggested by t3suji and Franz, Chebotarev shows that the rank is infinite. On the other hand, the following trick shows that $L^\times/K^\times$ is a subgroup of a group in $\mathcal{C}$ (and hence in $\mathcal{C}$ itself): Replace $L$ by its Galois closure. Let $\sigma\_1,\ldots,\sigma\_d$ be the elements of $\operatorname{Gal}(L/K)$. Then
$$x \mapsto (\sigma\_1(x)/x,\ldots,\sigma\_d(x)/x)$$
injects $L^\times/K^\times$ into $L^\times \times \cdots \times L^\times$,
which is in $\mathcal{C}$. | Perhaps useful to you: As a replacement of finitly generated in a local situation, one can sometimes use that the quotient is cocompact.
For a local field, we have in the usual scaling of the multiplicative Haar measure that the quotient measure $F^\times / K^\times$ is the ramification index. |
23,105,118 | I'm Python newbie and would like to convert ASCII string into a series of 16-bit values that would put ascii codes of two consecutive characters into MSB and LSB byte of 16 bit value and repeat this for whole string...
I've searched for similar solution but couldn't find any. I'm pretty sure that this is pretty easy task for more experienced Python programmer... | 2014/04/16 | [
"https://Stackoverflow.com/questions/23105118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2152780/"
] | If you take a look at the [date reference](http://php.net/manual/en/function.date.php), a lower-case `h` is the 12-hour formatted hour. You need a capital `H`:
```
echo date( 'Y:m:d H:i:s', strtotime( $date1 )); // 12:10:00
echo date( 'Y:m:d H:i:s', strtotime( $date2 )); // 00:10:00
```
FWIW: Your time variables should be strings, with quotes.:
```
$date1 = "12:10:00";
$date2 = "00:10:00";
``` | You can check difference using AM or PM or use 24 hours format cause 0 and 12 same mean for time different is it's am or pm
```
$date1 = '12:10:00';
$date2 = '00:10:00';
echo date( 'Y:m:d h:i:s A', strtotime( $date1 )); // 2014:04:16 12:10:00 PM
echo date( 'Y:m:d h:i:s A', strtotime( $date2 )); // 2014:04:16 12:10:00 AM
```
or use capital `H`
```
echo date( 'Y:m:d H:i:s', strtotime( $date1 )); // 12:10:00
echo date( 'Y:m:d H:i:s', strtotime( $date2 )); // 00:10:00
``` |
3,917,081 | I'm trying to convert from a SQL Server database backup file (`.bak`) to MySQL. [This question](https://stackoverflow.com/questions/156279/how-to-import-a-sql-server-bak-file-into-mysql) and answers have been very useful, and I have successfully imported the database, but am now stuck on exporting to MySQL.
The *MySQL Migration Toolkit* was suggested, but seems to have been replaced by the *MySQL Workbench*. Is it possible to use the MySQL Workbench to migrate from SQL Server in the same way that the migration tool worked?
Or is the Migration Toolkit still available somewhere? | 2010/10/12 | [
"https://Stackoverflow.com/questions/3917081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265985/"
] | PhpMyAdmin has a Import wizard that lets you import a MSSQL file type too.
See <http://dev.mysql.com/doc/refman/5.1/en/sql-mode.html> for the types of DB scripts it supports. | I used the below connection string on the Advanced tab of MySQL Migration Tool Kit to connect to SQL Server 2008 instance:
```
jdbc:jtds:sqlserver://"sql_server_ip_address":1433/<db_name>;Instance=<sqlserver_instanceName>;user=sa;password=PASSWORD;namedPipe=true;charset=utf-8;domain=
```
Usually the parameter has "systemName\instanceName". But in the above, *do not add* "systemName\" (use only InstanceName).
To check what the instanceName should be, go to services.msc and check the DisplayName of the MSSQL instance. It shows similar to MSSQL$instanceName.
Hope this help in MSSQL connectivity from mysql migration toolKit. |
33,255,058 | ```
p
| user / a.active(href="#{back_url}") james
```
I even tried
```
p
| user /
| a.active(href="#{back_url}") james
```
No error in my terminal, just the html is broken. I want it to be like this
```
<p>user / <a class="active" href="link">james</a></p>
``` | 2015/10/21 | [
"https://Stackoverflow.com/questions/33255058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5440072/"
] | Just sum two lists produced by multiplication first and second elements:
```
['a']*100 + ['b']*100
```
It's faster than list comprehension and sort:
```
python -m timeit "sorted(['a', 'b']*100)"
100000 loops, best of 3: 9.76 usec per loop
python -m timeit "[x for x in ['a', 'b'] for y in range(100)]"
100000 loops, best of 3: 5.15 usec per loop
python -m timeit "['a']*100 + ['b']*100"
1000000 loops, best of 3: 1.86 usec per loop
``` | ```
from itertools import repeat
list(repeat('a',100)) + list(repeat('b',100))
``` |
620,564 | How can I replace a text in all files in all subfolders when my search includes "\*"
for example I have many text files containing such pattern (some wrong paths that I want to correct)
```
/folder1/(abc)/params.launch
/folder2/(efd)/gui.launch
/folder3/(ghi)/robot.launch
```
Now I want to add /launch before each file to have such a result
```
/folder1/(abc)/launch/params.launch
/folder2/(efd)/launch/gui.launch
/folder3/(ghi)/launch/robot.launch
```
I thought about searching for the string pattern
>
> `")/*.launch"`
>
>
>
but then how can I replace it while keeping the content of those "\*" | 2015/05/07 | [
"https://askubuntu.com/questions/620564",
"https://askubuntu.com",
"https://askubuntu.com/users/266492/"
] | Should be fairly simple with `sed`:
```
sed 's;\([^/]*.launch$\);launch/\1;'
```
* You can group matched text by surrounding the expression in brackets (`\( ... \)`). You need to escape the parentheses to make `sed` see them as special syntax.
* The groups can be referred to using the position - the first group is `\1`, the second is `\2`, etc.
Example output:
```
$ sed 's;\([^/]*.launch\);launch/\1;' foo
/folder1/(abc)/launch/params.launch
/folder2/(efd)/launch/gui.launch
/folder3/(ghi)/launch/robot.launch
```
This is for Basic Regular Expressions. For Extended Regular expressions, one can use `sed -r`, in which case the parentheses need not be escaped:
```
sed -r 's;([^/]*.launch);launch/\1;'
```
Lastly, in `sed`, and some other tools, the complete matched text can be referred to using `&`, avoiding the need for groups and backreferences altogether:
```
sed 's;[^/]*.launch;launch/&;' foo
``` | Using `bash`:
```bsh
#!/bin/bash
while IFS= read -r line; do
ini="${line%/*}"
last="${line##*/}"
repl="${line##*.}"
echo "${ini}/${repl}/${last}"
done <file.txt
```
**Output :**
```
/folder1/(abc)/launch/params.launch
/folder2/(efd)/launch/gui.launch
/folder3/(ghi)/launch/robot.launch
```
Here we have used the [parameter substitution](http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) of `bash` to have three variables:
* The `ini` variable will contain the part before last `/` e.g. `/folder1/(abc)`
* The `last` variable will contain the part after last `/` e.g. `params.launch`
* The `repl` variable will contain what to be put inside the `ini` and `last` variables i.e. `launch`
Then we have printed the values of the variables in the specified pattern puting `/` between them. |
38,202,769 | I made a game in Swift but I need to download .zip files on my website, and use the content (images) in game.
Actually, I download the .zip file and store it in documents, and I need to unzip the file into the same documents folder.
I tried marmelroy's Zip, iOS 9 Compression module and tidwall's DeflateSwift but none of these worked. It could be good if it was compatible with iOS 8. | 2016/07/05 | [
"https://Stackoverflow.com/questions/38202769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6551357/"
] | I got it work with SSZipArchive and a bridging header:
1. Drag & drop the SSZipArchive directory in your project
2. Create a {PROJECT-MODULE-NAME}-Bridging-Header.h file with the line ***import "SSZipArchive.h"***
3. In Build Settings, drag the bridging header in Swift Compiler - Code generation -> Objective-C Bridging Header.
4. Use SSZipArchive in your Swift code. | **Important: Requires Third Party Library**
Using this [library](https://github.com/marmelroy/Zip) you can use this line:
```
let unzipDirectory= try Zip.quickUnzipFile(filePath) //to unZip your folder.
```
If you want more help , check the repository. |
24,241,943 | I'd like to create a 'go-to-top'-button via jquery - but scroll() and scrollTop() aren't working...
Here's my setup:
```
<div id="go_top">go to top</div>
```
and CSS
```
#go_top {
position: fixed;
right: 2em;
bottom: 2em;
color: #000;
background-color: rgba(167, 204, 35, 0.6);
font-size: 12px;
padding: 1em;
cursor: pointer;
display: none;
}
#go_top:hover {
color: #000;
background-color: rgba(167, 204, 35, 1);
}
```
Therefore, I setup the following jquery:
```
$(document).ready(function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 200) {
$('#go_top').fadeIn(200);
} else {
$('#go_top').fadeOut(100);
}
}
});
```
But it's not working. The div just won't show :( | 2014/06/16 | [
"https://Stackoverflow.com/questions/24241943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3048602/"
] | ```
$(document).ready(function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 200) {
$('#go_top').fadeIn(200);
} else {
$('#go_top').fadeOut(100);
}
}); // ')' is missing here**
});
```
You are missing **')'** in your function. | Try this,
```
$(document).ready(function() {
$(window).scroll(function() {
if ( $(this).scrollTop() > 200) {
$('#go_top').fadeIn(100);
} else {
$('#go_top').fadeOut(100);
}
});
});
```
you are missing one closing brace and remove the px from 200 |
48,076,425 | What is the meaning and difference between these queries?
```
SELECT U'String' FROM dual;
```
and
```
SELECT N'String' FROM dual;
``` | 2018/01/03 | [
"https://Stackoverflow.com/questions/48076425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5657953/"
] | *In this answer i will try to provide informations from official resources*
(1) The N'' text Literal
========================
`N''` is used to convert a string to `NCHAR` or `NVARCHAR2` datatype
**According to this Oracle documentation [Oracle - Literals](https://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements003.htm#i42617)**
>
> The syntax of text literals is as follows:
>
>
> [](https://i.stack.imgur.com/OrmrH.gif)
>
>
> where `N` or `n` specifies the literal using the national character set (`NCHAR` or `NVARCHAR2` data).
>
>
>
**Also in this second article [Oracle - Datatypes](https://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements001.htm#i45685)**
The `N'String'` is used to convert a string to `NCHAR` datatype
From the article listed above:
>
> The following example compares the `translated_description` column of the `pm.product_descriptions` table with a **national character set string**:
>
>
>
> ```
> SELECT translated_description FROM product_descriptions
> WHERE translated_name = N'LCD Monitor 11/PM';
>
> ```
>
>
---
(2) The U'' Literal
===================
`U''` is used to handle the SQL NCHAR String Literals in Oracle Call Interface (OCI)
**Based on this Oracle documentation [Programming with Unicode](https://docs.oracle.com/cd/B19306_01/server.102/b14225/ch7progrunicode.htm)**
>
> **The Oracle Call Interface** (OCI) is the lowest level API that the rest of the client-side database access products use. It provides a flexible way for C/C++ programs to access Unicode data stored in SQL `CHAR` and `NCHAR` datatypes. Using OCI, you can programmatically specify the character set (UTF-8, UTF-16, and others) for the data to be inserted or retrieved. It accesses the database through Oracle Net.
>
>
>
>
> OCI is the lowest-level API for accessing a database, so it offers the best possible performance.
>
>
>
>
> Handling SQL NCHAR String Literals in OCI
> -----------------------------------------
>
>
> You can switch it on by setting the environment variable `ORA_NCHAR_LITERAL_REPLACE` to `TRUE`. You can also achieve this behavior programmatically by using the `OCI_NCHAR_LITERAL_REPLACE_ON` and `OCI_NCHAR_LITERAL_REPLACE_OFF` modes in `OCIEnvCreate()` and `OCIEnvNlsCreate()`. So, for example, `OCIEnvCreate(OCI_NCHAR_LITERAL_REPLACE_ON)` turns on `NCHAR` literal replacement, while `OCIEnvCreate(OCI_NCHAR_LITERAL_REPLACE_OFF)` turns it off.
>
>
> [...] Note that, when the `NCHAR` literal replacement is turned on, `OCIStmtPrepare` and `OCIStmtPrepare2` **will transform `N'` literals with `U'` literals in the SQL text and store the resulting SQL text in the statement handle**. Thus, if the application uses `OCI_ATTR_STATEMENT` to retrieve the SQL text from the `OCI` statement handle, **the SQL text will return `U'` instead of `N'` as specified in the original text**.
>
>
>
---
(3) Answer for your question
============================
From datatypes perspective, there is not difference between both queries provided | * `N'*string*'` just returns the `*string*` as `NCHAR` type.
* `U'*string*'` returns also `NCHAR` type, however it does additional processing to the `*string*`: it replaces `\\` with `\` and `\*xxxx*` with Unicode code point `U+*xxxx*`, where `*xxxx*` are 4 hexadecimal digits. This is similar to `UNISTR('*string*')`, the difference is that the latter returns `NVARCHAR2`.
`U'` literals are useful when you want to have a Unicode string independent from encoding and NLS settings.
Example:
```
select n'\€', u'\\\20ac', n'\\\20ac' from dual;
N'\€' U'\\\20AC' N'\\\20AC'
----- ---------- ----------
\€ \€ \\\20ac
``` |
1,453,482 | In Linux, if I want to observe the system log in terminal in real-time, I can use the `tail` command to output the `/var/log/syslog` file with the `-f` or `--follow` switch, which "output(s) appended data as the file grows", say:
```
tail -f /var/log/syslog
```
... or could also use:
```
dmesg --follow
```
... where `-w, --follow` argument for `dmesg` stands for "Wait for new messages".
In any case, both of these applications in this mode generally block the terminal, and then dump new text lines/messages as they come, until you hit Ctrl-C to exit them.
On Windows, I understand that the equivalent to the system log is the Event (Log) Viewer, which is a GUI application. After a while, I found <https://www.petri.com/command-line-event-log> - which notes that one can use the `WEVTUTIL.EXE` command-line application to query the Windows event log.
So, I've tried this:
```
C:\>wevtutil qe System
```
... but this simply dumps all events, and then exits (same as if you'd call `dmesg` on Linux without any arguments).
I looked through the help `wevtutil /?`, but I cannot see any command line argument that would put `wevtutil` in "follow" mode (i.e. so it blocks the terminal after it has dumped everything up to that point, and then prints new events/text lines as they are logged).
So - is it possible to get `wevtutil` to work in follow mode, and if so, how? If not, is there another utility I could use, that would do the same - dump the system Event Log of Windows to terminal in follow mode? | 2019/06/27 | [
"https://superuser.com/questions/1453482",
"https://superuser.com",
"https://superuser.com/users/688965/"
] | Go to [sysinternals.com](https://sysinternals.com), then look at the documentation for ProcessExplorer.
You can set filters to exe, events, messages and in real-time or duration.
You can trace and debug too. Sysinternals Suite gives much better detail than event viewer.
1. [ProcessExplorer](https://docs.microsoft.com/en-au/sysinternals/downloads/process-explorer)
2. [ProcessMonitor](https://docs.microsoft.com/en-au/sysinternals/downloads/procmon)
3. [ProcessDump](https://docs.microsoft.com/en-au/sysinternals/downloads/procdump)
Once you find the events or objects you need, check the properties to see what you can call in terminal. | OK, so looked up something a bit more; found this:
* <https://stackoverflow.com/questions/15262196/powershell-tail-windows-event-log-is-it-possible>
... which gives examples of using PowerShell for this behavior. Based on this post, this is what I did:
First, I wanted to create a PowerShell script; the page <https://www.windowscentral.com/how-create-and-run-your-first-powershell-script-file-windows-10> notes that the extension for a PowerShell script is `.ps1`.
Then, I wanted to specifically create the script in root of drive `C:`. Turns out, this is protected in Windows 10 - you must have Administrator privileges to do this (else you get `Access is denied.`). So, I fired up Command Prompt in administrator mode ("Run as administrator"), and created these two files:
```
C:\WINDOWS\system32>cd C:\
C:\>echo > wevent_tail_01.ps1
C:\>echo > wevent_tail_02.ps1
```
Note that these files will not be empty, but will have the text line `ECHO is on.` in them - however, that line can b deleted; or ( <https://ss64.com/ps/syntax-comments.html> ) prefixed with `#` which is the comment character in PowerShell.
Then, I opened those files in Notepad to edit them - from the same terminal, so the Administrative privileges are kept (otherwise one will get access denied when trying to save the files from Notepad):
```
C:\>notepad wevent_tail_01.ps1
C:\>notepad wevent_tail_02.ps1
```
Then, I pasted this code from the SO:15262196 as `wevent_tail_01.ps1`:
```
$idx = (get-eventlog -LogName System -Newest 1).Index
while ($true)
{
start-sleep -Seconds 1
$idx2 = (Get-EventLog -LogName System -newest 1).index
get-eventlog -logname system -newest ($idx2 - $idx) | sort index
$idx = $idx2
}
```
... and I pasted the code from the [other answer](https://stackoverflow.com/a/16364295/6197439) in `wevent_tail_02.ps1`, but I couldn't quite get it to work. So in the rest of this post, I'll only use `wevent_tail_01.ps1`.
Now, it's time to run this script in PowerShell; the windowscentral post points out that scripts are ran by prefixing their path with ampersand and space `&`; however, if you just start PowerShell normally, and try it, you'll get:
```
PS C:\> & "C:\wevent_tail_01.ps1"
& : File C:\wevent_tail_01.ps1 cannot be loaded because running scripts is disabled on this system. For more
information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:3
+ & "C:\wevent_tail_01.ps1"
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
```
The windowscentral post recommends that you use `Set-ExecutionPolicy RemoteSigned` to fix this - but to have this command complete, you'll again need to run PowerShell with administrative privileges; however, you can also limit it to the current user, in which case you can keep the normally started PowerShell:
```
PS C:\> Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): A
PS C:\>
```
So, at this point, we should have a permission to run our script:
```
PS C:\> & "C:\wevent_tail_01.ps1"
```
... and nicely, the script will block the terminal, but most likely, no text will be dumped. So, we'd like to test and see if this works.
For this, we'll need to open another PowerShell, but with administrative properties; I found the right info on <https://mcpmag.com/articles/2016/09/08/powershell-to-write-to-the-event-log.aspx> - in brief: to write arbitrary stuff in Windows Event Logs, we need to specify a "source":
```
PS C:\WINDOWS\system32> New-EventLog -LogName System -Source 'MySysTest'
```
... and then, we can use `Write-EventLog` to write into the event log:
```
PS C:\WINDOWS\system32> Write-EventLog -LogName "System" -Source "MySysTest" -EventID 3001 -EntryType Information -Message "MyApp added a user-requested feature to the display." -Category 1 -RawData 10,20
PS C:\WINDOWS\system32> Write-EventLog -LogName "System" -Source "MySysTest" -EventID 3001 -EntryType Warning -Message "MyApp added a user-requested feature to the display." -Category 1 -RawData 10,20
PS C:\WINDOWS\system32> Write-EventLog -LogName "System" -Source "MySysTest" -EventID 3001 -EntryType Error -Message "MyApp added a user-requested feature to the display." -Category 1 -RawData 10,20
```
If we now switch to the first PowerShell, where the `C:\wevent_tail_01.ps1` was running and blocking, we should see something like:
```
PS C:\> & "C:\wevent_tail_01.ps1"
Index Time EntryType Source InstanceID Message
----- ---- --------- ------ ---------- -------
2577 Jun 27 10:34 Information MySysTest 3001 MyApp added a user-requested feature to the dis...
2578 Jun 27 10:35 Warning MySysTest 3001 MyApp added a user-requested feature to the dis...
2579 Jun 27 10:35 Error MySysTest 3001 MyApp added a user-requested feature to the dis...
```
In fact, at first I did not see this when switching to this terminal, but then I think I right-clicked it once, and it "woke up", and then it started dumping lines in realtime.
Well, I guess this is what I wanted - though I did kinda hope that this would have been a bit easier ...
---
EDIT: if you want to "tail" both System and Application log, here is the PowerShell script:
```
$sidx = (get-eventlog -LogName System -Newest 1).Index
$aidx = (get-eventlog -LogName Application -Newest 1).Index
while ($true)
{
start-sleep -Seconds 1
$sidx2 = (Get-EventLog -LogName System -newest 1).index
$aidx2 = (Get-EventLog -LogName Application -newest 1).index
get-eventlog -logname system -newest ($sidx2 - $sidx) | sort index
get-eventlog -logname application -newest ($aidx2 - $aidx) | sort index
$sidx = $sidx2
$aidx = $aidx2
}
```
... and to test, you **have** to make a new provider, with a unique name, registered to Application log, so:
```
New-EventLog -LogName Application -Source 'MyAppTest'
```
... which you can test/fire up with:
```
Write-EventLog -LogName "Application" -Source "MyAppTest" -EventID 3001 -EntryType Error -Message "MyApp added a user-requested feature to the display." -Category 1 -RawData 10,20
``` |
58,303,657 | Data Source
-----------
I am trying to take the following XML structure, and transform it into a CSV file with XSL.
```
<Root>
<Row>
<Employee>Harry</Employee>
<Employees_Manager_1>Ron</Employees_Manager_1>
<Employees_Manager_2>Hermione</Employees_Manager_2>
<Employees_Manager_3>Ginni</Employees_Manager_3>
</Row>
<Row>
<Employee>Ross</Employee>
<Employees_Manager_1>Emma</Employees_Manager_1>
<Employees_Manager_2>Monica</Employees_Manager_2>
<Employees_Manager_3>Rachel</Employees_Manager_3>
</Row>
</Root>
```
Desired Output in CSV
---------------------
```
Harry,Ron,
Harry,Hermione,
Harry,Ginni,
Ross,Emma,
Ross,Monica,
Ross,Rachel,
```
Failed Attempt
--------------
I am a beginner in XML/XSL, and so far I only know how to use the following:
```
<xsl:template match="Root">
<xsl:for-each select="Row">
<xsl:value-of select="Employee"/>
<text>,</text>
<xsl:value-of select="Employees_Manager_1"/>
<text>,</text>
<xsl:value-of select="Employees_Manager_2"/>
<text>,</text>
<xsl:value-of select="Employees_Manager_3"/>
<text>,</text>
<endTag>
</endTag>
</xsl:for-each>
</xsl:template>
```
I am getting this result:
```
Harry, Ron, Hermione, Ginni,
Ross, Emma, Monica, Rachel,
```
Question
--------
Is there a way to get my desired output with XSL? Thank you. | 2019/10/09 | [
"https://Stackoverflow.com/questions/58303657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12188126/"
] | I don't think that you will need to save the data to a custom data structure, instead you could take a look at Hibernate's 2nd level cache for both entities and queries.
With proper settings the Hibernate will cache the data and the query you are using for you.
[There](https://www.baeldung.com/hibernate-second-level-cache) is good article on Baeldung about 2nd level cache that can get you started. | i believe you should write a database listener that listens on DB records change event then fetches the records in the data structure of your choice then caches the records to be used in case the DB change event isn't triggered
* this is a good [article](https://stackoverflow.com/questions/12618915/how-to-implement-a-db-listener-in-java) on how to implement db listener in java |
28,028,618 | I'm currently implementing a KD Tree and nearest neighbour search, following the algorithm described here: <http://ldots.org/kdtree/>
I have come across a couple of different ways to implement a KD Tree, one in which points are stored in internal nodes, and one in which they are only stored in leaf nodes. As I have a very simple use case (all I need to do is construct the tree once, it does not need to be modified), I went for the leaf-only approach is it seemed to be simpler to implement. I have successfully implemented everything, the tree is always constructed successfully and in most cases the nearest neighbour search returns the correct value. However, I have some issues that with some data sets and search points, the algorithm returns an incorrect value. Consider the points:
```
[[6, 1], [5, 5], [9, 6], [3, 81], [4, 9], [4, 0], [7, 9], [2, 9], [6, 74]]
```
Which constructs a tree looking something like this (excuse my bad diagramming):

Where the square leaf nodes are those that contain the points, and the circular nodes contain the median value for splitting the list at that depth. When calling my nearest neighbour search on this data set, and looking for the nearest neighbour to `[6, 74]`, the algorithm returns `[7, 9]`. Although this follows the algorithm correctly, it is not in fact the closest point to `[6, 74]`. The closest point would actually be `[3, 81]` which is at a distance of 7.6, `[7, 9]` is at a distance of 65.
Here are the points plotted, for visualization, the red point being the one I am attempting to find the nearest neighbour for:

If it helps, my search method is as follows:
```
private LeafNode search(int depth, Point point, KDNode node) {
if(node instanceof LeafNode)
return (LeafNode)node;
else {
MedianNode medianNode = (MedianNode) node;
double meanValue = medianNode.getValue();
double comparisonValue = 0;
if(valueEven(depth)) {
comparisonValue = point.getX();
}
else {
comparisonValue = point.getY();
}
KDNode nextNode;
if(comparisonValue < meanValue) {
if (node.getLeft() != null)
nextNode = node.getLeft();
else
nextNode = node.getRight();
}
else {
if (node.getRight() != null)
nextNode = node.getRight();
else
nextNode = node.getLeft();
}
return search(depth + 1, point, nextNode);
}
}
```
So my questions are:
1. Is this what to expect from nearest neighbour search in a KD Tree, or should I be getting the closest point to the point I am searching for (as this is my only reason for using the tree)?
2. Is this an issue only with this form of KD Tree, should I change it to store points in inner nodes to solve this? | 2015/01/19 | [
"https://Stackoverflow.com/questions/28028618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3750097/"
] | The explanation given on ldots.org is just plain wrong (along with many other top Google results on searching KD Trees).
See <https://stackoverflow.com/a/37107030/591720> for a correct implementation. | Not sure if this answer would be still relevant, but anyway I dare to suggest the following kd-tree implementation: <https://github.com/stanislav-antonov/kdtree>
The implementation is simple enough and could be useful in a case if one decided to sort out how the things work in practice.
Regarding the way how the tree is built an iterative approach is used, thus its size is limited by a memory and not a stack size. |
9,656,523 | I'm trying to find a way to use jQuery autocomplete with callback source getting data via an ajax json object list from the server.
Could anybody give some directions?
I googled it but couldn't find a complete solution. | 2012/03/11 | [
"https://Stackoverflow.com/questions/9656523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1248959/"
] | My issue was that end users would start typing in a textbox and receive autocomplete (ACP) suggestions and update the calling control if a suggestion was selected as the ACP is designed by default. However, I also needed to update multiple other controls (textboxes, DropDowns, etc...) with data specific to the end user's selection. I have been trying to figure out an elegant solution to the issue and I feel the one I developed is worth sharing and hopefully will save you at least some time.
**WebMethod (SampleWM.aspx):**
* ***PURPOSE:***
+ *To capture SQL Server Stored Procedure results and return them as a JSON String to the AJAX Caller*
* ***NOTES:***
+ *Data.GetDataTableFromSP() - Is a custom function that returns a DataTable from the results of a Stored Procedure*
+ *< System.Web.Services.WebMethod(EnableSession:=True) > \_*
+ *Public Shared Function GetAutoCompleteData(ByVal QueryFilterAs String) As String*
---
```
//Call to custom function to return SP results as a DataTable
// DataTable will consist of Field0 - Field5
Dim params As ArrayList = New ArrayList
params.Add("@QueryFilter|" & QueryFilter)
Dim dt As DataTable = Data.GetDataTableFromSP("AutoComplete", params, [ConnStr])
//Create a StringBuilder Obj to hold the JSON
//IE: [{"Field0":"0","Field1":"Test","Field2":"Jason","Field3":"Smith","Field4":"32","Field5":"888-555-1212"},{"Field0":"1","Field1":"Test2","Field2":"Jane","Field3":"Doe","Field4":"25","Field5":"888-555-1414"}]
Dim jStr As StringBuilder = New StringBuilder
//Loop the DataTable and convert row into JSON String
If dt.Rows.Count > 0 Then
jStr.Append("[")
Dim RowCnt As Integer = 1
For Each r As DataRow In dt.Rows
jStr.Append("{")
Dim ColCnt As Integer = 0
For Each c As DataColumn In dt.Columns
If ColCnt = 0 Then
jStr.Append("""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
Else
jStr.Append(",""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
End If
ColCnt += 1
Next
If Not RowCnt = dt.Rows.Count Then
jStr.Append("},")
Else
jStr.Append("}")
End If
RowCnt += 1
Next
jStr.Append("]")
End If
//Return JSON to WebMethod Caller
Return jStr.ToString
```
---
**AutoComplete jQuery (AutoComplete.aspx):**
* ***PURPOSE:***
+ *Perform the Ajax Request to the WebMethod and then handle the response*
---
```
$(function() {
$("#LookUp").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SampleWM.aspx/GetAutoCompleteData",
dataType: "json",
data:'{QueryFilter: "' + request.term + '"}',
success: function (data) {
response($.map($.parseJSON(data.d), function (item) {
var AC = new Object();
//autocomplete default values REQUIRED
AC.label = item.Field0;
AC.value = item.Field1;
//extend values
AC.FirstName = item.Field2;
AC.LastName = item.Field3;
AC.Age = item.Field4;
AC.Phone = item.Field5;
return AC
}));
}
});
},
minLength: 3,
select: function (event, ui) {
$("#txtFirstName").val(ui.item.FirstName);
$("#txtLastName").val(ui.item.LastName);
$("#ddlAge").val(ui.item.Age);
$("#txtPhone").val(ui.item.Phone);
}
});
});
```
--- | I used the construction of `$.each (data [i], function (key, value)`
But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: [autocomplete form with ajax success](http://sysadmin-arh.ru/auto-complete-form-elements-with-ajax-query-results/) |
48,233,470 | I'm trying to set my form to specif logic when the two dates are within 30 days.
```
Date fromDate = form.getFromDate();
Date toDate = form.getToDate();
if(fromDate.compareTo(toDate) > 30){ // if the selected date are within one month
}
```
I want to add like validation to be sure the selected two dates are in month rang | 2018/01/12 | [
"https://Stackoverflow.com/questions/48233470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594057/"
] | ```
Date fromDate = form.getFromDate();
Date toDate = form.getToDate();
LocalDateTime from = LocalDateTime.ofInstant(fromDate.toInstant(), ZoneId.systemDefault());
LocalDateTime to= LocalDateTime.ofInstant(toDate.toInstant(), ZoneId.systemDefault());
if(Duration.between(from, to).toDays() <= 30){
//do work
}
```
Make sure to specify the ZoneId correctly. | Since Java 8 you can get the help of [`ChronoUnit`](https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoUnit.html):
To determine if the difference between your dates is 30 days use [`ChronoUnit.DAYS`](https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoUnit.html#DAYS):
```
LocalDate from = fromDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate to = fromDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
if(ChronoUnit.DAYS.between(from, to) == 30L){
// 30 days between dates
}
```
For a real month use [`ChronoUnit.MONTHS`](https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoUnit.html#MONTHS):
```
LocalDate from = fromDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate to = toDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
if(ChronoUnit.MONTHS.between(from, to) == 1L){
// 1 month between dates
}
``` |
4,324,969 | Has anyone used Trent Richardsons TimePicker?
It's a wonderful plugin, but I just can't seem to change the format of the date to dd/mm/yyyy
Has anyone used this control and knows if this can be done? | 2010/12/01 | [
"https://Stackoverflow.com/questions/4324969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296392/"
] | this works
```
> DatePicker2.datepicker({ dateFormat:
> 'dd/mm/yy', changeMonth: true,
> changeYear: true, showAnim: '',
> showTime: true, duration: ''
> });
``` | There is a property `dateFormat` on the `TimePicker` object itself.
```
$.datepicker.regional['en'] = {
dateFormat: 'dd.mm.yyyy'
}
``` |
5,221,757 | It would be nice to have larger MessageBox Buttons since the target for this application is a tablet.
```
DialogResult dialogResult = MessageBox.Show(
message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
switch (dialogResult)
{
case DialogResult.Yes:
// ...
``` | 2011/03/07 | [
"https://Stackoverflow.com/questions/5221757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/398460/"
] | It is a system setting. Tablet PCs are normally already configured to make it easy to tap buttons like this so that it works well in any program, not just yours. To configure your tablet, in Win7, use Control Panel + Display, Personalization, Window Color. Click Advanced appearance settings, select "Message Box" in the Item combo. Increase the font size. Don't be fooled by the poor preview, the button will actually grow. There are additional settings in this dialog you might want to tweak to make it easier to manipulate the UI. | You can make a 2nd form, then you can make the buttons as big as you want |
4,445,414 | Consider the fragment below:
```
[DebuggerStepThrough]
private A GetA(string b)
{
return this.aCollection.FirstOrDefault(a => a.b == b);
}
```
If I use F11 debugger doesn't skip the function instead it stops at **a.b == b**.
Is there any way to jump over this function rather than using F10? | 2010/12/14 | [
"https://Stackoverflow.com/questions/4445414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/251231/"
] | I can see why it happens but don't have a way to get around it. Perhaps someone can build on this. The lambda expression gets compiled into an Anonymous Method.
I see: Program.GetA.AnonymousMethod\_\_0(Test a)
Just like if you called another method in the method you've shown, pressing F11 would go into that method. eg/
```
[DebuggerStepThrough]
static A GetA<A>(IList<A> aCollection, string b) where A : Test
{
DoNoOp();
return aCollection.FirstOrDefault(a => a.b == b);
}
static void DoNoOp()
{
// noop
Console.WriteLine("got here");
}
``` | IMO this is a bug in the C# compiler. The compiler should also place those attributes on the anonymous methods. The workaround is to fallback to doing the work manually that the C# compiler does for you:
```
[DebuggerStepThrough]
private A GetA(string b)
{
var helper = new Helper { B = b };
return this.aCollection.FirstOrDefault(helper.AreBsEqual);
}
private class Helper
{
public string B;
[DebuggerStepThrough]
public bool AreBsEqual(A a) { return a.b == this.B; }
}
```
But of course this is nasty and quite unreadable. That's why the C# compiler should have done this. But the difficult question for the C# team is of course: which of the attributes that you place on a method must be copied to internal anonymous methods and which should not? |
263,103 | I have a problem with lightning:inputField, in my page I have a mix of lighting:input and lightning:inputField.
When I dispaly inputField in large screen, the label is horizontally aligned with the input.
[](https://i.stack.imgur.com/X9i9Z.jpg)
I would like to align it vertically.
There is my code
```
<aura:component >
<aura:attribute name="account" type="Account" />
<lightning:recordEditForm aura:id="formAccount"
objectApiName="Account">
<lightning:inputField fieldName="Name" value="{!v.account.Name}" />
<lightning:input type="text"
required="true"
label="Account site"
value="{!v.account.Site}" />
</lightning:recordEditForm>
</aura:component>
```
Thank you. | 2019/05/21 | [
"https://salesforce.stackexchange.com/questions/263103",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/55463/"
] | i think your org moved to summer 19, please have look [new changes in summer 19](https://releasenotes.docs.salesforce.com/en-us/summer19/release-notes/rn_aura_components.htm) , your use case you need to give density attribute for `lightning:recordeditform` please try below code
```
<aura:component >
<aura:attribute name="account" type="Account" />
<lightning:recordEditForm aura:id="formAccount" density="comfy"
objectApiName="Account">
<lightning:inputField fieldName="Name" value="{!v.account.Name}" />
<lightning:input type="text"
required="true"
label="Account site"
value="{!v.account.Site}" />
</lightning:recordEditForm>
``` | I tried your code in my personal org and its working completely fine. When I dispalyed inputField in large screen, the label is aligned vertically with the label.
Try Element inspection by clicking F12, this would help you in finding what is going wrong. |
1,804,336 | If I have the following differential equation:
$\dfrac{dy}{dx} = \dfrac{y}{x} - (\dfrac{y}{x})^2$
And if I make the variable change: $\dfrac{y}{x} \rightarrow z$
I know have $\dfrac{dy}{dx} = z-z^2$
What is $\dfrac{dx}{dy}$ after the variablechange? | 2016/05/29 | [
"https://math.stackexchange.com/questions/1804336",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/332511/"
] | Suppose you have a differential equation that looks like this: $$y'=F\left ( \frac{y}{x}\right )$$
then you can make a substitution $v(x)=\frac{y}{x} \iff y=vx \implies y'=v+xv'$ to transform your ODE into an ODE in $v$ $$\implies v+xv'=F(v) \iff \frac{dv}{F(v)-v}=\frac{dx}{x}$$
This equation is separated and you can solve it by the usual methods.
In your case you have: $$y'=\frac{y}{x}-\left (\frac{y}{x}\right)^2$$
A substitution $u=\frac{y}{x} \iff ux=y \iff y'=u+xu'$ will lead to the differential equation:
$$xu'=-u^2$$
Can you solve it from here? | If you make $y=x z$, $y'=x z'+z$ and the equation becomes $$x z'+z=z-z^2$$ that is to say $$x z'=-z^2$$which is separable. |
8,838,212 | I'm trying to resize the `<li>`s in my jQuery mobile site (listview) and can't seem to find the right class in CSS to do it. I've basically resized some of the elements (the header and footer, etc.). I have five `<li>` buttons stacked vertically and there is a gap below the buttons and the footer.
I just want to set each `<li>`'s height to 20% (that would do the trick since there is five of them and they are nested in a body content div. Does anyone know the class in the jQuery Mobile CSS that controls this? I can't seem to find this info in a search. Here's a link to the CSS for reference:
[jQuery Mobile Default CSS](http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.css)
Thanks!
UPDATE
------
I was originally meaning to discuss 'listview' exclusively for the buttons. I was too broad in my original explanation but basically I'm trying to resize not all buttons but just the `<li>`s. | 2012/01/12 | [
"https://Stackoverflow.com/questions/8838212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975592/"
] | If you check-out the classes you can make your own decision about how to select the `LI` elements, I would use the `.ui-li` class and if you want to make sure to only get one `listview` element then you can specify a more detailed selector:
```
#my-listview-id > .ui-li {
height : 20%;
}
```
Here is some sample `listview` output from the jQuery Mobile docs:
```
<ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="f" class="ui-listview ui-listview-inset ui-corner-all ui-shadow">
<li data-role="list-divider" role="heading" class="ui-li ui-li-divider ui-btn ui-bar-f ui-corner-top ui-btn-up-undefined">Overview</li>
<li data-theme="c" class="ui-btn ui-btn-icon-right ui-li-has-arrow ui-li ui-btn-up-c"><div class="ui-btn-inner ui-li" aria-hidden="true"><div class="ui-btn-text"><a href="docs/about/intro.html" class="ui-link-inherit">Intro to jQuery Mobile</a></div><span class="ui-icon ui-icon-arrow-r ui-icon-shadow"></span></div></li>
<li data-theme="c" class="ui-btn ui-btn-up-c ui-btn-icon-right ui-li-has-arrow ui-li"><div class="ui-btn-inner ui-li" aria-hidden="true"><div class="ui-btn-text"><a href="docs/about/getting-started.html" class="ui-link-inherit">Quick start guide</a></div><span class="ui-icon ui-icon-arrow-r ui-icon-shadow"></span></div></li>
<li data-theme="c" class="ui-btn ui-btn-up-c ui-btn-icon-right ui-li-has-arrow ui-li"><div class="ui-btn-inner ui-li" aria-hidden="true"><div class="ui-btn-text"><a href="docs/about/features.html" class="ui-link-inherit">Features</a></div><span class="ui-icon ui-icon-arrow-r ui-icon-shadow"></span></div></li>
<li data-theme="c" class="ui-btn ui-btn-up-c ui-btn-icon-right ui-li-has-arrow ui-li"><div class="ui-btn-inner ui-li" aria-hidden="true"><div class="ui-btn-text"><a href="docs/about/accessibility.html" class="ui-link-inherit">Accessibility</a></div><span class="ui-icon ui-icon-arrow-r ui-icon-shadow"></span></div></li>
<li data-theme="c" class="ui-btn ui-btn-icon-right ui-li-has-arrow ui-li ui-corner-bottom ui-btn-up-c"><div class="ui-btn-inner ui-li" aria-hidden="true"><div class="ui-btn-text"><a href="docs/about/platforms.html" class="ui-link-inherit">Supported platforms</a></div><span class="ui-icon ui-icon-arrow-r ui-icon-shadow"></span></div></li>
</ul>
```
**UPDATE**
There was a little more to this than I had previously posted, here is some tested/working code:
```
#my-page {
height : 100%;
margin : 0;
padding : 0;
}
#my-page .ui-content, #my-listview {
min-height : 100%;
height : 100%;
margin : 0;
padding : 0;
}
#my-listview .ui-li {
height : 20%;
}
```
Where `#my-page` is the id of my `data-role="page"` element and `#my-listview` is the id of the `data-role="listview"` element.
Here is a demo: <http://jsfiddle.net/gu7WE/> | It is simple as that:
```
.ui-li>.ui-btn-inner {
padding-top: 10px
padding-bottom: 10px
}
``` |
36,681,463 | I have this schema.
```
create table "user" (id serial primary key, name text unique);
create table document (owner integer references "user", ...);
```
I want to select all the documents owned by the user named "vortico". Can I do it in one query? The following doesn't seem to work.
```
select * from document where owner.name = 'vortico';
``` | 2016/04/17 | [
"https://Stackoverflow.com/questions/36681463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/272642/"
] | ```
SELECT * FROM document d INNER JOIN "user" u ON d.owner = u.name
WHERE u.name = 'vortico'
``` | You can use subquery. For your example it can be faster
```
SELECT * FROM document WHERE
owner = (SELECT id FROM users WHERE name = 'vortico');
``` |
407,771 | How can one allow code snippets to be entered into an editor (as stackoverflow does) like FCKeditor or any other editor while preventing XSS, SQL injection, and related attacks. | 2009/01/02 | [
"https://Stackoverflow.com/questions/407771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40376/"
] | Part of the problem here is that you want to allow certain kinds of HTML, right? Links for example. But you need to sanitize out just those HTML tags that might contain XSS attacks like script tags or for that matter even event handler attributes or an href or other attribute starting with "javascript:". And so a complete answer to your question needs to be something more sophisticated than "replace special characters" because that won't allow links.
Preventing SQL injection may be somewhat dependent upon your platform choice. My preferred web platform has a built-in syntax for parameterizing queries that will mostly prevent SQL-Injection (called cfqueryparam). If you're using PHP and MySQL there is a similar native mysql\_escape() function. (I'm not sure the PHP function technically creates a parameterized query, but it's worked well for me in preventing sql-injection attempts thus far since I've seen a few that were safely stored in the db.)
On the XSS protection, I used to use regular expressions to sanitize input for this kind of reason, but have since moved away from that method because of the difficulty involved in both allowing things like links while also removing the dangerous code. What I've moved to as an alternative is XSLT. Again, how you execute an XSL transformation may vary dependent upon your platform. I wrote [an article for the ColdFusion Developer's Journal](http://br.sys-con.com/node/206288) a while ago about how to do this, which includes both a [boilerplate XSL sheet](http://gemsres.com/story/apr06/206288/source.html) you can use and shows how to make it work with CF using the native XmlTransform() function.
The reason why I've chosen to move to XSLT for this is two fold.
First validating that the input is well-formed XML eliminates the possibility of an XSS attack using certain string-concatenation tricks.
Second it's then easier to manipulate the XHTML packet using XSL and XPath selectors than it is with regular expressions because they're designed specifically to work with a structured XML document, compared to regular expressions which were designed for raw string-manipulation. So it's a lot cleaner and easier, I'm less likely to make mistakes and if I do find that I've made a mistake, it's easier to fix.
Also when I tested them I found that WYSIWYG editors like CKEditor (he removed the F) preserve well-formed XML, so you shouldn't have to worry about that as a potential issue. | The same rules apply for protection: **filter input, escape output.**
In the case of input containing code, filtering just means that the string must contain printable characters, and maybe you have a length limit.
When storing text into the database, either use query parameters, or else escape the string to ensure you don't have characters that create SQL injection vulnerabilities. Code may contain more symbols and non-alpha characters, but the ones you have to watch out for with respect to SQL injection are the same as for normal text.
Don't try to duplicate the correct escaping function. Most database libraries already contain a function that does correct escaping for all characters that need escaping (e.g. this may be database-specific). It should also handle special issues with character sets. Just use the function provided by your library.
I don't understand why people say "use stored procedures!" Stored procs give no special protection against SQL injection. If you interpolate unescaped values into SQL strings and execute the result, this is vulnerable to SQL injection. It doesn't matter if you are doing it in application code versus in a stored proc.
When outputting to the web presentation, escape HTML-special characters, just as you would with any text. |
52,830,733 | I am trying to export a websphere profile. Tried various commands under wsadmin
```
$AdminTask exportWasprofile {-archive c:/myCell.car}
AdminTask.exportWasprofile('[-archive c:/myCell.car]')
AdminTask.exportWasprofile(['-archive', 'c:/myCell.car'])
```
all return a syntax error
com.ibm.bsf.BSFException: error while eval'ing Jacl expression:
how do you export a profile?
(Websphere 8.5.5.14) | 2018/10/16 | [
"https://Stackoverflow.com/questions/52830733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3249353/"
] | The first example you give is correct for use with wsadmin in jacl language mode, the third is correct for jython lang mode. The error message you posted indicates that wsadmin is operating in jacl language mode. | You're almost right, this one should work.
`AdminTask.exportWasprofile(['-archive c:\myCell.car'])` |
1,410,211 | I'd like to stop immediately a method if I press cancel in the "processing" animation screen. I'm using Async call through delegates. Is it possible to stop immediately the execution of the method through delegates?
Thanks :) | 2009/09/11 | [
"https://Stackoverflow.com/questions/1410211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48834/"
] | You can use [System.ComponentModel.BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx). It supports cancellation so that you don't have to write the boilerplate code. Client code can simply call [CancelAsyn](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync.aspx) method and you can check [CancellationPending](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancellationpending.aspx) property within your code when and where it makes sense to determine if the client has cancelled the operation and bail out. | As Jon has already stated, you can't tell a thread: "please stop now" and expect the thread to obey. Thread.Abort will not tell it to stop, will simply "unplug" it. :)
What I did in the past was add a series of "if (wehavetostop)" within the thread's code and if the user pressed a "cancel" I put wehavetostop == true.
It's not too elegant and in some cases it may be "hard" to put the "if" checks, specially if your thread runs a "long" operation that you can't divide.
If you are trying to establish a network connection (and it's taking time) and you really think that an "abnormal" termination of the thread wouldn't cause any corrupting state, you may use it, but remember that you cannot trust the state of things that were involved in that thread. |
25,263 | I have had 2 brews and a mate, one brew recently that have turned nuclear. And it has been on or about day 20-21 after bottling in all instances. All brews were a different style but the same manufacturer, namely Mangrove Jack. Were we live is currently getting warm, 33-35C. I’ve saved most of my brews by either putting them on ice or in the fridge. They taste perfect.
When we were discussing the possibilities we speculated about the yeast potentially reactivating on or around the 3 week mark, exacerbated by the high temps. We have both made MJ brews a few months ago when it was cooler with no problems.
We brew slightly differently, he goes for lower alcohol and I for the recommend recipe.
We haven’t encountered the same problem with Black Rock or Morgan’s that we also use.
Look forward to your input.
Waz | 2020/09/29 | [
"https://homebrew.stackexchange.com/questions/25263",
"https://homebrew.stackexchange.com",
"https://homebrew.stackexchange.com/users/18577/"
] | OK. You're brewing kit beers, so I'm assuming your wort composition has been more or less consistent (i.e. 1 tin of hopped malt extract, 1 kg of brew blend which is mostly dextrose with some maltodextrin and some dry malt extract blended in, and water up to 23 litres / 6 gallons. That means your bottle bombs could only have a few possible causes.
1. You bottled too early. Did you get the same final gravity (typically 1.010 for MJ kit beers) every time? If not, a high FG means you're bottling too early and too much fermentation continues in the bottle.
2. Contamination with a wild yeast that ferments sugars (typically polysaccharides and dextrins) that the regular MJ kit yeast leaves alone. Do your explosive beers taste dryer (with less body) than the non-explosive ones?
3. Overfilling the bottles. You need enough headspace under the cap so that the air can compress sufficiently when CO2 develops.
You say the beer tastes fine, so I'm ruling out bacterial infection on the basis of that.
If my assumption of consistent wort composition is wrong and you have varied your ingredients, there could be a complex sugar in the mix that ferments out very slowly, so that too much fermentation is delayed until after bottling. Also note that some yeast strains struggle with some malt extracts, so some yeast/extract combinations can also lead to overcarbonated (although seldom explosive) beers. If you have varied the yeasts you use rather than use the MJ kit yeast for all beers, this *might* also be a factor. | I believe the issue was a combination of post bottling temperature and hop creep. Whilst not excessively hopping(20-30g) dry, it’s hot in the tropics. My shed could get to 32-34C during the day. Backed off the priming sugar bit by bit, nah. Time to keg. Another challenge but not as potential messy. The Kveik yeast works really well here, no fridge needed and over in 2-3 days. Yes just using extract cans, hot storage shortens there shelf life as I’ve learned.
All the best for 2021 and a new Pres. |
2,015,408 | >
> If the power series $\sum a\_nz^n$ converges at $3+4i$ then find radius of convergence of the series.
>
>
>
I can conclude that radius of convergence is either $\ge 5$ or $\le 5$.But how to find it?
Please help | 2016/11/15 | [
"https://math.stackexchange.com/questions/2015408",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/294365/"
] | You cannot find the radius of convergence exactly here. The center of expansion is 0, let $\rho$ be the radius of convergence. The relevant theorem says that the series converges (absolutely) for $|z| < \rho$ and diverges for $|z| > \rho$. Therefore you know that the series is only allowed to converge for $|z| \leq \rho$ (but there is no guarantee of convergence on the circle of course). Since it converges when at $z=3+4i$, then is that the we get that $5 = |3+i4| \leq \rho$. And that's the best that you can say about $\rho$. It could be that it is 5, it could also be that it is 6.1, and it could even be infinity. For example the series for $e^z$ converges at $3+4i$, and in fact it converges everywhere. So the question, as stated, does not have enough information to state precisely what $\rho$ is.
On the other hand if you knew that the series converges but not absolutely at $3+4i$, then you could conclude that $\rho=5$. | The series converges at $z$ if $|z|$, which is the distance from $0$ to $z$, is less than the radius of convergence, and diverges if if $|z$ is more than the radius of convergence. If $|z|$ is exactly equal to the radius of convergence, then it may converge or diverge depending on which series you've got and which point on the boundary of the circle is $z$.
If $z= 3 + 4i$ then $|z| = \sqrt{3^2+4^2} = 5.$ So the radius of convergence must be $\ge 5$. The radius might be exactly $5$ or some finite number more than $5$ or $\infty$, depending on which series it is. |
3,992,541 | There are many, many questions and quality answers on SO regarding how to prevent leading zeroes from getting stripped when importing to or exporting from Excel. However, I already have a spreadsheet that has values in it that were truncated as numbers when, in fact, they should have been handled as strings. I need to clean up the data and add the leading zeros back in.
There is a field that should be four characters with lead zeros padding out the string to four characters. However:
```
"23" should be "0023",
"245" should be "0245", and
"3829" should remain "3829"
```
Question: Is there an Excel formula to pad these 0's back onto these values so that they are all four characters?
Note: this is similar to the age old Zip Code problem where New England-area zip codes get their leading zero dropped and you have to add them back in. | 2010/10/21 | [
"https://Stackoverflow.com/questions/3992541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369601/"
] | I know this was answered a while ago but just chiming with a simple solution here that I am surprised wasn't mentioned.
```
=RIGHT("0000" & A1, 4)
```
Whenever I need to pad I use something like the above. Personally I find it the simplest solution and easier to read. | If you use custom formatting and need to concatenate those values elsewhere, you can copy them and Paste Special --> Values elsewhere in the sheet (or on a different sheet), then concatenate those values. |
31,298,960 | I have a problem with one of my forms that I've created. It is supposed to be an email sender that allows the user to send an email to a given email in the code from a specified email that they put in `TextBox1`. The problem is that the email, when sent to my Gmail account, does not use this custom 'from' email.
Here is my code below:
```
Imports System.Net.Mail
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim EmailMessage As New MailMessage()
Try
EmailMessage.From = New MailAddress(TextBox1.Text)
EmailMessage.To.Add("to@gmail.com")
EmailMessage.Subject = TextBox2.Text
EmailMessage.Body = RichTextBox1.Text
Dim SMTP As New SmtpClient("smtp.gmail.com")
SMTP.Port = 587
SMTP.EnableSsl = True
SMTP.Credentials = New System.Net.NetworkCredential("user", "*******")
SMTP.Send(EmailMessage)
Catch ex As Exception
End Try
End Sub
End Class
```
And a picture of the form:

Can anybody help me out and make it so the "Return email:" field is the email that is used as the sender.
By the way, the subject and body fields do work correctly. | 2015/07/08 | [
"https://Stackoverflow.com/questions/31298960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | It looks like you are setting the `From` property correctly. That will set the `From` value in the SMTP header. However, not all email clients honor that `From` value in the header. GMail, in particular, ignores the `From` value in the header and always displays the actual email account that originally sent the message. Their intent in doing so is to avoid scams where people are fooled by fake From addresses. | I don't believe google let's you replace the From: address, it will always use the logged in users SMTP alias as the From:
You might be able to use the ReplyTo/ReplyToList properties though, have never tried.
EDIT: Did some further searching and found [this](https://stackoverflow.com/questions/5431631/when-using-gmail-for-smtp-can-you-set-a-different-from-address) issue that appears to be instructions for doing exactly what you want to do. |
10,740,265 | I understand the `-> theading macro in Clojure applies all the provided functions provided to a given argument. However, it doesn't seem to work with anonymous functions. For example:
```
user> (-> 4 inc inc dec)
5
```
But:
```
user> (-> 4 #(+ % 1) #(- % 1) #(+ % 1))
```
Returns the error:
```
clojure.lang.Symbol cannot be cast to clojure.lang.IPersistentVector
[Thrown class java.lang.ClassCastException]
```
If someone knows a way around it would be helpful. Thanks! | 2012/05/24 | [
"https://Stackoverflow.com/questions/10740265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767760/"
] | You can have anonymous functions in Clojure macros. You are having problems, because you are missing some parentheses. :) Your example is edited below.
```
(-> 4 (#(+ % 1)) (#(- % 1)) (#(+ % 1)))
``` | Your specific case could have been solved simply using:
```
(-> 4 (+ 1) (- 1) (+ 1))
```
where the thread first macro `->` takes care of inserting the result of the previous step as the first argument in the "current" function.
The confusion arises from the fact that `->` is not a function but a macro and the arguments are treated very differently in this case as explained by other answers. |
8,929,786 | For the past day I have been trying to figure out how to change the min-height styling on a jQuery mobile page when viewing in mobile safari. I have tried, inline styles, overriding ui-page styles and have yet to find a way to override the height of data-role="page". Ideally if the page "content" is less than the "page" height I would like the "page" height to automatically adjust to the "content". I have attached an illustration to better explain the issue.

```
<div data-role="page">
<div data-role="header">
Header Elements
</div>
<div data-role="content" class="homeNav">
<ul data-role="listview" data-inset="false" data-filter="false">
<li><a href="expertise.html">Expertise</a></li>
<li><a href="greatesthits.html">Greatest Hits</a></li>
<li><a href="profile.html">Profile</a></li>
<li><a href="mindset.html">Mindset</a></li>
<li><a href="connect.html">Connect</a></li>
</ul>
</div><!-- /content -->
<div data-role="footer" data-position="fixed">
Footer elements
</div><!-- /footer -->
</div><!-- /page -->
``` | 2012/01/19 | [
"https://Stackoverflow.com/questions/8929786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971677/"
] | The `min-height` of the `data-role="page"` element is set via JavaScript in a `resize` event handler for the `window` object. You can create your own JavaScript that resizes the page differently:
```
$(function () {
$(window).bind('resize', function (event) {
var content_height = $.mobile.activePage.children('[data-role="content"]').height(),
header_height = $.mobile.activePage.children('[data-role="header"]').height(),
footer_height = $.mobile.activePage.children('[data-role="footer"]').height(),
window_height = $(this).height();
if (content_height < (window_height - header_height - footer_height)) {
$.mobile.activePage.css('min-height', (content_height + header_height + footer_height));
setTimeout(function () {
$.mobile.activePage.children('[data-role="footer"]').css('top', 0);
}, 500);
}
event.stopImmediatePropagation();
}).trigger('resize');
});
```
Here is a demo: <http://jsfiddle.net/sAs5z/1/>
Notice the `setTimeout` used to set the `fixed-position-footer`; the timeout duration can probably be made smaller. This is used because the jQuery Mobile Framework was re-positioning the `fixed-position-footer` back to the bottom of the page. An example of this can be seen here: <http://jsfiddle.net/sAs5z/>
Another note, you may want to only re-position the `fixed-position-footer` element and leave the page's `min-height` property the same; this will make the page gradient cover the whole screen but the footer won't have any space between it and the content. Here is a demo of this method: <http://jsfiddle.net/sAs5z/2/> | I was facing the same issue when showing a popup with an overlay $.mobile.resetActivePageHeight(); did the trick for me. Thanx! |
15,745,047 | I would like to know whether there is any open free radius server which supports radius fragmentation i.e. radius server which accepts packets greater than 4k size limit from the client and will do reassembly of the packet at server end. And once whole packet is assembled, will do the successful authentication of the packet?
Any pointers will help. | 2013/04/01 | [
"https://Stackoverflow.com/questions/15745047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053024/"
] | Since you want to run this on some files containing code, here's an example of that full functionality:
```
$ cat file
foo() {
String1.append("Hello");
if (bar) {
s.append("\n\n\n");
}
else {
s.append("\n\\n\n\\\n");
}
}
$
$ cat tst.awk
match($0,/[[:alnum:]_]+\.append\(".*"\)/) {
split(substr($0,RSTART,RLENGTH), orig, /"/)
head = substr($0,1,RSTART-1) orig[1]
tail = orig[3] substr($0,RSTART+RLENGTH)
tgt = orig[2]
gsub(/[\\][\\]/,"X",tgt)
gsub(/[\\]/,"",tgt)
$0 = sprintf("%s\"%s\", %d%s", head, orig[2], length(tgt), tail)
}
{ print }
$
$ awk -f tst.awk file
foo() {
String1.append("Hello", 5);
if (bar) {
s.append("\n\n\n", 3);
}
else {
s.append("\n\\n\n\\\n", 6);
}
}
```
I replaced the "\w" from the example in the original posted question with the POSIX equivalent "[[:alnum:]\_]" for portability. "\w" will work with GNU awk and some other tools, but not all tools and not all awks. | Yay for perl!
```
x='String1.append("Hello");'
echo $x | perl -pe 's/(\w*\.append\(\")(.*)(\"\);)/my($len)=length($2); $_="$1$2, ${len}$3";/e'
``` |
17,562,740 | We are attempting to implement simple grouping of items within a ComboBox using the ICollectionView. The grouping and sorting being used in the CollectionView works correctly. But the popup items list created by the ComboBox does not function as intended because the scroll bar scrolls the groups not the items.
*eg: If there were 2 groups of 25 items, then the scroll bar would have two positions/points to scroll through rather than the desired 50.*
Can someone explain why the scroll bar scrolls the groups not the items within the groups, and how we might change this behavior?
Viewmodel setting up the **ICollectionView**:
```
public ViewModel()
{
CurrenciesView.Filter = CurrencyFilter;
CurrenciesView.SortDescriptions.Add(new SortDescription("MajorCurrency", ListSortDirection.Descending));
CurrenciesView.SortDescriptions.Add(new SortDescription("Code", ListSortDirection.Ascending));
CurrenciesView.GroupDescriptions.Add(new PropertyGroupDescription("MajorCurrency", new CurrencyGroupConverter()));
public ICollectionView CurrenciesView { get { return CollectionViewSource.GetDefaultView(currencies); } }
private ObservableCollection<Currency> currencies = new ObservableCollection<Currency>();
public ObservableCollection<Currency> Currencies
{
get { return this.currencies; }
set
{
if (this.currencies != value)
{
this.currencies = value;
this.PropertyChanged(this, new PropertyChangedEventArgs("Currencies"));
}
}
}
```
XAML UserControl hosting the ComboBox
```
<UserControl x:Class="FilterView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:ViewModels">
<UserControl.Resources>
<ResourceDictionary>
<DataTemplate x:Key="CurrencyItem">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Code}" FontWeight="ExtraBold"/>
<TextBlock Text="{Binding Description}" Margin="10,0,0,0"/>
</StackPanel>
</DataTemplate>
<Style TargetType="ComboBox">
<Setter Property="MinWidth" Value="100"/>
<Setter Property="Margin" Value="0,5,0,5"/>
</Style>
<DataTemplate x:Key="GroupHeader">
<TextBlock Text="{Binding Name}" Padding="3"/>
</DataTemplate>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.Row="0">Currency</Label>
<ComboBox Grid.Column="1" Grid.Row="0" Name="Currency"
ItemsSource="{Binding Path=CurrenciesView, Mode=OneWay}"
ItemTemplate="{StaticResource CurrencyItem}"
SelectedValuePath="Code"
IsSynchronizedWithCurrentItem="True">
<ComboBox.GroupStyle>
<GroupStyle HeaderTemplate="{StaticResource GroupHeader}"/>
</ComboBox.GroupStyle>
</ComboBox>
</Grid>
</UserControl>
```

 | 2013/07/10 | [
"https://Stackoverflow.com/questions/17562740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46654/"
] | Fixed by setting CanContentScroll = false on PART\_Popup template for the child ScrollViewer.
```
<UserControl x:Class="FilterView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:ViewModels">
<UserControl.Resources>
<ResourceDictionary>
<DataTemplate x:Key="CurrencyItem">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Code}" FontWeight="ExtraBold"/>
<TextBlock Text="{Binding Description}" Margin="10,0,0,0"/>
</StackPanel>
</DataTemplate>
<Style TargetType="ComboBox">
<Setter Property="MinWidth" Value="100"/>
<Setter Property="Margin" Value="0,5,0,5"/>
</Style>
<DataTemplate x:Key="GroupHeader">
<TextBlock Text="{Binding Name}" Padding="3"/>
</DataTemplate>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.Row="0">Currency</Label>
<ComboBox Grid.Column="1" Grid.Row="0" Name="Currency"
ItemsSource="{Binding Path=CurrenciesView, Mode=OneWay}"
ItemTemplate="{StaticResource CurrencyItem}"
SelectedValuePath="Code"
IsSynchronizedWithCurrentItem="True"
**ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="True"**>
<ComboBox.GroupStyle>
<GroupStyle HeaderTemplate="{StaticResource GroupHeader}"/>
</ComboBox.GroupStyle>
</ComboBox>
</Grid>
</UserControl>
```
Or in ComboBox derived control:
```
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
Popup popup = GetTemplateChild("PART_Popup") as Popup;
if (popup != null)
{
ScrollViewer scrollViewer = GetVisualChild<ScrollViewer>(popup.Child);
if (scrollViewer != null)
{
scrollViewer.CanContentScroll = false;
}
}
}
``` | ```
<Combobox ScrollViewer.CanContentScroll="False"></Combobox>
```
Use above code it will solve problem.
Regards,
Ratikanta |
8,869,131 | i want to make action bar top and down in android 4.03 make code but when i run it it doesn't appear , i don't know what is wrong , i search for reson before asking here but i didn't find anything
here is menu/style.xml code:
```
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/first"
android:icon="@drawable/cat"
/>
<item
android:id="@+id/first"
android:icon="@drawable/phone"
/>
<item
android:id="@+id/first"
android:icon="@drawable/music"
/>
<item
android:id="@+id/first"
android:icon="@drawable/dialog"
/>
<item
android:id="@+id/first"
android:icon="@drawable/file"
/>
<item
android:id="@+id/first"
android:icon="@drawable/contact"
/>
<item
android:id="@+id/first"
android:icon="@drawable/contact"
/>
</menu>
```
manifest code:
```
<activity
android:label="@string/app_name"
android:name=".CalendarActivity"
android:uiOptions="splitActionBarWhenNarrow"
>
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
and activity code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater i=getMenuInflater();
i.inflate(R.menu.style, menu);
return true;
}
```
because this is first use to android 4.0 i'm a little confused, why my items in black color i can't see them ?? | 2012/01/15 | [
"https://Stackoverflow.com/questions/8869131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1081907/"
] | if Object1 , Object2 and Object3 are JSON strings convert it to Javascript objects using `eval` function.
Then merge them using `concat` method.
<http://www.w3schools.com/jsref/jsref_concat_array.asp>
```
var mergedArray = arr1.concat(arr2, arr3);
```
Then sort using `sort` method in Javascript Array.
ref : <http://www.w3schools.com/jsref/jsref_sort.asp>
ref: <https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort>
```
var sorted = mergedArray.sort(function(a, b){
// This function is used by sort method for sorting process
// This function gets called with parameters a,b which are the elements in array (here product objects from your JSON)
// if this function returns value < 0 a is placed before b
// if this function returns 0 nothing is changed
// if this function returns value > 0 b is placed before a
// a.price.replace("Rs.", "") removes Rs. from price string. so "Rs. 200" becomes 200
// parseFloat(a.price.replace("Rs.", "")) makes it number. "200" becomes 200. "200.50" becomes 200.5
// priceA - priceB returns -ve value if priceA < priceB, 0 if priceA = priceB, +ve value if priceA > priceB.
var priceA = parseFloat(a.price.replace("Rs.", ""));
var priceB = parseFloat(b.price.replace("Rs.", ""));
return priceA - priceB;
});
```
Use `return priceB - priceA;` for descending order.
jsfiddle : <http://jsfiddle.net/diode/FzzHz/>
. | Convert them to object and [this](https://stackoverflow.com/a/1129270/475726) should do the trick |
10,114,355 | I've been using mongo and script files like this:
```
$ mongo getSimilar.js
```
I would like to pass an argument to the file:
```
$ mongo getSimilar.js apples
```
And then in the script file pick up the argument passed in.
```
var arg = $1;
print(arg);
``` | 2012/04/11 | [
"https://Stackoverflow.com/questions/10114355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367685/"
] | Use `--eval` and use shell scripting to modify the command passed in.
`mongo --eval "print('apples');"`
Or make global variables (credit to Tad Marshall):
```
$ cat addthem.js
printjson( param1 + param2 );
$ ./mongo --nodb --quiet --eval "var param1=7, param2=8" addthem.js
15
``` | I solved this problem, by using the javascript bundler parcel: <https://parceljs.org/>
With this, one can use node environment variables in a script like:
```
var collection = process.env.COLLECTION;
```
when building with parcel, the env var gets inlined:
```
parcel build ./src/index.js --no-source-maps
```
The only downside is, that you have to rebuild the script every time you want to change the env vars. But since parcel is really fast, this is not really a problem imho. |
9,403,814 | Ok, first of; here's what I did:
1. Install AZURE tools
2. Reboot
3. Start Visual Studio - new Azure project
4. Add web role (asp.net MVC 4 beta web role)
5. Hit F5 (debug)
It starts up the storage emulator and the compute emulator and starts to load in runtimes, and then I get a popup saying that the debugger couldn't connect.

Then after some googeling I'm suggested to try to run the application without running the debugger to see if I can acces the application. When I do I get this:

So I figure that IIS does not have permissions to access some file/directory. So I go to IIS and look up the application pool running the app, and it tells me that the identity in use is NetworkService, then I go give NetworkService full permissions to the entirety of the folder IIS has set for the application (which also happens to be the path to the project dir). Still I get the same error. Now I'm more or less out of ideas, but I try one last thing, which is to also give IUSR full permissions to the same dir, but this did not help either.
How can I go about resolving this problem? I haven't tried actually launching my project to Azure yet, cause if I can't even get it to work in development I don't see much point. Any and all help would be appreciated. | 2012/02/22 | [
"https://Stackoverflow.com/questions/9403814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/213323/"
] | I got this exact same error and tried a re-install of IIS and the Azure SDK - nothing worked.
Eventually tracked it down to the "IIS URL Rewrite Module 2". I went to the Control Panel and chose Repair and it resolved it. If you have a section in your web.config then this might be the cause. | Follow step 11 from <http://www.microsoft.com/en-us/download/details.aspx?id=35448>. Worked for me on Windows 8 with Oct 2012 SDk when upgraded from 2011. |
13,575,703 | I recently installed IPython after hearing about it on this forum. I am looking for an environment that is similar to what might come with MATLAB or RStudio for R.
I was under the impression that IPython would give me that but the version I downloaded for Windows looks very bare. In fact I do not really see a difference between IDLE and IPython except tab completion and history (which I have been wanting) but this is about as much as the interpreter that comes with R which I used to think was hard to work with.
Have I misunderstood the point of IPython? Or is it possible that I have not installed correctly?
I have also downloaded the 'Console' and while I am not convinced that it is working properly, it looks very bare as well.
Komodo looks good but is somewhat costly. Netbeans and Eclipse also look good, but do not seem to be straightforward to install, at least for somebody with my level of knowledge, so it would be good if somebody could verify their compatibility with Python, features, and ease of use for a non-expert user. | 2012/11/27 | [
"https://Stackoverflow.com/questions/13575703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816858/"
] | For the context, i've been using Eclipse, pycharm, got tired of those, and i started to ask around what people use, and the one i've heard the most about is [sublime text](http://www.sublimetext.com/).
You should take a look, maybe it's what you are looking for!
I just saw it's not open source though!
What i'm using now is [Ninja-IDE](http://ninja-ide.org/), which is written in python and is open source and seems pretty good! It has plenty of plugins, which includes an IPython plugin | Have you tried the [`qtconsole`](https://ipython.org/ipython-doc/3/interactive/qtconsole.html) backend? It was released after you asked your question.
>
> This is a very lightweight widget that largely feels like a terminal,
> but provides a number of enhancements only possible in a GUI, such as
> inline figures, proper multiline editing with syntax highlighting,
> graphical calltips, and much more.
>
>
>
From the Windows command prompt, enter:
```
ipython qtconsole
```
[](https://i.stack.imgur.com/ABqdj.jpg) |
30,145,779 | I'm trying to redirect www URLs to non-www for my forum. My forum is installed in a subdirectory called "forum". In my root directory I've got WordPress installed. For the WordPress in my root directory the .htaccess redirection works fine, but I'm having trouble get it working for my forum.
I've tried a couple of rules that I found in Google search but they didn't work.
I've also checked this topic [Generic htaccess redirect www to non-www](https://stackoverflow.com/questions/234723/generic-htaccess-redirect-www-to-non-www)
but in my case the htaccess file is in a subdirectory and not in the root.
Probably I'm doing something wrong so here is my entire .htaccess file:
```
# Mod_security can interfere with uploading of content such as attachments. If you
# cannot attach files, remove the "#" from the lines below.
#<IfModule mod_security.c>
# SecFilterEngine Off
# SecFilterScanPOST Off
#</IfModule>
ErrorDocument 401 default
ErrorDocument 403 default
ErrorDocument 404 default
ErrorDocument 405 default
ErrorDocument 406 default
ErrorDocument 500 default
ErrorDocument 501 default
ErrorDocument 503 default
<IfModule mod_rewrite.c>
RewriteEngine On
# If you are having problems with the rewrite rules, remove the "#" from the
# line that begins "RewriteBase" below. You will also have to change the path
# of the rewrite to reflect the path to your XenForo installation.
RewriteBase /forum
RewriteCond %{HTTP_HOST} www.example.com$
RewriteRule ^(.*)$ http://example.com/forum$1 [R=301,L]
# This line may be needed to enable WebDAV editing with PHP as a CGI.
#RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(data/|js/|styles/|install/|favicon\.ico|crossdomain\.xml|robots\.txt) - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
</IfModule>
```
Any help is appreciated.
Thanks | 2015/05/09 | [
"https://Stackoverflow.com/questions/30145779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2511117/"
] | To set up Dark theme as a "global" theme, and the theme you like from Eclipse Color Theme that you installed from Market Place, you can do the following. I used:
1. windows 10 (64 bit, but for 32 bit is probably the same)
2. eclipse oxygen
Steps:
1. Set the "global" theme to the dark theme: (`Windows>Preferences>General>Appearance>Theme:Dark`)
2. close eclipse. (You can change the Color Theme to let's say Recogn Eyes -which is my favorite-)
3. Re-open eclipse. (If you changed the Color theme you will have the default for the Dark theme, since you are reading this)
4. Open File explorer and look for `C:\Users\[user]\eclipse-workspace\.metadata\.plugins\org.eclipse.core.runtime\.settings`
5. Open `org.eclipse.e4.ui.css.swt.theme`.
6. Copy text after **`=`**, and **keep that in your clipboard** , in my case it was `org.eclipse.e4.ui.css.theme.e4_dark`
7. (In eclipse) Set the schema to default, and close the application.
8. open eclipse and choose your favorite color theme.
9. Close eclipse.
10. Go to the file `org.eclipse.e4.ui.css.swt.theme` again and paste what was in the clipboard (`themeid=org.eclipse.e4.ui.css.theme.e4_dark`, in my case) after the **=**. | Nothing from here works for me. I even deleted the workspace and created new one.
The only thing i kept was the git archive containing the eclipse project files and the java stuff.
And still after a restart the first 30s it seems as if it works. Then suddently the colors in the editor changes AND the content of the org.eclipse.e4.ui.css.swt.theme file changes the theme to "...default:" with some numbers at the end.
I have no plugins installed, only the package downloaded from eclipse.org |
37,048 | Can anyone advise on how to crop an image, let's say jpeg, without using any .NET framework constructs, just raw bytes? Since this is the only\* way in Silverlight...
Or point to a library?
I'm not concerned with rendering i'm wanting to manipulate a jpg before uploading.
\*There are no GDI+(System.Drawing) or WPF(System.Windows.Media.Imaging) libraries available in Silverlight.
Lockbits requires GDI+, clarified question
Using fjcore: <http://code.google.com/p/fjcore/> to resize but no way to crop :( | 2008/08/31 | [
"https://Stackoverflow.com/questions/37048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] | You could easily write crop yourself in fjcore. Start with the code for Resizer
<http://web.archive.org/web/20140304090029/http://code.google.com:80/p/fjcore/source/browse/trunk/FJCore/Resize/ImageResizer.cs?>
and FilterNNResize -- you can see how the image data is stored -- it's just simple arrays of pixels.
The important part is:
```
for (int y = 0; y < _newHeight; y++)
{
i_sY = (int)sY; sX = 0;
UpdateProgress((double)y / _newHeight);
for (int x = 0; x < _newWidth; x++)
{
i_sX = (int)sX;
_destinationData[0][x, y] = _sourceData[0][i_sX, i_sY];
if (_color) {
_destinationData[1][x, y] = _sourceData[1][i_sX, i_sY];
_destinationData[2][x, y] = _sourceData[2][i_sX, i_sY];
}
sX += xStep;
}
sY += yStep;
}
```
shows you that the data is stored in an array of color planes (1 element for 8bpp gray, 3 elements for color) and each element has a 2-D array of bytes (x, y) for the image.
You just need to loop through the destination pixels, copying then from the appropriate place in the source.
edit: don't forget to provide the patch to the author of fjcore | where is silverlight executed?
Is there any reason at all to send an complete picture to the client to make the client crop it?
Do it on the server... (if you are not creating an image editor that is..) |
184,204 | I have file like this :
```
other lines . . .
blah blah blah (:34)
```
I wish to find the occurrence of numbers in the above file. I came up with:
```
grep [0-9] filename
```
But that is printing the whole:
```
blah blah blah (:34)
```
Rather I want only `34`. Is there any way to do so? | 2012/09/05 | [
"https://askubuntu.com/questions/184204",
"https://askubuntu.com",
"https://askubuntu.com/users/12227/"
] | `grep -o` will print only the matching part of the line. Otherwise grep will print any lines with the pattern. | **I would use curl to access your file locally or remotely, then I would grep lines with numbers wrapped in (: ) then cut those pieces off and write to file**
the accepted answer ignores there could be numbers in the previous lines of the file, it does work for the example data, but what if the file was remote?
**Local**
```
curl file:///home/$USER/Public/input.txt | grep -o '(:.*)' | cut -d ":" -f 2 | cut -d ")" -f 1 > output.txt
```
In this example `output.txt` in your current folder will be written over, we are accessing `input.txt` from your Public folder.
**Remote**
```
curl https://yoursite.com/Public/input.txt | grep -o '(:.*)' | cut -d ":" -f 2 | cut -d ")" -f 1 > output.txt
```
In this example `output.txt` in your current folder will be written over, we are accessing `input.txt` from `https://yoursite.com/Public/`. |
2,468,132 | I have a script that looks like this
```
#!/bin/bash
function something() {
echo "hello world!!"
}
something | tee logfile
```
I have set the execute permission on this file and when I try running the file like this
```
$./script.sh
```
it runs perfectly fine, but when I run it on the command line like this
```
$sh script.sh
```
It throws up an error. Why does this happen and what are the ways in which I can fix this. | 2010/03/18 | [
"https://Stackoverflow.com/questions/2468132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18548/"
] | Running it as `./script.sh` will make the kernel read the first line (the shebang), and then invoke bash to interpret the script. Running it as `sh script.sh` uses whatever shell your system defaults `sh` to (on Ubuntu this is Dash, which is sh-compatible, but doesn't support some of the extra features of Bash).
You can fix it by invoking it as `bash script.sh`, or if it's your machine you can change `/bin/sh` to be bash and not whatever it is currently (usually just by symlinking it - `rm /bin/sh && ln -s /bin/bash /bin/sh`). Or you can just use `./script.sh` instead if that's already working ;)
If your shell is indeed dash and you want to modify the script to be compatible, <https://wiki.ubuntu.com/DashAsBinSh> has a helpful guide to the differences. In your sample it looks like you'd just have to remove the function keyword. | if your script is at your present working directory and you issue `./script.sh`, the kernel will read the shebang (first line) and execute the shell interpreter that is defined. you can also call your `script.sh` by specifying the path of the interpreter eg
```
/bin/bash myscript.sh
/bin/sh myscript.sh
/bin/ksh myscript.sh etc
```
By the way, you can also put your shebang like this (if you don't want to specify full path)
```
#!/usr/bin/env sh
``` |
58,915,047 | I want create a rotate icon inside a image:
```
<ImageBackground style={stylesNative2.image} source={{ uri }} >
<TouchableOpacity onPress={ () => { alert("handler here") }} tyle={styles.rotateImageIcon}>
<Icon name='rotate-ccw' type='Feather' style={styles.rotateImageIcon} />
</TouchableOpacity>
</ImageBackground>
const stylesNative2 = StyleSheet.create({
image: {
zIndex: 0,
position: 'absolute',
height: h,
width: WIDTH,
resizeMode: 'cover',
transform: [{ rotate: this.state.imageRotation + 'deg' }]
}
});
const styles = StylesManager.getStyles({
rotateImageButton: {
backgroundColor: 'transparent',
elevation: 0,
zIndex: 1
},
rotateImageIcon: {
marginTop: '1rem',
marginLeft: '1rem',
fontSize: '1.7rem',
color: 'white',
}
});
```
The icon appear but the TouchableOpacity is not working.
Any idea why it's not working? | 2019/11/18 | [
"https://Stackoverflow.com/questions/58915047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8830231/"
] | following command:
```
find -name '*[0-9][0-9][0-9][0-9]' -type d -exec bash -c 'for dir; do mv "$dir" "${dir%[0-9][0-9][0-9][0-9]}(${dir#${dir%[0-9][0-9][0-9][0-9]}})"; done' - {} + -prune
```
should work.
* double quote arround variable expansion
* `${dir%[0-9][0-9][0-9][0-9]}` to remove last 4 digits suffix
* `${dir#${dir%[0-9][0-9][0-9][0-9]}}` to remove previous prefix
* `-exec bash -c '..' - {} +` the `-` to skip the first argument after `-c command` which is taken for `$0`, see `man bash` `/-c`
* `-prune` at the end to prevent to search in sub tree when matched, (suppose `2004/2004` then `mv 2004/2004 "2004/(2004)"` or mv 2004/2004 (2004)/2004' would fail) | I found Bash annoying when it comes to find and rename files for all the escaping one needs to make. This is a cleaner Ruby solution :
```
#!/usr/bin/ruby
require 'fileutils'
dirs = Dir.glob('./**/*').select {|x| x =~ / [0-9]*/ }
dirs.sort().reverse().each do |dir|
new_name=dir.gsub(/(.*)( )([0-9]{4})/, '\1\2(\3)')
FileUtils.mv dir,new_name
end
``` |
309,208 | ...and what should we do with them?
I'm starting to see questions on the Python tag like:
* "How do you access a value in a list?" (i.e., how do you use a basic data structure)
* "How do I call a function?"
* "How do I call a method?"
These are extremely basic questions about simple language features that should be covered by any tutorial. They're not too broad, because each has a specific, simple answer. If they **are** duplicates, then I submit it's a waste of community time to moderate them that way. Why should I spend five minutes looking all over the site for a proper dupe target when in 5 minutes there will be 10 answers all saying the same thing?
These questions encourage both help vampires (who are asking them) and repwhores (who are lining up to answer them) and depleting the resources of moderating users who can't do anything about them. Downvoting doesn't do anything because the questions still get a ton of upvoted answers.
So what should we do? This will just get downvoted or closed if I turn this into yet another "We should bring back the minimal understanding" flag, but opening up SO to questions like, "How do I open up a text editor and type?" seems like a bad idea. | 2015/10/30 | [
"https://meta.stackoverflow.com/questions/309208",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/2588818/"
] | >
> Are there questions that are too trivial to answer?
>
>
>
No.
>
> Are there questions that are too trivial to answer *by Stack Overflow's standards*?
>
>
>
Yes. If I Google your problem and get a large number of hits, and a trivial inspection of one of those hits reveals the solution, then your question is too trivial for the site. | The coming-soon documentation feature should cover such simple questions. I hope we'll have a special flag or some other way to mark questions as already explained in the documentation. Then you won't have to search though a lot of questions because there will be a single and obvious place to search. |
4,745,994 | I just have a List<> and I would like to add an item to this list but at the first position.
List.add() add the item at the last.. How can I do that?..
Thanks for help! | 2011/01/20 | [
"https://Stackoverflow.com/questions/4745994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142234/"
] | ```
List<T>.Insert(0, item);
``` | Use `List.Insert(0, ...)`. But are you sure a [`LinkedList`](http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx) isn't a better fit? Each time you insert an item into an array at a position other than the array end, all existing items will have to be copied to make space for the new one. |
3,001,026 | I have a SQl Server 2005 database backup that I want to transfer to SQL Server 2008 on my server. I spent 3 days transferring the .bak file from my own machine to my server. I then tried to restore the bak file and I got an error. I then read online a completely different method for adding a SQL server 2005 Database to SQL server 2008 which was the detach and attach method which means I need to detach the database in SQL Server 2005 and then transfer the MDF file from it via ftp to my server and then attach it in SQL Server 2008. Well I already used a lot of bandwidth transferring the .bak file to my server. is there a way to convert my .bak file which is already on my server to an MDF file and attach it in SQL server 2008?
Here is the error:
==================================
Restore failed for Server 'SERVER'. (Microsoft.SqlServer.SmoExtended)
---
For help, click: <http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.0.1600.22+((SQL_PreRelease).080709-1414+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Restore+Server&LinkId=20476>
---
Program Location:
at Microsoft.SqlServer.Management.Smo.Restore.SqlRestore(Server srv)
at Microsoft.SqlServer.Management.SqlManagerUI.SqlRestoreDatabaseOptions.RunRestore()
===================================
System.Data.SqlClient.SqlError: RESTORE detected an error on page (61823:-268517280) in database "testing" as read from the backup set. (Microsoft.SqlServer.Smo)
---
For help, click:
---
Program Location:
at Microsoft.SqlServer.Management.Smo.ExecutionManager.ExecuteNonQueryWithMessage(StringCollection queries, ServerMessageEventHandler dbccMessageHandler, Boolean errorsAsMessages)
at Microsoft.SqlServer.Management.Smo.BackupRestoreBase.ExecuteSql(Server server, StringCollection queries)
at Microsoft.SqlServer.Management.Smo.Restore.SqlRestore(Server srv) | 2010/06/08 | [
"https://Stackoverflow.com/questions/3001026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197032/"
] | I've found the reason.
Query string parameter is using in my URL, so it looks like "<http://localhost/Image.ashx?id=49>". I've thought that if VaryByParams is not set explicitly, server will always take value of id param into account, because context.Response.Cache.VaryByParams.IgnoreParams is false by default. But in fact, server doesn't use cache at all in this case (nevertheless user browser does).
So, if parameters are using in query string, Response.Cache.VaryByParams should be set explicitly, like
```
context.Response.Cache.VaryByParams.IgnoreParams = true;
```
for ignoring parameters or
```
context.Response.Cache.VaryByParams[<parameter name>] = true;
```
for variation by some parameter or
```
context.Response.Cache.VaryByParams["*"] = true;
```
for variation by all parameters. | public cacheability depends on user browser or proxy it specifies that the response is cacheable by clients and shared (proxy) caches.
had you tried using `HttpCacheability.Server`
<http://msdn.microsoft.com/en-us/library/system.web.httpcacheability(v=VS.71).aspx> |
127,704 | I want to write a function that takes an array of letters as an argument and a number of those letters to select.
Say you provide an array of 8 letters and want to select 3 letters from that. Then you should get:
```
8! / ((8 - 3)! * 3!) = 56
```
Arrays (or words) in return consisting of 3 letters each. | 2008/09/24 | [
"https://Stackoverflow.com/questions/127704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9191/"
] | Here is my proposition in C++
I tried to impose as little restriction on the iterator type as i could so this solution assumes just forward iterator, and it can be a const\_iterator. This should work with any standard container. In cases where arguments don't make sense it throws std::invalid\_argumnent
```cpp
#include <vector>
#include <stdexcept>
template <typename Fci> // Fci - forward const iterator
std::vector<std::vector<Fci> >
enumerate_combinations(Fci begin, Fci end, unsigned int combination_size)
{
if(begin == end && combination_size > 0u)
throw std::invalid_argument("empty set and positive combination size!");
std::vector<std::vector<Fci> > result; // empty set of combinations
if(combination_size == 0u) return result; // there is exactly one combination of
// size 0 - emty set
std::vector<Fci> current_combination;
current_combination.reserve(combination_size + 1u); // I reserve one aditional slot
// in my vector to store
// the end sentinel there.
// The code is cleaner thanks to that
for(unsigned int i = 0u; i < combination_size && begin != end; ++i, ++begin)
{
current_combination.push_back(begin); // Construction of the first combination
}
// Since I assume the itarators support only incrementing, I have to iterate over
// the set to get its size, which is expensive. Here I had to itrate anyway to
// produce the first cobination, so I use the loop to also check the size.
if(current_combination.size() < combination_size)
throw std::invalid_argument("combination size > set size!");
result.push_back(current_combination); // Store the first combination in the results set
current_combination.push_back(end); // Here I add mentioned earlier sentinel to
// simplyfy rest of the code. If I did it
// earlier, previous statement would get ugly.
while(true)
{
unsigned int i = combination_size;
Fci tmp; // Thanks to the sentinel I can find first
do // iterator to change, simply by scaning
{ // from right to left and looking for the
tmp = current_combination[--i]; // first "bubble". The fact, that it's
++tmp; // a forward iterator makes it ugly but I
} // can't help it.
while(i > 0u && tmp == current_combination[i + 1u]);
// Here is probably my most obfuscated expression.
// Loop above looks for a "bubble". If there is no "bubble", that means, that
// current_combination is the last combination, Expression in the if statement
// below evaluates to true and the function exits returning result.
// If the "bubble" is found however, the ststement below has a sideeffect of
// incrementing the first iterator to the left of the "bubble".
if(++current_combination[i] == current_combination[i + 1u])
return result;
// Rest of the code sets posiotons of the rest of the iterstors
// (if there are any), that are to the right of the incremented one,
// to form next combination
while(++i < combination_size)
{
current_combination[i] = current_combination[i - 1u];
++current_combination[i];
}
// Below is the ugly side of using the sentinel. Well it had to haave some
// disadvantage. Try without it.
result.push_back(std::vector<Fci>(current_combination.begin(),
current_combination.end() - 1));
}
}
``` | Another one solution with C#:
```
static List<List<T>> GetCombinations<T>(List<T> originalItems, int combinationLength)
{
if (combinationLength < 1)
{
return null;
}
return CreateCombinations<T>(new List<T>(), 0, combinationLength, originalItems);
}
static List<List<T>> CreateCombinations<T>(List<T> initialCombination, int startIndex, int length, List<T> originalItems)
{
List<List<T>> combinations = new List<List<T>>();
for (int i = startIndex; i < originalItems.Count - length + 1; i++)
{
List<T> newCombination = new List<T>(initialCombination);
newCombination.Add(originalItems[i]);
if (length > 1)
{
List<List<T>> newCombinations = CreateCombinations(newCombination, i + 1, length - 1, originalItems);
combinations.AddRange(newCombinations);
}
else
{
combinations.Add(newCombination);
}
}
return combinations;
}
```
Example of usage:
```
List<char> initialArray = new List<char>() { 'a','b','c','d'};
int combinationLength = 3;
List<List<char>> combinations = GetCombinations(initialArray, combinationLength);
``` |
10,914,802 | I am aware that this is a very basic question, but an interviewer asked me in a very trick way and I was helpless :(
I know only material or theoretical definition for an interface and also implemented it in many projects I worked on. But I really don't understand why and how is this useful.
I also don't understand one thing in interface. i.e for example, we use
`conn.Dispose();` in finally block. But I don't see that class is implementing or inheriting `IDisposable` interface (`SqlConnection`) class I mean. I am wondering how I can just call the method name. Also in the same thing, I am not understanding how Dispose method works as because, we need to implement the function body with our own implementation for all interface methods. So how Interfaces are accepted or named as contracts? These questions kept on rolling in my mind till now and frankly I never saw any good thread that would explain my questions in a way that I can understand.
MSDN as usual looks very scary and no single line is clear there (*Folks, kindly excuse who are into high level development, I strongly feel that any code or article should reach the mind of anyone who see it, hence like many others say, MSDN is not of use*).
The interviewer said:
He has 5 methods and he is happy to implement it in the class directly, but if you have to go for Abstract class or interface, which one you choose and why ? I did answered him all the stuffs that I read in various blog saying advantage and disadvantage of both abstract class and interface, but he is not convinced, he is trying to understand "Why Interface" in general. "Why abstract class" in general even if I can implement the same methods only one time and not gona change it.
I see no where in net, I could get an article that would explain me clearly about interfaces and its functioning. I am one of those many programmers, who still dont know about interfaces (I know theoretical and methods I used) but not satisfied that I understood it clearly. | 2012/06/06 | [
"https://Stackoverflow.com/questions/10914802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1183979/"
] | This is an easy example:
Both of `Array` and `List` implement the interface `IList`. Below we have a `string[]` and a `List<string>` and manipulate both of them with only one method by using **IList**:
```
string[] myArray = { "zero", "one", "two", "three", "four"};
List<string> myList = new List<string>{ "zero", "one", "two", "three"};
//a methode that manipulates both of our collections with IList
static void CheckForDigit(IList collection, string digit)
{
Console.Write(collection.Contains(digit)); //checks if the collection has a specific digit
Console.Write("----");
Console.WriteLine(collection.ToString()); //writes the type of collection
}
static void Main()
{
CheckForDigit(myArray, "one"); //True----System.String[]
CheckForDigit(myList, "one"); //True----System.Collections.Generic.List`1[System.String]
//Another test:
CheckForDigit(myArray, "four"); //True----System.String[]
CheckForDigit(myList, "four"); //false----System.Collections.Generic.List`1[System.String]
}
``` | You can only inherit from one abstract class. You can inherit from multiple interfaces. This determines what I use for most of the cases.
The advantage of abstract class would be that you can have a base implementation. However, in the case of IDisposable, a default implementation is useless, since the base class does not know how to properly clean things up. Thus, an interface would be more suitable. |
49,248,195 | New to Hugo and css. Trying to change the fonts of the beautifulhugo theme based on these instruction:
See Chandra's Nov 17 post:
<https://discourse.gohugo.io/t/font-selection-in-theme/8803/8>
I have downloaded two fonts and placed them in static/fonts
Added the following to config.toml
```
googlefonts = “http://fonts.googleapis.com/css?family=Itim|Limelight”
```
Added this to static/css/custom\_style.css
```
body {
font-family: ‘Limelight’, cursive;
}
p {
font-family: ‘Itim’, cursive;
}
```
And added this to layouts/partials/head\_custom.html
```
{{ if .Site.Params.googlefonts }}
<link rel="stylesheet" href="{{ .Site.Params.googlefonts }}" type="text/css" media="all" />
{{ end }}
```
yet, no changes are visible. Please advise as to what I am doing wrong.
Everything should be available here: <https://github.com/ixodid198/blog> | 2018/03/13 | [
"https://Stackoverflow.com/questions/49248195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5057346/"
] | In config.toml, add
```
[params]
custom_css = ["css/custom_style.css"]
```
Not sure if this works on all themes generally, but it works on [the theme I'm using](https://themes.gohugo.io/hugo-coder/). | You say:
>
> I have downloaded two fonts and placed them in static/fonts
>
>
>
Why would you do that if you are using google fonts?
Anyway, did you try removing `http:` form `googlefonts = “http://fonts.googleapis.com/css?family=Itim|Limelight”`
You probably have something down the line in your code that is overwriting you font settings.
It would be helpfull if you could put your site somewhere online so that we can check what is going on. |
96,201 | I believe there is a single word that represents what I am trying to say, but for the life of me I can’t remember it.
I have a line graph of amounts vs. time. The amounts are for different currencies. I then have a derivative graph where all the amounts are in one currency.
>
> The second graph is [blanked] to the same currency.
>
>
>
I thought of *normalized*, but it doesn't feel quite right. The idea behind this word is to take a disparate dataset and to make it the same. | 2012/12/31 | [
"https://english.stackexchange.com/questions/96201",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/33005/"
] | How about *exchanged*?
Graph 1 represents each series in the local currency.
Graph 2 represents each currency exchanged to [reporting currency here] using the [datasource] rates as of [datestamp]. | I am also a fan of **normalized**, but here is another option: When one set of data is translated into coordinate system, we sometimes say the data is *projected*. This is more commonly used when converting from a 3-dimensional system to a 2-dimensional system, such as using a flat map to represent a globe (consider the [Mercator Projection](https://en.wikipedia.org/wiki/Mercator_projection)) |
12,571,031 | If I have a view and want to see all the set variables for the particular view, how would I do it? | 2012/09/24 | [
"https://Stackoverflow.com/questions/12571031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/873429/"
] | Variables assigned to a `Zend_View` object simply become public properties of the view object.
Here are a couple of ways to get all variables set in a particular view object.
**From within a view script:**
```
$viewVars = array();
foreach($this as $name => $value) {
if (substr($name, 0, 1) == '_') continue; // protected or private
$viewVars[$name] = $value;
}
// $viewVars now contains all view script variables
```
**From a `Zend_View` object in a controller:**
```
$this->view->foo = 'test';
$this->view->bar = '1234';
$viewVars = get_object_vars($this->view);
// $viewVars now contains all public properties (view variables)
```
The last example would work just as well for a view object created manually using `$view = new Zend_View();` | ```
$this->view->getVars()
```
or from inside the view
```
$this->getVars()
``` |
19,321,609 | I added `vertical-align: middle` for all td with day number:
```
#calendar td {
vertical-align: middle !important;
}
```
but this don't work for responsive web page for first column:
How I can fix it?
I try added margin-top in % and em, its work for tablet, bot don't work on PC browser.
UPDATE: added code on jsfiddle: <http://jsfiddle.net/8ctRu/>
**HTML**
```
<div id='calendar'></div>
```
**CSS**
```
#calendar td {
vertical-align: middle !important;
border: 1px solid #000;
}
.fc {
text-align: center !important;
}
.fc td {
padding: 0;
vertical-align: middle !important;
}
```
**jQuery**
```
$('#calendar').fullCalendar({
header: {
left: 'prev',
center: 'title',
right: 'next'
},
dayClick: function(date, allDay, jsEvent, view) {
var now = new Date();
if (date.setHours(0,0,0,0) > now.setHours(0,0,0,0)){
$(this).toggleClass("blackAndWhite");
} else {
$(tempVar).css({
'background-color':'white',
'color' : '#000'
});
}
}
});
``` | 2013/10/11 | [
"https://Stackoverflow.com/questions/19321609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970863/"
] | This will center the day vertically without JS. Not sure what it'll do to the events though.
Added to your demo: <http://jsfiddle.net/8ctRu/10/>
```
.fc-day:first-child > div:first-child {
position: relative;
}
.fc-day:first-child > div:first-child .fc-day-number {
position: absolute;
top: 50%;
left: 0px;
right: 0px;
text-align: center;
margin-top: -.5em;
line-height: 1em;
}
``` | `min-height:64px` is throwing you off..
Put the `height:64px` on the container `<td>` |
32,497,466 | I need to connect two tables by two columns.
First table has primary key as integer type id.
Second table has varchar2 type column which contains the same primary key but is located in the middle of a string.
>
> For example in first table I have column called integer ID with ID
> like 1234. In the second table I have column with string like
> 'abcdefgh - 1234 (ijklmno)'.
>
>
>
Is there a way to use that nested key? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32497466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | From Oracle 11g you can use a virtual column:
[SQL Fiddle](http://sqlfiddle.com/#!4/30645/1)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE TableA (
id NUMBER(4,0) PRIMARY KEY
);
INSERT INTO TableA VALUES ( 1234 );
CREATE TABLE TableB (
data VARCHAR2(25) NOT NULL
CHECK ( REGEXP_LIKE( data, '\w+ - (0|[1-9]\d{0,3}) \(\w+\)' ) ),
id NUMBER(4,0) GENERATED ALWAYS AS ( TO_NUMBER( REGEXP_SUBSTR( data, '\w+ - (0|[1-9]\d{0,3}) \(\w+\)', 1, 1, null, 1 ) ) ) VIRTUAL,
CONSTRAINT TableB__ID__FK FOREIGN KEY ( id ) REFERENCES TableA ( id )
);
INSERT INTO TableB ( data ) VALUES ( 'abcdefgh - 1234 (ijklmno)' );
```
**Query 1**:
```
SELECT * FROM TableB
```
**[Results](http://sqlfiddle.com/#!4/30645/1/0)**:
```
| DATA | ID |
|---------------------------|------|
| abcdefgh - 1234 (ijklmno) | 1234 |
``` | Firstly, the table **design** is bad. You should have the **primary key** column with a **foreign key relationship** in the second table. And have a **supporting index** for the foreign key. Storing **delimited text** in a **single column** is not a good design and violates **normalization**.
If the pattern of the string is same for all the rows in the second table, then you could use **SUBSTR** to extract the required string and then **join** with the first table.
For example,
```
SQL> WITH t(str) AS(
2 SELECT 'abcdefgh - 1234 (ijklmno)' FROM dual
3 )
4 SELECT substr(str, 12, 4) new_str FROM t;
NEW_
----
1234
SQL>
```
You could join `substr(str, 12, 4)` with the primary key of the first table,
```
SELECT column_list
FROM table_1 t1
JOIN table_2 t2
ON (t1.primary_key = substr(column_name, 12, 4)
WHERE ...
```
From **performance point of view**, you need to create a **function-based index** on the column in second table:
```
CREATE INDEX fn_idx_col ON table_2(substr(column_name, 12, 4));
```
From 11g onwards, `VIRTUAL COLUMN` is introduced. However, creating an **index** on the **virtual column** is same as creating a **function-based index** on a static column.
**NOTE** Since you do not have a foreign key relationship, you will always end up with **tablescans on both the tables**. If you have the proper relationships, then *ideally* **Oracle would only use the primary key of the first table and avoid any table scan on the second table**. |
855,334 | I would like my `Canvas` to automatically resize to the size of its items, so that the `ScrollViewer` scroll bars have the correct range. Can this be done in XAML?
```
<ScrollViewer HorizontalScrollBarVisibility="Auto" x:Name="_scrollViewer">
<Grid x:Name ="_canvasGrid" Background="Yellow">
<Canvas x:Name="_canvas" HorizontalAlignment="Left" VerticalAlignment="Top" Background="Green"></Canvas>
<Line IsHitTestVisible="False" .../>
</Grid>
</ScrollViewer>
```
In the above code the canvas always has size 0, though it doesn't clip its children. | 2009/05/12 | [
"https://Stackoverflow.com/questions/855334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22820/"
] | ```
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
autoSizeCanvas(canvas1);
}
void autoSizeCanvas(Canvas canv)
{
int height = canv.Height;
int width = canv.Width;
foreach (UIElement ctrl in canv.Children)
{
bool nullTop = ctrl.GetValue(Canvas.TopProperty) == null || Double.IsNaN(Convert.ToDouble(ctrl.GetValue(Canvas.TopProperty))),
nullLeft = ctrl.GetValue(Canvas.LeftProperty) == null || Double.IsNaN(Convert.ToDouble(ctrl.GetValue(Canvas.LeftProperty)));
int curControlMaxY = (nullTop ? 0 : Convert.ToInt32(ctrl.GetValue(Canvas.TopProperty))) +
Convert.ToInt32(ctrl.GetValue(Canvas.ActualHeightProperty)
),
curControlMaxX = (nullLeft ? 0 : Convert.ToInt32(ctrl.GetValue(Canvas.LeftProperty))) +
Convert.ToInt32(ctrl.GetValue(Canvas.ActualWidthProperty)
);
height = height < curControlMaxY ? curControlMaxY : height;
width = width < curControlMaxX ? curControlMaxX : width;
}
canv.Height = height;
canv.Width = width;
}
```
In the function, i'm trying to find the maximum X position and Y position, where controls in the canvas can reside.
Use the function only in Loaded event or later and not in constructor. The window has to be measured before loading.. | I have also encountered this problem, my issue was that the grid wasn't auto-resizing when the Canvas did resize thanks to the overrided MeasureOverride function.
my problem:
[WPF MeasureOverride loop](https://stackoverflow.com/questions/30726257/wpf-measureoverride-loop) |
41,913,818 | let me first start with showing the code:
build.gradle (module):
```
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
dataBinding {
enabled = true
}
defaultConfig {
applicationId "com.example.oryaa.basecalculator"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.google.android.gms:play-services-appindexing:8.1.0'
```
activity\_main.xml:
```
<data>
<import type="android.view.View" />
<variable
name="baseCalcModel"
type="com.example.oryaa.basecalculator.BaseCalcModel">
</variable>
</data> <TextView
android:id="@+id/resultOutput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/resultTextView"
android:textColor="@color/DarkBlue"
android:text="@{baseCalcModel.calcResult}"
android:textSize="32dp" />
```
MainActicity.java:
```
public class MainActivity extends AppCompatActivity {
EditText userInput = null;
TextView resultTV = null;
Spinner fromBaseSpinner = null;
Spinner toBaseSpinner = null;
ArrayList<String> spinnerArray = new ArrayList<>();
String _allowedChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String _onlyOnceChar = "-+*/";
BaseCalcModel baseCalcModel = new BaseCalcModel();
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setBaseCalcModel(this.baseCalcModel);
this.resultTV = (TextView) this.findViewById(R.id.resultOutput);
this.fromBaseSpinner = (Spinner) findViewById(R.id.fromBaseSpinner);
this.toBaseSpinner = (Spinner) findViewById(R.id.toBaseSpinner);
this.userInput = (EditText) findViewById(R.id.userInput);
SetupUI();
baseCalcModel.setCalcResult("test");
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
```
BaseCalcModel.java:
```
ublic class BaseCalcModel extends BaseObservable {
public String calcResult;
public BaseView firstNumView;
public BaseView secondNumView;
public BaseView resultNumView;
public int firstNumBase;
public int secondNumBase;
public int resultNumBase;
public String error;
@Bindable
String getCalcResult() {
return calcResult;
}
@Bindable
public BaseView getFirstNumView() {
return firstNumView;
}
@Bindable
public BaseView getSecondNumView() {
return secondNumView;
}
@Bindable
public BaseView getResultNumView() {
return this.resultNumView;
}
@Bindable
public int getFirstNumBase() {
return this.firstNumBase;
}
@Bindable
public int getSecondNumBase() {
return this.secondNumBase;
}
@Bindable
public int getResultNumBase() {
return this.resultNumBase;
}
@Bindable
public String getError() {
return this.error;
}
public void setCalcResult(String calcResult) {
this.calcResult = calcResult;
notifyPropertyChanged(com.example.oryaa.basecalculator.BR.calcResult);
}
public void setFirstNumView(BaseView firstNumView) {
this.firstNumView = firstNumView;
notifyPropertyChanged(com.example.oryaa.basecalculator.BR.firstNumView);
}
public void setSecondNumView(BaseView secondNumView) {
this.secondNumView = secondNumView;
notifyPropertyChanged(com.example.oryaa.basecalculator.BR.secondNumView);
}
public void setResultNumView(BaseView resultNumView) {
this.resultNumView = resultNumView;
notifyPropertyChanged(com.example.oryaa.basecalculator.BR.resultNumView);
}
public void setFirstNumBase(int firstNumBase) {
this.firstNumBase = firstNumBase;
notifyPropertyChanged(com.example.oryaa.basecalculator.BR.firstNumBase);
}
public void setSecondNumBase(int secondNumBase) {
this.secondNumBase = secondNumBase;
notifyPropertyChanged(com.example.oryaa.basecalculator.BR.secondNumBase);
}
public void setResultNumBase(int resultNumBase) {
this.resultNumBase = resultNumBase;
notifyPropertyChanged(com.example.oryaa.basecalculator.BR.resultNumBase);
}
public void setError(String error) {
this.error = error;
notifyPropertyChanged(com.example.oryaa.basecalculator.BR.error);
}
public BaseCalcModel() {
firstNumView = new BaseView();
secondNumView = new BaseView();
resultNumView = new BaseView();
firstNumBase = 0;
secondNumBase = 0;
resultNumBase = 0;
calcResult = "";
error = "";
}
public BaseCalcModel(BaseView firstNumView, BaseView secondNumView, BaseView resultNumView,
int firstNumBase, int secondNumBase, int resultNumBase, String clcResult,
String error) {
this.firstNumView = firstNumView;
this.secondNumView = secondNumView;
this.resultNumView = resultNumView;
this.firstNumBase = firstNumBase;
this.secondNumBase = secondNumBase;
this.resultNumBase = resultNumBase;
this.calcResult = clcResult;
this.error = error;
}
```
[](https://i.stack.imgur.com/fFGTq.png)
Im trying to do simple data binding, but my view doesn't updating after the proparty is changing.
as you can see in the image, my code arriving to:
```
notifyPropertyChanged(com.example.oryaa.basecalculator.BR.calcResult);
```
but the view is updating only when the app started or when I'm rotating my phone for vertical to horizontal or vice versa.
Where is my problem?
Thanks a lot,
Or Yaacov | 2017/01/28 | [
"https://Stackoverflow.com/questions/41913818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I had a similar issue when I needed to refresh the views after an event, with my variable objects not observable, so I added this:
```
binding?.invalidateAll()
```
I hope it helps. | You need to call `executePendingBindings()` for immediately update binding value in view:
>
> When a variable or observable changes, the binding will be scheduled to change before the next frame. There are times, however, when binding must be executed immediately. To force execution, use the executePendingBindings() method.
>
>
>
Look at [Advanced Binding](https://developer.android.com/topic/libraries/data-binding/index.html) chapter for more info |
10,472 | How do I find public Minecraft servers?
Is there a directory of them? | 2010/11/08 | [
"https://gaming.stackexchange.com/questions/10472",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/3375/"
] | There is no *official* directory for Minecraft servers, but the most popular places are:
[Minecraft Classic Servers](http://www.minecraft.net/servers.jsp)
[Minecraft Alpha Servers](http://servers.minecraftforum.net/) | There is also [Abyssal-Legion Minecraft Server Status Page](http://minecraft.abyssal-legion.com/serverstatus/). |
1,012,453 | Georg Cantor is formally known as the first one who discovered existence of infinities of different sizes. But the history of thinking about the concept of "infinity" in maths and philosophy goes back to ancient era.
>
> **Question:** Was there anybody (mathematician, philosopher, etc.) *before* Cantor who mentioned (or conjectured) existence of infinities of different sizes even if he stated this claim informally? Please introduce your references.
>
>
> | 2014/11/08 | [
"https://math.stackexchange.com/questions/1012453",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | See [Galileo's Paradox](http://en.wikipedia.org/wiki/Galileo's_paradox) with the English transaltion of the relevant part of
* *Discorsi e dimostrazioni matematiche intorno a due nuove scienze attenenti alla meccanica e i movimenti locali* (Leida, 1638) :
>
>
> >
> > *Simpl.* Qui nasce subito il dubbio, che mi pare insolubile: ed è, che sendo noi sicuri trovarsi linee una maggior dell'altra, tutta volta che amendue contenghino punti infiniti, bisogna confessare trovarsi nel medesimo genere una cosa maggior dell'infinito, perché la infinità de i punti della linea maggiore eccederà l'infinità de i punti della minore. Ora questo darsi un infinito maggior dell'infinito mi par concetto da non poter esser capito in verun modo.
> >
> >
> > *Salv.* Queste son di quelle difficoltà che derivano dal discorrer che noi facciamo col nostro intelletto finito intorno a gl'infiniti, dandogli quelli attributi che noi diamo alle cose finite e terminate; il che penso che sia inconveniente, perché stimo che questi attributi di maggioranza, minorità ed egualità non convenghino a gl'infiniti, de i quali non si può dire, uno esser maggiore o minore o eguale all'altro. Per prova di che già mi sovvenne un sì fatto discorso, il quale per più chiara esplicazione proporrò per interrogazioni al Sig. Simplicio, che ha mossa la difficoltà.
> >
> >
> >
>
>
>
Here the English translation [from Wikipedia : Galileo Galilei, *Dialogues concerning two new sciences*, transl. Crew and de Salvio (Dover reprint, 1954), pp.31–33] :
>
> *Simplicio* : Here a difficulty presents itself which appears to me insoluble. Since it is clear that **we may have one line greater than another, each containing an infinite number of points, we are forced to admit that, within one and the same class, we may have something greater than infinity** [emphasis added], because the infinity of points in the long line is greater than the infinity of points in the short line. This assigning to an infinite quantity a value greater than infinity is quite beyond my comprehension.
>
>
> *Salviati* : This is one of the difficulties which arise when we attempt, with our finite minds, to discuss the infinite, assigning to it those properties which we give to the finite and limited; but this I think is wrong, for we cannot speak of infinite quantities as being the one greater or less than or equal to another. To prove this I have in mind an argument which, for the sake of clearness, I shall put in the form of questions to Simplicio who raised this difficulty.
>
>
>
[...]
>
> *Sagredo* : What then must one conclude under these circumstances?
>
>
> *Salviati* : So far as I see we can only infer that the totality of all numbers is infinite, that the number of squares is infinite, and that the number of their roots is infinite; neither is the number of squares less than the totality of all the numbers, nor the latter greater than the former; and finally the attributes "equal," "greater," and "less," are not applicable to infinite, but only to finite, quantities. When therefore Simplicio introduces several lines of different lengths and asks me how it is possible that the longer ones do not contain more points than the shorter, I answer him that one line does not contain more or less or just as many points as another, but that each line contains an infinite number.
>
>
>
So Galileo's conclusion was **not** a pre-cantorian theory of *infinites* of different size but the clear understanding that some "properties" of *finite* "magnitudes" (like : "equal", "greater" and "less") are not applicable to the infinite ones.
---
This discussion about the *Paradox of infinite* traces back to medieval philosophy; see [Nicole Oresme](http://plato.stanford.edu/entries/nicole-oresme/) using
>
> the principle of one-to-one correspondence [to show] that the collection of odd natural numbers is not smaller than the collection of natural numbers, because it is possible to count the odd natural numbers by the natural numbers [para **2.6 Mathematics**, and also the reference to Bearwardine].
>
>
> Oresme shows that of two actual infinites neither is greater or smaller than the other. [...] Oresme's result does not necessarily imply equality between actual infinites. Moreover Oresme shows that cases can be conceived in which two infinites can be regarded as unequal, but this unequality is not to be understood in the sense of ‘smaller’ or ‘greater’ (Oresme does not contradict himself), but rather in the sense of ‘different’.
>
>
> Since comparable quantities are either equal to one another or one is smaller or greater than the other, Oresme concludes that actual infinites are incomparable: that is, that notions like ‘smaller’, ‘bigger’, and ‘equal’ do not apply to infinites.
>
>
> | According to [this reference](http://books.google.ca/books?id=hN454jMVmLkC&pg=PA183&lpg=PA183&dq=earliest%20reference%20to%20infinity&source=bl&ots=zLehq-58CB&sig=8IbtwFtlI8X_RV9cm0mwDR516co&hl=en&sa=X&ei=8Y9eVO67IdDtoATulILwBw&ved=0CEgQ6AEwBw#v=onepage&q=earliest%20reference%20to%20infinity&f=false)
in 400BC, Jain mathematicians distinguished between five types of infinity : infinite in one direction, infinite in two directions, infinite in area, infinite everywhere, and infinite perpetually.
Of course, this is not entirely a proper distinction, however one could say that the perpetually infinite is distinct from the spacially infinite, so they may have *correctly* identified two different infinities.
Regarding Cantor, his well-documented comment - "I see it but I don't believe it" - would seem to suggest that he believed he was the first to explode these ideas (formally). |
51,205,695 | I'm implementing an App only for iPad and apparently react native doesn't support numeric keyboard type for iPad. just want to know any idea how to manage keyboard to show only numbers.
I tried some regular expression but it doesn't work properly. | 2018/07/06 | [
"https://Stackoverflow.com/questions/51205695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2083099/"
] | For some reason this is not supported for Ipad. So you will need to either:
1) Show non-numeric characters but only accept numeric characters (via code).
2) Use this library [react-native-custom-keyboard](https://github.com/reactnativecn/react-native-custom-keyboard). | Try
```
keyboardType = 'number-pad'
```
Hope it works
Or read some [article](https://facebook.github.io/react-native/docs/textinput#keyboardtype) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.