INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
LED stays on. Wont' turn on and off
So all I'm trying to do is make a function to turn on and turn off the LED which will be called into the main. The LED turns on but it doesn't turn on and off. What's wrong with my code?
I'm using ATmega328p board and Atmel Studio 6.2
#define F_CPU 16000000UL // 16MHz clock from the debug processor
#include <avr/io.h>
#include <util/delay.h>
dot();
int main()
{
DDRB |= (1<<DDB5);
while(1)
{
dot();
}
}
int dot()
{
PORTB |= (1<<PORTB5); // Set port bit B5 to 1 to turn on the LED
_delay_ms(200); // delay 200mS
PORTB |= (0<<PORTB5); // Set port bit B5 to 0 to turn on the LED
_delay_ms(200); // delay 200mS
}
|
Read about bit-operators. `a |= b` sets all bits in a which are set in `a` **or** `b`. So if `b == 0`, it does not alter `a`.
You need the bit-and operator after the first delay. This sets all bits which are set in `a` **and** `b`:
PORTB &= ~(1U<<PORTB5);
The inversion operator `~` inverts the mask, so it leaves only the relevant bit `0`, all other bits are `1`. So bit number `PORTB5` will be cleared, all other are left unchanged.
Note using an unsigned constant. This is in general recommended, as bit-operators and shifts are implementation defined for negative values or if the sign changes - at best and _undefined behaviour_ at worst.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "c, led, atmega, atmel"
}
|
Java 8 Streams get original object after filtering map
I have to get the receipt id for not paid invoices. Orders has multiple receipts and receipts has invoices. I am using Java 8 stream. From receipts stream, I am able to get only invoices list, but I want to get receipt id for not paid invoices
Here is my code:
List<Invoice> invoicesNotPaid = receipts.stream()
.map(ReceiptsVO::getInvoices)
.flatMap(List::stream)
.map(inv -> Invoice.builder().status(InvoiceStatus.getStatus(inv.getStatus().name())).build())
.filter(Invoice::hasNotBeenPaid).collect(Collectors.toList());
after the final filter I am getting invoices only, I am not able to get the original receipts object reference. I have to do some thing like below, after checking the receipts against not paid invoices.
receipts -> receipt.getReceiptId()
How to get the receipt Id for not paid invoices?
|
you can stream the `receipts` and then check at least one `invoive` in receipt is not paid and then collect those receipt id's
List<Integer> receiptIdNotPaid = receipts.stream()
.filter(receipt-> receipt.getInvoices().stream()
.map(inv->Invoice.builder().status(InvoiceStatus.getStatus(inv.getStatus().name())).build())
.anyMatch(Invoice::hasNotBeenPaid))
.map(Receipt::getReceiptId)
.collect(Collectors.toList());
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "java, java 8, java stream"
}
|
Geometry question about similarity
(x)}{(x+1)^2} $$ $$\frac{[BZX]}{[ABC]}=\frac{(1)(x)}{(x+1)^2}$$ $$\frac{[CXY]}{[ABC]}=\frac{(1)(x)}{(x+1)^2} $$ So $$[ZXY]=\frac{x^2-x+1}{x^2+2x+1} [ABC]$$ $$[ZXY]=\frac{x^2-x+1}{x^2+2x+1} $$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "geometry"
}
|
ksoap2 in Android: noclassdeffounderror on SoapObject
I've added ksoap2-android-assembly-2.5.5-jar-with-dependencies to my build path in eclipse and given internet permissions in the manifest. The error is on: 'SoapObject request = new SoapObject(namespace, methodName);' and is a noclassdeffounderror. I checked the references folder and there is definitely a class called SoapObject in the ksoap2 file. I'm using Eclipse Helios. All of the other relevent posts I have seen don't appear to solve my version of this problem so any help would be greatly appriciated!
Thanks in advance
|
After some frustration trying all of the solutions I could possibly find I had a "duh" moment. I had imported the ksoap2 file as a zip and it occured to me that maybe android couldn't deal with it. I imported the jar and it worked perfectly.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, eclipse, ksoap2"
}
|
Как с помощью python скачать файл с Google drive?
Хочу реализовать программу с автообновлением, а для этого нужно чтобы скрипт скачивал файл с Google Drive. Сразу говорю что файл находится в открытом для чтения и скачивания доступе. Но как это сделать если не получается получить ссылку на сам файл, поэтому я и не знаю как это реализовать.
|
import urllib.request
logo = urllib.request.urlopen("
f = open("имя файла с расширением", "wb")
f.write(logo)
f.close()
Могу дать наглядный пример:
import urllib.request
logo = urllib.request.urlopen("
f = open("photo.jpg", "wb")
f.write(logo)
f.close()
Но чтобы получить такую ссылку, заканчивающюся на download, нужно сначала перейти по ссылке, указанной для общего доступа, а потом нажать на значок загрузки. И открывшаяся ссылка, собственно, будет заканчиваться на download, а это как раз то что нам и было нужно. А потом просто копируем её в вставляем.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 5,
"tags": "python, python 2.x, google drive"
}
|
Showing the derivative of a piecewise function is not continuous at a point
$$f(x) = \begin{cases} 2x+(x^2)\sin(\frac 1x), & \text{if $x\ne 0$} \\\ 0, & \text{if $x=0$}\end{cases}$$
I need proof of $f'$ is not continuous at $x=0$. And I need to describe it and say the requisite to be continuous.
|
We have
For $x\neq 0$, $f'(x)=2(1+x\sin(\frac{1}{x}))-\cos(\frac{1}{x})$
and
$f'(0)=\lim_{x\to 0}\frac{f(x)}{x}=0$.
but
$\lim_{x\to 0}f'(x)$ doesn't exist since
$\lim_{n \to +\infty}f'(\frac{1}{2n\pi})=1$
and
$\lim_{n \to +\infty}f'(\frac{1}{2n\pi+\frac{\pi}{2}})=2$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "calculus"
}
|
Efficient sorting when you only want the best
I have a `list` of 5000 items that are sorted using a custom algoritm.
I only need the best one, i.e. `list[0]` after the sort has completed.
So I need an algoritm that takes the first item of the list, compares it to the second item and then compares the better one of these two, with the third item etc. Just one loop through the whole list (order n).
Which sorting method in c# should I use for this rather common scenario?
I believe the `Sort(..)` algoritm that I currently use is very inefficient for this purpose.
|
I found the `MaxBy` of MoreLinq with selection, projection, source and key somewhat too complicated and just used my own code as an extension method:
public static T GetBest<T>(this List<T> list, IComparer<T> comparer)
{
if (list == null) throw new ArgumentNullException("list");
if (comparer == null) throw new ArgumentNullException("comparer");
if (list.Count > 0)
{
T best = list[0];
for (int i = 1; i < list.Count; i++)
{
if (comparer.Compare(best, list[i]) > 0)
{
best = list[i];
}
}
return best;
}
return default(T);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, sorting"
}
|
Get Storing updated rows and previous rows as well
Let's suppose I have table as :
column_1 | column_2 | column_3 | column_4
abc 12 23 34
abc 01 12 45
I am looking for query something like
insert into table(column_1,column_2,column_3,column_4) values(List of updated rows i.e select (do some logic here of changing value of column_1) from where column_1='abc')
Output should be as :-
column_1 | column_2 | column_3 | column_4
abc 12 23 34
abc 01 12 45
xyz 12 23 34
xyz 01 12 45
|
You can do it with another select from you insert. it not necessary to use insert into ... (...) values(..). You can use select as well as your value.
insert into table(column1,column2,column3,column4)
select 'xyz' as column1,column2,column3,column4
from table
where column1 = 'abc'
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "mysql, sql, database"
}
|
youtube autoplay is not working with iframe
i have php function which generate youtube code to display video but auto play is not working properly
function get_youtube_embed($youtube_video_id = 0, $auto = 0) {
$embed_code = "";
if ($auto == 1) {
$embed_code = '<iframe width="589" height="342" src=" . $youtube_video_id . '?autoplay=1" frameborder="0" allowfullscreen></iframe>';
}
else {
$embed_code = '<iframe width="589" height="342" src=" . $youtube_video_id . '" frameborder="0" allowfullscreen></iframe>';
}
return $embed_code;
}
Thanks
|
Your code is alright, try doing it by hand, without Javascript. Most likely that the way to set autoplay is wrong in your code.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "php, youtube"
}
|
Combining child class lists to parent class list
I have a parent class X and two lists of child classes X1 and X2 (X1 and X2 derive from X). Is there an easy way to combine the lists of X1 and X2 into a list of Xs?
I could loop over the lists of X1 and X2 and add then to the list of X but this seems a bit cumbersome.
|
LINQ can do this conveniently with
var both = list1.Cast<X>().Concat(list2.Cast<X>()).ToList();
or with
var both = ((IEnumerable<X>)list1).Concat((IEnumerable<X>)list2).ToList();
but it's looping nonetheless -- just under the covers.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 5,
"tags": "c#, linq, c# 4.0"
}
|
MySQL select total row number in query with group by
I need to know total results of a query, I'm using COUNT() the problem is that inside this query I have a GROUP BY
instead getting 5 as results I get 5 rows with total number of results for each row
SELECT COUNT(c.id) AS tot
FROM contributors AS c LEFT JOIN contributors_info AS ci
ON c.id = ci.idcontributor
WHERE c.state = 'active'
GROUP BY c.id
ORDER BY c.id ASC
my query result is
|c.id|
| 1 |
| 2 |
| 1 |
| 1 |
| 1 |
|
Try below query.
SELECT COUNT(*) as tot FROM(
SELECT c.id
FROM CONTRIBUTORS AS c LEFT JOIN contributors_info AS ci
ON c.id = ci.idcontributor
WHERE c.state = 'active'
GROUP BY c.id
ORDER BY c.id ASC
) AS tmp
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "mysql"
}
|
Can SolrNet do exact field value matches?
The one thing I can't find in SolrNet is exact field matches. So, if my field contains exactly "My Name is James Bond," then I'm looking for something like this:
new SolrQueryExactMatch("FieldName", "My Name is James Bond");
I'm effectively looking for SQL-like searching:
WHERE FieldName = 'My Name is James Bond'
I'm wondering if this is a function of indexing? Do we index the field, but not tokenize it? If "My Name is James Bond" was a single token, I'm wondering if that would have the same effect?
Does such a thing exist in SolrNet?
|
I needed to store the field as a `string` not as `text` and then use SolrQueryByField on the value.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "solrnet"
}
|
integrating with arctanh
What is the best way to integrate $\int_{0}^{v}\frac{dv}{g - Dv^2}$. The book I'm studying uses arctanh, but it seems it would be a bit simpler by rewriting it into a form of $\int\frac{du}{a^2 - u^2}$ which results in an expression using natural logarithms? Are they equivalent?
|
They are indeed equivalent. The hyperbolic trigonometric functions can be written as combinations of exponentials:
$\begin{eqnarray}\sinh(x) & = & \frac{e^x - e^{-x}}{2}\\\ \cosh(x) & = & \frac{e^x + e^{-x}}{2}\\\ \tanh(x) & = & \frac{e^x - e^{-x}}{e^x + e^{-x}}\end{eqnarray}$
and so logically their inverses can be written with logarithms:
$\begin{eqnarray}\sinh^{-1}(x) & = & \ln(x+\sqrt{x^2+1})\\\ \cosh^{-1}(x) & = & \ln(x+\sqrt{x^2-1})\\\ \tanh^{-1}(x) & = & \frac{1}{2}\ln\left(\frac{1+x}{1-x}\right)\end{eqnarray}$
As to whether the integral with an arctanh function is "simpler" than the one with logarithms or not probably depends a lot on what you're using it for, and whether the respective functions make sense in the domain you're integrating over.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "calculus"
}
|
DataTable group by separated by comma
I have a datatable that looks like the following
cname tname text allowgroupping
A M good Yes
A M bad Yes
A M ugly Yes
B N sick No
B N lovely No
C R pathatic Yes
I want to group the datatable by the first column `cname` so the result will look like
cname tname text allowgroupping
A M good,bad,ugly Yes
B N sick,lovely No
C R pathatic Yes
I have done it by looping each column and doing a lot of checks, but how can I do it using LINQ and save the result to a datatable?
|
You can do something like this:
var query = from row in dataTable.AsEnumerable()
group row by row["cname"] into g
select new { cname = g.Key,
tname = g.First()["tname"] ,
text = String.Join(", ", g.Select(r=>r["text"].ToString()).ToArray()),
allowgrouping = g.First()["allowgroupping"]
};
foreach (var row in query)
{
resultDataTable.Rows.Add(row.cname, row.tname, row.text, row.allowgrouping);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, linq, datatable, group by"
}
|
Outlook MAPI folders not working in 2013, were as the same code is working good in 2007 version
I am using outlook 2013 and the below code gives me the error as given in the below screen shot.
Sub Testing()
Dim olApp As Outlook.Application
Dim olNS As Outlook.Namespace
Dim olFol As Outlook.Folder
Dim abc
Set olApp = New Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
'Set olFol = olNS.PickFolder
Set abc = olNS.Folders.Item("[email protected]")
End Sub
Error details is given below.
Run Time error '-2147221163 (80040155)'
Method 'Folders' of object '_NameSpace' failed
I have tried a lot of combination. this works in 2007 and below version.
|
The error is REGDB_E_IIDNOTREG.
Is this a click-to-run Outlook 2013 installation?
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "excel, vba, outlook, outlook 2010"
}
|
How to tell if RAD Studio 10 Seattle Update 1 has been installed?
I Uninstalled RAD Studio 10 Seattle in preparation for upgrading to Update 1. I just reinstalled RAD Studio 10 Seattle but I don't remember if I ran the Update 1 ISO or the original ISO.
Is there a quick way to tell if RAD Studio 10 Seattle Update 1 has been installed?
|

> Delphi 10 Seattle and C++Builder 10 Seattle Subscription Update 1
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -2,
"tags": "delphi, delphi 10 seattle"
}
|
Bash Script to Rename Files Based on Size
I have a bash script that renames files in a folder according to input from a command prompt:
echo "Please rename and press enter" read rename
if [ -z "$rename" ]; then
printf "no caption was selected, aborting!\n"
exit 1
fi
printf "rename is $rename\n" count=1
for i in *.jpg; do
j=printf "%04d" $count
j="$rename"$j".jpg"
count=$((count + 1))
mv "$i" $j
done
fi
shift
done
How can I modify this script so that the files in the folder are renamed according to their size?
If I sort the files according to size, they will look like this in the folder:
a009 978kb
a001 567kb
a003 499kb
a008 432kb
So I want the resulting files to be renamed:
a001 978kb
a002 567kb
a003 499kb
a004 432kb
|
The main trick is to replace
for i in *.jpg
with
for i in $(ls -S *.jpg)
however, as Kusalananda's pointed out, this assumes "educated" file names (no spaces, no control characters), so here is a different approach:
count=1
ls -S --escape *.jpg | while read f; do
n=$(printf "%04d" $count)
((count++))
mv --no-clobber "$f" "$rename$n.jpg"
done
`-S` sorts by decreasing file size
`--escape` prevents names with embedded newlines causing damage
`--no-clobber` prevents overwriting destination files in case the script is run twice
P.S. Ole Tange's answer is a very nice efficient way of doing the same, but you probably won't see the difference unless you routinely rename thousands files.
|
stackexchange-unix
|
{
"answer_score": 4,
"question_score": 5,
"tags": "rename"
}
|
I need help solving the differential equation $y'(t)+7\sin(t)y(t)=(te^{\cos(t)})^{7}$
I need help solving this differential equation
$$y'(t)+7\sin(t)y(t)=(te^{\cos(t)})^{7}$$
What I've tried:
$$\implies e^{-\cos(t)}y'(t)+e^{-7\cos(t)}7\sin(t)y(t)=t^{7}$$ $$\implies (y(t)e^{-7\cos(t)})'=t^7$$ $$\implies y(t)e^{-7\cos(t)}=\int t^7 dt = \frac{t^8}{8}+c$$ $$\implies y(t)=\frac{e^{7\cos(t)}t^8}{8}+c$$
However, when I use Maple's dsolve I get a different result. Can anyone see where I've gone wrong?
)$ on your result.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 0,
"tags": "ordinary differential equations, maple"
}
|
How do I use TextWatcher to check for a specific string of characters instead of just one character?
I'm new to both Android and Java. My app needs to be able to check what the user is typing as they are typing it. If the user types in a predetermined word that has been flagged, an event needs to occur before the user presses a button. It seems like the best choice for this would be a TextWatcher and an addChangedTextListener. I haven't been able to figure out how to get it to check a sequence of characters (a word). For instance, if the flagged word was "very", when the user types "It is very warm." in the edittext, the program should be able to recognize that "very" was typed and alert the user in some way.
I hope I was able to make this clear without using any code. Any help that could be given would be greatly appreciated.
|
This is the simplest form of doing it via **TextWatcher** :
String word = "very";
TextWatcher watcher = new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
String tmp = s.toString().trim().toLowerCase();
if(tmp.contains(word.toLowerCase())){
//inform the user here
}
}
};
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, android, android edittext, textwatcher"
}
|
How to remove blank spaces from SQL*Plus query?
My query below being called from sqlplus is returning lot of spaces in the end of each value, how can I remove it?
See example below: * I substituted the values with x
x ,x
,x ,x ,x,x
x
My query is:
set linesize 1000
set trimspool on
set trimout on
set pagesize 0
set colsep ,
set feedback off
spool /result.csv
SELECT process_id,
x1,
x2,
x3,
x4,
x5,
x6,
x
FROM x
WHERE x IN ('x');
|
The simplest way is to concatenate the columns with the commas in between, rather than using `colsep`:
select process_id
||','|| x1
||','|| x2
...
Note that you only have the comma in the concatenation strong, not between the columns. You end up with a single column in the reult.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "oracle, sqlplus"
}
|
Bitwise AND: why do I get this behaviour?
I have this simple program here:
#include <iostream>
#include <bitset>
using namespace std;
int main() {
unsigned char a = 0b11100111;
if((a & (1<<2)) == true) // THIS IS THE LINE
cout << "Entering if block!" << endl;
else
cout << "Too bad, maybe next time.." << endl;
bitset<8> x(a & (1<<2));
cout << x << '\n';
}
Can you tell me why this `if((a & (1<<2)) == true)` outputs: **Too bad, maybe next time.. 00000100**
While this `if((a & (1<<2))` outputs: **Entering if block! 00000100**
I'm compiling with g++ -std=c++14.
|
`0b100` is a number and shouldn't be compared against true.
Try changing your if statement to:
if (a & (1<<2))
or equivalently
if((a & (1<<2)) != 0)
since in an `if` statement, anything not zero is considered `true`.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c++, bit manipulation, bitwise operators"
}
|
Simple Error '(' expected
public void displayResults
{
for(int i = 0; i < arrayLength; i++)
{
System.out.printf("Value %d = %.6f\n", i, list[i]);
}
System.out.printf("Sum of all values = %0.6f\n", sum);
System.out.printf("Average of all values = %0.6f\n", average);
System.out.printf("Largest value = %0.6f\n", largest);
System.out.printf("Smallest value = %0.6f\n", smallest);
}
I am getting the good old `error: '(' expected`
at where the `{` should be, I really don't see whats wrong with what I have. Been staring at this same error for almost a hour. really hoping a new set of eyes can see the issue.
public void displayResults
==> {
for(int i = 0; i < arrayLength; i++)
{
|
public void displayResults ()
^^
You need to add the parameter list parentheses even if you have no parameters.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 0,
"tags": "java"
}
|
Compile 32bit kernel on 64bit machine
I'm trying to compile a kernel for a 32bit single-core Intel Atom machine. Needless to say, the compile is taking inordinate amounts of time. It's been going for 2 hours and it's still only halfway through the driver modules.
Compiling a kernel on my main desktop only takes 15 minutes but it's a 64bit machine. Can I cross compile to generate a 32bit kernel package from the better machine?
|
While the kernel can be cross-compiled, the easiest way is to create a 32bit (i386) chroot and build it in there.
Install `ubuntu-dev-tools`:
$ sudo apt-get install ubuntu-dev-tools
Create an i386 chroot:
$ mk-sbuild --arch=i386 precise
(You will probably have to run that twice. The first time, it installs `schroot` etc. and sets up `mk-sbuild`)
Then enter the chroot:
$ schroot -c precise-i386
And build the kernel, as you would, normally.
|
stackexchange-askubuntu
|
{
"answer_score": 28,
"question_score": 23,
"tags": "kernel, compiling, architecture"
}
|
Execute javascript inside iframe document
I am trying to execute javascript which is inside an iframe document using Dotnetbrowser 1.11.
In the following code returnValue.IsFunction() returns false.
JSValue returnValue = browser.ExecuteJavaScriptAndReturnValue(FunctionName);
if (returnValue.IsFunction){//something}
ExecuteJavaScript works fine if the script is in the current loaded document. But when the script is loaded in an iframe document which is inside the current loaded document, the same is not found.
Please assist regarding the same.
|
ExecuteJavaScriptAndReturnValue() method has an override which allows executing JavaScript code in a specific frame by using its id number. To get a list of child frames ids on a currently loaded document you can use Browser.GetFramesIds() method. Here is a code sample:
browser.FinishLoadingFrameEvent += (s, e) =>
{
if (e.IsMainFrame)
{
List<long> framesIds = e.Browser.GetFramesIds();
JSValue returnValue =
e.Browser.ExecuteJavaScriptAndReturnValue(framesIds.First(), FunctionName);
if (returnValue.IsFunction){//something}
}
};
Take into account that Browser.GetFramesIds() should be used after completely page loading, either the list will contain only already loaded ids.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "dotnetbrowser"
}
|
Block users coming from a particular URL after clicking banner ad
I want to block users coming from a particular URL. our adbanner is shown in many websites. People who click our banner on a website are directed to our registration page. I don't want the page to be shown for people who click our ad on a particular website say < How can I implement this restriction ? Thanks in advance
|
You can check the value of the variable `$_SERVER['HTTP_REFERER']` for the domain you want to restrict.
Something like this can work:
$bad_domain = 'abc.com';
if (stripos($_SERVER['HTTP_REFERER'], $bad_domain) !== false) {
// block user, they came from $bad_domain
}
It's easy to spoof the referer string in a browser, or install a plugin to leave it blank but many people don't have such restrictions. Also, if they clicked from an `https` page, the referer is also not sent.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "php"
}
|
Problem when mixing TabNavigator and StackNavigator
I have 2 Stacks in a TabNavigator. The structure is as below
StackA
\- Screen A
\- Screen A1
\- Screen A2
StackB
\- Screen B
\- Screen B1
\- Screen B2
TabNavigator
\- StackA
\- StackB
Now, in screen A, I want to navigate to screen B1. I just use navigate('Screen B1'), the navigating looks successfully. But when I click back button (I my god) I'm on StackB which is showing screen B.
I really expect seeing screen A in this case.
|
To do this, you will have to create a custom `backButton` that let's your screen know where you navigated from. An example would be:
this.props.navigation.navigate('ScreenB1', {lastScreen:"ScreenA1"}) //navigating from stack to other stack with param
Then, the `backButton` would check about the `lastScreen` variable and see if it's defined.
<BackButton onPress={({navigation})=>{
let lastScreen=navigation.state.params.lastScreen
if (lastScreen) return navigation.navigate(lastScreen)
else navigation.pop(1)
}
}
As i dont know how your code looks like i wrote a general situation, but you can change it however you need.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "react native, react native navigation"
}
|
Read a text file using LinQ and then insert it into SQL Table using LinQ To SQL
as you see this is a simple code to read a file and print the lines separated by comma into a listbox. I'm just starting to learn LinQ and I need some examples using this easy one. I need to convert this code to LinQ and then insert the results into a SQL Table using LinQ to objects. I believe I can do the insertion but I need to save this with Linq to an array or list so I can point it to the right direction. Please any help will be highly appreciated.
StreamReader file = new StreamReader(@"C:\Files\Archivo.txt");
string line;
while((line = file.ReadLine()) != null)
{
string[] fields = line.Split(',');
foreach (string word in fields)
{
listBox1.Items.Add(word);
}
}
|
Without proper testing, I believe this will help:
File.ReadAllLines(@"C:\Files\Archivo.txt").SelectMany(s => s.Split(',')).ToList();
This will read all lines from your file, split on the ',', flatten the array and return a `List<string>`. You can then even add an extra `Select` at the end to enumerate the collection and create you objects from this. There are plenty of examples of how to do that on stackoverflow and elsewhere on the internet.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "sql, linq, linq to sql, streamreader"
}
|
Golang : convert Byte slice array to integer array
In Golang, the code `[body, err := ioutil.ReadAll(resp.Body)], the ioutil.ReadAll()` returns a byte Slice array, based on the documentation.
This is stored in the variable 'body'. My question is how to convert this byte Slice array, to an array of Integers.
|
I just found some code that does what I was wanting:
import "fmt"
import "strconv"
func main() {
var t = []string{"1", "2", "3"}
var t2 = []int{}
for _, i := range t {
j, err := strconv.Atoi(i)
if err != nil {
panic(err)
}
t2 = append(t2, j)
}
fmt.Println(t2)
}
* * *
So this code, does do what I want.
BUT l am disappointed in Golang, for not having a nice one liner that could do this kind of conversion. Certain basic things like this, should be packaged up for the programmer, and not have to do this kind of 'low' level programming.
Note, i still like Golang, they had done a lot to make a better C type language that has higher level Data Types when compared to C and also make some things more dynamic compared to C. SO just disappointed they did not make a High Abstraction for this kind of case, which comes up quite a bit.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -4,
"tags": "http, go"
}
|
Ruby/Rails break out of method inside loop
I have two methods I use to sync categories to a 3rd party service. The first method loops through everything and the second actually exports each category. If there is a failure, how do I break out of the loop completely?
def export_all
Category.find_each do |c|
export_category(c)
end
end
def export_category(c)
begin
sync_category(c)
rescue Exception => e
# break out of `export_all` loop
end
end
|
You have a couple of options for breaking out of a loop. Most simply, you can use `break` or `return` in your looping code.
In the context of your example above, it might be easier, if possible within the larger context of your application, to do the following:
def export_all
Category.find_each do |c|
begin
export_category(c)
rescue SpecificErrorIsBetterThanGenericExceptionIfPossible => e
break
end
end
end
def export_category(c)
sync_category(c)
end
It appears from your question that you want the loop in your export_all method to break when an exception is encountered. In such a case, I prefer my break/error handling code at that level.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "ruby, ruby on rails 3, rescue"
}
|
Extend Experience Profile Search with unique identifier
All of our contacts are identified by a unique customer id. By default in the Experience Profile dashboard, we can search by name or e-mail.
**How can I extend this functionality so that the identifier gets searched too?**
_ in your implementation and customize the implementation of the `private SearchResults<IndexedContact> QueryIndex(IProviderSearchContext ctx, ContactSearchParameters parameters)` method.
|
stackexchange-sitecore
|
{
"answer_score": 2,
"question_score": 2,
"tags": "experience profile"
}
|
What's the best way to mix Ruby and other languages? (Especially C++)
I'm learning Ruby, and I'm starting to play with building extensions in C. I have _Programming Ruby The Pragmatic Programmers' Guide_ and so I can follow that for the basic nuts and bolts. What I was wondering is if there already existed some nifty frameworks/whatever to help interoperability between Ruby and other languages, with C++ being the most important for me. I've tried googling, but the results focus on language comparisons, rather than language interoperability.
TIA,
Andy
|
Take a look at SWIG. It's a nice framework for integrating C and C++ programs with other programs written in higher level languages. It was originally written to support Python, TCL, and Perl, but has been expanded to support Ruby as well.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "c++, ruby, interop"
}
|
WYSIWYG web scraping/crawling setup using Javascript/html5?
My goal is to allow less experienced people to setup the required parameters needed to scrape some information from a website.
The idea is that a user enters an URL, after which this URL is loaded in a frame. The user should then be able to select text within this frame, which should give me enough information to scrape this information again when this specific text changes dynamically.
The question is, if it's even possible to detect what part of the source of an external site corresponds to the selection of the user in a frame?
If not, are there any alternatives ?
Thanks in advance.
Regards, Tom
|
The short answer is no. If you don't control the content in the iframe, there's not much you can do to interact with it.
However, you could make a bookmarklet that does something like you're describing, or a browser plugin.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -1,
"tags": "javascript, html, screen scraping, wysiwyg, web crawler"
}
|
CSS adjust button width to text
I have a problem in my button width. my form is able to switch language. For some language the content of the button is longer then the button width, How can I adjust the button width proprety to the text lenght ? Here is my CSS :
html .formRowSubmit input[type="submit"] {
width: 26%;
margin: 5px 0% 5px ;
margin-bottom: 10px;
height: 25px;
border-radius: 3px;
outline: 0;
-moz-outline-style: none;
background: #CAD722;
border: none;
color: white;
font-size: 10px;
font-weight: 150;
cursor: pointer;
transition: box-shadow .4s ease;
}
|
You should try setting a `min-width` instead of a width, this will let the button expand if need be. Once you do this you should also set some horizontal padding so the text isnt butted up to the end like so:
input[type="submit"] {
min-width: 26%;
padding: 5px 15px;
}
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "css"
}
|
Merge Laravel collections keys in only string
I have this Laravel 5.3 tinny collection:
Collection {#325
#items: array:8 [
0 => 2638
1 => 2100
2 => 5407
3 => 2970
4 => 4481
5 => 1611
6 => 5345
7 => 50
]
}
And I want combined in only string the values, I need this:
"2638,2100,5407,2970,4481,1611,5345,50"
|
use implode <
if $collection is the value you have shown then
`dd($collection->implode(','));` should give the expected result
And if it's a multi-dimensional array, `implode` can also accept first arg as the key name:
$collection = collect([
[ 'title' => 'Hello world' ],
[ 'title' => 'Another Hello world' ]
]);
$collection->implode('title', ',')
|
stackexchange-stackoverflow
|
{
"answer_score": 27,
"question_score": 16,
"tags": "php, laravel, laravel 5, laravel 5.3"
}
|
Springboot executable jar error using java -jar
using command `/opt/jdk1.8.0_211/bin/java -jar webprx.jar` get this error: `Error: Invalid or corrupt jarfile webprx.jar`
jar was build with mvn clean package and mvn install
Pom
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
</plugins>
</build>
<packaging>jar</packaging>
|
Remove the `executable` configuration.
From the documentation this makes it executable by `*NIX` systems.
> Make a fully executable jar for *nix machines by prepending a launch script to the jar.
>
> Currently, some tools do not accept this format so you may not always be able to use this technique. For example, jar -xf may silently fail to extract a jar or war that has been made fully-executable. **It is recommended that you only enable this option if you intend to execute it directly, rather than running it with java -jar or deploying it to a servlet container**.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "maven, spring boot, java 8"
}
|
If I need to create a large format poster @ 120 dpi can the image on the poster be @ 120 dpi as well?
If I need to create a large format poster that's supposed to be printed at 120 dpi can the image on the poster have an effective DPI of 120 dpi as well?
|
Printing at X resolution, placed images will not benefit from being greater than X effective resolution.
If there is a forced limitation on the resolution at the output, then everything will end up at that resolution anyway. In fact, there may be a benefit in starting out with the exact output resolution because then you at least have some control over how the images are subsampled, rather than leaving that choice up to the RIP or whatever software you use to export the subsampled production file.
|
stackexchange-graphicdesign
|
{
"answer_score": 0,
"question_score": 0,
"tags": "images, resolution, dpi"
}
|
Apache regular expression on RewriteRule, "or" syntax
I'm tiring to get all string before first slash when an url ends with "word1" or "word2", and im using this code:
RewriteRule ^(.+)/word1|word2/?$ index.php?query=$1 [NC]
I haven't any problem with url that have "word1" on his ends, but if the url ends with "word2", Apache dose not return any value to "query" variable
|
You need to group the alternations in your expression:
^(.+)/(?:word1|word2)/?$
Without the grouping your expression means:
`^(.+)/word1` **or** `word2/?$`
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "regex, apache"
}
|
Node js Uncaught SyntaxError: Unexpected identifier
When I call node filename.js then it return an error.(Uncaught SyntaxError: Unexpected identifier).
 5) ?
What does this line of code mean?
#define NAME ((LPCSTR) 5)
If I define a variable, `NAME *tmp`, then use it like this:
((LPCSTR) 5) *tmp;
What does that code do?
Note: `LPCSTR` is `typedef __nullterminated CONST CHAR *LPCSTR`
|
That's a simple cast, it converts 5 to a character pointer (`__nullterminated CONST CHAR *`)
That's probably undefined behaviour by the standard, but sometimes used in real life.
* To address specific physical addresses on your machine - for example the kernel has to do this to configure cards, onbard chips, etc...
* To send special values in arguments or return values.. for example the call normally expects a pointer in the second argument, but if you pass "5" it meants something else.
As you can see, it's really a pointer, so what you've tried, `NAME *tmp;`, won't compile.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c, windows"
}
|
jQuery masonry issue
I'm having a bit of bother with my web page. I'm using the jquery plugin masonry and it works great however I'm having an issue which I can seem to fix.
Basically, I hide the div which the masonry is contained within when a button is clicked which works fine and when I click another button to bring it back it appears again. So that's all working fine BUT if I resize my browser before clicking to bring back the masonry, all of the masonry tiles are positioned one on top of the other in the top left corner. When I inspect with firebug the correct positioning is added to each div but it seems that css is ignoring these yet when I refresh the masonry moves each tile to where it should be...any idea on how I can fix this? Thanks in advance!
|
Fixed it - I just called the masonry function again! :) Thanks anyways!
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery, css, jquery masonry"
}
|
How to change URL of browser window from within frameset frame?
I have an html document using frames. This is the code:
<frameset cols="10%,*" border="0">
<frame src="left_page.html">
<frameset rows="50%,50%" border="0">
</frameset>
</frameset>
Then in left_page.html, this is my code:
<form action="http:www.google.com">
<input type="submit" value="GotoGoogle" />
</form>
The problem is, when I click the button, it loads google.com in the left frame, not the entire screen. How can I get the web page to display on the entire screen and not just the left side frame?
|
You need to specify the target frame (_top is the full page)
<form action="http:www.google.com" target="_top">
<input type="submit" value="GotoGoogle" />
</form>
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "html, frames, frameset, html frames"
}
|
How can I mock to an @autowired @Qualifier attribute in a Service?
I have a service with an attribute like this:
@Autowired
@Qualifier("test")
private String test;
This attribute come from context xml file.
I become nothing in unit test, probably that a correct behavior in unit test. But can I mock this attribute to become a value?
for example:
when(test).thenReturn("a string");
Thanks Regards
|
Based on your comment making the field public is an option. You can just set it afterwards:
myMock = Mock(MyClass)
myMock.test = "foobar"
Besides that you could add a setter, leaving the field private. Or you could try `@InjectMocks` or Spring's `ReflectionTestUtils`, both from the accepted answer here.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "spring, junit, mockito"
}
|
binary file generated by gcc objcopy has a size much larger than sum of 'text' and 'data' in gcc size output
I use `objcopy -S -g -O binary test.elf test.bin` to get a `.bin` file from `.elf`.
$ ll test.bin
-rwxr-xr-x 1 hongzhuwang md_psw 1472320 Oct 28 19:07 test.bin
$ size test.elf
text data bss dec hex filename
173062 6328 6605424 6784814 67872e test.elf
The size of `test.bin` is apparently larger than the sum of _text_ and _data_ in `test.elf`. Why is there such a huge difference? Which sections will `objcopy` copy from `.elf` into `.bin`?
|
I found some `NOBITS`sections between `PROGBITS` sections in the linker script. The binary file will occupy a continuous address space, so the `NOBITS` sections' space are filled by zero by `objcopy`. I think that's the root cause for the difference.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "gcc, elf, objcopy"
}
|
Nginx : Error_log and Access_log max size
i need to define max size of error_log and error_access in Nginx.conf. i found that error_log has size of 400gb for moment my configuration is pretty basic `error_log /home/ubuntu/logs/nginx-logs/error.log ` is there a way to specify this ?
|
I used logs Rotation to solve the issue : Answered by Ivan Shatsky
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "nginx, nginx config"
}
|
Are the Githyanki and the Githzerai a single race with two subraces, or two separate races?
In _Mordenkainen's Tome of Foes_ , the introduction to "Chapter 4: Gith and Their Endless War" states (p. 85; emphasis mine):
> If **the two races** were ever to team up against the illithids, [...]
Later, under the "Githzerai" section, it says (p. 93):
> The githzerai were born as a race [...]
These two quotes seem to imply that the githyanki are (lorewise) two separate races. However, under the "Vlaakith's Dilemma" subheading in the description of the githzerai, it says (p. 87):
> Long gone are the days when **the gith race** was fully embroiled in conflict.
**Are the gith actually one race with two subraces, or are they two separate races?**
I would prefer 5e sources that distinctly mention this, but if none are available, then sources from other editions are acceptable.
|
### The Githyanki and Githzerai are warring factions of the same race, Gith.
From _Mordenkainen’s Tome of Foes_:
> But after they won their freedom, two factions among the gith disagreed on what kind of civilization they would forge.
These factions are later described as the Githyanki and the Githzerai.
Further, _MToF_ lists the two as subraces of Gith. No matter which you choose to play, the race details state, "Your character shares the following traits with other gith", then goes on to detail the specifics of each subrace.
So in the mechanical sense, they are certainly one race, but lore wise, they may be called different races of the same species in the same way we speak of different races of human here in the real world.
As I mentioned in this answer, there is no reason to believe the Githyanki and Githzerai have any significant differences in biology.
|
stackexchange-rpg
|
{
"answer_score": 19,
"question_score": 15,
"tags": "dnd 5e, lore, races, gith"
}
|
Combining multiple 1D arrays returned from a function into a 2D array python
I m a little new to python. I have a function named featureExtraction which returns a 1-D array for an image. I need to stack all such 1-d arrays row wise to form a 2-d array. I have the following equivalent code in MATLAB.
I1=imresize(I,[256 256]);
Features(k,:) = featureextraction(I1);
featureextraction returns a 1-d row vector which is stacked row-wise to form a 2-d array. What is the equivalent code snippet in python?
Thank You in advance.
|
Not sure what you're looking for, but maybe `vstack` or `column_stack`?
>>> np.vstack((a,a,a))
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> np.column_stack((a,a,a))
array([[0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5],
[6, 6, 6],
[7, 7, 7],
[8, 8, 8],
[9, 9, 9]])
Or even just `np.array`:
>>> np.array([a,a,a])
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 5,
"tags": "python, arrays, numpy"
}
|
How do I deploy a clickonce application through a website?
I published the application to my file system to the web application's files (I'm running it on visual studio 2010) and made the application "download" the "setup" file to my desktop. But when I tried to execute the setup – it was missing files. Is the only way to deploy a clickonce application to have users download more than one file?
|
No need to download any files - just point to the setup.exe file (local or web). ClickOnce is just an packaging format with the ability to update from either local path/network spare or an URL. If you want to be able to install the app from a website, just put the clickonce files on an IIS and install from there e.g. c:\inetpub\wwwroot\myclickonceapp and point to address]/myclickonceapp/setup.exe . Remember to setup your update URLs/paths correctly in the project properties - this may be causing your problems when installing locally.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "asp.net, visual studio 2010, clickonce"
}
|
Stop the Binging Noise when alt is used in a hotkey
When you press alt+almost Any other key it makes binging noise. The noise says "you've tried to do something you can't"
I'd like to use the alt key in several combinations as a keyboard shortcut for a web app.
Despite there being something to do when alt+* is hit the bing is persistent.
Is there a way to keep the bing from sounding in JavaScript?
Edit: ~~This is probably just a windows issue~~ This is an issue in chrome.
|
I've found that registering the key you wish to use as an accessKey will prevent chrome from emitting the Error noise _BING_.
Problem has been solved by using a very blank anchor tag with the accessKey assigned to my desired hot key.
<a accessKey=*>
Solution discovered thanks to this post: Managing JavaScript hotkeys in Chrome Browser
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "javascript, keyboard shortcuts"
}
|
Write a java program to restart glassfish every day
Glassfish would hang every one or two days, I had to manually restart the server. This is quite annoying and I think the problem is that the server run out of memory? So I am been thinking to write a java program to auto restart the server every day. Any one also experience the same problem? Thanks in advance
|
Not sure of glassfish. But in our case, we have a series of commands in order to stop and restart a server.
Do the following:
1. Create a bat file say `abc.bat` containing commands like below:
kill - all - tasks
stop - server
SLEEP 10 --> Number of seconds taken by the server to stop. You can put more value for safety.
start - myserver
2. Create a java say `ServerStopStart.java` using process.
Process p = Runtime.getRuntime().exec(TRIGGER_MY_BATCH_FILE);
3. Using crontab or some other scheduling mechanism, schedule to run the ServerStopStart.java at mid-night or any other appropriate time when user load is NIL.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, glassfish"
}
|
Is the normal force the reaction force?
There is a box on the surface of earth. The earth exerts a force to the box (black arrow). The box exerts a reaction force to the earth(brown arrow). But this reaction force is exerted to the earth not the box, so where is the normal force? If the reaction is the normal force then why they put the arrow starting in the box upwards and not starting in earth? (second diagram).
, not the third law.
|
stackexchange-physics
|
{
"answer_score": 4,
"question_score": 2,
"tags": "newtonian mechanics, forces, free body diagram"
}
|
Tikz draw Integral
},0) arc(0:180:{sqrt(2)}) coordinate(BL) node[above left,black]{$-\sqrt{2}$};
\draw[fill=gray,thick,draw=blue] (1,1) coordinate(TR) node[above,black]{$B$} arc(45:180:{sqrt(2)})
node[below]{$A$} -- cycle;
\draw[-latex,thick] (-2,0) -- (2,0) node[below]{$x$};
\draw[-latex,thick] (0,0) -- (0,2) node[left]{$y$};
\draw[dashed] (0,1) node[left]{$1$} -- (1,1) -- (1,0) node[below] {$1$};
\path (BL) -- (TR) coordinate[pos=-0.2] (start) coordinate[pos=1.2] (end);
\draw[blue,thick] (start) -- (end) node[above left,black]{$d$};
\end{tikzpicture}
\end{document}

Just checked my site < in this tool < using the tablet setting Apple IPad 768x1024.
For this size the navigation menu seems to be too big, cause it is displayed in two lines. Thats why I would like to set the responsive breakpoint to 800px width so that instead of the navigation menu the navigation for mobile version is displayed (≡ menu symbol on the top, right corner).
What do I have to change in the responsive.css to get this done?
Thx for your tips. BR Heidi
|
There's nothing to change in **responsive.css** but instead you will be modifying the main style sheet @ style.css
Simply replace all the instances of **719px** to **800px**
!enter image description here
Now replace all the instances of **720px** with **801px**
* * *
You can copy paste the whole style sheet in a notepad ( or any similar tool ) and then start replacing just the **719px** part and **720px** and you should be good.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "css, wordpress, twitter bootstrap"
}
|
How to compress and download directory from remote to local?
I have a directory on my Ubuntu server that has many subdirectories and files. I want to download entire folder, so I used this command:
scp -r [email protected]:/path/to/target_directory /path/to/local_directory
So target_directory ends up in /path/to/local_directory/target_directory. This is fine so far.
**The problem:** target_directory is not so big (around 50MB) but has many tiny files. `scp` download files one by one, which takes too long. So I'm thinking may be there's a way to compress the directory and download it (optionally, without keeping the compressed file on the server). I think it's achievable but not sure how.
**Note:** I use Mac for my local machine.
|
You don't really need compression, if the problem is that there are many small files. Use `tar` to make an archive on Ubuntu, and instead of saving the archive to a file, send it to stdout (the default for Ubuntu's GNU tar when there's no file specified) and read the `tar` file on the other end:
ssh ubuntu-server tar c -C /path/to/target_directory . | tar xvf - -C /path/to/local_directory
Or use a smarter tool like `rsync`.
|
stackexchange-askubuntu
|
{
"answer_score": 1,
"question_score": 0,
"tags": "compression, scp"
}
|
Apple Match O-Linker Error when testing on iPad 4th gen
I'm using the Facebook iOS SDK the latest version, added `AdSupport`, `Accounts` and `Social` frameworks to my project along with the `FacebookSDK` framework. My project is targeted for iOS 5.1, works fine in the simulator, but when I try to test on my iPad 4th gen y get this:
ld: warning: directory not found for option '-L/Users/8vius/Projects/Work/Fonyk/Fonyk-iPhone/Fonyk/facebook-ios-sdk'
ld: warning: directory not found for option '-F/Users/8vius/Projects/Work/Fonyk/Fonyk-iPhone/../../Desktop/facebook-facebook-ios-sdk-6825350/build'
ld: file is universal (3 slices) but does not contain a(n) armv7s slice: /Users/8vius/Projects/Work/Fonyk/Fonyk-iPhone/Fonyk/libGoogleAnalytics.a for architecture armv7s
Any idea how I can fix this issue?
|
Ok, the problem is because the Facebook SDK isn't updated and doesn't match my current architecture for testing. To solve this issue go to Project -> Build Settings and change the valid architectures to armv7 for `Release`, `Ad-Hoc` and `Debug` (or just for the one you need right now). and set `Build Active Architecture Only` to No
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "ios, ipad, build, ios6, ios simulator"
}
|
How to get apache version in php?
I know this question has been asked/answered on this site multiple times, But my question is a little diffrent. I have already reviewed some of those posts and what I got from there is :
<?Php
echo apache_get_version();?>
I know this function returns the Apache version.
My website is on a free webhost eu5.org where they have disabled both **phpinfo()** and **apache_get_version()** And because of this I am not able to know which version I am using.
Is there any other way to get the server version in php?
Thanks!
|
This Gist provides probably the best fallback I've seen if the apache_get_version function is disabled.
Basically you need to define a function that uses the operating system to call the httpd daemon directly to get the version information. Although, in your situation, it's likely that OS commands are also disabled so this might not be terrible helpful.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php"
}
|
Decrease Visual Studio build time
I've got a Visual Studio solution that consists of about 100 projects. Most of them form a dependency hierarchy. Now if I change a single .cs for a project and build it, all dependent projects get built as well - regardless of whether they've been changed or not. Is there a way to make Visual Studio only build the changed projects? I'm wasting minutes every time I do a little change by rebuilding the whole lot. It adds up big time!
|
No, there is no good way to do this. Some _incremental_ building does sometimes occur (Visual Studio 2010 or later), but there are no guarantees.
Compile the projects that are mature into assemblies, and reference them from your unstable (currently in development) projects. If you are doing proper unit testing, this should not be a huge issue. Divide and conquer; finish the dependencies first and get them stable, then commit them to assemblies.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 7,
"tags": "performance, visual studio, time, build"
}
|
Project Euler 2 python3
I've got, what I think is a valid solution to problem 2 of Project Euler (finding all even numbers in the Fibonacci sequence up to 4,000,000). This works for lower numbers, but crashes when I run it with 4,000,000. I understand that this is computationally difficult, but shouldn't it just take a long time to compute rather than crash? Or is there an issue in my code?
import functools
def fib(limit):
sequence = []
for i in range(limit):
if(i < 3):
sequence.append(i)
else:
sequence.append(sequence[i-1] + sequence[i-2])
return sequence
def add_even(x, y):
if(y % 2 == 0):
return x + y
return x + 0
print(functools.reduce(add_even,fib(4000000)))
|
The problem is about getting the Fibonacci numbers that are smaller than 4000000. Your code tries to find the first 4000000 Fibonacci values instead. Since Fibonacci numbers grow exponentially, this will reach numbers too large to fit in memory.
You need to change your function to stop when the last calculated value is more than 4000000.
Another possible improvement is to add the numbers as you are calculating them instead of storing them in a list, but this won't be necessary if you stop at the appropriate time.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "python"
}
|
GPMC missing Hide/Show links
We currently have a single 2012 R2 server in our domain. As we're rolling out Windows 8+ machines I like using it for Group Policy Management.
For some reason the Group Policy Management Console on this server doesn't show the "Show/Hide" links in the Settings tab, so I can't fold and unfold the sections.
 in Server Manager.
|
stackexchange-serverfault
|
{
"answer_score": 6,
"question_score": 6,
"tags": "group policy, windows server 2012 r2, mmc"
}
|
What does "index" stands for in TableRow.addView (View child, int index)?
Is it meaning that you can build a table row with an empty column ?
I want to do a TableLayout like this :
+--------------+---------------------+
+ *Nothing* + LinearLayout +
+------------------------------------+
+ LinearLayout + *Nothing* +
+--------------+---------------------+
Is it possible with index property ?
TableRow topTableRow = new TableRow(context);
topTableRow.addView(xAxisScrollView, 1);
addView(topTableRow);
TableRow bottomTableRow = new TableRow(context);
bottomTableRow.addView(yAxisScrollView, 0);
addView(bottomTableRow);
|
As you can read in the documentation, it should be possible. But I would just try it. It's done in 2 minutes ;)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "android, android widget"
}
|
regex for string which consist of 1 to 4 non-zero numeric characters or 1 to 4 non-zero numeric characters and 1 alphabet
I am writing a regex for strings that consist of 1 to 4 non-zero numeric characters or 1 to 4 non-zero numeric characters and 1 alphabetic, but I am stuck in how to fix length of the alphabetic characters to one.
"(^[1-9]{1,4}$|^[[a-zA-Z][1-9]{1,4}]$)"
I tried this way, but its not working; it is validating only strings that consist of 1 to 4 non-zero numeric characters.
|
^(?:\d{1,4}|(?=\d*[a-zA-Z]\d*$)[\da-zA-Z]{2,5})$
You need a `lookahead` for this.See demo.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "javascript, regex"
}
|
error while building application Couldn't delete /output.json?
i hope you have a good day i have this problem when i try to build an application or when connect my phone to install app on it directly from Android Studio
this error shown up
any help ? thanks
|
It seems to be a problem with your build. Try running Clean Project and then Rebuild Project from the build menu.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "java, android, android studio"
}
|
how to separate a split array $input back into the 2 separate value in php
My current `$input` array is as follows `Array ( [0] => 15 [1] => 250 [2] => 18|1.0 [3] => 70 [4] => 9.0 )`
How can I grab the split values in `$input[2]` above without causing `Notice: A non well formed numeric value encountered in ....` error The error is because it doesn't know which number to select due to the split |. is there a way to say `number before split` then `number after split` as I need to now reference the values separately to calculate.
Any help appreciated
|
Problem is that you store in `$input[2]` not string but result of bitwise operation `| (OR)` = number `19`. So when you want to perform any mathematical action on that variable you will get always number 19.
It's impossible to revert `bitwise OR` operation.
$number = 18 | 1.0;
$string_number = "18|1.0";
var_dump($number); // int(19)
var_dump($string_number); //string(6) "18|1.0"
$string_number_array = explode('|', $string_number);
var_dump($string_number_array[0]); // string(2) "18"
var_dump($string_number_array[1]); // string(3) "1.0"
var_dump((int)$string_number_array[0]); // double(18)
var_dump((double)$string_number_array[1]); // double(1)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, split"
}
|
How to get a pop-up window for flutter web app?
I have been looking for a flutter web app pop-up window but all I could find so far, is a pop-up dart package that just acts like a stack on top on my app, that's not what I want, I want a complete new pop-up window that loads a web page , any help?
|
As I understand:- you want to launch another web page.
`dart:js` enables interoperability between Dart and JS
Sample code :-
import 'dart:js' as js;
FlatButton(
child: Text('launch another window'),
onPressed: () {
js.context.callMethod('open', ['
},
),
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "flutter, flutter layout, flutter web, flutter navigation, flutter packages"
}
|
Google Datastore: query filter by descendant key
In google datastore, is it possible to query for keys that do _not_ contain a specific child.
So, if I have the following data
<User>/<Action=Purchase>/<Id=123456>/Initiate
/Complete
I would like to find all purchases that are not complete - ie, that do not contain a 'Complete' child.
I would also like all changes to be non-destructive - ie, I want to avoid ovewritting any existing data. So for example, I would prefer to avoid having a parameter on Id=123456 that records state (does that make sense, or is it a silly requirement?)
(I am creating this in node, if that makes a difference)
|
There is no way in Cloud Datastore to query for missing data. You can only query for data that exists. So you'll need to track a state, probably on your id=123456 entity.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "google cloud datastore"
}
|
How to Show and Hide Div using C# in MVC 3 Razor View Engine?
I have to write C# code for showing and hiding div in MVC3 for various controls based on switch case in C# .How can it be done without using JQuery Show or hide.. but in fully server side..?
|
Add your switch statement directly into your .cshtml file. It will all be server-side at that point.
Controller:
public ActionResult Page()
{
string data = "value1";
return View(data);
}
CSHTML:
@model string; // this should be the Type your controller passes
<div>some html content</div>
@switch(Model) // Model is how you access your passed data
{
case "value1":
<div>...</div>
break;
case "value2":
<div>...</div>
break;
}
<div>more html content</div>
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 10,
"tags": "c#, asp.net mvc, razor"
}
|
How to get the column header height of a TListView?
In a `TListView` I want to get the first pixel vertically where the list client area starts. Normally, it starts at 0 but when the header is present it starts at header height.
|
Get header handle (alternative - with corresponding `LVM_GETHEADER` message) and retrieve its size by any method.
uses ... commctrl;
var
h: THandle;
r: TRect;
begin
h := ListView_GetHeader(ListView2.Handle);
GetWindowRect(h, r);
Caption := IntToStr(r.Bottom - r.Top);
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "listview, delphi, delphi 2009"
}
|
Remove non-int from rows in CSV
I'm trying to teach myself Python for data analysis and to practice I'm working on analyzing a CSV file containing 27k survey responses.
The responses take the form of "# - Rating" (For example: "10 - Extremely Interested")
Would anyone be able to tell me how would I go about removing everything but the numerical value so that I could plot this data with matplotlib?
Thank you :)
Edit: My apologies, here is the code for the df I'm working with:
likely_recc = pd.read_csv('test_data.csv', usecols = (['How likely are you to recommend this product to a friend?']))
|
This should do the trick
df['col'].str.split(' ').str[0].astype(int)
Take a look at the pandas docs on string methods for more information.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, pandas, csv"
}
|
What is the synonym of the word focus here?
I wonder if there are any synonyms of the word focus here? As far as I get the phrase "bring into focus" means "draw attention to", but other sentences are not very clear to me. I guess the closest definition will be a : a center of activity, attraction, or attention OR b : a point of concentration
"Flow helps some of the world's most creative companies streamline their communication by bringing all parts of it into focus. This focus isn't just something we do, it's something we believe in—and certainly something I've been trying to practice on a regular basis since my time studying with Thích Nhất Hạnh".
|
It seems that for the author, the "focus" word in
> This focus isn't just something we do
acts as a noun describing the action of "bringing into focus" (in the sense of your option _a)_ ).
You could compare it with how "treatment" is the act of treating, for example, though I'm not sure this use of "focus" as the action of bringing into focus is very correct because in the dictionaries it doesn't appear.
|
stackexchange-english
|
{
"answer_score": -1,
"question_score": 0,
"tags": "synonyms"
}
|
Bash: numbered files in Find
I was writing a bash script that finds and deletes the .blend1 and .blend2 files that blender creates as you edit and save .blend files. It contains lines in pairs like this:
find Documents -name "*.blend1" -exec rm -rf {} \;
find Documents -name "*.blend2" -exec rm -rf {} \;
This works just fine, though I was curious if it is at all possible to combine those two find commands some way, so that it would be just one command that finds and deletes both .blend1 and .blend2 files.
Not super-important, I'd just prefer it if my script were a little more compact.
|
find Documents -name '*.blend[12]' -delete
(`-delete` is a GNU find extension.)
Other ways:
find Documents '(' -name '*.blend1' -o -name '*.blend2' ')' -delete
find Documents -name '*.blend*' -delete
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "linux, bash, find"
}
|
Read file in python - Last line "None"
I make a code to read each line of the file "name":
def readFile(name):
with open(name) as f:
for line in f:
line = line.strip()
print line
My file have this:
11001
10010
My output is:
11001
10010
None
Why None?
|
You have the right idea, here's a neat trick.
def readFile(name):
with open(name) as f:
for line in f:
line = line.rstrip()
print line
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python"
}
|
Stacked bar chart may not repect changed colors
For my dc.js dashboard I use a stacked bar chart and a pie chart. When changing the default colors with
dc.config.defaultColors(d3.schemePastel1);
the pie chart changes the color, but not the stacked bar chart. Do I missed something? A jsfiddle example is provided to quickly check the behaviour.
|
This looks like a bug left over from when charts would set their color defaults separately. I filed it here.
Until that's fixed, you can set the colors explicitly for the bar chart:
chart
.colors(d3.scaleOrdinal(d3.schemePastel1))

my css
#gallery{
display: flex;
-ms-flex-direction: row;
flex-direction: row;
align-items: flex-end;
justify-content: space-around;
align-content: space-around;
flex-wrap: nowrap;
}
#gallery img{
max-width: 100%;
align-self: flex-end;
padding: 5px;
box-sizing: border-box;
}
I've tried adding flex grow and shrink to be 1, once i change the flex wrap to nowrap they just inflate to full size
I want to ultimately use this method to show the index images here <
|
The only way you can achieve the image stacking is using a Javascript.
There's two Javascript libraries that does the magic for you.
* Masonry
* Isotope
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 0,
"tags": "javascript, html, css, masonry, jquery isotope"
}
|
How to share realm objects between screens
I am working on an app written in Swift, which needs e.g. the data of the currently logged-in User on multiple screens and after updating it from an API to save the data.
What is the best practice to get this data? Get the instance on every occurrence from the Database by a selection like this:
do {
let realm = try Realm()
let result = realm.objects(User).filter("name = \(loggedInPlayerName)")
if result.count > 0 {
return result.first
}
}
Or sharing it after getting it once by a (singleton) SessionService or something similar?
Or have the Player Model Object some selection method like User().getLoggedInUser() which has the above written method to select an instance?
Would appreciate some thoughts on how to do that correctly!
|
Correct I would do something like that! I assume loggedInPlayName is a unique id, so you could set the property name as a primary key.
Then I would do:
`let user = realm.objectForPrimaryKey(User.self, key: loggedInPlayerName)`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "swift, realm"
}
|
Return to specific view after playing embedded youtube video in iOS
I'm playing a youtube video from a specific view (not the view that appears for first at app launch) in an iPhone app I'm developing.
Everything works fine: the video preview shows up in the web view inside my specific view and when I tap on it the video plays full screen.
When the video ends (or when I press the Done button) my app shows back, but showing the first view (the one that appears at app launch), not the one from which I launched the video. And what's even worst, the app doesn't respond to events (it doesn't crash, it just doesn't respond).
I tried to put some NSLogs in all the AppDelegate methods (in case the youtube plugin acts as if leaving my app and then returning), but none gets triggered...
I really have no clue what the problem can be...
|
I finally avoided the problem using the syntax introduced here <
In this way, the youtube player correctly returns to the "calling" view containing the web view.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "iphone, ios, youtube"
}
|
How do I parse a string and get formula? in C#
> **Possible Duplicate:**
> Evaluate C# string with math operators
So lets say I have a basic string with the value "1*2+4"
How would I go about parsing the information and then doing the calculation?
I am self teaching c# but my assumption is this is a common issue in programming but without using a library how would one do this?
My results so far have got me splitting the string up and putting them into an array of chars, but this is where I've stopped since I am trying to figure out how to compare chars to operators and chars to ints.
I am not sure if I am going the right way about this but would be great if someone could point me in the right direction.
Thank you for your help in advanced.
|
What you're looking for is the `Shunting-yard` algorithm. You'll need at least two stacks; one for storing operators and one for operands. After you fill the stacks you can make a `RPN` and calculate the answer.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 3,
"tags": "c#, string, parsing, math"
}
|
Change value of tag attibute?
I would like to change the value of the `readonly` attribute using jQuery but this piece of code does not work :
$('#L1E').live('change',function() {
$('.hidden').attr('readonly','');
return false;
});
Does anyone know why ?
|
You should use removeAttr to remove the read only attribute:
$('.hidden').removeAttr('readonly');
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery"
}
|
Listing columns from multiple tables in sql
I've got a database which is formed like this:
BOOKTYPES ( book_type_id (PK), book_type )
CATEGORIES ( category_id (PK), category )
PUBLISHERS ( publisher_id (PK), publisher, speciality, country )
BOOKS ( book_id (PK), title, publisher_id (FK), published_year,
purchase_price, category_id (FK),purchase_date, pages,
book_type_id(FK) )
AUTHORS ( author_id (PK), first_name, last_name, pseudonym )
AUTHORSHIP ( author_id (PK), book_id (PK) )
Now, what I need help with is listing category and the number of books that contain that category. This means that I need to retrieve the category from CATEGORIES, and category_id from books. The problem I'm facing with this is that category_id already exists inside categories, and that isn't the one that I want to retrieve.
I'd really appreciate some help with this since it's been picking my brain for quite the while now.
|
> listing category and the number of books that contain that category
That looks like a simple aggregate query on `books`:
SELECT category_id, COUNT(*) count_of_books FROM books GROUP BY category_id
If you want the category name as well, you can `JOIN` on `categories`. You do disambiguate the column names by prefixing them with the table they belong to (or the table alias):
SELECT c.category, COUNT(*)
FROM books b
INNER JOIN categories c ON c.category_id = b.category_id
GROUP BY c.category_id, c.category
To filter on a given count of categories, you can use a `HAVING` clause:
SELECT c.category, COUNT(*)
FROM books b
INNER JOIN categories c ON c.category_id = b.category_id
GROUP BY c.category_id, c.category
HAVING COUNT(*) > 5
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sql, join, select, group by"
}
|
URL Redirect when there is no extension available
I want to perform a redirection like this:
to
and still show the original URL in the browser (under the hood redirect)
_The environment is IIS 6 / Asp.Net 3.5 on Windows Server 2003 SP2_
How would I do this using `web.config` or IIS.
I know how to handle redirects if I can map an extension to the `aspnet_isapi.dll` and use `Context.RewritePath(string)` but I don't know how to do that for URLs that don't have extensions.
|
If you are able to move to ASP.NET 4 then there is a lot more support for extentionless URL rewriting.
However, if you have to use ASP.NET 3.5/IIS6 you can use ScottGu's blog post here:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 4,
"tags": "asp.net, redirect, url rewriting, iis 6"
}
|
Do complex thread index calculations have an impact on the performance?
I have just asked myself if complex index calculations with e.g. threadIdx.x have an impact on the performance. Do these variables become constant as soon as the kernel is uploaded to the device?
I want to navigate to a huge array where the index depends on threadIdx.x, threadIdx.y and threadIdx.z. I need e.g. modulo operations like
array[threadIdx.y % 2 + ...]
|
If someone is interested, I have evaluated the corresponding PTX code.
(1) Complex thread ID calculations have an impact on the performance. "threadIdx.x" etc. are not constants.
(2) "threadIdx.y % 2" is implemented efficiently and corresponds to "threadIdx.y & 0x00000001" (Cuda Toolkit 5.5).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "cuda"
}
|
Only open one infowindow at a time
I'm creating a Google map with multiple markers. At the moment each marker has an infowindow, how can I only have one infowindow open at a time?
At the moment it closes all windows on clicking the map.
I know this question has been asked a few times but the code seems vastly different to mine.
// if marker contains HTML, add it to an infoWindow
if( $marker.html() )
{
// create info window
var infowindow = new google.maps.InfoWindow({
content : $marker.html()
});
// show info window when marker is clicked
google.maps.event.addListener(marker, 'click', function() {
infowindow.open( map, marker );
});
google.maps.event.addListener(map, 'click', function(event) {
if (infowindow) {
infowindow.close(); }
});
}
|
Try this: declare just one infowindow (global to the map, not one by marker).
var infoWindow;
...
if( $marker.html() ){
google.maps.event.addListener(marker, 'click', function() {
if (infoWindow) infoWindow.close();
infoWindow = new google.maps.InfoWindow({
content : $marker.html()
});
infoWindow.open( map, marker );
});
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, google maps"
}
|
Can laravel controllers functions be variables?
My question is simple, i want to create a variable route, but i want to create a variable function inside the route.
Is this posible?
Route::get('/{tabla}/get','WebSystem\{tabla}@{tabla}')->name('activities');
|
You could use different notation (it require to change default namespace in your routeServiceProvider):
Route::get('/{tabla}/get, [ExampleController::class, 'methodName'])->name('activities');
Which leads us to:
$controller = ExampleController::class;
$methodName = 'methodName';
Route::get('/{tabla}/get', [$controller, $methodName]);
In addition, this approach guarantee that some IDE (like PhpStorm) will refactor your routes. In example: when you want to change name or namespace of your controller.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "php, laravel"
}
|
deep shadows cut in stony features
The following is from 'The Blackhouse' by Peter May
> He just stood staring at Fin, **deep shadows cut in stony features** by the light on Fin's desk.
I don't understand the bold description. Can you explain it, please?
|
The phrase isn't idiomatic. It's probably metaphor.
It seems to be intended to evoke imagery, both of the unchangeability ("stoniness") of the person's affect and the contrast of light and shadow cast by the singular desk lamp. The shadows are "cut" like something carved or etched into a rock surface. _Stony features_ may also hint that there are ridges and wrinkles on the man's face, or that he has a fixed expression that is wrinkling and furrowing his facial features.
|
stackexchange-ell
|
{
"answer_score": 1,
"question_score": 0,
"tags": "phrase meaning"
}
|
C# Linq Result ToDictionary Help
I have a lambda expression that gets results from a Dictionary.
var sortedDict = (from entry in dctMetrics
orderby entry.Value descending
select entry);
The expression pulls back the pairs I need, I can see them in the IDE's debug mode.
How do I convert this back a dictionary of the same type as the source? I know sortedDict's TElement is a KeyValuePair, but I am having trouble fully understanding the ToDictionary extension method's syntax. I also tried foreach'ing the var result to piecewise construct a new dictionary, but to no avail.
Is there something like this (functionality wise):
var results = (from entry in dictionary
orderby entry.Value descending
select entry);
Dictionary<string,float> newDictionary = results as (Dictionary<string,float>);
|
You can do it like this:
var newDictionary = results.ToDictionary(r => r.Key, r => r.Value);
Read that as "for each pair in results, add that element to the new dictionary, where the key will be produced as the key of the pair, and the value will be produced as the value of the pair."
Also, just based on your sample code -- you should keep in mind that a `Dictionary<T, U>` is implemented as a hash table, so it won't maintain the order of the elements you put into it. Consider using a `SortedDictionary` or a `SortedList` instead if you need an ordered map.
|
stackexchange-stackoverflow
|
{
"answer_score": 22,
"question_score": 7,
"tags": "c#, linq, dictionary, lambda, key value"
}
|
Gradle: Differences when define task with and without << operator
I'm using Gradle and I try to configure for my Android project. I read document and I see that there are two ways of defining a task.
**Without << Operator**
task SampleTask {
methodA param1 param2
}
**With << Operator:**
Task SampleTask <<{
methodA param1 param2
}
My question is: what is real differences between above 2 ways?
Thanks :)
|
you can define tasks like this :
task hello {
doLast {
println 'Hello world!'
}
}
here, the last thing that `hello` task does, is to print 'Hello World!' I can use another syntax for defining my task like this :
task hello << {
println 'Hello world!'
}
these two tasks are same. another example is :
task hello << {
println 'Hello Earth'
}
hello.doFirst {
println 'Hello Venus'
}
hello.doLast {
println 'Hello Mars'
}
hello << {
println 'Hello Jupiter'
}
now the output will be :
Hello Venus
Hello Earth
Hello Mars
Hello Jupiter
read documentation for more details.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "android, gradle, gradle task"
}
|
Optional whitespaces inside lookbehind regex
Using Smarty template engine, but looking to pre-process HTML to change font-size across all CSS.
I want to make the whitespace(s) optional after the colon so it will match the number no matter what.
The issue is I can only seem to get optional matching as part of the expression, not the lookbehind.
RegEx: `(?<=font-size: )[0-9]+`
HTML excerpt:
body {
font-family: 'Open Sans', sans-serif;
font-size: 9pt;
height: 100%;
min-height: 100%;
display:block;
}
|
Do not use lookbehinds when you can do it easily with a capturing group.
In your case you can do something like:
(\bfont-size:\s*)([0-9]+)
Then use the capturing groups `$1` and `$2` as you need.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "regex"
}
|
Find strings in txt file and move them in another txt
Hi i need to make a script in vbs that do this:
* Find 3 strings and move them in another txt file.
So this is for example the input txt:
*************************************
NAME: NOTHING
FUNCTION: NOT IMPORTANT
DATA_START: 20/05/2013
DATA_STOP: 22/05/2013
*************************************
FUNCTION: NOT IMPORTANT
TIME_STOP: 21.00.00.00
*************************************
DATA_NUMBER: 0000000054
*************************************
Well this is the file.. Now, i have to "take" these strings:
DATA_START: 20/05/2013 DATA_STOP: 22/05/2013 TIME_STOP: 21.00.00.00 DATA_NUMBER: 0000000054
and move them in another txt writing:
20/05/2013 22/05/2013 21.00.00.00 0000000054
This is what i want..
I can't find the error
|
Here try this:
Const ForReading = 1
Const ForWriting = 2
Dim objFSO 'File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objInputTS 'Text Stream Object
Set objInputTS = objFSO.OpenTextFile("c:\input.txt", ForReading, False)
Dim objOutputTS 'Text Stream Object
Set objOutputTS = objFSO.OpenTextFile("c:\output.txt", ForWriting, True)
Do Until objInputTS.AtEndOfStream
Dim strLine
strLine = objInputTS.ReadLine()
If (Left(strLine, 11) = "DATA_START:") Then objOutputTS.WriteLine(Mid(strLine, 13))
If (Left(strLine, 10) = "DATA_STOP:") Then objOutputTS.WriteLine(Mid(strLine, 12))
If (Left(strLine, 10) = "TIME_STOP:") Then objOutputTS.WriteLine(Mid(strLine, 12))
If (Left(strLine, 12) = "DATA_NUMBER:") Then objOutputTS.WriteLine(Mid(strLine, 14))
Loop
objOutputTS.Close()
objInputTS.Close()
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "vbscript, text files"
}
|
Как проверить является ли неориентированный граф двудольным
Можете дать алгоритм , который определит можно ли перекрасить неориентированный граф в 2 цвета , или же просто алгоритм , который проверяет является ли неориентированный граф 2-цветым(двудольным)
|
Есть простой алгоритм. Используете любой алгоритм (поиск в ширину или глубину), что бы пройти по всем вершинам. Каждую вершину при посещении разукрашиваете в белый или черный цвет (можно хранить отдельно массив с разукрашенными вершинами.
Правило раскраски - две соседние вершины должны быть разного цвета. То есть, если текущая белая, то соединенные с ней - черные. Если все вершины разукрасились - ура, наш граф двудольный. Если в процессе разукраски натолкнулись на уже покрашенную вершину и цвет совпал, ок, продолжаем. Если не совпал - нашли проблемное место, грав не двудольный.
Более строгое математическое определение - все циклы в таком графе - четные. (теорема Кенига).
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c++, алгоритм"
}
|
How to set From as a name in SparkPost email
I'm using Sparkpost client library for java.
When I set a `fromEmail`and `username` to `contentAttributes` I expect to see Name Name instead of [email protected] in email I have got. But it doesn't work. Is there any way to show Name instead of Email in message?
place where I need my name instead of email address
TemplateContentAttributes contentAttributes = new TemplateContentAttributes();
AddressAttributes addressAttributes = new AddressAttributes();
addressAttributes.setName(username);
addressAttributes.setEmail(fromEmail);
contentAttributes.setFrom(addressAttributes);
contentAttributes.setSubject(subject);
contentAttributes.setHtml(html);
contentAttributes.setText(text);
|
maintainer of the Java SparkPost library here. I just modified this sample.
I changed it to this:
TemplateContentAttributes contentAttributes = new TemplateContentAttributes();
AddressAttributes fromAddress = new AddressAttributes(from);
fromAddress.setName("My Name");
contentAttributes.setFrom(fromAddress);
And this is the result !} $$
I know I should use $$e^x=\sum_{n=0}^{\infty}\frac{x^n}{n!} $$
But then I get confused, and I don't how I shall proceed to find the answer.
|
$$\sum_{n=0}^{\infty} \frac{x^{n}}{(n+3)!}=\sum_{n=3}^{\infty} \frac{x^{n-3}}{n!}=x^{-3}\sum_{n=3}^{\infty} \frac{x^{n}}{n!}=x^{-3}(e^x-\frac{x^0}{0!}-\frac{x^1}{1!}-\frac{x^2}{2!})=\frac{e^x}{x^3}-\frac{1}{x^3}-\frac{1}{x^2}-\frac{1}{2x}$$ I believe that I've done everything correctly.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "power series"
}
|
How to use Amazon Corretto JDK with Github Actions?
I have a Github Java project that uses Amazon Corretto 11.
But I am not able to write a Github action so that workflow would build the project at every pull request.
For example, with OpenJDK it would look like below
# This workflow will build a Java project with Maven
# For more information see:
name: Java CI with Maven
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 11
uses: actions/setup-java@v2
with:
java-version: '11'
distribution: 'adopt'
- name: Build with Maven
run: mvn -B package --file pom.xml
How to use Corretto instead of OpenJDK? Is there a Github standard action to do that? Or any other way?
|
If you want to use that action you would probably need to submit a PR to the action to add Coretto as a supported distribution.
I am curious why it matters though? You should be able to build using any Java distribution. Is there a reason you think you need to build using Correto?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "github actions, corretto"
}
|
How to write down a presentation of a Lie algebra if we know a set of generators?
How to write down a presentation of a Lie algebra if we know a set of generators in matrix form? For example, for $sl_2$, if we know $e=(0, 1; 0, 0)$, $f=(0, 0; 1, 0)$ , $h=(1, 0; 0, -1)$, how to write a presentation of $sl_2$ from these matrices?
|
What you need to compute is the Lie bracket of the generators, in this case this is just the commutator. Because of antisymmetry, you just have to compute one direction: \begin{align*} [e,f]&=ef-fe=\begin{pmatrix}0&1\\\0&0\end{pmatrix}\begin{pmatrix}0&0\\\1&0\end{pmatrix}-\begin{pmatrix}0&0\\\1&0\end{pmatrix}\begin{pmatrix}0&1\\\0&0\end{pmatrix}\\\ &=\begin{pmatrix}1&0\\\0&-1\end{pmatrix}=h\\\ [e,h]&=eh-he=\begin{pmatrix}0&1\\\0&0\end{pmatrix}\begin{pmatrix}1&0\\\0&-1\end{pmatrix}-\begin{pmatrix}1&0\\\0&-1\end{pmatrix}\begin{pmatrix}0&1\\\0&0\end{pmatrix}\\\ &=-2e \end{align*} I leave the computation for $[f,h]$ for you.
In googling this question I found a nice paper on the issue how to convert the different possibilities of presenting a Lie algebra into each other. It is Cohen, de Graaf, Ronyai: Computations in finite-dimensional Lie algebras, _Discrete Mathematics and Theoretical Computer Science_ , 1997.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "lie algebras"
}
|
Select variating position NTH child with CSS
I have an item (X) in a menu that changes the position depending of the user, for example:
Regular user:
N | N | N | X | N
Admin User:
N | N | N | N | X
I need to select that item using NTH-CHILD, the item has no ID or CLASS or any fields, this needs to be done using NTH-CHILD, so using the first example to select the item in a regular user menu:
element:nth-child(4)
But this instead should work for both cases in a single selector
element:nth-child(4 or 5 will always be the same with the algorithm)
|
Selectors match elements based on information relayed by the markup. This information does not include text content. That's why Johannes and dippas have suggested adding the appropriate class names to the body or some other element — because that's precisely the sort of thing classes were meant for.
If your markup does not discriminate based on whether the user is a regular user or an administrator, then as far as CSS is concerned, your markup is identical in either case, and there's nothing you can do to ensure that your selector always matches the right element.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html, css, css selectors"
}
|
Execute column values in SQL Server
I need to do an arithmetic operation to the values saved in SQL table, for example, I have value as 5*10 in next column I want 15
EQUATION VALUE
2+5 7
6+8 14
Based on the equation I need to calculate the value.
|
As you know by now, SQL Server does not have an EVAL() function. However, with a little dynamic SQL, it is possible, **but really not recommended**.
**Example**
Declare @YourTable Table (id int,[EQUATION] varchar(150))
Insert Into @YourTable Values
(1,'2+5')
,(2,'6+8')
,(3,'datediff(DAY,''2018-01-01'',getdate())') -- Added Just for Fun
Declare @SQL varchar(max) = Stuff((Select ',' + concat('(',ID,',',[EQUATION],')')
From @YourTable A
For XML Path (''))
,1,1,'')
Exec('Select * from (values ' + @SQL + ')A([ID],[Value])')
**Returns**
ID Value
1 7
2 14
3 189
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "sql, sql server"
}
|
Best way to get word frequency counts for a website? Or part of a website?
Pretty simple, I just looking for a simple means of extracting word frequencies from a given website, or section of a website.
I am also interested in calculating average distance between two given words throughout a website. The units of distance being in words.
I am asking this question because I quite frankly haven't been able to find much information leading to the intuition of performing such a task. I don't have any experience with web spidering or scraping of any kind.
Thanks (I asked this question earlier, but it wasn't well formed)
|
You could try to use Scrapy. It is quite powerful tool for scrapping websites, but may require knowledge of regular expressions and XPath. Try to follow tutorial.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 4,
"tags": "javascript, python, html, web scraping"
}
|
on submit action
I am trying to call submit action from javascript using simpleFormController of Spring but action calling only handleRequest but its not calling the onsubmit action
|
As Bozho says, it would help to see some code. However, my experience is that when onSubmit is not being called, it's usually because the request is showing up as a GET rather than a POST; by default the controller determines whether a request is a form submission by looking for a POST.
Two ways to fix it: 1) make it a POST (i.e. submit a form via javascript, say) or 2) override isFormSubmission to use some other criteria for deciding whether a given request is a form submission -- for example, you might want to say that if a certain parameter is present, the request should be treated as a form submission, even if it's a GET request.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, javascript, spring, spring mvc"
}
|
How to pass values to a static HTML page
I am trying to pass a value to a static HTML page. jQuery finds the value in the table, but how do I pass it to the next page
$('.gobutton').bind('click', function(){
var value = $(this).closest('tr').find('td')[0].innerHTML
var forward = window.location.replace('{% url 'example' %}');
});
I tried using `sessionStorage.setItem("user_val",value)` but I cant seem to recover it on that view in any way.
`$.post('{% url 'example' %}', {"user_val":value})` method doesn't load the html page, but passes the value.
|
Ended up doing
sessionStorage.setItem("user_val",value);
window.location.replace('{% url 'example' %}');
Then on `example` page I checked for existence of `user_val` with `sessionStorage.getItem` If `user_val` existed I launched the coded (AJAX) I need. And set `user_val` to `""`, cleaning up the memory. If `user_val` didnt exist it would launch the page like it was previously.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jquery, django, html"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.