text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Variance of $\frac{x_i}{\sum_{i=1}^nx_i}$ when $x_1,\ldots,x_n$ are iid random variables
Suppose $x_1,\ldots,x_n$ are iid random variables with finite variances. Is the variance of $z_i=\frac{x_i}{\sum_{i=1}^nx_i}$ a function of $n$ only? I am interested in two cases. Case 1: the variance of $x_i$ is zero. Case 2: the variance of $x_i$ is nonzero.
I know that the expectation is $\frac{1}{n}$ because $\sum_{i=1}^nz_i=1$ so that both $\sum_{i=1}^nE(z_i)=nE(z_i)$ and $\sum_{i=1}^nE(z_i)=E(\sum_{i=1}^nz_i)=1$. To find the variance $V(z_i)$ we would want to find $E(z_i^2)$, and we could do so by finding $E(\sum_{i=1}^nz_i^2)=E(\frac{\sum_{i=1}^nx_i^2}{(\sum_{i=1}^nx_i)^2})$.
A:
As clarified in the comments, the question is whether the variance is a function of $n$ only or depends on the distribution.
It depends on the distribution. The variance of $z_i$ is zero or not according as the variance of the $x_i$ is zero or not.
For a slightly more interesting case, consider $x_i$ uniformly distributed over $\{a,b\}$. Then $z_i$ takes the value $\frac12$ with probability $\frac12$ and the values $\frac a{a+b}$ and $\frac b{a+b}$ with probabilities $\frac14$ each, so the variance is
$$
\frac14\left(0+0+\left(\frac a{a+b}-\frac12\right)^2+\left(\frac b{a+b}-\frac12\right)^2\right)=\frac18-\frac{ab}{2(a+b)^2}\;,
$$
which depends on $a$ and $b$ and thus on the distribution.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unexpected task switch on Linux despite of real time and nice -20
I have a program that needs to execute with 100% performance but I see that it is sometimes paused for more than 20 uSec. I've struggled with this for a while and can't find the reason/explanation.
So my question is:
Why is my program "paused"/"stalled" for 20 uSec every now and then?
To investigate this I wrote the following small program:
#include <string.h>
#include <iostream>
#include <signal.h>
using namespace std;
unsigned long long get_time_in_ns(void)
{
struct timespec tmp;
if (clock_gettime(CLOCK_MONOTONIC, &tmp) == 0)
{
return tmp.tv_sec * 1000000000 + tmp.tv_nsec;
}
else
{
exit(0);
}
}
bool go_on = true;
static void Sig(int sig)
{
(void)sig;
go_on = false;
}
int main()
{
unsigned long long t1=0;
unsigned long long t2=0;
unsigned long long t3=0;
unsigned long long t4=0;
unsigned long long t5=0;
unsigned long long t2saved=0;
unsigned long long t3saved=0;
unsigned long long t4saved=0;
unsigned long long t5saved=0;
struct sigaction sig;
memset(&sig, 0, sizeof(sig));
sig.sa_handler = Sig;
if (sigaction(SIGINT, &sig, 0) < 0)
{
cout << "sigaction failed" << endl;
return 0;
}
while (go_on)
{
t1 = get_time_in_ns();
t2 = get_time_in_ns();
t3 = get_time_in_ns();
t4 = get_time_in_ns();
t5 = get_time_in_ns();
if ((t2-t1)>t2saved) t2saved = t2-t1;
if ((t3-t2)>t3saved) t3saved = t3-t2;
if ((t4-t3)>t4saved) t4saved = t4-t3;
if ((t5-t4)>t5saved) t5saved = t5-t4;
cout <<
t1 << " " <<
t2-t1 << " " <<
t3-t2 << " " <<
t4-t3 << " " <<
t5-t4 << " " <<
t2saved << " " <<
t3saved << " " <<
t4saved << " " <<
t5saved << endl;
}
cout << endl << "Closing..." << endl;
return 0;
}
The program simply test how long time it takes to call the function "get_time_in_ns". The program does this 5 times in a row. The program also tracks the longest time measured.
Normally it takes 30 ns to call the function but sometimes it takes as long as 20000 ns. Which I don't understand.
A little part of the program output is:
8909078678739 37 29 28 28 17334 17164 17458 18083
8909078680355 36 30 29 28 17334 17164 17458 18083
8909078681947 38 28 28 27 17334 17164 17458 18083
8909078683521 37 29 28 27 17334 17164 17458 18083
8909078685096 39 27 28 29 17334 17164 17458 18083
8909078686665 37 29 28 28 17334 17164 17458 18083
8909078688256 37 29 28 28 17334 17164 17458 18083
8909078689827 37 27 28 28 17334 17164 17458 18083
The output shows that normal call time is approx. 30ns (column 2 to 5) but the largest time is nearly 20000ns (column 6 to 9).
I start the program like this:
chrt -f 99 nice -n -20 myprogram
Any ideas why the call sometimes takes 20000ns when it normally takes 30ns?
The program is executed on a dual Xeon (8 cores each) machine.
I connect using SSH.
top shows:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8107 root rt -20 16788 1448 1292 S 3.0 0.0 0:00.88 myprogram
2327 root 20 0 69848 7552 5056 S 1.3 0.0 0:37.07 sshd
A:
Even the lowest value of niceness is not a real time priority — it is still in policy SCHED_OTHER, which is a round-robin time-sharing policy. You need to switch to a real time scheduling policy with sched_setscheduler(), either SCHED_FIFO or SCHED_RR as required.
Note that that will still not give you absolute 100% CPU if it isn't the only task running. If you run the task without interruption, Linux will still grant a few percent of the CPU time to non-real time tasks so that a runaway RT task will not effectively hang the machine. Of course, a real time task needing 100% CPU time is unlikely to perform correctly.
Edit: Given that the process already runs with a RT scheduler (nice values are only relevant to SCHED_OTHER, so it's pointless to set those in addition) as pointed out, the rest of my answer still applies as to how and why other tasks still are being run (remember that there are also a number kernel tasks).
The only way better than this is probably dedicating one CPU core to the task to get the most out of it. Obviously this only works on multi-core CPUs. There is a question related to that here: Whole one core dedicated to single process
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android - Using an Activity without a manifest entry
I have been working on a bunch of utility activities. The goal is that the user simply can reuse the source code and there is no need for any layout xml files. Hence, all the layouts are created programmatically. There is no reference to any layout xml file.
The only problem I am running into is that the user is forced to enter the activities in the manifest file.
I am wondering if there is a way to bypass this step by the user. Perhaps the user can call some Init() method in my code that will programmatically add activities to the "manifest" object. There must be some notion of manifest object as Android is looking it up when a new activity is created.
Thank you in advance for your help.
A:
The goal is that the user simply can reuse the source code and there is no need for any layout xml files. Hence, all the layouts are created programmatically. There is no reference to any layout xml file.
This hardly seems like a good thing. Now you are preventing your reusers from readily modifying matters, to tweak for different device characteristics that you are not yet supporting, etc. Android library projects allow you to create reusable components that contain layout files and other resources.
I am wondering if there is a way to bypass this step by the user.
No, sorry, that is impossible.
Eventually, I think Android library projects will support merging of manifests to help deal with this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Каким образом можно вынести описание функции в отдельный файл?
У меня есть длинные функции, которые, для удобства, хочется разместить в отдельных файлах.
Как правильно должен составляться такой файл? Насколько понимаю, требуется расширять класс Program или что-то в этом роде. Но как именно?
На всякий случай упомяну, что мне нужна, просто, функция, не связанная ни с какими классами.
A:
Согласен с @DreamChild, что при нормальном написании кода потребности в таких странностях обычно не возникает, но если уж очень хочется, то можно использовать partial:
В одном файле:
public partial class TestApp
{
public static void Main()
{
Console.WriteLine(TestMethod());
Console.ReadKey();
}
}
в другом:
public partial class TestApp
{
public static string TestMethod()
{
return "!!!";
}
}
A:
На всякий случай упомяну, что мне нужна, просто, функция, не связанная ни с какими классами
Такое в C# невозможно. Это полностью объектно-ориентированный язык, и функции (точнее, методы - в C# нет понятия "функция") могут находиться только в составе класса. Класс, впрочем, может быть статическим и по сути являться пространством имен для методов, однако методов без класса в шарпе быть не может.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Bank function, where new account gets $5, but when the withdraw is larger than balance, it doesnt take away the balance and gives error
public class Acc{
private double balance;
public Account()
{
balance = 5;
}
public Acc(double sBalance)
{
balance = sBalance;
}
public void depos(double amount)
{
balance = balance + amount;
}
public void withd(double amount)
{
balance = balance - amount;
if (withd>balance){
System.out.println("Error");
}
}
public double gBalance()
{
return balance;
}
}
Main:
public class Main{
public static void main(String[] args){
Acc newBank = new Acc(50);
newBank.withd(20);
newBank.depos(5);
System.out.println(newBank.gBalance());
}
}
Basically I wanted to create a function to withdraw and deposit a value from stored in balance, where $5 is added to every new account created. It seems to work, however I wanted to extend and make it so withdrawing more than the balance amount would give an error and not take away from the balance
A:
First, there are inconsistencies in the code you provided, which makes it impossible to compile:
The first constructor is public Account() while the class name is Acc
As pointed out by @Andy Turner, you are using the method name withd in the condition. It should rather be amount > balance.
If I understand what you are trying to do, the withdraw method should be:
public void withd(double amount)
{
if (amount > balance) {
System.out.println("Error");
} else {
balance = balance - amount;
}
}
where you check if the balance has enough money before performing the withdraw.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how get index of HTML Table for given element using delphi
I'm using Delphi 2009 and I want to find index of HTML table which contains given element.
So, in the application, which I created, I use web browser to see the web page. I want to select element from this page and want to get Index of table which contains this element.
If someone can do it, please help me
A:
Using the browser's DOM interfaces, locate the IHTMLElement interface of the desired HTML element as needed, then use its parentElement property to get its parent element, repeating as needed, until you find an element that supports the IHTMLTableCell interface. Its cellIndex property will tell you the index of the cell within its row. Keep iterating the parentElement chain until you find an element that supports the IHTMLTableRow interface. Its rowIndex property will tell you the index of the row within its table. If you need to access the table itself, keep iterating the parentElement chain until you find an element that supports the IHTMLTable interface.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to append plain html (from other file) to HTML DOM element in PHP?
I have the main document created with DOM server-side using PHP. And I have to include some pieces of PHP/HTML without DOM.
Example. There is file form.php containing a form
<form action="" method="post">
<input type="text" name="firstname" id="firstnameid" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
I want to place that form into a <DIV> created using DOM in the file index.php. The DIV inside depends on other logic (condition $form_is_needed)
<!DOCTYPE html>
<html lang="en">
<head> <meta charset="utf-8" /> </head>
<body>
<?php
$form_is_needed = true;
$dom = new DOMDocument();
$domDiv = $dom->createElement("div");
if ($form_is_needed) {
// trying load not DOM
$str = file_get_contents('form.php');
$domDivText = $dom->createTextNode( html_entity_decode( $str ) );
$domDiv->appendChild($domDivText);
}
else {
$domDivText = $dom->createTextNode( "There is no form." );
$domDiv->appendChild($domDivText);
}
$dom->appendChild($domDiv);
$html = $dom->saveHTML();
echo $html;
?>
</body>
</html>
I get my content inside DIV but the escape characters has been added
<div><form action="" method="post">
<input type="text" name="firstname" id="firstnameid" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
A:
There is, to my knowledge, no node which can emit raw content, but if it is well-formed, you could try loading it into a DOMDocumentFragment and appending it that way:
$frag = $dom->createDocumentFragment();
$frag->appendXML($str);
$domDiv->appendChild($frag);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to implement Views in Fragment
I've used this sample code to create a sliding menu using navigation drawrer.
I have now the pages of this menu that are Fragment. Now I need to put View elements in these pages like buttons textviews, etc. How do I do this? As I'm not in an Activity class, I cant put view elements in the Fragment. I've read that i have to create an activity that comunicates with the fragment and does the work. How is this done? can you please show me some sample code? Thanks
A:
Refer to the code below. It has initlialized Button and an ArrayAdapter.
Some things to remember with fragments :
In fragments, you have to use "getActivity()" instead of context.
When writing "findViewById", you have to use instance of View as shown in the code.
This will help you start.
e.g.
public class FragmentExample extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.fragment_layout, container,
false);
// String[] valuesD = getResources().getStringArray(
// R.array.amtsDestination);
// ArrayAdapter<String> destinationArray = new ArrayAdapter<String>(
// this.getActivity(), android.R.layout.simple_spinner_item,
// valuesD);
// destinationArray
// .setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
// destination.setAdapter(startArray);
Button button = (Button) v.findViewById(R.id.buttonRoute);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(getActivity(), "Clicked", 6000).show();
Intent intent = new Intent(getActivity(),
NewActivity.class);
startActivity(intent);
}
});
return v;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Difference between break and continue statement
Can anyone tell me the difference between break and continue statements?
A:
break leaves a loop, continue jumps to the next iteration.
A:
See Branching Statements for more details and code samples:
break
The break statement has two forms: labeled and unlabeled. You saw the
unlabeled form in the previous discussion of the switch statement. You
can also use an unlabeled break to terminate a for, while, or do-while
loop [...]
An unlabeled break statement terminates the innermost switch, for,
while, or do-while statement, but a labeled break terminates an outer
statement.
continue
The continue statement skips the current iteration of a for, while ,
or do-while loop. The unlabeled form skips to the end of the innermost
loop's body and evaluates the boolean expression that controls the
loop. [...]
A labeled continue statement skips the current iteration of an outer loop marked with the given label.
A:
System.out.println ("starting loop:");
for (int n = 0; n < 7; ++n)
{
System.out.println ("in loop: " + n);
if (n == 2) {
continue;
}
System.out.println (" survived first guard");
if (n == 4) {
break;
}
System.out.println (" survived second guard");
// continue at head of loop
}
// break out of loop
System.out.println ("end of loop or exit via break");
This will lead to following output:
starting loop:
in loop: 0
survived first guard
survived second guard
in loop: 1
survived first guard
survived second guard
in loop: 2
in loop: 3
survived first guard
survived second guard
in loop: 4
survived first guard
end of loop or exit via break
You can label a block, not only a for-loop, and then break/continue from a nested block to an outer one. In few cases this might be useful, but in general you'll try to avoid such code, except the logic of the program is much better to understand than in the following example:
first:
for (int i = 0; i < 4; ++i)
{
second:
for (int j = 0; j < 4; ++j)
{
third:
for (int k = 0; k < 4; ++k)
{
System.out.println ("inner start: i+j+k " + (i + j + k));
if (i + j + k == 5)
continue third;
if (i + j + k == 7)
continue second;
if (i + j + k == 8)
break second;
if (i + j + k == 9)
break first;
System.out.println ("inner stop: i+j+k " + (i + j + k));
}
}
}
Because it's possible, it doesn't mean you should use it.
If you want to obfuscate your code in a funny way, you don't choose a meanigful name, but http: and follow it with a comment, which looks alien, like a webadress in the source-code:
http://stackoverflow.com/questions/462373
for (int i = 0; i < 4; ++i)
{
if (i == 2)
break http;
I guess this is from a Joshua Bloch quizzle. :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does my background image distort when viewed on a MacBook?
My page has a full screen background image, using cover. On Windows machines this looks fine, but when viewed on a MacBook, the image looks stretched and "cloudy". Why has this happened? My CSS is below:
background: url("images/backgroundimage.jpg");
background-size:100% auto;
background-repeat:no-repeat;
background-position:center top;
background-attachment:fixed;
-o-background-size: cover;
-moz-background-size: cover;
-webkit-background-size:cover;
background-size:cover;
A:
I think your Macbook has a retina display. That's why your image is getting distort and stretched. If that is the case, you need to use retina ready images (that is 2X larger that the image you are currently using) to solve this problem.
Here is a nice article about retina ready website. A guide for creating a better retina web.
Take a look. It might solve your problem.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Format from ticks to date
I am needing to transfer some logs which were timestamped in ticks to an XML document. I would prefer the timestamps to be more Specific such as "July 14, 2009 10:18:04 pm"
I was planning to using something along the line of:
DateTime logDate = DateTime.Parse(logText);
logDate.ToString("MMM dd yyyy hh:mm:ss tt");
I figured this would be OK as DateTime.Now.Ticks is how you can get ticks. It is however returning that it is not a proper DateTime format. during setting logDate.
I am sure there is a simple solution but I just can't come across it.
A:
If logText is a string, you can convert it to long (Int64) and use this constructor:
DateTime date = new DateTime(long.Parse(logText));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Use SQL View or SQL Query?
I am working on an application to get data from a MS-SQL server (2005). In the command text, I can pass a sql query like this:
string query = "SELECT T1.f1, T1.f2, T2.f3 FROM table1 T1 join table2 T2" +
"on T1.id = T2.id AND T1.dt = T2.dt ..."
....
cmd.CommandText = query;
I could also put the query as a view on my SQL server like this:
CREATE VIEW V1 AS
"SELECT T1.f1, ..."
Then I can use the view in a simplified query like this:
string query = "SELECT f1, f2, f3 FROM V1";
....
cmd.CommandText = query;
I am not sure which way is better. Will be the view be faster then a SQL query? By the way, the query I show here is a simplified one. The actual query SELECT is more complicated one.
A:
I would create a VIEW for several reasons
A) A well constructed view does tend to perform faster than a query, though with query optimization you may not notice much of a difference.
B) It keeps knowledge of the database structure within the database itself - adding a good layer of abstraction (as a side note, consider using a stored procedure rather than an inline query - this also keeps database knowledge within the database itself)
C) If you do need to make a structural change to the database, you can keep the view consistent without needing to rebuild your code.
AMENDMENT I'm going to amend this answer in light of some of the comments so as to clarify some points ...
It is absolutely true that a standard view does not provide any real performance gain over a query. A standard view is materialized at run time which essentially makes it no different than a convenient way to execute a query of the same structure. An index view, however, is materialized immediately and the results are persisted in physical storage. As with any design decision, the use of an indexed view should be carefully considered. There is no free lunch; the penalty you pay for use of indexed views comes in the form of additional storage requirements and overhead associated with maintaining the view when there are any changes to the underlying database. These are best used in instances of commonly used complex joining and aggregation of data from multiple tables and in cases in which data is accessed far more frequently than it is changed.
I also concur with comments regarding structural changes - addition of new columns will not affect the view. If, however, data is moved, normalized, archived, etc it can be a good way to insulate such changes from the application. These situations are RARE and the same results can be attained through the use of stored procedures rather than a view.
A:
In general I've found it's best to use views for several reasons:
Complex queries can get hard to read in code
You can change the view without recompiling
Related to that, you can handle changes in the underlying database structure in the view without it touching code as long as the same fields get returned
There are probably more reasons, but at this point I would never write a query directly in code.
You should also look into some kind of ORM (Object Relational Mapper) technology like LINQ to SQL (L2S). It lets you use SQL-like queries in your code but everything is abstracted through objects created in the L2S designer.
(I'm actually moving our current L2S objects to run off of views, actually. It's a bit more complicated because the relationships don't come through as well... but it's allowing me to create one set of objects that run across 2 databases, and keep everything nicely abstracted so I can change the underlying table names to fix up naming conventions. )
A:
Or you could use a stored procedure. Using a stored proc will allow SQL to cache the execution plan. I think the same is true of a view. Your first method (ad-hoc query) will probably be the least efficient.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the symbiotic relationship between truffle fungi and their host trees?
I understand that truffles share a symbiotic relationship as they reside among the root systems of host trees, but I cannot find any material that specifies the details of such a relationship. In other words, what exactly do truffles get from their host trees, and what do they provide in turn?
A:
A truffle is the fruiting body of a subterranean Ascomycete fungus, predominantly one of the many species of the genus Tuber. Truffles are ectomycorrhizal fungi and form symbiotic relationships with the roots of several tree species including beech, birch, hazel, hornbeam, oak, pine, and poplar.
Mycorrhizal symbiosis is a mutualistic association between a fungus and the roots of a plant (usually a tree) in which (typically) the fungus obtains energy in the form of carbohydrates from the plant, and the plant gains the benefits of the mycelium's higher absorptive capacity for water and mineral nutrients, partly because of the large surface area of fungal hyphae, which are much longer and finer than plant root hairs, and partly because some such fungi can mobilize soil minerals unavailable to the plants' roots. The effect is thus to improve the plant's mineral absorption capabilities.
Based on the quote below from the website of a truffle nursery in Australia (http://trufficulture.com.au/what_are_truffles.html), it sounds like truffle symbiosis is a completely standard mycorrhizal symbiotic relationship.
The truffle coats the tips of the tree roots to form mycorrhiza which
act as an extension of the tree's root system. The tree provides the
truffle with a source of photosynthesised carbohydrates, and in return
the fine, thread-like filaments (mycelia) of the truffle, extract and
trade soil minerals and nutrients which would normally be unavailable
to the tree. Thus the mycorrhiza is able to increase the effectiveness
of the trees roots, enabling the tree to grow in soils which would
normally be too nutrient deficient to support them.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
general solution for non-homogeneous linear PDEs
suppose we have had the general solution of the homogeneous part, and we have a particular solution for the equation. Will the particular solution plus the general solution for homogeneous part be the general solution for the whole equation? I know we have this kind of theorem in ODE, will it hold for PDE?
A:
Yes. This in true in general for any kind of linear equation. If $T$ is a linear operator, the solution of the linear equation
$$
Tx=f
$$
is
$$
x=x_h+x_p
$$
where $x_h$ is the general solution of $Tx=0$ and $x_p$ a particular solution of $Tx=f$. Proof: let $y$ be any solution. Since $T$ is linear, $y-x_p$ is a solution of $Tx=0$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting req.headers is undefined when trying to read from req object in NextJS
On page load, I try to fire off an authentication request if a token exists in local storage.
// utils.ts
const init = async () => {
try {
const token = window.localStorage.getItem('token');
if (token) {
axios.defaults.headers.common['x-auth-token'] = token;
const { user } = await axios.get('/api/auth/load')
console.log('user!', user);
} else {
delete axios.defaults.headers.common['x-auth-token'];
}
} catch (err) {
console.log('There was an error with init: ', err);
}
}
And my pages/api/auth/load.ts file:
export default async function load(req: TLoadUserRequest, res) {
auth(req, res);
const { id } = req.user;
await connectDb();
const user = await User.findById(id);
return res.json(user);
}
The problem lies within my auth.ts, which throws an error,
TypeError: req.headers is not a function
Here it is:
// middleware/auth.ts
import jwt from 'jsonwebtoken';
import config from 'config';
export default (req, res) => {
const token = req.headers('x-auth-token');
if (!token) return res.status(401).json({ msg: 'No token. Authorization denied.' });
try {
const decoded = jwt.verify(token, config.get('jwtSecret'));
req.user = decoded.user;
} catch (err) {
return res.status(401).json({ msg: 'Token is invalid' });
}
};
When I use Node/Express, I don't get this error -- does NextJS' req object not have a headers property? How can I add it, so I can use it with axios like this?
A:
Your syntax is a bit wrong for getting a header value.
req.headers('x-auth-token')
Should be
req.headers['x-auth-token']
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use ngChange in custom directive
I want to create directive for toggle button, I have code that I want to put into directive:
<div class="toggle-button" ng-class="{true: toggleTrue === true, false: toggleTrue === false}">
<button class="true" ng-click="toggleTrue = true">Y</button><button class="false" ng-click="toggleTrue = false">N</button>
</div>
(I only work on style change, that's why I have only class change)
I want to have something like:
<toogle ng-change="SomeFunction()" ng-model="someValue" />
how can I work with ng-change in my directive? Should I just parse attr or use scope attribute or is there a code like with ngModel that need to be use together with ngChange.
A:
By try and error I found code that work with ngModel and ngChange:
return {
restrict: 'E',
require: 'ngModel',
scope: {},
template: '<div class="toggle-button" ng-class="{true: toggleValue === true, false: toggleValue === false}">'+
'<button class="true" ng-click="toggle(true)">Y</button>'+
'<button class="false" ng-click="toggle(false)">N</button>'+
'</div>',
link: function(scope, element, attrs, ngModel) {
ngModel.$viewChangeListeners.push(function() {
scope.$eval(attrs.ngChange);
});
ngModel.$render = function() {
scope.toggleValue = ngModel.$modelValue;
};
scope.toggle = function(toggle) {
scope.toggleValue = toggle;
ngModel.$setViewValue(toggle);
};
}
};
For unknow reason scope: true don't work (if I have $scope.toggle variable used as model, it try to execute that boolean instead of a function)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Editing field value of a parent
I have my Case object linked to the Contact object with a lookup field (Contact__c). What is the best way to modify the value of a field in a Contact record from the Case record, when there's a contact selected?
For example, I have a Case with the Contact__c lookup populated. I want to modify the value of a picklist in the Contact, from the Case.
A:
If you are looking to do this from the a Case page layout, unfortunately I don't believe this will be possible. A page layout uses a StandardController which doesn't have any functionality innately built into it to save any object but the main object of the controller.
Programmatically this is very simple. You just need to update each object separately, but that won't help you for a page layout.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++ - proper way to map objects (like strings) to member functions in table
I'm processing events defined by a 3rd party API.
The events are identified by string identifiers i.e. "EventABC"
I need to map these (string) events in a table to member-functions of an object.
QUESTION
What's the safest and cleanest way to do this?
A:
Without further constraints, this is easily accomplished with a std::map or std::unordered_map from std::string to std::function<void()>. With C++11 you can use lambdas to unobtrusively capture the this object to call the member functions on.
class HandlerHandler
{
std::map<std::string, std::function<void()>> handlers;
void foo();
void bar();
void frobnicate();
HandlerHandler()
{
handlers["FOO"] = [this](){ foo(); };
handlers["BAR"] = [this](){ bar(); };
handlers["FROB"] = [this](){ frobnicate(); };
}
void handle(std::string h)
{
handlers[h]();
}
};
https://godbolt.org/z/nbygdF
You may want to guard against the case of h not being present in the map (currently it will throw an exception as it tries to call a default-constructed function).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What's the event of blockly structure change?
I have a web app that include blockly and I want to be able to save the structure user created on blockly on backend db.
I just want to know how to get the current workspace structure so I can post it to server to save it.
and then load it again when user login.
Thanks.
A:
From Importing and exporting blocks:
If your application needs to save and store the user's blocks and restore them at a later visit, use this call for export to XML:
var xml = Blockly.Xml.workspaceToDom(workspace);
var xml_text = Blockly.Xml.domToText(xml);
This will produce a minimal (but ugly) string containing the XML for the user's blocks. If one wishes to obtain a more readable (but larger) string, use Blockly.Xml.domToPrettyText instead.
Restoring from an XML string to blocks is just as simple:
var xml = Blockly.Xml.textToDom(xml_text);
Blockly.Xml.domToWorkspace(xml, workspace);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Finding eigenvalues for a $4\times4$ matrix
I am trying to find the eigenvalues for this $4\times4$ matrix $A$, where $A$ is
\begin{bmatrix}
2 & 1 & 1 & 1 \\
1 & 2 & 1 & 1 \\
0 & 0 & 2 & 1 \\
0 & 0 & 1 & 2 \\
\end{bmatrix}
I was wondering if there is an easy way to do it or do I have to find the determinant the long way?
A:
Result 1: Eigenvalues of the matrix in a triangular form is the entries of the principal diagonal. For example, if we have the following matrix (Upper triangular)
\begin{bmatrix} 2 & 1 & -1 & -1 \\ 0 & 2 & 1 & 1 \\ 0 & 0 & 2 & 1 \\ 0 & 0 & 0 & 2 \\ \end{bmatrix}
Then eigenvalues of this matrix are given by the entries of principal diagonal which are $2, 2, ,2 ,2$. That is $2$ with algebraic multiplicity $4$.
Generalized form of above result can be summarized from the below example which may help you to solve your problem.
Consider the following matrix
\begin{bmatrix} A_1 & B \\ \mathcal{O} & A_2 \\ \end{bmatrix}
where $A_1$ and $A_2$ are square matrices and $\mathcal{O}$ is the matrix with zero entries.
Eigenvalue of above matrix can be obtained by computing the eigenvalues of matrices $A_1$ and $A_2$. Since Characteristic polynomial of this matrix is the product of Characteristic polynomial of $A_1$ and $A_2$.
In your problem you can take $A_1 $ to be
\begin{bmatrix} 2 & 1 \\ 1 & 2 \\ \end{bmatrix}
and
$A_2 $ to be
\begin{bmatrix} 2 & 1 \\ 1 & 2 \\ \end{bmatrix}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
screen scraping using Ghost.py
Here is the simple program which does not work
from ghost import Ghost
ghost = Ghost(wait_timeout=40)
page, extra_resources = ghost.open("http://samsung.com/in/consumer/mobile-phone/mobile-phone/smartphone/")
ghost.wait_page_loaded()
n=2;
links=ghost.evaluate("alist=document.getElementsByTagName('a');alist")
print links
ERROR IS: raise Exception(timeout_message)
Exception: Unable to load requested page
iS there some problem with the program?
A:
Seem like people are reporting similar issues to yours, without really getting any explanation (for example: https://github.com/jeanphix/Ghost.py/issues/26)
Adjust the evaluate line to the following, which is referenced by a ghost.py documentation:
links = gh.evaluate("""
var links = document.querySelectorAll("a");
var listRet = [];
for (var i=0; i<links.length; i++){
listRet.push(links[i].href);
}
listRet;
""")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Populate MySQL table from Text file
This should be an easy one. I need to populate a table from a text file. Basically, I'd like to do this in a linux shell script. Thanks!!
Example:
MySQL Table
Item color shape size
Textfile
car blue round small
carrot red square big
apple green round medium
A:
You could run a query like this:
LOAD DATA INFILE 'data.txt' INTO TABLE yourTable
FIELDS TERMINATED BY ' '
LINES TERMINATED BY '\n'
And then all you need is to write a tiny shell script, executing the query.
Edit:
A complete script could look something like this:
#!/bin/bash
mysql databaseName<<EOFMYSQL
LOAD DATA INFILE 'data.txt' INTO TABLE yourTable
FIELDS TERMINATED BY ' '
LINES TERMINATED BY '\n';
EOFMYSQL
The script could be executed like this:
chmod +x script.sh
./script.sh
You probably run into user issues, since the shell does not handle mysql directly. Try looking into how you can execute mysql without logging in. This should be part of just about any mysql backup script :-)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Giving table cells equal height
I am trying to make a square table with an unknown number of rows and columns. The table should always be 90% screen width and have an equal height, but when I give the table the correct height, only the top row gets rescaled.
.interface div {
display: inline-block;
width: 30%;
text-align: center;
padding: 10px;
margin-left: auto;
margin-right: auto;
}
.interface {
margin-left: auto;
margin-right: auto;
width: 50%;
text-align: center;
padding: 10px;
}
#board {
width: 90vw;
height: 90vw;
table-layout: fixed;
}
.boardSpace {
border-radius: 10px;
border: 5px solid black;
}
<table id="board">
<tbody>
<tr id="boardRow0">
<td id="boardSpace0" class="boardSpace" onclick="placeBlock(0, 0)">0</td>
<td id="boardSpace1" class="boardSpace" onclick="placeBlock(1, 0)">1</td>
<td id="boardSpace2" class="boardSpace" onclick="placeBlock(2, 0)">2</td>
<td id="boardSpace3" class="boardSpace" onclick="placeBlock(3, 0)">3</td>
<td id="boardSpace4" class="boardSpace" onclick="placeBlock(4, 0)">4</td>
<td id="boardSpace5" class="boardSpace" onclick="placeBlock(5, 0)">5</td>
</tr>
</tbody>
<tbody>
<tr id="boardRow1">
<td id="boardSpace6" class="boardSpace" onclick="placeBlock(0, 1)">6</td>
<td id="boardSpace7" class="boardSpace" onclick="placeBlock(1, 1)">7</td>
<td id="boardSpace8" class="boardSpace" onclick="placeBlock(2, 1)">8</td>
<td id="boardSpace9" class="boardSpace" onclick="placeBlock(3, 1)">9</td>
<td id="boardSpace10" class="boardSpace" onclick="placeBlock(4, 1)">10</td>
<td id="boardSpace11" class="boardSpace" onclick="placeBlock(5, 1)">11</td>
</tr>
</tbody>
<tbody>
<tr id="boardRow2">
<td id="boardSpace12" class="boardSpace" onclick="placeBlock(0, 2)">12</td>
<td id="boardSpace13" class="boardSpace" onclick="placeBlock(1, 2)">13</td>
<td id="boardSpace14" class="boardSpace" onclick="placeBlock(2, 2)">14</td>
<td id="boardSpace15" class="boardSpace" onclick="placeBlock(3, 2)">15</td>
<td id="boardSpace16" class="boardSpace" onclick="placeBlock(4, 2)">16</td>
<td id="boardSpace17" class="boardSpace" onclick="placeBlock(5, 2)">17</td>
</tr>
</tbody>
<tbody>
<tr id="boardRow3">
<td id="boardSpace18" class="boardSpace" onclick="placeBlock(0, 3)">18</td>
<td id="boardSpace19" class="boardSpace" onclick="placeBlock(1, 3)">19</td>
<td id="boardSpace20" class="boardSpace" onclick="placeBlock(2, 3)">20</td>
<td id="boardSpace21" class="boardSpace" onclick="placeBlock(3, 3)">21</td>
<td id="boardSpace22" class="boardSpace" onclick="placeBlock(4, 3)">22</td>
<td id="boardSpace23" class="boardSpace" onclick="placeBlock(5, 3)">23</td>
</tr>
</tbody>
<tbody>
<tr id="boardRow4">
<td id="boardSpace24" class="boardSpace" onclick="placeBlock(0, 4)">24</td>
<td id="boardSpace25" class="boardSpace" onclick="placeBlock(1, 4)">25</td>
<td id="boardSpace26" class="boardSpace" onclick="placeBlock(2, 4)">26</td>
<td id="boardSpace27" class="boardSpace" onclick="placeBlock(3, 4)">27</td>
<td id="boardSpace28" class="boardSpace" onclick="placeBlock(4, 4)">28</td>
<td id="boardSpace29" class="boardSpace" onclick="placeBlock(5, 4)">29</td>
</tr>
</tbody>
<tbody>
<tr id="boardRow5">
<td id="boardSpace30" class="boardSpace" onclick="placeBlock(0, 5)">30</td>
<td id="boardSpace31" class="boardSpace" onclick="placeBlock(1, 5)">31</td>
<td id="boardSpace32" class="boardSpace" onclick="placeBlock(2, 5)">32</td>
<td id="boardSpace33" class="boardSpace" onclick="placeBlock(3, 5)">33</td>
<td id="boardSpace34" class="boardSpace" onclick="placeBlock(4, 5)">34</td>
<td id="boardSpace35" class="boardSpace" onclick="placeBlock(5, 5)">35</td>
</tr>
</tbody>
</table>
The table is generated by javascript, but I put the default 6x6 table in for this example. Meaning this is what the Index document looks like after generating a table.
A:
Try only using one <tbody></tbody> set of tags.
<table id="board">
<tbody>
<tr id="boardRow0">
<td id="boardSpace0" class="boardSpace" onclick="placeBlock(0, 0)">0</td>
<td id="boardSpace1" class="boardSpace" onclick="placeBlock(1, 0)">1</td>
<td id="boardSpace2" class="boardSpace" onclick="placeBlock(2, 0)">2</td>
<td id="boardSpace3" class="boardSpace" onclick="placeBlock(3, 0)">3</td>
<td id="boardSpace4" class="boardSpace" onclick="placeBlock(4, 0)">4</td>
<td id="boardSpace5" class="boardSpace" onclick="placeBlock(5, 0)">5</td>
</tr>
<tr id="boardRow1">
<td id="boardSpace6" class="boardSpace" onclick="placeBlock(0, 1)">6</td>
<td id="boardSpace7" class="boardSpace" onclick="placeBlock(1, 1)">7</td>
<td id="boardSpace8" class="boardSpace" onclick="placeBlock(2, 1)">8</td>
<td id="boardSpace9" class="boardSpace" onclick="placeBlock(3, 1)">9</td>
<td id="boardSpace10" class="boardSpace" onclick="placeBlock(4, 1)">10</td>
<td id="boardSpace11" class="boardSpace" onclick="placeBlock(5, 1)">11</td>
</tr>
<tr id="boardRow2"><td id="boardSpace12" class="boardSpace" onclick="placeBlock(0, 2)">12</td>
<td id="boardSpace13" class="boardSpace" onclick="placeBlock(1, 2)">13</td>
<td id="boardSpace14" class="boardSpace" onclick="placeBlock(2, 2)">14</td>
<td id="boardSpace15" class="boardSpace" onclick="placeBlock(3, 2)">15</td>
<td id="boardSpace16" class="boardSpace" onclick="placeBlock(4, 2)">16</td>
<td id="boardSpace17" class="boardSpace" onclick="placeBlock(5, 2)">17</td>
</tr>
<tr id="boardRow3">
<td id="boardSpace18" class="boardSpace" onclick="placeBlock(0, 3)">18</td>
<td id="boardSpace19" class="boardSpace" onclick="placeBlock(1, 3)">19</td>
<td id="boardSpace20" class="boardSpace" onclick="placeBlock(2, 3)">20</td>
<td id="boardSpace21" class="boardSpace" onclick="placeBlock(3, 3)">21</td>
<td id="boardSpace22" class="boardSpace" onclick="placeBlock(4, 3)">22</td>
<td id="boardSpace23" class="boardSpace" onclick="placeBlock(5, 3)">23</td>
</tr>
<tr id="boardRow4">
<td id="boardSpace24" class="boardSpace" onclick="placeBlock(0, 4)">24</td>
<td id="boardSpace25" class="boardSpace" onclick="placeBlock(1, 4)">25</td>
<td id="boardSpace26" class="boardSpace" onclick="placeBlock(2, 4)">26</td>
<td id="boardSpace27" class="boardSpace" onclick="placeBlock(3, 4)">27</td>
<td id="boardSpace28" class="boardSpace" onclick="placeBlock(4, 4)">28</td>
<td id="boardSpace29" class="boardSpace" onclick="placeBlock(5, 4)">29</td>
</tr>
<tr id="boardRow5">
<td id="boardSpace30" class="boardSpace" onclick="placeBlock(0, 5)">30</td>
<td id="boardSpace31" class="boardSpace" onclick="placeBlock(1, 5)">31</td>
<td id="boardSpace32" class="boardSpace" onclick="placeBlock(2, 5)">32</td>
<td id="boardSpace33" class="boardSpace" onclick="placeBlock(3, 5)">33</td>
<td id="boardSpace34" class="boardSpace" onclick="placeBlock(4, 5)">34</td>
<td id="boardSpace35" class="boardSpace" onclick="placeBlock(5, 5)">35</td>
</tr>
</tbody>
</table>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Running tesseract 4.1 with openjpeg2 - cannot produce pdf output
I have installed on my RedHat machine:
(py36_maw) [rvp@lib-archcoll box]$ tesseract -v
tesseract 4.1.0
leptonica-1.78.0
libjpeg 6b (libjpeg-turbo 1.2.90) : libpng 1.5.13 : libtiff 4.0.3 : zlib 1.2.7 : libopenjp2 2.3.1
Found SSE
I try to run, per what docs I can find, to produce pdf output:
(py36_maw) [rvp@lib-archcoll box]$ time tesseract test.jp2 out -l eng PDF
read_params_file: Can't open PDF
Tesseract Open Source OCR Engine v4.1.0 with Leptonica
Warning: Invalid resolution 0 dpi. Using 70 instead.
Estimating resolution as 275
That takes 10 seconds and produces file out.txt with fine OCR to text conversion evident.
However, it tries to read a file called PDF, but I cannot figure how to get PDF output.
I have read various docs, the most promising seeming to be advising to edit the config file, but the only docs I can guess are relevant, by googling 'tesseract 4.1 config', list many 'config' variable names, for older versions of tesseract, but none of which seems to indicate I can specify producing pdf output, much less specifically for tesseract 4.1.
How can I invoke tesseract 4.1 (using libopenjp2 2.3.1) via CLI to produce pdf output from my jp2 input file? Bonus question: how can I get it to produce both txt and pdf output in one run?
Robert
A:
After more surfing and digging, assuming the reader also has done some and knows what TESSDATA_PREFIX is used for by tesseract, here are the steps that worked for me:
Download the pdf.ttf file from: https://github.com/tesseract-ocr/tesseract/blob/master/tessdata/pdf.ttf
Copy pdf.ttf to your directory $TESSDATA_PREFIX and make sure that variable is exported to your shell.
TIP: Use command: tesseract --print-parameters # to discover defined variable names you can use in your own config file
Go to your dir with the test.jp2 file and create file config with these lines.
tessedit_create_pdf 1 Write .pdf output file
tessedit_create txt 1 Write .txt output file
(Note: or you may be able to put the config file in the TESSDATA_PREFIX directory as well and let it always be the default. Not tested.)
Run in that dir:
$ tesseract test.jp2 outputbase -l eng config
Verify your success: it runs and produces files outputbase.txt and outputbase.pdf. The txt file looks good and the searchable pdf looks and works OK in a pdf viewer, that is, you can search and find text strings.
Hope this helps someone else!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using XAML/WPF in PowerShell, how do I populate a list box?
I've found a number of great threads here but can't seem to track down my answer. I'm making a GUI using Visual Studio and copy/pasting the XAML into PowerShell. I know I should be doing this in c#, but as my knowledge isn't there yet, it's pure PowerShell for me.
So I've got my GUI made, but I can't seem to populate my data fields. Doing other things like textboxes were solvable, but I can't seem to get this listview / data grid to populate with values.
At this moment, the connection to Azure has been removed, until I can resolve this hitch of adding items to my list box.
XAML to draw my form
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Azure"
Title="Azure Accelerator" Height="300" Width="315">
<Grid Margin="0,0,174,0">
<Image Name="image" HorizontalAlignment="Left" Height="46" Margin="10,10,-97,0" VerticalAlignment="Top" Width="210" Source="C:\Users\stephen\Dropbox\My Code\Powershell\WPF\mslogo.png"/>
<TextBlock Name="textBlock" HorizontalAlignment="Left" Height="21" Margin="10,61,-140,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="248" Text="VM PickerUse"/>
<Button Name="btnOK" Content="OK" HorizontalAlignment="Left" Margin="217,268,-160,0" VerticalAlignment="Top" Width="75" Height="23"/>
<Button Name="btnExit" Content="Cancel" HorizontalAlignment="Left" Margin="12,268,0,0" VerticalAlignment="Top" Width="75" Height="23"/>
<ListView Name="listView" HorizontalAlignment="Left" Height="108" Margin="12,107,-140,0" VerticalAlignment="Top" Width="246">
<ListView.View>
<GridView>
<GridViewColumn Header="VMName" DisplayMemberBinding ="{Binding VMName}"/>
<GridViewColumn Header="Status" DisplayMemberBinding ="{Binding Status}"/>
<GridViewColumn Header="Other"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
'@
Loading the XAML into memory/making objects
#Read XAML
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
try{$Form=[Windows.Markup.XamlReader]::Load( $reader )}
catch{Write-Host "Unable to load Windows.Markup.XamlReader. Some possible causes for this problem include: .NET Framework is missing PowerShell must be launched with PowerShell -sta, invalid XAML code was encountered."}
#===========================================================================
# Store Form Objects In PowerShell
#===========================================================================
$xaml.SelectNodes("//*[@Name]") | %{Set-Variable -Name "VMpick$($_.Name)" -Value $Form.FindName($_.Name)}
Where I probably need help
#Try to setup a dummy entry
$vmpicklistView.items.Add( @{'VMName'='1';Status="AccessDenied";'Other'='1'})
#===========================================================================
# Shows the form
#===========================================================================
$Form.ShowDialog() | out-null
As you can see from my screen shot, when I added a binding to the columns (which I thought would instantiate the columns and let me plug in values for them...nope) they no longer update when I try to add a new item. However, the 'Other' column, which I did not apply the binding to, does at least show someput, but it incorrectly lists Collection, as if it is trying to display the whole hashtable.
So, my final question, how do I add items to a listview?
A:
Alright, I figured out the answer. It turns out that when I was using .Add, I should have been specifying a PowerShell custom object as my overload, not a simple hashtable as I was doing before. When I changed my code to the following:
#Add DisplayMemberBindings for all columns
<GridViewColumn Header="VMName" DisplayMemberBinding ="{Binding VMName}"/>
<GridViewColumn Header="Status" DisplayMemberBinding ="{Binding Status}"/>
<GridViewColumn Header="Other" DisplayMemberBinding ="{Binding Other}"/>
And then modify my Add statement as well:
$vmpicklistView.items.Add([pscustomobject]@{'VMName'='1';Status="Access Denied";Other="Yes"})
I'm able to populate my fields, like so
#Make Dummy Entries
1..15 | % {
if ($_ % 2){$vmpicklistView.items.Add([pscustomobject]@{'VMName'="VM_$($_)";Status="Online";Other="Yes"})}
else{$vmpicklistView.items.Add([pscustomobject]@{'VMName'="VM_$($_)";Status="Access Denied";Other="Yes"})}
}
Why did I have to do this?
Here is my interpretation as to why this was needed. PowerShell Custom Objects provide an Object with Named values, which I can pluck out using bindings, while a hashtable is a collection of Key/Value pairs, not well suited for this purpose.
I hope this answer has helped anyone else who got stumped as I did!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to assign a test file in resharper?
how to assign a test file in resharper?
whenever I select 'run tests' it says no test file found.
I created a test project, how do I link it?
A:
I've only done minimal work with NUnit and Resharper, but the way I've always done it is just write all of the test code in your test project, and link/include the library you want to test using using statements. Make sure to include the [TestFixture] and [Test] attributes in your test classes, and when you select "Run Unit Tests" in VS on your test project, it should go through each [TestFixture] class and run all of the [Test] functions.
All that being said, I have found that running nunit tests in Resharper (v3.1 at least) to be less than ideal. It does not recognize some test conditions such as ExpectedException, so I always run my tests directly in NUnit itself.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find the fundamental group of the torus with an open disc removed
I'm trying to find a fundamental group of $\mathbb{T} \setminus \mathbb{D}$, the $2$-torus $\mathbb{T}$ with an open disc $\mathbb{D}$ removed. Any help would be really appreciated.
A:
Big hint: View the torus as the square $I^2/\sim$ with the usual equivalence relation $\sim$ identifying opposite edges, and then removes a small disk from the interior of $I^2$. Can you see how this space is homotopy equivalent to a wedge of some number of circles? (I'll leave you to figure out how many)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
why can't get readyState 3 when doing a ajax
i read from books that if i do a ajax request from sever, i will get readyState from 0 - 4. here is my code:
xhr = new XMLHttpRequest();
console.log(xhr.readyState);
xhr.onreadystatechange = function() {
console.log(xhr.readyState);
};
xhr.open('GET', 'http://localhost:81/data.txt', true);
xhr.send();
i see from the console that 0 1 2 4 exit, and 3 is not, why does this happen?
pls help me thank you~
A:
You have a small payload so RS3 goes by so fast the response is NULL
AND/OR
Your response is returning NULL in Chrome (Assuming you are using Chrome) because that is what webkit browsers do with RS3
Try setting ...
Content-type: text/xml
Also you need to push at least 1k of data before it sends any response besides NULL in RS3 in Chrome, though the "official" threshold is 256b, its not correct and Chrome doesn't start sending until about 1k+ has been rendered.
This is basically true of all webkit browsers
But it's OK because you don't need anything from RS3. RS4 is the only thing you really need to worry about.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dispatcher.BeginInvoke lambda capture thread-safe?
In Windows Phone 7 / Silverlight, is the following code safe or is it a race condition?
//Snippet 1
foreach(var item in list)
{
Deployment.Current.Dispatcher.BeginInvoke( () => { foo(item); });
}
Surely (?) this alternative is racy?
//Snippet 2
Deployment.Current.Dispatcher.BeginInvoke( () =>
{
foreach(var item in list){ foo(item); }
});
list.Clear();
A:
"Race condition" may not be the best way to put the problem with the first snippet. But basically, you are using a captured variable outside the capture scope. The value of "item" will end up being the last item then your foo method is called, for all items.
Instead, do this:
foreach(var item in list)
{
var tmpItem = item;
Deployment.Current.Dispatcher.BeginInvoke( () => foo(tmpItem));
}
This puts a variable in a lower scope, and it is captured in that scope. This makes sure that each value is captured and sent to foo.
The second version is almost certainly an error given a sane scope of the list variable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
wcf webservice not running
I m trying to create a wcf service
but it keep bugging me with the below error while running
HTTP could not register URL http://+:80/ConsoleWCFapp/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).
code
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(StockService), new Uri("http://localhost:8000/ConsoleWCFapp"));
host.AddServiceEndpoint(typeof(IStockService), new BasicHttpBinding(), "");
host.Open();
Console.WriteLine("Listening to request now, Please enter to exit \n\n");
Console.ReadLine();
host.Close();
}
please advice
A:
Run the code / Visual Studio as Administrator. I just ran into the same thing in my environment.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use a Switch Statement in PHP with FORM Post to Update, Search, and Insert into SQL Database?
I have a form that has user input fields and 3 submit buttons at the bottom of the form. It's supposed to either update, insert, or search database records when filled out. I've tested my database connection and it is connecting. I've tested my Post and it is not null. But on my results page the only thing I ever see displayed is my default in my switch statement. So it seems like none of my case statements are working. The switch statement is supposed to work off of the $action submitted - either insert, update, or search.
form.php
<input type="submit" value="insert" name="action" class="btn btn-default">
<input type="submit" value="update" name="action" class="btn btn-default">
<input type="submit" value="search" name="action" class="btn btn-default">
form-results.php
require_once 'DataBaseConnection.php';
$firstName = $_POST['$firstName'];
$lastName = $_POST['$lastName'];
$phoneNumber = $_POST['$phoneNumber'];
$address1 = $_POST['$address1'];
$city = $_POST['$city'];
$zip = $_POST['$zip'];
$birthday = $_POST['$birthday'];
$username = $_POST['$username'];
$password = $_POST['$password'];
$sex = $_POST['$sex'];
$relationship = $_POST['$relationship'];
$action = $_POST['$action'];
?>
<div class="container">
<div class="row" style="padding-top:100px;">
<div class="col-md-12 col-sm-12">
<h2>Family & Friends Form</h2>
<p>Results:</p>
<?php
if ( !empty($_POST) ) { echo"<p>not empty post</p>";}
switch ($action){
case "insert":
$insert = "INSERT INTO `friends_family`.`users` (`firstName`,`lastName`,`phoneNumber`,`address1`,`city`,`state`,`zip`,`birthday`,`username`,`password`,`relationship`)
VALUES (`$firstName`, `$lastName`, `$phoneNumber`,`$address1`, `$city`,`$state`, `$zip`,`$birthday`,`$username`,`$password`,`$relationship`)";
$success = $con->query($insert);
if ($success == FALSE) {
$failmess = "Whole query " . $insert . "<br>";
echo $failmess;
die('Invalid query: '. mysqli_error($con));
} else {
echo "$firstName was added<br>";
}
break;
case "update":
$update = "UPDATE `friends_family`.`users` SET `phoneNumber` = '$phoneNumber', `address1` = '$address1', `city` = '$city', `zip` ='$zip', `birthday` = '$birthday',`username` = '$username',`password` = '$password',`relationship`='$relationship' WHERE `firstName` = '$firstName', `lastName`='$lastName'";
echo "$firstName $lastName was updated<br>";
break;
case "search":
$search = "SELECT * FROM friends_family.users WHERE firstName like '%$firstName%' ORDER BY firstName";
$return = $con->query($search);
if (!$return) {
$message = "Whole query " . $search;
echo $message;
die('Invalid query: ' . mysqli_error($con));
}
echo "<table class='table'><thead><th>First Name</th><th>Last Name</th><th>Phone</th><th>Address</th><th>City</th><th>State</th><th>Zip</th><th>Birthday</th><th>Sex</th><th>Relationship</th></thead><tbody>\n";
while ($row = $return->fetch_assoc()){
echo "<tr><td>" . $row['firstName']
. "</td><td>" . $row['lastName']
. "</td><td>" . $row['phoneNumber']
. "</td><td>" . $row['address1']
. "</td><td>" . $row['city']
. "</td><td>" . $row['state']
. "</td><td>" . $row['zip']
. "</td><td>" . $row['birthday']
. "</td><td>" . $row['sex']
. "</td><td>" . $row['relationship'] . "</td></tr>\n";
}
echo "</tbody></table>";
break;
default:
echo "Error";
break;
}
mysqli_close($con);
?>
</div>
</div>
A:
The name of the form element is action, not $action. So this:
$_POST['$action']
should be this:
$_POST['action']
(And similarly for the rest of your form elements.)
It's also worth noting that your code is wide open to SQL injection. You should look into using prepared statements with query parameters. This and this are good places to start.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to connect to a web service from windows mobile(when running emulator)
I have as asp.net webserver that I hosted and I went to my mobile application I am building and made a web reference to it.
So it finds it and stuff and now I can access the web methods because of the wsdl generated. However when it tries to connect I get this:
Could not establish connection to network.
So do I have to enable something to make this work?
A:
Take a look at this article. It explains how to setup your mobile device for internet connectivity.
Windows Mobile Emulator and Internet Connectivity
It's been awhile since i have had to do this. Perhaps it is as easy as Matt has suggested, I can remember having a hard time making this work with Windows Vista, Visual Studio 2005 and the Windows Mobile 5.0 Pocket PC Emulator. I've found a couple more articles, hope this helps.
HOWTO: Configure Network in Windows Mobile / PocketPC Device Emulator
Making Emulator to connect to the Network
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find Values in CSV that only Appear Once
I have a csv file with thousands of lines in it. I'd like to be able to find values that only appear once in this file.
For instance
dog
dog
cat
dog
bird
I'd like to get as my result:
cat
bird
I tried using the following awk command but it returned one of each value in the file:
awk -F"," '{print $1}' test.csv|sort|uniq
Returns:
dog
cat
bird
Thank you for your help!
A:
Just with awk:
awk -F, '{count[$1]++} END {for (key in count) if (count[key] == 1) print key}' test.csv
A:
Close. Try:
awk -F"," '{print $1}' test.csv |sort | uniq -c | awk '{if ($1 == 1) print $2}'
the -c flag on uniq will give you counts. Next awk will look for any items with the count of 1 (first field) and print the value of the second field ($2)
Only caveat is that this will return bird before cat due to it being previously sroted. you could pipe once more to sort -r to reverse the sort direction. This would be identical to the expected answer you asked for, but it is not the original sort order.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can a transceiver pin be used if its clock is so much faster than the FPGA clock?
I'm trying to understand how a transceiver pin can actually operate at, say, 2.5GHz given that the clock speed of an FPGA is so much slower. In my understanding, to transmit data you need to synchronize pulses so that, given that you have a lot of data to send, you 'pulse' for a certain time, and that time is controlled by the clock. Or am I misunderstanding how transceiver pins work?
A:
The external clock input(s) to an FPGA is typically in the range of 10 to 100 MHz, depending on the application. However, all FPGAs include some number of PLLs (phase-locked loops) that can be used to multiply the clock internally to a much higher value. It is these high-speed clocks that are used to drive the SERDES (serializer-deserializer) logic in the IOBs (I/O buffers — i.e., pad drivers and receivers).
A:
The pins that operate at 2.5GHz (and much higher) are for a SERDES (SERialiser/DESerialiser) that operates completely independently of the FPGA system clock. Link protocols such as HDMI, PCIe and SATA (to name only a few) operate using this type of transceiver.
This is a self-clocked self-synchronising serial single bit interface. As it would be practically impossible to attempt to synchronise multiple paths with a clock path much above a few 100MHz, it forgoes any attempt at synchronising anything to anything.
The serialiser accepts word data from the FPGA, and converts 8 bit bytes to 10 bit words, which introduces enough redundancy so that clock, byte and frame alignment can be recovered at the receiving end.
Where multiple lanes are used for higher link throughput, there is no synchronisation between them at the 2.5GHz level. Data is framed, and lane to lane alignment occurs at the much slower and more practical frame level.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NullPointerException when trying to print random values in android studio
I keep getting a null pointer exception at lines 99 and 77, which is where I attempt to print the random values created by the random class (line 99), and where I call my setQuestion method (line 77. randomNum to the layout_game xml file. I'm not sure why I am getting a null value because when i log the values to the console it says that values are being generated.
package com.grantsolutions.mathgamechapter1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class GameActivity extends Activity implements OnClickListener {
int correctAnswer;
Button buttonObjectChoice1;
Button buttonObjectChoice2;
Button buttonObjectChoice3;
TextView textObjectPartA //it says that textObjectPartA and B are never used;
TextView textObjectPartB;
TextView textObjectScore;
TextView textObjectLevel;
int currentScore;
int currentLevel = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_game);
//declaring variables for game
//no longer being declared
/*int partA = 2;
int partB = 2;
correctAnswer = partA * partB;
int wrongAnswer1 = correctAnswer - 1;
int wrongAnswer2 = correctAnswer + 1;
/*this is where we link the variables
from the java code to the button UI in
activity_game xml itself
*/
TextView textObjectPartA = (TextView) findViewById(R.id.holdTextA);
TextView textObjectPartB = (TextView) findViewById(R.id.holdTextB);
textObjectScore = (TextView) findViewById(R.id.textLevel);
textObjectLevel = (TextView) findViewById(R.id.textScore);
buttonObjectChoice1 =
(Button) findViewById(R.id.choice1);
buttonObjectChoice2 =
(Button) findViewById(R.id.choice2);
buttonObjectChoice3 =
(Button) findViewById(R.id.choice3);
/*Use the setText method of the class on our objects
to show our variable values on the UI elements.
Similar to outputting to the console in the exercise,
only using the setText method*/
//telling the console to listen for button clicks from the user
buttonObjectChoice1.setOnClickListener(this);
buttonObjectChoice2.setOnClickListener(this);
buttonObjectChoice3.setOnClickListener(this);
setQuestion();
}
void setQuestion() {
Random randomNum;
randomNum = new Random();
int partA = 0;
int numberRange = currentLevel * 3;
partA = randomNum.nextInt(numberRange) + 1;
//removes possibility of a zero value
int partB = randomNum.nextInt(numberRange) + 1;
correctAnswer = partA * partB;
Log.i("info", ""+partA);
Log.i("info", ""+partB);
Log.d("info", ""+partA);
int wrongAnswer1 = correctAnswer - 2;
int wrongAnswer2 = correctAnswer + 2;
Log.i("info", ""+partA);
Log.i("info", ""+partB);
textObjectPartA.setText(""+partA); //error here
textObjectPartB.setText(""+partB);
//case for setting multiple choice buttons
int buttonLayout = randomNum.nextInt(3);
switch (buttonLayout) {
case 0:
buttonObjectChoice1.setText("" + correctAnswer);
buttonObjectChoice2.setText("" + wrongAnswer1);
buttonObjectChoice3.setText("" + wrongAnswer2);
break;
case 1:
buttonObjectChoice2.setText("" + correctAnswer);
buttonObjectChoice1.setText("" + wrongAnswer1);
buttonObjectChoice3.setText("" + wrongAnswer2);
break;
case 2:
buttonObjectChoice3.setText("" + correctAnswer);
buttonObjectChoice1.setText("" + wrongAnswer1);
buttonObjectChoice2.setText("" + wrongAnswer2);
break;
}
}
void updateScoreAndLevel(int answerGiven) {
if (isCorrect(answerGiven)) {
for (int i = 1; i <= currentLevel; i++) {
currentScore = currentScore + i;
}
} else {
currentLevel = 1;
currentScore = 0;
}
currentLevel++;
}
boolean isCorrect(int answerGiven) {
boolean correctTrueOrFalse = true;
if (answerGiven == correctAnswer) {//YAY!
Toast.makeText(getApplicationContext(), "Well Done", Toast.LENGTH_LONG).show();
}
else {//If wrong print this instead
Toast.makeText(getApplicationContext(), "You're wrong", Toast.LENGTH_SHORT).show();
} //case for each button being made
correctTrueOrFalse = false;
return correctTrueOrFalse;
}
@Override
public void onClick (View view){
//declaring a new int to use in all cases
int answerGiven;
switch (view.getId()) {
//case for each button being made
case R.id.choice1:
//button1 information goes here
//initialize a new integer with the value
//contained in buttonObjectChoice1
answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText());
//check if the right answer
break;
case R.id.choice2:
//button2 information goes here
answerGiven = Integer.parseInt("" + buttonObjectChoice2.getText());
break;
case R.id.choice3:
//button 3 information goes here
answerGiven = Integer.parseInt("" + buttonObjectChoice3.getText());
break;
}
}
}
code snippet for lines 99 and 77 here
line 77
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_game);
TextView textObjectPartA = (TextView) findViewById(R.id.holdTextA);
TextView textObjectPartB = (TextView) findViewById(R.id.holdTextB);
textObjectScore = (TextView) findViewById(R.id.textLevel);
textObjectLevel = (TextView) findViewById(R.id.textScore);
buttonObjectChoice1 =
(Button) findViewById(R.id.choice1);
buttonObjectChoice2 =
(Button) findViewById(R.id.choice2);
buttonObjectChoice3 =
(Button) findViewById(R.id.choice3);
/*Use the setText method of the class on our objects
to show our variable values on the UI elements.
Similar to outputting to the console in the exercise,
only using the setText method*/
//telling the console to listen for button clicks from the user
buttonObjectChoice1.setOnClickListener(this);
buttonObjectChoice2.setOnClickListener(this);
buttonObjectChoice3.setOnClickListener(this);
setQuestion(); //code error shown in this line
}
line 99
Log.i("info", ""+partA);
Log.i("info", ""+partB);
textObjectPartA.setText(""+partA); //error here
textObjectPartB.setText(""+partB);
the layout_game file
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="2"
android:id="@+id/holdTextA"
android:layout_marginTop="44dp"
android:textSize="50sp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="44dp"
android:layout_marginStart="44dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="X"
android:id="@+id/textView4"
android:layout_alignTop="@+id/holdTextA"
android:layout_centerHorizontal="true"
android:textSize="50sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="4"
android:id="@+id/holdTextB"
android:textSize="50sp"
android:layout_above="@+id/textView6"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="53dp"
android:layout_marginEnd="53dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="="
android:id="@+id/textView6"
android:layout_marginTop="118dp"
android:layout_below="@+id/textView4"
android:layout_alignLeft="@+id/textView4"
android:layout_alignStart="@+id/textView4"
android:textSize="60sp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/choice1"
android:text="2"
android:textSize="40sp"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/holdTextA"
android:layout_alignEnd="@+id/holdTextA"
android:layout_marginBottom="37dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:id="@+id/choice2"
android:layout_alignBottom="@+id/choice1"
android:layout_alignLeft="@+id/holdTextB"
android:layout_alignStart="@+id/holdTextB"
android:textSize="40sp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:id="@+id/choice3"
android:layout_alignBottom="@+id/choice1"
android:layout_centerHorizontal="true"
android:layout_alignTop="@+id/choice1"
android:textSize="40sp" />
A:
In your
onCreateView()
you have declared
TextView textObjectPartA = (TextView) findViewById(R.id.holdTextA);
This way your global variable textObjectPartA has not been set, and hence the null point exception.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
¿Cómo obtener el mismo resultado de esta función para calcular el hash con sha1 y codificarla en base 64?
En PHP uso:
$hash = base64_encode(sha1($password.$key, true).$key);
Y en Node.js yo utilizo estas líneas para hacer un nuevo hash pero... no tengo los mismos resultados que con php
var hash = crypto.createHash('sha1').update(password + key).digest('base64');
A:
Puntualmente el problema que pude ver es que en PHP al usar sha1 y establecer $raw_output = true (segundo parámetro), el resumen sha1 será devuelto en formato binario.
Es por esto que en NodeJS al generar el hash SHA1, al resultado también es en necesario convertirlo a binary (o Latin1 que es lo mismo).
Intenta hacerlo así
crypto
// Generamos el SHA1, lo convertimos a 'binary'
var sha1 = crypto.createHash('sha1').update(password + key).digest('latin1') + key;
// Encodeamos a Base64
var hash = new Buffer(sha1, 'latin1').toString('base64');
crypto-js
// Generamos el SHA1, lo convertimos a 'binary'
var sha1 = crypto.SHA1(password + key).toString(crypto.enc.Latin1) + key;
// Creamos un WordArray para poder hacer el encode de la nueva cadena
var wordArray = crypto.enc.Latin1.parse(sha1);
// Encodeamos a Base64
var hash = crypto.enc.Base64.stringify(wordArray);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Set svn keywords recursively on *.cpp and *.h files
I need to set from command line (cmd or powershell) some svn keywords recursively on ALL .h and .cpp files. How can I do it? I tried
svn propset svn:keywords "My keywords" -R *.cpp *.h
without success, it says me:
svn: warning: '.cpp' is not under version control
svn: warning: '.h' is not under version control
A:
Solved, I used THIS script for powershell
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# Storing class instances in an array to use in other forms
So i have my own class and i want to store an instance of the class by button click into a class array and then use this array in a different form under the same project however despite declaring it as public static i still can't access it on my other form. I have even tried putting it into the class itself just to see if that would work. I have heard you can use a list array but i am not sure how i would do that and again how to access it over my whole project.
Sorry if i missed something obvious or anything I'm fairly new to C#.
A:
Let's say you create the object in Form1 and want to use it in Form2. You can do it like this:
// Form1-----------------------------------------------------
public partial class Form1 : Form
{
public string myName { get; set; }
public Form1()
{
InitializeComponent();
MyClass myClass = new MyClass() {Name = "John"};
myName = myClass.Name;
}
}
public class MyClass
{
public string Name { get; set; }
}
// Form2-----------------------------------------------------
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
Form1 form1 = new Form1();
this.label1.Text = form1.myName;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mockrunner(Java) query with Regex
I am using Mockrunner to mock Sql DB for my unit tests. Following is my query:-
"select * from table where userId in (" + userIds + ")"
Now my userIds is state dependent. I don't need my test cases dependent on the arrangement inside the list - userIds. So I don't need exact match but regex matching. I have already enabled regex matching by below code:-
StatementResultSetHandler statementHandler = connection.getStatementResultSetHandler();
usersResult = statementHandler.createResultSet("users");
statementHandler.setUseRegularExpressions(true);
//How to write this regex query?
statementHandler.prepareResultSet("select * from table where userId in .*", campaignsResult);
But as it is noted, I have no idea about the regex syntax supported by Mockrunner.
Edit: I unable to match queries like "Select * from tables" with "Select * from tab .*". So It has to do something with the way I using regex with Mockrunner
A:
There are some helpful examples available here. For instance:
public void testCorrectSQL() throws Exception {
MockResultSet result = getStatementResultSetHandler().createResultSet();
getStatementResultSetHandler().prepareResultSet("select.*isbn,.*quantity.*", result);
List orderList = new ArrayList();
orderList.add("1234567890");
orderList.add("1111111111");
Bookstore.order(getJDBCMockObjectFactory().getMockConnection(), orderList);
verifySQLStatementExecuted("select.*isbn,.*quantity.*\\(isbn='1234567890'.*or.*isbn='1111111111'\\)");
}
From this, I surmise that it's using standard Java regex syntax. In which case, you probably want:
prepareResultSet("select \\* from table where userId in \\(.*\\)", campaignsResult);
...or perhaps more succinctly (and depending upon exactly how fine-grained your tests need to be):
prepareResultSet("select .* from table where userId in .*", campaignsResult);
The main caveat to be aware of when enabling the regex matching is that any literal special characters that you want in your query (such as *, (, and ) literals) need to be escaped in your regex before it will work properly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Separating EFI partitions of Ubuntu 20.04 and Mac OSX on Macbook Pro
I installed Ubuntu 20.04 alongside OSX on my early 2015 Macbook pro by following this answer. And somehow I messed up.
I created a separate 400MB EFI partition for Ubuntu but, the system automatically selected Mac OS EFI partition. Can I transfer the Ubuntu boot files to the separate Partition without reinstall? I recently started using Linux. please someone help me out?
$: fdisk /dev/sda
Disk /dev/sda: 233.78 GiB, 251000193024 bytes, 490234752 sectors
Disk model: APPLE SSD SM0256
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: gpt
Disk identifier: E25C4B1F-9E64-4BCB-B346-07F1727F45F3
Device Start End Sectors Size Type
/dev/sda1 40 409639 409600 200M EFI System
/dev/sda2 409640 234784639 234375000 111.8G unknown
/dev/sda3 234784768 235567103 782336 382M EFI System
/dev/sda4 235567104 362520575 126953472 60.5G Linux filesystem
/dev/sda5 362520576 391817215 29296640 14G Linux swap
/dev/sda6 391817216 392595455 778240 380M Microsoft basic data
/dev/sda7 392597504 490233855 97636352 46.6G Microsoft basic data
$ gdisk /dev/sda
Disk /dev/sda: 490234752 sectors, 233.8 GiB
Model: APPLE SSD SM0256
Sector size (logical/physical): 512/4096 bytes
Disk identifier (GUID): E25C4B1F-9E64-4BCB-B346-07F1727F45F3
Partition table holds up to 128 entries
Main partition table begins at sector 2 and ends at sector 33
First usable sector is 34, last usable sector is 490234718
Partitions will be aligned on 8-sector boundaries
Total free space is 3045 sectors (1.5 MiB)
Number Start (sector) End (sector) Size Code Name
1 40 409639 200.0 MiB EF00
2 409640 234784639 111.8 GiB AF0A
3 234784768 235567103 382.0 MiB EF00
4 235567104 362520575 60.5 GiB 8300
5 362520576 391817215 14.0 GiB 8200
6 391817216 392595455 380.0 MiB 0700
7 392597504 490233855 46.6 GiB 0700
A:
I am not sure why the Ubuntu installer allows the user to select which EFI partition to use, then ignores the setting and installs to the first EFI partition. Below are the step to move the boot files to the second EFI partition.
Boot to Ubuntu.
Press the control+option+T key combination to open a Terminal window.
Enter the command below to become the root user.
sudo bash
Enter the command below to format the second EFI partition.
Note: This command will erase the contents of this partition.
mkfs.vfat -F 32 -n EFI2 /dev/sda3
Enter the command below to mount the second EFI partition.
mkdir efi2
mount -t vfat /dev/sda3 efi2
Enter the commands below to copy the boot files from the first EFI partition to the second EFI partition.
mkdir efi2/EFI
mv /boot/efi/EFI/BOOT efi2/EFI
mv /boot/efi/EFI/ubuntu efi2/EFI
Enter the commands below to get the UUID of the two EFI partitions.
blkid /dev/sda1
blkid /dev/sda3
Edit the /etc/fstab file to change the UUID value for the mount point /boot/efi. This can be accomplished by replacing the UUID of the first EFI partition with the UUID of the second EFI partition. Below is the command to open the file in the nano editor.
nano /etc/fstab
Enter the command given below to output the contents of the /etc/fstab file. Visually confirm the changes to the file.
cat /etc/fstab
Enter the command given below to unmount the second EFI partition.
umount efi2
rmdir efi2
Enter the commands given below to close the Terminal window.
exit
exit
Restart the Mac.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is Cartesian product for two empty sets.
If there are two sets $A$ and $B$ and both are null sets(or empty sets). What is $A\times B$ ? Is it also a null set?
A:
$$\begin{array}{rcll}
\varnothing \times \varnothing
&=& \{(x,y) \ | \ x \in \varnothing \land y \in \varnothing\} & \text{defn. of Cartesian product} \\
&=& \{(x,y) \ | \ \bot \land \bot\} & \text{defn. of empty set} \\
&=& \{(x,y) \ | \ \bot\} & \text{defn. of conjunction} \\
&=& \varnothing & \text{defn. of empty set} \\
\end{array}$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Key Value Store for large list of integer values
My application requires a key value store. Following are some of the details regarding key values:
1) Number of keys (data type: string) can either be 256, 1024 or 4096.
2) Data type of values against each key is a list of integers.
3) The list of integers (value) against each key can vary in size
4) The largest size of the value can be around 10,000,000 integers
5) Some keys might contain very small list of integers
The application needs fast access to the list of integers against a specified key . However, this step is not frequent in the working of the application.
I need suggestions for best Key value stores for my case. I need fast retrieval of values against key and value size can be around 512 MB or more.
I checked Redis but it requires the store to be stored in memory. However, in the given scenario I think I should look for disk based key value stores.
A:
LevelDB can fit your use case very well, as you have limited number of keys (given you have enough disk space for your requirements), and might not need a distributed solution.
One thing you need to specify is if (and how) you wish to modify the lists once in the db, as levelDB and many other general key-val stores do not have such atomic transactions.
If you are looking for a distributed db, cassandra is good, as it will also let you insert/remove individual list elements.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++ force override
I have some class, like
class object {
public:
virtual std::string name() const;
};
It provides some interface, and I want all derivated to override method name.
Problem is, it is not overriden, nothing breaks at compile time, but I get problems in run-time.
Is it any way to enforce method overriding?
EDIT: I want to enforce overriding in all derivates, not just direct descedants!
A:
Yes, make it a pure virtual:
constexpr virtual std::string name() = 0;
A:
You can check whether a member is defined in a base class by checking its pointer-to-member type:
static_assert(std::is_same<decltype(&U::name), std::string (U::*)()>::value,
"name must be defined directly in U");
This does mean that at compile time you must have access to all the descendant types that you're interested in.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to access JSON data in AJAX method?
How do access data I have encoded from a PHP to in a $ajax() method?
My question mainly is what to use as a variable and what should be the value of the data attribute? Here is the code that I have so far. I am new to AJAX and I would appreciate an answer, thanks in advance.
$dcweather = array('weather' => "$DCfahrenheit", 'wind' => "$DCwind", 'humidity' => "$DChumidity");
$jsonCode = json_encode($dcweather);
echo ($jsonCode);
('#button_dc').click(function() {
var data = {
weather: "$DCfahrenheit",
wind: "DCwind",
humidity: "DChumidity"
}
$.ajax({
type: 'POST',
url: 'DCweather.php',
data: data,
dataType: 'json',
success: function(result) {
consol.log(result);
$('#div_new').replaceWith(result);
}
});
});
A:
From the code above result would be a object with the indices of weather, wind, and humidity.
So:
result.weather would be whatever $DCfahrenheit was set to on the server.
However, the typo of consol.log(result) with throw an error, and no further code will be processed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In which version of WordPress was the new gallery shortcode implemented?
As of WordPress 3.5, as I'm sure you all know, the gallery shortcode generated from the media uploader changed and now includes a list of image IDs.
The gallery shortcode codex page says the following:
"It's important to note that this style of gallery shortcode is not
new to 3.5, however it is much easier to generate and manage with the
new Media Workflow introduced in 3.5."
Does anyone know what the minimum WP version is, in which this style of gallery shortcode will still work?
A:
The file /wp-includes/media.php, where the Gallery Shortcode is defined, first appears in WordPress 2.5.
It has the id (singular) attribute to refer to the post_parent:
$attachments = get_children("post_parent=$id ...
The ids (plural) attribute appears in WordPress 3.5, and is used to include attachments:
if ( ! empty( $attr['ids'] ) ) {
$attr['include'] = $attr['ids'];
}
...
$_attachments = get_posts( array('include' => $include
PS: I've updated the Codex, now it reads (updates in bold):
Since WordPress 2.5 and up until 3.5, the gallery shortcode [...]
[...]
It's important to note that this style of gallery shortcode is not new to 3.5, previously we could use the include attribute.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
twitter WebResponse freezing C#
ok i am facing a really strange problem with the twitter client of mine.
The code i am using for getting twitter timeline is
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
StreamReader read = new StreamReader(response.GetResponseStream());
string read_string = read.ReadToEnd();
read.Close();
The thing is i can call this code any number of times and i get a response. I also use another code to send status messages to twitter. However whenever i send a message for the 2nd time to twitter and then call this code the WebResponse just freezes. No error code it just freezes.
Initially i suspected that i might had something to do with the shared variable with the write code so i seprated them. But still it was to no avail.
Guyz need urgent help on this one, have been trying to solve this for hours but its no use. I can post whole code if required.
Thank you.
A:
Close the Response:
response.Close();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I correct editor.photoEditorDelegate = self?
I am still a beginner at Swift programming and I am trying to build a very basic iOS app. The app requires users to take a photo and edit them on a photo editor. I am having issues with using editor.photoEditorDelegate = self.
This is what the developer of the photo editor used in his example and it gave no problem but it's not working for me. It is giving an error of:
Cannot assign value of type 'PhotosViewController?' to type 'PhotoEditorDelegate?'
I have tried to fix it with:
editor.photoEditorDelegate = self as? PhotoEditorDelegate
but it just makes the app crash when the editor is called.
I declared the editor with:
let editor = PhotoEditorViewController(nibName:"PhotoEditorViewController",bundle: Bundle(for: PhotoEditorViewController.self))
A:
You need to make your PhotosViewController your PhotoEditorDelegate:
class PhotosViewController: PhotoEditorDelegate {
...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Facebook Help, iOS SDK
I am currently making a Facebook iOS Application and In the app I am trying to get the users Facebook wall and put it in a UITable View.
So Far I Have:
[facebook requestWithGraphPath:@"me/home" andDelegate:self];
This is called when the view is loaded.
The in Facebook Did Receive Response, I want To Populate the table view with the posts, but this is where I have trouble. I looked everywhere for an answer and I read the apple and Facebook documentation, and they didn't help me in my case. Also If Someone Posts a Video or Image, How Would I Handle That in a TableView?? Any Help would be greatly appreciated.
Thanks,
Virindh Borra
A:
You need to take the response and put it into an NSArray. Then in your UITableViewDelegate methods load up the cell:
-(void)request:(FBRequest *)request didLoad:(id)result {
// take my result and put it into an array, usually it's an NSDictionary
NSArray *friendsFBData = [result objectForKey:@"data"];
NSMutableArray *friendIds = [NSMutableArray arrayWithCapacity:friendsFBData.count];
for (int x = 0; x < friendsFBData.count; x++) {
[friendIds addObject:[((NSDictionary*)[friendsFBData objectAtIndex:x]) objectForKey:@"id"]];
}
// don't forget to call loadData for your tableView
[self reloadData];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Grab data from array
NSString *myName = [myArray objectAtIndex:indexPath.row];
[myLabel setText:myName];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get jpa(hibernate) query resultlist as HashMap?
Currently I have tasked to prepare Document service for client side parser that user can view, edit, manage just allowed documents. Documentprivileges has @onetomany relationship for documents model. I have added get single privilege by document
public String getDocumentPrivilege(Long documentId);
......
I also want to return HashMap (docId and privilege) via overriden method. So far I have done:
@Override
public HashMap<Long, String> getDocumentPrivilege(List<Long> documentIds)
{
Query q = null;
if (documentIds != null && documentIds.size()>0) {
q = em.createQuery("select new map(d.document_id as id, d.privilege as privilege) from DocumentPrivileges d"
+ " where d.document_id IN ?1");
q.setParameter(1, documentIds);
@SuppressWarnings("unchecked")
HashMap<Long, String> results = (HashMap<Long, String>) q.getResultList();
if(results != null && results.size()>0)
return results;
}
return null;
}
But I am getting below error:
Caused by: org.hibernate.hql.ast.QuerySyntaxException: unexpected token: : near line 1, column 140 [select new map(d.document_id as id, d.privilege as privilege) from xxx.xxxx.xxxx.xxxmodel.DocumentPrivileges d where d.document_id IN :docs]
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:284)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:98)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1760)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:268)
... 136 more
I have checked other examples it was quite similar. Am I following wrong way?
A:
the map is predefined to map<column, value> not map<column1value, column2value> you have to build the map from the resultlist
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using static get only property thread safe?
I have this class:
class MyFoo
{
private static readonly string _foo = InitFoo();
public static string Foo
{
get
{
return _foo;
}
}
private static string InitFoo()
{
Debug.WriteLine("InitFoo");
// do some job
return "Foo";
}
}
The private static _foo member is initialized only once when there is a reference to MyFoo.Foo.
The data returned from InitFoo() is large and the method might be time consuming (a matter of 1-2 seconds max), My question, is there a chance that while a thread is referencing MyFoo.Foo another thread that reference it will get an uncompleted or un-initialized data back b/c the InitFoo() is not complete yet?
In other words, Is the above thread-safe? if not how to make it thread-safe (if possible avoid a lock object?)
Thanks.
EDIT: following the comments about Lazy<T> is it now better for thread safety?:
public sealed class MyFoo
{
// Explicit static constructor to tell C# compiler not to mark type as beforefieldinit
static MyFoo() { }
private static readonly Lazy<string> _foo = InitFoo();
public static string Foo
{
get
{
return _foo.Value;
}
}
private static Lazy<string> InitFoo()
{
string s = "Foo";
return new Lazy<string>(() => s);
}
}
A:
Is there a chance that while a thread is referencing MyFoo.Foo another thread that reference it will get an uncompleted or un-initialized data back b/c the InitFoo() is not complete yet?
No. Type initialization is thread-safe:
No other threads get to use your type while it's being initialized by another thread
All writes to memory performed by the initialization thread are made visible to other threads when the initialization has been performed
There's one wrinkle which is that if the same thread that's initializing MyFoo ends up reading MyFoo._foo before it's finished initializing, that will cause a problem. That can be particularly awkward to diagnose if there are types that depend on each other for initialization in a cycle.
Here's an example, with two type initializers that each use a value from the other. They both have static constructors to make the behavior deterministic. (The rules for when types are initialized depend on whether or not they have static constructors.)
using System;
public class Program
{
public static void Main(string[] args)
{
// Determine which type to initialize first based on whether there
// are any command line arguemnts.
if (args.Length > 0)
{
Class2.DoNothing();
}
Console.WriteLine($"Class1.Value1: {Class1.Value1}");
Console.WriteLine($"Class2.Value2: {Class2.Value2}");
}
}
public class Class1
{
public static readonly string Value1 =
$"When initializing Class1.Value1, Class2.Value2={Class2.Value2}";
static Class1() {}
}
public class Class2
{
public static readonly string Value2 =
$"When initializing Class2.Value2, Class2.Value2={Class1.Value1}";
static Class2() {}
public static void DoNothing() {}
}
Running this without any command line arguments, Class1 starts initializing first, which in turn initializes Class2:
Class1.Value1: When initializing Class1.Value1, Class2.Value2=When initializing Class2.Value2, Class2.Value2=
Class2.Value2: When initializing Class2.Value2, Class2.Value2=
With any command line argument, we initialize Class2 first, which in turn initializes Class1:
Class1.Value1: When initializing Class1.Value1, Class2.Value2=
Class2.Value2: When initializing Class2.Value2, Class2.Value2=When initializing Class1.Value1, Class2.Value2=
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change color of pagination in bootstrap-vue?
I tried to change it with bootstrap examples but failed.
<b-pagination
v-model="currentPage"
:total-rows="users.length"
:per-page="perPage"
align="fill"
size='lg'
first-number
last-number
class="my-0"
></b-pagination>
A:
SCSS
As Troy pointed out in a comment, bootstrap has various SCSS variables you can use to customize the pagination. So if you're using SCSS this would be the preferred way.
View the variables.
CSS
You can add a class to b-pagination and use that class to target the a tags inside the pagination. Check the snippet for an example of this.
You can also use the following props (requires v2.3.0+) to place specific classes on the various types of buttons.
Note these will place the class on the li, so you'll still need CSS to target the a tag.
For more information about the class props check the reference section
page-class
first-class
last-class
prev-class
next-class
ellipsis-class
If you're using a scoped style tag in your components, note you might have to use a deep selector to target that a tags correctly.
new Vue({
el: '#app'
})
.customPagination > li > a {
color: red;
}
.customPagination > li.active > a,
.customPagination > li > a:hover
{
color: white;
background-color: green!important;
}
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.js"></script>
<link href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" rel="stylesheet"/>
<div id="app">
<b-pagination
:total-rows="50"
:per-page="5"
class="customPagination"
>
</b-pagination>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error separando en palabras desde índices de caracteres no alfabéticos
Hice este código para intentar buscar palabras. Lo explico a detalle en el mismo código.
Me gustaría que me dijeran donde está mi error al pensar que me funcionaría o que está mal y cual sería la forma más óptima (pero principalmente dónde está mí error en el algoritmo, para no cometerlo en un futuro).
function principal(palabra){
var stringArray = palabra.split(''); // Para trabajarlo como array
var soloLetras = /[a-zA-Z]/i; // Las palabras solo se componen de letras
var palabrasSeparadas = []; // Para guardar las palabras cuando se haya recorrido el array mediante el for que esta abajo
var indicesNoLetras = []; // Aquí se guardan los índices de los caracteres que NO SON LETRAS, para frenar en el for.
for(let i=0;i<stringArray.length;i++){ // Recorro la palabra
if(soloLetras.test(stringArray[i]) === false) { // SI NO ES LETRA
var reversa = i; // Separare las palabras con esta lógica: Cuando se encuentre un caracter que no es una letra, todas las letras anteriores a esta se agregan a un array como una palabra encontrada.
indicesNoLetras.push(i); // Guardo el indice de los caracteres que NO SON LETRAS, para qué? Porque cuando la palabra por EJEMPLO, ya COMIENZE en el indice 4 del array 'stringArray' que es la que pasé por parametro, NO RETROCEDA HASTA 0, porque osino volveria a agregar todo el array, entonces retrocederá hasta UN INDICE MÁS(i+1) del último caracter QUE NO ERA UNA LETRA.
var contador = 0; // Para saber en que indice de NO LETRAS, voy llevando.
for(let j = reversa ; j >= indicesNoLetras[contador]; j--) { // Retrocedo desde el caracter que no es letra hasta 0, y la agrego al array.
palabrasSeparadas.push(stringArray[j]);
contador++; // Para que le sumo? para que si encuentra otra palabra, retroceda hasta el ultimo caracter no alfabetico encontrado y no hasta el primero, osino como ya dije agregaria practicamente todo el array.
}
}
}
return palabrasSeparadas;
}
console.log(principal('Hola ! Juan Daniel:)'));
A:
El error está en el segundo bucle for. Comento en el código.
var contador = 0; // Se está inicializado en creo, pero indicesNoLetras puede contener índices que separaban a palabras previas
for(let j = reversa ; j >= indicesNoLetras[contador]; j--) {
// acá se están agregando letras al array,
// pero lo único que hace falta es buscar el índice
// y agregar la palabra completa
contador++;
// Es un error incrementar el contador, ya que cambiaría
// el índice de no letras, mientras se está decrementando a j.
}
Siguiendo tu misma lógica, si vamos guardando los índices de caracteres no alfabéticos, sólo es necesario ver cuándo el índice anterior está distanciado en más un carácter, y ahí agregar la palabra.
No es necesario separar en letras en un array, ya que se puede acceder a cualquier caracter de un String por su índice como palabra[i].
Y para obtener una parte de un string a partir de 2 índices, usamos el método String.substring().
function principal(palabra){
var soloLetras = /[a-záéíóúüñ]/i;
var palabrasSeparadas = [];
var ultimoIndiceNoLetra = -1; // Para guardar la posición del último caracter no alfabético
for(let i=0;i<=palabra.length;i++){
let finalString = (i === palabra.length);
if(finalString || !soloLetras.test(palabra[i])) { // SI NO ES LETRA o si es el final del string
if (i > ultimoIndiceNoLetra + 1) {
// Si hay más de un carácter alfabético en el medio,
// agregar la palabra
let nuevaPalabra = palabra.substring(ultimoIndiceNoLetra + 1, i);
palabrasSeparadas.push(nuevaPalabra);
}
ultimoIndiceNoLetra = i; // guardamos como último índice
}
}
return palabrasSeparadas;
}
console.log(principal('Hola ! Juan Daniel:)'));
Una forma más sencilla. Y probablemente te arranques algunos pelos cuando lo veas.
La expresión regular:
/[a-záéíóúüñ]+/ig;
coincide con cualquier grupo de caracteres alfabéticos. El + del final permite que coincida con 1 o más caracteres consecutivos y el modificador /g es para que encuentre todas las coincidencias. Podemos utilizar ese regex en la función String.match():
function principal(palabra){
return palabra.match(/[a-záéíóúüñ]+/ig);
}
console.log(principal('Hola ! Juan Daniel:)'));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Database for Android App
How and where I can maintain my DB for my android app. I know we can use sqlite DB for android apps but, I don't have any idea of Storing the DB at some other location and then accessing it on the app.
Example Structure:
I want to know, where and how we can have DB at some different point of location, Do I need to buy space or rent? Or there are any other ways (Having DB Server at my own Desktop and accessing it via IP address. Will there be any difficulties or dependencies) I believe we can access it by creating a connection to the Db and writing queries to fetch by using Http Get and Post or Put methods.
If yes, then can we use SQL Server Management studio 2008 or what would be the simplest & the best to work with.
A:
Use parse.com as a backend services.Easy to use and simple. follow this answer
A:
Use realm, please.
https://realm.io/
It is much easier comparing to sqlite.
You can check the usages at https://realm.io/docs/java/latest/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using a group by to group a select statement
Using a group by to group a select stament
SELECT
k.Ivalue, k.JOBDESCRIPTION ,
count( k.Ivalue) as TOTAL
FROM
(SELECT
a."ID" as Ivalue, b."JOBDESCRIPTION", rq."CURRENTSTATUS"
FROM
tblG2o_Requests a
INNER JOIN
tblG2o_JOBS b ON a."JOBPOSTID" = b."ID"
INNER JOIN
(SELECT
r.REQUESTID, ir."CURRENTSTATUS"
FROM
TBLG2O_RESULTSPOOL r
INNER JOIN
tblG2o_Requests ir ON r.RequestID = ir."ID"
WHERE
r.ShortListed = '1') rq ON rq.REQUESTID = a."ID"
WHERE
"ACTIVE" = '1'
AND "DATECOMPLETED" IS NULL
ORDER BY
"REQUESTDATE" DESC) k
GROUP BY
k.JOBDESCRIPTION
A:
What is the question? You seem to be missing the group by clause, and you do not need double quotes around field names unless you have spaces in them, and even then, if TSQL for example, you would use [] in preference.
I had to remove an ORDER BY in the subquery, that isn't allowed unless other conditions demand it (like TOP n in TSQL)
SELECT
k.Ivalue
, k.JOBDESCRIPTION
, COUNT(k.Ivalue) AS TOTAL
FROM (
SELECT
a.ID AS Ivalue
, b.JOBDESCRIPTION
, rq.CURRENTSTATUS
FROM tblG2o_Requests a
INNER JOIN tblG2o_JOBS b
ON a.JOBPOSTID = b.ID
INNER JOIN (
SELECT
r.REQUESTID
, ir.CURRENTSTATUS
FROM TBLG2O_RESULTSPOOL r
INNER JOIN tblG2o_Requests ir
ON r.RequestID = ir.ID
WHERE r.ShortListed = '1'
) rqenter
ON rq.REQUESTID = a.ID
WHERE ACTIVE = '1'
AND DATECOMPLETED IS NULL
) k
GROUP BY
k.Ivalue
, k.JOBDESCRIPTION
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Combo Box Boolean in Visual Basic
I'm on visual studio and I have trouble doing some boolean on Visual Basic for a Combo Box Boolean. I am using Visual Studio btw. I tried to add the following:
if ClientBox.ValueMember() = "Agentleader1 (Leader)" Then
But it wouldn't work.
My program is a basic Contact-Us form for a person to fill out. A field (the combo-box field, called: clientbox) is a combo-box to where you can select which member of the whole group you want to send the contact-form to. Which is a problem. I'm very sorry I can't give a sample of the code. And btw, I just started C++ please don't give complex answers and maybe add a few annotations so I can understand. Please comment this question if I have not explained enough about my program! BTW, please no C# answers.
A:
I found a solution to my problem, if anybody is wondering here it is, sorry for my amateur-ness! This actually kinda is a better answer than anything I could have come up with (except the fact that I found this answer by myself:
if ComboBox.SelectedItem().Equals("any choice of one of the items") = True Then
'execute command!
The above was the syntax, I got an example of my code below:
if ClientBox.SelectedItem().Equals("Agentleader1 (Leader)") = True Then
TEA = "****" 'That's my email!
Hope this helped to anybody that couldn't figure out how to find whether a specified item that is selected in a certain combo-box is selected!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
rake assets:precompile error message: No such file or directory -- ruby
I'm following along to the excellent Michael Hartl Rails book (Rails 3.2) but am getting an error when attempting to run the command:
rake assets:precompile
The error is as follows:
/Users/Jamie/.rvm/rubies/ruby-1.9.3-p448/bin/ruby ruby /Users/Jamie/.rvm/gems/ruby-1.9.3-p448@movies/bin/rake assets:precompile assets:precompile:all RAILS_ENV=production RAILS_GROUPS=assets
/Users/Jamie/.rvm/rubies/ruby-1.9.3-p448/bin/ruby: No such file or directory -- ruby /Users/Jamie/.rvm/gems/ruby-1.9.3-p448@movies/bin/rake assets:precompile (LoadError)
rake aborted!
Command failed with status (1): [/Users/Jamie/.rvm/rubies/ruby-1.9.3-p448/b...]
/Users/Jamie/.rvm/gems/ruby-1.9.3-p448@movies/gems/actionpack- 3.2.14/lib/sprockets/assets.rake:12:in `ruby_rake_task'
/Users/Jamie/.rvm/gems/ruby-1.9.3-p448@movies/gems/actionpack-3.2.14/lib/sprockets/assets.rake:21:in `invoke_or_reboot_rake_task'
/Users/Jamie/.rvm/gems/ruby-1.9.3-p448@movies/gems/actionpack-3.2.14/lib/sprockets/assets.rake:29:in `block (2 levels) in <top (required)>'
/Users/Jamie/.rvm/gems/ruby-1.9.3-p448@movies/bin/ruby_executable_hooks:14:in `eval'
/Users/Jamie/.rvm/gems/ruby-1.9.3-p448@movies/bin/ruby_executable_hooks:14:in `<main>'
Tasks: TOP => assets:precompile
Thanks for your help!
A:
I fixed this by reverting back from p448 to p392 and then running:
rvm ruby-1.9.3-p392@global do gem install executable-hooks
as suggested by mpapis here: Rake assets:precompile cannot find ruby
|
{
"pile_set_name": "StackExchange"
}
|
Q:
datepicker date range: max date's min date = start day + 1 day
Using the jQuery UI's datepicker date range, how can I customize the default functionality so that when the start date is selected the min date for the end date is not the same as start date, but start day + 1 day.
I know I could replace the 'selectedDate' with bunch of getDate() and setDate() functions called on the start date val(), but I was wondering if there might be a intended feature supported by the datepicker. Something like selectedDate +1 day, but obviously I already tried that and that does not work.
Bellow is the code I am currently using that sets the option for minDate of #to to selected date in #from
<input type="text" id="from" name="from">
<input type="text" id="to" name="to">
<script>
$(function() {
$( "#from" ).datepicker({
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
//how to change this so that the minDate is selectedDate + 1 day?
}
});
$( "#to" ).datepicker({
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
</script>
A:
You could use this
var actualDate = new Date(selectedDate);
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
$(function() {
$( "#from" ).datepicker({
onClose: function( selectedDate ) {
//$( "#to" ).datepicker( "option", "minDate", selectedDate );
//how to change this so that the minDate is selectedDate + 1 day?
var actualDate = new Date(selectedDate);
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
$("#to").datepicker("option","minDate", newDate)
},
});
$( "#to" ).datepicker({
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/jquery-ui.js"></script>
<input type="text" id="from" name="from">
<input type="text" id="to" name="to">
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Given a pointer of node to be deleted in a linked list . how will you pass a pointer to the node in main function?
Suppose I have a list [10 20 30 40 50 60]
I want to delete a node which has a data value 40, how would I pass the pointer of this node from main() function ?
I understand if I want to delete 10 the I can simply pass head and if I want to delete 2nd node then i can pass head->next, but what if the list is so big and suppose I want to delete 70th node?
A:
In general, whatever be the length, you have to take the approach,
Start traversing the linked list nodes, starting from the head, one by one.
Arrive at a particular node, check the data value.
if a match, update the pointer to next (previous) node(s).
if no match, move to next node.
continue until you reach the leaf node.
Regarding passing the node, you can simply pass the pointer to the node to be freed up and deallocate the memory from the deletion function. before calling the deletion function, you need to make the required changes to re-align the list, without the to-be-deleted node.
Write the code, if you face any issues, we'll be happy to help.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
argc/argv in c linked list or binary tree
So I am trying to make a linked list/binary tree and:
The user should be able to choose the data structure directly from the command line when it starts the program. This should use the argc or argv arguments to main()
how would I do this? I don’t get it why not just use switch case statement asking the student.
option 1: linked list
option 2: binary tree?
we didn’t really cover argc argv properly can anyone help?
Apparently its a duplicate ... hmm.. well i am asking specically about binary tree/linked list how would the user tell it to choose which data structure?
A:
Experiment with the following skeleton program, and find out.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "Usage: %s COMMAND\n", argv[0]);
return EXIT_FAILURE;
}
if (!strcmp(argv[1], "foo")) {
printf("Doing foo.\n");
} else
if (!strcmp(argv[1], "bar")) {
printf("Doing bar.\n");
} else {
fprintf(stderr, "Unknown command line parameter '%s'.\n", argv[1]);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
The most common way to inform the utility user as to what to do, is to run the utility without parameters, or with -h or --help as the only parameter. (Windows command-line utilities might use /? or similar.)
Let's say the user can run the compiled program, program in the following ways:
./program list
./program tree
./program -h
./program --help
./program
where the first form tells the program to use a linked list; the second form tells the program to use a tree; and the other forms just output usage, information on how to call the program:
Usage: ./program [ -h | --help ]
./program MODE
Where MODE is one of:
list Linked-list mode
tree Tree mode
Further details on what the program actually does...
You achieve this with very little code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
enum {
NO_MODE = 0,
LIST_MODE,
TREE_MODE
};
int main(int argc, char *argv[])
{
int mode = NO_MODE;
if (argc != 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
printf("Usage: %s [ -h | --help ]\n", argv[0]);
printf(" %s MODE\n", argv[0]);
printf("\n");
printf("Where MODE is one of\n");
printf(" list for linked list mode\n");
printf(" tree for tree mode\n");
printf("\n");
printf("Further details on what the program actually does...\n");
printf("\n");
return EXIT_SUCCESS;
}
if (!strcmp(argv[1], "list"))
mode = LIST_MODE;
else
if (!strcmp(argv[1], "tree"))
mode = TREE_MODE;
else {
fprintf(stderr, "%s: Unknown MODE.\n", argv[1]);
return EXIT_FAILURE;
}
/* mode == LIST_MODE or TREE_MODE here,
depending on the first command line parameter.
*/
return EXIT_SUCCESS;
}
Note that || operator is short-circuited in C: if the left side is false, the right side is not evaluated at all. So, above, the first strcmp() check is only done when argv == 2, and the second when argv == 2 and the first strcmp() returned nonzero (no match).
In other words, the body of the usage section is only run when argv != 2 (there is less than two, or more than two command line items, counting the program name as one); or if the sole command-line parameter matches either -h or --help.
! is the not operator in C. !x evaluates to 1 if and only if x is zero or NULL; and to 0 otherwise.
(You can confuse people by using !!x. It evaluates to zero if x is zero, and to one if x is not zero. Which is logical. It's often called the not-not operation.)
The enum is just there to remind you that magic constants are bad; it is better to use either enums, or preprocessor macros (#define NO_MODE 0 and so on). It would be terribly easy to use 1 in one place to indicate tree mode, and 2 in another; such bugs are horrible to debug, needs way too much concentration from the human reading the code, to find such bugs. So don't use magic constants, use enums or macros instead.
Above, I decided that NO_MODE has value zero, and let the compiler assign (increasing) values to LIST_MODE and TREE_MODE; consider them compile-time integer constants. (Meaning, you can use them in case labels in a switch statement.)
Because strcmp() returns zero if the two strings match, !strcmp(argv[1], "baz")) is true (nonzero) if and only if argv[1] contains string baz. You see it all the time in real-world code when strings are compared.
If you look at my answers here, you'll very often see an if (argc ...) "usage" block in my example code. This is because even I myself will forget, often within days, exactly what the purpose of the program is. I typically have several dozen example programs on my machines I've written, and rather than looking at the sources to see if something jogs my memory, I simply run the example snippets without command-line parameters (or actually, with -h parameter, since some are filters), to see what they do. It's faster, less reading, and I'll find the relevant snippet faster.
In summary, write an usage output block in all your programs, especially when it is just a test program you won't publish anywhere. They are useful, especially when you have a library full of them, of various code snippets (each in their own directory; I use a four-digit number and a short descriptive name) that implement interesting or useful things. It saves time and effort in the long run, and anything that lets me be efficient and lazy is good in my book.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
query execution time in mysql
I have run the query in mysql which consists of approximately 33million records when i have executed the query
select population1 < 200000 from city;
it shows like this after execution
34459393 rows in set (16.04 sec)
My question is what is 16.04 sec because in normal time it has taken morethan 30min but it shows 16.04 sec.
How can i calculate the actual time.
A:
The 16.04 seconds is a timer on the client that measures the amount of time that passed between the call and the execution of the query (if you want to be more specific than that, the wall clock time between calling start_timer() and mysql_end_timer(), something that can lead to hilarious results like this one I got).
The reason that you think that it took you more than 30 minutes to execute is probably because it doesn't have into account the output to the stdout. You can check that it really takes 16 second by doing:
mysql> pager cat > /dev/null
mysql> <your query here>
mysql> nopager
If you want to measure how much time takes to write to the standard output, you can do:
$ time mysql -u <your user> -p<your password> <your database> \
-e "select population1 < 200000 from city"
Note: Are you sure you want to print a 0 or a 1 for ALL rows from that table? Maybe the option --safe-updates and/or using a GUI can help you a bit with your queries?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
error_messages_for is deprecated in ruby - how do I find the replacement?
I am reading an old book (2008) to learn ruby and it is for rails 2.0.2.
I have decided to use Rails 3 to find out the differences between the ruby back then to what it is now. Most of it has been good so far and I have been easily been able to find and correct the differences.
The problem I am having now, is that the code is using a deprecated function error_messages_for and upon looking at http://apidock.com/rails/ActionView/Helpers/ActiveRecordHelper/error_messages_for I cannot find a replacement or any way to show me what the new way is. Can someone help me find the new way to use error_messages_for and how I should go about finding the new way to do things and the way to discover the new best practices etc.
A:
f.error_messages in Rails 3.0
Rails error_messages helper
http://www.emersonlackey.com/article/rails3-error-messages-for-replacement
http://ariejan.net/2010/12/15/why-did-errormessagesfor-disappear-from-rails-3/
https://gist.github.com/1113828
Just the top 5 links found searching Google for "rails error_messages_for rails 3".
That said, you really should use an up-to-date book. Even the latest free Rails tutorials are covering Rails 3.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to subset a large igraph to just one node and its connected nodes using R?
I have a very large igraph (called g) in R.
I am just interested in one node (NodeA) plus whatever nodes are directly connected to NodeA. I want to end up with a very simple graph like the picture below.
I have tried subgraph(g, "nodeA") but I just end up with NodeA all by itself.
I think I need to subset the edges of graph g to those that connect to nodeA then use subgraph.edges(). I can't figure out how to subset the edges based on what nodes they are connected to...
A:
Try using neighbors()
# Example graph
g1 <- graph_from_literal(1:2:3---3:4:5)
# Let's take a look at it
plot(g1)
# Say we are interested in the subgraph consisting of vertex 1 and all
# other vertices it is connected to
g2 <- induced_subgraph(g1, c(1, neighbors(g1,1)))
plot(g2)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
retrieve and combine chunks of information from string using regex in postgres
I need to retrieve information from structured text fragments which have the following format:
(AAB) Some name1 here 1234 (BB) More 12-text 99 (XY*) Hello world 12
What I want to get out is the following: {AAB1234, BB99, XY*12}
Strategy:
get characters inside brackets [e.g. (XY*)]
get last group of digits which is either followed by brackets or the end of string [e.g. 1234 (]
I did not get very far, as my regex skills are fairly limited.
SELECT regexp_matches('(AAB) Some name1 1234 (BB) More text 99 (XY*) Hello world 12',
'\((.*?)\).*?(\d+)', 'g');
Giving
{AAB,1}
{BB,9}
{XY*,1}
Any ideas?
Add-on question:
I have the above text information in a column information in table my_table and I want to write the results into column results. How can I integrate the above solution into an UPDATE statement?
I.e.
UPDATE my_table SET results = ???.
A:
You may try:
SELECT array_agg(v) FROM (
SELECT array_to_string(
regexp_matches(
'(AAB) Some name1 1234 (BB) More text 99 (XY*) Hello world 12',
'\((.*?)\).*?(\d+)(?=$| \()', 'g'
),
''
) as v
) s;
Note that as usual, regexps can be quite fragile if you don't have a very formal definition of the syntax.
EDIT
To update, this should do the trick:
UPDATE my_table SET results = ARRAY(
SELECT array_to_string(
regexp_matches(
information,
'\((.*?)\).*?(\d+)(?=$| \()', 'g'
),
''
)
);
It expects results to be of type text[]. Alternatively, you could store the results as a string by adding an array_to_string.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cancel asynctask download on backbutton press
This is my download class in which I used Asynctask.Everything works fine, when the file is downloaded fully,it shows 'file downloaded' and on 'ok' press goes back to previous activity.Now I wanted to cancel the asynctask(pls not that 'cancel asynctask' and not only the 'loading' dialogue)on back button press and go back to previous activity.How to do that?someone please help.Thanks in advance
public class Download extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.down);
startDownload();
}
private void startDownload() {
String url = data.proj;
new DownloadFileAsync().execute(url);
}
private void showMsg() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Document is downloaded")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//do things
Download.this.finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
String fname;
fname = data.proj.substring( data.proj.lastIndexOf('/')+1, data.proj.length() );
InputStream input = new BufferedInputStream(url.openStream());
String path=Environment.getExternalStorageDirectory()
.toString() + File.separator;
OutputStream output = new FileOutputStream(path+fname);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
@Override
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
showMsg();
}
}}
A:
Really old question, but it seems many people still face an issue in cancelling AsyncTasks. So, here goes...
You will need a field in your AsyncTask class (DownloadFileAsync) to store the View which is being used to cancel the task (a ProgressDialog here).
For ProgressDialog, when creating the dialog, pass true to setCancelable()
mProgressDialog.setCancelable(true);
To pass the view, change the call to the Task as follows:
new DownloadFileAsync(mProgressDialog).execute(url);
and inside our AsyncTask class, create a constructor which saves this value to a field and register an OnCancelListener to call cancel method of AsyncTask:
ProgressDialog mProgressDialog;
DownloadFileAsync(ProgressDialog progressDialog) {
mProgressDialog = progressDialog;
mprogressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
cancel(true);
}
});
}
In your while loop in doInBackground, add the following code inside the loop:
if (isCancelled()) {
outputStream.flush();
outputStream.close();
inputStream.close();
return null;
}
This way we are checking whether the task was cancelled, every once in a while, and if yes, we close open streams and stop running the task with return (return will be of type given for result of Task). Next, in onCancelled
@Override
protected void onCancelled (Integer fileSize) {
super.onCancelled(fileSize);
Log.d("TASK TAG", "Cancelled.");
//anything else you want to do after the task was cancelled, maybe delete the incomplete download.
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to pass a value from a function to a text box
I am very new to JavaScript and I need some help. I am trying to pass a value from a function within the <head> of my HTML document, so that it'll run once the page loads, and I am unable to figure out how to pass a value from the function to a text box within a form in the <body> of the document.
alert ('Starting now');
function calc(){
const FEES=14.5;
const DUES=5;
var cFees;
var lDues;
cFees=FEES * 16;
lDues=DUES * 16;
document.getElementById("league");
}
alert('Finished');
I am unable to understand what I am suppose to do in order to pass along the value of cFees to a text box with the id of "league". The alerts are there to indicate that it is actually starting/ending properly.
EDIT: here is the code that I want to pass the values to
<form>
</div>
<div id="righta">
<input type="text" name="league" id="league" readonly />League Dues
<br />
<input type="text" name="fee" id="fee" readonly />Golf Course Fees
<br />
<input type="text" name="total" id="total" readonly />Total for the Season
</div>
</form>
A:
You need to set its value property:
document.getElementById('league').value = cFees;
If you were passing it to an HTML element, you may wish to use innerHTML instead...
e.g. <div id="divTest"></div>
document.getElementById('divTest').innerHTML = cFees;
If you wish it to run when the page loads, then add an event listener to the window...
window.addEventListener(
'load',
function() {
document.getElementById('league').value = cFees;
},
false);
FULL CODE EXAMPLE
Here's a full HTML example showing the fields being updated accordingly as per the calc() function. I've set this to update on the load of the window, but you could set it via some other event, if you wish.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function calc() {
const FEES = 14.5;
const DUES = 5;
var cFees = FEES * 16;
var lDues = DUES * 16;
document.getElementById('txtFees').value = cFees.toFixed(2);
document.getElementById('txtDues').value = lDues.toFixed(2);
}
window.addEventListener('load', calc, false);
</script>
</head>
<body>
<input id="txtFees" type="text" value="" readonly>
<input id="txtDues" type="text" value="" readonly>
</body>
</html>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to call Doctrine CacheProvider function in Laravel 4 Controller
I have seen some useful functions like the following in
vendor/doctrine/cache/lib/Doctrine/Common/Cache/CacheProvider.php of laravel 4 installation.
public function flushAll()
{
return $this->doFlush();
}
How can I call this function from my controller.
A:
This question was asked in Laravel Forum and here also, but no response!
Luckily I have derived solution for my question.
The Composer vendor have a class autoload map file which have an array with all class names with their namespace.
This file will be updated in all instance of composer install or composer update which will be prepeded by composer dump-autoload command.
If I am making a class somewhere, I have to execute the php artisan dump-autoload command to properly auto-load them.
So here in vendor/composer/autoload_classmap.php, we have reference to all vendor classes including Symfony and Doctrine.
And the entry for the Doctrine Cache Provider will be,
'Doctrine\\Common\\Cache\\CacheProvider' => $vendorDir . '/doctrine/cache/lib/Doctrine/Common/Cache/CacheProvider.php'
Here I can see which file it is, and what will be the namespace.
Now we can call functions by using the namespace,
use Doctrine\Common\Cache\CacheProvider as DoctrineCache;
DoctrineCache::flushAll();
And also we can add this in providers array with app.php
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ViewFlipper with detail views from a ListActivity?
I feel like I'm missing something basic, and I'm actually kind of embarrassed asking this question. But that's what happens when you start learning a new platform...
I have a ListViewActivity that is populated via a CursorAdapter. When a list item is clicked, I start a new Activity to display the details for that item. What I want to do is enable flinging/swiping to iterate through the items from the detail activity. I don't want to fully populate a ViewFlipper, as there is no hard-coded limit to the number of items in the List, and it just seems wasteful. Is there some way to intercept the fling gesture/trackball movement, and reset the detail activity with the next/previous item detail?
My ListViewActivity just sets up a Cursor (via managedQuery) and the associated CursorAdapter, with an OnListItemClick that calls startActivity with the appropriate Intent.
public final class ModelList extends ListActivity {
private Cursor m_models = null;
private ModelAdapter m_adapter;
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(m_models == null) {
m_models = managedQuery(Model.CONTENT_URI, Model.PROJECTION, null, null, Model.DEFAULT_SORT_ORDER);
}
m_adapter = new ModelAdapter(this, R.layout.modelitem, m_models);
setContentView(R.layout.forcelist);
setTitle(R.string.activity_list);
setListAdapter(m_adapter);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.d(getPackageName(), "Clicked item id:" + id);
if(id < 0) {
startActivity(new Intent(Intent.ACTION_EDIT, Model.CONTENT_URI));
} else {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Model.CONTENT_URI + "/" + id)));
}
}
}
My detail Activity seems pretty straightforward; it's simply a RelativeLayout with a number of Views set up to display the details of the item based on the Intent's Uri.
public class ModelDetail extends Activity {
private Uri mUri;
private FactionHelper factionHelper;
private static String mCostFormat;
private static String mDescriptionFormat;
private ModelAdapter.MarAdapter marAdapter;
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.modeldetail);
setTitle(R.string.activity_detail);
mCostFormat = getBaseContext().getResources().getString(R.string.modelCostFormat);
mDescriptionFormat = getBaseContext().getResources().getString(R.string.modelDescriptionFormat);
mUri = getIntent().getData();
factionHelper = new FactionHelper(getBaseContext());
populateData();
}
protected void populateData() {
TextView name = (TextView) findViewById(R.id.modelName);
TextView description = (TextView) findViewById(R.id.modelDescription);
// ... More finding Views and populating data ...
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
populateData();
}
}
A:
Just pass the ID of the current record to the details activity. This will then query the details for the ID given and get a Cursor for that record.
Then create a class which extends ViewSwitcher (the user will only be able to see one details at a time, so we only need 2 views at any one time). In your custom view switcher class add a method similar to:
class MySwitcher extends ViewSwitcher {
...
long currentRowId;
long nextRowId;
long previousRowId;
public void setItemDetails(long rowId) {
final View nextView = this.getNextView();
currentRowId = rowId;
/* Get the next/previous record IDs with a query like
* "SELECT row_id FROM table WHERE row_id < "+currentRowId+" ORDER BY row_id DESC LIMIT 1;" (Previous)
* "SELECT row_id FROM table WHERE row_id > "+currentRowId+" ORDER BY row_id ASC LIMIT 1;" (Next)
*/
// Do something with nextView, like set some text or something
// You could get a cursor based on the rowID with
// "SELECT * FROM table WHERE row_id = "+currentRowId+" LIMIT 1;"
((TextView) nextView.findViewById(R.id.myTextView)).setText("Details for item #" + rowId);
this.showNext();
}
}
If you don't want an animation the first time setItemDetails is called then use setAnimateFirstView(false) on the ViewSwitcher.
Then you need to add an OnTouchListener to detect drags/swipes, and then call setItemDetails with the next/previous row ID when you detect a horizontal swipe -- you might want to set a different animation depending on whether you are moving to the next or previous item.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Gradle - multiple project and git repositories
We have 3 projects and a 4th one that is shared among them.
A multiple project in gradle requires one to create a wrapper project and include all the sub projects in it.
Each of our sub projects are being worked on by different team members and we use git as an svn.
Our concern before going into gradle is the fact that we will only have 1 git repository that consists of the wrapper project with all sub projects instead of 4 different repos, each for each sub project.
1) Are we missing something?
2) Is it possible to create 4 repos on a multi project?
3) One of our requirements is to deploy a single war (for example only webapp #1 out of the 4)--does using the multi project template make it possible?
A:
ad 1) You have some choices:
Use a single Git repo.
Use multiple Git repos and exchange artifacts via a binary repository (e.g. Artifactory), with artifacts being produced on a regular basis by CI jobs.
Use something like Github submodules to create a "virtual" overall Git repo (wouldn't recommend this one).
ad 2) Gradle doesn't really care how many Git repos the build is comprised of, as long as everything that settings.gradle points to (at least all build scripts) exists on disk when the build starts. Of course it may be inconvenient for developers (and CI admins) to juggle multiple Git repositories and put them in the right (relative) locations.
ad 3) Yes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
why tags are not inline on my slider?
I'm trying to create a fluid slider width:100%
it works perfectly until I add more than 4 items. After 4 items the 5 item goes under the 1 item.
this how <li> should look like inline
12345678
but instead they go under like this
1234
5678
I know it has to be something with the width but when I add more width to the parent the items go off place
heres a js fiddle i made . please help!
https://jsfiddle.net/jaysg_/tk20dckv/light/
A:
The problem is the way youre setting your widths. You have 8 slides so you have to do the math:
100 / 8 = 12.5
That means that each slide should have a width of 12.5% and your slide container should have a width of 800%:
Try this:
.work-slider ul {
width: 800%;
}
.work-slider ul li {
width: 12.5%;
}
Fiddle: https://jsfiddle.net/tk20dckv/7/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PayPal Express Checkout API - Is there a way to process both recurring payment in one session using method CreateRecurringPaymentsProfile?
I tried to process two recurring payment in one session using method CreateRecurringPaymentsProfile. Here is the chronology of my actions:
First I set method SetExpressCheckout:
'METHOD' => 'SetExpressCheckout',
'RETURNURL' => $this->paypalreturnurl,
'CANCELURL' => $this->paypalcancelurl,
'PAYMENTREQUEST_0_CURRENCYCODE' => $this->paypalcurrencycode,
'PAYMENTREQUEST_0_PAYMENTACTION'=> 'SALE',
'L_BILLINGTYPE0' => 'RecurringPayments',
'L_BILLINGAGREEMENTDESCRIPTION0'=> 'Tier 1 + Management Services',
'PAYMENTREQUEST_0_DESC' => 'Tier 1 + Management Services',
'L_PAYMENTREQUEST_0_NAME0' => 'Tier 1',
'L_PAYMENTREQUEST_0_NUMBER0' => '10101',
'L_PAYMENTREQUEST_0_QTY0' => '1',
'L_PAYMENTREQUEST_0_AMT0' => '0.02',
'L_PAYMENTREQUEST_0_DESC0' => 'Description of Tier 1',
'L_PAYMENTREQUEST_0_NAME1' => 'Management Services 8 hours - for $0.01',
'L_PAYMENTREQUEST_0_NUMBER1' => '212121',
'L_PAYMENTREQUEST_0_QTY1' => '1',
'L_PAYMENTREQUEST_0_AMT1' => '0.01',
'L_PAYMENTREQUEST_0_DESC1' => 'Description of Management Services 8 hours - for $0.01',
'PAYMENTREQUEST_0_ITEMAMT' => '0.03',
'PAYMENTREQUEST_0_AMT' => '0.03'
After successful response from SetExpressCheckout method, the first recurring payment is executed successfully using CreateRecurringPaymentsProfile method. Here is the parameters:
'L_PAYMENTREQUEST_0_NAME0' => 'Management Services 8 hours - for $0.01',
'PROFILEREFERENCE' => 'RPInvoice1234',
'PROFILESTARTDATE' => date('Y-m-d') . 'T' . date('H:i:s').'Z',
'SUBSCRIBERNAME' => 'Mr Sub Scriber',
'TOKEN' => urlencode($token),
'DESC' => 'Tier 1 + Management Services',
'AMT' => '0.01',
'BILLINGPERIOD' => 'Month',
'BILLINGFREQUENCY' => '1',
'TOTALBILLINGCYCLES' => '12',
'REGULARTOTALBILLINGCYCLES' => '1',
'VERSION' => '74.0',
'MAXFAILEDPAYMENTS' => '1',
'L_PAYMENTREQUEST_0_AMT0' => '0.01',
'INITAMT' => '0.01',
'L_PAYMENTREQUEST_0_NUMBER0' => '212121',
'L_PAYMENTREQUEST_0_QTY0' => '1',
'L_BILLINGTYPE0' => 'RecurringPayments',
'L_BILLINGAGREEMENTDESCRIPTION0'=> 'Tier 1 + Management Services',
'L_PAYMENTREQUEST_0_ITEMCATEGORY0'=> 'Digital'
After the successful response from CreateRecurringPaymentsProfile method, I tried to create another recurring payment ( unfortunately without success ) using similar parameters and again CreateRecurringPaymentsProfile method:
'L_PAYMENTREQUEST_0_NAME0' => 'Hosted Saas Tier 1',
'PROFILEREFERENCE' => 'RPInvoice123',
'PROFILESTARTDATE' => date('Y-m-d') . 'T' . date('H:i:s').'Z',
'SUBSCRIBERNAME' => 'Mr Sub Scriber 2',
'TOKEN' => urlencode($token),
'DESC' => 'Hosted Saas Tier 1 + Community Management Services',
'AMT' => '0.02',
'BILLINGPERIOD' => 'Month',
'BILLINGFREQUENCY' => '1',
'TOTALBILLINGCYCLES' => '12',
'REGULARTOTALBILLINGCYCLES' => '1',
'VERSION' => '74.0',
'MAXFAILEDPAYMENTS' => '1',
'L_PAYMENTREQUEST_0_AMT0' => '0.02',
'INITAMT' => '0.02',
'L_PAYMENTREQUEST_0_NUMBER0' => '10101',
'L_PAYMENTREQUEST_0_QTY0' => '1',
'L_BILLINGTYPE0' => 'RecurringPayments',
'L_BILLINGAGREEMENTDESCRIPTION0'=> 'Hosted Saas Tier 1 + Community Management Services',
'L_PAYMENTREQUEST_0_ITEMCATEGORY0'=> 'Digital'
Unfortunately this method always return the same error, regardless the changes I made:
Profile description is invalid, L_ERRORCODE0 = 11581.
When I change the recurring payments order the same error appears for the first recurring payment with title "Management Services 8 hours - for $0.01" !? The problem is that every time second recurring returns the same error - "Profile description is invalid, L_ERRORCODE0 = 11581."
How can I get this working?
A:
Finally, with a little help from the PayPal support, I find a solution to create multiple recurring profiles in a single Express Checkout session:
First you must Pass both Profiles in SetExpressCheckout method (first
method in my example), for example:
L_BILLINGTYPE0=RecurringPayments
L_BILLINGAGREEMENTDESCRIPTION0=Tier 1
and second product
L_BILLINGTYPE1=RecurringPayments
L_BILLINGAGREEMENTDESCRIPTION1=Management Services
And then, after buyer has approved both in PayPal, you need to call CreateRecurringPaymentsProfile twice:
One sending "DESC" with the value "Tier 1" and another one sending "DESC" with the value "Management Services"
Also check this
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A Code Scratchpad Extension in Visual Studio 2010 - How to?
Maybe it's somehow freaky, but I'd like to write an extension for Visual Studio 2010, which mimics the behavior of the Command Window in Visual Foxpro. For those of you who don't know about it:
In Foxpro, you could enter code in the command window, which got executed directly. This way, you where able to try things out without messing with your project or "real code". And you had some kind of Intellisense. If you created an object via CREATEOBJECT, you got an Intellisense with all available methods and functions in the next step. Somehow like a Code Scratchpad. This is something I'm missing in VS 2010.
I've seen the EditorToolwindow - Demo from the Visual Studio 2010 SDK, but I'd like to have a Syntax Highlighter and Intellisense, and provide my own logic for dealing with the code in this window, e.g. on-the-fly execution etc. A little bit like LINQPad.
Does anyone have an idea how I could accomplish this?
A:
Have a look at Jon Skeet's Snippy utility which allows you to execute dot net code in a stand alone editor. There is also a Snippy Reflector add-in.
You could take a look through reflection to see how Snippy was built and go from there. Or just use it on it's own merit.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regular expression in PostgreSQL LIKE clause
I'm stuck with a simple regular expression. Not sure what I'm missing. A little rusty on regex skills.
The expression I'm trying to match is:
select * from table where value like '00[1-9]%'
-- (third character should not be 0)
So this should match '0090D0DF143A' (format: text) but it's NOT!
A:
Like @a_horse commented, you would have to use the regular expression operator ~ to use bracket expressions.
But there's more. I suggest:
SELECT *
FROM tbl
WHERE value ~ '^00[^0]'
^ ... match at start of string (your original expression could match at any position).
[^0] ... a bracket expression (character class) matching any character that is not 0.
Or better, yet:
SELECT *
FROM tbl
WHERE value LIKE '00%' -- starting with '00'
AND value NOT LIKE '000%' -- third character is not '0'
Why? LIKE is not as powerful, but typically faster than regular expressions. It's probably substantially faster to narrow down the set of candidates with a cheap LIKE expression.
Generally, you would use NOT LIKE '__0', but since we already establish LIKE '00%' in the other predicate, we can use the narrower (cheaper) pattern NOT LIKE '000'.
Postgres can use a simple btree index for the left-anchored expressions value LIKE '00%' (important for big tables), while that might not work for a more complex regular expression. The latest version of Postgres can use indexes for simple regular expressions, so it might work for this example. Details:
Difference between LIKE and ~ in Postgres
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Show that $A$ cartesian closed need not imply $A^J$ is cartesian closed.
I need to find an example of a cartesian closed category whose functor category (from some diagram $J$) is not cartesian closed. I thought of one possible solution: let $A$ be a commutative square (which is a poset, hence ccc) and let $J$ be the category $\bullet \to \bullet$. Then $A^J$ is the arrow category, and I claim it's impossible to form the product of the parallel arrows in $A$'s square. This seems like a poor example though, any other suggestions?
A:
I think it will not be easy to find an example with $J=2$. Since a cartesian closed category has finite products, the result cited in David White's answer shows the category $A$ for such an example must not have equalizers. So it cannot be a preorder, and so (having binary products) it cannot be finite. It is not hard to find infinite cartesian closed categories without equalizers -- but I have not found one with a specific pair of functors that I can show have no exponential.
The best example that occurs to me has $J$ the poset with bottom element $0$ and a countable infinity of objects right above $0$, with no arrows to each other. That is the partial order on the natural numbers with $x\leq y$ if and only if $x=0$. And for $A$ the category of finite sets (hereditarily finite, if you like ZF foundations and want a small category). The result follows since the functor assigning the empty set to $0$ and the two element set to every other object of $J$ has infinitely many natural transformations to itself (uncountably many).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cartesian product of fields is semisimple iff the index set is finite
This question may have already been asked.
Let $R = \prod_{i\in I} K_i$ where each $K_i$ is a field. Show that
$R$ is a semisimple ring iff the index set $I$ is finite.
I think I need to show that the direct product of a finite number of fields, when taken as a module over itself, can be reduced to corresponding to a direct sum of irreducible modules. Can I receive a hint in how to go about doing that?
A:
If you know that a semisimple ring is Artinian, then obviously $\prod_{i\in I} K_i$ is not Artinian if $I$ is infinite (just create an ascending chain of ideals using the factors you're given.)
If you know what an essential ideal is: $A=\oplus_{i\in I}K_i$ is an essential ideal in $\prod_{i\in I}K_i$, and if $I$ is infinite, $A$ is a proper ideal. But a proper essential ideal cannot be a direct summand. All ideals must be summands, of course, in a semisimple ring.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Which configuration properties are not changeable in deployment time / runtime in Quarkus?
I was reading the Quarkus documentation about configuration, and this caught my attention:
Quarkus does much of its configuration and bootstrap at build time. Most properties will then be read and set during the build time step. To change them, make sure to repackage your application.
Where can I find the list of configurations that are not changeable on deployment time/runtime?
A:
All of the Quarkus configuration options can be found here:
https://quarkus.io/guides/all-config
To the left of some properties there is a "lock" icon, which means the configuration property is fixed at build time. All other properties that do not have the "lock" icon next to them may be overridden at runtime.
For example, the quarkus.datasource.jdbc.driver property is fixed at build time, meaning between dev/test/prod you must use the same JDBC driver. On the other hand, properties such as quarkus.datasource.jdbc.url may be overridden at runtime, so at dev/test time it could point to jdbc://localhost:5432/myDB and in production this value could point to the production DB URL.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Write to variable outside of block in objective c
I'm using NSRegularExpression enumerateMatchesInString].
I'm passing it an inline block.
The block is called each time a result is found. I'd like to create a new string by appending the results one after the other to the new string.
I can't access variables outside the block (apparently). I can't return a value from the block since enumerateMatchesInString expects the block to have return type void.
I can't believe using properties of the class is the best practice here...
How do I do this?
A:
There is nothing wrong in accessing properties in a block, but you have to be careful.
by default blocks capture variables strongly. if the class now holds the block, you get an retain cycle.
To avoid this, you can create a weak variable of self. in the block you than create a (default) strong variable to avoid, that the object self will be released while processing the block
__weak typeof(self) weakSelf = self;
self.testBlock = ^(NSInteger itemIndex) {
typeof(self) strongSelf = weakSelf;
if(strongSelf){
strongSelf.foo = ....;
}
};
if you want to write to a variable from the surrounding scope, you use __block.
__block NSUInteger foundIndex = NSNotFound;
[array enumerateObjectsUsingComparator:^(id obj, NSUInteger idx, *BOOL stop){
if([obj ....]){
foundIndex = idx;
*stop = YES;
}
}];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dealing with Android's texture size limit
I have a requirement to display somewhat big images on an Android app.
Right now I'm using an ImageView with a source Bitmap.
I understand openGL has a certain device-independent limitation as to
how big the image dimensions can be in order for it to process it.
Is there ANY way to display these images (with fixed width, without cropping) regardless of this limit,
other than splitting the image into multiple ImageView elements?
Thank you.
UPDATE 01 Apr 2013
Still no luck so far all suggestions were to reduce image quality. One suggested it might be possible to bypass this limitation by using the CPU to do the processing instead of using the GPU (though might take more time to process).
I don't understand, is there really no way to display long images with a fixed width without reducing image quality? I bet there is, I'd love it if anyone would at least point me to the right direction.
Thanks everyone.
A:
You can use BitmapRegionDecoder to break apart larger bitmaps (requires API level 10). I've wrote a method that will utilize this class and return a single Drawable that can be placed inside an ImageView:
private static final int MAX_SIZE = 1024;
private Drawable createLargeDrawable(int resId) throws IOException {
InputStream is = getResources().openRawResource(resId);
BitmapRegionDecoder brd = BitmapRegionDecoder.newInstance(is, true);
try {
if (brd.getWidth() <= MAX_SIZE && brd.getHeight() <= MAX_SIZE) {
return new BitmapDrawable(getResources(), is);
}
int rowCount = (int) Math.ceil((float) brd.getHeight() / (float) MAX_SIZE);
int colCount = (int) Math.ceil((float) brd.getWidth() / (float) MAX_SIZE);
BitmapDrawable[] drawables = new BitmapDrawable[rowCount * colCount];
for (int i = 0; i < rowCount; i++) {
int top = MAX_SIZE * i;
int bottom = i == rowCount - 1 ? brd.getHeight() : top + MAX_SIZE;
for (int j = 0; j < colCount; j++) {
int left = MAX_SIZE * j;
int right = j == colCount - 1 ? brd.getWidth() : left + MAX_SIZE;
Bitmap b = brd.decodeRegion(new Rect(left, top, right, bottom), null);
BitmapDrawable bd = new BitmapDrawable(getResources(), b);
bd.setGravity(Gravity.TOP | Gravity.LEFT);
drawables[i * colCount + j] = bd;
}
}
LayerDrawable ld = new LayerDrawable(drawables);
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
ld.setLayerInset(i * colCount + j, MAX_SIZE * j, MAX_SIZE * i, 0, 0);
}
}
return ld;
}
finally {
brd.recycle();
}
}
The method will check to see if the drawable resource is smaller than MAX_SIZE (1024) in both axes. If it is, it just returns the drawable. If it's not, it will break the image apart and decode chunks of the image and place them in a LayerDrawable.
I chose 1024 because I believe most available phones will support images at least that large. If you want to find the actual texture size limit for a phone, you have to do some funky stuff through OpenGL, and it's not something I wanted to dive into.
I wasn't sure how you were accessing your images, so I assumed they were in your drawable folder. If that's not the case, it should be fairly easy to refactor the method to take in whatever parameter you need.
A:
You can use BitmapFactoryOptions to reduce size of picture.You can use somthing like that :
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3; //reduce size 3 times
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I run a ruby script right after the server starts in Rails 5
I have two ruby scripts that need to be running while the server is.
Currently I am running them separately using detached screens, but I would like to launch them at the same time the rails server is starting.
How can I integrate them so that I can achieve this behavior?
A:
Have you tried Foreman gem? It will allow you to create a simple file (Procfile) where you can specify all the process that should be started simultaneously.
I usually create a file named Procfile.dev in the project's root, that would look like for example:
web: bundle exec rails server thin start -p 4000
mail: mailcatcher -f
your_script: instructions
Then you start your Rails app as:
foreman start -f Procfile.dev
With that command, Foreman will execute all the processes on the file.
You should install the gem locally and not in the Gemfile.
Foreman Gem
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to create vector polygon objects after watershed segmentation
After watershed segmentation using openCV-python to segment objects , I would like to get vector polygon objects (objects inside the blue circle) but I don't know how to do it in opencv-python. I attached the python code of the watershed segmentation and the image.
How to create vector polygon objects
import cv2
import numpy as np
import scipy.misc
import scipy.ndimage as snd
# image is read and is converted to a numpy array
img = cv2.imread('D:/exam_watershed/Example_2_medicine/Medicine_create_poly/medicine.jpg')
# image is convereted to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# binary thresholding is done using the threshold
# from Otsu's method
ret1,thresh1 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# foreground pixels are determined by
# performing erosion
fore_ground = cv2.erode(thresh1,None,iterations = 3)
bgt = cv2.dilate(thresh1,None,iterations = 3)
ret,back_ground = cv2.threshold(bgt,1,100,1)
# marker is determined by adding foreground and background pixels
marker = cv2.add(fore_ground,back_ground)
# converting marker to 32 int
marker32 = np.int32(marker)
cv2.watershed(img,marker32)
m = cv2.convertScaleAbs(marker32) #the output is converted to unit8 image
ret3,thresh3 = cv2.threshold(gray,0,255,\
cv2.THRESH_BINARY+cv2.THRESH_OTSU)
_, contours1, _= cv2.findContours(thresh3,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
b = cv2.drawContours(img, contours, -1, (0,255,0), thickness=1, lineType=8)
A:
You are close, just need a few more lines after finding the contours:
polys = []
for cont in contours1:
approx_curve = cv2.approxPolyDP(cont, 3, False)
polys.append(approx_curve)
cv2.drawContours(img, polys, -1, (0, 255, 0), thickness=1, lineType=8)
cv2.imshow("medicine polygons", img)
cv2.waitKey()
The doc on approxPolyDP.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Symfony template does not render labels in EasyAdmin
Instead of interpreting things like {{ list.page_title }}, it's just rendering as list.page_title, paginator.next, action.search, etc. I'm not getting any errors in the debug toolbar or dev log. I have cleared the cache.
Is there some setting I missed? How do I fix this or figure out where the error is?
A:
Make sure that the translator service is enabled in config.yml
framework:
translator: { fallbacks: [ "en" ] }
For more translation customisation see: https://symfony.com/doc/current/bundles/EasyAdminBundle/tutorials/i18n.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Controlling features rendered with ArcGIS Server service?
Question: Using a mapping service set up with ArcGIS Server, how can I set up a parameter that limits which features are being rendered? e.g. "/service?organization=megacorp"?
Background: I am working on a web mapping application which will be used by organizations. They all have their own data, but it is stored in the same tables.
When they log in, they will be brought to a map which shows their data points. Due to existing features, our preference is to store this data in a single table:
points_table
id | organization | name
------------------------------
1 | the state | poor house
2 | megacorp | tenements
3 | union carbide| bhopal
It looks like the proper way to secure this service will be to use windows integrated authentication, and although I'm not clear on the details, use that to control which features are being rendered.
A:
It looks like the proper way to secure this service will be to use
windows integrated authentication, and although I'm not clear on the
details, use that to control which features are being rendered.
Potentially, but not with ArcGIS Server security. ArcGIS Server security at 10.1 currently only allows you to dish out individual map services to different roles.
Approach 1 - Serve same data up as multiple services
Add points_table to ArcMap.
Apply definition query to only show features for specific organisation.
Publish this as a map service.
Repeat 1-3 for each organisation.
Setup ArcGIS Server security and add roles for each organisation. You mention Windows Authentication, but im assuming that each organisation does not belong to one active directory, so I would recommend just using the default users & roles identity store within ArcGIS Server, and create one user under each organisation role, and provide those credentials to each organisation to use.
Secure each service to each organisation role.
Serve all of these services up in a web application, and making use of the Esri Javascript API (can use any API, or even the ArcGIS Viewer for Flex), you can prompt users to login using the Identity Manager. Each organisation will only see the corresponding service they are entitled to see. Make sure you overlay these services onto a nice looking basemap as well.
Approach 2 - Use one Map Service and make use of the QueryTask
Server up your points_layer as one map service.
Manage security outside of ArcGIS Server. Perhaps with basic authentication at the web server level, creating a different user account for each organisation to use.
Users hit a login page. Once prompted to login, they are then redirected to your web application. (Or the login is just a modal prompt on the actual web application page, redirecting you to a different page if incorrect credentials).
As the user (organisation) logs in, this then feeds in this user to a QueryTask to only display the relevant points from your one map service on the map.
e.g.
sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/1/query?text=Texas
This REST call returns only the states that match the value of Texas.
These are just two ideas. Personally I would go with #2, but will depend on how secure this needs to be (#1 is more secure), how many points/organisations you have, and how much server power do you have (#1 will suck up more resources).
Id wait awhile to see what other answers pop up, as there may well be a better way.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sorting a 2 dimensional array in c
I am trying to sort a 2 dimensional array.the original array is
5 0 3
4 1 2
3 1 1
4 2 2
3 3 1
When sorted, it should be like
3 1 1
3 3 1
4 2 2
4 1 2
5 0 3
Here is the code i used trying to implement Bubble Sort,i represents the number of rows.
int x,y,z,j,temp1,temp2,temp3;
for(x=0;x<i;x++)
{
for (j=0;j<i-1;j++)
{
if(a[j][0]>a[j+1][0])
{
temp1=a[j][0];
temp2=a[j][1];
temp3=a[j][2];
a[j][0]=a[j+1][0];
a[j][1]=a[j+1][1];
a[j][2]=a[j+1][2];
a[j+1][0]=temp1;
a[j+1][1]=temp2;
a[j+1][2]=temp3;
}
}
}
it still does not sort, any help will be greatly appreciated.
A:
It looks like you are trying to sort the rows of the array in lexicographical order. If you treat the 2D array as an array of arrays, then you are just sorting the second-level arrays within the first-level array into ascending lexicographical order.
Depending on whether the number of columns in your array is fixed, you might be able to do this using the qsort function with a custom comparator. For example, if you know that there will always be exactly 3 elements in each column, you could write a comparator like this one:
static const size_t NUM_COLS = 3;
/* Lexicographically compare two arrays of size NUM_COLS. */
int CompareArrays(const void* arr1, const void* arr2) {
/* Convert back to the proper type. */
const int* one = (const int*) arr1;
const int* two = (const int*) arr2;
/* Do an element-by-element comparison. If a mismatch is found, report how
* the arrays compare against one another.
*/
for (size_t i = 0; i < NUM_COLS; i++) {
if (one[i] < two[i]) return -1;
if (one[i] > two[i]) return +1;
}
/* If we get here, the arrays are equal to one another. */
return 0;
}
/* Use qsort to sort the arrays */
qsort((const int*)&one, numRows, sizeof(int[NUM_COLS]), CompareArrays);
Hope this helps!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
string in xpath
I have a string and I want to use it as a selector in xpath to select a node with name as value of the string.
declare variable $get_count := <count><comedy>1</comedy></count>;
(: $string = "comedy" :)
let $value = $get_count/$string (: but this doesn't return anything)
How shall i do it?
A:
let $value = $get_count/$string (: but this doesn't return anything)
Use:
declare variable $get_count := <count><comedy>1</comedy></count>;
declare variable $string := "comedy";
let $value := $get_count/*[name()=$string]
return
$value
When this is applied on any XML document (not used), the wanted, correct result is produced:
<comedy>1</comedy>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
error: command 'C:\\ Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.14.26428\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2
Hi so I was trying to pip install python-ldap using my git bash but at first it told me that i don't have cl.exe so i downloaded the visual studio C++ pack now it's showing this error
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.14.26428\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2
I never coded with C++ so I'm not sure what the error is. I downloaded the CLI tools for C++ too and I don't think it's because the cl.exe isn't in the path since it found it. Any insights ??
A:
There doesn't seem to be a valid solution for this error but one workaround is to install the windows binary package from https://www.lfd.uci.edu/~gohlke/pythonlibs/#python-ldap
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android Service not getting start from JobIntentService on BOOT
I am trying to run a service on OREO device and service get started as it listens to android.intent.action.BOOT_COMPLETED intent.
Below is Boot Received Broadcast Reciever class:
public class ConnectionBOOTReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MyIntentService.enqueueWork(context, new Intent());
}
}
Below is my IntentService Class:
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;
public class MyIntentService extends JobIntentService {
// Service unique ID
static final int SERVICE_JOB_ID = 997;
// Enqueuing work into this service.
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, MyIntentService.class, SERVICE_JOB_ID, work);
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
onHandleIntent(intent);
}
private void onHandleIntent(Intent intent) {
startService(new Intent(this,MyBackgroundService.class));
//Handling of notification goes here
}
}
As I know there is some Background limitation I have to create two background services one is Foreground and other one runs in the background.
Background Service Code:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class MyBackgroundService extends Service {
private static final String TAG = "MyBackgroundService";
public int counter = 0;
public MyBackgroundService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "NotifyingDailyService", Toast.LENGTH_LONG).show();
Log.i("com.example.ss ", "NotifyingDailyService");
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
// send new broadcast when service is destroyed.
// this broadcast restarts the service.
stoptimertask();
}
private Timer timer;
private TimerTask timerTask;
long oldTime = 0;
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 1000, 1000); //
}
/**
* it sets the timer to print the counter every x seconds
*/
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
Log.i("in timer", "in timer ++++ " + (counter++));
}
};
}
/**
* not needed
*/
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
Foreground Service code :
public class MyForegroundBackgroundService extends Service {
private Context context;
public static final String NOTIFICATION_CHANNEL_ID = "10001";
public MyForegroundBackgroundService() {
}
@Override
public void onCreate(){
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
context = this;
super.onStartCommand(intent, flags, startId);
Intent intent1 = new Intent(this, MyForegroundBackgroundService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent1, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Calendar cal= Calendar.getInstance();
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.talentify_logo_red)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
public void sendNotification(String message,Context context){
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.general_message_notfication);
remoteViews.setTextViewText(R.id.message,message);
Intent intent = new Intent();
intent = new Intent(context, HomeActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.talentify_logo_red)
.setAutoCancel(true)
.setContentIntent(pIntent)
.setContent(remoteViews);
NotificationManager notificationmanager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
try {
long[] pattern = new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400};
builder.setVibrate(pattern);
builder.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.notification_sound));
} catch (Exception e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
int importance = NotificationManager.IMPORTANCE_HIGH;
@SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Urgent", importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
notificationmanager.createNotificationChannel(notificationChannel);
}
notificationmanager.notify(0, builder.build());
}
}
Below is exception which i am getting :
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=test.MyApplication/.service.MyBackgroundService }: app is in background uid UidRecord{7e9d561 u0a158 TRNB idle procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1536)
at android.app.ContextImpl.startService(ContextImpl.java:1492)
How can I start my service from Boot Broadcast receiver? How can I make sure that it should keep running always?
A:
Since Android O Apps can no longer run Background Services while the App is in the Background. You will need to either update to a foreground service or migrate to jobs. I recommend the Evernote Android Job library to simplify working with Jobs and backwards compatibility.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to avoid error when Get-AppxPackageManifest not found
This script lists the Windows Apps (Universal applications) installed on the system. It works but the command Get-AppxPackageManifest $app produces an error when the manifest file is not found. In my case, it happens for the app Windows.MiracastView.
I'm not familiar enough with PS scripting to write code to trap and avoid this error. What would be the "IF" command to skip an $app if its manifest file is not found?
$installedapps = get-AppxPackage
foreach ($app in $installedapps)
{
echo $app.Name
foreach ($id in (Get-AppxPackageManifest $app).package.applications.application.id)
{
$line = $app.Name + "=" + $app.packagefamilyname + "!" + $id
echo $line
$line >> 'C:\Temp\CollectWindowsAppsList.txt'
}
}
echo "Press any key to continue..."
[void][System.Console]::ReadKey($true)
Thanks.
A:
Try Catch block is one way to do this:
$installedapps = Get-AppxPackage
foreach ($app in $installedapps){
Write-Output $app.Name
$ids = $null
try{
# Add ids to array
$ids += (Get-AppxPackageManifest $app -erroraction Stop).package.applications.application.id
}
catch{
# this catches everything so good idea to provide some feedback
Write-Warning "No Id's found for $($app.name)"
}
foreach ($id in $ids){
$line = $app.Name + "=" + $app.packagefamilyname + "!" + $id
Write-Output $line
$line >> 'C:\Temp\CollectWindowsAppsList.txt'
}
}
Write-Output "Press any key to continue..."
[void][System.Console]::ReadKey($true)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java 32 bit and 64 bit
Java Byte Code is the language to which Java source is compiled and
the Java Virtual Machine understands. Unlike compiled languages that
have to be specifically compiled for each different type of computers,
a Java program only needs to be converted to byte code once, after
which it can run on any platform for which a Java Virtual Machine
exists.
I can understand that once java is compiled the class can be run from any machine because the compiled class can be understood by any machine.
My question is: Why are there 2 types of jdk then? (x86, x64)
A:
The Java Virtual Machines are themselves applications that need to run on top of a hardware architecture and operating system and most likely they are not implemented in Java themselves.
That is the case of the popular Java HotSpot Virtual Machine (the default implementation from Oracle) which is mostly implemented in C/C++.
That means you need a compiled version of it for every hardware architecture and operating system in which you intend to use it, and so that explains that there are versions of it for 32-bit and 64-bit hardware architectures.
This is also the case of other JVM implementations, like JRockit, IBM J9, Azul Systems Zulu and probably many others.
Other helper programs aside the Java Virtual Machine, typically included for programmers to develop applications as part of what is know as the JDK (Java Development Kit) may also be developed in this way. That is the case of tools like the compiler (javac), the documentation generator (javadoc), the RMI compiler (rmic), the Java disassembler, (javap), etc.
So, those JDK tools would also require a hardware dependent implementation. And so that's why you are offered a choice when downloading the JDK.
--Edit--
Addressing the questions on the "portability" subject
It depends on what you mean by "portability". If you mean the Java's WORA (write once, run anywhere), then it has to be through a virtual machine like Java, Python or Ruby. But languages like C/C++ compile to machine code, and therefore, they are not run through a virtual machine, but by the hardware itself. This does not mean they are not portable, you may write your code in way that can be run in multiple architectures, it is just that you cannot use the same binaries. You have to recompile for every case, since the program must be written/compiled in a way a particular hardware/os understands.
This gap is what the virtual machines intend to close.
Now, portability can mean more than just using the same binaries. Even with Java you may write code that is not portable, perhaps because you use OS dependent features or because you mistakenly programmed paths using literals (i.e Linux / vs Windows \), etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
UIViewAnimationOptionTransitionFlipFromRight not recognized by Xcode
I am implementing a very simple flip animation, but the flip isn't there.
I am using an example from the docs as a template, Apple now recommends you use blocks for animations and that this is the approach to take: (from the docs)
[UIView transitionWithView:containerView
duration:0.2
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{ [fromView removeFromSuperview]; [containerView addSubview:toView]; }
completion:NULL];
Wrapping the two views you want to transition between in a container.
I do it like this.
UIView *container = [[UIView alloc] initWithFrame:target];
[self.view addSubview:container];
[container addSubview:productImage];
UIView *background = [[UIView alloc] initWithFrame:target];
[background setBackgroundColor:[UIColor darkGrayColor]];
[background setAlpha:0.1f];
[UIView transitionWithView:container
duration:0.8
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
[[[container subviews] objectAtIndex:0] removeFromSuperview];
[container addSubview:background];
}
completion:NULL];
Two strange things happen:
There is no transition, the container displays the productImage (of type UIImageView), then swaps it with the background view. No animation.
The second thing is what led me to believe that this is not the usual typo, was that the
UIViewAnimationOptionTransitionFlipFromRight
is not recognized by Xcode, it will not autocomplete, it is not highlighted. Xcode will only do that if I use the deprecated:
UIViewAnimationTransitionFlipFromRight //i.e. without the Option part
I then started to check my SDK version etc. everything seems to be set to 4.2, XCode is version 3.2.5, both target and project settings has build and deploy target set to 4.2.
What am I missing here?
Hope a set of trained eyes can help me:) thank you in advance.
A:
If you are going with blocks (and everyone should start going with them), please refer to
+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion
and/or
+ (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find the value of the real part of (z+w)/(z-w) when |z| = |w|
It's an IBDP question.
When I try to solve it, I end up with a fraction with many variables.
I was thinking maybe I should rationalize the fraction...
A:
Write $z=re^{it}$ and $w=re^{iu}$. Then
$$\frac{z+w}{z-w}=\frac{e^{it}+e^{iu}}{e^{it}-e^{iu}}
=\frac{e^{i(t-u)/2}+e^{-i(t-u)/2}}{e^{i(t-u)/2}-e^{-i(t-u)/2}}
=\frac{2\cos\frac12(t-u)}{2i\sin\frac12(t-u)}=i\cot\theta$$
where $\theta=\frac12(u-t)$ is half the angle between $z$ and $w$ in the
Argand diagram. So zero real part, but the imaginary part is interesting.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Прокрутка страницы ниже, чем окончание кода?
При написание кода в PhpStorm у меня остается маленький кусок страницы снизу, после которого прокрутка страницы ниже прекращается:
Можно конечно через Enter создать еще пачку пустых строк, но не думаю, что это хороший вариант:
Вопрос: где в настройках PHPStorm (если такого в настройках нет, то какой плагин посоветуете), чтобы сделать область после кода больше, а лучше вообще ее отключить, чтобы можно было крутить страницу в низ неограниченно?
A:
Решение:
Settings > Editor > General : Show virtual space at file bottom = yes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Global variables in SharePoint
Is it possible to define a global variable in SharePoint 2010 and then reference it in menus and server-side pages? We currently have a menu item on all 30+ web sites that points to the existing intranet home but will need to change it to point to the new one. Is it possible to set this to a variable defined in global.asax? Is there another way to change the menu item globally?
Thank you.
A:
The recommended way to do this is to use PropertyBag (key/value pairs) through the Properties of SPFarm, SPSite.RootWeb (for root site of site collections), SPWeb, SPList etc (depending upon the scope that you need).
Managing Custom Configuration Options for a SharePoint Application
Update code example:
// ...inside web app feature activation code
SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
string existingValue = ... //get existing value from menu
webApp.Properties.Add("settingkey", existingValue);
// reference property later
string savedProperty = webApp.Properties["settingkey"];
Accessing SPWeb.Properties was just as easy except that I referenced the web application differently. Since the feature is scoped to the web, the Feature.Parent will be an SPWeb instance instead of SPWebApplication. Follow this pattern instead.
SPWeb web = (SPWeb)properties.Feature.Parent;
web.Properties.Add("settingkey", existingValue);
A:
Another option is to use Chris O'Brien Config Store (in CodePlex). Essentially it is a SharePoint list that contains your variables and values that can be accessed programatically. It also deals with caching so it doesn't have to retrieve the value every time. There's some installation and configuration hassles to be aware of (like modifying web.config ) but generally it works perfectly well. The clear advantage here is the user experience with access to the SharePoint list to perform CRUD operations on the variables.
Check it out in Code Plex here. And you know it is quality as Chris O'Brien is a legend in the SP space.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I implement a timeout / wait for an NSStream to effectively make method synchronous
I have an input stream and output stream for a bluetooth connected accessory
I want to achieve the following:
write data to outputStream
wait until data received on inputStream OR until 10 seconds pass
if inputStream data arrived return data
else return nil
I tried to implement this like so:
- (APDUResponse *)sendCommandAndWaitForResponse:(NSData *)request {
APDUResponse * result;
if (!deviceIsBusy && request != Nil) {
deviceIsBusy = YES;
timedOut = NO;
responseReceived = NO;
if ([[mySes outputStream] hasSpaceAvailable]) {
[NSThread detachNewThreadSelector:@selector(startTimeout) toTarget:self withObject:nil];
[[mySes outputStream] write:[request bytes] maxLength:[request length]];
while (!timedOut && !responseReceived) {
sleep(2);
NSLog(@"tick");
}
if (responseReceived && response !=nil) {
result = response;
response = nil;
}
[myTimer invalidate];
myTimer = nil;
}
}
deviceIsBusy = NO;
return result;
}
- (void) startTimeout {
NSLog(@"start Timeout");
myTimer = [NSTimer timerWithTimeInterval:10.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];
}
- (void)timerFireMethod:(NSTimer *)timer {
NSLog(@"fired");
timedOut = YES;
}
- (void)stream:(NSStream*)stream handleEvent:(NSStreamEvent)streamEvent
{
switch (streamEvent)
{
case NSStreamEventHasBytesAvailable:
// Process the incoming stream data.
if(stream == [mySes inputStream])
{
uint8_t buf[1024];
unsigned int len = 0;
len = [[mySes inputStream] read:buf maxLength:1024];
if(len) {
_data = [[NSMutableData alloc] init];
[_data appendBytes:(const void *)buf length:len];
NSLog(@"Response: %@", [_data description]);
response = [[APDUResponse alloc] initWithData:_data];
responseReceived = YES;
} else {
NSLog(@"no buffer!");
}
}
break;
... //code not relevant
}
}
So the theory was to have an NSTimer running on a separate thread that would set a boolean when it fired, then also have the handleEvent delegate method set another boolean if data is received.
In the method we have a while loop with a sleep that will cease when one of these bools is set.
The problem I am having is that in the 'timeout scenario' my timerFireMethod is not getting called. My gut feeling is that I am not actually correctly setting the timer on a separate thread.
Can anyone see what is going wrong here or suggest a better implementation for the requirement above?
A:
Instead to impose an inappropriate synchronous approach for an inherently asynchronous problem, make your method sendCommandAndWaitForResponse asynchronous.
It's possible to wrap the "stream write" task into an asynchronous operation/task/method. For example, you might end with a concurrent subclass of NSOperation with the following interface:
typedef void (^DataToStreamCopier_completion_t)(id result);
@interface DataToStreamCopier : NSOperation
- (id) initWithData:(NSData*)sourceData
destinationStream:(NSOutputStream*)destinationStream
completion:(DataToStreamCopier_completion_t)completionHandler;
@property (nonatomic) NSThread* workerThread;
@property (nonatomic, copy) NSString* runLoopMode;
@property (atomic, readonly) long long totalBytesCopied;
// NSOperation
- (void) start;
- (void) cancel;
@property (nonatomic, readonly) BOOL isCancelled;
@property (nonatomic, readonly) BOOL isExecuting;
@property (nonatomic, readonly) BOOL isFinished;
@end
You can implement a "timeout" feature utilizing the cancel method.
Your method sendCommandAndWaitForResponse: becomes asynchronous with a completion handler:
- (void)sendCommand:(NSData *)request
completion:(DataToStreamCopier_completion_t)completionHandler
{
DataToStreamCopier* op = [DataToStreamCopier initWithData:request
destinationStream:self.outputStream
completion:completionHandler];
[op start];
// setup timeout with block: ^{ [op cancel]; }
...
}
Usage:
[self sendCommand:request completion:^(id result) {
if ([result isKindOfClass[NSError error]]) {
NSLog(@"Error: %@", error);
}
else {
// execute on a certain execution context (main thread) if required:
dispatch_async(dispatch_get_main_queue(), ^{
APDUResponse* response = result;
...
});
}
}];
Caveat:
Unfortunately, implementing a concurrent NSOperation subclass properly with an underlying task employing a run loop isn't that trivial as it should be. There will arise subtle concurrency issues which force you to use synchronization primitives like locks or dispatch queues and a few other tricks to make it really reliable.
Luckily, wrapping any Run Loop task into a concurrent NSOperation subclass requires basically the same "boiler plate" code. So, once you have a generic solution, the coding effort is just copy/past from a "template" and then tailor the code for your specific purpose.
Alternative Solution:
Strictly, you don't even need a subclass of NSOperation if you don't plan to put a number of those tasks into a NSOperationQueue. A concurrent operation can be simply started with sending it the start method - there is no NSOperationQueue required. Then, not using a subclass of NSOperation can make your own implementation simpler, since subclassing NSOperation itself has its own subtleties.
However, you actually need an "operation object" which wraps your Run Loop driving a NSStream object, since the implementation requires to hold state, which cannot be accomplished in a simple asynchronous method.
So, you can use any custom class which can be viewed as an asynchronous operation having a start and cancel method and having a mechanism to notify the call-site when the underlying task is finished.
There are also more powerful means to notify the call-site than completion handlers. For example: promises or futures (see wiki article Futures and promises).
Assuming you implemented your own "asynchronous operation" class with a Promise as a means to notify the call-site, e.g.:
@interface WriteDataToStreamOperation : AsyncOperation
- (void) start;
- (void) cancel;
@property (nonatomic, readonly) BOOL isCancelled;
@property (nonatomic, readonly) BOOL isExecuting;
@property (nonatomic, readonly) BOOL isFinished;
@property (nonatomic, readonly) Promise* promise;
@end
your original problem will look much more "synchronous" - albeit sill being asynchronous:
Your sendCommand method becomes:
Note: assumes a certain implementation of a Promise class:
- (Promise*) sendCommand:(NSData *)command {
WriteDataToStreamOperation* op =
[[WriteDataToStreamOperation alloc] initWithData:command
outputStream:self.outputStream];
[op start];
Promise* promise = op.promise;
[promise setTimeout:100]; // time out after 100 seconds
return promise;
}
Note: the promise has set a "timeout". This is basically registering a timer and a handler. If the timer fires before the promise gets resolved by the underlying task, the timer block resolves the promise with a timeout error. How (and IF) this is implemented depends on the Promise library. (Here, I'm assuming the RXPromise library, where I'm the author. Other implementation may also implement such a feature).
Usage:
[self sendCommand:request].then(^id(APDUResponse* response) {
// do something with the response
...
return ...; // returns the result of the handler
},
^id(NSError*error) {
// A Stream error or a timeout error
NSLog(@"Error: %@", error);
return nil; // returns nothing
});
Alternative Usage:
You may set the timeout in a different way. Now, suppose we didn't set a timeout within the sendCommand: method.
We can set a timeout "outside":
Promise* promise = [self sendCommand:request];
[promise setTimeout:100];
promise.then(^id(APDUResponse* response) {
// do something with the response
...
return ...; // returns the result of the handler
},
^id(NSError*error) {
// A Stream error or a timeout error
NSLog(@"Error: %@", error);
return nil; // returns nothing
});
Making the asynchronous method synchronous
Usually, you don't need to and shouldn't "convert" an asynchronous method to some synchronous method in your application code. This always leads to suboptimal and inefficient code which unnecessarily consumes system resources, like threads.
Nonetheless, you may want to do this in Unit Tests where it makes sense:
Example for "synchronizing" asynchronous methods in Unit Tests
When testing your implementations, you frequently want to "wait" (yes synchronously) for a result. The fact that your underlying task is actually executing on a Run Loop, possibly on the same thread where you want to wait for the result, doesn't make the solution simpler.
However, you can accomplish this easily with RXPromise library utilizing the runLoopWait method which effectively enters a run loop and waits there for the promise to be resolved:
-(void) testSendingCommandShouldReturnResponseBeforeTimeout10 {
Promise* promise = [self sendCommand:request];
[promise setTimeout:10];
[promise.then(^id(APDUResponse* response) {
// do something with the response
XCTAssertNotNil(response);
return ...; // returns the result of the handler
},
^id(NSError*error) {
// A Stream error or a timeout error
XCTestFail(@"failed with error: %@", error);
return nil; // returns nothing
}) runLoopWait]; // "wait" on the run loop
}
Here, method runLoopWait will enter a run loop, and wait for the promise to be resolved, either by a timeout error or when the underlying task has resolved the promise. The promise will not block the main thread and not poll the run loop. It will just leave the run loop when the promise has been resolved. Other run loop events will be processed as usual.
Note: You can safely call testSendingCommandShouldReturnResponseBeforeTimeout10 from the main thread without blocking it. And this is absolutely necessary, since your Stream delegate methods may execute on the main thread, too!
There are other approaches usually found in Unit testing libraries which provide a similar feature to "wait" for the result of an asynchronous method or operation while entering a run loop.
Other approaches to "wait" for an eventual result of an asynchronous method or operation are not recommended. These usually will dispatch the method to a private thread and then block it until the result is available.
Useful resources
Code snippet (on Gist) for an operation like class which copies a stream into another stream utilizing Promises:
RXStreamToStreamCopier
|
{
"pile_set_name": "StackExchange"
}
|
Q:
EXC_BAD_ACCESS In Sending Mail With Attachement in iPhone
I have create program to send mail with my some detail from sqlite database
It is working fine if I am not using attachment but if i uncomment that like i m getting exception like this:
Thread 1: EXC_BAD_ACCESS(code=1, address=0x474e5091
here is My code:
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = (id) self;
NSArray *recipients = [NSArray arrayWithObject:@"[email protected]"];
[mailView setToRecipients:recipients];
[mailView setSubject:@"Try Mail From User Application"];
NSString *body = [[NSString alloc] initWithFormat:@"First Name : %@ <br>",lblFirstName.text];
body = [body stringByAppendingFormat:@"Last Name : %@<br>",lblLastName.text];
body = [body stringByAppendingFormat:@"Username : %@<br>",lblUsername.text];
body = [body stringByAppendingFormat:@"Password : %@<br>",lblPassword.text];
body = [body stringByAppendingFormat:@"Birthdate : %@<br>",lblBD.text];
[mailView addAttachmentData:[UIImagePNGRepresentation(u.Img1) bytes]
mimeType:@"image/png"
fileName:@"a.png"];
[mailView setMessageBody:body isHTML:YES];
[self presentModalViewController:mailView animated:YES];
I m getting data correctly from database and i m able to display image on screen but problem is only when i attach image to mail
Here in
UIImagePNGRepresentation(u.Img1)
U is an object of User Class (user define class) and Img1 is object of UIImage
A:
First of the addAttachmentData:mimeType:fileName: method need a NSData object, so there is not need o call the bytes method on the NSData.
If you try this in you code you can check wether the UIImagePNGRepresentation() method returns a valid NSData object. Just place a breakpoint on the line and check what the values are in the debugger.
NSData *imageDate = UIImagePNGRepresentation(u.Img1);
[mailView addAttachmentData:imageDate mimeType:@"image/png" fileName:@"a.png"];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
DataTemplate does not show up with TabControl
i am using a DataBinding to show all Controls in the ItemsSource
<TabControl Grid.Row="1" TabStripPlacement="Left" ItemsSource="{Binding Source={StaticResource WorkflowSelector}, Path=Workflows}" SelectedIndex="0">
<TabControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding PluginName}"></Label>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
the WorkflowSelector is my ViewModel which contains a List of all Controls that should be shown in the TabControl.
I created an itemTemplate to show the PluginName (public property) in the Tab
but nothing is shown.
If i inspect the Visual tree i can see the Databinding of the Tabcontrol, containing 1 Item that has a Property PluginName.
The evaluated Value of the BindingExpression of the Label is empty
first thing i noticed is that the ContentPresenter does not have a DataContext, while the Border does have the correct DataContext
Additionally ... if i change the ItemTemplate to ContentTemplate the binding is working correctly (but in the content not in the header)
A:
since i saw in the Visual tree that the DataContext was set higher up in the hierarchy, i changed my data binding to:
<Label Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TabItem}}, Path=DataContext.PluginName}"></Label>
this does not explain the root-cause, but it is a short workaround i can live with
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Elementary Events vs Elements in the Sample Space
I keep seeing questions in my assignments like
What is the sample-space for this set, and what are it's elementary events?
For the past couple of assignments, I assumed they were the same thing. It seems like this type of question pops up quite often and I'd like to know the difference between them.
If I were to take a guess at the difference it would be:
Elementary Events: Unique events in the sample space.
Sample Space: The set of events that are possible.
These are the definitions that I keep seeing for both of these, but to me, the definitions are basically the same.
A:
I keep seeing questions in my assignments like
What is the sample-space for this set, and what are it's elementary events?
For the past couple of assignments, I assumed they were the same thing. It seems like this type of question pops up quite often and I'd like to know the difference between them.
They are mostly the same thing in concept; though technically different.
An event is a set of outcomes. An atom, or atomic set, is a set of one element. An atomic event and an outcome are different things; although often loosely referred to as though they were the same thing.
The sample space is the set of all outcomes. Its elementary events are the collection of atomic subsets that partition the space.
$\{1,2,3,4,5,6\}$ is the sample space for the result of one die roll.
$\{1\},\{2\},\{3\},\{4\},\{5\},\{6\}$ are the elementary events of this space.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are locks unnecessary in multi-threaded Python code because of the GIL?
If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all?
If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect?
sorry if this is a dumb question, but it is something I have always wondered about Python on multi-processor/core machines.
same thing would apply to any other language implementation that has a GIL.
A:
You will still need locks if you share state between threads. The GIL only protects the interpreter internally. You can still have inconsistent updates in your own code.
For example:
#!/usr/bin/env python
import threading
shared_balance = 0
class Deposit(threading.Thread):
def run(self):
for _ in xrange(1000000):
global shared_balance
balance = shared_balance
balance += 100
shared_balance = balance
class Withdraw(threading.Thread):
def run(self):
for _ in xrange(1000000):
global shared_balance
balance = shared_balance
balance -= 100
shared_balance = balance
threads = [Deposit(), Withdraw()]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print shared_balance
Here, your code can be interrupted between reading the shared state (balance = shared_balance) and writing the changed result back (shared_balance = balance), causing a lost update. The result is a random value for the shared state.
To make the updates consistent, run methods would need to lock the shared state around the read-modify-write sections (inside the loops) or have some way to detect when the shared state had changed since it was read.
A:
No - the GIL just protects python internals from multiple threads altering their state. This is a very low-level of locking, sufficient only to keep python's own structures in a consistent state. It doesn't cover the application level locking you'll need to do to cover thread safety in your own code.
The essence of locking is to ensure that a particular block of code is only executed by one thread. The GIL enforces this for blocks the size of a single bytecode, but usually you want the lock to span a larger block of code than this.
A:
Adding to the discussion:
Because the GIL exists, some operations are atomic in Python and do not need a lock.
http://www.python.org/doc/faq/library/#what-kinds-of-global-value-mutation-are-thread-safe
As stated by the other answers, however, you still need to use locks whenever the application logic requires them (such as in a Producer/Consumer problem).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Combinatorics Question - Permutations and Supersets
I had a question that seems pretty straightforward, but I can't seem to wrap my mind around it.
Let's say I have a bunch of elements in a set. {A, B, C, D, E}.
How many permutations are there of every subset of this set? For example, I want to come up with every permutation of these elements that uses all possible elements, as well as all possible subsets of all the elements.
My guess is that we have 5! permutations to use all elements, 4! permutations to use a set of 4, which there are 5 of, 3! permutations to use a set of 3, which there are (5 * 4) of, 2! permutations to use a set of 2, which there are (5 * 4 * 3) of, and 1! permutations to use a set of 1, which there are (5 * 4 * 3 * 2) of.
Mathematically, how can this expression be generalized to a set of size n?
Thanks!
A:
The number of permutations of every subset of a set of size $n$ is $\lfloor n!e\rfloor$. This is because
$$
\sum_{k=0}^n\underbrace{\binom{n}{k}}_{\substack{\text{number of}\\\text{subsets of}\\\text{size $k$}}}\underbrace{k!\vphantom{\binom{n}{k}}}_{\substack{\text{number of}\\\text{permutations}\\\text{on a subset}\\\text{of size $k$}}}
=\sum_{k=0}^n\frac{n!}{(n-k)!}
=\sum_{k=0}^n\frac{n!}{k!}
=\lfloor n!e\rfloor
$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is Poison Resistance Over Time with Anti-Toxin Possible?
I've got in-world poisons, often with real-world analogues (like belladonna) but in building the social structure of the back-stabbing nobility, I began looking at poison resistances and antidotes.
Basically, those who protect royalty also try and find a way to up their poison resistance, and during especially troubled times, put anti-toxins in their foods.
I already know about Mithridatism, "the practice of protecting oneself against a poison by gradually self-administering non-lethal amounts." But this is not what I am wanting to do.
I am looking to gradually dose the king with a general anti-toxin that's proof against most poisons. My question here is, are there real-life analogues that would be that broad? And if not, what combinations of things would be best?
EDIT: Don't worry about tech level--can be anything through to today's science--this is set in a Renaissance-type world, but I can adjust anything to fit because the world is pretty flexible and not entirely Renaissance, I just need some jumping off points to create what's needed.
THE PROBLEM:
Right now, I am finding that many things which wipe out poison aren't actually good to ingest on the regular (like charcoal)--and I am looking for things that will. Stuff that's close is ok, because I can use it as a starting point at least in building that bit of my world.
A:
This seems possibly unlikely. One problem in answering your answer is an uncertainty in the technological level of your world. Traditional poisons are deadly herbs and mineral-derived chemicals. Unless your world possesses herbs or other planet materials that can act as counter-agents to a given class of toxic herbs, then this may be improbable.
However, this argument can be turned on its head. Since, it's your world, you are free to introduced varieties of poisonous plants that have other plants which naturally produce substances that either denature the poisons themselves or bind to the receptors in the intended victim's body to prevent the toxins from binding and causing the death of the person.
By and large, what you are contemplating to an anitoxin (or class of antitoxins) that work on equivalent lines to to a snake antivenom. While this requires post-medieval medical science and technology to facilitate and make practical (in the real world). There is no reason why in a constructed world, as argued above, there could be classes of substances (preferably botanical or even animal derived) where some are poisons and others are their equivalent antitoxins.
Plants have a long, protracted and extensive evolutionary history of developing defensive substances to ward insects, fungi, bacteria and herbivores. Effectively, these are poisons. Therefore, it is possible that the various predators on poisonous plants will develop on their counter-agents. This can include developing antitoxins or metabolic pathways to detoxify any poisons.
If you allow yourself the luxury of going one step further, some but not necessarily all** antitoxins may have a vaccine-like action on persons to whom they administered. This will have desired effect to facilitate a situation along the lines you are hoping for in your world.
**: You don't want every poison vaccinated against, this will dissipate dramatic tension. Also, some vaccines can wear off. So keeping up your doses of antitoxin may still be necessary. Again this is good for dramatic tension. We all know you don't want to make things too easy.
A:
Cytochrome_P450s as a class are the enzymes which the body uses to break down most organic molecules - including drugs, toxins, ethanol and presumably organic poisons.
https://en.wikipedia.org/wiki/Cytochrome_P450#Drug_metabolism
In the presence of lots of substrate the liver upregulates the given cytochrome p450 molecules needs. Chronic alcohol, for example, upregulates CYP2E1. Other cytochromes which handle other toxins can be upregulated by specific substrates (and inhibited by others). This is why you are not supposed to drink grapefruit juice with certain drugs - the juice inhibits the CYP and thus the metabolism of the drug.
So to get the CYPs good and induced you could drink inducers. I think fortified wine (of the Night Train variety) laced with plentiful capsaicin would be a fine start.
For heavy metal detox the body uses glutathione. It is not so straightforward to induce. It is interesting, however, that the mechanism of glutathione is its abundance of -SH sulfhydryl groups which bind lead, mercury and the like. Hair is also very rich in free sulfhydryl groups and hair is the main ingredient in the well known antipoison, bezoar.
Bezoars are basically hairballs. This one ought to last you a couple of days.
So: to cover against arsenic, mercury and the like I recommend finely chopped bezoars (of the hairball variety!) to be added to the capsicum wine. Shake well. Serve cold.
One might object that no less an august personage that Ambroise Pare demonstrated bezoar to be ineffective by testing it on a cook condemned to die: instead of hanging the cook opted to eat a bezoar then poison, and died in agony. The poison chosen was lye. I do not think there is anything which will induce an immunity to lye.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Generating source maps for multiple concatenated javascript files compiled from Coffeescript
Has any one had any success with this?
A:
I think it's more or less an unsolved problem:
https://github.com/jashkenas/coffee-script/issues/2779 . Last meanigingful comment was from jwalton, a month ago.
Still, it doesn't seem rocket science to add support for it, so it will probably come soon.
Michael Ficarra (creator of CoffeeScript Redux) suggested using https://github.com/michaelficarra/commonjs-everywhere .
Two caveats:
It only works for bundling CommonJS modules.
It uses CoffeeScript Redux, which is still in beta (although working quite well it seems), and not 100% compatible with original CoffeeScript compiler.
So this does not work for what you ask for specifically, "concatenation".
Added April 14
You might have luck with these: combine-source-map and/or generate-sourcemap, both by same author.
Added April 26
This looks really simple: https://npmjs.org/package/mapcat . You just have to feed it the individual source map files generated by the coffee compiler.
Added May 16
Mariusz Nowak has just released webmake-coffee. Like CommonJS Everywhere, it requires code to be organized as CommonJS modules. Unlike CommonJS everywhere, it uses regular CoffeeScript.
It also seems the Grunt Coffee-Script plugin has had source-map support for concatenated files for quite a while (two months), effectively proving my original answer to be incorrect.
The upcoming version 2.0 of Snockets will have support for it too.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Como descobrir em que geração do garbage collector um objeto está alocado?
Considerando minha pergunta anterior sobre as gerações do GC, gostaria de entender se considerar o "momento" pelo qual um objeto está passando dentro do seu ciclo de vida, traz algum benefício ou é necessário para resolver algum tipo de problema?
Para que eu programe corretamente, preciso saber a geração na qual um objeto está alocado?
A:
Sim, é possível com o método GC.GetGeneration().
A utilidade prática em códigos normais é discutível. Você nem pode se valer muito disso porque é detalhe de implementação. É útil para fazer diagnósticos, medições, experimentos e talvez alguma coisa muito avançada, provavelmente uma ferramenta de desenvolvimento mais que uma aplicação normal.
O que precisa saber é que o ideal é que os objetos morram jovens ou vivam para sempre, não precisa saber em qual geração ele está. Quando dizemos que deve evitar que um objeto chegue na Gen2, não quer dizer que você precisa ficar monitorando isso. O problema da Gen2 é que se ela tiver que ser coletada pode ter uma pausa muito grande.
using System;
public class Program {
public static void Main() {
var objeto = new object();
Console.WriteLine($"Geração {GC.GetGeneration(objeto)}");
GC.Collect();
Console.WriteLine($"Geração {GC.GetGeneration(objeto)}");
GC.Collect();
Console.WriteLine($"Geração {GC.GetGeneration(objeto)}");
}
}
Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.