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 |
|---|---|---|---|---|---|
217,266 | I'm making a French cleat wall for a home office. I'm wondering how to make the strongest French cleat. Is it the length/angle of the bevel that matters most, like in B vs A in the diagram? Or is it the overall width of the cleat that is attached to the wall, like in X vs Y? Or does overall thickness of material (as in across A-side/B-side) make the real difference?
[](https://i.stack.imgur.com/mqEaF.png) | 2021/02/24 | [
"https://diy.stackexchange.com/questions/217266",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/115472/"
] | If you consider the physics of this, the B wedge is going to apply more outward force on the cleat attached to the wall then the A wedge for a given amount of weight supported. So you might cause the attachment to the wall to fail long before you would be reaching the capacity of the bolt's shear limit.
Generally a relatively shallow angle will give you all the support you need as you really just want it deep enough to keep the supported item from popping off the cleat.
If you are concerned about the amount of weight supported, use a wider cleat not a steeper angle on the cut.
Bottom line: Between your two diagrams, the LEFT one is the better choice. | I don't know that the strength really lies in the angle. If I were picking, I'd go with X over Y, but because you don't want to create too much of a wedge between the cleat and the wall (Y will put more stress on the cleat fasteners). The bevel helps it not slide off the cleat.
The main advantage of the cleat is you can mount a board to the wall in a secure fashion **before** you hang your heavy item on it. |
7,857,882 | I need to read from a file from using C.
```
#include <stdio.h>
struct record{
char name[2];
int arrival_time;
int job_length;
int job_priority;
};
const int MAX = 40;
main(){
struct record jobs[MAX];
FILE *f;
fopen("data.dat","rb");
int count =0;
while(fscanf(f, "%c%c %d %d %d", &jobs[count].name, &jobs[count].arrival_time, &jobs[count].job_length, &jobs[count].job_priority) != EOF){
count++;
}
int i;
for(i =0;i<count;i++){
printf("%c%c %d %d %d", &jobs[count].name, &jobs[count].arrival_time, &jobs[count].job_length, &jobs[count].job_priority);
}
}
```
The data file's format is the following:
```
A1 3 3 3
B1 4 4 4
C1 5 5 5
```
...
First one is char[2] and the other three int. I can't get the code right to read in until the end of file.
Anyone come across this before?
Updated Code. | 2011/10/22 | [
"https://Stackoverflow.com/questions/7857882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/695156/"
] | You need to get the line and parse it according to the type you want to read.
```
while(fgets(line, 80, fr) != NULL)
{
/* get a line, up to 80 chars from fr. done if NULL */
sscanf (line, "%s %d %d %d", &myText, &int1, &int2, &int3);
}
```
See example here:
<http://www.phanderson.com/files/file_read.html> | No, the lines do not contain ints. Each line is a string which can be easily parsed into four shorter strings. Then each of the strings can either be extracted and stored in your struct, or converted to ints which you can store in your struct.
The `scanf` function is the usual way that people do this kind of input string parsing when the data format is simple and straightforward. |
26,015,237 | I am trying to run multiple suites from one overall suite file. I define the suites I need to run and run the "master" suite file. I have used preserve-order to run each suite in sequence, however the behaviour is not as I would expect. It seems that it runs them straight away, one after the other, almost in parallel.
Does anyone know a way I can execute the suites, preserving the order, ideally waiting for first suite to finish before second suite will run?
My suite setup is as follows:
```
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="My test suite" preserver-order=true>
<suite-files>
<suite-file path="Test1.xml"></suite-file>
<suite-file path="Test2.xml"></suite-file>
<suite-file path="Test3.xml"></suite-file>
</suite-files>
</suite>
```
Regards,
Jacko | 2014/09/24 | [
"https://Stackoverflow.com/questions/26015237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4074322/"
] | According to the [testng documentation](http://testng.org/doc/documentation-main.html#testng-xml),
>
> By default, TestNG will run your tests in the order they are found in the XML file. If you want the classes and methods listed in this file to be run in an unpredictible order, set the preserve-order attribute to false
>
>
>
Moreover, if you want the execution to run in an unpredictable manner you can do it as following.
```
<suite name="My test suite" preserver-order="false">
<suite-files>
<suite-file path="Test1.xml"></suite-file>
<suite-file path="Test2.xml"></suite-file>
<suite-file path="Test3.xml"></suite-file>
</suite-files>
</suite>
```
You have to specify the
>
> preserve-order = "false"
>
>
>
not
>
> preserve-order = false
>
>
> | In Suite tag, specify attribute thread-count=1, parallel="false". Let me know if this works. |
56,744,537 | I am trying to map the values of one column in my dataframe to a new value and put it into a new column using a UDF, but I am unable to get the UDF to accept a parameter that isn't also a column. For example I have a dataframe `dfOriginial` like this:
```
+-----------+-----+
|high_scores|count|
+-----------+-----+
| 9| 1|
| 21| 2|
| 23| 3|
| 7| 6|
+-----------+-----+
```
And I'm trying to get a sense of the bin the numeric value falls into, so I may construct a list of bins like this:
```
case class Bin(binMax:BigDecimal, binWidth:BigDecimal) {
val binMin = binMax - binWidth
// only one of the two evaluations can include an "or=", otherwise a value could fit in 2 bins
def fitsInBin(value: BigDecimal): Boolean = value > binMin && value <= binMax
def rangeAsString(): String = {
val sb = new StringBuilder()
sb.append(trimDecimal(binMin)).append(" - ").append(trimDecimal(binMax))
sb.toString()
}
}
```
And then I want to transform my old dataframe like this to make `dfBin`:
```
+-----------+-----+---------+
|high_scores|count|bin_range|
+-----------+-----+---------+
| 9| 1| 0 - 10 |
| 21| 2| 20 - 30 |
| 23| 3| 20 - 30 |
| 7| 6| 0 - 10 |
+-----------+-----+---------+
```
So that I can ultimately get a count of the instances of the bins by calling `.groupBy("bin_range").count()`.
I am trying to generate `dfBin` by using the `withColumn` function with an UDF.
Here's the code with the UDF I am attempting to use:
```
val convertValueToBinRangeUDF = udf((value:String, binList:List[Bin]) => {
val number = BigDecimal(value)
val bin = binList.find( bin => bin.fitsInBin(number)).getOrElse(Bin(BigDecimal(0), BigDecimal(0)))
bin.rangeAsString()
})
val binList = List(Bin(10, 10), Bin(20, 10), Bin(30, 10), Bin(40, 10), Bin(50, 10))
val dfBin = dfOriginal.withColumn("bin_range", convertValueToBinRangeUDF(col("high_scores"), binList))
```
But it's giving me a type mismatch:
```
Error:type mismatch;
found : List[Bin]
required: org.apache.spark.sql.Column
val valueCountsWithBin = valuesCounts.withColumn(binRangeCol, convertValueToBinRangeUDF(col(columnName), binList))
```
Seeing the definition of an UDF makes me think it should handle the conversion fine, but it's clearly not, any ideas? | 2019/06/24 | [
"https://Stackoverflow.com/questions/56744537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7082628/"
] | The problem is that parameters to an `UDF` should all be of column type. One solution would be to convert `binList` into a column and pass it to the `UDF` similar to the current code.
However, it is simpler to adjust the `UDF` slightly and turn it into a `def`. In this way you can easily pass other non-column type data:
```
def convertValueToBinRangeUDF(binList: List[Bin]) = udf((value:String) => {
val number = BigDecimal(value)
val bin = binList.find( bin => bin.fitsInBin(number)).getOrElse(Bin(BigDecimal(0), BigDecimal(0)))
bin.rangeAsString()
})
```
Usage:
```
val dfBin = valuesCounts.withColumn("bin_range", convertValueToBinRangeUDF(binList)($"columnName"))
``` | **Try this** -
```
scala> case class Bin(binMax:BigDecimal, binWidth:BigDecimal) {
| val binMin = binMax - binWidth
|
| // only one of the two evaluations can include an "or=", otherwise a value could fit in 2 bins
| def fitsInBin(value: BigDecimal): Boolean = value > binMin && value <= binMax
|
| def rangeAsString(): String = {
| val sb = new StringBuilder()
| sb.append(binMin).append(" - ").append(binMax)
| sb.toString()
| }
| }
defined class Bin
scala> val binList = List(Bin(10, 10), Bin(20, 10), Bin(30, 10), Bin(40, 10), Bin(50, 10))
binList: List[Bin] = List(Bin(10,10), Bin(20,10), Bin(30,10), Bin(40,10), Bin(50,10))
scala> spark.udf.register("convertValueToBinRangeUDF", (value: String) => {
| val number = BigDecimal(value)
| val bin = binList.find( bin => bin.fitsInBin(number)).getOrElse(Bin(BigDecimal(0), BigDecimal(0)))
| bin.rangeAsString()
| })
res13: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function1>,StringType,Some(List(StringType)))
//-- Testing with one record
scala> val dfOriginal = spark.sql(s""" select "9" as `high_scores`, "1" as count """)
dfOriginal: org.apache.spark.sql.DataFrame = [high_scores: string, count: string]
scala> dfOriginal.createOrReplaceTempView("dfOriginal")
scala> val dfBin = spark.sql(s""" select high_scores, count, convertValueToBinRangeUDF(high_scores) as bin_range from dfOriginal """)
dfBin: org.apache.spark.sql.DataFrame = [high_scores: string, count: string ... 1 more field]
scala> dfBin.show(false)
+-----------+-----+---------+
|high_scores|count|bin_range|
+-----------+-----+---------+
|9 |1 |0 - 10 |
+-----------+-----+---------+
```
Hope this will help. |
2,345,926 | I'm upgrading a script to a new version with a hole new database layout. The upgrade starts fine but slowly starts taking more and more time for the same query. The query in question is the following:
```
SELECT nuser.user_id, nfriend.user_id AS friend_user_id, f.time
FROM oldtable_friends AS f
JOIN oldtable_user AS u ON ( u.user = f.user )
JOIN newtable_user AS nuser ON ( nuser.upgrade_user_id = u.id )
JOIN oldtable_user AS uf ON ( uf.user = f.friend )
JOIN newtable_user AS nfriend ON ( nfriend.upgrade_user_id = uf.id )
LIMIT 200
OFFSET 355600
```
The OFFSET here varies of course as data is fetched in batches of 200 records.
oldtable\_friends has about 2 million records.
oldtable\_user and newtable\_user have around 70,000 records.
That query executes very fast at first but slowly starts to add up and after a couple of hours it takes about 30 seconds to execute. Those tables don't change at all while the script is upgrading so I'm not sure where is the bottleneck. It seems that the query slows down as the OFFSET variable grows up.
Here is the EXPLAIN:
```
+----+-------------+---------+--------+-----------------+-----------------+---------+-----------------------------------+-------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+--------+-----------------+-----------------+---------+-----------------------------------+-------+-------------+
| 1 | SIMPLE | nuser | ALL | upgrade_user_id | NULL | NULL | NULL | 71638 | |
| 1 | SIMPLE | u | eq_ref | PRIMARY,user | PRIMARY | 4 | database.nuser.upgrade_user_id | 1 | |
| 1 | SIMPLE | f | ref | user,friend | user | 77 | database.u.user | 20 | |
| 1 | SIMPLE | uf | eq_ref | PRIMARY,user | user | 77 | database.f.friend | 1 | |
| 1 | SIMPLE | nfriend | ref | upgrade_user_id | upgrade_user_id | 5 | database.uf.id | 1 | Using where |
+----+-------------+---------+--------+-----------------+-----------------+---------+-----------------------------------+-------+-------------+
```
All the tables have indexes on the fields being used. I can provide the tables structure if needed. I've been playing around a bit with MySQL configuration options and although it improved a bit, it wasn't much. Any suggestions? | 2010/02/27 | [
"https://Stackoverflow.com/questions/2345926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143231/"
] | Take a look at [ORDER BY … LIMIT Performance Optimization](http://www.mysqlperformanceblog.com/2006/09/01/order-by-limit-performance-optimization/) for completeness although you don't appear to be doing anything wrong as such.
Large `OFFSET`s are slow. There's no getting around that after a certain point.
You say you're batching 200 records at a time. Why not just do one query and read through all 70,000 rows? That will in fact be much faster. | @cletus: There are almost 2 million records, but it's still a good idea. It takes almost the same for MySQL to get me 200 or 20,000 rows from that query so I think it should work.
Unfortunately when I try to do that in my PHP script I get a "Prematue end of scripts header". After a lot of debugging I'm sure it's not a PHP memory limit or max execution time but it still happens. I'm able to run that query just fine through console and *sometimes* through PHPMyAdmin but not in my script. I've found out that my script runs the query when there is a small OFFSET (300,000) but if I increase the OFFSET to 700,000 or 1,500,000 it throws the Internal Server Error. So my question is: is there any sort of timeout or something on mysql\_query() or mysql\_fetch\_array() or else?
BTW: not sure if I should post this as a new question. |
14,297,607 | I am having trouble trying to show that certain numbers (product numbers) exist in an associative array. When I try this code, I always get "false".
```
<?php
$products = array(
'1000' => array('name' => 'Gibson Les Paul Studio',
'price' => 1099.99),
'1001' => array('name' => 'Fender American Standard Stratocaster',
'price' => 1149.99),
'1002' => array('name' => 'Jackson SL1 USA Soloist',
'price' => 2999.99)
);
if (in_array('1001', $products)) {
echo "true";
} else {
echo "false";
}
?>
```
I would really appreciate any help. Thanks! | 2013/01/12 | [
"https://Stackoverflow.com/questions/14297607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1973046/"
] | You're looking for [`array_key_exists()`](http://php.net/array_key_exists), not `in_array()`, since you are searching for a specific key, not searching the values:
```
if( array_key_exists('1001', $products))
``` | You cannot use [in\_array()](http://php.net/manual/en/function.in-array.php) here (*checks if a value exists in an array*).
Try [array\_key\_exists()](http://php.net/manual/en/function.array-key-exists.php) (*checks if the given key or index exists in the array*).
```
if (array_key_exists('1001', $products)) {
echo "true";
} else {
echo "false";
}
```
You can even check for key existance with [isset()](http://php.net/manual/en/function.isset.php) and [empty()](http://php.net/manual/en/function.empty.php). |
930,611 | Does anybody know of a way I can calculate very large integers in c#
I am trying to calculate the factorial of numbers e.g.
5! = 5\*4\*3\*2\*1 = 120
with small numbers this is not a problem but trying to calculate the factorial of the bigest value of a unsigned int which is 4,294,967,295 it doesn't seem possible.
I have looked into the BigInteger class but it doesn't seem to do what I need
any help would be greatly appreciated | 2009/05/30 | [
"https://Stackoverflow.com/questions/930611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114907/"
] | To calculate the factorial of `uint.MaxValue` you'd need a *lot* of storage.
For example, the [Wikipedia article](http://en.wikipedia.org/wiki/Factorial) as 8.2639316883... × 10^5,565,708. You're going to gain information like crazy.
I *strongly* suspect you're not going find any way of calculating it on a sane computer in a sane amount of time. Why do you need this value? Would Stirling's approximation be close enough? | If you are doing calculations with factorials like combinations for example you rarely need to multiply all the way down to 1 (eg. 98 \* 98 \* 97 since everything else cancels out). |
36,599,004 | Problem Statement
=================
I am having problems running a python file that import's the enchant library. I've installed the enchant module with the following command:
```
$ pip install -U pyenchant
> Requirement already up-to-date: pyenchant in /usr/lib/python3.4/site-packages
```
My Python Environment
=====================
```
$ cat /etc/*-release
CentOS Linux release 7.2.1511 (Core)
$ cat ~/.zshrc
...
export PYTHONPATH=/usr/lib/python3.4/site-packages
alias py="python3"
alias pip="pip3"
...
$ py --version
Python 3.4.3
$ pip --version
pip 8.1.1 from /usr/lib/python3.4/site-packages (python 3.4)
$ echo $PYTHONPATH
/usr/lib/python3.4/site-packages
$ ls -al /usr/lib/python3.4/site-packages | grep enchant
drwxr-xr-x 5 root root 4096 13 apr 13:56 enchant
drwxr-xr-x 2 root root 4096 13 apr 13:56 pyenchant-1.6.6.dist-info
$ yum list installed | grep python-enchant
((nothing))
```
My Python File
==============
```
$ cat ~/diskchall.py
import enchant
dictionary = enchant.Dict("en_US")
...
```
Running the file
================
```
$ py ~/diskchall.py
Traceback (most recent call last):
File "/root/diskchall.py", line 1, in <module>
import enchant
File "/usr/lib/python3.4/site-packages/enchant/__init__.py", line 92, in <module>
from enchant import _enchant as _e
File "/usr/lib/python3.4/site-packages/enchant/_enchant.py", line 143, in <module>
raise ImportError(msg)
ImportError: The 'enchant' C library was not found. Please install it via your OS package manager, or use a pre-built binary wheel from PyPI.
```
~~OS X El Capitan - TypeError~~
===============================
Did pretty much the same steps on El Capitan, but when running it gave me a TypeError.
Fixed by changing the `_enchant.py` file as suggested by [this issue](https://github.com/rfk/pyenchant/issues/45).
Pretty much a shame that this commit was from **2014** and still hasn't made the Pip repo. | 2016/04/13 | [
"https://Stackoverflow.com/questions/36599004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3858801/"
] | It looks like you are missing at least one dependency the 'enchant' C library. It is either called libenchant or enchant. The python module is a wrapper around this library so you need this library to use the wrapper.
To see what is available try:
```
yum whatprovides '*enchant*'
```
Your command
```
yum list installed | grep python-enchant
```
will not show python-enchant as you installed it with pip not yum. Instead try:
```
pip freeze | grep enchant
```
A list of dependencies for one a build of python-enchant can be seen [here](http://rpm.pbone.net/index.php3/stat/4/idpl/27314566/dir/other/com/python-enchant-1.6.5-14_Oso.noarch.rpm.html) note the requirement for enchant >= 1.5.0 (sometimes called libenchant)
On RedHat a simple "yum whatprovides enchant" will do:
```
yum whatprovides enchant
...
Repo : rhel6-base-x86_64
...
1:enchant-1.5.0-4.el6.i686 : An Enchanting Spell Checking Library
Repo : rhel6-base-x86_64
...
1:enchant-1.5.0-5.el6.i686 : An Enchanting Spell Checking Library
Repo : rhel6-base-x86_64
...
1:enchant-1.5.0-5.el6.x86_64 : An Enchanting Spell Checking Library
Repo : rhel6-base-x86_64
...
```
Install it with:
```
yum install enchant
``` | In case you have Python 2.7 and Centos 7 (any minor version) these are the steps to install and run enchant library.
1. Install epel release for centos7, following other dependencies for enchant.
```
RUN rpm -Uvh ./rpms/epel-release-7-11.noarch.rpm
RUN rpm -Uvh ./rpms/hunspell-1.2.8-16.el6.x86_64.rpm
RUN rpm -Uvh ./rpms/hunspell-en-US-0.20121024-6.el7.noarch.rpm
RUN rpm -Uvh ./rpms/hunspell-1.3.2-15.el7.x86_64.rpm
RUN rpm -Uvh ./rpms/enchant-1.6.0-8.el7.x86_64.rpm
RUN rpm -Uvh ./rpms/aspell-0.60.6.1-9.el7.x86_64.rpm
RUN rpm -Uvh ./rpms/enchant-aspell-1.6.0-8.el7.x86_64.rpm
RUN rpm -Uvh ./rpms/python-enchant-1.6.5-14.el7.noarch.rpm
```
This will install pyenchant library with spell checker for EN (you can change it accordingly to any other language) and aspell interface for PY and hunspeller. |
37,130 | I have read so many internet articles about safety in Spain, and the fake police scam is one of the most mentioned problems.
Most of those reported cases are that the victims are surrounded by group of undercover 'police', accusing you of having drugs and wants to check your ID and wallet.
How can we avoid that or handle it in case it does happen? | 2014/10/03 | [
"https://travel.stackexchange.com/questions/37130",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/20555/"
] | Follow the steps:
1. Remain calm. Ask for identification before going anywhere with them or giving them anything.
2. Don't sign anything without a lawyer present. If they start accusing you of anything, state that you require they then contact your embassy to help you with a lawyer. Generally if they're scamming, they don't want documentation or third parties involved.
3. If they want to search your bags, ask if you're under arrest or have done anything wrong. If you're not under arrest (as you'd hope) then ask why you can't just walk away right now. If they want your ID, agree to do so at the station with a lawyer or embassy member present.
Basically, your goal is to throw documentation, process and evidence at them - all of them being something scammers will want to avoid.
Much of this is learned from [dealing with (real) police who were corrupt and doing basically the same thing](https://travel.stackexchange.com/q/1224/101). In theory, fake police should be easier to deal with. Good luck, and hope it doesn't happen to you! Spain is a great, friendly country in general. | I have been in similar situations with people trying to pretend that they have a legitimate reason to pressure you to do things that might be taken advantage of.
What I do is that I immediately pick up my phone and start dialling the police. When they ask me what I am doing I am honest and tell them that I am phoning the police, and say that they might be well within their right, but I am contacting the police to get instruction on how to proceed.
So far my only response to this is that they try to defuse the situation, or simply run away. So far I haven't been able to dial the complete number.
In any case, it is a very good idea to get to know the phone numbers to the local authorities. That might help you in many more difficult situations. |
6,110,082 | I want to compare two strings, such as:
```
str1 = "this is a dynamic data";
str2 = "this is a <data_1> data";
```
Is there any method that will find the nearest match? I have used Ternary Search Tree (TST) Dictionary functions. Are there any other ways to do this kind of thing? | 2011/05/24 | [
"https://Stackoverflow.com/questions/6110082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/347045/"
] | Some things to look at for SSO and Moodle 1.9:
* If you are ready to spend quite some hours you could use Mnet: <http://docs.moodle.org/en/MNet>
* There is also a phpcas authentication method that could do what you want: <http://docs.moodle.org/en/CAS_server_(SSO>) | Here is what I did
**1 -** I enabled the **(External database) Authentication Plugin**
**2 -** Create this php file in folder (my/moodle/root/login/)
```
<?php
require('../config.php');
$username = $_GET['id'];// 's3265';
$serverName = 'moodle' ;
$connectionInfo = array( "UID"=>"mssqlUser","PWD"=>"********","Database"=>"external_Database");
//I am using MSSQL2008
echo '<form action="' . $CFG->wwwroot .
'/login/index.php" method="post" name="login" id="form">';
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if (!$conn)
{die('Could not connect: ' . sqlsrv_error());}
$result = sqlsrv_query($conn , "SELECT * FROM Users WHERE LoginID = '" . $username . "'");
var_dump($conn, $result);
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
echo $row['FName'] . " " . $row['LName'] . ", please wait. . .";
$password = $row['LoginPassword'];
}
sqlsrv_close($conn);
?>
<p><input type="hidden" name="username" value="<?php echo $username ?>">
<p><input type="hidden" name="password" value="<?php echo $password ?>">
<script language="JavaScript">
function Validate(){document.login.submit();}
Validate();
</script>
</form>
```
**3 -** assume you named the rhr file **(test.php)**
now your link should look like `(http://your_domain/moodle/login/test.php?id=yourusername)`
for me it is working , but . . . I am not concerned about security . . . if you do . . . you have to add something to this |
36,651,256 | My code:
```
<div id="title">
<h2>
My title <span class="subtitle">My Subtitle</span></h2></div>
```
If I use this code:
```
title = soup.find('div', id="title").h2.text
print title
>> My title My Subtitle
```
It matches everything. I want to match My title and My Subtitle as 2 different objects:
```
print title
>> My title
print subtitle
>> My subtitle
```
Any help? | 2016/04/15 | [
"https://Stackoverflow.com/questions/36651256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4866484/"
] | One way to do it without using the class attribute is:
```
h2 = soup.find('div', id="title").h2
subtitle = h2.span.text
title = str(h2.contents[0])
```
The `h2.contents[0]` will return a `NavigableString` object here. Its behavior for print is same as that as the string version of it. If you're only going to use the print statement with it, then the `str()` call won't be necessary. | Another solution.
```
from simplified_scrapy import SimplifiedDoc
html = '''
<div id="title">
<h2>
My title <span class="subtitle">My Subtitle</span></h2></div>
'''
doc = SimplifiedDoc(html)
h2 = doc.select('div#title').h2
print ('title:',h2.firstText())
print ('subtitle:',h2.span.text)
```
Result:
```
title: My title
subtitle: My Subtitle
``` |
2,470,035 | I have a form that sends info into a database table. I have it checked with a Javascript but what is the best way to stop spammers entering http and such into the database with PHP when Javascript is turned off? | 2010/03/18 | [
"https://Stackoverflow.com/questions/2470035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/212148/"
] | There are two things to consider which should be implemented in parallel (maybe there's more).
1. Captcha (as mentioned before)
2. Verify your data on server side! You wrote you do this by javascript. This is good, but the very same verification proccess should be written in PHP.
Well, for CAPTCHA you'll have to make it's verification on server side anyway. But even if you decide not to implement captcha, you should make data verification on server side. | I suggest using the [`htmlentities()`](http://php.net/manual/en/function.htmlentities.php) function before doing your insert.
Obviously your insert should be done using [parametrized queries](http://us2.php.net/manual/en/pdo.prepared-statements.php) to interact with the database as well. captcha is certainly an option, but it more serves to limit *how often* someone can post, not *what* they can post. Use hmtl escaping (again, the `htmlentities()` function) to prevent the user from inputting things you don't want. |
30,576,610 | We have a big application which uses a lot of `Strings`:
* for serial numbers
* for product names
* for order number
* for customer references
* ... and many more ...
Unfortunately our developers are only human. Sometimes the `String` values get mixed up when calling methods.
For example:
```
// this method
public void addProductToOrder(String order, String productname, String serialnumber);
// should be called like:
addProductToOrder(order, productname, serialnumber);
// but is sometimes mistakenly called as:
addProductToOrder(productname, serialnumber, order);
```
Switching 2 parameters is hard to detect when your method takes about 30 of these parameters. (Yes, it's one of those heavy business applications)
*Sidenote: We wouldn't have this problem if we created our own class `SerialNumber` which just acts as a wrapper around `String`. But that seems so wrong.*
Recently, I started to wonder if there is **a way to detect mix-ups using custom annotations**. After all, there are already annotations like `Nullable`, `NonNull` ...
And this is not very different.
We would like to annotate our source code, for example like this:
```
public void addProductToOrder(@OrderReference String order, @ProductName String productname, @SerialNumber String serialnumber);
```
Next, we would like to find a way to make our IDE detect that 2 parameters were switched here.
```
@OrderReference String order = "ORDER_001";
@SerialNumber String sn = "0001-1213-007";
@ProductName String productname = "beer";
addProductToOrder(productname, serialnumber, order);
// should have been: addProductToOrder(order, productname, serialnumber);
```
We are using IntelliJ IDE. **What is possible without writing IDE plugins ?** | 2015/06/01 | [
"https://Stackoverflow.com/questions/30576610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833961/"
] | Autocompletion's behaviour in RubyMine has been changed since there were a lot of complains against it in previous versions (because it was choosing not always the desirable one option).
If you want to restore the old behaviour, type "Registry" in Search everywhere and look for **ide.completion.lookup.element.preselect.depends.on.context** and unselect it.
Note: To **Search Everywhere** double press "Shift" key. Don't mistake this for searching inside preferences window. | There is now an option for this in the settings.
Go to `Settings > Editor > Code Completion` in the Ruby section and uncheck the checkbox `Preselect first completion element` :
[](https://i.stack.imgur.com/WA0jN.png) |
44,170,329 | I'm trying to write a real time battle system for a text game. I would like the player to be able to act and have to wait a certain number of seconds before they're able to act again, while the NPC is doing the same.
I've written a small example:
```
import threading
import time
def playerattack():
print("You attack!")
time.sleep(2)
def npcattack():
while hostile == True:
print("The enemy attacks!")
time.sleep(3)
p = threading.Thread(target=playerattack)
n = threading.Thread(target=npcattack)
hostile = False
while True:
if hostile == True:
n.start()
com = input("enter 'attack' to attack:")
if 'attack' in com:
hostile = True
p.start()
```
The example will work fine for the first attack:
I enter 'attack', the hostile flag is set to True, the npc attack thread starts, but I get a 'RuntimeError: threads can only be started once' when I try to attack again.
Is there a way to reuse that thread without it throwing an error? Or am I going about this all wrong? | 2017/05/25 | [
"https://Stackoverflow.com/questions/44170329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7965650/"
] | The problem is that the thread is already running and you cannot start a running thread again because of while loop calling `n.start()` again.
Even after the thread is dead you need to reinitialize the thread instance and start again. You cannot start an old instance.
In your case in `while True` loop it is trying to start a thread multiple time. What you an do is check if thread is running, if not running start the thread instance.
```
import threading
import time
def playerattack():
print("You attack!")
time.sleep(2)
def npcattack():
while hostile:
print("The enemy attacks!")
time.sleep(3)
p = threading.Thread(target=playerattack)
n = threading.Thread(target=npcattack)
hostile = False
while True:
if hostile and not n.is_alive():
try:
n.start()
except RuntimeError: #occurs if thread is dead
n = threading.Thread(target=npcattack) #create new instance if thread is dead
n.start() #start thread
com = input("enter 'attack' to attack:")
if 'attack' in com:
hostile = True
if not p.is_alive():
try:
p.start()
except RuntimeError: #occurs if thread is dead
p = threading.Thread(target=playerattack) #create new instance if thread is dead
p.start()
``` | I found a (hacky) way to reuse a threading.Thread object, by creating a subclass and implementing a reset method, in case you just want to change the arguments of the function that the thread is "linked" to.
```
class ReusableThread(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self,*args, **kwargs)
self._default_args = self._target, self._args, self._kwargs
def run(self, *args, **kwargs):
super().run()
self.reset()
def reset(self, *args, **kwargs):
self._target = self._default_args[0]
self._args = args or self._default_args[1]
self._kwargs = kwargs or self._default_args[2]
```
In the python shell:
```
>>> r = ReusableThread(target=print, args=("banana",))
>>> r.start()
banana
>>> r.reset(("banana", "apple"), "kiwi", sep='\n', end="<<<\n")
>>> r.run()
('banana', 'apple')
kiwi<<<
>>>
``` |
269 | I've been using a house rule for a while now. If you have a trained skill, and you are making a knowledge check it's free.
For example, if you are trained in nature, and fighting natural beasts; you may make a free action nature check to see if you know anything about the beasts.
So far, I haven't had any ill effects, but I have a good group. Can anyone think of a way this could be broken? | 2010/08/19 | [
"https://rpg.stackexchange.com/questions/269",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53/"
] | That's actually not even a house rule — it's by the book. See pages 179-180 of the Player's Handbook, which discuss monster knowledge checks. On page 180:
>
> Monster Knowledge: No action required — either you know the answer or you don't.
>
>
> | There is nothing that "breaks" the game as long as you the DM reserve the right to run the rules the way you want. I'm sure there's some option somewhere, now or future, that lets a PC do a Knowledge check to accomplish something nontrivial, and when that happens, you'll need to say "well, that's not a free action."
Other than that, this seems fine... I don't think in 3.5 I ever enforced a Knowledge check like that taking up an action. |
255,969 | When booting into Linux, there are sometimes one or two lines that get quickly cleared. I think that some of them don't even appear in dmesg. If nothing else, I want to suppress the clear before the "login:" prompt. Is there a kernel command or sysctl that I can set to prevent this so I can read them on the console screen after booting? | 2011/04/05 | [
"https://serverfault.com/questions/255969",
"https://serverfault.com",
"https://serverfault.com/users/11131/"
] | Most of the information you want will be in `/var/log/dmesg` and `/var/log/messages` after the system boots, you should check those files first.
Generally linux machines run [mingetty](http://linuxcommand.org/man_pages/mingetty8.html) for the virtual terminals. If you have a traditional sysv init system, those are controlled by `/etc/inittab`. You can add the `--noclear` option to mingetty to prevent clearing the screen. To do this, edit `/etc/inittab` and change this line:
```
1:2345:respawn:/sbin/mingetty tty1
```
to
```
1:2345:respawn:/sbin/mingetty --noclear tty1
```
then reboot the machine.
Some newer linux distros use init replacements like Upstart (for example, Ubuntu). These generally don't use /etc/inittab and instead use some other config files. Here's a [discussion of how calling mingetty works on Ubuntu](https://bugs.launchpad.net/ubuntu/+source/upstart/+bug/67415). | With systemd things are different. See article [Stop Clearing My God Damned Console](http://mywiki.wooledge.org/SystemdNoClear). In short:
```
mkdir /etc/systemd/system/getty@.service.d
cat >/etc/systemd/system/getty@.service.d/noclear.conf <<EOF
[Service]
TTYVTDisallocate=no
EOF
systemctl daemon-reload
```
Verify the result with `systemctl cat getty@tty1.service` |
4,901 | Как писать такой сорт винограда, как Бастардо м(М)агарачский? "Каберне-Совиньон" вроде бы два слова с прописной, должна сработать аналогия по идее. Или нет? | 2012/05/25 | [
"https://rus.stackexchange.com/questions/4901",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/913/"
] | Скорее всего написание в общем случае пока не нормировано.
Я в курсе, т.к. на gramota.ru года четыре назад изрядно копий сломали, в чем и мне довелось участвовать. Попозже попробую найти ту ветку.
Тут вот какая штука. Строго говоря, в типичном случае приведенные вами названия не являются названиями сортов винограда. Они используются только как обозначение происхождения сырья при производстве вина. Первая часть такого названия в типичном случае представляет собой собственно сорт, вторая обычно - место производства, винодельческий регион, реже - региональный тип купажа (что для хороших вин вообще редкость).
На такие названия нет закреплённой орфографической кодификации, приходится руководствоваться общими принципами.
Исходя из них предлжил бы:
**Каберне Совиньон** (как родовое и видовое обозначение ср. Хомо Сапиенс); здесь не следует путать уточняющее Совиньон с самостоятельными сортами Совиньон Блан, Совиньон Руж и др., к этим сортам Каберне Совиньон отношения не имеет.
**Бастардо магарачский** - поскольку название связано с названием института "Магарач", создавшим этот "сорт", магарачский здесь обычное прилагательное.
Но, повторюсь, это личное мнение. | Внесу уточнение. Сравнивать Каберне Совиньон с Homo sapiens не совсем правильно. В латинских названиях живых существ с прописной буквы пишется только название рода, вид же - со строчной: Canis domestica, Ehium vulgare и т.д. |
12,843 | Recently I was in a fish and chip shop in [Mandurah, WA](http://en.wikipedia.org/wiki/Mandurah), selling local crumbed scallops.
* Is *local crumbed scallops* the correct form?
* Is *crumbed local scallops* more appropriate?
* What if "nonlocal" scallops were also available?
* [optional] What form would a native German speaker find more natural, and why? | 2011/02/16 | [
"https://english.stackexchange.com/questions/12843",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/3093/"
] | *Local crumbed scallops* seems ambiguous, as it could be understood as *local-crumbed scallops*, where *local* is referring to *crumbed*; in that case, the hyphen is necessary to avoid the ambiguity.
*Crumbed local scallops* is more clear, as it's evident that *local* is referring to *scallops*.
In English, the adjectives are written (or should be written) in a particular order; the answers given in [Adjective order](https://english.stackexchange.com/questions/1155/adjective-order) explain better in which order they should be written.
*Non-local* is generally not used; if the scallops are not local scallops, then they are generally called *scallops*. | There is a theory that adjective ordering is essentially universal (i.e. the same across all languages), so that in principle we ought to be able to give rules something like this:
* keep words forming a compound or colloquation together;
* if the adjectives all come before the noun in your native language, keep them in that same order in English;
* if some adjectives come after the noun in your native language, then those adjectives will come before the noun in English, but after other adjectives coming befor the noun in both languages;
* if in the adjectives coming after the noun in your native language, colour adjectives come last, then reverse the order of those adjectives in English.
The first rule means you could actually end up with variations of the sort "an elderly single mother" or "a single elderly mother" depending on which colloquation is intended.
The last rule covers some cases where adjectives following the noun can allow a "reversed" order or not, e.g. Rowlett (2007) cites French examples: "une jolie petite jupe [bleue fleurie écossaise']", which also permits "...[écossaise fleurie bleue]", with English "A pretty little blue floral Scottish skirt".
This goes for adjectives that are actually adjectives, incidentally: it isn't necessarily valid to class determiners, quantifiers, adverbs and nouns inside compounds as adjectives, for example (one of the links above appears to, and I think this could confuse the issue).
It should also be noted that we're talking about the unmarked order; for emphasis, the 'emphasised' adjectives can generally be placed before all others even if that means that it's out of place ("There are lots of cheap lawnmowers, but this is an OLD cheap lawnmower").
If you start giving actual lists of orderings (which, as I say, may be universal anyway), there is a danger in assuming that the order that applies with, say, nouns denoting tangible objects will then apply to nouns denoting emotions or actions. |
51,642 | **Task**
Get 100 as an answer with only four keystrokes on a regular calculator.
**Disallowed keys**
* 0
* 00
**Allowed keys**
All other than the aforementioned two keys.
Take the below image as a reference.
[](https://i.stack.imgur.com/1vVky.jpg)
**Condition**
Atleast two operators must be used. | 2017/05/09 | [
"https://puzzling.stackexchange.com/questions/51642",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/36532/"
] | I found another solution.
>
> .1 first and second key, 1/x third key, x2 fourth key. You need a calculator with those buttons though.
>
>
>
The OP says that calculator is just for reference, meaning I can use "a regular calculator" that's slightly different?
It's the standard calculator that came with my windows 10. | You can do it with 3 mouse clicks on a virtual claculator (Windows or Mac):
>
> With the calculator in "programmer" mode, base 16 selected, click 6 4 "base 10"
>
>
>
And for the pedants that require *2* "operators":
>
> With the calculator in "programmer" mode, base 16 selected, click 6 4 "base 10" =
>
>
> |
9,773,627 | I was wondering how I could set up css pseudo classes, specifically hover so when I hover over an element, like a div with an id, the properties of a different div with an id get changed?
so normally it would be this:
```css
#3dstack:hover {
listed properties
}
```
I'm not sure what the change would be to have it hover on div with the id `3dstack` and have it change another div. | 2012/03/19 | [
"https://Stackoverflow.com/questions/9773627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1119918/"
] | I do not think that is possible unless the element you want to change the properties of is a descendent or a sibling of the hovered element, in which case you can do:
```
#myElement:hover #myElementDescendent {
background-color: blue;
}
/*or*/
#myElement:hover + #myElementSibling {
background-color: blue;
}
```
Of course you can always use jquery to do this:
```
$("#anelement").hover(
function() {
$("otherelement").css("background-color", "blue");
});
```
[See the differences here](http://jsfiddle.net/AE3Ze/) | *Visually* you can do this using [LESS](http://lesscss.org/), but *under the hood* it's actually using JavaScript. |
59,127,979 | Is there any way to append data to an existing XML document using XML serializer.
I am currently doing it like this
```
string filePath = "Data.xml";
var serializer = new XmlSerializer(typeof(Event));
extWriter writer = new StreamWriter(filePath, true);
serializer.Serialize(writer, event);
```
This way adds the element like a root node instead of a child node...I also used LINQ to XML that way worked fine but that's way seems hardcoded.
Is there any way to achieve it using this method. | 2019/12/01 | [
"https://Stackoverflow.com/questions/59127979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11210734/"
] | No, there is no way to manipulate the file without loading it. The Serializers always handle the entire file.
So the right way to do modifications is to Load the File into memory, modify it, and save it again.
For direct anonymous Xml-Node-Level manipulation you should rather use XmlDocument.Load, instead of an XmlSerializer. The XmlSerializer translates the XML into your custom classes first. If you want to add your custom objects, this might be simpler, if you want to Add xml-nodes, you go better with XmlDocument. | If you now the data is at the end of the file
you can open the file by as text
seek to the end
delete the last row
write the data
and add the last row again
**This is only recommended in case of writing to large uniform files** |
5,734,629 | I have built a simple CSS drop down menu. What I am looking for is a way to add a css style class to the menu span depending on what directory you are in.
For example, you are in the contact directory <http://www.site.org/contact> on any page in that directory I would like the contact menu item which is a span with an id name to stay the color assigned to .current. Then if you leave to go to the about directory the contact dismisses the .current style and about changes to .current. | 2011/04/20 | [
"https://Stackoverflow.com/questions/5734629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/717649/"
] | One thing you could do is to treat the CSS like it is a theme. The way this is done for a "theme per directory" sort of approach is to have a base-line set of styles that will always apply to the site, and then also have a style sheet within each directory that overrides the base styles to change the theme for that directory.
So, for example, if you put this on all pages:
```
<link rel="stylesheet" type="text/css" href="/base.css">
<link rel="stylesheet" type="text/css" href="theme.css">
```
you are saying that `base.css` (in the root directory of the site) will define most of the styles, but then `theme.css` will be looked for in the same directory of the current page, and the styles there will *also* apply to the page, allowing you to override the base styles with different colors, etc.
If you have a dynamic site, you should be able to add a class to the navigation element that should be active currently. If it is static, however, or you cannot add/remove classes, you could give each navigation element a unique ID and use that ID in the various `theme.css` files to apply styles to the appropriate nav item within that directory.
Things will get a bit tricky if you go deeper underneath a particular directory, but the solution there is to either duplicate the theme file in that directory (yuck), or to have the deeper HTML pages link up to the correct directory like this (example for 1 directory lower):
```
<link rel="stylesheet" type="text/css" href="/base.css">
<link rel="stylesheet" type="text/css" href="../theme.css">
``` | Let's say you have something like this:
```
<ul id="nav">
<li id="nav-menu1">...</li>
<li id="nav-menu2">...</li>
<li id="nav-about">...</li>
<li id="nav-contact">...</li>
</ul>
```
Then you can do something like:
```
var whichCurrent = 'nav-' + window.location.href.replace('http://www.site.org/', '');
document.getElementById(whichCurrent).className = 'current';
```
Then in your menu Javascript you add and remove the `current` class according to your spec. |
74,308,028 | Question.
Write a PL/SQL program to check whether a date falls on weekend i.e.
‘SATURDAY’ or ‘SUNDAY’.
I tried running the code on livesql.oracle.com
My Code:
[](https://i.stack.imgur.com/loPAX.png)
I am very new to sql and don't really know why i am getting this error.
It is saying that all variables are not bound.
Please help.
The output which I was expecting is:
[](https://i.stack.imgur.com/Bcr2B.png)
I tried changing single quotes to double but that didn't work. | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410463/"
] | It is fairly straightforward, when you consider the namespaces involved. This is hinted at by the fact that you get a `NameError`, when you actually try and do anything with `test_var`, such as passing it to a function (like `print`). It tells you that the *name* you used is not known to the interpreter.
What does variable assignment do?
---------------------------------
What happens, when you assign a value to a variable in the global namespace of a module for the first time, is it gets added to that modules *globals* dictionary with the key being the variable name and the value being, well, its value. You can see this dictionary by calling the built-in [`globals`](https://docs.python.org/3/library/functions.html#globals) function in that module:
```py
from pprint import pprint
a = 1
pprint(globals())
```
The output looks something like this:
```
{'__annotations__': {},
...
'__name__': '__main__',
...
'a': 1,
...}
```
What does annotation do?
------------------------
When you look closer at that dictionary, you'll find another interesting key there, namely `__annotations__`. Right now, its value is an empty dictionary. But I bet you can already guess, what will happen, if we annotate our variable with a type:
```py
from pprint import pprint
a: int = 1
pprint(globals())
```
The output:
```
{'__annotations__': {'a': <class 'int'>},
...
'a': 1,
...}
```
When we add a type hint to (i.e. *annotate*) a variable, the interpreter adds that name and type to the relevant `__annotations__` dictionary (see [docs](https://docs.python.org/3/reference/simple_stmts.html#annassign)); in this case that of our module. By the way, since the `__annotations__` dictionary is in our global namespace we can access it directly:
```py
a: int = 1
print("a" in globals()) # True
print("a" in __annotations__) # True
```
Can you annotate without assigning?
-----------------------------------
Finally, what happens, if we *just* annotate **without assigning** a value to a variable?
```py
a: int
print("a" in globals()) # False
print("a" in __annotations__) # True
```
And that is the explanation of why we get an error, if we try and e.g. print out `a` in this example, but otherwise don't get any error. The code merely told the interpreter (and any static type checker) about the annotation, but it assigned no value, thus failing to create an entry in the global namespace dictionary.
It makes sense, if you think about it: What *should* be set as the value for `a` in that namespace? It has no value (not even `None` or `NotImplemented` or anything like that). To the interpreter the `a: int` line merely meant the creation of an entry in the `__annotations__` of our module, which is perfectly valid.
Runtime meaning of annotations
------------------------------
I would also like to stress the fact that the annotation is **not meaningless** for the interpreter and thus runtime, as some people often claim. It is admittedly *rarely* used, but as we just saw in the example, you can absolutely work with annotations at runtime. Whether or not this is useful is obviously up to you. Some packages like [Pydantic](https://pydantic-docs.helpmanual.io/) or the standard library's [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) actually rely **heavily** on annotations for their purposes.
The value set in the `__annotations__` dictionary in our example *is actually* a reference to the `int` class. So we can absolutely work with it at runtime, if we want to:
```py
a: int
a_type = __annotations__["a"]
print(a_type is int) # True
print(a_type("2")) # 2
```
You can play around with this concept in class namespaces as well (not just with module namespace), but I'll leave this as an exercise for the reader.
So to wrap up, for a name to be added to any namespace, it must have a value assigned to it. *Not* assigning a value and just providing an annotation is totally fine to create an entry in that namespace's `__annotations__`. | Python will not initialize a variable automatically, so that variable doesn't get set to anything. `a: int` doesn't actually define or initialize the variable. That happens when you assign a value to it. The typings really only act as hints to the IDE, and have no practical effect without assigning a value during compilation or runtime. |
19,239,605 | In joomla 2.5 is there any built in function to fetch all article from the specific category.
I don't want to use custom query to fetch article from the database. | 2013/10/08 | [
"https://Stackoverflow.com/questions/19239605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1740136/"
] | I'm not sure how're you're setting up your slider however to answer your actual question:
```
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*')
->from($db->quoteName('#__content'))
->where($db->quoteName('catid') . ' = 2');
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach ( $rows as $row ) {
echo $row->introtext;
}
```
There is a built in function to get articles using the route.php I believe which is what the likes of Accordions use and so on, however for the most simple method, use the above.
Note: Don't forget to change the `catid` value from `2` to whatever suits your needs.
Hope this helps | Check this out: /modules/mod\_articles\_category for a full-fledged (and fairly slow) implementation. You might want to make it simpler:
select introtext, params from #\_\_content where catid=%s AND state=1 AND ...
(you might want to add some checks on publish\_up fields etc, but if you're happy with managing published/unpublished and don't use publish\_up / down you don't need to do this).
Make sure you implement the module correctly to leverage Joomla cache, even if this query is fast it's best to avoid repeating it adlib. [Read this](http://www.fasterjoomla.com/joomla-dev/programmare-un-modulo-joomla-per-utilizzare-la-cache) for more details on module's cache |
1,583,982 | >
> We have a linear transformation $T:P\rightarrow P$ where $T(p)=p+p'$ and $P$ is the vector space of all real polynomials. I want to show that $T$ invertible.
>
>
>
I was able to prove that its injective, but I have difficulty to show that is surjective or is possible even to find $S$ such that $T\circ S=I$. | 2015/12/21 | [
"https://math.stackexchange.com/questions/1583982",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/95052/"
] | Notice that
$$
32^5=2^{25} \equiv 2^{10}\cdot 2^{10} \cdot 2^5 \equiv 24^2 \cdot 32 \equiv 32 \mod 100
$$
(I think what you wrote there does not make sense as stated)
and it follows that
$$
2^{5^k} \equiv 32 \mod 100
$$
for all $k\ge 1$
So indeed
$$
2^{5}+2^{5^2}+\cdots+2^{5^{2015}} \equiv 32 \cdot 2015 \equiv 64480 \equiv 80 \mod 100
$$ | If $X \equiv \sum\_{k=1}^{2015} 2^{\left(5^k\right)} \pmod {100}$, then you can compute:
$$X\_4 \equiv \sum\_{k=1}^{2015} 2^{\left(5^k\right)} \pmod 4$$
$$X\_{25} \equiv \sum\_{k=1}^{2015} 2^{\left(5^k\right)} \pmod {25}$$
$X\_4 \equiv 0$ in each term. $2^{20} \equiv 1 \pmod {25}$, this you seem to have noted. So
$$X\_{25} \equiv \sum\_{k=1}^{2015} 2^{\left(5^k \text{ mod } 20\right)} \pmod {25}$$
$5^k \equiv 5 \pmod 20$ for $k \ge 1$, so
$$X\_{25} \equiv \sum\_{k=1}^{2015} 2^5 \equiv 2015\cdot 32 \equiv 5\pmod {25}$$
And $$\begin{cases} X \equiv 5 \pmod {25} \\ X\equiv 0 \pmod 4 \end{cases}$$ only has 1 solution $\pmod {100}$. |
186,960 | How to say something like I am forced to agree or accept the situation in one word?
I believe there is a precise word to express this. | 2014/07/25 | [
"https://english.stackexchange.com/questions/186960",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/86186/"
] | Depending on the reasons, one of the following words may make sense.
1. Coerced
2. Blackmailed
3. Compelled
4. Required
5. Held hostage
6. Obligated or bound | Acquiesce, essentially to agree without protest, yet you'd prefer something else |
68,161,909 | ```py
Date
-1.476329
-2.754683
-0.763295
-3.113292
-1.353446
```
when I am trying to convert these -ve float values into `dd-mm-yyyy` , I am getting the year as 1969 or something with almost same date in every row. But the year should be near to 2018-2020 | 2021/06/28 | [
"https://Stackoverflow.com/questions/68161909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16333302/"
] | You can refer to the following documentation: <https://material.io/develop/android/theming/color>
* **colorPrimary**: The color displayed most frequently across your app’s screens and components. This color should pass accessibilty guidelines for text / iconography when drawn on top of the surface or background color.
* **colorPrimaryVariant**: A tonal variation of the primary color.
* **colorOnPrimary**: A color that passes accessibility guidelines for text/iconography when drawn on top of the primary color.
* **colorSecondary**: The secondary branding color for the app, usually an accented complement to the primary branding color.
* **colorSecondaryVariant**: A tonal variation of the secondary color.
* **colorOnSecondary**: A color that passes accessibility guidelines for text/iconography when drawn on top of the secondary color.
You can also refer to this SO: <https://stackoverflow.com/a/45879575/9246764> | If you're looking for specifics about each component, the [material.io](https://material.io) documentation usually provides information about the default values for various attributes.
For example, the documentation for [`MaterialCardView`](https://material.io/components/cards/android#card) specifies that the default `app:cardBackgroundColor` is `?attr/colorSurface`. |
57,535,565 | i want to send array with rest api in php but i don't know how to do this
i tried with json and without json but not response to me
```php
$drv = array('mobile'=>'+123456', 'title'=>"MR", 'firstName_en'=>'john', 'lastName_en'=>'wilet');
curl_setopt($process, CURLOPT_POSTFIELDS, "checkoutStation=xxx&checkoutDate=20190826&checkoutTime=0900&checkinStation=xxx&checkinDate=20190827&checkinTime=0900&email=info@site.net&driver=$drv");
```
also try
```php
$drv = array('mobile'=>'+123456', 'title'=>"MR", 'firstName_en'=>'john', 'lastName_en'=>'wilet');
$drv=json_encode($drv);
curl_setopt($process, CURLOPT_POSTFIELDS, "checkoutStation=xxx&checkoutDate=20190826&checkoutTime=0900&checkinStation=xxx&checkinDate=20190827&checkinTime=0900&email=info@site.net&driver=$drv");
```
because driver parameter required a array data value
when i run my codes return errors":["Error in driver data!"] to me | 2019/08/17 | [
"https://Stackoverflow.com/questions/57535565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7933827/"
] | Setting something as `async` will wrap the return object into a `Promise`. Promises are used to deal with asynchronous behavior, but there's nothing inherently asynchronous about the content of the `test` function. If instead you were to wrap the contents into a `setTimeout` function, that would cause a delay which would mimic asynchronous behavior and match the outcome you were expecting.
```js
async function test() {
setTimeout(() => {
for(let i = 0; i < 2; i++){
console.log("test");
}
})
}
console.log("a");
test();
console.log("b")
```
If you're looking to set up background tasks that can lock up the browser's main thread, you should check out [`WebWorkers`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers). They are a way to offload performance impacting tasks onto a separate thread. | an async function means that what is inside the function is expected to have some asynchronous calls. like if you had an Http call inside your test function.
and since nothing is asynchronous inside your function (you only have a normal loop) then your function will execute normally and sequentially until it finishes executing. |
44,063,286 | I am trying to add users to Tencent Cloud (QCloud) account, similar to one would do using AWS IAM.
Under "User Management" I added a user, but the user received an email indicating he is a collaborator and will receive notifications rather than the instruction on how to login to the account I created.
What is the Tencent Cloud equivalent of AWS IAM? | 2017/05/19 | [
"https://Stackoverflow.com/questions/44063286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2360262/"
] | **virtualenv** is a tool that allows you to create isolated Python environments, which can be quite helpful when you have different projects with differing requirements.
**mkvirtualenv** is command under **virtualenvwrapper** which is just a wrapper utility around virtualenv that makes it even easier to work with.
For detailed ref:
1. <http://www.silverwareconsulting.com/index.cfm/2012/7/24/Getting-Started-with-virtualenv-and-virtualenvwrapper-in-Python>
2. <https://virtualenvwrapper.readthedocs.io/en/latest/> | It used by a wrapper on `virtualenv`. It makes working on these environments easier since you can swap them by using `workon` command and they are stored in one place. [See this](http://virtualenvwrapper.readthedocs.io/en/latest/command_ref.html). |
46,927,667 | I am using nodejs with express and ejs.
Every one on internet ask how to pass value from node to the view, but what about the opposite?
For example, I ask my user to input a string in a form, when the user clicks the button, how can I get this string without passing it as a parameter in the url?
The form:
```
<div class="container">
<form style="width:50%">
<div class="form-group">
<label for="text">Name of the product</label>
<input type="text" class="form-control" id="pName">
</div>
<div class="form-group">
<label for="text">Reciever</label>
<input type="text" class="form-control" id="reciever">
</div>
<div class="form-group">
<label for="text">Location</label>
<input type="text" class="form-control" id="location">
</div>
<!-- <div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>-->
<button type="submit" class="btn btn-default">Submit</button>
</form>
```
The app.js
```
var express = require('express');
var app = express();
//ALL GLOBAL VARIABLES
var port = 8080;
app.get('/', function(req, res) {
res.render('index.ejs');
});
app.get('/barcode', function(req,res) {
res.render('barcode.ejs');
});
app.listen(port);
```
I know I can do this:
```
app.get('/url/:parameter', function(req.res) {
var foo = req.params.parameter;
}
```
But if I don't want to use the URL, is it possible to retrieve the data? | 2017/10/25 | [
"https://Stackoverflow.com/questions/46927667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6213883/"
] | Use POST as a method for your html form
```
<form action="/myapi" method="post">
<input type="text" class="form-control" id="pName" name="pName">
<button type="submit" class="btn btn-default">Submit</button>
</form>
```
And then handle the client form "action" with `app.post` on the back end
```
app.post('/myapi', function(req, res) {
res.send('The pName is "' + req.body.pName + '".');
});
``` | From your question, In general if you want to get a value from the unique id, you will store that value as a global variable. so you can easily get the current user and user related details. |
31,493,816 | I crawl a table from a web link and would like to rebuild a table by removing all script tags. Here are the source codes.
```
response = requests.get(url)
soup = BeautifulSoup(response.text)
table = soup.find('table')
for row in table.find_all('tr') :
for col in row.find_all('td'):
#remove all different script tags
#col.replace_with('')
#col.decompose()
#col.extract()
col = col.contents
```
**How can I remove all different script tags?** Take the follow cell as an exampple, which includes the tag `a`, `br` and `td`.
```
<td><a href="http://www.irit.fr/SC">Signal et Communication</a>
<br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a>
</td>
```
My expected result is:
```
Signal et Communication
Ingénierie Réseaux et Télécommunications
``` | 2015/07/18 | [
"https://Stackoverflow.com/questions/31493816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3067748/"
] | You are asking about [`get_text()`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text):
>
> If you only want the text part of a document or tag, you can use the
> `get_text()` method. *It returns all the text in a document or beneath a
> tag, as a single Unicode string*
>
>
>
```
td = soup.find("td")
td.get_text()
```
Note that [`.string`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#string) would return you `None` in this case since `td` has *multiple children*:
>
> If a tag contains more than one thing, then it’s not clear what
> `.string` should refer to, so `.string` is defined to be `None`
>
>
>
Demo:
```
>>> from bs4 import BeautifulSoup
>>>
>>> soup = BeautifulSoup(u"""
... <td><a href="http://www.irit.fr/SC">Signal et Communication</a>
... <br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a>
... </td>
... """)
>>>
>>> td = soup.td
>>> print td.string
None
>>> print td.get_text()
Signal et Communication
Ingénierie Réseaux et Télécommunications
``` | Try calling col.string. That will give you the text only. |
1,246,315 | I want to find out the natural block size of the IO media being used in an cocoa application. I saw a function in IOMedia.cpp called "getPreferredBlockSize()" which supposedly gives me my block size. Please can you guys explain me how to use this function in my app or if there is any other method using which i can find the natural block size of the underlying IO media.
Thanks | 2009/08/07 | [
"https://Stackoverflow.com/questions/1246315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148712/"
] | The C/C++ preprocessor acts in units of tokens, and a string literal is a *single* token. As such, you can't intervene in the middle of a string literal like that.
You could preprocess script.py into something like:
```
"some code\n"
"some more code that will be appended\n"
```
and #include that, however. Or you can use [`xxd`](http://linux.die.net/man/1/xxd)` -i` to generate a C static array ready for inclusion. | This won't get you all the way there, but it will get you pretty damn close.
Assuming `script.py` contains this:
```
print "The current CPU time in seconds is: ", time.clock()
```
First, wrap it up like this:
```
STRINGIFY(print "The current CPU time in seconds is: ", time.clock())
```
Then, just before you include it, do this:
```
#define STRINGIFY(x) #x
const char * script_py =
#include "script.py"
;
```
There's probably an even tighter answer than that, but I'm still searching. |
9,913,353 | I have a cancel button in a form:
```
@using (Html.BeginForm("ConfirmBid","Auction"))
{
some stuff ...
<input type="image" src="../../Content/css/img/btn-submit.png" class="btn-form" />
<input type="image" src="../../Content/css/img/btn-cancel.png" class="btn-form" />
}
```
The issue is I want this button to go to a particular view when I click on it. How do I do this? | 2012/03/28 | [
"https://Stackoverflow.com/questions/9913353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/991788/"
] | Either you can convert the Cancel button as an anchor tag with @Html.ActionLink helper method and apply a css class which makes the link to looks like a button and then in the controller action for that link, you can return the specific view.
```
@Html.ActionLink("Cancel","Index","Products",null, new { @class="clsButtonFake"})
```
or
Use 2 submit buttons in the form. One for real submit and one for the cancel. and in your controller action, check which button called the action method.
You can read more about it [here in this answer.](https://stackoverflow.com/a/8258799/40521) | Lot of the answers worked in either of the browsers, chrome or ie but not all.
This worked in all -
```
<input type="button" value="Cancel" onclick="location.href='@Url.Action("Index","Home")';"/>
``` |
2,474,912 | >
> $$A = \begin{pmatrix} 2 & -1 \\ 1 & -1 \end{pmatrix} $$ Find the $2 \times 2$ matrix $X$ such that $XA^2 − XA^{-1} = A$.
>
>
>
Can anyone advise me on how to do questions like this? Very confusing. Trying to teach myself matrices. | 2017/10/16 | [
"https://math.stackexchange.com/questions/2474912",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/492079/"
] | Hint
Multiply by $A$ to the right, to get
$$XA^3 - X = A^2$$
$$X(A^3 - \mathbb{1}) = A^2$$
Then you just need to compute $A^3 - \mathbb{1} = AAA - \mathbb{1}$ and $A^2 = AA$.
At the end, calling $A^3 - \mathbb{1} = B$ you will have
$$XB = A^2$$
Multiply for $B^{-1}$ to the right to get the solution:
$$X = A^2 B^{-1}$$
**Remark**
Notice that you have to do with simple $2x2$ matrices, hence their inverse is a piece of cake. In general you have:
$$
M =
\begin{pmatrix}
a & b \\
c & d
\end{pmatrix}
~~~~~~~~~~~ M^{-1} = \frac{1}{\text{det} M}
\begin{pmatrix}
d & -b \\
-c & a
\end{pmatrix}
$$
Of course you need to have $\text{det} M \neq 0$ in order to have an invertible matrix. | Hint: use Cayley-Hamilton to find out an equation $A^2+aA+bI=0$.
Then you can reduce all higher matrix powers $A^k$ for $k\ge 2$, so that
$A$ appears only in degree $1$ and $0$. Then $X=A^2(A^3-I)^{-1}$ can be reduced, too. |
22,038,494 | I am developing a MVC 4 application ,using JavaScript jQuery for validations.
But the JavaScript functions are not getting triggered in Mozilla Firefox.
Can some body explain me what might be the issue here.
I have the following JavaScript function inside script tag of the page.
```
function dateValidation() { debugger; }
```
and my html button is as follows
```
<button name="button" value="Request VM/s" class="btn active" id="AddNewRequest" onclick="dateValidation()">Request VM/s</button>.
```
When I run the portal in IE the JavaScript function is getting triggered but the issue is with only Mozilla | 2014/02/26 | [
"https://Stackoverflow.com/questions/22038494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3090286/"
] | For example, use [`array_keys()`](http://php.net/array_keys):
```
$a = array(
0 => '',
'address_country' => '',
'1' => '2011-11-29 14:49:10',
'createdtime' => '2011-11-29 14:49:10'
);
$keys = array_keys($a);
$i = 1;
$m = count($keys);
foreach($a as $key=>$value)
{
echo(sprintf('My key is [%s] and my next neighbor key is [%s]'.PHP_EOL, $key, $i<$m?$keys[$i++]:null));
}
```
this will result in
```
My key is [0] and my next neighbor key is [address_country]
My key is [address_country] and my next neighbor key is [1]
My key is [1] and my next neighbor key is [createdtime]
My key is [createdtime] and my next neighbor key is []
```
note, that for last element next key will be treated as `null` | try this. I think this is what you want
```
$c = array_values($a);
for($i = 0; $i < count($c); $i++){
if(count($c)-1 > ($i)) {
if(array_search($c[$i+1],$a) == "address_country")
echo "found";
}
}
``` |
1,070,425 | Im building multi-server support for a file upload site Im running. When images are uploaded.... they are thumbnailed and stored on the main front-end server, until cron executes (every 10 mins) and moves them to storage servers, so for the first 10 mins, they will reside, and be served off the main front-end server.
When a file is uploaded, users are given embed codes... which is a thumbnail url + link to the full size, which is a html page. So it might be something like <http://www.domain.com/temp_content/filename.jpg> which links to <http://www.domain.com/file-ID>
Except in 10 mins, <http://www.domain.com/temp_content/filename.jpg> wont exist, it will be <http://server1.domain.com/thumbs/filename.jpg>
if the user grabbed the original code... the thumb file will be broken.
I COULD move the file to its destination, without cron, but that will take time, and will lag the script until the move is complete. I also dont like to have users running commands like that, I'd rather have the server do them at regular intervals.
Anything else I can? | 2009/07/01 | [
"https://Stackoverflow.com/questions/1070425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Have you considered a database storing the image\_name/image\_location, and a generic PHP script to serve the images from the database-details? | Really, given your situation the only option I can see is to give your users the actual URL's, since I'm sure you will be able to know them. You will then need to notify the users that they cannot actually use the link for 10 minutes.
In an idea world, I would see you putting this file directly to its final resting place, given your need to allow users access to the link. |
33,842 | A legacy software application needs to be rewritten to improve performance. This software is used on an hourly basis to bring money to the business. Because of the nature of its importance to the business, the business wants to know what is the impact to the current systems if it is rewritten. They have a concern that if the new software application fails, the old system needs to be used.
What should I consider when I do the impact analysis? Is there a template that I can use to present the data to the business? | 2022/04/03 | [
"https://pm.stackexchange.com/questions/33842",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/49476/"
] | You need to develop a case for change. You need to discuss:
* Problem statement and the need for change
* Current state with current business metrics such as revenue and
profit over the past several quarters
* Analysis of alternatives
* For each alternative, provide:
Expected business value, both objective and subjective, with the predicted timeframe for each value; Penalty paid if this alternative is rejected; Cost of this alternative; Risks with this alternative with high-level mitigating strategies and exit strategies; and ROI with this alternative
* Recommended decision
* Estimated duration of the change | Without specific knowledge of the business and the application, it is unlikely that anyone can give you a definitive answer. However, there are principles that you can use to guide you:
1. Don't try to do everything yourself. Use colleagues both in the business and in the technical teams to provide information on what they expect from the system, and the impact if these capabilities cannot be met.
2. Think about both the project risks (i.e. what happens if the project doesn't deliver) AND the operational risks (i.e. what happens if the live system doesn't do as expected or fails in live operation). Be very careful that you don't confuse these different types of risk, as they are almost certainly owned and must be dealt with by different people.
3. Consider the approach to delivering the system - do you need to deliver a "like for like" solution, or are there any "must have" add-ons, or are there any redundant features in the current solution that can be deleted? Does the full capability have to be there on day 1 of the new system, or can you survive with a limited feature set and develop the remainder in future iterations?
4. Think about the impact and the likelihood of any issues, and combine them in a way that is meaningful to you to grade the risks associated with each. Then treat these risks in turn. Most risk analyses I have seen have been graded as "High", "Medium", "Low" on both axes, so you may have risks in each of the 9 categories "High / High", "High / Medium", etc, right down to "Low / Low". Get these signed off by the product owner / business owner of the system, and then address them.
In terms of business presentation, I suggest that you list the risks according to the groupings I have mentioned above: Project risks and Operational risks kept separately, then prioritised within each according to their position in the risk matrix with "High / High" at the top of the list. Your question really refers to the Operational risks more than the project risks, so perhaps that is the area to concentrate on first, but don't forget about the project risks entirely.
Good luck! |
6,484,177 | I have a text file which always has one line, how could I set a string for the first line of the text file in C#?
e.g. line1 in test.txt = string version | 2011/06/26 | [
"https://Stackoverflow.com/questions/6484177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/816110/"
] | A text file is not line based, so you can't change a specific line in a text file, you would need to rewrite the entire file.
If your file only ever contains that single line, you can just rewrite the file with the new string:
```
File.WriteAllText(fileName, newValue);
```
### Edit:
As you said that what you actually want to do is to read the file, it's different... If there is only a single line in the file, you can read the entire file:
```
string line = File.ReadAllText(fileName);
```
If the file could contain more than a single line, you would have to open the file and only read the first line:
```
string line;
using (StreamReader reader = new StreamReader(fileName)) {
line = reader.ReadLine();
}
```
You could also use `File.ReadAllLines` and get the first line from the result, but that would be wasteful if the file contains a lot of lines. | Have a look at the [`File` class](http://msdn.microsoft.com/en-us/library/system.io.file.aspx). |
50,276,833 | Ok, first time posting a question so I hope I do everything by the book.
I wanted to use javascript to retrieve and display the width/height of an image that the user picks using an Input button. But it's a hot day here and I can feel my brain just going round in circles.
Using this script I get it to display the image and the width (or so I thought). I try to select an image which is 180px wide but my script returns the number 16. Other images either returns 16 or other arbitrary numbers.
EDIT: Different browsers return different numbers.
What am I displaying and what am I missing to get it right?
This is my HTML:
```
<head>
<title>Image size calculator</title>
<!-- Normalize.css -->
<link rel="stylesheet" type="text/css" href="normalize.css">
<!-- Custom Styles -->
<link rel="stylesheet" type="text/css" href="style.css">
<!--[if IE]>
<script
src="https://github.com/aFarkas/html5shiv/blob/master/src/html5shiv.js">
</script>
<![endif]-->
</head>
<body>
<h1>Vilken storlek har min bild?</h1>
<p><em>Supported formats are: BMP/CUR/GIF/ICO/JPEG/PNG/PSD/TIFF/WebP/SVG/DDS</em></p><br><br>
<form>
<input type="file" onchange="readURL(this);">
<br><br>
<img id="imageDisplay" src="#" />
<label id="imageSize">Bilden är: </label>
</form>
<!-- How to load jQuery.
1. Load the CDN version (internet)
2. If fail, load the installed (local) -->
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="js/jquery-3.3.1.js"><\/script>');</script>
<script src="js/script.js"></script>
</body>
```
And this is the code in my script.js file:
```
function readURL(input) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageDisplay')
.attr('src', e.target.result)
.width(this.width)
.height(this.height);
};
reader.readAsDataURL(input.files[0]);
var imgWidth = $("#imageDisplay").width();
$("#imageSize").append(imgWidth);
```
}
EDIT 2: Thanks for all the solutions. I tried out Scott's (which made me smack my forehead and say 'duh' when I read it). It seems I was on the right track as my suspicion was that the image wasn't fully loaded. I just couldn't get the code for checking that right. Sometimes you need a little push in the right direction. :) | 2018/05/10 | [
"https://Stackoverflow.com/questions/50276833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9771747/"
] | You should use [`HTMLImageElement.naturalWidth`](https://www.w3schools.com/jsref/prop_img_naturalwidth.asp) and [`HTMLImageElement.naturalHeight`](https://www.w3schools.com/jsref/prop_img_naturalheight.asp) instead of just [`image.width`](https://www.w3schools.com/jsref/prop_img_width.asp) and [`image.height`](https://www.w3schools.com/jsref/prop_img_height.asp).
While the former returns the original/intrinsic width or height of the image, the latter will return the dimensions of the image as displayed. That means that if you are resizing it with CSS, you will get the values based on that.
Also, the image itself also has an [`image.onload` event](https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/image.onload) you should listen to in order to access its properties once it has finished loading. Otherwise, you might access them before and get incorrect values.
Anyway, `image.naturalWith` and `image.naturalHeight` are available before the `onload` event is triggered, so you might try to get them instead, but in order to have a reliable solution, you need to implement polling using [`WindowOrWorkerGlobalScope.setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval).
You can check this out in this example:
```js
const input = document.getElementById('input');
const button = document.getElementById('button');
const image = document.getElementById('image');
const naturalSize = document.getElementById('naturalSize');
const displaySize = document.getElementById('displaySize');
let intervalID = null;
function updateSizeLabels() {
naturalSize.innerText = `ORIGINAL SIZE: ${ image.naturalWidth } × ${ image.naturalHeight }`;
displaySize.innerText = `DISPLAY SIZE: ${ image.width } × ${ image.height }`;
};
function changeImage(src) {
console.clear();
// Reset src so that you don't get the previus dimensions
// if you load more than one image:
image.src = '';
image.src = src;
// Solution with polling:
// We try to get the dimensions just after setting src:
const alreadyAvailable = pollNaturalDimensions();
// Polling only needed if the dimensions are not there yet:
if (!alreadyAvailable) {
// Just in case we already have a setInterval running:
clearInterval(intervalID);
// Every 10ms, we check again if naturalWidth is there:
intervalID = setInterval(pollNaturalDimensions, 10);
}
}
function pollNaturalDimensions() {
if (image.naturalWidth) {
console.log('Dimensions already available.');
// Stop polling:
clearInterval(intervalID);
// You can display the dimensions already:
updateSizeLabels();
return true;
}
}
// Solution with onload:
// This will update the size labels everytime an image is loaded:
image.onload = () => {
console.log('Image loaded.');
updateSizeLabels();
};
input.onchange = () => {
const reader = new FileReader();
reader.onload = (e) => changeImage(e.target.result);
reader.readAsDataURL(input.files[0]);
}
button.onclick = (e) => {
e.preventDefault();
changeImage(image.src === 'http://www.traversecityfilmfest.org/wp-content/uploads/2017/07/Baby-driver-gif.gif' ? 'https://thumbs.gfycat.com/BleakTenderBarb-small.gif' : 'http://www.traversecityfilmfest.org/wp-content/uploads/2017/07/Baby-driver-gif.gif');
};
```
```css
body {
padding: 0 0 45px;
}
body,
input,
button {
font-family: monospace;
}
.as-console-wrapper {
max-height: 45px !important;
}
#image {
max-width: 200px;
max-height: 200px;
margin: 16px 0 0;
}
```
```html
<h1>Select an image to see its dimensions:</h1>
<form>
<input id="input" type="file">
<button id="button">Load Remote Image</button>
</form>
<img id="image" />
<p id="naturalSize"></p>
<p id="displaySize"></p>
```
Note, that when working with local images, the `image.onload` solution might return the dimensions before the polling one. When testing it on my Mac, they seem to be head-to-head. However, if you try loading remote images, especially big ones and/or on slow networks, the polling solution would make more sense. | As correctly pointed out by LGSon, you have to wait for onLoad.
```
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
}
}
``` |
33,823 | I have a server in the closet and an extra monitor which I setup on the wall just outside the closet. I would like to have it display various status tools. I like RDP as is but want to have the experience something like VNC provides without it's sluggish performance.
Is it possible with Windows Server 2008 R2 (or prev server versions) to have RDP act like VNC?
The server is connected directly with a VGA cable to 15" LCD that I can see from my desk about 10 feet away. The feature I would like to have from VNC is being able to see my keyboard and mouse interactions on the monitor. Usually RDP acts like a separate login instead of taking over the screen like VNC. | 2009/06/30 | [
"https://serverfault.com/questions/33823",
"https://serverfault.com",
"https://serverfault.com/users/411/"
] | **RDP** acts like RDP.
You may want to consider using something else.
**[Best Windows remote support / screen sharing tools?](https://serverfault.com/questions/155/best-windows-remote-support-screen-sharing-tools)** | -console does not work with windows 2008, vista, or windows 7. that switch has been depreciated.
the closest match is /admin, but that just gives you an administrative RDP session, it does not give you the console itself.
in fact, if the same use is logged in on the console of a 2008r2 server, you will convert their session to an RDP session, and then it can be timed out by RDP group policy settings and closed. |
1,303,029 | I am playing around with C# collections and I have decided to write a quick test to measure the performance of different collections.
My performance test goes like this:
```
int numOps= (put number here);
long start, end, numTicks1, numTicks2;
float ratio;
start = DateTime.Now.Ticks;
for(int i = 0; i < numOps; i++)
{
//add two elements to collection #1
//remove one element from collection #1
}
end = DateTime.Now.Ticks;
numTicks1 = end - start;
start = DateTime.Now.Ticks;
for(int i = 0; i < numOps; i++)
{
//add two elements to collection #2
//remove one element from collection #2
}
end = DateTime.Now.Ticks;
numTicks2 = end - start;
ratio = (float)numTicks2/(float)numTicks1;
```
Then I compare the ratio value using different Collections and different values for numOps to see how they compare.
The problem is sometimes when I use a small enough number (numOps = 500), the test results between a Hashtable and List are sporadic (in other words it's a coin flip which one is faster). Can anyone explain why this is?
**EDIT: Thanks everyone! Stopwatch works like a charm.** | 2009/08/19 | [
"https://Stackoverflow.com/questions/1303029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159615/"
] | The proper way to time things diagnostically is to run the code many times iteratively (so that the total time is many multiples of the resolution of whatever timing mechanism you use) and then divide by the number of iterations to get an accurate time estimate.
Stopwatch returns times that are not quantized by 15 ms, so it's obviously more appropriate for timing events. | I used the following code to test the performance of a `Dictionary` using three different `GetHash` implementations:
```
class TestGetHash
{
class First
{
int m_x;
}
class Second
{
static int s_allocated = 0;
int m_allocated;
int m_x;
public Second()
{
m_allocated = ++s_allocated;
}
public override int GetHashCode()
{
return m_allocated;
}
}
class Third
{
int m_x;
public override int GetHashCode()
{
return 0;
}
}
internal static void test()
{
testT<First>(100, 1000);
testT<First>(1000, 100);
testT<Second>(100, 1000);
testT<Second>(1000, 100);
testT<Third>(100, 100);
testT<Third>(1000, 10);
}
static void testT<T>(int objects, int iterations)
where T : new()
{
System.Diagnostics.Stopwatch stopWatch = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < iterations; ++i)
{
Dictionary<T, object> dictionary = new Dictionary<T, object>();
for (int j = 0; j < objects; ++j)
{
T t = new T();
dictionary.Add(t, null);
}
for (int k = 0; k < 100; ++k)
{
foreach (T t in dictionary.Keys)
{
object o = dictionary[t];
}
}
}
stopWatch.Stop();
string stopwatchMessage = string.Format("Stopwatch: {0} type, {1} objects, {2} iterations, {3} msec", typeof(T).Name, objects, iterations, stopWatch.ElapsedMilliseconds);
System.Console.WriteLine(stopwatchMessage);
stopWatch = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < iterations; ++i)
{
Dictionary<T, object> dictionary = new Dictionary<T, object>();
for (int j = 0; j < objects; ++j)
{
T t = new T();
dictionary.Add(t, null);
}
}
stopWatch.Stop();
stopwatchMessage = string.Format("Stopwatch (fill dictionary): {0} type, {1} objects, {2} iterations, {3} msec", typeof(T).Name, objects, iterations, stopWatch.ElapsedMilliseconds);
System.Console.WriteLine(stopwatchMessage);
{
Dictionary<T, object> dictionary = new Dictionary<T, object>();
for (int j = 0; j < objects; ++j)
{
T t = new T();
dictionary.Add(t, null);
}
stopWatch = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < iterations; ++i)
{
for (int k = 0; k < 100; ++k)
{
foreach (T t in dictionary.Keys)
{
object o = dictionary[t];
}
}
}
stopWatch.Stop();
stopwatchMessage = string.Format("Stopwatch (read from dictionary): {0} type, {1} objects, {2} iterations, {3} msec", typeof(T).Name, objects, iterations, stopWatch.ElapsedMilliseconds);
System.Console.WriteLine(stopwatchMessage);
}
}
}
``` |
82,867 | A [field](https://en.wikipedia.org/wiki/Field_(mathematics)) in mathematics is a set of numbers, with addition and multiplication operations defined on it, such that they satisfy certain axioms (described in Wikipedia; see also below).
A finite field can have pn elements, where `p` is a prime number, and `n` is a natural number. In this challenge, let's take `p = 2` and `n = 8`, so let's make a field with 256 elements.
The elements of the field should be consecutive integers in a range that contains `0` and `1`:
* -128 ... 127
* 0 ... 255
* or any other such range
Define *two* functions (or programs, if that is easier), `a(x,y)` for abstract "addition", and `m(x,y)` for abstract "multiplication", such that they satisfy the field axioms:
* Consistency: `a(x,y)` and `m(x,y)` produce the same result when called with same arguments
* Closedness: The result of `a` and `m` is an integer in the relevant range
* Associativity: for any `x`, `y` and `z` in the range, `a(a(x,y),z)` is equal to `a(x,a(y,z))`; the same for `m`
* Commutativity: for any `x` and `y` in the range, `a(x,y)` is equal to `a(y,x)`; the same for `m`
* Distributivity: for any `x`, `y` and `z` in the range, `m(x,a(y,z))` is equal to `a(m(x,y),m(x,z))`
* Neutral elements: for any `x` in the range, `a(0,x)` is equal to `x`, and `m(1,x)` is equal to `x`
* Negation: for any `x` in the range, there exists such `y` that `a(x,y)` is `0`
* Inverse: for any `x≠0` in the range, there exists such `y` that `m(x,y)` is `1`
The names `a` and `m` are just examples; you can use other names, or unnamed functions. The score of your answer is the sum of byte-lengths for `a` and `m`.
If you use a built-in function, please also describe in words which result it produces (e.g. provide a multiplication table). | 2016/06/14 | [
"https://codegolf.stackexchange.com/questions/82867",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/25315/"
] | JavaScript (ES6), 10 + 49 = 59 bytes
------------------------------------
```
a=(x,y)=>x^y
m=(x,y,p=0)=>x?m(x>>1,2*y^283*(y>>7),p^y*(x&1)):p
```
Domain is 0 ... 255. [Source](https://en.wikipedia.org/wiki/Finite_field_arithmetic#Program_examples). | IA-32 machine code, 22 bytes
============================
"Multiplication", 18 bytes:
```
33 c0 92 d1 e9 73 02 33 d0 d0 e0 73 02 34 1b 41
e2 f1
```
"Addition", 4 bytes:
```
92 33 c1 c3
```
This stretches rules a bit: the "multiplication" code lacks function exit code; it relies on the "addition" code being in memory right afterwards, so it can "fall-through". I did it to decrease code size by 1 byte.
Source code (can be assembled by `ml` of MS Visual Studio):
```
TITLE x
PUBLIC @m@8
PUBLIC @a@8
_TEXT SEGMENT USE32
@m@8 PROC
xor eax, eax;
xchg eax, edx;
myloop:
shr ecx, 1
jnc sk1
xor edx, eax
sk1:
shl al, 1
jnc sk2
xor al, 1bh
sk2:
inc ecx
loop myloop
@m@8 endp
@a@8 proc
xchg eax, edx;
xor eax, ecx
ret
@a@8 ENDP
_text ENDS
END
```
The algorithm is the standard one, involving the usual polynomial `x^8 + x^4 + x^3 + x + 1`, represented by the hexadecimal number `1b`. The "multiplication" code accumulates the result in `edx`. When done, it falls through to the addition code, which moves it to `eax` (conventional register to hold return value); the `xor` with `ecx` is a no-op, because at that point `ecx` is cleared.
One peculiar feature is the loop. Instead of checking for zero
```
cmp ecx, 0
jne myloop
```
it uses the dedicated `loop` instruction. But this instruction decreases the loop "counter" before comparing it to 0. To compensate for this, the code increases it before using the `loop` instruction. |
66,737 | It was pointed out [in this answer](https://christianity.stackexchange.com/a/66731) and [this answer](https://christianity.stackexchange.com/a/66712) that in the book of Mormon, [2 Nephi 2:22-23](https://www.lds.org/scriptures/bofm/2-ne/2) it states
>
> 22. And now, behold, if Adam had not transgressed he would not have fallen, but he would have remained in the garden of Eden. And all things which were created must have remained in the same state in which they were after they were created; and they must have remained forever, and had no end.
> 23. And they would have had no children; wherefore they would have remained in a state of innocence, having no joy, for they knew no misery; doing no good, for they knew no sin.
>
>
>
Is there any biblical basis for the book of Mormon to state that everything in the Garden of Eden was to remain unchanged and therefore Adam and Eve would not have had children without falling from God's grace?
This seems to contradict God's first instruction to Adam and Eve in Genesis 1:28 when He said
>
> Be fruitful and increase in number; fill the earth and subdue it. ([NIV](https://www.biblestudytools.com/genesis/1.html))
>
>
> | 2018/10/19 | [
"https://christianity.stackexchange.com/questions/66737",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/35851/"
] | The Bible doesn't have a direct reference to this, but this is part of the reason the Church of Jesus Christ believes in the need for multiple scriptures. One can see that in Genesis Adam and Eve were only kicked out of the Garden of Eden and only started having children after partaking of the fruit of knowledge of good and evil.
[Chapter 3](https://www.lds.org/scriptures/ot/gen/3?lang=eng)
>
> 5 For **God doth know that in the day ye eat thereof, then your eyes shall be opened, and ye shall be as gods, knowing good and evil**.
>
>
> 6 And when the woman saw that the tree was good for food, and that it was pleasant to the eyes, and a tree to be desired to make one wise, **she took of the fruit thereof, and did eat, and gave also unto her husband with her; and he did eat**.
>
>
> 7 And the eyes of them both were opened, and they knew that they were naked; and they sewed fig leaves together, and made themselves aprons.
>
>
> 17 And unto Adam he said, Because thou hast hearkened unto the voice of thy wife, and hast eaten of the tree, of which I commanded thee, saying, Thou shalt not eat of it: cursed is the ground for thy sake; in sorrow shalt thou eat of it all the days of thy life;
>
>
> 22 ¶ And the **Lord God said, Behold, the man is become as one of us, to know good and evil**: and now, lest he put forth his hand, and take also of the tree of life, and eat, and live for ever:
>
>
> 23 Therefore the Lord God sent him forth from the garden of Eden, to till the ground from whence he was taken.
>
>
>
Chapter 4
>
> 1 And Adam knew Eve his wife; and she conceived, and bare Cain, and said, I have gotten a man from the Lord.
>
>
>
The reason the first two commandments contradicted was that God was setting the stage to show all of us that mankind has Agency, which is integral to the Plan of Salvation.
[Moses 3:17](https://www.lds.org/scriptures/pgp/moses/3.17?lang=eng#p16) clarifies the commandment to not eat of the tree of knowledge.
>
> 17 But of the tree of the knowledge of good and evil, thou shalt not eat of it, nevertheless, **thou mayest choose for thyself**, for it is given unto thee; but, remember that I forbid it, for in the day thou eatest thereof thou shalt surely die.
>
>
> | >
> This seems to contradict God's first instruction to Adam and Eve in Genesis 1:28
>
>
>
Correct. Note that there are two types of human, the general found in Gen 1:27 and the specific in Gen 2:7. This is implied in Cain's fear of being killed by other humans and his wife Gen 4:14,17. So Gen 1:28 applies to the general humans, and indirectly to Adam.
Regarding the Mormon passage, there is a shift in thought from verse 22 to 23, which creates the problem. The *state* used in 22 is correct when it refers to the state of innocence, but not in 23 when referring to the state of physical condition. It confuses the spiritual state with the physical. Humans were expected to develop and progress intellectually while remaining in the state of righteousness before God. Trees, plants, and animals were to grow and flourish throughout the Earth.
The assumption that somehow children are the product of evil is stated as a blessing in Gen 1:28. Thus, God clearly expected lots of humans who could not think anything good or bad. Furthermore, Eve was created before the fall with the intent that 'therefore shall a man leave his father and mother' (Gen 2:24) which clearly anticipates children prior to the fall.
So we (you and I) can agree with verse 22, but not verse 23, even though 23 throws in the word *innocence*. |
4,037,081 | We have a sequence given by:
$$a\_1 = 1 \\ a\_2 = b \\
a\_{n+2}=a\_{n+1}+a\_n$$
We need to find the limit of the sequence. The procedure of getting the solution is that we $a\_n = p^n$ and then somehow solve the equation $p^{n+2}=\frac{1}{3}p^n+\frac{2}{3}p^{n+1}\implies p^2 - \frac{2}{3}p-\frac{1}{3} = 0$
For this quadratic equation there are two solutions, that we input:
$$a\_1 = A - \frac{1}{3}B = 1, a\_2 = A +\frac{1}{9}B = b \implies A = \frac{1+3b}{4}, B = \frac{9(b-1)}{4}$$
However I do not understand this process. Why can we say that $a\_n = p^n$ and what follows from it. Where can we use this technique? | 2021/02/23 | [
"https://math.stackexchange.com/questions/4037081",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/511545/"
] | I guess what you are asking is how the "guess" $a\_n = p^n$ can be justified, i.e. why is this the way to proceed and why is it complete, i.e. it produces all solutions.
Without having to develop a theory of difference equations from scratch, we can use mighty results from linear algebra. Transform your difference equation $a\_{n+2}=a\_{n+1}+a\_n$ into a vector equation as follows:
$$
\left ( \begin{matrix}
a\_{n+2}\\a\_{n+1}
\end{matrix} \right ) = \left ( \begin{matrix}
1&1\\1&0
\end{matrix} \right )
\left ( \begin{matrix}
a\_{n+1}\\a\_{n}
\end{matrix} \right )
$$
Now writing for short the vector $
x\_n =
\left ( \begin{matrix}
a\_{n+1}\\a\_{n}
\end{matrix} \right )
$ and the matrix $A = \left ( \begin{matrix}
1&1\\1&0
\end{matrix} \right )
$ we have $x\_{n+1} = A \cdot x\_n$ and hence $x\_{n+1} = A^{n} \cdot x\_1$. Your $
x\_1 =
\left ( \begin{matrix}
a\_{2}\\a\_{1}
\end{matrix} \right )
=\left ( \begin{matrix}
b\\1
\end{matrix} \right )
$ is obviously a known start vector.
So the problem has been transferred to obtaining the power of a matrix $A$. Now the linear algebra results come in. Let $u\_1$ and $u\_2$ be the two eigenvectors of $A$ with corresponding eigenvalues $\lambda\_1$ and $\lambda\_2$, then the eigenvectors form a basis and you can write any initial condition as $x\_1 = c\_1 u\_1 + c\_2 u\_2$ with constants $c\_1$ and $c\_2$. Then you have $x\_{n+1} = A^{n} \cdot x\_1 = c\_1 \lambda\_1^n u\_1 + c\_2 \lambda\_2^n u\_2$.
So here you have the answer to the above question. Since taking the first component of $x\_{n+1}$, which is $a\_{n+2}$, gives $a\_{n+2} = d\_1 \lambda\_1^n + d\_2 \lambda\_2^n$ with constant coefficients $d\_1$ and $d\_2$ depending on the initial conditions and on $A$. So we can deduce:
a) the *ansatz* $a\_{n} = b\_1 \lambda\_1^n + b\_2 \lambda\_2^n$ is correct and complete.
b) the $\lambda\_1$ and $\lambda\_2$ in this ansatz are the eigenvalues of $A$.
c) the constants $b\_1$ and $b\_2$ in this ansatz have to be matched to the initial conditions.
So it was not by chance or by some phenomenal genius that a power law was "guessed" in the beginning. Also, the characteristic equation does not appear from out of the blue, but is exactly what is needed to find the eigenvalues of $A$.
Obviously, this derivation generalizes to homogenous linear difference equations of any finite degree. | Here is some presentation without matrices, it is easy to understand for a recurrence with only two terms, but keep in mind that the generalization with many terms is easier to handle with linear algebra theory as in Andreas's answer.
* Let start with the simple case $x\_{n+1}=ax\_n$
It can be solved by induction to $x\_n=a^nx\_0$
* Now with $x\_{n+1}=ax\_n+bx\_{n-1}$
Recall that the quadratic equation $$r^2-sr+p=0$$ has roots whose sum is $s$ and product $p$.
So let's call $r\_1,r\_2$ the roots of $r^2-ar-b=0$
We can rewrite our equation $x\_{n+1}=(r\_1+r\_2)x\_n-r\_1r\_2x\_{n-1}\iff (\overbrace{x\_{n+1}-r\_1x\_n}^{y\_{n+1}})=r\_2(\overbrace{x\_n-r\_1x\_{n-1}}^{y\_n})$
By first case then $$y\_{n+1}=r\_2y\_n\iff y\_n=C\_2{r\_2}^n$$
And since equation is linear, a solution is the sum of a general solution of homogeneous equation and a particular solution with RHS.
In this case $x\_{n+1}-r\_1x\_n=\overbrace{C\_2{r\_2}^n}^{\text{RHS}}$
Solves to $x\_n=C\_1{r\_1}^n+y\_n=C\_1{r\_1}^n+C\_2{r\_2}^n$
Rem: *here I assumed $r\_1\neq r\_2$, when they are equal the particular solution is different, but not let's compilate too much for the moment*
* For the general case $x\_{n+1}=\sum\limits\_{i=1}^k a\_ix\_{n+1-i}$
We can proceed similarly using [Newton's identities](https://en.wikipedia.org/wiki/Newton%27s_identities) to express the $a\_i$ in terms of the roots $r\_i$ and rearrange the terms to make an expression $y\_{n+1}=r\_ky\_n$ and solve it recursively like in the case with $k=2$.
This is why we generally solve the characteristic equation $r^k=\sum\limits\_{i=1}^{k}a\_ir^{i-1}$ whose roots are $r\_i$.
And that we have a solution $x\_n=C\_1{r\_1}^n+\cdots+C\_k{r\_k}^n$
This at least is in the ideal case where all roots are distinct, the complications arise when some roots have higher multiplicity, in which case the general solution for a root of multiplicity $m$ is $$(\alpha\_0+\alpha\_1n+\cdots+\alpha\_{m-1}n^{m-1})r^n\quad\text{instead of}\quad (\alpha\_0\,r^n)$$ |
10,667,286 | I have seen some applications that scan image and give back text. Is there any library for this or not? I mean either scanning text or taking a picture of it and identify characters?
I have searched for OCR but I have not found material so as to read. Can you help me with this? | 2012/05/19 | [
"https://Stackoverflow.com/questions/10667286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1267718/"
] | Have a look at a library called [Tesseract](http://code.google.com/p/tesseract-ocr/). Here's [a tutorial](http://gaut.am/making-an-ocr-android-app-using-tesseract/). | Yes you can use google vision library for convert image to text, it will give better output from image.
Add below library in build gradle:
```
compile 'com.google.android.gms:play-services-vision:10.0.0+'
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap) // your image bitmap
.build();
String imageText = "";
SparseArray<TextBlock> textBlocks = textRecognizer.detect(imageFrame);
for (int i = 0; i < textBlocks.size(); i++) {
TextBlock textBlock = textBlocks.get(textBlocks.keyAt(i));
imageText = textBlock.getValue(); // return string
}
``` |
55,382 | My understanding of the Heartbleed vulnerability is that there is no bounds check on the payload length/buffer size so the server can read into memory outside of its process space.
But can the start address be modified?
If not, then the probability of snagging anything interesting from a server with gigs of RAM, where much of the time that space may not change, is far less likely than if any 64K space can be read.
This article seems to sensationalize the impact from a rational discussion of probability to a stance of "you cannot trust anything; your server RAM has been 100% exposed for years".
<https://www.schneier.com/blog/archives/2014/04/heartbleed.html>
Granted, 64K is a fairly large chunk, enough to store 3,200 SHA1 hashes, but on a 4Gb server, its still only 1 / 67,108th of the total address space - is the threat being hyped? | 2014/04/10 | [
"https://security.stackexchange.com/questions/55382",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/29911/"
] | The 64k block that gets returned is selected effectively at random, which seems like it would make it hard to find worthwhile data. However, there are two factors that significantly increase the threat:
First, the attack won't return memory that was allocated during program start-up. This means the area occupied by boring things like program code won't show up in attack results; likewise, the half of the address space reserved for the operating system won't be returned.
Second, because of how memory allocation is done, the 64k block will tend to come from recently-used memory. For example, if a server handles a lot of login attempts, the memory is likely to have been used for a recent login, and could very well contain a username/password pair or two. Good timing might get you memory used to set up the SSL connection, and you might be able to find an SSL private key in that.
A third point is that the attack can be performed quickly and repeatedly -- and is almost impossible to detect. A home internet connection might be able to hit a server with tens of thousands of heartbeat requests per second. | There was an answer here that has since been deleted that was really interesting, at least in the comments it provoked.
Essentially, the answererer was (not very clearly) trying to say that each new allocation of buffer to read the heartbeat from changes the start address, and because you are able to run the attack many times, you are able to randomly pull data from a particular area of RAM, hitting a different spot each time.
Mark says in his answer above:
>
> The 64k block that gets returned is selected effectively at random
>
>
>
He is also presumably alluding to this mechanism. |
1,099,371 | In Perl 5.10, how do I create and access a hash with scalar keys whose values are arrays?
```
#Doing this does not work properly.
%someHash= ("0xfff" => ('Blue', 'Red', 'Yellow'));
@arr = @fileContents{"0xfff"};
print @arr;
```
When I print the array, the only thing that prints is "ARRAY('randmemAddr')". When I do a foreach loop on @arr, only the first element is printed. I have then concluded that I have not stored the array properly in the hash. | 2009/07/08 | [
"https://Stackoverflow.com/questions/1099371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57627/"
] | My original answer posted working code, but didn't really explain the problem with yours. This is expanded a bit to correct that. Your example had two problems. First, you had a problem when making the reference. You need to use `[ ]` instead of the standard parentheses in order to create a reference (to an anonymous array). Second, when you tried to get at the reference, you left off one set of brackets. You want to put the reference itself inside `@{ }` in order to get at the whole array. (Also, and this may be a typo: you have no `$` before `filecontents`.)
The code here is essentially from [`perldoc perldsc`](http://perldoc.perl.org/perldsc.html). I highly recommend it. Also very useful if you're new to references in Perl is [`perldoc perlreftut`](http://perldoc.perl.org/perlreftut.html). Both tutorials discuss how to make and get at references in a variety of situations. Finally, you can find a good cheat sheet for references in a post on [PerlMonks](http://www.perlmonks.org/?node_id=69927).
```
#!/usr/bin/env perl
use strict;
use warnings;
my %HoA = (
flinstones => [ qw/fred barney/ ],
jetsons => [ qw/george jane elroy/ ],
);
for my $family (keys %HoA) {
print "Members of the \u$family:\n";
print "\t @{ $HoA{$family} }\n";
}
``` | I find it much easier to use [Data::Dumper](http://search.cpan.org/~smueller/Data-Dumper-2.124/Dumper.pm) module. Odds are very high that it comes with your perl distribution. It allows you to quickly see what your data structure is.
In your case it would be:
```
use Data::Dumper;
my %someHash= ("0xfff" => ('Blue', 'Red', 'Yellow'));
print Dumper \%someHash;
```
This will output:
```
$VAR1 = {
'Red' => 'Yellow',
'0xfff' => 'Blue'
};
```
of course, to fix it you need to store your array as reference:
```
use Data::Dumper;
my %someHash= ("0xfff" => [qw(Blue Red Yellow)]);
print Dumper \%someHash;
```
Which will produce:
```
$VAR1 = {
'0xfff' => [
'Blue',
'Red',
'Yellow'
]
};
```
Bottom line is Data::Dumper is your best friend |
58,338,604 | I have problem to automate this drop down using selenium web driver using Java
[This](https://jedwatson.github.io/react-select/) is the link - Go to 5th drop down named as Github users (fetch. js)
I am not able to enter the data into search field.
I am using send keys after perform click but it throws an exception like this " element is not interact able"
Steps I follow
```
driver.findElement(By.xpath("xapth")).click
```
drop down opens with no options because it is searchable and options are coming dynamically after entering key word into the search field.
```
driver.findElement(By.xpath("xapth")).sendkeys("Test");
```
Sendkeys are not working in this case because of drop down closed when perform send keys action.
```
<div class="Select-placeholder">Select...</div>
``` | 2019/10/11 | [
"https://Stackoverflow.com/questions/58338604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12180800/"
] | We can handle this requirement with the help of `ROW_NUMBER` and a pivot query:
```
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY PhoneID) rn
FROM Phones
)
SELECT
CustomerID,
MAX(CASE WHEN rn = 1 THEN PhoneNum END) AS PhoneNum1,
MAX(CASE WHEN rn = 2 THEN PhoneNum END) AS PhoneNum2,
MAX(CASE WHEN rn = 3 THEN PhoneNum END) AS PhoneNum3
FROM cte
GROUP BY
CustomerID
ORDER BY
CustomerID;
```
[Demo
----](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=68fa8ea57cea6309dddf89bf5db59b14) | ```
The query above was very useful. But when I use the Where, the result is not right
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY PhoneID) rn
FROM Phones
)
SELECT
CustomerID,
MAX(CASE WHEN rn = 1 THEN PhoneNum END) AS PhoneNum1,
MAX(CASE WHEN rn = 2 THEN PhoneNum END) AS PhoneNum2,
MAX(CASE WHEN rn = 3 THEN PhoneNum END) AS PhoneNum3
FROM cte
where PhoneNum ='09811111'
GROUP BY
CustomerID
ORDER BY
CustomerID;
Result:
--------------------------------------------------------------------------
| CustomerID | PhoneNum1 | PhoneNum2 | PhoneNum3 |
--------------------------------------------------------------------------
| 1 | 09811111 | NULL | NULL |
---------------------------------------------------------------------------
``` |
56,719,066 | * At the end of each unit tests, I call `tf.reset_default_graph()` to clear the default graph.
* However, when a unit test fails, the graph doesn't get cleared. That makes the next unit test fails as well.
How to clear a graph upon exiting the `tf.Session()` context?
Example (pytest):
```
import tensorflow as tf
def test_1():
x = tf.get_variable('x', initializer=1)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(4 / 0)
print(sess.run(x))
def test_2():
x = tf.get_variable('x', initializer=1)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(x))
``` | 2019/06/22 | [
"https://Stackoverflow.com/questions/56719066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8704463/"
] | I suggest to use the tools `pytest` offers:
```
@pytest.fixture(autouse=True)
def reset():
yield
tf.reset_default_graph()
```
The fixture will be automatically invoked before and after each test (flag `autouse`), code before/after `yield` is executed before/after test. This way the tests from your question will work without any modification and you follow the DRY principle, refusing to write duplicated code in each test. Another example:
```
@pytest.fixture(autouse=True)
def init_graph():
with tf.Graph().as_default():
yield
```
will create a new graph for each test before the test executes.
Fixtures in `pytest` are very powerful and can fully eliminate code repetitions when used properly. For example, the tests from your question are equivalent to:
```
@pytest.fixture
def x():
return tf.get_variable('x', initializer=1)
@pytest.fixture
def session(x):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
yield sess
@pytest.fixture(autouse=True)
def init_graph():
with tf.Graph().as_default():
yield
def test_1(session, x):
print(4 / 0)
print(session.run(x))
def test_2(session, x):
print(session.run(x))
```
If you want to learn more, start with [pytest fixtures: explicit, modular, scalable](https://docs.pytest.org/en/latest/fixture.html). | Would something like this work?
```py
import tensorflow as tf
def test_1():
G = tf.Graph()
with G.as_default():
x = tf.get_variable('x', initializer=1)
with tf.Session() as sess:
sess.run(tf.initializers.global_variables())
print(sess.run(x))
print(4 / 0)
def test_2():
G = tf.Graph()
with G.as_default():
x = tf.get_variable('x', initializer=1)
with tf.Session() as sess:
sess.run(tf.initializers.global_variables())
print(sess.run(x))
``` |
722,593 | Show that there is no solution to:
$$v(x)=1+3 \int\_0^1 xy v(y) dy$$
When the solution $v(x)$ must be of the form $1+cx$ for some constant $c$.
I tried solving this I am getting $x=0$. What am I doing wrong? | 2014/03/22 | [
"https://math.stackexchange.com/questions/722593",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/126012/"
] | I assume $y$ is a dummy variable for the integration and independent of $x$. Pull the $x$ out of the integral, and write $v(y)=1+cy$; then this says
$$1+cx=1+3x\int\_0^1 y+cy^2dy$$
Integrating gives $\frac {y^2}2+c\frac{y^3}3$, so after evaluating this becomes $$1+cx = 1+3x\left(\frac 13 c+\frac 12\right)=1+cx+\frac 32x$$
So what we've said here is that $v(x)=v(x)+\frac 32x$ as functions (in other words, this equality is true for all values of $x$.) But that's just silly: it says, for instance, that $v(2)=v(2)+3$, so $3=0$. | See that
LHS: $1+cx$
RHS: $$1+3\int\_{0}^{1}xy(1+cy)dy=1+3x\int\_{0}^{1}y+cy^2dy=1+x[\frac{1}{2}y^2+\frac{c}{3}y^3]^{1}\_{0}=1+3x(\frac{1}{2}+\frac{c}{3})$$So if it should be equal we have that $$
c=3(\frac{1}{2}+\frac{c}{3})\Rightarrow 0=\frac{3}{2}
$$
which is clearly impossible |
12,410 | I am writing selenium tests, and following the convention of using Webdriver Waits to have the webdriver poll for an object before it tries to interact with it.
I am frequently finding my tests are failing, and it seems like it is due to a race condition where I am interacting with an element before it has fully loaded.
For example, if I go to my product catalog page, apply some filter, then click on one of the products (loaded by javascript after the filter is applied), sometimes the click will open a pop up, sometimes it won't. My current solution is to throw in Thread.Sleep() to get around the race condition, but I know this is frowned upon.
Has anyone else run into this? What is the best solution? Maybe polling the javascript to verify that the click event has loaded? | 2015/03/12 | [
"https://sqa.stackexchange.com/questions/12410",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/8937/"
] | Se2 experts suggest NOT USE IMPLICIT WAIT at all. [Especially don't mix them with explicit waits](https://stackoverflow.com/questions/15164742/combining-implicit-wait-and-explicit-wait-together-results-in-unexpected-wait-ti) (Jim Evans is Se2 core team member). So @kirbycope advice is against opinion of experts (and my own experience). But he correctly advises to search StackOverflow (where I found link above).
What works well for me, is to (explicitly) wait for some other element (by ID), which is available when page is fully loaded. I created my own simple framework, using PageObject design pattern, which uses implicit waits ONLY (wait time is site-wide constant), and my code is more stable.
[Implicit ws explicit wait explained](http://www.bizalgo.com/2012/01/14/timing-races-selenium-2-implicit-waits-explicit-waits/) | Explicit Waits are not ideal. Look into using an Implicit Wait. Official documentation, [here](http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp).
Here is a copy+paste should the URL change or something:
>
> An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
>
>
>
```
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
```
StackOverflow also has a few Q/As for "selenium wait for element". |
1,232,796 | The recent SIGGRAPH 2009 saw the announcement of [WebGL](http://www.khronos.org/news/press/releases/khronos-webgl-initiative-hardware-accelerated-3d-graphics-internet/) - a port of OpenGL ES to javascript.
The application that immediately came to my mind is web-based 3D first person shooters with AJAX as basis for communication.
I think this has the potential to answer the long awaited promise set forth by VRML a long long time ago...
Can you think of any other cool applications for this technology? | 2009/08/05 | [
"https://Stackoverflow.com/questions/1232796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9611/"
] | 3D Google Maps in the browser with real-time navigation using location awareness.
3D How To Find Us.
3D Bar Charts in online techy reviews.
Cross-platform 3D role playing games, because WebGL will be slower because of Javascript, and probably not suitable for low-latency, high-framerate 3D games. Well, not in the next couple of years.
Um ... that's about it. | Here's my WebGL based 3D map. I just got the blue marble tiles working today.
<http://github.com/fintler/lanyard>
Here's a live demo. Zooming with the mouse wheel works, but dragging to rotate is broken at the moment.
<http://github.bringhurst.org/lanyard-pre-demo-2> |
64,036,826 | I have a DevOps pipeline that is tasked with updating a file, and committing it back to a protected branch in Github. Checking out from the repo works just fine. I thought I had the right permission setup, but it doesn't work.
I have allowed azure-pipelines the permissions here:
[](https://i.stack.imgur.com/jhF3Wl.png)
I have specified the following to preserve the authentication from the original checkout here:
```
steps:
- checkout: self
persistCredentials: true
- task: Bash@3
inputs:
targetType: inline
script: |
git checkout integration
```
Then after the changes I make, I want to push back to the integration branch like this:
```
- task: Bash@3
inputs:
targetType: inline
script: |
cd ./Test/Test.UWP
git config --global user.email "test@test.com"
git status
cd ../..
git add .
git commit -m "Release $(versionNumber)"
git push origin integration
```
This returns the following output though and it doesn't push it back to the `integration` branch:
```
remote: error: GH006: Protected branch update failed for refs/heads/integration.
remote: error: At least 1 approving review is required by reviewers with write access.
To https://github.com/test/test-app
! [remote rejected] integration -> integration (protected branch hook declined)
error: failed to push some refs to 'https://github.com/test/test-app'
``` | 2020/09/23 | [
"https://Stackoverflow.com/questions/64036826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3386635/"
] | It turns out there are two CDN's that can provide this: snowpack/skypack, and jspm:
skypack:
```
import firebase from 'https://cdn.skypack.dev/@firebase/app'
import 'https://cdn.skypack.dev/@firebase/database'
```
jspm:
```
import { firebase } from 'https://jspm.dev/@firebase/app'
import 'https://jspm.dev/@firebase/database'
```
These both deal with "bare import" conversion to JS, and any code conversions required to be JS Modules.
Google does not appear to want to support a module form on their firebase CDN, an Issue to that effect was immediately closed, suggesting complex workflow solutions.
I'm really thankful to the two projects above, supporting simple es6 JS and zero workflow solutions.
Edit: snowpack's esinstall can turn most js files into modules. Here's a node script that brought in all my dependencies:
```
#!/usr/bin/env node --require esm
import { install } from 'esinstall'
import nodePolyfills from 'rollup-plugin-node-polyfills'
async function run() {
const foo = await install(
[
'mapbox-gl',
'three',
'three/examples/jsm/controls/OrbitControls.js',
'three/src/core/Object3D.js',
'chart.js',
'dat.gui',
'fflate',
'@turf/turf',
'stats.js',
'@firebase/app',
'@firebase/database',
],
{
rollup: {
plugins: [nodePolyfills()],
},
}
)
}
run()
``` | If you're using a bundler, then follow the instructions in the [documentation](https://firebase.google.com/docs/web/setup#using-module-bundlers):
>
> Install the firebase npm package and save it to your package.json file
> by running:
>
>
>
> ```
> npm install --save firebase
>
> ```
>
> To include only specific Firebase products (like Authentication and
> Cloud Firestore), import Firebase modules:
>
>
>
> ```
> // Firebase App (the core Firebase SDK) is always required and must be listed first
> import * as firebase from "firebase/app";
>
> // If you enabled Analytics in your project, add the Firebase SDK for Analytics
> import "firebase/analytics";
>
> // Add the Firebase products that you want to use
> import "firebase/auth";
> import "firebase/firestore";
>
> ```
>
>
For realtime database, you would add `import "firebase/database"`. |
54,530,257 | I'm adding a material **ChipGroup** dynamically to a parent linear layout which is set to VERTICAL orientation but the chip items seem to be added horizontally. Is there any way to make it lay out the chip items vertically?
**setLayoutDirection()** method of ChipGroup class method doesn't seem to take any parameter that supports VERTICAL orientation. | 2019/02/05 | [
"https://Stackoverflow.com/questions/54530257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8889580/"
] | you can set width = match\_parent in each Chip item
```
<com.google.android.material.chip.ChipGroup
android:id="@+id/chipGroup"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="24dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/questionTxt">
<com.google.android.material.chip.Chip
android:id="@+id/opt1"
style="@style/Widget.MaterialComponents.Chip.Choice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fire" />
<com.google.android.material.chip.Chip
android:id="@+id/opt2"
style="@style/Widget.MaterialComponents.Chip.Choice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Water" />
<com.google.android.material.chip.Chip
android:id="@+id/opt3"
style="@style/Widget.MaterialComponents.Chip.Choice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Psychic" />
<com.google.android.material.chip.Chip
android:id="@+id/opt4"
style="@style/Widget.MaterialComponents.Chip.Choice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Psychic" />
</com.google.android.material.chip.ChipGroup>
```
[final layout](https://i.stack.imgur.com/qsHsK.png) | ```
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.chip.ChipGroup
android:id="@+id/chipsGrp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/screen_pd"
android:padding="@dimen/screen_pd"
app:chipSpacing="@dimen/screen_pd"
app:singleSelection="true" />
</ScrollView>
```
Inclose your **ChipGroup within Scrollview** |
196,197 | I have a document library by which I want staff to only see items they create or modify. However, I want supervisors to see all items. Is this possible? | 2016/10/06 | [
"https://sharepoint.stackexchange.com/questions/196197",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/60769/"
] | * Create a page.
* Add your doc library as a web part.
* Then modify the web part's view.
* This will be exclusive to this page. Then set permissions on the page.
That satisfies the question in the title.
* You can use a workflow to trim item level permissions and can set to a sharepoint group of supervisors, Created By, and Modified By. | Create a default view that only show the documents created or modified by [me]. That way user will only see the documents created or modified by them. Then remove the Allitems.aspx view from library setting. However, when you type out the URL of the view, you can still see and supervise all the documents. |
72,848,624 | I have a list of words with the format `word1**word2`
I want to put the firt word at the end of the String like `word2 - word1`.
how can I split the first word without `**` and add a `-` before paste the word at the end?
I want to let the lines read from a file `words.txt` and create a new file `new-words.txt`
For example, I want `Bibi**Tina` to be converted in `Tina - Bibi`
Edit:
I tried a new code.
Now I get the right output on the Console but the new created file is empty.
```
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]) {
List<String> lines = new ArrayList<String>();
String line = null;
try {
File f1 = new File("C:\\Users\\PC\\Desktop\\new-words.txt");
FileOutputStream fop = new FileOutputStream(f1);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(new FileReader("C:\\\\Users\\\\PC\\\\Desktop\\words.txt"));
while ((line = br.readLine()) != null) {
if (!line.contains("\\*\\*\\yok")) {
String[] a = line.split("\\*\\*");
System.out.println(a[1] + " - " + a[0]);
}
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
``` | 2022/07/03 | [
"https://Stackoverflow.com/questions/72848624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15204441/"
] | Look at the [official java doc](https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html). There are 3 options of how to use the `write` method, and none of them take a string as an argument.
>
> * **void write(*byte[] b*)**: Writes b.length bytes from the specified byte array
> to this file output stream.
> * **void write(*byte[] b, int off, int len*)**: Writes
> len bytes from the specified byte array starting at offset off to this
> file output stream.
> * **void write(*int b*)**: Writes the specified byte to this
> file output stream.
>
>
>
You need to convert your string into a byte[] in order to write it to a file using a file output stream.
See [this StackOverflow post](https://stackoverflow.com/a/40972105/9661573) which talks about how to do that. | ```
star.split('**').reverse().join('-')
``` |
1,006,746 | I am trying to accomplish something in C# that I do easily in Java. But having some trouble.
I have an undefined number of arrays of objects of type T.
A implements an interface I.
I need an array of I at the end that is the sum of all values from all the arrays.
Assume no arrays will contain the same values.
This Java code works.
```
ArrayList<I> list = new ArrayList<I>();
for (Iterator<T[]> iterator = arrays.iterator(); iterator.hasNext();) {
T[] arrayOfA = iterator.next();
//Works like a charm
list.addAll(Arrays.asList(arrayOfA));
}
return list.toArray(new T[list.size()]);
```
However this C# code doesn't:
```
List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
//Problem with this
list.AddRange(new List<T>(arrayOfA));
//Also doesn't work
list.AddRange(new List<I>(arrayOfA));
}
return list.ToArray();
```
So it's obvious I need to somehow get the array of `T[]` into an `IEnumerable<I>` to add to the list but I'm not sure the best way to do this? Any suggestions?
EDIT: Developing in VS 2008 but needs to compile for .NET 2.0. | 2009/06/17 | [
"https://Stackoverflow.com/questions/1006746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79534/"
] | The issue here is that C# doesn't support [co-variance](http://weblogs.asp.net/astopford/archive/2006/12/28/c-generics-covariance.aspx) (at least not until C# 4.0, I think) in generics so implicit conversions of generic types won't work.
You could try this:
```
List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
list.AddRange(Array.ConvertAll<T, I>(arrayOfA, t => (I)t));
}
return list.ToArray();
```
---
For anyone that strumbles across this question and is using .NET 3.5, this is a slightly more compact way of doing the same thing, using Linq.
```
List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
list.AddRange(arrayOfA.Cast<I>());
}
return list.ToArray();
``` | [Arrays of reference objects are covariant in C#](http://blogs.msdn.com/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx) (the same is true for Java).
From the name, I guess that your T is a generic and not a real type, so you have to restrict it to a reference type in order to get the implicit conversion from T[] to I[].
Try this:
```
public static I[] MergeArrays<T,I>(IEnumerable<T[]> arrays)
where T:class,I
{
List<I> list = new List<I>();
foreach(T[] array in arrays){
list.AddRange(array);
}
return list.ToArray();
}
``` |
53,300,103 | I have a web page in which there are 'n' number of combo boxes in a column. In which I have to verify that all the drop down items in each and every combo boxes are clickable in iteration using robot framework. I have my script as follows:
```
*** Keywords ***
User should be able to select each and every role suggested in the combo boxes
@{combo_boxes}= Get WebElements css=div.col > div:nth-child(1) > div:nth-child(3) > div:nth-child(1) > combo-box:nth-child(1) > div:nth-child(1)
:FOR ${each} IN @{combo_boxes}
\ Click Element ${each}
\ Select drop down item
Select drop down item
@{drop_down_list}= Get WebElements css=div.col:nth-child(2) > div:nth-child(1) > div:nth-child(3) > div:nth-child(1) > combo-box:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div
:FOR ${each} IN @{drop_down_list}
\ Click Element ${each}
```
On executing the above script we are getting the following error:
```
WebDriverException: Message: unknown error: Element <div _ngcontent-c6="" id="divCombo" style="height: 100%; background-color: transparent;">...</div> is not clickable at point (1014, 358). Other element would receive the click: <span _ngcontent-c6="" class="flexColumnFill dropdown-optionName">...</span>
(Session info: chrome=70.0.3538.77)
(Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Windows NT 10.0.17134 x86_64)
```
[](https://i.stack.imgur.com/EsX0p.jpg) | 2018/11/14 | [
"https://Stackoverflow.com/questions/53300103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9669560/"
] | It should work as follows:
```
Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.InternalServerError)
.OrResult(r => r.StatusCode == HttpStatusCode.BadGateway)
.WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(5));
```
The `.OrResult(...)` does not need generic type arguments, because the `.Handle<HttpResponseMessage>(...)` clause has already bound the policy to handle results of type `HttpResponseMessage`. | Correct your Retry definition specifing type:
```
private RetryPolicy<HttpResponseMessage> Retry { get; }
``` |
11,471,624 | I created a conformation box from jquery. I want to submit the page and view PHP echo message when click the confirm button in the confirmation box. Can you help me with code that comes for the confirmation button?
My jQuery/javascript function is here:
```
$(document).ready(function(){
$('#click').click(function(){
//$(function() {
// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
$( "#dialog:ui-dialog" ).dialog( "destroy" );
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Ok": function() {
// I WANT THE CODE FOR HERE TO SUBMIT THE PAGE TO WIEW PHP ECHO MESSAGE
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
});
``` | 2012/07/13 | [
"https://Stackoverflow.com/questions/11471624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1434869/"
] | Do you have the HiddenHttpMethodFilter filter in your web.xml?
```
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
<http://static.springsource.org/spring/docs/current/spring-framework-reference/html/view.html#rest-method-conversion> | The error messages indicate that the browser is *actually* sending a GET request rather than a DELETE request.
What you need to do is:
* examine the source of the web page that the browser is on at the time, and
* using the browser's web debugger, see what the request URL and method actually are. |
579,414 | So, I was reading an article, and just saw this sentence here:
*I figured I'd sort out the train into the city instead of hopping in a cab.*
Is that a common usage of "sort out"? It seems like it would mean "search for" or something like that, but I've never seen it used in this way. I checked in [Macmillan](https://www.macmillandictionary.com/us/dictionary/american/sort-out_1#sort-out_1__7) and I think it may fit into definition 3 or 5, but it still sounds weird to me. | 2021/11/30 | [
"https://english.stackexchange.com/questions/579414",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/439499/"
] | **sort out** (v.)
>
> Arrange or organize something
>
>
> *They are anxious to sort out travelling arrangements*
>
>
> *I've sorted the travel - that's no problem.* [Lexico](https://www.lexico.com/definition/sort_out)
>
>
>
---
>
> He stood beside her as she **sorted out** the ticket, then they walked
> across the car park together, almost amused. [Ann Enright; *A Green
> Road*](https://www.google.com/books/edition/The_Green_Road_A_Novel/8AmdBAAAQBAJ?hl=en&gbpv=1&dq=%22sorted%20out%20the%20ticket%22&pg=PT183&printsec=frontcover)
>
>
>
>
> From the Job Centre, we went straight to the train station to **sort
> out** the train times. [Richard Cliff; *Franklyn*](https://www.google.com/books/edition/Franklyn/ohRDCwAAQBAJ?hl=en&gbpv=1&dq=%22sort%20out%20the%20train%22&pg=PT56&printsec=frontcover)
>
>
>
>
> I have **sorted out** the train tickets to get the cast up to Edinburgh
> on Monday. [Robert Bryndza; *The Not So Secret Email of Coco Pinchard*](https://www.google.com/books/edition/The_Not_So_Secret_Emails_of_Coco_Pinchar/3UA3DwAAQBAJ?hl=en&gbpv=1&dq=%22sorted%20out%20the%20train%22&pg=PT237&printsec=frontcover)
>
>
>
>
> Roger had **sorted out** the travel arrangements with S.E.L. but
> coordinating everything else was delegated to Ian. [Andy Gee; *Livin' the
> Dream*](https://www.google.com/books/edition/Livin_the_Dream/osxHEAAAQBAJ?hl=en&gbpv=1&dq=%22sorted%20out%20the%20travel%22&pg=PT223&printsec=frontcover)
>
>
>
>
> The Firm had **sorted out** the plane ticket for Mark and, here he
> was, bright and early, at Heathrow airport, waiting to fly British
> Airways to Frankfurt; from Frankfurt, a Lufthansa flight would take
> him to Tehran. [James Brandon; *Zahedan*](https://www.google.com/books/edition/Zahedan/qMe2KJeTp80C?hl=en&gbpv=1&dq=%22sorted%20out%20the%20plane%22&pg=PT52&printsec=frontcover)
>
>
> | From [Longman Dictionary](https://www.ldoceonline.com/dictionary/sort-out):
Sort out:
>
> 4. (especially British English) to succeed in making arrangements for something.
>
>
> |
8,051,569 | ```
USE NORTHWIND;
GO
SELECT SHIPCOUNTRY,[ORDERS_ID] =
CASE ORDERID
WHEN ORDERID = 10300
THEN 'I AM FROM 10300'
WHEN ORDERID = 10400
THEN 'I AM FROM 10400'
WHEN ORDERID = 10500
THEN 'I AM FROM 10500'
ELSE 'I AM OUT OF RANGE'
END
FROM ORDERS;
GO
```
>
> Error - Msg 102, Level 15, State 1, Line 3 Incorrect syntax near '='.
>
>
>
If you have northwind Database in your sql server,you can execute this query.
I don't understand where the issue is.Can anyone help me to resolve this issue? | 2011/11/08 | [
"https://Stackoverflow.com/questions/8051569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1035724/"
] | The `case` construct can have two different forms:
```
case n
when n then n
when n then n
end
```
and:
```
case
when n = n then n
when n = n then n
end
```
You are mixing them. Use:
```
SELECT SHIPCOUNTRY,[ORDERS_ID] =
CASE ORDERID
WHEN 10300 THEN 'I AM FROM 10300'
WHEN 10400 THEN 'I AM FROM 10400'
WHEN 10500 THEN 'I AM FROM 10500'
ELSE 'I AM OUT OF RANGE'
END
FROM ORDERS
``` | ```
USE NORTHWIND;
GO
SELECT SHIPCOUNTRY,
CASE ORDERID
WHEN 10300
THEN 'I AM FROM 10300'
WHEN 10400
THEN 'I AM FROM 10400'
WHEN 10500
THEN 'I AM FROM 10500'
ELSE 'I AM OUT OF RANGE'
END ORDERS_ID
FROM ORDERS;
GO
``` |
69,546 | I'm in the process of getting an apartment with my girlfriend and a friend. We plan on all sharing rent and utilities but there is a large gap in earnings between the three of us, mostly that I out-earn both combined. I want to do things as fairly as possible, so I'm unsure how to split the rent, and ensuing utilities.
Due to the area where I work, the apartment is more expensive than the others would be able to afford without me, and splitting things at the 33% mark would simply leave them next to no money outside of rent, or so I fear. How should I go about this?
Edit for requested information:
All of our incomes are known between each other.
Me and my girlfriend are sharing a single room. | 2016/08/15 | [
"https://money.stackexchange.com/questions/69546",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/49209/"
] | Myself and my partner do things a little differently to most. We split accommodation and utilities payments by net income proportion to ensure that we both have the same amount of spending money.
For example;
* if we both earn $40,000pa we both pay 50% of the bills
* if she earns $50,000pa and I earn $25,000 she pays ~66% of the bill
The really important bit is *net income*. We take off a whole bunch of payments, e.g;
* Pension contributions
* Student loan
* Employer subsidised healthcare
Our contributions go into a joint account and the rest is our money to spend. The upshot is that we both get to enjoy the same minimum quality of life because we both get the same amount to spend at the bar. | Does your apartment have several bedrooms that are all different in size? If yes, then everyone can pay by square footage. However, if you share the room with your girlfriend, it won’t work. Even if your live in a master bedroom with her, you friend will probably pay more than your girlfriend.
I heard there are websites that let each roommate bid the max they’re willing to pay for each room in the apartment. You can try one of these service.
Or you can simply divide the rent between three of you, but utilities will be covered only by you. |
442,026 | Why don't more mainstream statically typed languages support function/method overloading by return type? I can't think of any that do. It seems no less useful or reasonable than supporting overload by parameter type. How come it's so much less popular? | 2009/01/14 | [
"https://Stackoverflow.com/questions/442026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23903/"
] | To steal a C++ specific [answer from another very similar question](https://stackoverflow.com/questions/249296/return-type-polymorphism-in-c-like-languages#249309) (dupe?):
---
Function return types don't come into play in overload resolution simply because Stroustrup (I assume with input from other C++ architects) wanted overload resolution to be 'context independent'. See 7.4.1 - "Overloading and Return Type" from the "C++ Programming Language, Third Edition".
>
> The reason is to keep resolution for an individual operator or function call context-independent.
>
>
>
They wanted it to be based only on how the overload was called - not how the result was used (if it was used at all). Indeed, many functions are called without using the result or the result would be used as part of a larger expression. One factor that I'm sure came into play when they decided this was that if the return type was part of the resolution there would be many calls to overloaded functions that would need to be resolved with complex rules or would have to have the compiler throw an error that the call was ambiguous.
And, Lord knows, C++ overload resolution is complex enough as it stands... | This one is slightly different for C++; I don't know if it would be considered overloading by return type directly. It is more of a template specialization that acts in the manner of.
**util.h**
```
#ifndef UTIL_H
#define UTIL_H
#include <string>
#include <sstream>
#include <algorithm>
class util {
public:
static int convertToInt( const std::string& str );
static unsigned convertToUnsigned( const std::string& str );
static float convertToFloat( const std::string& str );
static double convertToDouble( const std::string& str );
private:
util();
util( const util& c );
util& operator=( const util& c );
template<typename T>
static bool stringToValue( const std::string& str, T* pVal, unsigned numValues );
template<typename T>
static T getValue( const std::string& str, std::size_t& remainder );
};
#include "util.inl"
#endif UTIL_H
```
**util.inl**
```
template<typename T>
static bool util::stringToValue( const std::string& str, T* pValue, unsigned numValues ) {
int numCommas = std::count(str.begin(), str.end(), ',');
if (numCommas != numValues - 1) {
return false;
}
std::size_t remainder;
pValue[0] = getValue<T>(str, remainder);
if (numValues == 1) {
if (str.size() != remainder) {
return false;
}
}
else {
std::size_t offset = remainder;
if (str.at(offset) != ',') {
return false;
}
unsigned lastIdx = numValues - 1;
for (unsigned u = 1; u < numValues; ++u) {
pValue[u] = getValue<T>(str.substr(++offset), remainder);
offset += remainder;
if ((u < lastIdx && str.at(offset) != ',') ||
(u == lastIdx && offset != str.size()))
{
return false;
}
}
}
return true;
}
```
**util.cpp**
```
#include "util.h"
template<>
int util::getValue( const std::string& str, std::size_t& remainder ) {
return std::stoi( str, &remainder );
}
template<>
unsigned util::getValue( const std::string& str, std::size_t& remainder ) {
return std::stoul( str, &remainder );
}
template<>
float util::getValue( const std::string& str, std::size_t& remainder ) {
return std::stof( str, &remainder );
}
template<>
double util::getValue( const std::string& str, std::size_t& remainder ) {
return std::stod( str, &remainder );
}
int util::convertToInt( const std::string& str ) {
int i = 0;
if ( !stringToValue( str, &i, 1 ) ) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " Bad conversion of [" << str << "] to int";
throw strStream.str();
}
return i;
}
unsigned util::convertToUnsigned( const std::string& str ) {
unsigned u = 0;
if ( !stringToValue( str, &u, 1 ) ) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " Bad conversion of [" << str << "] to unsigned";
throw strStream.str();
}
return u;
}
float util::convertToFloat(const std::string& str) {
float f = 0;
if (!stringToValue(str, &f, 1)) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " Bad conversion of [" << str << "] to float";
throw strStream.str();
}
return f;
}
double util::convertToDouble(const std::string& str) {
float d = 0;
if (!stringToValue(str, &d, 1)) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " Bad conversion of [" << str << "] to double";
throw strStream.str();
}
return d;
}
```
This example is not exactly using function overload resolution by return type, however this c++ non object class is using template specialization to simulate function overload resolution by return type with a private static method.
Each of the `convertToType` functions are calling the function template `stringToValue()` and if you look at the implementation details or algorithm of this function template it is calling `getValue<T>( param, param )` and it is returning back a type `T` and storing it into a `T*` that is passed into the `stringToValue()` function template as one of its parameters.
Other than something like this; C++ does not really have a mechanism to have function overloading resolution by return type. There may be other constructs or mechanisms that I'm not aware of that could simulate resolution by return type. |
24,326,291 | I have the code below in a file called `code.py`. I am using `IDLE` to edit the file. When I click `Run>Run Module` I get the error:
>
> "IDLE's subprocess didn't make connection. Either IDLE can't start a
> subprocess of personal firewall software is blocking the connection."
>
>
>
I am using Windows 7 Ultimate 64bit, but I have the 32bit version of Python 2.7 installed.
I have looked for a solution on this site as well as others but all of them seem to recommend deleting something called `tkinter.py` (I have no idea what this is) or to turn off my firewalls (I have none enabled aside from `Microsoft Security Essentials` which isn't a firewall.)
```
#Globals
#-------------------
x_pad = 476
y_pad = 444
import ImageGrab
import os
import time
import win32api, win32con
def screenGrab():
box = (x_pad+1,y_pad+1,x_pad+641,y_pad+480)
im = ImageGrab.grab(box)
im.save(os.getcwd() + '\\full_snap__' + str(int(time.time())) +
'.png', 'PNG')
def main():
pass
if __name__ == '__main__':
main()
def leftClick():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(.1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
print 'Click.' #completely optional. But nice for debugging purposes.
def leftDown():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(.1)
print 'left Down'
def leftUp():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
time.sleep(.1)
print 'left release'
def mousePos(cord):
win32api.SetCursorPos((x_pad + cord[0], y_pad + cord[1])
def get_cords():
x,y = win32api.GetCursorPos()
x = x - x_pad
y = y - y_pad
print x,y
``` | 2014/06/20 | [
"https://Stackoverflow.com/questions/24326291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3759884/"
] | Another fix!!! Hopefully this will help someone.
I had the same problem and noticed something quite interesting. I had accidentally named a file (inside the desktop folder I was working in) "tkinter" (it will cause the same problem if you rename a file by any reserved keyword, I assume). Everytime I ran or attempted to run this file, it created a pycache folder, and the error you mention above came up. Deleting the erroneously named python file solved the problem.
So - look for ANY files (in the folder you are working with or indeed the root folder) that are named after any reserved words. Delete them. Hopefully it'll work! | I also had the following problem. My file was named code.py, and was working fine untill I installed Canopy, and numpy.
I tried reinstalling python, but what solved the problem for me was simply renaming the file. I called my file myCode.py, everything started working fine. Strange problem... |
37,183,254 | I'm having some troubles using AWS C++ SDK, due to a serious lack of documentation. However I managed to compile and install it on my computer.
I'm now trying hard to have a program working and resolved quite a lot of problems, but a (hopefully) last one remains that I cannot defeat alone...
Here is the code :
```
#include <aws/s3/model/GetObjectRequest.h>
int main()
{
Aws::S3::Model::GetObjectRequest getObjectRequest;
}
```
I tried to have the simplest code for my example. That code doesn't compile, I've got the following error :
```
CMakeFiles/example.dir/example.cpp.o:(.rodata._ZTIN3Aws2S39S3RequestE[_ZTIN3Aws2S39S3RequestE]+0x10): undefined reference to `typeinfo for Aws::AmazonSerializableWebServiceRequest'
```
I don't get what the problem is. I tried checking in the source code of the library, and no pure virtual function remains in the GetObjectRequest class. I think I linked correctly the libraries. Here is my CMakeLists.txt :
```
project( TEST_AWS )
cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
add_definitions ( -Wall -Wextra )
set(LIBAWSSDK_INCLUDE_DIR /usr/local/include/ CACHE STRING "aws SDK include directories")
set(LIBAWSSDK_CORE_LIB "-l:/usr/local/lib/libaws-cpp-sdk-core.so" CACHE STRING "aws SDK core link lib")
set(LIBAWSSDK_S3_LIB "-l:/usr/local/lib/libaws-cpp-sdk-s3.so" CACHE STRING "aws SDK S3 link lib")
set(target_external_libraries
${LIBAWSSDK_CORE_LIB}
${LIBAWSSDK_S3_LIB}
)
include_directories(
${LIBAWSSDK_INCLUDE_DIR}
)
add_executable( example example.cpp )
target_link_libraries( example ${target_external_libraries} )
target_compile_features(example PRIVATE cxx_lambdas)
```
I know the way I linked the library with cmake is a little bit dirty, but for the moment I just want the code to compile... | 2016/05/12 | [
"https://Stackoverflow.com/questions/37183254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4114072/"
] | ### Answering last comment: Only one line... Pure [bash](/questions/tagged/bash "show questions tagged 'bash'"):
```
read string <InputFile
echo -n "${string%$'\r'}"
```
Explanation: `read` will read by line, so drop naturally trailing *newline*. Then `${variable%$'\r'}` will remove **1** trailing *CR*.
Have a look at `help read` for limitation and options about doing this way:
```
printf ' foo\\x\r\t bar\r\n' > InputFile
IFS= read -r string <InputFile
echo -n "${string%$'\r'}" | od -A n -t a -t c
sp f o o \ x cr ht sp b a r
f o o \ x \r \t b a r
```
(I use `-t c` **and** `-t a` because the second is more *readable* but don't show spaces explicitely.)
This may work under regular [shell](/questions/tagged/shell "show questions tagged 'shell'") too:
```
CR=`printf \\\r`
read string <InputFile
echo -n "${string%$CR}"
```
### 1st answer: *End of line* and *line separator*
To whipe a *CR* at end of line, use this:
```
sed -e 's/\r$//'
```
Under Unix's `sed`, lines are *separated* by `\n`, so while you don't use `N` sed command, you may never found `\n` in **one line**.
But if you want to *merge* all your lines:
```
sed -ne ':;N;$!b;s/\r\n//g;p'
```
This will drop all `CRLF` except at very end of file. (you could drop with bash `${var%$'\r\n'}` or `head -c -2` )
```
sed -ne ':;N;$!b;s/\r\n//g;p' | head -c -2
``` | With GNU awk for multi-char RS and Binary Mode:
```
$ od -tc file
0000000 f o o b a r \r \n
0000011
$ awk -v BINMODE=3 -v RS='\r\n' -v ORS= '1' file | od -tc
0000000 f o o b a r
0000007
```
Here's why you need to set `BINMODE=3`:
```
$ awk '1' file | od -tc
0000000 f o o b a r \n
0000010
$ awk -v BINMODE=3 '1' file | od -tc
0000000 f o o b a r \r \n
0000011
```
Without it on some platforms (e.g. cygqwin) gawk never even sees the `\r`, underlying C primitives remove it. |
24,582,384 | I have 2 go files:
`/Users/username/go/src/Test/src/main/Test.go`
```
package main
import "fmt"
func main() {
fmt.Printf(SomeVar)
}
```
and file `/Users/username/go/src/Test/src/main/someFile.go`
```
package main
const SomeVar = "someFile"
```
However I am constantly getting compiler error:
>
> /Users/username/go/src/Test/src/main/Test.go:6: undefined: SomeVar
>
>
>
Can someone explain to me why is `SomeVar` labeled as undefined? | 2014/07/05 | [
"https://Stackoverflow.com/questions/24582384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3806851/"
] | Try
```
go run Test.go someFile.go
``` | You code is correct:
* `someFile.go` and `Test.go` belong to the same package (`main`)
* `SomeVar` is a `const` declared at top level, so it has a package block scope, namely the `main` package block scope
* as a consequence, `SomeVar` is visible and can be accessed in both files
(if you need to review scoping in Go, please refer to the [Language Specification - Declarations and Scope](https://golang.org/ref/spec#Declarations_and_scope)).
Why do you get an `undefined` error then?
You probably launched `go build Test.go` or `go run Test.go`, both producing the following output, if launched from `/Users/username/go/src/Test/src/main`:
```
# command-line-arguments
./Test.go:6: undefined: SomeVar
```
You can find the reason here: [Command go](https://golang.org/cmd/go/)
If you launch `go build` or `go run` with a list of `.go` files, it treats them as a list of source files specifying a single package, i.e., it thinks there are no other pieces of code in the `main` package, hence the error.
The solution is including all the required `.go` files:
```
go build Test.go someFile.go
go run Test.go someFile.go
```
`go build` will also work with no arguments, building all the files it finds in the package as a result:
```
go build
```
**Note 1**: the above commands refer to the local package and, as such, must be launched from the `/Users/username/go/src/Test/src/main` directory
**Note 2**: though other answers already proposed valid solutions, I decided to add a few more details here to help the community, since this is a common question when you start working with Go :) |
2,341,976 | Supose I have a sequence $\{a\_n\}$ of positive real numbers such that $\lim\limits\_{n \to \infty}a\_n^{1/n} = 1$. Is it true that $\lim\limits\_{n \to \infty} \frac{a\_{n + 1}}{a\_n} = 1$ or depends of the sequence that a choose? | 2017/06/30 | [
"https://math.stackexchange.com/questions/2341976",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/364941/"
] | Here a simple counterexample: let $a\_n=1$ if $n$ is even, and $a\_n=2$ if $n$ is odd. Clearly $\lim\limits\_{n \mapsto \infty}a\_n^{\frac{1}{n}} = 1,$ while $a\_{n+1}/a\_n$ oscillates between $2$ and $1/2,$ i.e., does not converge. | Let $r\_n = \frac{a\_{n + 1}}{a\_n}$ and $s\_n = a\_n^{1/n}$. Then the rule is
$$ \liminf r\_n \le \liminf s\_n \le \limsup s\_n \le \limsup r\_n. $$
So if both limits exist then they are equal but $\lim s\_n$ might exist where $\lim r\_n$ might not. |
3,953,854 | I've recently become heavily involved in a few projects that are going to work as company-wide intranet systems. They will basically be intranet websites, replacing older legacy systems that are desktop-based. I'd like to research the best ways to set-up these web site, or web application projects.
Most notably, I'm looking for:
1. Different architectures and the pros and cons of each. i.e. (Tiered architecuture, etc.)
2. Enterprise website programming practices, performance, caching, etc.
3. Optimized class architectures in .NET websites, web apps
I basically want some references and resources all pertaining to some of the best practices, ways in which I can optimize performance, layout a project to be easily maintainable and run at optimal levels of performance.
I did end up reading some of [Microsoft Application Architecture Guide](http://www.microsoft.com/downloads/en/details.aspx?FamilyID=ce40e4e1-9838-4c89-a197-a373b2a60df2&displaylang=en), 2nd Edition, which is free online, Something along those lines would be helpful, although a little less cookie cutter. | 2010/10/17 | [
"https://Stackoverflow.com/questions/3953854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38629/"
] | wget (GNU command line tool) will do this for you.
The documentation for what you want to do is here:
<http://www.gnu.org/software/wget/manual/html_node/Recursive-Retrieval-Options.html> | Try Wget. it's a simple command line utility able to do that. |
943,000 | **This question has been retitled/retagged so that others may more easily find the solution to this problem.**
---
I am in the process of trying to migrate a project from the Django development server to a Apache/mod-wsgi environment. If you had asked me yesterday I would have said the transition was going very smoothly. My site is up, accessible, fast, etc. However, a portion of the site relies on file uploads and with this I am experiencing the strangest and most maddening issue. The particular page in question uses [swfupload](http://swfupload.org/) to POST a file and associated metadata to a url which catches the file and initiates some server-side processing. This works perfectly on the development server, but whenever I POST to this url on Apache the Django request object comes up empty--**no GET, POST, or FILES data**.
I have eliminated client-side issues by snooping with Wireshark. As far as I can discern the root cause stems from some sort of Apache configuration issue, possibly related to the temporary file directory I am trying to access. I am a relative newcomer to Apache configuration and have been banging my head against this for hours.
My Apache config:
```
<VirtualHost *:80>
ServerAdmin user@sitename.com
ServerName sitename.com
ServerAlias www.sitename.com
LogLevel warn
WSGIDaemonProcess sitename processes=2 maximum-requests=500 threads=1
WSGIProcessGroup sitename
WSGIScriptAlias / /home/user/src/sitename/apache/django.wsgi
Alias /static /home/user/src/sitename/static
Alias /media /usr/share/python-support/python-django/django/contrib/admin/media
</VirtualHost>
```
My intuition is that this may have something to do with the permissions of the file upload directory I have specified in my Django settings.py (`'/home/sk/src/sitename/uploads/'`), however my Apache error log doesn't suggest anything of the sort, even with the log level bumped up to debug.
Suggestions on how I should go about debugging this? | 2009/06/03 | [
"https://Stackoverflow.com/questions/943000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24608/"
] | Another possibility is a bug in "old" releases of mod\_wsgi (I got crazy to find, and fix, it). More info in this [bug report](http://code.google.com/p/modwsgi/issues/detail?id=121). I fixed it (for curl uploads) thanks to the [following hint](http://the-stickman.com/web-development/php-and-curl-disabling-100-continue-header/) (that works on the CLI too, using the -H switch). | Normally apache runs as a user "www-data"; and you could have problems if it doesn't have read/write access. However, your setup doesn't seem to use apache to access the '/home/sk/src/sitename/uploads'; my understanding from this config file is unless it hit /static or /media, apache will hand it off WGSI, so it might be good to check out those permissions and logs, rather than the apache ones. |
5,896,576 | I have done its configurations using configuration wizard but I couldn't understand where it is logging messages. I even see app.config file but couldn't find any logging source.
Please guide me where it does logs and how I can check that log.
Here is my config file:
```
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add fileName="C:\Users\Administrator\Desktop\EAMS\trace.log"
header="----------------------------------------" footer="----------------------------------------"
formatter="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
traceOutputOptions="LogicalOperationStack" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="FlatFile TraceListener" />
<add source="Enterprise Library Logging" formatter="Text Formatter"
log="Application" machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
traceOutputOptions="LogicalOperationStack" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Formatted EventLog TraceListener" />
</listeners>
<formatters>
<add template="Timestamp: {timestamp}
Message: {message}
Category: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Title:{title}
Machine: {machine}
Application Domain: {appDomain}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
Extended Properties: {dictionary({key} - {value}
)}"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=YAWARLAPTOP;Initial Catalog=EAMS;Integrated Security=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
``` | 2011/05/05 | [
"https://Stackoverflow.com/questions/5896576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/576510/"
] | You need to configure one or more [Trace Listeners](http://msdn.microsoft.com/en-gb/library/ff664768%28PandP.50%29.aspx). Also see [Configuration Overview](http://msdn.microsoft.com/en-gb/library/ff664760%28PandP.50%29.aspx)
**Edit 1**
Thank you for an example of you config file. You are logging your messages into Application Event Log. Please open this [Event Log](http://en.wikipedia.org/wiki/Event_Viewer) as you normally do and you'll be able to see your messages in there.
**Edit 2**
In your original question you asked where the messages are logged. This answer has been provided to you. When you write a question, it's better to specify upfront, what are you trying to achieve. To log into a flat file, after you configured a flat file listener you need to add reference to this listener to your sources. See how it's done with the Event Log trace listener in your example and follow the same pattern. | This is correct.
Authentication has been added to the email tracelistener in v5.0.
If you must use v4.1, there's a version of the email tracelistener with authentication on [EntLibContrib](http://entlibcontrib.codeplex.com/). |
37,977,223 | I want to remove a matching substring from a string in python .
Here is what I have tried so far:
```
abc= "20160622125255102D87Z2"
if "Z2" in abc:
abc.rstrip("Z2")
print(abc)
```
But this doesn't work. Kindly help | 2016/06/22 | [
"https://Stackoverflow.com/questions/37977223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6500607/"
] | `rstrip()` returns a new string; it does not modify the existing string.
You have to reassign abc to contain the new string:
```
abc = abc.rstrip("Z2")
``` | It's because rstrip returns a new string. Try
```
abc = abc.rstrip("Z2")
```
Also, if the substring you want to remove could appear anywhere in the string (as opposed to being at the end always), you might instead want to use
`abc.replace("Z2","")` |
13,801 | What's the thing with $\sqrt{-1} = i$? Do they really teach this in the US? It makes very little sense, because $-i$ is also a square root of $-1$, and the choice of which root to label as $i$ is arbitrary. So saying $\sqrt{-1} = i$ is plainly false!
So why do people say $\sqrt{-1} = i$? Is this how it's taught in the US? | 2010/12/10 | [
"https://math.stackexchange.com/questions/13801",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/3793/"
] | I believe this is a common misconception. Here in Sweden we (or at least I) was taught that $i^2 = -1$, *not* that $\sqrt{-1} = i$. They are two fundamentally different statements. Of course most of the time one chooses $\sqrt{-1} = i$ as the principal branch of the square root. | Alex it is just a notion. We use the value of $i = \sqrt{-1}$ so that we can work more freely. For example consider the Quadratic Equation $$x^{2}+x+1=0$$ The discriminant for this is $D=b^{2}-4ac=-3$. So the roots have the value $$x = \frac{-1 \pm{\sqrt{3}i}}{2}$$ which looks better when written with an $i$ notation. That's all.
I don't know how this is taught in the US but to me, i encountered this when i was at high school, learning how to solve for Quadratic Equations when the *Discriminant* is less than $0$.
Next, note that $\mathbb{C}$ doesn't have the same ordering as $\mathbb{R}$. That is for any 2 real numbers $a,b$ we have either:
* $a>b$
* $a< b$
* $a=b$
But for complex number's this is not true. Since if you take $i$ and $0$, we must have either $i > 0$ or $i < 0$, but this isn't true. |
4,019,849 | Let's say I have these two functions:
```
function fnChanger(fn) {
fn = function() { sys.print('Changed!'); }
}
function foo() {
sys.print('Unchanged');
}
```
Now, if I call `foo()`, I see `Unchanged`, as expected. However, if I call `fnChanger` first, I still see `Unchanged`:
```
fnChanger(foo);
foo(); //Unchanged
```
Now, I assume this is because `foo` is not being passed to `fnChanger` by reference, but I may be wrong.
Why does `fnChanger` not change `foo` to print `Changed!`?
Furthermore, how can I get `fnChanger` to change `foo` without too much messy syntax?
PS: I'm using node.js to test all this stuff, so that's where the `sys.print` comes from. | 2010/10/26 | [
"https://Stackoverflow.com/questions/4019849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130442/"
] | As @CMS pointed out you cannot assign it within the function due to the scope. However you could reassign it like this:
```
var fnChanger = function() {
return function() {
alert('changed!');
}
}
var foo = function() {
alert('Unchanged');
}
foo = fnChanger();
foo();
```
[example](http://jsfiddle.net/subhaze/JmNLE/) | **In Javascript, functions are first class objects that can be treated just as another variable**. But for the function to return its result, it has to be first invoked.
When you are invoking the fnChanger(foo), the fn variable actually gets overridden with foo().
But you are not getting the result because that function was never invoked. Try returning it and invoking as given below and you will the required answer.
```js
function fnChanger(fn) {
fn = function() {
console.log('Changed!');
}
return fn;
}
function foo() {
console.log('Unchanged');
}
fnChanger(foo)();
foo();
``` |
56,833 | We recently had a c.s. theory / networks paper accepted at a special issue after addressing a major revision. After we got the letter of acceptance, author proofs, signed the copyright release, etc., we got a letter saying
>
> the paper was inadvertently marked as "Accepted" which was not the decision of the guest editors of the special issue. Apologies for the confusion.
>
>
>
They then ask us to strengthen our revisions to the same reports we responded to before:
>
> Please understand that although we believe that you made a considerable effort in revising your manuscript, we think that reviewers' comments 5, 8, 9, and 11 require further attention.
>
>
>
But they misinterpret what the referees want in those points. One example is that the referee originally asks
>
> Why not use testbed experiment to evaluate it?
>
>
>
(we have given reasons in our paper why testbed experiments are not necessary) but the editor writes
>
> the reviewers ask to perform testbed experiments
>
>
>
They close with
>
> If the paper is successfully revised and the reviews are positive, then it could be accepted and appear in a later addendum to the special issue.
>
>
>
**In short, the editors claim to have accidentally pressed "accept" and then forgotten about our paper for 2 months while it went through the editorial and publishing process, and that we have not met the reviewer's demands, which the editor has clearly misinterpreted.**
How do we proceed in a way that ensures our fair treatment and, ultimately, the publication of our paper at this journal? | 2015/10/24 | [
"https://academia.stackexchange.com/questions/56833",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/43156/"
] | Unfortunately, these things do happen sometimes, and there's not much you can do about it. If the journal does not want to publish your paper yet, there's not much you can do to get it to publish your paper without carrying out the revisions that they request. At least they caught their mistake before it was actually published, [unlike in this case at PLOS ONE](http://retractionwatch.com/2015/08/26/a-mess-plos-mistakenly-publishes-rejected-adhd-herbicide-paper-retracts-it/), so you don't have a retraction on your record.
I would suggest you treat this just as any other request for revision: improve the paper and hope that the next revision is sufficient for publication. | No one here can tell you what will insure the publication of your article beyond satisfactorily making the changes that the reviewer wants.
On the other hand, I have had at least one successful case writing a strongly worded, polite, and well-reasoned rebuttal letter to the editor explaining why the reviewer is wrong. You might be able to convince the editor that the article is fine as is so that it can be published without additional changes. This route probably has lower odds of success since you have to convince the editor that they were wrong and that their hand-picked reviewer is wrong, but if what the reviewer wants is impossible or nonsensical, you might have to try this approach.
You might try writing the letter and not sending it. Get a couple of close colleagues who are not co-authors to read the paper, the reviewer report, and the letter, and tell you how they feel. You don't have to send it. If you can't convince a friend, maybe you shouldn't try to convince the editor.
Edited to add: This is a strategy that you should only undertake with the help and complete assent of your current co-authors. When I did it, my PhD supervisor and I were the only authors. He agreed, strongly, that the editor was wrong to agree with the reviewer, and we worked on a nice rebuttal letter that was convincing. We sent it under our joint names, but it would have appeared to have come from me more since I was first author and we listed my name first in the letter. |
39,901,949 | I´m lost, so
```
public class Filter {
public static void main(String[] args) {
// read in two command-line arguments
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
// repeat as long as there's more input to read in
while (!StdIn.isEmpty()) {
// read in the next integer
int t = StdIn.readInt();
if (????) {
StdOut.print(t + " ");
}
}
StdOut.println();
} }
```
This program is supposed to read in two integers and use them to filter out the StdIn. stream, for example if the arguments are 2,3 and StdIn 5 7 8 9 10 4 6, then it should print out 8 9 10, (skip the first 2 and print the next 3) | 2016/10/06 | [
"https://Stackoverflow.com/questions/39901949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5388980/"
] | ```
public class Filter {
public static void main(String[] args) {
// read in two command-line arguments
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
// repeat as long as there's more input to read in
while (!StdIn.isEmpty()) {
// read in the next integer
int t = StdIn.readInt();
if(a-- > 0)
continue;
if (b-- > 0) {
StdOut.print(t + " ");
}
}
StdOut.println();
} }
``` | `?????` needs to be `--a <= 0 && --b >= 0`.
Note that I'm exploiting the fact that `&&` is short-circuited. i.e. `--b` will not be evaluated until `--a` is 0 or less.
Eventually, of course, the `int` will underflow for a very long input steam session, but this is still a very cool solution. |
8,392,905 | I have an audio stream I'd like to include on a Facebook Page, above or at the top of, the wall. Apparently BBC did this (though I can't find the link). Any suggestions on where I should start? I have the html hosted as a Heroku app right now, and can get it to display as a separate link on the Page. But how do I move it from it's own page and onto the Wall?
Thanks much from a FB Developer newbie,
Peter | 2011/12/05 | [
"https://Stackoverflow.com/questions/8392905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/558386/"
] | value is a custom property for a td,
so you can access it using this method
```
function typeThis(){
document.getElementById('box_1').value = this.getAttribute("value");
}
```
**Side Note:**
this is how your table should look like
```
<table id = "typewriter">
<tr>
<td value="k" onclick="typeThis();">k</td>
<td value="c" onclick="typeThis();">c</td>
<td value="y" onclick="typeThis();">y</td>
<td value="s" onclick="typeThis();">s</td>
<td value="p" onclick="typeThis();">p</td>
</tr>
</table>
<input type="text" id="box_1">
```
**Example 2:**
```
function typeThis(letter){
document.getElementById('box_1').value = letter;
}
<table id = "typewriter">
<tr>
<td value="k" onclick="typeThis('k');">k</td>
<td value="c" onclick="typeThis('c');">c</td>
<td value="y" onclick="typeThis('y');">y</td>
<td value="s" onclick="typeThis('s');">s</td>
<td value="p" onclick="typeThis('p');">p</td>
</tr>
</table>
``` | How about
```
var box = document.getElementById("box_1");
var tds = document.getElementsByTagName("td");
for (var i = 0; i < tds.length; i++) {
var valToAdd = tds[i].textContent ? tds[i].textContent :
(tds[i].innerText ? tds[i].innerText : tds[i].innerHTML);
box.value = box.value + valToAdd;
}
```
to avoid using innerHTML it checks for the newer textContent and uses it if present. If not, it falls back to innerText and, as a last resort, innerHTML.
Also, if you want to add custom attributes to your td tags, you may want to opt for the more standard data-value="k" format. And check your code for a closing table tag |
48,339,862 | I have a huge form with around 30 parameters and I don't think it's a good idea to do what I usually do.
The form will be serialized and pass all the parameters via ajax post to spring controller.
I usually do like this:
```
@RequestMapping(value = "/save-state", method = RequestMethod.POST)
public @ResponseBody
void deleteEnvironment(@RequestParam("environmentName") String environmentName, @RequestParam("imageTag") String imageTag) {
//code
}
```
but if I have 30 parameters I will have a huge parameter list in the function.
What is the usual and correct way to avoid this?
**EDIT: What if I pass the HttpServlet request only?? The request will have all the parameters and I can simple call request.getParameters("").** | 2018/01/19 | [
"https://Stackoverflow.com/questions/48339862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can do something like this:
```
@RequestMapping(value = "/save-state", method = RequestMethod.POST)
public void deleteEnvironment(@RequestBody MyData data) {
//code
}
```
Create a class containing all your form parameters and receive that on your method. | Correct way is to serialize all parameters as Json and call back end api with one parameter.
On back-end side get that json and parse as objects.
Example:
```
` @RequestMapping(method = POST, path = "/task")
public Task postTasks(@RequestBody String json,
@RequestParam(value = "sessionId", defaultValue = "-1") Long sessionId)
throws IOException, AuthorizationException {
Task task = objectMapper.readValue(json, Task.class);
`
``` |
62,091,622 | We use a shared Outlook email box and we need to save some of the attachments from that email.
I need the macro to:
* Allow user to select multiple emails and save all the attachments in the selection
* Allow the user to select what folder to save the attachments in (it will be different every time)
* Add the `ReceivedTime` to the file name as we get some email attachments with the same name but they are always received on different days
* Not alter the original email (don't delete the attachment or add a note to the email)
I have combined different lines from macros I found.
On both lines with "\*\*\*" I get
>
> "Runtime error 91: "object variable or With block variable not set"
>
>
>
I remove the `dateFormat` and `SaveAs` and still get the runtime error on the `SaveAs` line.
```vb
Sub saveAttachment()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem
Dim objAtt As Outlook.Attachment
Dim objSel As Outlook.Selection
Dim lngCount As Long
Dim sFolder As String
Dim dateFormat As String
dateFormat = Format(objMsg.ReceivedTime, "yyyy-mm-dd") '***
Dim xlObj As Excel.Application
Set xlObj = New Excel.Application
' Open the select folder prompt
With xlObj.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then ' if OK is pressed
sFolder = .SelectedItems(1)
ElseIf .Show = 0 Then
MsgBox "Failed to select folder to save attachements to"
Exit Sub
End If
End With
xlObj.Quit
Set xlObj = Nothing
Set objOL = CreateObject("Outlook.Application")
Set objSelection = objOL.ActiveExplorer.Selection
For Each objMsg In objSelection
Set objAttachments = objMsg.Attachments
lngCount = objAttachments.Count
If lngCount > 0 Then
objAtt.SaveAsFile sFolder & "\" & objAtt.FileName & dateFormat '***
Else
MsgBox "No attachements selected"
End If
Next
End Sub
```
We are utilizing Office365. | 2020/05/29 | [
"https://Stackoverflow.com/questions/62091622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13643329/"
] | ```
int initQueue_ch(Queue_ch* q)
{
q = (Queue_ch*)malloc(sizeof(Queue_ch));
q->count = 0;
q->front = NULL;
q->rear = NULL;
return 0;
}
```
This function is unusable. It ignores the value of `q` passed into it and does not return a pointer to the queue it initialized. C is strictly pass by value.
```
int main()
{
Queue_ch* queue;
initQueue_ch(queue);
enqueue_ch(queue, "hello");
return 0;
}
```
This code never gives `queue` any value and passes a garbage value to `initQueue_ch` (which it ignores) and then a garbage value to `enqueue_ch`. | If you are initializing using malloc() then return the pointer() instead of passing pointer to function like following.
```
struct wordlist* wordlist_create(void)
{
struct wordlist* wordListPtr = (struct wordlist*) malloc(sizeof(struct wordlist));
wordListPtr->count = 0;
wordListPtr->root = getTrieNode();
return wordListPtr;
}
``` |
13,506,460 | Capture the domain till the ending characters `$, \?, /, :`. I need a regex that captures `example.com` in all of these.
```
example.com:3000
example.com?pass=gas
example.com/
example.com
``` | 2012/11/22 | [
"https://Stackoverflow.com/questions/13506460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340688/"
] | If you actually have valid URLs, this will work:
```
var urls = [
'http://example.com:3000',
'http://example.com?pass=gas',
'http://example.com/',
'http://example.com'
];
for (x in urls) {
var a = document.createElement('a');
a.href = urls[x];
console.log(a.hostname);
}
//=> example.com
//=> example.com
//=> example.com
//=> example.com
```
Note, using regex for this kind of thing is silly when the language you're using has other built-in methods.
Other properties available on `A` elements.
```
var a = document.createElement('a');
a.href = "http://example.com:3000/path/to/something?query=string#fragment"
a.protocol //=> http:
a.hostname //=> example.com
a.port //=> 3000
a.pathname //=> /path/to/something
a.search //=> ?query=string
a.hash //=> #fragment
a.host //=> example.com:3000
```
---
EDIT #2
-------
Upon further consideration, I looked into the Node.js docs and found this little gem: [**`url#parse`**](http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost)
The code above can be rewritten as:
```
var url = require('url');
var urls = [
'http://example.com:3000',
'http://example.com?pass=gas',
'http://example.com/',
'http://example.com'
];
for (x in urls) {
console.log(url.parse(urls[x]).hostname);
}
//=> example.com
//=> example.com
//=> example.com
//=> example.com
```
---
EDIT #1
-------
See the revision history of this post if you'd like to see how to solve this problem using `jsdom` and `nodejs` | I'm using Node `^10` and this is how I extract the hostname from a URL.
```
var url = URL.parse('https://stackoverflow.com/q/13506460/2535178')
console.log(url.hostname)
//=> stackoverflow.com
``` |
9,469,174 | I'm trying to set the theme for a fragment.
Setting the theme in the manifest does not work:
```
android:theme="@android:style/Theme.Holo.Light"
```
From looking at previous blogs, it appears as though I have to use a ContextThemeWrapper. Can anyone refer me to a coded example? I can't find anything. | 2012/02/27 | [
"https://Stackoverflow.com/questions/9469174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1232691/"
] | I know its a bit late but it might help someone else because this helped me.You can also try adding the line of code below inside the onCreatView function of the fragment
```
inflater.context.setTheme(R.style.yourCustomTheme)
``` | Use this in fragment which you want different theme:
```
@Override
public void onAttach(@NonNull Context context) {
context.setTheme(R.style.your_them);
super.onAttach(context);
}
``` |
10,539,579 | Is it possible to add an app icon , like it shows in Live Aquarium Wallpaper (https://play.google.com/store/apps/details?id=fishnoodle.aquarium\_free&feature=search\_result#?t=W251bGwsMSwxLDEsImZpc2hub29kbGUuYXF1YXJpdW1fZnJlZSJd)
When I install this wallpaper, it shows and icon which opens up the settings page when clicked on it. Has anyone done this before? | 2012/05/10 | [
"https://Stackoverflow.com/questions/10539579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1182140/"
] | You would need to declare an Activity in your `AndroidManifest.xml` with the default [intent-filter](http://developer.android.com/guide/topics/intents/intents-filters.html):
```
<activity
android:name="com.your.company.ui.SettingsActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
``` | For those still looking for the correct answer:
You need to declare a `<meta-data>` tag, inside your declaration of Wallpaper Service tag inside the manifest file:
```
<service
android:name=".MyWallpaperService"
android:enabled="true"
android:label="My Wallpaper"
android:permission="android.permission.BIND_WALLPAPER" >
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService"/>
</intent-filter>
<meta-data
android:name="android.service.wallpaper"
android:resource="@xml/wallpaper" >
</meta-data>
</service>
```
This tag points to an xml file which contains information about the icon of the wallpaper which appears in the Live-Wallpapers section:
```
<?xml version="1.0" encoding="UTF-8"?>
<wallpaper
xmlns:android="http://schemas.android.com/apk/res/android"
android:label="GIF Wallpaper"
android:thumbnail="@android:drawable/btn_star">
</wallpaper>
```
So `android:thumbnail` is where you set the resource for the icon |
24,083,659 | I am having a problem with multiple `ng-repeat` elements when showing `div` elements as `inline-block`. There is a strange gap between elements where one `ng-repeat` ends and the next one starts, as illustrated by the image:

I have created a [plunk](http://plnkr.co/mDHcEEaVng5VJlBbf3z1) to demonstrate this behavior:
Why is this happening and how to remove the gap? | 2014/06/06 | [
"https://Stackoverflow.com/questions/24083659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/757391/"
] | Check this [plunk](http://plnkr.co/edit/cCpFl5gqHMVMhmRxMNBZ)
There is a hack to remove space between inline elements that appears at line-break.
```
<div class="red" ng-controller="TestCtrl">
<div class="blue number" ng-repeat="number in array1 track by $index">{{number}}</div><!--
--><div class="green number" ng-repeat="number in array2 track by $index">{{number}}</div><!--
--><div class="teal number" ng-repeat="number in array3 track by $index">{{number}}</div>
</div>
```
You could read more about other hacks [here](http://css-tricks.com/fighting-the-space-between-inline-block-elements/). | This is caused by the whitespace between the `<div>` elements. There are various ways to address this like the other answers have suggested. My preferred layout is:
```
<div class="blue number" ng-repeat="number in array1 track by $index">{{number}}</div
><div class="green number" ng-repeat="number in array2 track by $index">{{number}}</div
><div class="teal number" ng-repeat="number in array3 track by $index">{{number}}</div>
```
But the other suggestions are valid.
Another way to handle this without worrying about the HTML is to set the font size of the container to 0 so that the white space doesn't appear.
<http://plnkr.co/edit/wXKl61lyiqdONbChYI9o?p=preview>
The downside to this approach is that you can't use percentage sizes for the contained element fonts and you have to set them explicitly. |
31,793,078 | I have a tail recursive implementation as below
```
@tailrec
def generate() : String = {
val token = UUID.randomUUID().toString
val isTokenExist = Await.result(get(token), 5.seconds).isDefined
if(isTokenExist) generate()
else token
}
```
`get(token)` will return a `Future[Option[Token]]`.
I know that blocking in a Future is not good. I tried to return a `Future[String]` instead of `String`. But seems that its not possible unless I wait for `isTokenExist` to be completed.
Any other way/suggestion to implement this? | 2015/08/03 | [
"https://Stackoverflow.com/questions/31793078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5180015/"
] | `consume` is a static method, COM does not support any support static methods only instance methods and properties. Get rid of the `static`'s from your code.
You're consume method will also always return an empty string. You are stating your `Consumer` inside of a task but you are not waiting for that task to complete. You'll either need to get rid of the `Task` and run the `Consumer` synchronously or add an `event` to your `netConsumer` class and raise that event when the task completes.
Synchronous way:
```
public class netConsumer
{
public string message;
public KafkaOptions options = new KafkaOptions(new Uri("http://rqdsn0c.bnymellon.net:9092"), new Uri("http://rqdsn0c.bnymellon.net:9092"), new Uri("http://rqdsn0c.bnymellon.net:9092"))
{
Log = new ConsoleLog()
};
public BrokerRouter router = new BrokerRouter(options);
public string consume()
{
var consumer = new Consumer(new ConsumerOptions("TestHarness3", router));
foreach (var data in consumer.Consume())
{
Console.WriteLine("Response: P{0},O{1} : {2}", data.Meta.PartitionId, data.Meta.Offset, data.Value);
var utf8 = Encoding.UTF8;
message += utf8.GetString(data.Value, 0, data.Value.Length);
ExcelWorksheet.writeToExcel(message);
}
return message;
}
}
```
Asynchronous with event:
```
public delegate void ConsumeCompleteHandler(string message);
public class netConsumer
{
public string message;
public KafkaOptions options = new KafkaOptions(new Uri("http://rqdsn0c.bnymellon.net:9092"), new Uri("http://rqdsn0c.bnymellon.net:9092"), new Uri("http://rqdsn0c.bnymellon.net:9092"))
{
Log = new ConsoleLog()
};
public BrokerRouter router = new BrokerRouter(options);
public void consume()
{
Task.Factory.StartNew(() =>
{
var consumer = new Consumer(new ConsumerOptions("TestHarness3", router));
foreach (var data in consumer.Consume())
{
Console.WriteLine("Response: P{0},O{1} : {2}", data.Meta.PartitionId, data.Meta.Offset, data.Value);
var utf8 = Encoding.UTF8;
message += utf8.GetString(data.Value, 0, data.Value.Length);
ExcelWorksheet.writeToExcel(message);
}
OnConsumeComplete(message);
});
}
public event ConsumeCompleteHandler ConsumeComplete;
protected virtual void OnConsumeComplete(string message)
{
var handler = ConsumeComplete;
if (handler != null) handler(message);
}
}
``` | Couple of things. In the VBA code Consumer means two things (both the variable and the container of netConsumer); this is going to cause confusion at the least.
What is the external Consumer anyway? (The one that's not the variable.) It looks from the C# code like it should be netConsumer. How are you exporting the class to COM anyway? (Wrong stuff about namespace and class names edited out as per shf301 below.)
Third, since consume() is a static method, why are you creating a netConsumer anyway? |
41,131 | The MT 1 Samuel 2:31 reads:
>
> הִנֵּה, יָמִים בָּאִים, וְגָדַעְתִּי אֶת-זְרֹעֲךָ, וְאֶת-זְרֹעַ בֵּית
> אָבִיךָ--מִהְיוֹת זָקֵן, בְּבֵיתֶךָ.
>
>
> Behold, the days come, that I will cut off thine arm, and the arm of
> thy father's house, that there shall not be an old man in thy house.
>
>
>
Or as the NIV (who actually follows the MT reading in this case) has it:
>
> The time is coming when I will cut short your strength and the
> strength of your priestly house, so that no one in it will reach old
> age,
>
>
>
The way the MT chooses to vowelize זרע is really odd, since the context strongly suggests that the word זרע here should be taken as זֶרַע = seed/children rather than זְרֹע = hand/strength. This is actually clearly spelled out in the following verse that none will reach old age and they will all die before reaching maturity thereby cutting the line of Eli short.
Indeed some translations ignore the MT and interpret the verse in the more natural way. The ISV for example renders the verse as follows:
>
> The time is coming when I'll cut away at your family and your
> ancestor's family until there are no old men left in your family.
>
>
>
I also think it is most unnatural to translate the Hebrew term into *hand* or *strength*, as it is entirely unclear what *cutting off the strength of the house of Eli* would mean in this context anyway.
Can anyone explain why the MT chooses to translate this verse in the most unnatural way (instead of children)? What evidence is there in favor of the MT, and how can it be justified? | 2019/06/16 | [
"https://hermeneutics.stackexchange.com/questions/41131",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/15819/"
] | Great question, as usual!
Some possibilities/considerations:
1. Earlier spellings of the word may have made it clear that this was the correct reading. For example, in this case, the full spelling of zera (seed) would be spelled זרע, while the full spelling of zero'a (strength) would be spelled זרוע. If there were earlier books that spelled the word this way, there would be no question as to the vowelization. (see [here](https://archive.org/details/vetustestamentum01kenn/page/520))
2. It is possible that they chose this vowelization since the verb גדע does not pair well with zera (seed). When Tanach refers to "cutting off seed" it uses the verb כרת. On the other hand, גדע seems to relate to a physical cutting, as would make sense with the word zero'a, which is literally an arm. See as well Job 22:9 and Psalms 37:17, noted in Ellicott's commentary.
3. It is possible that due to other connections where another word relating to strength is used, it chose to use a word of strength here. For example:
* Rashi cites Samuel I 2:16, in which Chofni and Pinchas tell those bringing sacrifices that they will take from them "by force".
* The Benson Commentary notes Psalms 78:61, which refers to the Ark as "God's strength", which refers to the episode in which this prophecy was fulfilled. | If God cut off the seed there would be no one in the house at all, but if he cut off the strength then they would all be weak and would not live to old age, so the second part of the verse supports the MT. Eli's house was deposed from the priesthood, rather than destroyed altogether. |
7,583,716 | I am facing this error when i try to commit my SVN .
```
svn: 'C:\Users\wageeha junaid\workspace\Copy of HOLS\gwt-unitCache\gwt-unitCache- 00000132A65F0D8B' does not exist
``` | 2011/09/28 | [
"https://Stackoverflow.com/questions/7583716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764446/"
] | you should not commit the unitCache to the versioning system. use [svn:ignore](http://svnbook.red-bean.com/en/1.1/ch07s02.html#svn-ch-7-sect-2.3.3) for that purpose. | Easy fix if you are using Eclipse: Right click on the gwt-unitCache folder and press Refresh. The problem is that you need to update the folder from the package explorer before you commit. |
56,154,094 | I have a 2 row table with `input` fields that does a calculation when I focusout on the first input. The problem I am experiencing is when I focusout on the second row, my new value is displayed in the first row corresponding `input`. I'm not sure why this is happening. I would greatly appreciate your help.
My expectation is when I enter a value in a row input (Cost) and `focusout` the new value should be set in the same row but in the input (New Cost).
```js
function Calculate(element) {
var dollar = 216.98;
var id = element.id;
var oldcost = $(element).val();
var newcost = oldcost * dollar;
$("#" + id).closest("tr").find("td #new").val(newcost);
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Cost</th>
<th>New Cost</th>
</tr>
<tr>
<td><input type="number" id="old" onfocusout="Caluculate(this)" /></td>
<td><input type="number" new="new" /></td>
</tr>
<tr>
<td><input type="number" id="old" onfocusout="Caluculate(this)" /></td>
<td><input type="number" new="new" /></td>
</tr>
</table>
``` | 2019/05/15 | [
"https://Stackoverflow.com/questions/56154094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1465183/"
] | Your use of id's is kind of messed up. First of all be sure to use an id once in the entire HTML file.
For your usecase better use classes.
Also be sure to type your function names correct ;)
```js
function Calculate(element) {
var dollar = 216.98;
var parent = $(element).closest('tr');
var oldcost = $(element).val();
var newcost = oldcost * dollar;
parent.find(".new").val(newcost.toFixed(2));
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Cost</th>
<th>New Cost</th>
</tr>
<tr>
<td><input type="number" class="old" onfocusout="Calculate(this)" /></td>
<td><input type="number" class="new" /></td>
</tr>
<tr>
<td><input type="number" class="old" onfocusout="Calculate(this)" /></td>
<td><input type="number" class="new" /></td>
</tr>
</table>
``` | * Firstly, there is a a typo.Change `caluculate` to `calculate`
* There must not be the same `id` two elemnts have the same `id`.You could change the id of the first to `old-1` or something different |
59,165,133 | I can figure out how to see who it was last updated by, but I'm looking for a list of Jira Tickets that has been updated by someone at any point during the week. Even if someone else updated it afterwards. | 2019/12/03 | [
"https://Stackoverflow.com/questions/59165133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5366100/"
] | I'm not sure if you're referring to Jira Server/DC or Jira Cloud. For on-premise solutions, here is my answer.
**Jira 7.x and lower**
There are no JQL functions to get this information. With out-of-the-box functions, you can actually get information only about status changes by a certain user or query history of certain system fields - see Aaron's answer.
```
status changed by currentUser() AFTER startOfWeek()
assignee was currentUser() AFTER startOfWeek()
assignee was currentUser() AFTER startOfWeek() AND updated > startOfWeek()
```
With [ScriptRunner](https://marketplace.atlassian.com/apps/6820/scriptrunner-for-jira?hosting=server&tab=overview) installed, you will have more JQL functions available and you can get more information about worklogs and comments:
```
issueFunction in commentedBy("username after startOfWeek()")
issueFunction in workLogged("by username after startOfWeek()")
```
Similarly with [JQL Tricks](https://marketplace.atlassian.com/apps/31399/jql-tricks-plugin?hosting=server&tab=overview) add-on ([documentation](https://www.j-tricks.com/jql-tricks-plugin.html)).
**Jira 8+**
Atlassian has added (limited) support after 15 years (!) of requesting this feature ([JRASERVER-1973](https://jira.atlassian.com/browse/JRASERVER-1973)). There is the new JQL function `updatedBy`.
```
issue in updatedBy(username)
issue in updatedBy(username, -7w)
```
Unfortunately, this JQL function is unable to work with relative functions (`currentUser()`, `startOfWeek()`).
See more information about this JQL function in [Atlassian Documentation](https://confluence.atlassian.com/jirasoftwareserver080/advanced-searching-functions-reference-967899663.html#Advancedsearching-functionsreference-approverupdatedBy()). | Depends on what changes you are looking for. Jira does have limited support for search functions on history enabled fields (specifically: `Assignee`, `Fix Version`, `Priority`, `Reporter`, `Resolution` and `Status`)
Meaning you could do a search similar to:
```
status changed by "replace_user_name_here" AFTER startOfWeek();
```
There would be ways to restrict workflows to automatically update one of those fields if you needed a wider net of changes caught by the history (i.e. have comments trigger changes of status as a part of a business logic), but that would be up to the configuration of your business's logic and how you intend to utilize the history field. |
15,526 | I'm making a kind of editor that have tool views (on sides of the main window) and documents being edited. In fact those documents are themselves "views" of a specific document, so you can have several different views of the same document, but it's not really the point. Each "view" has it's own state and manipulations possibles.
I have a menu in the main window, but for some view-specific actions, I'm considering adding a menu in the sub-windows.
What do you think? Would it be bad ergonomy? I'm doubting about such a design because, for example, Adobe products doesn't have separate menus, only menus that change depending on the focus.
```
+------------------------------------------------------------------------------+
| Main Window |
+------------------------------------------------------------------------------+
| File | Edit | Something | |
|------------------------------------------------------------------------------|
|Tools | |
|---------------| +-----------------------------------------------------+ |
| | | Document View | |
| [ Brush ] | +-----------------------------------------------------+ |
| | | Document | Item | Window | | |
| [ Pen ] | |-----------------------------------------------------| |
| | | | |
| [ Eraser ] | | | |
| | | | |
| | | | |
| | | | |
| | | | |
| | | | |
| | | | |
| | +-----------------------------------------------------+ |
|------------------------------------------------------------------------------|
| Status Bar |
+------------------------------------------------------------------------------+
``` | 2011/12/29 | [
"https://ux.stackexchange.com/questions/15526",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/6824/"
] | It's still fairly common to have "Document" menus in applications that will adjust settings or make changes to one particular document. I was going to mention Acrobat as @dnbrv did- they definitely used to do this, but seem to have moved away from it in version 10.
"View" menus exist as well, but they tend to deal with showing or hiding particular components of the UI like toolbars and extra panels. So, while your objects are called "views", I wouldn't recommend using that term as the menu label as users may end up confused by what they find there.
If these views are really different layouts of the same data, "Layout" may be a label option for you as well. | You can go the way of Adobe Acrobat, which has a menu item called Document containing all commands for manipulating the document as opposed to reviewing tools. Having 2 sets of menus will clutter your interface more than confuse users. |
10,546,504 | I am designing a program in JAVA that captures results in about 10 iterations. At the end of these iterations all the results must be written into a log file.
If any exception occurs then it should be written on my text file and secondly the program must not stop, it must go on till the last iteration is completed...
That is to say - if some error occur on any part of any iteration the *program must not stop* here. The error must be mentioned within my results by the name of error and it must go on and update my log file.
My code till now is bit lengthy...used try-catch, the try block is doing my calculations and writing my text file, but I need if incase some exception occurs my program must not stop and that exception must be updated in my log file. | 2012/05/11 | [
"https://Stackoverflow.com/questions/10546504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365268/"
] | You're looking for the `try`-`catch` block. See, for example, [this tutorial](http://docs.oracle.com/javase/tutorial/essential/exceptions/). | the case is, in this kind of a question, you should better provide us a sample code, then only we can identify the problem without any issue.
If you just need to view the error, then "e.printStackTrace" will help you. The "e" is an instance of class "Exception".
However, if you need to LOG, then "Logger" class will help you, with Exception class.For an example,
```
try {
f = location.createNewFile();
} catch (IOException ex) {
Logger.getLogger(TestForm.class.getName()).log(Level.SEVERE, null, ex);
}
```
To do all of these, it is better to surround your code with try catch block |
47,850,439 | How can I change the parameter "symbol" in the url to each element of the array one by one and run the function multiple times?
```
var symbols = [MSFT, CSCO, FB, AMZN, GOOG];
window.onload = function() {
$.ajax({
type: "GET",
url: "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=AAPL&interval=1min&apikey=T6UEJETEQRVGDJS9",
success: function(result){
stocks = result;
document.getElementById("myDiv").innerHTML = stocks;
}
});
}
```
Thanks! | 2017/12/16 | [
"https://Stackoverflow.com/questions/47850439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101762/"
] | You have to separate the AJAX call to stand alone function, and then call the that function each time with different parameter.
Like so:
```
window.onload = function() {
var symbols = ['MSFT', 'CSCO', 'FB', 'AMZN', 'GOOG'];
symbols.forEach( symbol => makeAjaxCall(symbol));
}
function makeAjaxCall(param){
$.ajax({
type: "GET",
url: "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol="+ param +"&interval=1min&apikey=T6UEJETEQRVGDJS9",
success: function(result){
stocks = result;
document.getElementById("myDiv").innerHTML = stocks;
}
});
}
``` | You can set it as a variable:
```
$ node
> var symbol = 'aallalla'
undefined
> var html = 'http://www.google.com/?symbol='
undefined
> html + symbol
'http://www.google.com/?symbol=aallalla'
>
```
This will allow you to change it on demand. |
26,395,776 | I am constructing a navigation bar using bootstrap framework. I am trying to align the search field to extreme right,but its not happening.
any suggestion would be appreciated . below is my code
```
<h1 id="topHeader"><a href="/EduTechOnline/jsp/secure/index.jsp" id="topHeaderLink"></a></h1>
<div id="logo">
<img src="/EduTechOnline/images/logo.png" width="200" height="80" />
<div id="slogan"><h2 id="slogan">Take the world's best online courses</h2></div>
</div>
<!-- This is the header that will be present on every page -->
<nav class="navbar navbar-inverse" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="collapse navbar-collapse" id="navbar-collapse-1">
<ul class="nav navbar-nav">
<nav id="headerli">
<li><a class="active"href="#">Home</a></li>
<li><a href="#">Courses</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Videos</a></li>
</ul>
<ul class="nav pull-right nav navbar-nav">
<li> <form class="navbar-form" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn-group btn-group-sm">Go</button>
</form>
</li>
</ul>
</ul>
</nav>
</div>
</ul>
</nav>
``` | 2014/10/16 | [
"https://Stackoverflow.com/questions/26395776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2218797/"
] | I wouldn't call it beautiful, but here's a method using `map`:
```
let numbers = ["1","2","3","4","5","6","7"]
let splitSize = 2
let chunks = numbers.startIndex.stride(to: numbers.count, by: splitSize).map {
numbers[$0 ..< $0.advancedBy(splitSize, limit: numbers.endIndex)]
}
```
The `stride(to:by:)` method gives you the indices for the first element of each chunk, so you can map those indices to a slice of the source array using `advancedBy(distance:limit:)`.
A more "functional" approach would simply be to recurse over the array, like so:
```
func chunkArray<T>(s: [T], splitSize: Int) -> [[T]] {
if countElements(s) <= splitSize {
return [s]
} else {
return [Array<T>(s[0..<splitSize])] + chunkArray(Array<T>(s[splitSize..<s.count]), splitSize)
}
}
``` | In Swift 4 or later you can also extend `Collection` and return a collection of `SubSequence` of it to be able to use it also with `StringProtocol` types (`String` or `Substring`). This way it will return a collection of substrings instead of a collection of a bunch of characters:
**Xcode 10.1 • Swift 4.2.1 or later**
```
extension Collection {
func subSequences(limitedTo maxLength: Int) -> [SubSequence] {
precondition(maxLength > 0, "groups must be greater than zero")
var start = startIndex
var subSequences: [SubSequence] = []
while start < endIndex {
let end = index(start, offsetBy: maxLength, limitedBy: endIndex) ?? endIndex
defer { start = end }
subSequences.append(self[start..<end])
}
return subSequences
}
}
```
---
Or as suggested in comments by @Jessy using collection method
```
public func sequence<T, State>(state: State, next: @escaping (inout State) -> T?) -> UnfoldSequence<T, State>
```
---
```
extension Collection {
func subSequences(limitedTo maxLength: Int) -> [SubSequence] {
precondition(maxLength > 0, "groups must be greater than zero")
return .init(sequence(state: startIndex) { start in
guard start < self.endIndex else { return nil }
let end = self.index(start, offsetBy: maxLength, limitedBy: self.endIndex) ?? self.endIndex
defer { start = end }
return self[start..<end]
})
}
}
```
Usage
```
let array = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
let slices = array.subSequences(limitedTo: 2) // [ArraySlice(["1", "2"]), ArraySlice(["3", "4"]), ArraySlice(["5", "6"]), ArraySlice(["7", "8"]), ArraySlice(["9"])]
for slice in slices {
print(slice) // prints: [["1", "2"], ["3", "4"], ["5", "6"], ["7", "8"], ["9"]]
}
// To convert from ArraySlice<Element> to Array<element>
let arrays = slices.map(Array.init) // [["1", "2"], ["3", "4"], ["5", "6"], ["7", "8"], ["9"]]
```
---
---
```
extension Collection {
var singles: [SubSequence] { return subSequences(limitedTo: 1) }
var pairs: [SubSequence] { return subSequences(limitedTo: 2) }
var triples: [SubSequence] { return subSequences(limitedTo: 3) }
var quads: [SubSequence] { return subSequences(limitedTo: 4) }
}
```
---
Array or ArraySlice of Characters
```
let chars = ["a","b","c","d","e","f","g","h","i"]
chars.singles // [["a"], ["b"], ["c"], ["d"], ["e"], ["f"], ["g"], ["h"], ["i"]]
chars.pairs // [["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"], ["i"]]
chars.triples // [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
chars.quads // [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i"]]
chars.dropFirst(2).quads // [["c", "d", "e", "f"], ["g", "h", "i"]]
```
---
StringProtocol Elements (String and SubString)
```
let str = "abcdefghi"
str.singles // ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
str.pairs // ["ab", "cd", "ef", "gh", "i"]
str.triples // ["abc", "def", "ghi"]
str.quads // ["abcd", "efgh", "i"]
str.dropFirst(2).quads // ["cdef", "ghi"]
``` |
2,217,132 | `AddPage()` in tcpdf automatically calls Header and Footer. How do I eliminate/override this? | 2010/02/07 | [
"https://Stackoverflow.com/questions/2217132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15654/"
] | Use the `SetPrintHeader(false)` and `SetPrintFooter(false)` methods before calling `AddPage()`. Like this:
```
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, 'LETTER', true, 'UTF-8', false);
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->AddPage();
``` | >
> How do I eliminate/override this?
>
>
>
Also, [Example 3 in the TCPDF docs](http://www.tcpdf.org/examples/example_003.phps) shows how to override the header and footer with your own class. |
6,822,929 | Has something was changed in the way IE9 treats the **title** attribute in an anchor tag?
I try to use a regular anchor, such as -
```
<a href="http://www.somelink.com" title="Some title here">This is a link</a>
```
A tooltip should be with the title is expected to appear, and it does appear in previous versions of IE and also in other browsers, but not on IE9.
Is there a know issue with that? I tried to search the web for that, but found nothing about this.
Any ideas?
Thanks | 2011/07/25 | [
"https://Stackoverflow.com/questions/6822929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776561/"
] | I have found a good work-around, Place your title in an abbr tag. I've tested this in Safari, Chrome, IE9, and Firefox. It works in all of them. | I had a typical scenario wherein we had to show a image with tooltip. The image was inside a Iframe and tooltips were not being displayed, when opened in a Browser with IE 10 Compat Mode.
The alt tag helped me out. The solution was to set the images alt tag.
```html
<A onclick=navigate() title="Did not work" href="javascript:void(0);" height="" width="">
<IMG alt="This worked" src="http://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/icons/imageviewer_back_button.gif">
</A>
``` |
27,531,050 | I want the cell spacing to be 0.5 for an ASP GridView. Is there any way to accomplish this as it tries to cast the value to Int32 and obviously 0.5 will not cast to Int32. I want it this way because IE expresses really ugly cell separators, but if I set CellSpacing to 0 or remove it, the cells are way too crowded.
IE9 with CellSpacing = 3:

IE9 with CellSpacing = 0:

Chrome with CellSpacing = 3:

Chrome with CellSpacing = 0

Setting it to 1 is ok, but I was hoping there was some way to do less. | 2014/12/17 | [
"https://Stackoverflow.com/questions/27531050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1282988/"
] | To call `OnMapReady(GoogleMap map)`, append the following to your `onCreate(...)` method :
```
MapFragment mapFragment = (MapFragment)
getFragmentManager().findFragmentById(R.id.map);
```
then, add:
```
// This calls OnMapReady(..). (Asynchronously)
mapFragment.getMapAsync(MapDisplay.this);
``` | Add:
```
mMap = map
```
above `onMapReady` |
20,832 | I found it odd that in John 9:30-33, the (healed) blind man refers to scripture, suddenly speaking as a learned scholar to the point where the Pharisees accuse him of lecturing them. I wonder, was it common back in those days, that even the blind and beggars would have thorough understanding of scripture? I assumed only the Pharisees would have such knowledge. To me, this is like a homeless man suddenly getting up and reciting the derivation of the Schrodingers equation to everyone on the street... | 2015/12/02 | [
"https://hermeneutics.stackexchange.com/questions/20832",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/11359/"
] | The setting here is long before the invention of the printing press. The scriptures were hand copied, thus ordinary people would not have been able to own a copy of the scriptures. However, in ancient Judea during the Second Temple Period, the Jewish scriptures(Christian Old Testament) would have been publicly available in the synagogues to read. In fact, the Jews would go to the synagogue on the Sabbath to hear rabbis read the scripture out loud. Jesus actually does this in Luke 4:16-21.
It is also important to remember that the Torah, Prophets, and Wisdom literature that make up the Christian Old Testament were central to Jewish religion and law during this time. The words of scripture were, as they are now, believed to be inspired by God. With this importance placed on them, it is not a surprise that a man handicapped by blindness would look to the scriptures as an explanation of his ailment as well as a possible source of healing. Thus the blind man had both means and motive to remember the scriptures that he quoted. | All Israelites men were required to teach all of their household the laws as well as assemble themselves on the Sabbath at the synagogue to hear the master builders (rabbis) and the reading of the Torah. |
21,795 | My Nikon D3100 out of the blue cannot focus correctly.
It seem the that the focus motor always stops at the end of the run (Infinity) and cannot lock on the target, thus cannot release the shutter. I tried with two other AF-S lens but still the same.
This only happen when I use the viewfinder. The AF motor works fine and can focus on the target if I use the live view (LCD).
I tried the single point auto-focus, Reset to Factory Setting, and I tried cleaning the contacts but still cannot get the AF to focus on the target through the viewfinder.
What could be wrong and what can I do about it? | 2012/03/28 | [
"https://photo.stackexchange.com/questions/21795",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/9177/"
] | If it won't focus in OVF mode with several lens, especially after checking all focus options and switches, switching in/out of manual focus, re-seating the lens, cleaning the contacts AND verifying that the live-view CDAF works in the very same situations, I would contact the vendor and/or Nikon and possibly send in for repairs.
Best of luck. | I read this thread when I had the same problem (with live view). Turned the Rangefinder off, then back on and now it works. |
669,062 | I have a variable, `var`, that contains:
```
XXXX YY ZZZZZ\n
aaa,bbb,ccc
```
All I want is `aaa` in the second line.
I tried:
```
out=$(echo "$var" | awk 'NR==2{sub(",.*","")}' )
```
but I get no output. I tried using `,` as the FS but I can't get the syntax right. I really want to learn awk/regex syntax.
I want to use out as a variable "$out" somewhere else -- not to print. | 2021/09/15 | [
"https://unix.stackexchange.com/questions/669062",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/475899/"
] | You don't want regexes there. The entire point of `awk` is to automatically split a line into fields, so just set the field separator to `,` and print the first field of the second line:
```
$ printf '%s' "$var" | awk -F, 'NR==2{print $1}'
aaa
```
Or, if your shell supports `<<<`:
```
$ awk -F, 'NR==2{print $1}' <<<"$var"
aaa
```
If you really want to do it manually and not use `awk` as intended, you can do:
```
$ awk 'NR==2{sub(/,.*/,""); print}' <<<"$var"
aaa
```
You were getting no output because you didn't tell `awk` to print anything. | Using `cut`:
```
cut -d, -f1
```
will give you the first field (`-f1`) until the delimiter `-d`
If you want the last line only, you can pipe from `tail`. Or pipe from `sed` to get a specific line.
```
tail -n1 <<< "$var" | cut -d, -f1
sed -n 2p <<< "$var" | cut -d, -f1
``` |
21,705,533 | I'm currently developing an application on MVC3 and:
1. I have a form in which the user is completing the form for each
register.
2. When he click one button the records are passed to the controller
and stored in a list and then passed to the view again to show a
preview of what is at the momment in the "buffer"
3. The data which is not edited and only displayed (previous registers) for avoiding their dissapear are preserverd in the multiple steps using hiddenfor
4. Finally the user can save all the elements on the list in the database when click another button
My question is: there is way to preserving the data in the list without having to make a hiddenfor for every element in each step? | 2014/02/11 | [
"https://Stackoverflow.com/questions/21705533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2662302/"
] | You can use [array\_walk](http://us1.php.net/array_walk) and [explode](http://us1.php.net/explode) to do this.
```
$array = array();
$string = "2,100|7,104|15,1110";
array_walk(explode("|", $string), function($value) use(&$array) {
$group = explode(",", $value);
$array[$group[0]] = $group[1];
});
```
PHP 5.4+ | Like Yatin Trivedi said, exploding twice should give you the result that you are after:
```
$string = '2,100|7,104|15,1110';
$result = array();
foreach (explode('|', $string) as $entry) {
$values = explode(',', $entry);
$result[$values[0]] = $values[1];
}
``` |
57,944,714 | I got an error when I tried to add flutter to an existing iOS app it worked fine on the android side, in IOS I got this error message :
```
/Users/mac/Library/Developer/Xcode/DerivedData/Fixit- dffmmspbqmueppghdvveloietubr/Build/Intermediates.noindex/Fixit.build/Debug- iphoneos/Fixit.build/Script-04B0EA9A232E6ABD008A0448.sh: line 3: /packages/flutter_tools/bin/xcode_backend.sh: No such file or directory
/Users/mac/Library/Developer/Xcode/DerivedData/Fixit- dffmmspbqmueppghdvveloietubr/Build/Intermediates.noindex/Fixit.build/Debug- iphoneos/Fixit.build/Script-04B0EA9A232E6ABD008A0448.sh: line 4: /packages/flutter_tools/bin/xcode_backend.sh: No such file or directory
Command PhaseScriptExecution failed with a nonzero exit code
```
inside my pod file i added this inside target application:
```
flutter_application_path = 'Users/mac/FixitApps/customerApp/fixit_flutter_customer_app/'
eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)
```
I followed this tutorial: <https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps> | 2019/09/15 | [
"https://Stackoverflow.com/questions/57944714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6462382/"
] | if you create a script file in the build phase for building dart code remove it and add this to your podfile :
```
flutter_application_path = 'Users/mac/FixitApps/customerApp/fixit_flutter_customer_app/'
eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)
install_all_flutter_pods(flutter_application_path)
``` | In my case when I have deleted some files from assets but forget to remove from pubspes.yaml.
Error solved after
1. remove deleted files from pubspes.yaml
2. click on `pub get`.
3. run on device |
51,703,562 | I have this query
```
select p.ID, dp.ID
from MyDB.dbo.Table1 as p
inner join MyDB.dbo.Table2 as dp
on p.Title = dp.Title
```
It compares two strings(varchars) and it gives 113 rows which is the right result.
I am not sure what should I do in TSQL to get only the IDs/rows where p.Title is different then dp.Title.
Using inner join, or left or right join, gives Cartesian product i.e 32000 rows. Something like:
```
select p.ID, dp.ID
from MyDB.dbo.Table1 as p
join MyDB.dbo.Table2 as dp
on p.Title <> dp.Title
```
Should I use some string function to compare strings, or find IS NULL results?
I need to get combinations of p.ID and dp.ID.
Note: The IDs of both table are not linked or known to be identical up-front i.e they are required. | 2018/08/06 | [
"https://Stackoverflow.com/questions/51703562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/885838/"
] | Try the following query-:
```
select a.ID,b.ID from (
select ID,ROW_NUMBER() over (order by ID) rn
from MyDB.dbo.Table1
where ID
not in (select MyDB.dbo.Table1.ID from MyDB.dbo.Table1 join MyDB.dbo.Table2 on MyDB.dbo.Table1.name=MyDB.dbo.Table2.name)
)a
full outer join (
select ID,ROW_NUMBER() over (order by ID) rn
from MyDB.dbo.Table2
where ID
not in (select MyDB.dbo.Table2.ID from MyDB.dbo.Table1 join MyDB.dbo.Table2 on MyDB.dbo.Table1.name=MyDB.dbo.Table2.name)
) b
on a.rn=b.rn
```
SQL Server 2014 | I am not entirely sure what you are after. Here is a little fiddle showing the simple join on "inequality" of titles: <http://rextester.com/TFIXP19067>
```
select p.ID id1, dp.ID id2, p.title t1, dp.title t2
from Table1 as p
inner join Table2 as dp
on p.Title != dp.Title
```
This query will give you a "Cartesian product"-like result. But that is to be expected since you have no further condition on the `JOIN` other than the inequality between the two titles.
Judging by the points given to the other answers I guess you are *not* interested in the Cartesian product solution. In that case maybe a listing of the two tables, one after (below!) the other, limited to those entries that have no equivalence in the other table is a valid solution? Like
```
select * from Table1 where not exists ( select 1 from table2 where table2.title=table1.title );
select * from Table2 where not exists ( select 1 from table1 where table1.title=table2.title )
```
see here: <http://rextester.com/RVJRVG86860>
**Please note:**
With this query you will get you all differing table entries, regardless of how many there are in each table. The accepted answer (by IShubh) will only list "pairs" of entries and *will not list all entries* if the two tables have *different record counts*. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.