text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
Disable CKEditor on summary
When I use the widget "field-type-text-with-summary" with the CKEditor, my summary is shown in the CKEditor-format. Can I prevent this and display the field with the plain-format? Hooking into the form, I haven't found a format for the summary; there is just one for the whole body field.
using CKEditor module.
Are you using the CKEditor module, or the WYSIWYG module?
the CKEditor module
OK, I think using WYSIWYG instead of CKEditor will help your issue. See my answer below.
thank you, but I want/need to use the CKEditor module for better configuration.
and in drupal8 ?
I believe the easier path is going with WYSIWYG module.
If you want to go with CKEditor, it sets the editor using hook_element_info_alter. It changes the widget for any form element of the type text_format, in every form built with drupal.
I went looking for the pre_render function CKEditor uses to set the editor up, and figured out a way to prevent it from showing up in summary fields only. First, we'll have to swap the CKEditor pre_render function for one of our own:
function MYMODULE_element_info_alter(&$types) {
if (!empty($types['text_format']['#pre_render'])) {
$types['text_format']['#pre_render'] = array_diff($types['text_format']['#pre_render'], array('ckeditor_pre_render_text_format'));
}
$types['text_format']['#pre_render'][] = 'MYMODULE_ckeditor_pre_render_text_format';
}
Your module must run its code after CKEditor, and you better declare it depends on CKEditor in the .info file.
Then copy the ckeditor_pre_render_text_format from CKEditor module to your module and change its name to MYMODULE_ckeditor_pre_render_text_format. You will notice it already has an if clause that checks whether $element['summary'] and loads CKEditor for both value and system. Just delete the line that sets it for summary. In version 1.4 (latest stable) the line looks like this:
$element['summary'] = ckeditor_load_by_field($element['summary'], $element['format']['format'], FALSE);
and in drupal8?
I solved this for the CKEditor module for Drupal 7 by altering the widget itself using hook_field_widget_WIDGET_TYPE_form_alter():
/**
* Implements hook_field_widget_WIDGET_TYPE_form_alter().
* Set the '#wysiwyg'-attribute to false for the summary fields.
*/
function YOURMODULE_field_widget_text_textarea_with_summary_form_alter(&$element, &$form_state, $context) {
if (isset($element['summary']) && !isset($element['summary']['#wysiwyg'])) $element['summary']['#wysiwyg'] = false;
}
Hope this helps!
I used $element['summary']['#wysiwyg'] = false; in my hook_form_alter where I create the form. Works like a charm +1
It is odd that the CKEditor module does not have this option. But until that happens, I created a module that inserts a #wysiwyg=FALSE via a #process function.
Use the CKeditor plain summary module.
Rather than use the CKEditor module use WYSIWYG (and place the CKEditor library in the sites/all/libraries directory). It will only apply the editor of choice to a particular input format so you don't need to mess around with disabling the editor on textareas where it's not needed. Using CKEditor with the WYSIWYG module will not apply the editor to the summary (like you want), although it is possible with hooks to add one if needed.
Drupal doesn't have an input format for the summary: Both the summary and the body use the same input format.
Might have to take an approach similar to http://drupal.org/project/excerpt, (Drupal 6). Some details from the module's project page:
Excerpt module allows you to enter a separate excerpt/summary/teaser for a node, which does not have to be a cut off version of the body.
Even though Drupal 6 provides similar functionality, Excerpt is useful for various reasons, for instance, when also using editors like TinyMCE.
Have a look at the hooks used and something might be useful.
You may be able to implement hook_form_alter and use the #wysiwyg parameter with a value of FALSE. I used this in Fill PDF to aid in preventing the WYSIWYG editor from appearing without having to set a separate ignore rule.
See this issue: http://drupal.org/node/285200 - looks like it's just been re-implemented. I never knew it had been removed!
| common-pile/stackexchange_filtered |
Implementation of interfaces and components in a component-based framework
I'm currently trying to develop a small component-based android framework, but I have a doubt about which is the best way to implement my components and interfaces. An architecture of one of my components is shown below.
My doubt is, should I create one implementation per interface ( i.e ClientBuyHistoryImpl, CallClientImpl, etc. ) and create a ClientsSystem class that would be my component and then declare those implemented interfaces inside it. e.g. :
public class ClientsSystem {
public IClientBuyHistory clientBuyHistoryImpl;
public ICallClient callClientImpl;
/* ... */
}
Or should I create a class that implements all interfaces? e.g. :
public class ClientSystem implements IClientBuyHistory, ICallClient{
@Override
/* ... */
@Override
/* ... */
}
Another approach I was thinking about is to use Dagger2 to create Modules and Components and then inject them, but this way, How would be the implementation? My interface's implementation will become a Module and my component class would become a Component.?
I would probably be more in favor of making an implementation per interface, and then using them to compose whatever the system requires through a factory. How the ClientSystem class is supposed to be used ? Is it supposed to be a facade or something ?
What don't you try to inject the required component implementation inside ClientSystem methods ? You could used inversion of control, that would be probably a better approach. I can provide you an example, if you wish.
| common-pile/stackexchange_filtered |
what's the difference between NoSql DB and OO Db?
what's the difference between NoSql DB and OO Db?
An object-oriented database, like db4o, would be considered one of the alternatives presented by NoSQL, which means Not Only SQL. It's a set of alternatives to relational databases: Voldemort, Hadoop, MongoDB, CouchDB, BigTable, Neo4J, db4o and others.
I would characterize Neo4J as a graph database, not an object-oriented database. Also, I disagree with your statement that NoSQL is about alternatives to relational databases. Stuff like Rel or Tutorial D, which are relational, are very much in the scope of NoSQL. Also: what does a graph database store if not relations?
+1 for pointing out that NoSQL means "Not only SQL", and not "No SQL"
You are correct, Jorg. My mistake. I was thinking of db4o. I'll correct it.
Relational in the sense of tables, columns, and joins as traditionally done by RDBMS systems like Oracle, MySQL, etc.
So is an OODB considered a NoSQL db?
What do you think?
NoSQL DB are normally de-normalized (save copy of object data in place of object), where as OODB is normalized database with object relationships. In OODB, data is stored in object at one place and is linked (relation) to other objects.
Due t above difference of de-normalized and normalized, both have their own pros and cons. NoSQL DBs like Mongo are fast to read but poor in writing / updating data. Due to de-normalized nature of NoSQL DBs, it hard to maintain integrity of data with that, where as OODB as Wakanda are easy to manage and have data integrity. You delete one object and all its relations are deleted automatically.
I tried a lot to figure out some good javascript object oriented DB, but as of now could not find any other than www.wakanda.org. In case you know any, kindly share details.
Sorry for very late update. I found some good alternatives to Wakanda ( OODB) and those OrientDB and ArangoDB. Both are good for OLTP apps as we can manage the DB in normalized manner.
NoSQL is a movement, OODB is a technology. Or in other words: NoSQL is a group of people, an OODB is a piece of code.
There's no strict definition of "NoSQL", so the differences are largely semantic. Generally an Object Oriented Database is considered a subset (a kind of) NoSQL Database. However, in general an OO DB will still have ACID-like locking to keep consistency, while NoSQL will generally have some kind of "eventually consistent" or partial locking semantics. A NoSQL's schema may be object-based or may be key-value based (or something else), making it a more general term.
| common-pile/stackexchange_filtered |
How to differentiate $\left(x^2 + \frac{1}{x^2}\right)^5$
How can I differentiate this expression
$$\left(x^2 + \frac{1}{x^2}\right)^5$$
I will appreciate any help.
There are many ways to differentiate the given expression. What we are looking for is your effort. If you are stuck somewhere, we can help.
How about chain rule?
Using calculus differentiation
You can try to apply the chain rule. You can find it in almost every textbook.
$5 = 2 \times \frac{5}{2}$ so you can seperate the equation expression: $$\bigg(x^2 + \frac{1}{x^2}\bigg)^5 \to \bigg(x^2 + \frac{1}{x^2}\bigg)^{2 \times 2\frac{1}{2} = \bigg(x^2 + \frac{1}{x^2}\bigg)^4 \times \sqrt {x^2 + \frac{1}{x^2}}$$
$$\bigg(x^2 + \frac{1}{x^2}\bigg)^5 \to \bigg(x^2 + \frac{1}{x^2}\bigg)^{2 \times 2\frac{1}{2}} = \bigg(x^2 + \frac{1}{x^2}\bigg)^4 \times \sqrt {x^2 + \frac{1}{x^2}}
???? What ???? bruh
@GeorgeN.Missailidis You need another set of $$ after the math text.
Chain rule:
$$\frac{d}{dx}f(g(x))=f'(g(x))g'(x)$$
use $g(x)=x^2+\frac{1}{x^2}$ and $f(x)=x^5$.
Power rule:
$$\frac{d}{dx}x^n=nx^{n-1}\qquad\text{where $n\in\Bbb Z/\{0\}$}$$
note, $\frac{1}{x^2}=x^{-2}$.
Start with the Chain Rule:$\frac{d}{dx}f(g(x))=f'(g(x))g'(x)$
where $f(x)=x^5$ and $g(x)=x^2+\frac{1}{x^2}$. $$\\$$
For $f'(g(x))$ we get:
$$f'(x)= 5(x^2+\frac{1}{x^2})^4.$$
For $g'(x)$ we can separate the expression:
$$\frac{d}{dx} (x^2) + \frac{d}{dx} (\frac{1}{x^2})$$
$\frac{d}{dx} (x^2) = 2x$ and $\frac{d}{dx} (\frac{1}{x^2}) = \frac{-2}{x^3}$.
So, For $g'(x)$ we get:
$$2x-\frac{2}{x^3}.$$
Thus, we get $f'(g(x))g'(x)$ as:
$$(5(x^2+\frac{1}{x^2})^4)(2x-\frac{2}{x^3}).$$
| common-pile/stackexchange_filtered |
OrientDB import from CSV, nullValue property
I'm trying to import a fake CSV file into OrientDB Server 2.1.2.
The ETL tool looks amazing, allowing people to input many options, however it seems to me that the csv transformer (when I tried to use the CSV extractor I got a Extractor 'csv' not found error) does not interpret correctly the "nullValue" option.
I used the following JSON to try to load a simple file and, when using "NULL" as null value both in the data and in the JSON I could import the file correctly, while when using "?" I couldn't.
`
{
"source": { "file": {"path": "Z:/test.tsv"}},
"extractor": { "row": {}},
"transformers": [
{"csv": {
"separator": " ",
"nullValue": "?",
"columnsOnFirstLine": true,
"columns": [
"a:STRING",
"b:STRING",
"c:String",
"n:Integer"
],
"dateFormat": "dd.mm.yyyy"
}
},
{"vertex": {"class": "Test", "skipDuplicates": true}}
],
"loader": {
"orientdb": {
"dbURL": "plocal:C:/Users/taatoal1/tmp/orientdb/databases/test",
"dbType": "graph",
"classes": [
{"name": "Test"}
]
}
}
}
`
Here is the data:
a b c 1
a0 b0 c0 2
a1 b1 c1 ?
Am I doing something wrong?
my suggestion is to try with (just released) latest version, 2.1.4:Orient Download
In 2.1.4 we add the support for the CSV extractor which internally uses commons-csv from Apache.
I've tried it: the CSV extractor is present but the problem with the "?" is still there, and disappears when I use "NULL" both in the data and in the ETL configuration. Here is part of the output: OrientDB etl v.2.1.4 (build @BUILD@) www.orientdb.com BEGIN ETL PROCESSOR [file] INFO Reading from file Z:/projects/employees2graph/final_data/orientdb/test.tsv with encoding UTF-8 {a:a,b:b,c:c,n:1} {a:a0,b:b0,c:c0,n:2} Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
Could you please fill an issue request: https://github.com/orientechnologies/orientdb-etl/issues
Hi, we just promoted ETL to be part of core modules. Your issues is moved too: https://github.com/orientechnologies/orientdb/issues/5154. You can wait the next hotfix release (2.1.5) or build the etl jar from source. NOTE: sources are now under the main orientDB repo https://github.com/orientechnologies/orientdb/
| common-pile/stackexchange_filtered |
AttributeError at /profile/chandan 'tuple' object has no attribute 'another_user'
I am trying to get follower system to work but it just wont work
class Followers(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
another_user = models.ManyToManyField(User, related_name='another_user')
def __str__(self):
return self.user.name
def profile(request, user_name):
user_obj = User.objects.get(username=user_name)
session_user, create = User.objects.get(username=user_name)
session_following, create = Followers.objects.get_or_create(user=session_user)
following = Followers.objects.get_or_create(user=session_user.id)
check_user_followers = Followers.objects.filter(another_user=user_obj)
is_followed = False
if session_following.another_user.filter(username=user_name).exists() or following.another_user.filter(username=user_name).exists():
is_followed=True
else:
is_followed=False
param = {'user_obj': user_obj,'followers':check_user_followers, 'following': following,'is_followed':is_followed}
if 'user' in request.session:
return render(request, 'users/profile2.html', param)
else:
return redirect('index')
I am getting the error:
AttributeError at /profile/chandan
'tuple' object has no attribute 'another_user'
get_or_create(…) [Django-doc] returns a 2-tuple with as first item the object, and as second item a boolean that indicates if the object was created (True), or already in the database.
You can make use of iterable unpacking to set the boolean to a "throwaway" variable:
# ↓ throw away the second item of the 2-tuple
session_following, __ = Followers.objects.get_or_create(user=session_user)
following, __ = Followers.objects.get_or_create(user=session_user)
what is that underscore for?
@sly_Chandan: it is just a variable that we use to unpack the tuple and assign the first item to the session_following, and the second to __, __ is thus here an ad hoc variable we need to unpack the 2-tuple.
cannot unpack non-iterable User object
@sly_Chandan: you should only do this for .get_or_create, not for .get(...).
I am getting the tuple error 'tuple' object has no attribute 'another_user'
@sly_Chandan: but your (updated) question, contains two mistakes: it does not unpack Followers.objects.get_or_create(user=session_user) and it unpacks session_user, create = User.objects.get(username=user_name), as said, in case it is a .get(..) you do not unpack, and for a .get_or_create you do (unless you are interested if the item is created).
| common-pile/stackexchange_filtered |
Constraints not working when using block syntax in Rails
I tried to add constraints to a group of scoped routes like so:
constraints locale: 'de' do
scope 'magazin' do
get '', to: 'magazine#index', as: 'magazine'
# more routes
end
end
It doesn't make use of the restriction.
Whereas putting the restriction to a single route works as expected.
get '', to: 'magazine#index', as: 'magazine', constraints: { locale: 'de' }
I tried to use the constraints block in different positions, inside and outside the scope block. Without any change in the result.
The Rails Guide for Routing has this example which I pretty much copied:
namespace :admin do
constraints subdomain: 'admin' do
resources :photos
end
end
Any ideas what's wrong with the code?
Without having the whole routes.rb file it is hard to say why it doesn't work as expected.
Is it possible you have some kind of scope defined for locale??
Imagine sth like
scope '/:locale', locale: /de|en/ do
# lots of routes so you are not aware of the scope
constraints locale: "de" do
scope 'magazin' do
get '', to: 'magazine#index', as: 'magazine'
end
end
end
With this your are actually setting a constraint to locale to be either de or en. The constraint from the scope has precedence over the constraints block.
While this is not clear from the rails guide I found a merge request that proves my argumentation.
| common-pile/stackexchange_filtered |
Manual SIMD vectorialization in Fortran
The question is simple but I still cannot find an answer:
How can I use SIMD Intrinsics in a Fortran code?
I don' mean to use use !$omp directives, and in this example post from Intel. Always from the same source, I have that Fortran does not allow SIMD calls at least with Intel's Fortran compiler, but that post is from 2006, quite old information.
What I mean is to explicitly call SIMD functions just like I do in C and C++. For instance given:
__m128i a;
a = _mm_lddqu_si128 ((__m128i*)(ptr)); // with ptr defined previously
how can one do the same in Fortran?
Be aware that I know I can write a wrapper in C and call it from Fortran, I will do this if there is no way of using just Fortran.
Hmm, I don't know of any way to do this. But may I ask why you want to explicitly call those routines and don't depend on the compiler to choose the best fitting one?
@PVitt sometimes I'd like to try different operations, and sometimes the compiler gives up on vectorizing, while I know it is possible.
That post is from 2006 and still up-to-date.
FYI, _mm_lddqu_si128 is obsolete. Use _mm_loadu_si128 in new code. (The lddqu instruction was faster on Pentium 4, but on everything else I think it just decodes the same as movqdu.)
The assembly language has sort of conceptual merged into C with the roll your own SIMD. The optimiser, OMP and !DIR (and SImD declarations) give the majority of speed. If one really has a hot spot, then Asembly is another viable option.
| common-pile/stackexchange_filtered |
Getting MemoryError from DataFrame.sortlevel in pandas
I'm trying to run sortlevel(0,0) on a DataFrame with a MultiIndex (3 levels) and a size of about 900'000x4.
>>>data.as_matrix().shape
(899262, 4)
>>>data.sortlevel(0,0) #<--- throws MemoryError almost instantaneous
I'm running Windows Vista (not willingly) and as I understand it a process can only allocate about 2GB of RAM, but I can't see how the .sortlevel can use that amount of RAM really? What algorithm is used for the sorting? Is there any walkarounds to sort it in the same way?
Edit Did only test it in ipython by old habit.
Looks like an issue. Is data a slice from a bigger set of data? What do you get if you do data.reset_index().sort()?
No it shouldn't be a slice. data.reset_index().sort('slot') seems to work.
Could you post an issue on Github https://github.com/pydata/pandas/issues? Include os, pandas version and code to reproduce issue.
I'm not able to reproduce it for some reason, a generated dataframe which looks essentially the same works without hassle.
Now I get MemoryError just before when appending 4 dataframes, I think I'll have to look into this closer.
It seems to be an issue with using run filename.py in ipython, it for some reason used alot more RAM then the ordinary python from the command prompt.
There are some places where pandas is not as careful as it could be about memory usage when it comes to MultiIndex-- if you do find a case that reproduces the issue please do post it on the issue tracker.
I experienced the same MemoryError problem sorting large DataFrames when the module was run from IPython.
If you have a 64 bit processor, operating system and more than 2GB of RAM another solution is to run 64 bit Python, you can get a prepackaged 64 bit version of Python like Anaconda Community Edition or get the unofficial 64 binaries
| common-pile/stackexchange_filtered |
Collaborative graph exploration algorithm
Given a minimum spanning tree in an unweighted graph of (10 .. 500) vertices and (vertice_count .. 1000) edges. Each vertex can have
up to 6 edges.
Given K agents/bots/processes/etc.., all starting from the root of the spanning tree.
What would be the best way to distribute the "work" to explore the graph (eg. visit all the vertices) in as little time as possible?
Any ideas/strategies/algorithms that can allocate the exploration to the agents and deal with the ones that have reached a leaf but might help contribute to the exploration later?
Let's see an example. Here's a graph, the orange node is the starting point, the grey nodes are the leaves and the number inside the nodes are the number of paths going through that node to one of the leaves.
Obviously, if K=8, then each agent is affected one "path" (or leaf) and once everyone has done their job, they will have explored the whole graph is as little time as possible.
Now my problem is how to organize the exploration when K<8? How to best re-affect the free agents?
Wow! Another edit, with a nice example graph: it's difficult to keep the pace. I edited my answer. But in future, better avoid to edit your question in a way it makes existing answers completely obsolete; ask additional questions instead ;-)
Sorry about that. It turns out I'm bad at asking "good" questions...
Initial answer to the initial question
Important remark: the question was significantly edited. The original question only mentioned the need to explore all the nodes of the graph without mentioning MST. Despite it is now obsolete, I leave the first paragraph, because it linked to parallel algorithms solving the problem.
Your question is very broad. First let's give a name to your problem aiming at exploring all the edges: you want to build a minimum spanning tree of your graph. And when you say collaboratively, I undestand with concurrent processes. For this there are knwon parallel algorithms that are proven to work.
General approach when parallelizing graph exploration
More generally, you may apply the following advices for parallelizing graph exploration and traversal problems:
Many graph algorithms use a queue or a stack, to store partial paths to be extended further. Some version of DFS hide the stack in the call stack.
If there is a queue based version of the algorithm use it: Without queue, it's more difficult to share work, and you need to find other ways to apply the following tricks.
The trick for easy parallelization is to distribute queued elements for being processed by available processing nodes. So instead of extending the explored path one edge at a time, you'd extend N nodes in the same time in parrallel. Using queues to distribute work is the easiest way to parllelize work: one process manages the queue, and N worker-processes dequeue the elements, process them and enqueue the results.
Most graph traversal algorithms are inherently sequential. Parallelizing them means that you might aggressively process elements in the queue that would never be processed in the sequential version. So there is a tradeoff to find between adding more workers (with the risk of doing unnecessary work) and having less workers (but going back to sequential like performance).
So be prepared to make measurements and validate your approach.
A long time ago, I had for example to parallelize A* on a limited set of geographical data. Measurements showed that adding up to 4 worker-nodes increased performance, but beyond 4, the performance decreased again, just because of the additional communication overhead and the unnecessary extension of unpromising partial paths.
Edit: considering that all the edges are same-weighted, the risk of processing suboptimal nodes in the queue are significantly reduced if you use DFS. So if you can modify BFS in a way to make sure that it ends the search if and only if all the nodes were explored, go for it;
Example based on your new graph example.
Your visual reasoning about branches of the MST is not valid for solving your problem:
First, building your MST already requires you to explore every node
Second, graph exploration algorithms have to unfold node by node and edge by edge. When you start at the orange node, you don't know how many branches there will be in the MST nor which part of the graph to assign to which worker.
With the approach proposed above, you'd enqueue the first node (orange 8). A free worker dequeues it, prolonges the path and enqueue the single result (O8->8). As we are in a "corridor", the same must happen again (O8->8->8) before we have more choices and more parallelism. Then a free worker-process dequeues the only path in the queue, extends it: we have 2 alternatives that will be enqueued: O8->8->8->6 and 08->8->8->2. Now a first worker will take the first path in the queue (...->6), another free worker will take the second path (...->2), and both workers extend in parallel their nodes. If both workers have the same speed, we now have 5 paths in the queue and up to 5 workers busy, and so on.
Of course, you'll notice that O8->8->8->6->bottom2 and O8->8->8->2 arrive at the same point. In your exploration you must avoid such duplicates. This can be done by marking visited nodes to avoid double visit. This cannot be done safely in the workers because of synchronisation issues. So you may implement this when you enqueue the results and discard any path that arrives at an already visited node.
With this approach, everytime there's a branch, you'll use more pralelism until you reach the maximum number of workers. However in your simple graph, I think that you'll never have more than 5 workers active at the same time, that's 6 parallel processes if you add the queue manager.
The worst case is when you graph is a long chain of nodes, each one linked only with a successor. It will run with 2 active processes only: worse than sequential because of the overhead of work distribution.
Other variants
There are other parallelization of task possible, without adding workers, for example parrallelizing the sorting of the queue, the filtering of doubled targets, etc...
If your graph topology is a bottleneck for parallization, you may introduce some randomness. Take K random nodes and start exploration from there; when enqueuing in the global queue, any path with nodes in common would be merged. As soon as one of the processor gets iddle, pick a new random unvisited node and add it to the queue.
This variant adds a small inefficiency: some nodes might get visited twice, once from each connection. It's those that lead to a path merger. But it keeps all the processors as busy as possible. In your example, most of the time 8 processors will work instead of a maximum of 5 before.
And this is why in my original answer, I adviced to carefully measure performance, to find the most suitable parallelization strategy (which might also depend on the graph topology).
So I've been reading a lot, and it seems like in an unweighted (or "sameweighted") undirect graph like I have, doing a BFS or a DFS will give you the MST (plus, any spanning tree is a minimum spanning tree) - https://cs.stackexchange.com/questions/23179/if-all-edges-are-of-equal-weight-can-one-use-bfs-to-obtain-a-minimal-spanning-t
I've re-worded my question to put an emphasis on my problem: which is how to best organize the exploration of the spanning tree.
@ZogStriP ok, so sameweighted creates less risks of distortions. Nevertheless, it doesn't fundamentally change my answer: first look at the link about paralellization of MST: there are already proven answers there. Then DFS or BFS algorithms stop when you've found what you search. THis doesn't guarantee that all edges were visited. THat's difference between theory and practice: you'd first need to adapt DFS/BFS to find an ending condition. MST frees you from that. If you prefert to adapt DFS, go for DFS. I'll edit my answer to explain.
Thanks a lot @Christophe for all your time and hard work answering my poorly asked question. You definitely deserve the bounty
However, I've dug into the research papers and found that what I want to do is not "easily" solvable...
What I want to do is exactly this - Fast collaborative graph exploration
We study the following scenario of online graph exploration. A team of k agents is initially located at a distinguished vertex r of an undirected graph. We ask how many time steps are required to complete exploration, i.e., to make sure that every vertex has been visited by some agent.
Or similarly explained in Graph Explorations with Mobile Agents
Collective exploration requires a team of k agents that start from the same location, to explore together all the nodes of the graph, such that each node is visited by at least one of the agents. The agents are assumed to have distinct identifiers such that each agent can be assigned a distinct path to explore. Assuming that
all agents move with the same speed (i.e. they are synchronized), the main objective is to minimize the time needed for exploration.
When the graph is known in advance, it is possible to devise a strategy to divide the task among the agents such that each agent travels on a distinct tour and they together span the nodes of the graph. We call this an offline strategy for exploration; finding the optimal offline strategy that minimizes the maximum tour length of any agent for a given graph G and team size k is known to be an NP-hard problem even for trees.
And more specifically this - Collective tree exploration
In the offline model, when the graph is known in advance, the problem of establishing an optimal sequence of moves for k agents in a [graph] is shown to be NP-hard.
So, as it turns out, this is a well-researched problem and is NP-hard. I guess I'm gonna have to find heuristics then.
| common-pile/stackexchange_filtered |
Post Request works in swagger but not in JavaScript or jQuery
So, I am trying to call a rest API using ajax post. Response contains Status code and Response body which in JSON. When I test this in swagger it works.
When I try this in either JavaScript or JQuery,
const values = {
clientId: '9d9d865a-96c6-41ff-9842-89101c8ccc7a'
};
$.ajax({
url: "https://-----.-----------.ca/Asset/EstimatedWaitTime",
type: "POST",
data: values,
contentType: "application/json",
dataType: "text",
beforeSend: function(xhr) {
xhr.setRequestHeader('access-control-allow-headers', 'Origin, X-Requested-With, Content-Type, Accept');
success: function(response) {},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
I get the following error:
Why is this not working, or what am I doing wrong?
Thank you guys!
It's a Cross-Origin Resource Sharing (CORS) error
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Best way is your own API with access to external web resource.
JS (AJAX request) -> Your API -> External web resource -> Your API -> Your Web page (js response)
| common-pile/stackexchange_filtered |
Want to center a marketing div and put a box around it - Using Bootstrap
I am using bootstrap 3 and I am trying to center marketing div and put a box around it. I would like to keep the marketing div small and in the center.
The .box is just a simple box with a border.
Here is my code:
<div class="container">
<div class="col-md-offset-2">
<div class="row box">
<div class="marketing">
<div class="col-lg-3">
<img class="img-responsive" src="http://placehold.it/100x100" alt="placeholder" class="img-rounded">
<h2>Lorem Ipsum</h2>
<p class="marketing-desc">Lorem ipsum dolor sit amet</p>
</div>
<div class="col-lg-3">
<img class="img-responsive" src="http://placehold.it/100x100" alt="placeholder" class="img-rounded">
<h2>Lorem Ipsum</h2>
<p class="marketing-desc">Lorem ipsum dolor sit amet, quidam debitis honestatis ut eam. Dicant perpetua pro an, id mei iusto ridens. Cibo salutatus has ex..</p>
</div>
<div class="col-lg-3">
<img class="img-responsive" src="http://placehold.it/100x100" alt="placeholder" class="img-rounded">
<h2>Lorem Ipsum</h2>
<p class="marketing-desc">Lorem ipsum dolor sit amet, quidam debitis honestatis ut eam.</p>
</div>
</div>
</div>
</div>
</div>
It's extending the box too far to the right and I can't figure out why it's not even on both sides.
Link1
By far to right ...do you mean left :P..This is what I see: http://jsfiddle.net/rUFkT/
If you'll create a fiddle link with css..chances are people will respond quickly and you'll get an answer.
Looks like your columns don't quite add up. Instead, you can nest another row of 12 columns inside of an existing column. Try:
<div class="container">
<div class="row">
<div class="col-lg-offset-2 col-lg-8">
<div class="row box">
<div class="marketing">
<div class="col-lg-4">
<img class="img-responsive" src="http://placehold.it/100x100" alt="placeholder" class="img-rounded">
<h2>Lorem Ipsum</h2>
<p class="marketing-desc">Lorem ipsum dolor sit amet</p>
</div>
<div class="col-lg-4">
<img class="img-responsive" src="http://placehold.it/100x100" alt="placeholder" class="img-rounded">
<h2>Lorem Ipsum</h2>
<p class="marketing-desc">Lorem ipsum dolor sit amet, quidam debitis honestatis ut eam. Dicant perpetua pro an, id mei iusto ridens. Cibo salutatus has ex..</p>
</div>
<div class="col-lg-4">
<img class="img-responsive" src="http://placehold.it/100x100" alt="placeholder" class="img-rounded">
<h2>Lorem Ipsum</h2>
<p class="marketing-desc">Lorem ipsum dolor sit amet, quidam debitis honestatis ut eam.</p>
</div>
</div>
</div>
</div>
</div>
</div>
edit: jsfiddle (columns are only set for large so make sure the window is large enough)
| common-pile/stackexchange_filtered |
Unable to query or get any response from BscScan contract
The following code:
const { JsonRpcProvider } = require("@ethersproject/providers")
const { Contract } = require("ethers")
const { Wallet } = require("@ethersproject/wallet");
const abi = require('./abi.json');
const GLOBAL_CONFIG = {
PPV2_ADDRESS: "0x18B2A687610328590Bc8F2e5fEdDe3b582A49cdA",
PRIVATE_KEY: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
BSC_RPC: "https://bsc-mainnet.public.blastapi.io"
};
const signer = new Wallet(GLOBAL_CONFIG.PRIVATE_KEY, new JsonRpcProvider(GLOBAL_CONFIG.BSC_RPC));
const contract = new Contract(GLOBAL_CONFIG.PPV2_ADDRESS, abi, signer)
const predictionContract = contract.connect(
signer
)
predictionContract.on("StartRound", async (epoch) => {
console.log("\nStarted Epoch", epoch.toString())
});
It has been working perfectly for months. However, last night it stopped. No new builds/code changes on my end. I've been trying everything I can think of but nothing. The signer seems to bring back my wallet details ok. I can also see all the functions on the predictionContract but can't get it to return the current Epoch value etc. As you've probably already noticed, I'm not much of a coder, so any help in understanding this would be amazing.
After some more time thinking, I noticed that the contract seemed pretty busy and decided to try a different RPC (I'd already tried 3 before). Seems to be working now, but not exactly scientific. Is there any way to monitor the time requests take and where the lag is? I had a design idea to test a multiple of RPCs during initiation and then use the fastest / most reliable, but no idea where to start with that!
| common-pile/stackexchange_filtered |
Android OpenGL ES shader compiler support
The OpenGL ES 2.0 Specs state that "[s]hader compiler support is optional" (see "Notes" here).
Are there any Android devices that do not support shader compilation? If so, is there some shader compiler that I can include with my app to generate a binary instead? Or is the format of the binary also standardized so that I can precompile my shaders before hand and ship the binary with my app if needed? Or is there a requirement I can put into my app so that it isn't offered to devices without compiler support?
I haven't found a strict definition saying that shader compilation must be supported in Android. I have never seen a phone/tablet that does not support it. I believe making it optional in ES 2.0 was intended more for very minimal devices. Shader compilation is used in some of the public Android system/framework code. But at least theoretically, vendors could change that code. A lot of apps would not work without shader compilation, so this looks more like an academic question for typical phone/tablet types of devices.
Since Android 4.0 (actually 3.0 but Google/Android never released the code as distinct product) OpenGL ES 2.0 has always been part of the spec required to get Android Market/Google Play. See: Android 4.0 Compatibility Definition Document and Android Compatibility Definition Document Archive for the other versions.
Since OpenGL ES 2.0 uses shaders written in OpenGL ES Shader Language I believe your reference to 'optional' for the Shader Compiler refers to the fact the driver vendor can provide a different interface (binary) to load shaders in. Given that there is no specified binary format, everyone as far as I can tell has got GLSL text fed into the graphics driver to build the shaders at runtime. And don't forget there are multiple GPU vendors/chipsets so specific binaries for each doesn't look too attractive from a developer point of view at least in the multi CPU architecture (ARM,x86,MIPS) multi GPU (Qualcomm,PowerVR,nVidia) world of Android. Vendors can still interpret the text differently but at least it would be within the proscribed Khronos spec.
Since text is the what is being sent over to the GPU driver, well performance could be better since it has to do the translation, mapping, scheduling, etc. which leads to the recent announcement for Vulkan see: Android Developer Blog Vulkan Announcement. If you look at the specs, it describes an intermediate binary format but is probably at least a year away from a consumer available implementation.
Unless your intention is to support Gingerbread (2.3) and below - you should be able to rely upon OpenGL ES 2.0 availability.
I am indeed trying to support Gingerbread and below as well, but since I have an OpenGL ES 1.0 version of my code running already, that issue is basically taken care of. I'm really only worried about the case where OpenGL ES 2.0 is available, but without shader compiler support.
So what you're saying is that even if I can't find an official statement that all Android devices support a shader compiler, it's probably still a safe assumption, since anything else wouldn't make any sense. I'd buy that. So, probably the reason why this comment is in the official spec is for some fringe embedded cases or so, but it doesn't really apply in the real world... Did I get that right? :)
I'll wait a bit to accept your answer to see if anyone can still find an official reference, but if nothing comes up, you get the √, and definitely a +1 already. :)
So you could have the two paths - if on Gingerbread, 1.0 path, else 2.0 path (and to handle the big screens). Agree on your assessment of the spec.
| common-pile/stackexchange_filtered |
python generating netaddr.core.NotRegisteredError invalid syntax exception
I am trying to get a piece of software called Probemon
working and have come up with an error when I try to run it.
root@root:~/probemon/src$ python3 ./probemon.py -h
File "./probemon.py", line 69
except netaddr.core.NotRegisteredError, e:
^
SyntaxError: invalid syntax
I am not sure what it is trying to indicate here...
Prior to this I have run these commands:
git clone https://github.com/drkjam/netaddr
cd netaddr
sudo python setup.py install
cd
git clone https://github.com/secdev/scapy.git
cd scapy
sudo python setup.py install
to ensure netaddr and scapy dependencies are installed.
I have python 2 and python3 installed as this was default on the raspberrypi distro and I note from the probemon webpage, you
This is still using python2 ️. This is easily converted to
python3 script with 2to3 though
but I'm not sure where this needs to change. I have found the first line of probemon.py as
#!/usr/bin/python2
and changed it to
#!/usr/bin/python3
although I am not sure whether this is what this means.
Does anyone know what is going on here?
Thanks
Edit to show response to running with python2:
root@root:~/probemon/src$ python2 ./probemon.py -h
Traceback (most recent call last):
File "./probemon.py", line 11, in <module>
import netaddr
File "/usr/local/lib/python2.7/dist-packages/netaddr-0.8.0-py2.7.egg/netaddr/__init__.py", line 18, in <module>
from netaddr.core import (AddrConversionError, AddrFormatError,
File "/usr/local/lib/python2.7/dist-packages/netaddr-0.8.0-py2.7.egg/netaddr/core.py", line 11, in <module>
from netaddr.compat import _callable, _iter_dict_keys
File "/usr/local/lib/python2.7/dist-packages/netaddr-0.8.0-py2.7.egg/netaddr/compat.py", line 93, in <module>
import importlib_resources as _importlib_resources
File "/usr/local/lib/python2.7/dist-packages/importlib_resources-3.0.0-py2.7.egg/importlib_resources/__init__.py", line 5, in <module>
from ._common import (
File "/usr/local/lib/python2.7/dist-packages/importlib_resources-3.0.0-py2.7.egg/importlib_resources/_common.py", line 9, in <module>
from ._compat import (
File "/usr/local/lib/python2.7/dist-packages/importlib_resources-3.0.0-py2.7.egg/importlib_resources/_compat.py", line 42, in <module>
from zipp import Path as ZipPath # type: ignore
File "/usr/local/lib/python2.7/dist-packages/zipp-3.1.0-py2.7.egg/zipp.py", line 217
def open(self, mode='r', *args, pwd=None, **kwargs):
^
SyntaxError: invalid syntax
try to run it with python2 ./probemon.py instead. This script is to be ran with python2 (converting it in python3 is "easy" but still requires you to run a script according to the author's message).
The script you have is compatible only with python2.
You can choose one of the following solutions:
run it using python2 ./probemon.py instead (if python2 is installed on your machine)
convert it to python3 using an automatic tool like 2to3
thanks for this. I have tried and edited my original post to reflect the additional errors I get when I try to run with python2.
@cosmarchy It's not the same problem, you should create another question for this, it seems the program you are using is not written in valid python2, where you cannot describe a function like that, which seems weird cause it seems to be an external library (maybe library is faulty, or a python3 version is installed in your python2 files for some reason)
| common-pile/stackexchange_filtered |
Angular. How to hide data in the title attribute of the image if the object value is null?
I understand ng-show/ng-hide can be used but this case is a little different. This is my script below. Basically what I'm trying to do is hide the word "PEAK" if 'info.peak' value is empty in the title tag. DO I need to create two versions of this image tag? One with and without 'peak'? If show How would I do that also?
<img
class="icon lazyloaded"
data-ng-src="{{ info.image }}"
alt="{{ info.title }}"
title="Last Week: {{ info.lastweek}} Move: {{ info.move }} Peak: {{ info.peak }}"
width="100"
height="100">
You can do this with the following:
{{ info.peak ? 'Peak: ' + info.peak : '' }}
in place of where you have Peak: {{ info.peak }}. So if info.peak does not exist/is null, it will simply append an empty string to the end.
You got it! Thanks very much
| common-pile/stackexchange_filtered |
How to query/search name of non-friends of a certain user from database?
I have 2 tables in database: Users and Friend. I want to make a query that searches for users name that are not friends with a certain user using @Query. How should the query look like?
I have created this query for it:
@Query("SELECT u.name FROM Users u WHERE u.user_id NOT IN
(SELECT f.friend_id FROM Friend f WHERE f.user_id= ?1)
AND u.name LIKE %?2% ", nativeQuery = true)
List<String> searchingNonFriendsByUserId(int userId, String search)
But this doesn't give the right results that I want.
Info/attributes about tables:
Users(user_id PK, name, score)
Friend(id PK, user_id, friend_id)
EXAMPLE FOR CLARIFICATION:
USERS:
(1, "test", 5), (2, "Tim", 10), (5, "Tom", 11), (4, "test2", 13), (6, "Tam", 0)
FRIENDS: (1, 1, 2) , (2, 1, 5) , (3, 1, 4) , (4, 2, 5) , (5, 2, 1)
I want names (specified by the LIKE clause) of the users that are not a friend of "Tim" (user_id = 2) for example. Here Tim is friends with "Tom" and "test". For example I type in the letter "T" between the % of the LIKE clause for user_id = 2, Then I want only "Tam" and "test2" to be queried.
Use NOT EXISTS.
Select the user(s) who are not friends with the given user id by excluding any user who has a row in the Friend table where the given user exists (user_id = ?1) or the other way around.
SELECT u.name
FROM Users u
WHERE NOT EXISTS (SELECT 1 FROM Friend
WHERE user_id = ?1 AND friend_id = u.user_id)
AND u.user_id != ?1
AND u.name LIKE '%?2%'
Shouldn't be user_id here equal to ?1 instead of friend_id ? Also where is the LIKE clause?
Can you please clarify what your query does? Because I don't think it does what I want.
I Updated the question
Ok I don't want to use the friend_id to fetch non-friends. I want to give the user_id into the query and fetch friend_id from that and then filter the friends of that user to get non-friends names
Ok so what are the 1's in the query for? Are you only doing it for user_id = 1 here?
Ok I tried your latest query and it works well! Thanks very much for the help and effort!
Can you try this out ?
select u.name from Users u where not exists(
Select User_id from friend where user_id = ?1)
| common-pile/stackexchange_filtered |
How to add placeholder for search field in admin.py
How can I add placeholder in django for a search field I am using in admin.py with Django3.1 as:
class MyAdmin(admin.ModelAdmin):
list_display = ['community']
search_fields = ['community']
Is there any way to do something like this?
class MyAdmin(admin.ModelAdmin):
search_fields = ['community']
search_input_placeholder = 'Please input community id'
Maybe this answer is useful?
@RolvApneseth That is one solution, but seems not pythonic.
With Django 4, you can now add a search_help_text.
More details in the doc here.
| common-pile/stackexchange_filtered |
D-link DI-524 a hub connecting to a wireless router?
I live in an apartment where I am allowed to use the wireless router's connection for the internet but the speed is sometimes very shaky and weak. Is is possible to use a D-Link DI-524 wireless router that I have as a hub to connect to the wireless connection I am already using in order to increase the speed and stability of my internet connection?
It sounds like you're looking for a "wireless client mode" feature that will let your router connect to the other wireless network as though it's just a plain wireless adapter. A lot of routers don't include this feature in their stock firmware, which is a shame. It's hard to say just from looking at the specs of that router, and the little bit of Googling doesn't reveal much. I would need to look in the firmware's web interface to be positive, but my guess is, no.
You didn't ask this, but as far as other devices that will allow you to do this, I personally own the Asus RT-N12/B which has an awesome switch on the back to let you change modes between router, repeater, and access point. I use it as a repeater with my main router to provide stronger signal on another level of our house and it also lets you plug wired devices in. All you do to set it up is put in the SSID and PSK of the main wireless network.
I know other devices have this feature, that's just the one I use and know, and tends to be a pretty good bargain.
Thanks a lot for your reply and you are right in saying what I am am looking for, I am definitely going to look into getting the Asus RT-N12/B as it sounds like this will solve my situation quite easily instead of messing around with the D-Link I have ... Cheers and happy holidays.
Your guess is right :) I have this router and it has no client or bridged mode.
Can't do it.
I have the DI-524. It offers no client bridge mode, and it's incompatible with DD-WRT, so you're not going to get the feature by changing your firmware.
| common-pile/stackexchange_filtered |
If $X:\Omega\to\Omega'$ and $f:\Omega'\to\Omega''$ are measurable and $f$ is injective, then $\sigma(X)=\sigma(f\circ X)$
Let
$(\Omega,\mathcal{A})$, $(\Omega',\mathcal{A}')$ and $(\Omega'',\mathcal{A}'')$ be measurable spaces
$X:\Omega\to\Omega'$ be $\mathcal{A}$-$\mathcal{A}'$-measurable
$f:\Omega'\to\Omega''$ be $\mathcal{A}'$-$\mathcal{A}''$-measurable and injective
I want to show that $$\sigma(X)=\sigma(f\circ X)$$
We've got $$\sigma(X)\stackrel{\text{def}}{=}\left\{X^{-1}(A):A\in\mathcal{A}'\right\}\stackrel{(1)}{=}\left\{X^{-1}(A):A\in\left.\mathcal{A}'\right|_{X(\Omega)}\right\}$$
where $(1)$ should hold since each $A\in\mathcal{A}'$ can be written in the form $$A=B\cup C\;\;\;\text{with }B\in\left.\mathcal{A}'\right|_{X(\Omega)},C\in\mathcal{A}'\setminus\left.\mathcal{A}'\right|_{X(\Omega)}$$ and $$X^{-1}(A)=X^{-1}(B\cup C)=X^{-1}(B)\cup\underbrace{X^{-1}(C)}_{=\emptyset}$$ I've got problems to proceed. How exactly do we need to use the injectivity of $f$?
The injectivity of $f$ implies that $A=f^{-1}(f(A))$ for each $A\in\mathcal A'$ so that the sets $X^{-1}(A)$, i.e. elements of $\sigma(X)$ can be written as $X^{-1}(f^{-1}(f(A)))=(f\circ X)^{-1}(f(A))$ wich are elements of $\sigma(f\circ X)$ if $f(A)\in\mathcal A''$
However, $A\in\mathcal A'$ combined with measurability of $f$ does not ensure that $f(A)\in\mathcal A''$ (see my comment).
So my answer is not complete.
Edit (to complete my answer)
Under these conditions statement $\sigma(X)=\sigma(f\circ X)$ is not true in general.
Counterexample:
Let $\Omega=\Omega'=\Omega''$ and $\mathcal A=\mathcal A'$. Let $f$ and $X$ both be the identity on $\Omega$. Let $\mathcal A'':=\{\varnothing,\Omega\}$.
Then $f$ and $X$ are both measurable, and this with $\sigma(X)=\mathcal A$ and $\sigma(f\circ X)=\{\varnothing,\Omega\}$. Also $f$ is bijective (hence injective).
However $\mathcal A$ can be properly finer than $\{\varnothing,\Omega\}$.
What if $f$ would be bijective?
If $\Omega'=\Omega''$ and $\mathcal A''$ is a proper subset of $\mathcal A'$ and $f$ is the (bijective) identity, then it is measurable but we can find a set $A\in\mathcal A'$ with $f(A)=A\notin\mathcal A''$.
| common-pile/stackexchange_filtered |
Autokey-GTK is missing a typing cursor when I use Dark Themes
I hoping that someone here can advise a work-around for this bug I'm experiencing in autokey-gtk.
When I use a dark theme, the phrase editor is missing its typing cursor.
I see no settings to adjust this and would appreciate any advice that would lead to me to being able to use Autokey-gtk with a dark theme, while also having a visible typing cursor.
The issue is that autokey-gtk's phrase-editor is not properly inheriting the dark background prescribed by the GNOME theme. The phrase-editor's background-color remains white no matter what the GNOME theme prescribes.
Conflictingly, the autokey-gtk phrase-editor is indeed properly inheriting the caret-color (typing cursor color) from the GMONE theme. The typing-cursor is not "missing"; it is there, but because its color is the same color as the background-color, it is invisible to the human eye.
Until this theme-inheritance bug is fixed in autokey-gtk, a work-around would be to change the caret-color to a color that remains visible on the dark theme you're using. For example, you could change the caret-color to blue.
* {caret-color: blue; }
adding above line in the .css file of the source file made it blue color
for example to override Yaru-Dark theme
navigate to /usr/share/themes/Yaru-Dark/gtk-3.20/gtk-dark.css and add the below line under the line @import url("resource:///com/ubuntu/themes/Yaru/3.20/gtk-dark.css");
* {caret-color: blue; }
to apply this line * {caret-color: blue; } to all the theme files (globally)
just put this line in the file ~/.config/gtk-3.0/gtk.css
reference: https://askubuntu.com/a/1159560/739431
I added your work-around to the bug report (comment 7). Thank you!
| common-pile/stackexchange_filtered |
Rails 4 - showing errors for nested associations
I have a belongs_to and has_many association between two models. I have a user creation form that creates the user and in the process, creates an organization and associates the two. I have a validation for the presence of an organization name. If that validation fails, i'd like the Organiation to add the Name cannot be blank error to the same hash of error messages that the User has. Basically, creating one list of error messages.
Here are my models:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable, :timeoutable
belongs_to :organization
validates_presence_of :display_name
end
class Organization < ActiveRecord::Base
has_many :users, dependent: :destroy
accepts_nested_attributes_for :users, :allow_destroy => true
validates_presence_of :name
end
Here's my create action:
def create
@user = User.new(sign_up_params)
if params[:user][:organization][:access_code].blank?
# create new organization
@access_code = "#{SecureRandom.urlsafe_base64(16)}#{Time.now.to_i}"
@organization = Organization.create(name: params[:user][:organization][:name], access_code: @access_code)
@user.organization_id = @organization.id
@user.is_admin = true
else
# try and add someone to an organization
@organization = Organization.find(:all, conditions: ["name = ? AND access_code = ?", params[:user][:organization][:name], params[:user][:organization][:access_code]])
if @organization.empty?
flash.now[:error] = "No organization has been found with that name and access code."
render :new
return
else
@user.organization_id = @organization.first.id
end
end
if @user.save
flash[:success] = "Your account has been successfully created! Check your email for a confirmation link to activate your account."
redirect_to sign_in_path
else
flash.now[:error] = "Something went wrong! Please try again."
render :new
end
end
Here's my view:
<% provide(:title, 'Sign Up') %>
<h1>Create Account</h1>
<%= nested_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= render "shared/error_messages", obj: @user %>
<fieldset>
<legend>Account Information</legend>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: "form-control", autofocus: true %>
</div>
<div class="form-group">
<%= f.label :display_name, "Display Name" %>
<%= f.text_field :display_name, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password %> <% if @validatable %><i>(<%= @minimum_password_length %> characters minimum)</i><% end %>
<%= f.password_field :password, class: "form-control", autocomplete: "off" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: "form-control", autocomplete: "off" %>
</div>
</fieldset>
<%= f.fields_for :organization do |o| %>
<fieldset>
<legend>Organization Information</legend>
<p>
<strong>Creating a New Organization:</strong> Fill out the Organization Name field, but leave the Access Code field blank.<br />
<strong>Joining an Existing Organization:</strong> Fill out both the Organization Name and Access Code field, using the access code that you received from someone at your organization.
</p>
<div class="form-group">
<%= o.label :name, "Organization Name" %>
<%= o.text_field :name, class: "form-control" %>
</div>
<div class="form-group">
<%= o.label :access_code, "Organization Access Code" %>
<%= o.text_field :access_code, class: "form-control" %>
</div>
</fieldset>
<% end %>
<div class="form-actions">
<%= f.submit "Create Account", class: "btn btn-primary" %>
<%= link_to "Cancel", :back %>
</div>
<% end %>
<%= render "users/shared/links" %>
And, here's the error_messages partial:
<% if obj.errors.any? %>
<div id="error_explanation">
<h2>There are <%= pluralize(obj.errors.count, "error") %> errors with this form:</h2>
<ul>
<% obj.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
I get the errors for User displaying like they should, just not for Organization. Could it be something to do with only passing @user to the partial?
It would make sense that you are only getting the error messages for the user object if you are only passing in the user, right? In your controller, instead of saying flash.now[:error] = "...", why don't you just say something like flash.now[:errors] = @user.errors.full_messages + @organization.errors.full_messages?
The flash messages actually are not related to this issue. The problem is with the ActiveModel validations i have setup through the models i believe. I was assuming that passing @user would be ok and the organization errors would come in through @user.organization.
Ok, i figure out my issue. Seems i may have had some things backwards with the model associations, or at least with the accepts_nested_attributes.
Here are my updated models:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable, :timeoutable
belongs_to :organization
accepts_nested_attributes_for :organization
validates_presence_of :display_name
end
class Organization < ActiveRecord::Base
has_many :users, dependent: :destroy
validates_presence_of :name
end
Here is my updated create action in my controller:
def create
@user = User.new(sign_up_params)
if params[:user][:organization_attributes][:access_code].blank?
# create new organization
@access_code = "#{SecureRandom.urlsafe_base64(16)}#{Time.now.to_i}"
@organization = Organization.create(name: params[:user][:organization_attributes][:name], access_code: @access_code)
@user.organization_id = @organization.id
@user.is_admin = true
else
# try and add someone to an organization
@organization = Organization.find(:all, conditions: ["name = ? AND access_code = ?", params[:user][:organization_attributes][:name], params[:user][:organization_attributes][:access_code]])
if @organization.empty?
flash.now[:error] = "No organization has been found with that name and access code."
render :new
return
else
@user.organization_id = @organization.first.id
end
end
if @user.save
flash[:success] = "Your account has been successfully created! Check your email for a confirmation link to activate your account."
redirect_to sign_in_path
else
flash.now[:error] = "Something went wrong! Please try again."
render :new
end
end
Here is my updated view:
<% provide(:title, 'Sign Up') %>
<h1>Create Account</h1>
<%= nested_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= render "shared/error_messages", obj: @user %>
<fieldset>
<legend>Account Information</legend>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: "form-control", autofocus: true %>
</div>
<div class="form-group">
<%= f.label :display_name, "Display Name" %>
<%= f.text_field :display_name, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password %> <% if @validatable %><i>(<%= @minimum_password_length %> characters minimum)</i><% end %>
<%= f.password_field :password, class: "form-control", autocomplete: "off" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: "form-control", autocomplete: "off" %>
</div>
</fieldset>
<% @user.build_organization unless @user.organization %>
<%= f.fields_for :organization do |o| %>
<fieldset>
<legend>Organization Information</legend>
<p>
<strong>Creating a New Organization:</strong> Fill out the Organization Name field, but leave the Access Code field blank.<br />
<strong>Joining an Existing Organization:</strong> Fill out both the Organization Name and Access Code field, using the access code that you received from someone at your organization.
</p>
<div class="form-group">
<%= o.label :name, "Organization Name" %>
<%= o.text_field :name, class: "form-control" %>
</div>
<div class="form-group">
<%= o.label :access_code, "Organization Access Code" %>
<%= o.text_field :access_code, class: "form-control" %>
</div>
</fieldset>
<% end %>
<div class="form-actions">
<%= f.submit "Create Account", class: "btn btn-primary" %>
<%= link_to "Cancel", :back %>
</div>
<% end %>
<%= render "users/shared/links" %>
Here is my updated error_messages partial (just showing for context - the code changed was not really related to issue):
<% if obj.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(obj.errors.count, "error") %> was found with this form:</h2>
<ul>
<% obj.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Now, when i try to save without entering any information, all of the correct errors are displayed. Also, when i enter all the needed user data and leave all of the organization fields blank, the correct organization related validation errors are displayed and the user record is not created. Works like i needed it to now.
| common-pile/stackexchange_filtered |
$\exp(a^2\partial_x^2)f(x) = ?$
I can prove that $\exp(a\partial_x)f(x) = f(x+a)$, but what happens for second derivatives? To be more precise, what is the right-hand side of $\exp(a^2\partial_x^2)f(x)$?
The above operator has an integral representation
$$\exp(a^2\partial_x^2)f(x) = \int\limits_{-\infty}^\infty \text{d}y K(x-y)f(y) \, ,$$
and I think that it must be $K(x-y) \propto \frac{1}{\sqrt{a}}\exp(-|x-y|^2/a^2)$. The reason is that in the limit $a\rightarrow 0$ I want to obtain $K(x-y) = \delta(x-y)$ such that $f(x)$ gets mapped to itself.
My questions:
How can I derive a formula for $K(x-y)$?
Why is the expression $\exp(a\partial_x)f(x) = f(x+a)$ so different when I put a second derivative in the exponent instead of a first derivative?
Let us introduce the function
\begin{align}
u(t, x) = \exp\left(t\alpha^2\partial^2_x \right)f(x)
\end{align}
then we see that $u$ satisfies the Cauchy problem
\begin{align}
\partial_t u - \alpha^2\partial^2_x u =0, \ \ u(0, x) = f(x),
\end{align}
which is just the heat equation. By fundamental PDE, we see that
\begin{align}
u(t, x) = \frac{1}{\sqrt{4\pi \alpha^2t}} \int^\infty_{-\infty} \exp\left(-\frac{(x-y)^2}{4\alpha^2 t}\right) f(y)\ \text{d}y.
\end{align}
Finally, set $t=1$ yields
\begin{align}
\exp\left(\alpha^2\partial^2_x\right)f(x) = \frac{1}{\sqrt{4\pi \alpha^2}}\int^\infty_{-\infty} \exp\left(-\frac{(x-y)^2}{4\alpha^2 }\right) f(y)\ \text{d}y.
\end{align}
Note that $u(t, x)= \exp(t\alpha \partial_x)f(x)$ satisfies a transport equation, i.e.
\begin{align}
\partial_t u-\alpha \partial_x u =0, \ \ u(0, x) = f(x).
\end{align}
Solving the pde yields $u(t, x) = f(x+\alpha t)$. Set $t=1$.
Thanks, that answers my question 1! Any ideas about question 2?
I already did. See last sentence.
What is this transport equation? I am not familiar with this term.
Okay. I updated the post.
| common-pile/stackexchange_filtered |
How could I have prevented this long drawn out game?
Consider the following game. I am black.
[FEN ""]
1. e4 g6 2. d4 d5 3. e5 e6 4. Nf3 b6 5. Nc3 Bb7 6. Bg5 Be7 7. h4 Nc6 8. Bd3 Qd7 9. Qd2 O-O-O 10. Nb5 f6 11. exf6 Bxf6 12. a4 h6 13. Bxf6 Nxf6 14. Bxg6 a6 15. Nc3 h5 16. Qg5 Rdf8 17. Ne5 Nxe5 18. Qxe5 Ng4 19. Qg5 Rxf2 20. Bxh5 Rxg2 21. Bxg4 Rxc2 22. Qe5 Rg8 23. Bxe6 Re8 24. Bxd7+ Kxd7 25. Qxe8+ Kxe8 26. Nxd5 Bxd5 27. b4 Bxh1 28. h5 Rh2 29. Rd1 Rxh5 30. Kd2 Bc6 31. a5 bxa5 32. Re1+ Kd7 33. bxa5 Rxa5 34. Rg1 Be4 35. Rg7+ Kd6 36. Kc3 Rb5 37. Rg4 Bd5 38. Rg6+ Be6 39. Kd3 Kd5 40. Rg5+ Kd6 41. Rg6 c6 42. Ke4 a5 43. Rh6 a4 44. Rh8 Rb4 45. Rd8+ Kc7 46. Re8 Bd5+ 47. Ke5 Kb6 48. Rb8+ Ka5 49. Ra8+ Kb5 50. Rb8+ Kc4 51. Rh8 Bg2 52. Rh2 Rb2 53. Rh4 Re2+ 54. Kd6 Re4 55. Rh2 Rxd4+ 56. Kc7 Rd2 57. Rh4+ Kb3 58. Rh8 a3 59. Rb8+ Kc2 60. Ra8 Kb2 61. Rb8+ Kc1 62. Rb4 a2 63. Ra4 Kb1 0-1
I would say that both of us are at about the same skill level. The game started out okay. White was being more aggressive and I ended up more defensive than I would have liked during the opening (let's say the tenth move). By move 27, white has a slight advantage but he makes a blunder and loses one of his rooks. Assuming neither of us wants a draw, here are my questions,
I have only a rook and a bishop. Just to make sure, it is difficult to force a mate with a rook and a bishop, right? Against a rook? Is my only option promoting to a queen and then mating him?
By move 37, my intuition was that the (sole) white pawn on d4 would become problematic. Forcing a mate with only one rook is impossible so white has no choice BUT to promote to a queen. Therefore, I have to take that pawn and then work on getting my pawn promoted. Was this a reasonable strategy or was I being too cautious? Is there a better decision I could have made at this point?
I was also unwilling to sacrifice one of my pawns because I didn't want to put all of my eggs in one basket. Was this reasonable or overly cautious?
I eventually took his pawn. The best case scenario is a draw for him now. By move 63, the forced mate is obvious to him and he finally resigns. My main question is,
Was there any way to force a win and end the game quickly after move 30? Any path to a quick decisive victory?
The game became very long and drawn out, probably because I was not being bold enough. This was correspondence chess so the game lasted like two months longer than it had to. My intuition is that I could have ended it sooner but I still can't actually see how. Is my intuition correct? Any comments in general to improve my game are also welcome.
Rook + Bishop vs Rook is indeed a difficult endgame to win. It is usually a theoretical draw, but it can be difficult to defend.
Very simple. Learn endgames.
If you knew much about endgames then you would know that in rook and pawn endgames your rook belongs behind your passed pawn. Knowing that on move 39 you wouldn't have played the pointless Kd5. Instead you would have played 39...a5 with the intention of following this with 40...a4 41...Ra5 and then just keep pushing the a pawn.
Note that your opponent's best plan was also to put his rook behind your passed pawn. That would make it impossible for you to put your rook behind the pawn and make it very difficult to push. Fortunately your opponent was equally ignorant of endgame theory.
Time spent learning endgames will gain you more points than anything else you could spend the same amount of time on.
I think I need to first clear up a misconception you have:
Forcing a mate with only one rook is impossible so white has no choice BUT to promote to a queen.
I eventually took his pawn. The best case scenario is a draw for him now.
This is false. A king and rook can, in fact, force checkmate upon a lone king. You should learn the technique ASAP. (It may be unlikely that he could do so considering all the extra material you have, but you need to be aware that it could be done.)
I have only a rook and a bishop. Just to make sure, it is difficult to force a mate with a rook and a bishop, right? Against a rook? Is my only option promoting to a queen and then mating him?
Yes, that's very difficult and possibly impossible to force, depending on the position. (It's also very difficult to properly defend, for what it's worth.) You may run into issues with the 50 move rule. Promoting to a queen - or forcing your opponent to give up their rook to stop you from queening - is your best option.
Therefore, I have to take that pawn and then work on getting my pawn promoted. Was this a reasonable strategy or was I being too cautious? Is there a better decision I could have made at this point?
Taking that pawn at that point was not strictly necessary, but it's a reasonable thing to do. If that pawn does queen you're in big trouble. If your concern was not drawing out the game, it probably would have been quicker to concentrate on advancing your a-pawn until he had to give up defending that pawn in order to stop you, at which point you might have been able to take it for free.
I was also unwilling to sacrifice one of my pawns because I didn't want to put all of my eggs in one basket. Was this reasonable or overly cautious?
It depends. If you saw a clear path to queening a pawn, then sacrificing some other pawn in this situation would be perfectly reasonable. But if you didn't, then keeping as much material as you can is just common sense. There are many pawn and rook vs rook endgames which are draws with best play, and many king and pawn vs king endgames which are draws with best play, and if you wound up with your bishop and a-pawn against a lone king that could be a draw if the enemy king is well-positioned (your bishop doesn't control the queening square so you can't force the enemy king out of the corner if it gets there first) and you don't want to accidentally end up in one of those situations.
| common-pile/stackexchange_filtered |
Problems with Cyrillic symbols
The following code doesn't detect encoding correct.
$data = 'ABCDEG АБВГДЕ';
$charset = mb_detect_encoding($data);
$data = iconv($charset, "UTF-8", $data);
$data = mb_strtolower($data, 'UTF-8');
$datasort = str_replace(array("\r", "\n", " "), '', $data);
$counter = mb_strlen($datasort,'UTF-8');
foreach (count_chars($datasort, 1) as $i => $val)
{
echo '
<tr>
<th scope="row">'.mb_detect_encoding(chr($i)).'</th>
// ON LATIN SYMBOLS IT DETECTED ANCII AND ON CYRILLIC IT DETECTED **NOTHING**
</tr>
';
}
Where here could be the problem?
//php file have UTF-8 encoding
ASCII is a subset of UTF-8, so if a document is ASCII then it is already UTF-8. In this case all letters will return ASCII but if you did to the word before looping and try to detect encoding it will give you UTF-8
@headmax Thats right. But primary question is: why when I try to detected encoding of cyrillic, I get nothing instead ASCII
Why would you want to detect (guess) a character encoding? You simply have to read with the encoding the text was written with. Have you lost that essential information (metadata)? In this case, the encoding is the one you told your editor to use.
| common-pile/stackexchange_filtered |
While using the public app on the Bigcommerce, is the app uses the merchant specific OAuth token and store-hash for making store specific API calls?
Do I need to maintain at my Public app host server database the individual set of OAuth token & store-hash pairs for all the merchants those will be installing my Public app from BigCommerce marketplace? So whenever they launch/use my public app from their store control panel, I need to pick up the relevant OAuth token and store-hash from the database for that merchant and then use them for making store specific API calls to that merchant store, right?
Yes, you will end up needing to store the client id, access token, and store hash. It may be desirable to also keep additional user information such as first name and email address.
You can see an example of this in different languages, such as Python using Flask framework.
There's a few pieces to this. Sample of db model being defined:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
bc_id = db.Column(db.Integer, nullable=False)
email = db.Column(db.String(120), nullable=False)
admin = db.Column(db.Boolean, nullable=False, default=False)
store_id = db.Column(db.Integer, db.ForeignKey('store.id'), nullable=False)
store = db.relationship('Store', backref=db.backref('users', lazy='dynamic'))
class Store(db.Model):
id = db.Column(db.Integer, primary_key=True)
store_hash = db.Column(db.String(16), nullable=False, unique=True)
access_token = db.Column(db.String(128), nullable=False)
scope = db.Column(db.String(128), nullable=False)
| common-pile/stackexchange_filtered |
NullPointerException while Printing StringArray[] in Toast message in android
I'm working with some multiple StringArrary where I can print Toast message inside the respective StringArray but unfortunately, I'm facing a problem with showing toast outside the block. I'm sharing my code below
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.region) {
positions = spinner_region.getSelectedItemPosition();
region_code = this.getResources().getStringArray(R.array.region_code);
//Toast.makeText(this, region_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.district) {
positions = spinner_district.getSelectedItemPosition();
district_code = this.getResources().getStringArray(R.array.district_code);
//Toast.makeText(this, district_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.upz) {
positions = spinner_upz.getSelectedItemPosition();
upz_code = this.getResources().getStringArray(R.array.upz_code);
//Toast.makeText(this, upz_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.union) {
positions = spinner_union.getSelectedItemPosition();
union_code = this.getResources().getStringArray(R.array.upz_code);
//Toast.makeText(this, union_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.village) {
positions = spinner_village.getSelectedItemPosition();
vill_code = this.getResources().getStringArray(R.array.village_code);
//Toast.makeText(this, vill_code[positions], Toast.LENGTH_LONG).show();
}
// Showing toast message here gives the error
//but in individual codeblock this show perfectly
Toast.makeText(this, union_code[positions]+upz_code[positions], Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
My Variable is like
String[] upz_code;
String[] union_code;
My arrays are like
private String[] Union = {"A", "B",};
private String[] Union = {"C", "D",};
The error I'm getting is:
java.lang.NullPointerException: Attempt to read from null array
This error caused the app to crash and don't understand the flaws. How can I overcome this or what I did wrong?
Please post the complete code block. Its possible you're trying to access a variable that is out of scope when you try to use it in the Toast
Please show more code, perhaps the entire function where this logic happens. It's not clear from the snippet you have shown - it seems to not start from the beginning of the function.
Hello, I update the code (full function). and hope you can now understand now.
Not yet @ArvindKumarAvinash
You may use if (union_code!=null) if you want show toast in only null case. Or if you want to show Toast in every case you can use this one:-
Toast.makeText(this,
"" + union_code[positions].toString() + upz_code[position].toString(),
Toast.LENGTH_SHORT).show();
I think, it should work.
Try this,
if(union_code!=null){
Toast.makeText(this,union_code[positions].toString() +upz_code[position].toString(),Toast.LENGTH_SHORT).show();
}
| common-pile/stackexchange_filtered |
Why am I allowed to set a read only property of a protocol using a struct that inherits said protocol?
I'm following a tutorial on the protocol oriented programming paradigm in which I'm confused by something I thought was rather simple which is read only properties of protocols or getters and setters. My understanding is that a read only property is signified by using the keyword 'get' when declaring a variable within a protocol. I was excited so I quickly coded created a playground to see if my thinking was accurate however it appears that I can still change the property which I thought was read only. What am I doing wrong to make it a true read only property to where I can't set it?
protocol FullName {
var firstName: String {get set}
var lastName: String {get set}
var readOnlyProperty: String {get}
}
struct OuttaBeerOuttaHere: FullName {
var firstName: String
var lastName: String
var readOnlyProperty: String = "Jack! Jack!...Line from Titanic"
}
var leonardoDicaprio = OuttaBeerOuttaHere.init(firstName: "Leonardo", lastName: "Dicaprio", readOnlyProperty: "WTF")
print(leonardoDicaprio.readOnlyProperty) //prints "WTF"
leonardoDicaprio.readOnlyProperty = "what now"
print(leonardoDicaprio.readOnlyProperty) //prints "what now"
FYI - your struct does not "inherit" the protocol. It "conforms to" the protocol.
What am I doing wrong to make it a true read only property to where I can't set it?
There is a difference between a protocol (a set of rules) and the type (i.e. your struct) that adopts the protocol.
Your protocol rule says that readOnlyProperty should be readable.
Your struct obeys by making it readable, and also makes it writable. That is not illegal, so all is well — and readOnlyProperty in your struct is read-write.
What would have been illegal would be the inverse, i.e. for the protocol to declare a property read-write but the adopter to declare it read-only. That situation didn't arise in your example, but if it had, the compiler would have stopped you.
Your protocol doesn't declare readOnlyProperty as a read-only property. It only requires that implementations of that protocol have at least gettable readOnlyProperty property. To allow mutations of that property or not is up to implementation itself.
From Docs
Here’s an example of a protocol with a single instance property requirement:
protocol FullyNamed {
var fullName: String { get }
}
The FullyNamed protocol requires a conforming type to provide a
fully-qualified name. The protocol doesn’t specify anything else about
the nature of the conforming type—it only specifies that the type must
be able to provide a full name for itself. The protocol states that
any FullyNamed type must have a gettable instance property called
fullName, which is of type String
it's a requirement from the protocol not a define
| common-pile/stackexchange_filtered |
What are hardware requirements to run a small mining pool?
Im planning on setting up a small Monero or DigitalNote minig pool just for fun. If for example, 10 people connect to that pool, what would be the hardware requirements for it (CPU, RAM and storage)? Could I run it on a Raspberry Pi 3? Would it somehow be profitable?
I have researched a bit and it looks like Ubuntu 14.04 LTS is the best choice for the server software. The raspberry pi reaches the hardwae requirements, but is it enough?
You've asked a number of questions here. I'll tackle the RP3 - no, at this time there aren't any coins you can CPU mine profitably with the device. The RP3 cost is approximately $6 @ 0.15kW/h per annum. That said, it is capable of mining so you can think of it as a lottery chance for a reward (i.e. $6 lottery "ticket" for multiple chances per year). The chance is remarkably bad, but it is greater than zero.
I actually intended to use the RP3 as a server only. The computers connected to it would do the mining. Is that possible?
I can't say from experience. It may be a bit of a "risk" as the SSDs in PI3s can corrupt from abnormal shutdowns more than we'd like...but conceptually I'd say yes.
Running a pool requires a pretty reliable machine. Pi's are fun, but they don't fit the bill. Spend a few bucks a month on a VPS with 2GB of RAM at least and enough disk space to house the Monero blockchain (to run the full-node daemon), and you'll reliably be able to keep a pool up. Who knows, make it public and others might use it too!
Also, wouldn't recommend running any full-node on a home connection as the bandwidth usage is very noticeable. Maybe I'm just saying that because of my wonderful Australian internet connection. (ha.)
If I had to build my own server, what CPU, RAM, and storage specs should it have?
My point is you shouldn't build your own server. Instead you should get a VPS that is hosted on another machine in a datacentre somewhere. It's much more reliable and you don't have to worry about a physical machine using electricity and bandwidth in your house. Plus setting up the routing so public users of the internet can connect to it is painful.
I use a server at home and it is an old Power Edge 2950 (2 x duel quad core Xeons and 32gb RAM). I am running UBUNTU 14.04 LTS and it seems to run the daemon, wallet, and front end via Apache2 pretty well. I haven't had a bunch of traffic on it yet because it is still in the testing phase and it is like pulling teeth finding miners to connect and hash to test everything out but it seems stable. I would think a quad core or better processor and at least 8 gb of RAM would be a pretty minimum requirement. Anything else would be a bonus unless you are planning on having hundreds/thousands connect in which case a VPS or upgrading to a newer hardware setip (perhaps with a Gb switch) would be warranted.
| common-pile/stackexchange_filtered |
Import Excel sheet into MySQL
This is the first project I have coded using Python.
Therefore, I am looking for someone to give me some comments to further improve my code.
Purpose of the application
This application help the staff in my organization to import the spreadsheet and store it into the database.
Flow
User would need to provide the document location before the application execute.
System will extract the information from spreadsheet and import into the database.
Source Code
Below is my source code.
The link below is the complete source code on Github,
https://github.com/WeeHong/0703-Extractor/blob/master/Main.ipynb
# Establish database connection
database = mysql.connector.connect(
host = 'localhost',
user = 'root',
password = '',
database = 'projects_0703'
)
# More about cursor:
# https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor.html
mycursor = database.cursor()
# Fetch all companies records from the companies table from database
mycursor.execute('SELECT id, name FROM companies')
companies = mycursor.fetchall()
# Spreadsheet location
# location = ("./Cluster.xlsx")
location = input()
# Open the spreadsheet from the given path based on the sheet index
workbook = xlrd.open_workbook(location)
sheet = workbook.sheet_by_index(3)
# Fetch all the value from the sheet and store into an array
for excel_row in range(2, sheet.nrows):
# Check respective fields are empty
# Cell 26 = Techsector
# Cell 27 = Sub-techsector
if sheet.cell_value(excel_row, 26):
category = categories[sheet.cell_value(excel_row, 26)]
else:
category = None
if sheet.cell_value(excel_row, 27):
subcategory = subcategories[sheet.cell_value(excel_row, 27)]
else:
subcategory = None
# Assign ID = 10 if the stage is 0 in spreadsheet
if sheet.cell_value(excel_row, 0) == 0:
stage = 10
else:
stage = sheet.cell_value(excel_row, 0)
# Replace NA into 0 for Manday
if sheet.cell_value(excel_row, 19) == 'NA':
manday = 0
else:
manday = sheet.cell_value(excel_row, 19)
# Check if workbook's company exists in database company
# Yes, fetch the company ID
# No, create new company record and fetch the company ID
if sheet.cell_value(excel_row, 1) in companies:
for company in companies:
if sheet.cell_value(excel_row, 1) == company[0][1]:
company_id = company[0][0]
else:
if sheet.cell_value(excel_row, 3):
# Get the industry ID from industries dictionary
industry_id = industries[sheet.cell_value(excel_row, 3)]
mycursor.execute('INSERT INTO companies(industry_id, name, category, country, source, created_at, updated_at) VALUES (%s, %s, %s, %s, %s, NOW(), NOW())', (industry_id, sheet.cell_value(excel_row, 1), 'a:1:{i:0;s:6:"Client";}', 'SINGAPORE', '0703',),)
company_id = mycursor.lastrowid
database.commit()
# Create new project record
mycursor.execute('INSERT INTO projects(company_id, source_id, stage_id, service_id, leader_id, category_id, subcategory_id, name, revenue, forecast, quotation, remarks, created_at, updated_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())', (company_id, sources[sheet.cell_value(excel_row, 4)], stage, services[sheet.cell_value(excel_row, 5)], staffs[sheet.cell_value(excel_row, 20)], category, subcategory, sheet.cell_value(excel_row, 2), sheet.cell_value(excel_row, 17), sheet.cell_value(excel_row, 16), sheet.cell_value(excel_row, 18), sheet.cell_value(excel_row, 28)),)
project_id = mycursor.lastrowid
database.commit()
# Check the number of project member in charge of the project
# Create new project member record
if sheet.cell_value(excel_row, 21):
members = sheet.cell_value(excel_row, 21).split(',')
for member in members:
mycursor.execute('INSERT INTO member_project(member_id, project_id, manday, created_at, updated_at) VALUES (%s, %s, %s, NOW(), NOW())', (staffs[member.strip()], project_id, manday),)
database.commit()
# Create new project techpartner record
# Cell 22 = Techpartner 1
# Cell 23 = Techpartner 2
# Cell 24 = Techpartner 3
# Cell 25 = Techpartner 4
for excel_cell in range(22, 26):
techpartner = sheet.cell_value(excel_row, excel_cell)
if techpartner:
if techpartner in companies:
for company in companies:
if techpartner == company[0][1]:
techpartner_id = company[0][0]
else:
mycursor.execute('INSERT INTO companies(name, category, country, source, created_at, updated_at) VALUES (%s, %s, %s, %s, NOW(), NOW())', (techpartner, 'a:1:{i:0;s:7:\"Partner\";)', 'SINGAPORE', '0703',),)
techpartner_id = mycursor.lastrowid
database.commit()
mycursor.execute('INSERT INTO project_techpartners(project_id, techpartner_id, created_at, updated_at) VALUES (%s, %s, NOW(), NOW())', (project_id, techpartner_id),)
database.commit()
```
workbook = xlrd.open_workbook(location) Where is xlrd defined? Please include your imports.
@Mast I think that this is a reasonable excerpt, given the GitHub link that contains the full code.
The code isn't unreasonable. There are ways to clean it up, though.
Functions
Organize your code into sub-routines - perhaps one to load categories from your spreadsheet, one to write information to your database, etc.
Magic numbers
Numbers like 26, 27, 19, etc. should be assigned to constants, to make the code easier to understand.
Ineffectual commit
The last line of your code is a commit after no operation. Perhaps this is just an indentation error and you meant to commit after your execute.
Delete the commit before it in the else. More broadly, you may want to consider reducing the number of commits in your code, maybe even to one at the end. This depends on a number of things, including how you want to deal with errors and whether they effect validity of the data as a whole, as well as performance.
Finally, have a read through https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-autocommit.html . The way you're using commits now, you're better off just turning on autocommit.
Combined inserts
Your insert into member_project is inefficient. You should not insert in a loop. Read https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html
Add a prompt to your input()
Otherwise, the user doesn't know why the program has suddenly hung.
Thank you. I will look into it and improve my code.
Much appreciated.
| common-pile/stackexchange_filtered |
Double Integral with Gauss- Hermite for one component
I am trying to perform the following integral
$$\int_{0}^{2\pi}\int_{0}^{+\infty} \frac{r'\left(e^{-r'^2/2\sigma^2}\right)\left(r-r'\cos(\theta-\theta')\right)}{r^2+r'^2-2rr'\cos(\theta-\theta')}dr'dθ'$$
Using Gauss-Hermite for $r$ and Simpson 1/3 rule for $\theta$ with no success. I can't find my mistake but the output should look like Fig. 2. This was my code (sorry for my bad formatting, this is my first time uploading here).
$\sigma$ should be assumed as 1.
import numpy as np
import matplotlib.pyplot as plt
import scipy.special as ss
def rt(d, r, theta ,sig):
return r*(d-r*np.cos(theta))*np.exp(-r**2/(2*sig**2))/(d**2+r**2-2*d*r*np.cos(theta))
def intheta1(d, r, b, sig, N):
h = b/N
I = rt(d,r,0,sig) + rt(d,r,b,sig)
for i in range(1, N, 2):
I += 4*rt(d, r, i*h, sig)
for j in range(2, N, 2):
I += 2*rt(d, r, j*h, sig)
return I*h/3
def intr1(d, b, sig, N, M):
x, w = ss.roots_hermitenorm(N)
s = 0
for k in range(N):
s += intheta1(d, x[k], b, sig, M)*w[k]
return s/2
ps = np.linspace(0, 5, 1000)
qs = intr1(xs, 2*np.pi, 1, 1000, 90)
plt.plot(ps, qs)
I cannot match rt function in your Python script with your formula written above. Are you sure the formula is correctly implemented? Also, please remove the image and write your formula by using our LaTeX here.
Did my best, hopefully it is a little more understandable.
Still I can't match it with your Python implementation. For example: in your formula you have: $\exp{(-\frac{(r^{'})^{2}}{2 \sigma^{2}})}$ but in your code you have: np.exp(-r**2/(2*sig**2)) and as far as I understand you use d in your code for showing $r^{'}$, but it's clearly in conflict with your formula. So, something is wrong here for sure...
I am using r as r' and d as r....My goal is to make the graph of the magnetic field (the result of the Integral) as a function of r (represented by d in python)
Gauss-Hermite quadrature is for an integral with $-\infty$ to $\infty$ limits, see it here: https://en.wikipedia.org/wiki/Gauss%E2%80%93Hermite_quadrature, but clearly your limit for $r$ is finite and positive. How would you map it? That's the problem with your implementation.
I guess being and even function I could make the Integral with limits $-\infty$ to $\infty$ limits and divide it by two. At least that was my initial thought, that's why I am returning s/2
Sorry but I don't think you can easily map a region of $[0,5]$ to $[-\infty,\infty]$ easily without a complex changing variable. More convenient way to do this is to use Gauss quadrature and map $[0,5]$ region to $[-1,1]$: https://en.wikipedia.org/wiki/Gaussian_quadrature
Yes but $[0,5]$ is the region of interest for my graph (for r). R' stills goes from $-\infty$ to $\infty$. R is for example my position and r' is the contribution of the infinite wire to the magnetic field.
Is $r^{'}$ radial distance in polar coordinate? If yes, $r^{'}$ is always a positive number and at most it varies between 0 to $\infty$.
Yes, sorry, that's what I meant.
Still, I believe that despite my region of interest for r being $[0,5]$, I have to integrate r' from 0 to $\infty$ as that's the contribution from the wire
Would you mind adding integration limits?
Done.
I have been studying this type of numerical integration and I believe I understood my mistake. First of all I am using gauss-Hermite which work with limits {-\infty} to {\infty} so using the fact that this function is even makes it so that to integrate from 0 to {\infty} I have to use np.abs() of my integration variable. Also, using Gauss-Hermite makes it so that I have to remove the exponential function. In this case I am using roots_hermitenorm() so I had to find a way to remove exp(-r^2/2) from the expression.
@TomásLopes, I think that your previous comment should be added to your answer.
@nicoguaro Sure, good idea
I have been studying this type of numerical integration and I believe I understood my mistake. First of all I am using Gauss-Hermite which work with limits ${-\infty}$ to ${\infty}$ so using the fact that this function is even makes it so that to integrate from $0$ to ${\infty}$ I have to use np.abs() of my integration variable. Also, using Gauss-Hermite makes it so that I have to remove the exponential function. In this case I am using roots_hermitenorm() so I had to find a way to remove $\exp(-r^2/2)$ from the expression.
I got to these answer which is currently working flawlessly.
python
def integral_theta(r, rline, theta, sigma):
rline = np.abs(rline)
return np.exp((-(rline)**2*(1-sigma**2))/2/sigma**2) * rline * (r - rline*np.cos(theta))/(r**2 + rline**2 - 2*r*rline*np.cos(theta))
def i_theta(r, rline, sigma):
a, b = 0, 2*np.pi
N = 100
h = (b-a)/N
s_odd = 0
for k in range(1,N,2):
s_odd += integral_theta(r, rline, a+k*h, sigma)
s_even = 0
for j in range(2, N-1,2):
s_even += integral_theta(r, rline, a+j*h, sigma)
return h/3*(integral_theta(r, rline, a, sigma) + integral_theta(r, rline, b, sigma) + 4*s_odd + 2*s_even)
def i_r(r, sigma):
M = 1000
x, w = ss.roots_hermitenorm(M)
s = 0
for h in range(M):
s += i_theta(r, x[h], sigma)*w[h]
return s/2/np.pi/sigma**2
No need to do any tricky stuff: There is a corresponding Gaussian quadrature with this weight function on the interval $[0,\infty]$. Just search for "half-open Hermite quadrature".
Or search for "Gauss–Laguerre quadrature".
@cos_theta: but Gauss-Laguerre has a different weight function as the one in the OP, i.e. $e^{-r}$ instead of $e^{-r^2/2}$.
| common-pile/stackexchange_filtered |
How to bind coordinates to the Canvas Panel. WinUI
I am developing a program Win UI and I have encountered a binding problem. I need to display the readings of objects on the screen. They are placed in an arbitrary position. The data is stored in the database with values from 0 to 1.
I am using an ObservableCollection consisting of Silos objects. Each Silos object contains information, including coordinates on the visualization panel.
My problem is that the conversion or binding is not working correctly. All objects are located at the same point.
Here is an example of how it is and how it should be.
XAML
<local:ConvertPixel x:Key="ConwertToPixel"/>
...
<ItemsControl x:Name="CanvasPannel" ItemsSource="{x:Bind ViewModel.Siloses}"
HorizontalAlignment ="Stretch"
Height="700">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Height="{Binding ElementName=CanvasPannel, Path=Height}"
Width="{Binding ElementName=CanvasPannel, Path=Width}"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding X, Converter={StaticResource ConwertToPixel}, ConverterParameter=1500}"/>
<Setter Property="Canvas.Top" Value="{Binding Y, Converter={StaticResource ConwertToPixel}, ConverterParameter=800}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Height="150"
Width="150">
<Image x:Name="backgroundImage" Source="{Binding PathImageSilos, Mode=OneWay}" ></Image>
<StackPanel Orientation="Vertical" VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Text="{Binding Name, Mode=OneWay}" FontSize="18"></TextBlock>
<StackPanel Orientation="Horizontal">
<TextBlock Margin="0,0,5,0">Max</TextBlock>
<TextBlock Text="{Binding Max, Mode=OneWay}" ></TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Margin="0,0,5,0">Mid</TextBlock>
<TextBlock Text="{Binding Mid, Mode=OneWay}" ></TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Margin="0,0,5,0">Min</TextBlock>
<TextBlock Text="{Binding Min, Mode=OneWay}" ></TextBlock>
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Conversion class
public class ConvertPixel : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (parameter != null)
{
return (int)((float)value * int.Parse((string)parameter));
}
else
return (int)((float)value*1000);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return (int)value / (int)parameter;
}
}
Thank you in advance.
I found a good example on a Russian-language website. https://habr.com/ru/articles/686438/
And of course I read articles from Microsoft.
Is the converter called for each item? Are the values that the converter receives and returns, correct?
Try adding a breakpoint in public class ConvertPixel : IValueConverter and checking the input and return in debug mode.
I was checking if the conversion was taking place. Added a Canvas to the DataTemplate in the Grid.Top and Canvas.Left. In the dynamic property Explorer, the values are correct, but there are no changes in the Canvas panel.
There an issue in the WinUI repo about this and it seems that Canvas is not working as an ItemsPanel.
Instead, you can try the CanvasView control from the CommunityToolkit-Labs. It's still an experimental control but you should take a look.
Here let me show you a basic sample code:
public partial class Item(object content, int x, int y) : ObservableObject
{
[ObservableProperty]
private object _content = content;
[ObservableProperty]
private int _x = x;
[ObservableProperty]
private int _y = y;
}
public partial class ShellViewModel : ObservableObject
{
[ObservableProperty]
private ObservableCollection<Item> _items =
[
new Item("Item 1", 100, 50),
new Item("Item 2", 200, 100),
new Item("Item 3", 300, 150),
];
}
<Page
...
xmlns:labs="using:CommunityToolkit.Labs.WinUI">
<labs:CanvasView ItemsSource="{x:Bind ViewModel.Items, Mode=OneWay}">
<labs:CanvasView.ItemTemplate>
<DataTemplate x:DataType="local:Item">
<Button
Canvas.Left="{x:Bind X, Mode=OneWay}"
Canvas.Top="{x:Bind Y, Mode=OneWay}"
Content="{x:Bind Content, Mode=OneWay}" />
</DataTemplate>
</labs:CanvasView.ItemTemplate>
</labs:CanvasView>
</Page>
In this answer, you can find the steps for experimental features from the CommunityToolkit-Labs.
You can find my working sample project here.
| common-pile/stackexchange_filtered |
How to fix colors glitch on iPhone 6 screen
I got the iPhone 6 just after the release of the iPhone XS. Recently, my iPhone started to have "colors" on the screen. Here are some photos of it,
I have updated the software to the max I could update it to. (iOS 12.5)
Do I need to replace the screen?
Welcome to Ask Different. Unfortunately, this looks like a hardware failure... You may want to consider purchasing a newer iPhone (there are reasonably priced second-hand models) Instead of replacing the screen: the iPhone 6 is not longer supported and you won't get any software updates for it.
Oh, okay. Thanks for the information!
| common-pile/stackexchange_filtered |
How to add a mathjax equation into the html page using a javascript button
Say I wanted to generate a random fraction on a webpage using MathJax, I might write this:
function newFrac() {
a1 = ran(1,20);
a2 = ran(1,20);
var txt = "$ \frac{"+a1+"}{"+a2+"} $"
document.getElementById("a").innerHTML=txt;
}
where ran(1,20) calls a function to generate a random number.
Then when the user clicked the button to make a new fraction it would write, say, $ \frac{3}{7} $ on my webpage, but I don't want that, I want the equation displayed. How would I do that? How would I tell it to update after the javascript had changed the html?
To evaluate math on the page after MathJax has processed it, you need to queue a call to Typeset via MathJax.Hub.Queue(["Typeset", MathJax.Hub, el]) where el is the element containing the math that needs to be evaluated:
function newFrac() {
a1 = ran(1,20);
a2 = ran(1,20);
var txt = "$ \frac{"+a1+"}{"+a2+"} $"
var el = document.getElementById("a");
el.innerHTML=txt;
MathJax.Hub.Queue(["Typeset", MathJax.Hub, el]);
}
See Modifying Math on the Page for more detail. See the section on Manipulating Individual Math Elements if you want to change an existing equation.
It doesn't seem to be working for me: http://dl.dropboxusercontent.com/s/c08a51r5w5tntb6/example.html
Am I doing something wrong?
@captainjamie - You haven't included MathJax in your page. See this page for instructions on getting started.
| common-pile/stackexchange_filtered |
Filter #tag tweets for a specific account using Twitter Streaming API
I am able to get tweets from a specific account using the streaming API. I can also manage to get tweets for specific #tags like below:
endpoint.trackTerms(Lists.newArrayList("twitterapi", "@myTwitter"));
and
endpoint.trackTerms(Lists.newArrayList("twitterapi", "#yolo"));
I wonder how to merge these two queries as I want to get specific tweets (#yolo) from a specific user (@myTwitter)
Code can be found here
https://github.com/twitter/hbc
Take a look to Twitter's documentation on the streaming API, how to track terms:
A comma-separated list of phrases which will be used to determine what
Tweets will be delivered on the stream. A phrase may be one or more
terms separated by spaces, and a phrase will match if all of the terms
in the phrase are present in the Tweet, regardless of order and
ignoring case. By this model, you can think of commas as logical ORs,
while spaces are equivalent to logical ANDs (e.g. ‘the twitter’ is the
AND twitter, and ‘the,twitter’ is the OR twitter).
twitter-hbc only allows to track terms separated by commas, so if you do this,
endpoint.trackTerms(Lists.newArrayList("@myTwitter", "#yolo"));
You will actually be doing @myTwitter OR #yolo, take a look to the implementation of the method trackTerms,
/**
* @param terms a list of Strings to track. These strings should NOT be url-encoded.
*/
public StatusesFilterEndpoint trackTerms(List<String> terms) {
addPostParameter(Constants.TRACK_PARAM, Joiner.on(',').join(terms));
return this;
}
Instead of using trackTerms, you could add the terms directly to the endpoint like this,
endpoint.addPostParameter(Constants.TRACK_PARAM, Joiner.on(' ').join(Lists.newArrayList("twitterapi", "#yolo")));
Or of course you could create a new method.
Hope it helps.
| common-pile/stackexchange_filtered |
Was there a word which meant roughly the same thing as "nerd" or "geek" does today?
...That is, a word meaning someone with deep and specialized knowledge, and could be used either as a badge of pride:
I'm a huge Linux nerd. I helped reoptimize some of the photonal decalcifiers for Intel CPUs.
...or a mark of shame:
Ugh, you're such a nerd. Stop going on about your kernel!
(Those aren't the best examples, but I think they get the point across)
I'm looking for something from Classical or Medieval Latin, but if there's a neologism with a similar meaning, I'd be interested to know.
The context is a person mildly swearing at another person under their breath after they geek out about arcane tech, then the other person turning around and saying something along the lines of, "I sure am a nerd!" except with a few more words that you didn't know unicorns could say.
You tagged your question "classical/medieval Latin" but mention "tech." Are you looking for a cultural equivalent from that period or for a term for the current phenomenon?
Also, since it's bound to come up: https://xkcd.com/747/
@brianpck The cultural equivalent.
The sociological side just doesn't match up between our culture and theirs. This is one of the reasons that we know so little about Greco-Roman practical technology -- the kind of people who knew about water wheels, tanning, or metallurgy were slaves or plebeian laborers. The kind of people whose ideas are recorded by history are aristocrats who wouldn't have dirtied their hands with such matters. It's the complete cultural opposite of the Steve Wozniak/Elon Musk thing.
Perhaps graeculus, often translated as Greekling?
It refers to Greeks who held positions of some import in Roman society due to their education and higher learning yet were considered too Greek to actually be considered proper Romans and, therefore, part of Roman society. It was also used to mock those Romans who exhibited a taste for Greek language, learning and customs, most (in)famously, of Hadrian in the Historia Augusta but also of Claudius in the Apocolocyntosis (see section 5).
The diminutive suggests a pejorative, as does its use in context (for example, the graeculus esuriens in Juvenal, Satires, 3.78 or almost anytime Cicero uses it!). The animosity inherent in the term seems to lie in the resentment of the erudition and cleverness of the Greek. This is perplexing as Greek literacy was considered cultured and elegant among Roman elite. Indeed, Cicero seems to use graeculus to mock Verres’ lack of authentic Greek learning (Against Verres, speech 2, book IV.127 – quite funny in its scathing sarcasm so I include a link: Against Verres). It has also been debated whether the use of graeculus to label Hadrian was a compliment or an insult.
Nevertheless, I don’t know if someone would lay claim to the label graeculus as a matter of pride. Perhaps for a successful, well-educated Greek in Rome, appropriating the term ironically as a marker of his Greekness could be an act of self-affirmation. Macrobius (who was possibly Greek himself) seems to use graeculus in an almost affectionate way. See the Saturnalia VI.26, for instance, when a guest exclaims “εὖγε, graeculus noster!/Well done, our little Greek!” after a very erudite exposition of the nervous system without any apparent malice, and also at II.31.
Thus, graeculus could perhaps encapsulate the idea of someone with great erudition and skill but on the outskirts of society. Further, its use as a pejorative or a compliment seems to lie in the eyes of the beholder (so to speak). Of course, it is also a racial epithet so perhaps not quite what you’re after. Even so, I thought it an interesting possibility so persevered with the research!
Welcome to the site and thank you for the interesting answer!
I think I like this the best: it's a great cultural parallel!
The other words are great for general put-downs as nerd was back in the day, but only this one I think really captures the cultural parallel.
In his Conversational Latin for Oral Proficiency (with which I am otherwise completely unfamiliar), John C. Traupman proposes inconcinnus, which is admittedly rare but has classical attestations. Lewis & Short glosses it as:
inelegant, awkward, absurd
I would also cautiously advance ineptus as a possibility:
unsuitable, impertinent, improper, tasteless, senseless, silly, pedantic, absurd, inept, without tact
Both words figure in Cicero's definition of an ineptus, in which he paints a picture of someone with no knowledge of social norms who wants to show off in a verbose way:
qui aut tempus quid postulet non videt aut plura loquitur aut se ostentat aut eorum, quibuscum est, vel dignitatis vel commodi rationem non habet aut denique in aliquo genere aut inconcinnus aut multus est, is ineptus esse dicitur. (Cic. de Orat. 2.17)
(N.B.: multus here means "prolix"--I learned something new today!)
Both words are obviously pejorative in a way that modern-day "geek" or "nerd" are not necessarily. They emphasize the lack of a certain kind of knowledge rather than excellence in another kind. Honestly, though, the "nerd" indicates such a localized cultural phenomenon that it's notoriously difficult/impossible to translate: see this Language Log post for an enlightening discussion of attempts to find an equivalent for the word in Sinitic languages, for instance.
Ooh, I like this answer -- but being an ineptus or inconcinnus doesn't seem like something that could be seen as both an insult and praise, which is basically the whole thing I'm trying to get at.
@QPaysTaxes Bear in mind that for many of us, when we were kids, nerd was definitely not praise, nor was geek, dork, and dweeb. It'd be like Roman kids going around saying, "Tam stultus sum!" Especially when you consider the etymology.
@C.M.Weimer you're right. I don't think "praise" is the right word -- it's more of an insulting word intentionally repurposed to mean something good to the insulted people, as they decided not to shy away from but accept and be proud of their label.
For what it's worth, I find a lot of Traupman highly suspect. The stuff in chapter 12—everyday locutions—is great, but the rest is a crap shoot.
Coming at this from the opposite direction, the first word I think of is artifex (-icis, m/f). It refers to a person who is highly skilled and knowledgeable about a specific topic, but not necessarily in a good way. An artifex is capable of twisting and controlling and manipulating something, whether it be marble and paint or the mood of a crowd.
Here's a positive example from Aeneid 1.455:
artificumque manus inter se operumque laborem
miratur, videt Iliacas ex ordine pugnas...
He sees the battles of Troy all in order, and marvels at the skill of the crafters and the effort of their works...
But it was also an epithet of Odysseus, for example, when Sinon is explaining how he was chosen as a sacrifice (2.125):
hic Ithacus vatem magno Calchanta tumultu
protrahit in medios; quae sint ea numina divum
flagitat. et mihi iam multi crudele canebant
artificis scelus, et taciti ventura videbant.
Here Odysseus brought out the seer Calchas among them, amid great commotion; he demanded to know from him what the will of the Gods might be. And already many people were cruelly predicting that schemer's wickedness, and were foreseeing what was about to come.
I hesitate to call it a real translation of "nerd", since it doesn't imply anything about social awkwardness—quite the opposite, in fact. But it's a word implying specialized skill or knowledge, which can either be a compliment or an insult depending on context.
In an ecumenical spirit, how 'bout artifex inconcinnus :)
In episode 8 I think of Legio XIII, Luke Ranierus, definitely one of the best Latin speakers in the world today, referred to himself as a nerd and he used the word 'umbratico' which L&S defines as an effeminate person, as well as one who is fond of the shade. The word was only used 8 times up until 200AD according to packhum. For those words that describe personality, it is very tough to figure out what they mean. Just imagine if there was a nuclear war and many of records were destroyed and suppose that the word 'tacky' only appeared 8 times in our corpus, would you be able to figure out what it meant?
Umbraticola seems to be the word for an effeminate man. Umbraticus, on the other hand, does not seem to have that particular meaning, but seems to refer to bookish types who stay indoors.
Well, the word is only used 8 times in the packhum corpus. Could you tell me what sentence(s) you're looking at that leads you to believe this? https://latin.packhum.org/search?q=umbratic
I wasn't looking at PHI, just Lewis and Short.
You have to look at the actual Latin texts. Just because L&S says x does not mean that x is true.
This is the answer I would have given. I find the others, while creative, unsatisfactory.
Do you mean that 'umbraticola' or 'umbratico' is how you would translate 'nerd'.
| common-pile/stackexchange_filtered |
Why does this static Receiver not respond to the ACTION_POWER_(DIS)CONNECTED Event?
I want a STATIC Broadcast Receiver to get fired, whenever the Phone gets charged or not. In my Manifest.xml, i have written the following Entry:
<receiver
android:name=".Starter">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
The Broadcast Receiver itself looks like this:
public class Starter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "blablabla", Toast.LENGTH_LONG).show();
}
}
When I register the Receiver programmatically, everything works fine, but I want the Receiver also to respond, when the Activity is not open, so I have to make a static Receiver.
Thank you for your help!!!
| common-pile/stackexchange_filtered |
How to enable Spring Security Annotations not using app-Context.xml file?
I've implemented my Application using SecurityContextImpl as SecurityContext. anything works well (Authentication and Authorization).
Now I want to use Spring Security Annotations (@Secured , ...) , I my searched result in a single comment :"USE in your context.xml file"
is there any other way to embed security annotations using non-file-based ContextImpls?
Here's the config snippet you need. Not sure why you don't want to enable via XML.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns:security="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<security:global-method-security secured-annotations="enabled" />
</beans:beans>
you know , I've got an exception :
'INFO: Spring Security 'config' module version is 3.1.0.RC3
Sep 26, 2011 7:12:55 PM org.springframework.security.config.SecurityNamespaceHandler loadParsers
SEVERE: Failed to load required web classes
java.lang.ClassNotFoundException: org.springframework.security.web.FilterChainProxy
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadCla..'
I'm working on a swing standalone application , and can't understand Why I have to use org.springframework.security.web.FilterChainProxy ?
Because Spring Security is used for web apps. As per the intro to the documentation: "Spring Security provides comprehensive security services for J2EE-based enterprise software applications." (http://static.springsource.org/spring-security/site/docs/3.0.x/reference/introduction.html#what-is-acegi-security). I did find this page: http://sacrephill.wordpress.com/2009/06/12/using-spring-security-in-a-swing-desktop-application/.
another reason is : I'm using SecurityContextImpl and working with multiple parallel users, each one has its own Context (for authorization features) and unfortunately I don't know how to add a new authenticated Authentication-Object (user) to ClassPathXmlApplicationContext
Spring main focus is on Web-Apps but Spring Security.
Supports standalone applications, remote clients,.. link
I have no other suggestions; I've never used Spring Security except in a J2EE app. Here is a blog post which might help you: http://weblogs.java.net/blog/kalali/archive/2010/03/18/using-spring-security-enforce-authentication-and-authorization-spring
| common-pile/stackexchange_filtered |
How Can I use Alias in Where
This is my code but it's not working:
$select = $db->select()
->from(array('p' => 'products'), 'p.product_id')
->columns(array('x' => new Zend_Db_Expr('(SELECT...)'
)))
->where('x = ?', 'value');
// Alternatively use columns('p.product_name')
How can I retrieve x and compere it in where clause?
This is the actual query:
SELECT `abstract_submission`.*,
(SELECT GROUP_CONCAT(CONCAT(user.firstName, " ", user.lastName) SEPARATOR ",")
FROM mamba_event.abstract_submission_reviewer reviewer INNER JOIN
mamba_account.account_user user ON user.id = reviewer.userId
WHERE reviewer.submissionId = mamba_event.abstract_submission.id AND
user.isEnabled = 1)
AS `reviewers`,
(SELECT GROUP_CONCAT(CONCAT(author.firstName, " ", author.lastName) SEPARATOR ",")
FROM mamba_event.abstract_author author INNER JOIN
mamba_event.abstract_submission_author map ON author.id = map.authorId
WHERE map.submissionId = mamba_event.abstract_submission.id)
AS `allAuthors`,
(SELECT COUNT(`abstract_paper`.`id`) FROM `mamba_event`.`abstract_paper`
WHERE `abstract_paper`.`submissionId` = `abstract_submission`.`id`)
AS `numPapers`,
(SELECT `paperNumber` FROM `mamba_event`.`abstract_paper`
WHERE `abstract_paper`.`submissionId` = `abstract_submission`.`id` AND
`abstract_paper`.`currentStatus` = 3 LIMIT 1)
AS `acceptedPaperNumber`,
(SELECT IF ((COUNT(1) > 0), 'Paper has been uploaded','None') AS hasUploadedPaper
FROM `mamba_event`.`abstract_paper` paper
WHERE paper.submissionId = `mamba_event`.`abstract_submission`.`id`)
AS `hasUploadedPaper`,
(SELECT GROUP_CONCAT(CONCAT(user.firstName, " ", user.lastName) SEPARATOR ",")
FROM `mamba_event`.`abstract_submission_reviewer` reviewer INNER JOIN
`mamba_account`.`account_user` user ON user.id = reviewer.userId
WHERE reviewer.submissionId = `mamba_event`.`abstract_submission`.`id`
AND reviewer.hasConflictOfInterest = 1
AND user.isEnabled = 1)
AS `reviewersWithConflict`,
(SELECT AVG(`score`) FROM `mamba_event`.`abstract_submission_score`
WHERE `submissionId` = `abstract_submission`.`id`)
AS `averageScore`,
(SELECT AVG(`score`) FROM `mamba_event`.`abstract_paper_score`, `mamba_event`.`abstract_paper`
WHERE `abstract_paper_score`.`paperId` = `abstract_paper`.`id`
AND `abstract_paper`.`submissionId` = `abstract_submission`.`id`
AND (`abstract_paper`.`currentStatus` = 1
OR `abstract_paper`.`currentStatus` = 3))
AS `averagePaperScore`,
(SELECT AVG(`score`*`scoreWeight`) FROM `mamba_event`.`abstract_submission_score` INNER JOIN
`mamba_event`.`abstract_request_criteria` ON `criteriaId` = `abstract_request_criteria`.`id`
WHERE `submissionId` = `abstract_submission`.`id`)
AS `averageWeightedScore`,
(SELECT AVG(`score`*`scoreWeight`) FROM `mamba_event`.`abstract_paper_score` JOIN
`mamba_event`.`abstract_paper` INNER JOIN
`mamba_event`.`abstract_request_criteria` ON
`criteriaId` = `abstract_request_criteria`.`id`
WHERE `abstract_paper_score`.`paperId` = `abstract_paper`.`id`
AND `abstract_paper`.`submissionId` = `abstract_submission`.`id`
AND (`abstract_paper`.`currentStatus` = 1
OR `abstract_paper`.`currentStatus` = 3))
AS `averageWeightedPaperScore`, `author`.`email`
AS `authorEmail`, `author`.`salutation`
AS `authorTitle`, `author`.`firstName`
AS `authorFirstName`, `author`.`lastName`
AS `authorLastName`, `author`.`organisation`
AS `authorOrganisation`, `author`.`position`
AS `authorPosition`, `author`.`department`
AS `authorDepartment`, `author`.`phone`
AS `authorPhone`, `author`.`fax`
AS `authorFax`, `address`.`line1`
AS `addressLine1`, `address`.`line2`
AS `addressLine2`, `address`.`line3`
AS `addressLine3`, `address`.`line4`
AS `addressLine4`, `address`.`city`
AS `addressCity`, `address`.`stateCode`
AS `addressStateCode`, `address`.`countryCode`
AS `addressCountryCode`, `address`.`postalCode`
AS `addressPostalCode`, `author`.`biography`
AS `authorBiography`, `request`.`title`
AS `request`, `request`.`blindReview`, `request`.`hasCustomTypes`, `file`.`content_type`, `file`.`original_filename` AS `filename`, `author`.`speakerId`,
(SELECT GROUP_CONCAT(
CONCAT('',ifnull(author.firstName,'-'),' ',
ifnull(author.lastName,'-'),'
(',ifnull(author.organisation,'-'),',
',ifnull(author.authorCountryCode,'-'),')')
SEPARATOR ",")
FROM `mamba_event`.`abstract_author` author LEFT JOIN
`mamba_event`.`abstract_submission_author` sa
ON sa.authorId = author.id
WHERE sa.submissionId = `abstract_submission`.`id`)
AS `authorDetails`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2185'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2185`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2335'
AND `field`.`fieldValue` = 'BSCS'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2335`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2336'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2336` FROM `mamba_event`.`abstract_submission`
INNER JOIN `mamba_event`.`abstract_request` AS `request` ON requestId = request.id
LEFT JOIN `mamba_account`.`account_file` AS `file` ON fileId = file.id
INNER JOIN `mamba_event`.`abstract_author` AS `author` ON `presenterId` = `author`.`id`
LEFT JOIN `mamba_general`.`address` ON `author`.`addressId` = `address`.`id` WHERE ((`abstract_submission`.`isEnabled` = '1') AND (`abstract_submission`.`eventId` = '1893')) AND (`field2335` LIKE "%BSCS%") ORDER BY `request` asc LIMIT 15
How's your query looking? echo $select;
please echo your query so its easy to solve problem
just posted the actual query...
Does mysql give you any error?
You can't use column alias in WHERE clause.
thanks for your replies, so how can I put a condition, is there any other way?
You can only use column aliases in GROUP BY, ORDER BY, or HAVING clauses.
You could do it with HAVING, like Muhammad Zeeshan said.
$select = $db->select()
->from(array('p' => 'products'), 'p.product_id')
->columns(array('x' => new Zend_Db_Expr('(SELECT...)')))
->having('x = ?', 'value');
| common-pile/stackexchange_filtered |
Sorting command line args
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
bool comp(int a, int b){
return a < b;
}
int main(int argc, char* argv[]){
char array[argc-1];
for(int i = 1; i < argc; i++){
array[i-1] = *argv[i];
}
for(int j = 0; j < argc; j++){
cout<<array[j]<<" ";
}
std::sort(array, array+argc-1, comp);
for(int j = 0; j < argc; j++){
cout<<array[j]<<" ";
}
cout<<endl;
return 0;
}
This code is supposed to sort the arguments of the command line. But when I launch it:
.\a.exe 11 21 34 9 87
I get this output:
1 2 3 8 9
You copy only the first character of each argument.
Yes, you get this output because this is what your program does. It sorts only the first character of each parameter. This is literally what your program does. If you want it to do something else, you will need to change your program accordingly. Does it make sense to you that your comparison function compares only two int values? How do you expect to sort character strings when the actual comparison only compares two int values? You can start with this part of the puzzle, and work your way from there.
Maybe this helps
Does this answer your question? Sort command line args in C++
array is an array of char, but your comparison function compare two int values.
Besides all that has been brought up already, please take some time to read the help pages, take the SO [tour], read [ask], as well as this question checklist. Then learn how to [edit] your questions to improve them, like for example actually asking a question. And tell us what problem the code is supposed to solve (possibly copy-paste the whole exercise/assignment including all limitations and requirements).
Variable length arrays are not C++ standard compliant, you should maybe use std::vector
Thanks for eachother. I solved this problem by using atoi() in pushing to array loop.
@G0053 atoi is dangerous, in case of overflow the behavior is undefined, std::stoi would be a better way. I'll answer.
Variable length arrays are not C++ standard compliant, you should instead use std::vector
In this case you wouldn't even need to do so, you can simply sort argv, which is nothing more than an array of strings, in place:
bool comp(const char* a, const char* b)
{
return std::stoi(a) < std::stoi(b); // convert to number and compare
}
int main(int argc, char *argv[])
{
try //if argument is not parseable, exception is thrown
{
std::sort(&argv[1], &argv[argc], comp);
}
catch (std::exception &e)
{
//error parsing argument handling
std::cerr << "Argument not parseable " << e.what() << "\n";
return EXIT_FAILURE;
}
for (int j = 1; j < argc; j++)
{
std::cout << argv[j] << " ";
}
}
The comparator function could also be a lambda which I believe you have an example in one of the links provided in the comments.
Input:
.\a.exe 11 21 34 9 87
Output:
9 11 21 34 87
Bad input:
.\a.exe 11 21 34 9 87 gjh
Output:
Argument not parseable stoi
| common-pile/stackexchange_filtered |
How to filter in a core result webpart on columnA is not empty or null?
How to filter in a core result webpart on a column which is not null or empty?
I try this but is not working:
ContentType="Project portal" and SRExperienceRecord="True" and columnA Not ""
Search queries cannot return null values. If a value is null it is not included in the index. You have to find another approach or use Content Enrichment to detect the null value and set a second fields value indicating that your value is Noll. This is one case were Search Query is not like SQL.
what about check if a date column is larger as 02-02-2015? something like this: and column > "02-02-2015"
Sure, you just can't test for null.
| common-pile/stackexchange_filtered |
How to continue looping after invalid data type input?
I'm trying to do one check for invalid input data type. If the the input data type is of type char, I want the re-loop over the menu options. But my program terminates instead.
int menu()
{
int choice = 15;
while ((choice > 14) || ( choice < 0))
{
cout << "Enter 0 to quit\n";
cout << "Enter 1 for Addition\n";
cout << "Enter 2 for Subtraction\n";
cout << "Enter 3 for Multiplication\n";
cout << "Enter 4 for Division of two integers\n";
cout << "Enter 5 for Real Division of two integers\n";
cout << "Enter 6 for Quotient of a division\n";
cout << "Enter 7 for Remainder of a division\n";
cout << "Enter 8 for Factorial of an integer\n";
cout << "Enter 9 for Exponential of two integers\n";
cout << "Enter 10 for Finding if number is even or odd\n";
cout << "Enter 11 for Area of a Square\n";
cout << "Enter 12 for Area of a Circle\n";
cout << "Enter 13 for Area of an Isoceles Triangle\n";
cout << "Enter 14 for Converting Decimal to binary or hexadecimal\n";
cin >> choice;
if((choice > 14) || (choice < 0))
{
cout << "Invalid entry: Try again" << endl << endl;
}
else if ( !choice )
{
return choice;
}
else if (choice)
{
return choice;
}
}
return choice;
}
Output after entering char 'f' as cin
use "try" and "catch" clause, use the exception you get when You type invalid character
I don't know how.
write the exception You get in the console and I think I can help
Use cin.fail() https://stackoverflow.com/questions/17928865/correct-way-to-use-cin-fail
Debug your program, check which return statement is being executed, and change it to handle the case that you wish to avoid returning from (BTW, you would probably want to initialize choice to some sort of "illegal" value before you scan it from the user).
@Sniper with cin.fail() it quits the program automatically tho right? I wan't to reloop tho.
Nope. cin.fail() check if input is correct. You could do if(cin.fail) continue; Or something like that
Try this instead
if (cin >> choice)
{
if((choice > 14) || (choice < 0))
cout << "Invalid entry: Try again" << endl << endl;
else
return choice;
}
else //Fail to cin into choice, user input is not a number
cout << "Invalid entry: Please key in a number." << endl;
Also, the while condition should change to while (true)
Remove space line and then run the code again.
if((choice > 14) || (choice < 0))
cout << "Invalid entry: Try again" << endl << endl;
else if ( !choice )
{
return choice;
}
////// remove the empty space line below///////////
else if (choice)
return choice;
///////////////////////////////////////////////////
How is that a solution?
| common-pile/stackexchange_filtered |
How to generate compressed public key in bitcoin format, using openssl and the command line?
I am using this line
openssl ecparam -genkey -name secp256k1 | openssl ec -pubout -outform DER | tail -c 65 | xxd -p -c 65
which produces an uncompressed bitcoin public key, for instance:
049ddf875b4a6e57d31004926bd8331271b4b45731be5c17ea841c89353cbd13adc9cc2347ae1bcb4ed369fd6bfc44040ffda9f8e68f86a6593c94261fc42eca35
The prefix 04 indices that this public key contains both the x and y coordinates of the point on the EC. What is the correct way to create the compressed version of this key?
How do I produce a compression version of a private key?
Try this script: https://bitcoin.stackexchange.com/questions/56680/openssl-generate-bitcoin-address
@Pak that was indeed the script I was trying but it produces uncompressed public keys. I think my edit produces compressed public keys correctly.
Another way is to let openssl do the hex and then tidy it up: (gen/read) | openssl ec -conv_form compressed -noout -text | awk -vORS= '/^pub:/{x=1;next} /^ASN/{exit} x{gsub(/[ :]/,""); print}' or ... | sed -n '/^pub/,/^ASN/p' | sed '1d;$d' | tr -d ' :\n'
Solution moved from @Anon21's question post.
found the answer:
openssl ecparam -genkey -name secp256k1 | openssl ec -pubout -conv_form compressed -outform DER | tail -c 33 | xxd -p -c 65
| common-pile/stackexchange_filtered |
Display a Template MS Chart for ,NET
VB2010 using MS Chart Control: I think my question is basic but havent found out how to do it. When the form first loads the chart control shows nothing, not even a grid. When I load points into my series then the grid plus the points get displayed.
How can I display a template chart with just the gridlines so that the user can see that there is a chart that will be populated. I did try to add two bogus points to one of my series and then disable the series to not display the points but the Chart control doesn't see it as a reason to render a grid.
Thanks for any help.
Edit: Thanks to @baddack for giving me food for thought.
Here is what i did:
On form load create a bogus series. This series will stay in the chart for the life of the app.
Dim srs As New Series 'create a new series
cht.Series.Add(srs) 'add series to chart
srs.ChartType = SeriesChartType.Point 'it will be a point chart with one point (or you can add several points to define your display envelope)
srs.Name = "bogus" 'name of our bogus series
srs.IsVisibleInLegend = False 'do not show the series in the legend
srs.Points.AddXY(25000, 1000) 'this will be a point in the upper-right corner of the envelope you want to display
srs.Points(0).MarkerColor = Color.Transparent 'no color for the marker
srs.Points(0).MarkerSize = 0 'no size for the marker
chtObstacles.Series("bogus").Enabled = True 'name of the bogus series
chtObstacles.Update() 'update the chart
then the first thing I do when I run my process is to clear all other series and enable the bogus series so that it can be used to size the "empty" grid.
cht.Series("srs1").Points.Clear()
cht.Series("srs2").Points.Clear()
cht.Series("bogus").Enabled = True
then run the process that provides the points for the chart:
if pointCount > 0 then
'turn off the series so it will not be used in the grid sizing
cht.Series("bogus").Enabled = False
'add points to the chart
'code to add points to MS Chart
endif
cht.ChartAreas("chaMain").RecalculateAxesScale() 'we must recalculate the axes scale to reset the mins/maxs
'resume updating UI
cht.Series.ResumeUpdates()
'force redraw of chart
cht.Update()
You can add an empty point to the chart. That will make the grids show up, but not display any points.
private void Form1_Load(object sender, EventArgs e)
{
chart1.Series.Clear();
SetChartAxisLines(chart1.ChartAreas[0]);
Series s = new Series();
chart1.Series.Add(s);
s.Points.Add();
s.Points[0].IsEmpty = true;
}
private void SetChartAxisLines(ChartArea ca)
{
//X-Axis
ca.AxisX.MajorGrid.LineColor = Color.DarkGray;
ca.AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Dash;
ca.AxisX.MinorGrid.Enabled = true;
ca.AxisX.MinorGrid.LineColor = System.Drawing.Color.Silver;
ca.AxisX.MinorGrid.LineDashStyle = ChartDashStyle.Dot;
//Y-Axis
ca.AxisY.MajorGrid.LineColor = System.Drawing.Color.DarkGray;
ca.AxisY.MajorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash;
ca.AxisY.MinorGrid.Enabled = true;
ca.AxisY.MinorGrid.LineColor = System.Drawing.Color.Silver;
ca.AxisY.MinorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dot;
}
Thanks. That gave me an idea on how to set this up since I wanted a specific empty chart with default x and y min/max. Your code helped me to realize that I could just add a bogus series for auto-sizing. Thanks for the tip. I will write the solution here in a bit.
| common-pile/stackexchange_filtered |
Creepy YA short story about children living in walls to hide from a monstrous man
This story scared me so badly when I was a little kid that my father threw the book away! I would have read it in English in the US prior to 1989, and it was almost certainly a Scholastic Book Club book. I would most likely have been in fourth or fifth grade at the time, so that might help narrow down which Scholastic flyer it had been in.
If it was a book, it was a very short book, but I think it's more likely that it was a short story in a compilation of creepy stories. I think the cover may have been blue.
The main thing that I recall about the story is the house. This house was huge and had twisting corridors and stairs everywhere - for some reason children had been transported to the house and had to hide inside the walls. Some of the children had been hiding in the house for years, possibly longer.
I think that it was a neighbourhood 'haunted house', and that's how the main kid in the story got trapped there - he decided to explore the house, and somehow got trapped there, stuck out of time or in a pocket dimension or whatever.
The windows of the house all showed views of different seasons - one window might show winter with snow on the ground, the next window would look out to spring and green grass, etc. I have the impression that the house was some sort of dimensional nexus, with the windows opening to different alternate universes or even different eras in time.
The children had to hide in the walls because a monstrous man was roaming the house, looking for the kids. I remember imagining that he looked like a gaunt Frankenstein's monster (he's what I was so scared of & the reason my dad tossed the book out!), but I am not at all certain that that's how he was described in the book - that's just how I imagined him looking. Tall, ominous, he never spoke as far as I can recall. He would snatch the children up if he could catch them, and take them away to an unknown but horrible fate.
A few details are off, but could it be 'The Littles' series overblown by your imagination?
Definitely not the Littles - this was a scary short story, not a children's book series. And the kids were normal human children, not tiny people. I'm about as certain of that as I am of anything about this story.
I know exactly the story you’re talking about because I arrived here on a google search looking for the scary short story that was part of a collection where there was a kid that went into a large house and encountered other kids trapped in the walls. It was implied that they had died or like you said were trapped in another dimension because they’d been caught by the lumbering man that roamed the house. The boy protagonist stayed too long in the house and became a spirit in the walls like the other kids. It was one of the scariest things I read at that age and I’m dying to figure out ...
... what the name of that story and collection was. I know this isn’t an answer but wanted you to know you didn’t imagine this story. It definitely would have predated RL Stine or the Scary Stories collection that came along later. I seem to remember it being illustrated and hardbound but it was a thin book with a couple of other stories. This one was the last story in the book from what I recall. Scholastic sounds right because I most likely picked it up at the book fair.
"The House on Pearl Street" from "The Haunted Planet" by D.J. Arneson and Tony Tallarico
Taking a shortcut through the woods, a boy comes across an old house. He goes in to find an ugly giant holding a group of ghostly children from different era’s of time captive inside the house. The children tell the boy he will be one of them too, and that there is no escape.
Horror Delve, The Haunted Planet Review
This review mentions different seasons windows and children in hidden panel in the wall.
He looks out the window and it is winter out. Only it was SUMMER when he came in! Then a super-tall ghoul-thing (see above) shows up and shambles after him. These children pull him into a hidden panel in the wall and tell him they are ghosts who live there because the ghoul-thing killed them, too, and he’ll be joining them soon, because there’s no escape. They kick him out of the safe room (I assume because they want to PLAY with him, Danny, and in order for them to do that, he has to be eaten by the ghoul-thing) and he runs around (outside of another window, it’s fall, this is the house of all the seasons, although it’s not really explained why that’s the case)
Yes! That's it! Thank you!
| common-pile/stackexchange_filtered |
|| converting empty string to bool, && not
Is this normal? Is it a feature or a bug? (I'm using firebug):
>>> '' || true
true
>>> '' || false
false
>>> '' && false
""
>>> '' && true
""
It is not converting the empty string to Boolean.
With ||
It is evaluating the left hand side, of which an empty string is falsy. It then checks the right hand side (because it's an or, and that side may be true), and returns that value.
With &&
Because && needs both sides to be true and the left hand side is falsy, it doesn't bother checking the right hand side (short circuit evaluation). Therefore, it just returns the left hand side, which is the empty string.
JavaScript always returns the last value it evaluated.
>>> '' || 0 || undefined || null || false || NaN || 'hello'
"hello"
It's not that one is converting and the other isn't; the lines with || are returning their second operand and the lines with && are returning their first, due to short-circuiting.
[ECMA-262 11.11]: Semantics
The production LogicalANDExpression : LogicalANDExpression &&
BitwiseORExpression is evaluated as follows:
Let lref be the result of evaluating LogicalANDExpression.
Let lval be GetValue(lref).
If ToBoolean(lval) is false, return lval.
Let rref be the result of evaluating BitwiseORExpression.
Return GetValue(rref).
The production LogicalORExpression : LogicalORExpression ||
LogicalANDExpression is evaluated as follows:
Let lref be the result of evaluating LogicalORExpression.
Let lval be GetValue(lref).
If ToBoolean(lval) is true, return lval.
Let rref be the result of evaluating LogicalANDExpression.
Return GetValue(rref).
The LogicalANDExpressionNoIn and LogicalORExpressionNoIn
productions are evaluated in the same manner as the
LogicalANDExpression and LogicalORExpression productions except
that the contained LogicalANDExpressionNoIn,
BitwiseORExpressionNoIn and LogicalORExpressionNoIn are evaluated
instead of the contained LogicalANDExpression, BitwiseORExpression
and LogicalORExpression, respectively.
NOTE The value produced by a && or || operator is not necessarily
of type Boolean. The value produced will always be the value of one of
the two operand expressions.
The || operator will return the first value which is truthy.
The && operator will return the second value if the first is truthy, otherwise it returns the first.
For more info, you can see the Logical Operators page on the MDC site.
In your case,
'' || true; '' is false, so the || operator moves onto the second value, which is true, and so returns it.
'' || false; '' is false, so the || operator moves onto the second value, which is false, and has no more values to compare, so returns it.
'' && false; the first value ('') is falsy, so it returns it.
'' && true; the first value ('') is falsy, so it returns it.
Your answer would be more clear if you pointed out that '' is falsy which, I believe, is what is confusing @Paolo.
@chuckj: I've added that to my answer :)
| common-pile/stackexchange_filtered |
nginx - rewrite js file with php file
with apache I use a file config.php to rewrite a file config.js based on domain, config.js contains placeholders which are replaced by RewriteRule directive, this is .htaccess file:
<IfModule mod_rewrite.c>
RewriteBase /foo
RewriteEngine On
RewriteRule config.js config.php [L,QSA]
</IfModule>
When i go into URL production.com/foo/config.js i see some values, instead into develop.com/foo/config.js i see other values, defined into config.php
Now i need move to nginx but i don't understand how to replicate the apache rule, i tried:
location /foo {
alias /src/www/foo;
index index.html;
rewrite config.js config.php break;
}
But have internal server error
Thanks
Sorry, I write about last instead of break but didn't change it in a config code block. Updated an answer.
All nginx URIs starts with slash. Using rewrite config.js config.php you are rewriting an URI from /foo/config.js to config.php. That URI cannot be processed by nginx causing internal server error.
First argument of rewrite directive is always treated as a regex where dot matched any symbol. So your rewrite rule would match any string containing config*js substring. I don't think it is what you really want.
Second argument of rewrite directive is a whole new URI, not a substitution part of the string. To make a substitution use something like rewrite ^(.*)old-string(.*)$ $1new-string$2.
Since you are rewriting your request to PHP script you should force nginx to process new URI with a location where your PHP-FPM handler is defined. To do it you should use last flag instead of break one with the rewrite directive.
Summing all of this, you need something like
location /foo {
alias /src/www/foo;
index index.html;
rewrite ^/foo/config\.js$ /foo/config.php last;
}
One more note. As nginx documentation states:
When location matches the last part of the directive’s value:
location /images/ {
alias /data/w3/images/;
}
it is better to use the root directive instead:
location /images/ {
root /data/w3;
}
so it would be better to use root /src/www; instead of alias /src/www/foo; within this location block if that foo substrings are really equal.
Thanks for reply, in this way when i go to http://example,com/foo/config.js i see the file config.php
@hellb0y77 So you do not set up nginx to work with PHP-FPM (or any other PHP handler) yet? You should have php-fpm installed on your server and a special location ~ \.php$ { ... } defined to use it (this is the most common approach, there are other choices, NGINX Unit for example). Default nginx config should have an example for using PHP-FPM (commented by default). This is out of the scope of your question, check this one.
nginx work with php-fpm, I've tried to place a phpinfo file at the same path of config.php and work.
@hellb0y77 Do you have rewrite ... last;, not the rewrite ... break;? Maybe your browser cached the response?
yes rewrite ^/foo/config.js$ /foo/config.php last;
@hellb0y77 The only possible reason I can imagine is some other regex matching (location ~ ...), exact matching (location = ...) or "do-not-check-regex-if-match" (location ^~ ...) location takes priority over location ~ \.php { ... } with this URI (/foo/config.php). Otherwise it should work as expected.
| common-pile/stackexchange_filtered |
Basic auth preventing page from loading
Node Version: 7.8.0
Protractor Version: 5.1.2
Angular Version: 1.5.3
Browser(s): Chrome 59
Operating System and Version OSX 10.12.5
My site requires basic auth. This has been running fine as I pass the credentials through the home page url.
browser.get(`https://${username}:${password}@${hosts.baseURL}`);
However after todays auto update to Chrome 59 this stopped working. The page will not load. I get a blank page.
I found if I remove the credentials from the url the page will load fine but I must enter the credentials manually. Not sure the basic auth is the problem.
Anyone know the possible cause/solution for this?
Thanks.
UPDATE:
Turns out @mplungjan was correct. The flag to change the way basic auth worked in chrome was added in Chrome v58 and enforced in v59. This basically broke all my tests. After several ocomplaints it will be changed back in v61 and maybe v60. To get chrome working with basic auth the way it used to function prior to the change add the following to the chrome options:
chromeOptions: {
args: ['--disable-blink-features=BlockCredentialedSubresources']
}
I suggest you complain on the link I gave. They may change their minds :) Alternatively accept that they have your and your visitors' safety in mind
It's gone:
Evaluate dropping legacy and credentialed subresource requests.
Enable blocking of subresource requests whose URLs include credentials.
This patch flips the 'BlockCredentialedSubresources' flag to 'stable', and
ties it to a feature flag in //content that we can use as a kill switch if
it turns out that enterprise usage of the feature is higher than we hope
(the overall numbers still look reasonably low[1]).
Intent: https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/lx-U_JR2BF0
This change hit us pretty hard. We have a number of scenarios where we use Selenium to test different users accessing web applications over the corporate intranet with windows authentication. We use these tests to confirm the users have|don't have access to urls, panels on pages, etc.. Anyway, thanks for the information - it took awhile to figure out what the actual problem was and why it stopped working.
you may work around this by using a proxy such as browsermob-proxy to handle basic authentication.
Here are quick instructions to do so:
download and extract browsermob-proxy
configure protractor to use a proxy: in protractor.conf.js, add a proxy section to your capabilities, eg:
capabilities: {
browserName: 'chrome',
'chromeOptions': {
'args': ['disable-infobars=true'],
'prefs': {'credentials_enable_service': false}
},
'proxy': {
'proxyType': 'manual',
'httpProxy': 'localhost:8888',
'sslProxy': 'localhost:8888'
},
},
start and configure browsermob proxy before running your specs with protractor (8080 is the port used to control browsermob via its REST api, 8888 is the actual proxy port):
$ browsermob-proxy --use-littleproxy false
$ curl -s --request POST --url http://localhost:8080/proxy?port=8888
$ curl -s --request POST --url \
http://localhost:8080/proxy/8888/auth/basic/your.site.com \
--data '{"username":"yourUsername","password":"yourPassword"}' \
-H 'Content-type: application/json'
This should work nicely (it does for me), as long as you don't rely on websockets.
Note that you may also control browsermob-proxy from your scripts, using a node module such as browsermob-proxy-api.
I'm using the following workaround:
First I pass the credentials in the URL
browser.get(`https://${username}:${password}@${hosts.baseURL}`);
so at this point I'm authenticated.
Then I do a second call passing the URL without credentials
browser.get(`https://${hosts.baseURL}`);
So in the end I have:
browser.get(`https://${username}:${password}@${hosts.baseURL}`);
browser.get(`https://${hosts.baseURL}`);
Same thing it's possible with any testing framework (I'm using both Protractor and Codeception).
So for example in Codeception it would be, if the URL with auth credentials is defined in the .yml file:
$I->amOnPage('/');
$I->amOnUrl(`https://`.$baseURL);
Or just
$I->amOnUrl(`https://`.$username.`:`.$password.`@`.$baseURL);
$I->amOnUrl(`https://`.$baseURL);
I am trying to add disable-blink-features=BlockCredentialedSubresources to chromeOptions in my config.js and it file worked for me!
config.js:
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
capabilities: {
"browserName": 'chrome',
"chromeOptions": {
args:['--disable-blink-features=BlockCredentialedSubresources']
},
specs: ['filename.js']
}
};
In spec:
browser.get('http://username:password@domain.com');
I made sure to keep credentials with URL. I tried to take it out at first and it failed, then added back in and worked great.
| common-pile/stackexchange_filtered |
how can I combine await.WhenAny() with GetAwaiter extension method
I want to await a button.click() event. For that created an extension GetAwaiter() method:
public static class ButtonAwaiterExtensions
{
public static ButtonAwaiter GetAwaiter(this Button button)
{
return new ButtonAwaiter()
{
Button = button
};
}
public class ButtonAwaiter : INotifyCompletion
{
public bool IsCompleted
{
get { return false; }
}
public void GetResult()
{
}
public Button? Button { get; set; }
public void OnCompleted(Action continuation)
{
RoutedEventHandler? h = null;
h = (o, e) =>
{
Button!.Click -= h;
continuation();
};
Button!.Click += h;
}
}
}
(I found it here: http://blog.roboblob.com/2014/10/23/awaiting-for-that-button-click/)
With that I can await the Button1.Click() event directly with await Button1; which is great.
BUT I couldn't figure out how to combine this awaitable with someting like await Task.WhenAny()
I tried
await Task.WhenAny(Button1, Button2);
It will tell me that it "cannot convert from Button to Task".
I thougt I found the solution here:
Using `Task.WhenAll` with `INotifyCompletion` by just adding a method
public static async Task GetTask()
{
await this;
}
to my ButtonAwaiterExtensions class, but the keyword this cannot be used in my static class.
I cannot figure out what to return in the method or generally how to await any Button.Click(). Any ideas?
I recommend reading about Tasks and asynchronous programming in C#. What you want to achieve could be done using the Task Asynchronous Pattern: https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/implementing-the-task-based-asynchronous-pattern. What you cannot do is await methods that do not return asynchronous Tasks.
Try creating an additional extension method async Task AsTask(this Button self) => await self and use it like await Task.WhenAny(button1.AsTask(), button2.AsTask()). Maybe this works.
My question to you: What do you actually want to achieve? Why do you want to await the execution of the Button.click() method?
@ewerspej this is meant for creating tutorials on the UI. Another example is found in the same blog as mentioned above (BUT also with a strict click-order which I do not want): http://blog.roboblob.com/2014/10/25/using-await-to-build-cool-ui-tutorials/
So you need to make then Click handlers awaitable, that might be possible in the way that @SebastianSchumann provided in the comment above. What you might want to do in that case is use await Task.WhenAll(new List<Task>{ button1.AsTask(), button2.AsTask() } ); instead of WhenAny(). WhenAll() will only return once all Tasks have completed.
@SebastianSchumann thank you. That worked. Small adjustment, great success! :-)
@ewerspej Task.WhenAny oder Task.WhenAll work directly without new List<Task>. Not necessary. Thank you anyway
Thanks to Sebastian Schumann comment (how can I combine await.WhenAny() with GetAwaiter extension method) I solved my problem by adding another extension method directly to my ButtonAwaiterExtensions class:
public async static Task AsTask(this Button self) => await self;
Complete solution:
public static class ButtonAwaiterExtensions
{
public static ButtonAwaiter GetAwaiter(this Button button)
{
return new ButtonAwaiter()
{
Button = button
};
}
public class ButtonAwaiter : INotifyCompletion
{
public bool IsCompleted
{
get { return false; }
}
public void GetResult()
{
}
public Button? Button { get; set; }
public void OnCompleted(Action continuation)
{
RoutedEventHandler? h = null;
h = (o, e) =>
{
Button!.Click -= h;
continuation();
};
Button!.Click += h;
}
}
public async static Task AsTask(this Button self) => await self;
}
An alternative (little shorter) Implementation for GetAwaiter might be:
public static TaskAwaiter GetAwaiter(this Button self)
{
ArgumentNullException.ThrowIfNull(self);
TaskCompletionSource tcs = new();
self.Click += OnClick;
return tcs.Task.GetAwaiter();
void OnClick(object sender, EventArgs args)
{
self.Click -= OnClick;
tcs.SetResult();
}
}
@SebastianSchuhmann thank you for the shorter version. Works flawless :-)
@TheodorZoulias Thx for the simplifications - but why did you remove the question mark from object sender? The EventHandler enforces the sender to be nullable and if we build our projects with all warnings as errors no project will build without that question mark.
@SebastianSchumann as far as I know most projects are compiled without #nullable enable, and the question marks generate warnings in those projects. But if you prefer then you could edit the question mark back.
| common-pile/stackexchange_filtered |
Nesting for loops in batch file
In a batch file I have 2 for loops like this
for /f "tokens=1 delims=_" %%k in (%CurrentDirec%\list.txt) do (
for /f "tokens=1" %%l in (%cd%\pragma.txt) do (
SourceFile.bat %%k %filenamecount% %%l
)
)
My question is I will be calling SourceFile.bat using the for loops but the looping should happen only for the number of times as the variable %%k in the first for statement. It should not call the source file.bat as a combination of both the for loops.
Now its calling both the sourcefile.bat as a combination of both the for loops.
And also I want to call the sourcefile.bat with 3 parameters.
Thanks in advance !!!
If you only want to call sourceFile.bat %%k times, why are you calling it inside the inner FOR loop? What are the contents of %cd%\pragma.txt?
what are typical contents of %%k and %%l ? and for a typical value of each, what is the invocation of sourcefile.bat you want to achieve?
| common-pile/stackexchange_filtered |
declare inside a bash funcion not working as expected with associative arrays
I declare an associative array:
$ declare -A dikv
Initialize it with some key/value pairs:
$ dikv=( ["k1"]="v1" ["k2"]="v2" ["k3"]="v3" ["k4"]="v4")
Then I can save the contents to a file:
$ declare -p dikv > /tmp/dikv.saved
This is the content of /tmp/dikv.saved:
$ cat /tmp/dikv.saved
declare -A dikv=([k4]="v4" [k1]="v1" [k2]="v2" [k3]="v3" )
Now, in a new shell environment, I can load the saved associative array:
$ source /tmp/dikv.saved
And the content is properly accesible:
$ echo "${!dikv[@]}"
k4 k1 k2 k3
$ echo "${dikv[@]}"
v4 v1 v2 v3
This works as expected, nice.
Now I want to do exactly the same but using a bash function:
#! /bin/bash
declare -A dikv
backup_dictionary()
{
local -n dict_ref=$1
FILE=$2
echo "${!dict_ref[@]}"
echo "${dict_ref[@]}"
declare -p dict_ref > $FILE
}
dikv=( ["k1"]="v1" ["k2"]="v2" ["k3"]="v3" ["k4"]="v4")
backup_dictionary dikv /tmp/dikv.saved
As you can see, I pass the associative array to the function using local -n. When I run this code, the echo's inside the function print the content of the associative array properly. So, as far as I understand, the associative array has been properly passed as argument.
However, this statement is not working as expected:
$ declare -p dict_ref > $FILE
This is the content of $FILE:
$ cat /tmp/dikv.saved
declare -n dict_ref="dikv"
I expected to see something like this:
dikv=( ["k1"]="v1" ["k2"]="v2" ["k3"]="v3" ["k4"]="v4")
As it happens when not using a bash funcion. Can you explain what happens here? And what should be the proper way to fix this? Thanks!
https://stackoverflow.com/a/8879444/5291015
the associative array has been properly passed as argument ... No. The name of the array has been properly passed as argument. The array itself is still global; you are accessing it indirectly via its name. Think of a pointer in C: If you pass a pointer to some data structure to a function, this does not pass the data structure itself.
@user1934428 thanks for the explanation, that makes sense.
Your dict_ref stores the string dikv. Hence if you do a declare -p dict_ref, I would expect to see as output something like
declare -n dict_ref=dikv
Note that dereferencing (due to the -n declaration) occurs during parameter expansion, i.e. when you do a $dict_ref.
You could do a
declare -p "$1" >$FILE
| common-pile/stackexchange_filtered |
Completing the cal, sum the vlookup value
As you can see that the value in column Amount in the first image is manually put into it. I would like to use VBA to do it automatically.
Table B546789 is one of the worker:
PriceList shown the amount of each code item:
Code:
Sub FINDSAL()
Dim E_name() As String
Dim Sal As String
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("PriceList")
SourceString = Worksheets("B546789").Range("B2").Value
E_name() = Split(SourceString, ",")
Sal = Application.WorksheetFunction.VLookup(E_name, Worksheets("PriceList").Range("A2:B7"), 2, False)
End Sub
What have you tried so far? Can you share the code?
Sub FINDSAL()
Dim E_name() As String
Dim Sal As String
SourceString = Worksheets("B546789").Range("B2").Value
E_name() = Split(SourceString, ",")
Sal = Application.WorksheetFunction.VLookup(E_name, Worksheets("PriceList").Range("A2:B7"), 2, False)
End Sub
I know that is not yet complete, but i have no idea how to do it. please help on this matter, seems complicated than vlookup as multiple sroucestring.
thank you Ashleedawg for edit the thread.
Welcome to Stack Overflow! Here's a video to get you started with VLookUp: Office.com: Excel 2013 training VLOOKUP — When and how to use it ...Please take a few minutes to check out the [tour] and there are also important tips in "[ask]" as well as tips about providing examples at "[mcve]". We like to see that some effort has been made in finding a solution before asking for help (on a specific problem), so please includes details about what you've tried so far.
Any hints that when i put below code to VBA ThisWorkbook, work fine. But assign this Marco to a button, it will crash when i run. do you know why?
Sub test()
Dim a As Long, b As Long, ttl As Double, ttlerror As String
Dim vals As Variant, pc As Variant
Dim sh As Worksheet
Dim WshtNames As Variant
Dim WshtNameCrnt As Variant
Set sh = ActiveWorkbook.Sheets("PriceList")
WshtNames = Array("B54546", "B87987")
For Each WshtNameCrnt In WshtNames
With Worksheets(WshtNameCrnt)
For b = 8 To [D8].End(xlDown).Row
ttl = 0
ttlerror = ""
vals = Split(.Cells(b, "D").Value2, Chr(44))
For a = LBound(vals) To UBound(vals)
pc = Application.Match(vals(a), sh.Columns(1), 0)
If Not IsError(pc) Then
ttl = ttl + sh.Cells(pc, "B").Value2
End If
Next a
.Cells(b, "E") = ttl
.Cells(b, "F") = ttlerror
Next b
End With
Next WshtNameCrnt
End Sub
the issue maybe related to this "For b = 8 To [D8].End(xlDown).Row", it only happen when i use the button feature.
Image here
i just want from the D8 to end of the designed table.
| common-pile/stackexchange_filtered |
Most significant present-day AI developments?
What do you consider the most significant progress / breakthroughs in real world applications of present-day AI research? (including, but not limited to: machine learning, statistical data processing, and other disciplines spinned off from AI).
Please spare / do not want: ramblings about AI winters / disappointment;
Do want: links, and pointers to concrete real-world applications.
I think the most significant breakthrough is that real world consumer applications actually utilize AI routinely today. It has become common, and is not just mere curiosity of academic research and special applications any more, like it was ten years ago. Some examples:
Speech and text recognition (e.g. iPhone).
Face recognition in digital cameras.
Search engines.
Email spam filtering.
Automatic gearboxes of cars.
Games.
etc.
It's all around us! :-)
You left out its use in Medicine which I think is a pretty big one so I'd add:
Diagnosis assistance
Pharma research
as per @mad-j game bots A.I. has come a long way: link to bots get smart
alt text http://www.spectrum.ieee.org/images/dec08/images/bot01.jpg
Actually, AI research is having a renaissance and has been for the past 5-8 years or so.
Back when neural networks were all the rage in the 70s and 80s, they were showing such promise in solving simple tasks that people's hopes were sky-high for the whole field of AI. Then, when it turned out to be very difficult to move on from the very simple tasks to real-world problems like language acquisition, a lot of people became disillusioned. Until recently, that is.
I am not the best person to ask -- being no AI expert -- but I believe some of the most promising areas are:
Semantic search and data mining (including text classification)
Statistical machine translation
'Real intelligence' HTMs (read Jeff Hawkins' On Intelligence)
Relevance / Recommendation engines (essentially a hybrid of data mining and network analysis)
Visual object recognition
I think real/strong AI has lost it way, for decades the speaking/understanding computer was going to be available 'in the next 5 years'. Then we ended up with Dragon (no connection) which doesn't understand anything, it's a clever microphone, and it's a while since I've heard anything about AI - it's just not mainstream anymore, because it is too damn hard. One thing I think has been proven beyond doubt real AI, as in thinking machine, Turing Test passing AI - is still a (very) long way away. Don't get me wrong, there's tons of good research going on, but we'll have to wait 200-500 years for a result.
My gut feel is they'll be some interesting stuff coming out of massively parallel systems, especially ones built with really simple nodes. And if I had to point at a single AI breakthrough I'd be looking at spin offs from the nano-tech field, getting really small and seeing what cells in the brain are up to - science fiction it is, but we'll crack it one day.
Although I agree with you, the poster explicitly requested no "ramblings about AI winters / disappointment".
ahh - I think my answer was the cause of messer Dragon's edit to exclude the AI winter - a next phrase don't you think?
| common-pile/stackexchange_filtered |
storyblok-assets-cleanup – The script doesn't create a assets_backup folder
I am not sure exactly how to debug this or find a solution.
Basically, with the help of this script, I am scanning through 60.000 + assets to make a backup and potentially find which ones are not used and can be deleted. Scanning through this amount of items takes about 7 hours. Now, I noticed that after 2 hours, there is still no assets_backup folder created, even with the flag --backup activated.
I set up a virtual environment as suggested, and it creates a cache folder in the local directory but no backup unfortunately. Any ideas how to find the reason for this?
Here is the script:
https://github.com/significa/storyblok-assets-cleanup?tab=readme-ov-file
| common-pile/stackexchange_filtered |
Offset in a struct with bit fields
If we have a struct with bit fields, then how are the subsequent members aligned in the struct? Consider the following code:
struct A{
int a:1;
char b; // at offset 1
};
struct B{
int a:16;
int b: 17;
char c; // at offset 7
};
printf("Size of A: %d\n", (int)sizeof(struct A));
printf("Offset of b in A: %d\n", (int)offsetof(struct A, b));
printf("Size of B: %d\n", (int)sizeof(struct B));
printf("Offset of c in B: %d\n", (int)offsetof(struct B, c));
Output:
Size of A: 4
Offset of b in A: 1
Size of B: 8
Offset of c in B: 7
Here, in the first case, b is allocated just in the 2nd byte of the struct without any padding. But, in the 2nd case, when bit fields overflow 4 bytes, c is allocated in the last (8th) byte.
What is happening in the 2nd case? What is the rule for padding in structs involving bit fields in general?
The rule in general is: the compiler can pad and align things in any way it wants. All compilers offer implementation-defined extensions to control how fields get packed, and you should use them if you care about it.
Possible duplicate of Does the type of bitfield affect structure alignement and also read this.
how are the subsequent members aligned in the struct?
Nobody knows. This is implementation-defined behavior and thus compiler-specific.
What is happening in the 2nd case?
The compiler may have added padding bytes or padding bits. Or the bit order of the struct might be different than you expect. The first item of the struct is not necessarily containing the MSB.
What is the rule for padding in structs involving bit fields in general?
The compiler is free to add any kind of padding bytes (and padding bits in a bit field), anywhere in the struct, as long as it isn't done at the very beginning of the struct.
Bit-fields are very poorly defined by the standard. They are essentially useless for anything else but chunks of boolean flags allocated at random places in memory. I would advise you to use bit-wise operators on plain integers instead. Then you get 100% deterministic, portable code.
Bit-wise operators on unsigned integers.
@ElchononEdelson Just so :)
I would take a small example. Hope this will make clear ::
Consider two structures :
struct {
char a;
int b;
char c;
} X;
Versus.
struct {
char a;
char b;
int c;
} Y;
A little more explanation regarding comments below:
All the below is not a 100%, but the common way the structs will be constructed in 32 bits system where int is 32 bits:
Struct X:
| | | | | | | | | | | | |
char pad pad pad ---------int---------- char pad pad pad = 12 bytes
struct Y:
| | | | | | | | |
char char pad pad ---------int---------- = 8 bytes
Thank you
Some reference ::
Data structure Alignment-wikipedia
| common-pile/stackexchange_filtered |
Tomcat 6 JSF/JSP filename configuration problem
I've a JSF app deploying from Eclipse Ganymede through Tomcat 6. The latter suggests JSP 2.0. I'm using Sun RI JSF implementation and RichFaces 3.3.2SR1.
My index.jsp file on request from the browser causes this error to the console:
05-Mar-2010 12:04:41 org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /index.jsp(35,41) #{..} is not allowed in template text
...
OK, I've seen various other posts on this subject including incompatibilities of versions of the various jars/taglibs/syntaxes etc.
The index.jsp is called using http://localhost:8989/myapp/index.jsf (or .jsp - gives the same error), and contains
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
which should be alright as facelets is in Mojarra 2.0.2FCS which I'm using. I seem to have to use the above syntax rather than eg. <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> as the facelets URI causes Eclipse to say Cannot find the tag library descriptor for "http://java.sun.com/jsf/facelets".
Is my problem to do with the way I'm listing these tags?
My Ant build file refers to these Tomcat jars:
<fileset dir="${cliTomcatlib}">
<include name="servlet-api.jar" />
<include name="jsp-api.jar" />
</fileset>
so I'm stumped as to how I can get round this error. It feels like it would be a simple fix but as I'm using latest jars that should be compatible with JSP 2.0, I'm wondering why I'm getting this error. JSF
EDIT
In response to BalusC's wisdom, I corrected two references to external jsp files and renamed all .jsp to .xhtml. I remembered to also update my faces-config.xml.
Redeploying now errors with a large and repeating error when the index.xhtml is requested like this:
05-Mar-2010 13:29:26 org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet Faces Servlet threw exception
java.lang.StackOverflowError
at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:824)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:216)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:544)
...
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:216)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:544)
at com.sun.faces.context.ExternalContextImpl.getSession(ExternalContextImpl.java:151)
at javax.faces.application.ViewHandler.calculateCharacterEncoding(ViewHandler.java:242)
at javax.faces.application.ViewHandler.initView(ViewHandler.java:458)
at com.sun.faces.application.view.MultiViewHandler.initView(MultiViewHandler.java:106)
at org.ajax4jsf.application.ViewHandlerWrapper.initView(ViewHandlerWrapper.java:128)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:109)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
which I admit isn't very illuminatory other than the first few lines of the stack trace are repeated so many times I had to change the console buffer on Eclipse. I'd be overflowing with gratitude if anyone has seen this before.
Mark
org.apache.jasper.JasperException: /index.jsp(35,41) #{..} is not allowed in template text
Unified EL is indeed not allowed in template text in JSP. It's only allowed in Facelets.
The index.jsp is called using http://localhost:8989/myapp/index.jsf (or .jsp - gives the same error) and contains
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
You're mixing up JSP with Facelets. You can and should not to that. Those are two distinct view technologies. Use the one or other. JSP is for the <%@taglib %> stuff and Facelets is XHTML oriented with <html xmlns> and <ui:xxx> stuff. For JSF 2.0 you're supposed to use Facelets. Rename all files from *.jsp to *.xhtml and replace and get rid of any <% %> and <jsp:xxx> stuff.
To learn more about Facelets, start here in the Java EE 6 tutorial part II chapter 5. If you'd like to fall back to the ancient JSP instead of Facelets for JSF 2.0, then you'll need to reconfigure the view handler in JSF.
Apart from the problem, Tomcat 6.0 is by the way JSP 2.1, not JSP 2.0.
Update: the StackOverflowError on getSession() indicates an infinite recursion in the servlet/filter mappings. How is your FacesServlet mapped? It should be mapped to listen on an url-pattern of *.jsf, not *.xhtml. Otherwise it will call itself recursively. Please consult/refer the JSF 2.0 books/tutorials/documentation closely how to configure it properly.
BalusC, see my question update. Thanks for your help on this one.
The key words in this answer are 'consult', 'documentation', 'configure' and 'properly'. Thanks goes to BalusC for the slap.
Add JSF impl jars to Tomcat's lib or your app lib and try again.
See this for more.
Tomcat doesn't ship with any JSF impl (unless the OP unnecessarily put them there, indeed).
Thanks for pointing out. I mostly work with GlassFish and JBoss.
| common-pile/stackexchange_filtered |
Pass variables from bokeh to JS via CustomJS
In the bokeh example http://docs.bokeh.org/en/latest/docs/user_guide/interaction/callbacks.html#customjs-for-hover
the dictonary "links" is passed to the JS by adding it at the end of the code block with:
....
""" % links
Is it possible to pass over two variables and what would the syntax look like?
I tried different versions like
""" % links,myvar
""" % ('links','myvar')
""" % links, % myvar
but they all create errors or do not work.
I also found this
Bokeh: pass vars to CustomJS for Widgets
but perhaps there is an update?
Thx
I'd suggest looking into general python string formatting (there isn't anything Bokeh-specific within that example).
But some options would be
JS_CODE = """
var variable_1 = %s
var variable_2 = %s
""" % (var1, var2)
or
JS_CODE = """
var variable_1 = {0}
var variable_2 = {1}
""".format(var1, var2)
or to set as a list
JS_CODE = """
var list_variable = %s
""".format(str(list_var))
docs: https://docs.python.org/2/library/string.html#formatexamples
| common-pile/stackexchange_filtered |
Android studio error while adding mopub sdk
I am trying to add the Mopub sdk to my android app.
I unzipped the SDK, and went to Project Structure to select import a New Module. When I chose the unzipped folder, the Finish button is grayed out, and there is an error saying 'Select Modules to import'
I tried following this post but i get this error in build.gradle file in the mopub-sdk
Error:(8) A problem occurred evaluating project ':mopub-sdk'.
Failed to apply plugin [id 'org.robolectric']
Plugin with id 'org.robolectric' not found.
how do i get around this? Im using Android studio 1.2.2
https://github.com/mopub/mopub-android-sdk/archive/v3.9.0.zip
just try archived sdk, it works // sorry I don't enough reputation to post image
Now i dont get the error saying 'Select Modules to import'. The sdk imports fine but Im still getting the Plugin with id 'org.robolectric' not found error
| common-pile/stackexchange_filtered |
How to select all characters to the right of a specific character in a string - PHP
I spent a long time trying to figure this out! How do I select all the characters to the right of a specific character in a string when I don't know how many characters there will be?
the function strstr does just that
You can also do:
$str = 'some_long_string';
echo explode( '_', $str, 2)[1]; // long_string
// find the position of the first occurrence of the char you're looking for
$pos = strpos($string, $char);
// cut the string from that point
$result = substr($string, $pos + 1);
Probably want to substr on $pos+1 to get only right of that character.
And now for multibyte characters! UTF-8 for the win!
I'm not sure this would fit your needs, but :
$string = explode(',','I dont know how to, get this part of the text');
Wouldn't $string[1] always be the right side of the delimiter? Unless you have more than one of the same in the string... sorry if it's not what you're looking for.
Yes! You are correct! This is exactly what I was looking for. Strange I couldn't find it with my searches. :)
This fails when you have more than one of the delimiter in the string. You need to specify the limit parameter as I did in my answer.
Just use strstr
$data = 'Some#Ramdom#String';
$find = "#" ;
$string = substr(strstr($data,$find),strlen($find));
echo $string;
Output
Ramdom#String
Use strpos to find the position of the specific character, and then use substr to grab all the characters after it.
You have to use substr with a negative starting integer
$startingCharacter = 'i';
$searchString = 'my test string';
$positionFromEnd = strlen($searchString)
- strpos($searchString, $startingCharacter);
$result = substr($searchString, ($positionFromEnd)*-1);
or in a function:
function strRightFromChar($char, $string) {
$positionFromEnd = strlen($string) - strpos($string, $char);
$result = substr($string, ($positionFromEnd)*-1);
return $result;
}
echo strRightFromChar('te', 'my test string');
(Note that you can search for a group of characters as well)
Assuming I want to select all characters to the right of the first underscore in my string:
$stringLength = strlen($string_I_want_to_strip);
$limiterPos = strpos($string_I_want_to_strip, "_");
$reversePos = $limiterPos - $stringLength + 1;
$charsToTheRight = substr($string_I_want_to_strip, $reversePos, $limiterPos);
I put this into production already because it does exactly what I want... It selects all characters to the right of a delimiter. The better method is "explode()" however.
| common-pile/stackexchange_filtered |
Trying to Share from both Facebook and Twitter in a Row
I have the following code:
- (IBAction)shareButton
{
if(self.isTwitter.on)
[self shareTwitter];
if(self.isFacebook.on)
[self shareFacebook];
}
The methods called work separately. If I try to run them together, however, the Twitter method runs, but then I get a warning:
Warning: Attempt to present <SLFacebookComposeViewController: 0x9471720> on <ViewController: 0xa193f30> while a presentation is in progress!
Is there a way to detect if a "presentation is in progress" (or rather, if a share sheet is already presented to the user) and wait until it's finished?
What you want to do is to wait until the user is finished with the twitter post before displaying the facebook dialog. You can code it so that the facebook dialog is displayed in the twitter dialog's completion handler:
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) //check if Twitter Account is linked
{
mySLComposerSheet = [[SLComposeViewController alloc] init]; //initiate the Social Controller
mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter]; //Tell him with what social plattform to use it, e.g. facebook or twitter
[mySLComposerSheet setInitialText:[NSString stringWithFormat:@"Test",mySLComposerSheet.serviceType]]; //the message you want to post
[mySLComposerSheet addImage:yourimage]; //an image you could post
[self presentViewController:mySLComposerSheet animated:YES completion:nil];
}
[mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result) {
// dismiss the Tweet Sheet
dispatch_async(dispatch_get_main_queue(), ^{
[self dismissViewControllerAnimated:NO completion:^{
[self shareFacebook];
}];
});
}];
EDIT: You will need to dismiss the controller first, and call the facebook method AFTER the controller has been dismissed.. You need to dismiss the controller on the main thread because the completion handler is not guaranteed to be called on the main thread.
However, from a UX perspective, it would be quite cumbersome for the user to be forced to share to twitter and Facebook at the same time. Perhaps there's a better way to do this sharing?
Unfortunately, that didn't work. Instead, I now get the warning: Warning: Attempt to present <SLFacebookComposeViewController: 0xa139850> on <ViewController: 0xa41b6c0> which is already presenting <SLTwitterComposeViewController: 0x10e09730>
There's a reason I want to do it this way. Thanks for your help, the edited version worked!
I wouldn't recommend doing this. But you can use NSOperationQueue.
| common-pile/stackexchange_filtered |
Expand single value extended properties on events delta query?
Should it be possible to provide an $expand=singleValueExtendedProperties... query parameter on an events delta request? My approach returns an error that I wasn't quite expecting.
The request looks like this:
API:
https://graph.microsoft.com/v1.0
RESOURCE:
me/calendarView/delta
PARAMS:
startDateTime: 2020-07-01T00:00:00Z
endDateTime: 2021-12-31T23:59:59Z
$expand: singleValueExtendedProperties($filter=id eq 'Boolean {00062002-0000-0000-c000-000000000046} Id 0x00008229')
The request fails, returning this message in the body:
Parsing OData Select and Expand failed: Value cannot be null.
Parameter name: initialState
It's unclear which value that is referring to, though given that the error does not happen when omitting the $expand I suspect it has something to do with trying to expand in a delta query, or specifying an expand on this/andy extended property.
Omitting the $expand results in a successful response, and I am omitting the $deltatoken parameter to create a new stream (because existing streams are not encoded with the $expand).
You'll nice that the expand is on a non-string type MAPI property, specifically it is the Invited property. It's explicitly documented that you cannot $select properties that are not tracked, but it doesn't mention whether or not they can be included in the delta response itself.
Is this supposed to be possible? If so, can you point in my the right direction for formatting this request? Thanks!
Regarding this adjacent question that has already been asked. Seems out of date per the following.
The Get delta for Messages explicitly states that $expand is supported, but the Get delta for Events does not explicitly state anything about $expand, or any OData at all, it just states that $select is not supported.
If there is some hidden restriction, can it just be explicitly documented in the events delta documentation?
The error you are receiving is actually a bug in the library the service is using, see this issue and that issue.
You should be receiving an error saying that the request is not supported.
Even when the parsing bug gets fixed, it's unlikely to work as schema and open extensions are stored in another system than the resource and providing a unique delta token containing a watermark valid for both systems is not implemented today. You can request support for it on uservoice.
"[...] providing a unique delta token containing a watermark valid for both systems is not implemented today" got it, was already aware and prepared for change tracking not to work here, and I think that's fair. Thanks for clarifying that this should actually just be considered unsupported, that answers a big open question about an implementation plan I am working on! Cheers!
| common-pile/stackexchange_filtered |
How do you determine if a JDBC Connection was retrieved from a JTA enabled DataSource or straight JDBC?
I'm using a vendor API to obtain a JDBC connection to the application's database. The API works when running in the application server or when running in a stand-alone mode. I want to run a series of SQL statements in a single transaction. I'm fine with them occurring in the context of the JTA transaction if it exists. However, if it doesn't then I need to use the JDBC transaction demarcation methods. (Calling these methods on a JDBC connection that is participating in a JTA transaction causes a SQLException.)
So I need to be able to determine whether the Connection came from the JTA enabled DataSource or if it's just a straight JDBC connection.
Is there a straight forward way to make this determination?
Thanks!
Even if it's straight JDBC, you can have a JTA transaction enabled. Checking the autoCommit flag will NOT help in this regard. You can be in a transaction, distributed or otherwise, with autoCommit set to false. autoCommit set to true would tell you you're not in a distributed transaction but a value of false just means you won't auto-commit... it could be in any kind of transaction.
I think you're going to have to call UserTransaction.getStatus() and verify that it is not equal to Status.NoTransaction(). This would tell you if you're in a JTA transaction.
What thilo says does make sense.
Otherwise, Not sure of a straight way BUT I will give you a "hack" way
write a BAD SQL which you know will give a DB exception.
That will result in a stack trace. From the stack trace, you can find out if it is a JTA derived connection or NOT ?
You could try to check the Connection's autoCommit flag to see if it is in a transaction (regardless of where it came from).
(Apparently, see the accepted answer, this does not work too well. I am not deleting this answer because the following still stands: )
But I think you should really modify your API to depend on external transactions exclusively. If you still want to support plain JDBC, wrap it into a separate API that just starts the transaction.
Update: Just re-read your question and saw that you are not providing an API, but want to use a container-managed connection. But still, can you just mandate (as part of your application's requirements) that JTA be in effect? If not, you could provide a configuration option to fall back to manually managed transactions. For such a critical feature it seems reasonable to require the proper configuration (as opposed to try to guess what would be appropriate).
Auto commit is a behaviour that says commit anyway it doesnt actually communicate whther something is XA or transacted etc.
| common-pile/stackexchange_filtered |
cannot convert varchar to float in sql
These are my 2 tables
CREATE TABLE [dbo].[dailyRate](
[SYMBOL] [varchar](50) NULL,
[SERIES] [varchar](50) NULL,
[OPENPRICE] [varchar](50) NULL,
[HIGHPRICE] [varchar](50) NULL,
[LOWPRICE] [varchar](50) NULL,
[CLOSEPRICE] [varchar](50) NULL,
[LASTPRICE] [varchar](50) NULL,
[PREVCLOSE] [varchar](50) NULL,
[TOTTRDQTY] [varchar](50) NULL,
[TOTTRDVAL] [varchar](50) NULL,
[TIMESTAMPDAY] [varchar](50) NULL,
[TOTALTRADES] [varchar](50) NULL,
[ISIN] [varchar](50) NULL
)
CREATE TABLE [dbo].[cmpDailyRate](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[SYMBOL] [varchar](50) NULL,
[SERIES] [varchar](50) NULL,
[OPENPRICE] [decimal](18, 4) NULL,
[HIGHPRICE] [decimal](18, 4) NULL,
[LOWPRICE] [decimal](18, 4) NULL,
[CLOSEPRICE] [decimal](18, 4) NULL,
[LASTPRICE] [decimal](18, 4) NULL,
[PREVCLOSE] [decimal](18, 4) NULL,
[TOTTRDQTY] [bigint] NULL,
[TOTTRDVAL] [decimal](18, 4) NULL,
[TIMESTAMPDAY] [smalldatetime] NULL,
[TOTALTRADES] [bigint] NULL,
[ISIN] [varchar](50) NULL,
[M_Avg] [decimal](18, 4) NULL
)
this is my insert query to fetch data from table to another with casting
Collapse | Copy Code
INSERT into [Stock].[dbo].[cmpDailyRate]
SELECT [SYMBOL],[SERIES],Str([OPENPRICE], 18,4),Str([HIGHPRICE],18,4),
Str([LOWPRICE],18,4),Str([CLOSEPRICE],18,4),Str([LASTPRICE],18,4),Str([PREVCLOSE],18,4),convert(bigint,[TOTTRDQTY]),Str([TOTTRDVAL],18,4),
convert(date, [TIMESTAMPDAY], 105),convert(bigint,[TOTALTRADES]),[ISIN],null
FROM [Stock].[dbo].[DailyRate]
This query runs perfectly in SQL Server 2005, but it's causing errors in SQL Server 2008 (above query run also in SQL Server 2008 when installed; error arise in last few days)
Error :
Error cannot convert varchar to float
What to do?
Check your data for invalid values
You don't have a WHERE filter in your example, but I'm curious if you do in your code. If you do, or if DailyRate gets truncated and refilled, you may get the error seemingly randomly if you're getting invalid values in your data. The case statement below is probably the safer approach.
One of your rows contains invalid data in the columns you are doing the float conversion (Str) on. Use the following strategy to work out which:
SELECT *
FROM [dailyRate]
WHERE IsNumeric([OPENPRICE]) = 0
OR IsNumeric([HIGHPRICE]) = 0
etc etc.
I did suggest a AND instead of OR
@Praveen : An AND would only help if multiple values were incorrect on the same row. The original query will fail if ANY column contains an incorrect value.
where and isnumeric(...) are not sufficient - sql may (and often does) convert values before applying where condition. case isnumeric(...) then ... else ... end will do the trick.
@Arvo : In the OP's example. How could SQL auto convert a value to a float and return IsNumeric() = 1 for a value that isn't a valid? What would the result be?
Sorry, I misread something (I somehow thought about conversion without errors). For just checking invalid values isnumeric() is sufficient of course.
Except of course that there are values for which ISNUMERIC() will return 1 but that which cannot be converted to float.
An example of @Damien_The_Unbeliever's point: print isnumeric('$1') ; print cast('$1' as float) results in 1 \n Msg 8114, Level 16, State 5, Line 1 \n Error converting data type varchar to float.
If you do not want to filter out data, a CASE statement might work better for you.
SELECT CASE
WHEN IsNumeric([OPENPRICE]) = 1 THEN [OPENPRICE]
ELSE NULL -- or 0 or whatever
END AS OPENPRICE,
CASE
WHEN IsNumeric([HIGHPRICE]) = 1 THEN [HIGHPRICE]
ELSE NULL -- or 0 or whatever
END AS [HIGHPRICE]
FROM [dailyRate]
| common-pile/stackexchange_filtered |
How to set imageurl and get image height and width dynamiclly in C#
Here is the image which i want to set image url and find the height and width of this image dynamically.
<asp:Image ID="imgLogo" runat="server"/>
//Assign the image path.
string Path= Server.MapPath("~/Images/testImage.jpg")
System.Drawing.Bitmap img = new System.Drawing.Bitmap(Path);
//Get the image height and width.
int height=0, width=0;
height = img.Height;
width = img.Width;
What is your question? What is your problem with this code?
What problem or error are you getting?
You have to use explicit conversion were we specifically ask the compiler to convert the value into another data type.
string Path= Server.MapPath("~/Images/testImage.jpg")
System.Drawing.Bitmap img = new System.Drawing.Bitmap(Path);
int height = (int)img.Height;
int width = (int)img.Width;
| common-pile/stackexchange_filtered |
Error building Player: IOException: Failed to Move File
I keep getting this error when I try to use my .aar plugin created in android studio on Unity 3d
Error building Player: IOException: Failed to Move File / Directory from 'Temp/StagingArea\android-libraries\app-release\classes.jar' to 'Temp/StagingArea\android-libraries\app-release\libs\classes.jar'.
Use provided scope in gradle.
https://sinking.in/blog/provided-scope-in-gradle/
dependencies
{
provided fileTree(dir: 'libs', include: ['*.jar'])
}
"provided" scope has now been replaced by "compileOnly".
You need to remove 'libs/classes.jar' in your aar(use your favorate archive manager, it's just ZIP file), since Unity will inject it by self. Unity will fail if there's already one.
I need that in my android plugin because I import com.unity3d.player.UnityPlayer;
If I don't use it, I cannot use UnityPlayer.UnitySendMessage() in java side.
Im working with the Unity-Editor and visual Studio. What did work for me was simply removing these files mentioned in the error log.The Editor managed to build after that on my android device. My game was running perfectly fine since then.
| common-pile/stackexchange_filtered |
Chrome sending entire element to screen reader when any change is made
At some point recently (I believe during the v80 update) Chrome has started sending the entire contents of an aria-live element to the screen reader whenever content is added. Previous to this, it used to only announce the additions. Firefox still works like it's supposed to, only announcing the additions to this element. I am testing using NVDA, but my users have reported the same behavior with JAWS as well. Here is some simple code to illustrate the behavior (you need to have a screen reader on to get the idea here).
<html>
<head>
<script>
function addtologinner()
{
document.getElementById('log').innerHTML += '<div><p>Event happened at ' + gettime() + '</p></div>';
}
function addtologappend()
{
var div = document.createElement('div');
div.innerHTML = '<p>Event happened at ' + gettime() + '</p>';
document.getElementById('log').appendChild(div);
}
function gettime()
{
return (new Date()).toJSON().slice(11,19);
}
</script>
</head>
<body>
<button onclick="addtologappend();">Append to Log</button>
<button onclick="addtologinner();">Add to innerHTML</button><br />
<div id="log" aria-live="polite" aria-atomic="false" aria-relevant="additions text" role="log"></div>
</body>
</html>
This was working previously in all major browsers, having the screen reading report only the changes, but my users reported this issue this week. Changing the values of the aria-atomic and aria-relevant attributes does nothing. It is as if Chrome is not respecting those attributes anymore, when it used to default to false/additions respectively. I have not had a chance to test in Edge or Safari, most of my users are using Chrome. Any ideas on how to work around this? I didn't find anything in the last patch notes for version 80 relating to this.
I forgot to mention, the reason there are two buttons on there is that when using the innerHTML += method, both browsers repeat the whole element. Which, kinda makes sense.
I can verify and created a bug: https://bugs.chromium.org/p/chromium/issues/detail?id=1067257
| common-pile/stackexchange_filtered |
Swift UI detect start and end of gesture
I want to use a long press gesture and detect when the user has been holding for 1 consecutive second, and I also want to detect when the user lets go of the screen. Currently the onChanged detects when the gesture begins and the onEnded fires after 1 second. So I can use the onEnded to detect when the user has been holding for 1 consecutive second. But how can I know when the user lets go?
Color.blue
.simultaneousGesture(LongPressGesture(minimumDuration: 1.0)
.onChanged { _ in
UIImpactFeedbackGenerator(style: .light).impactOccurred()
}
.onEnded { _ in
UIImpactFeedbackGenerator(style: .light).impactOccurred()
}
)
As you have found out, LongPressGesture ends when the time interval required to trigger it has elapsed, instead of when the user has lifted their finger. Therefore, it is unsuitable for detecting the finger lifting.
I would use a DragGesture instead. Its onChanged is called when the gesture starts, and its onEnded is called when the finger lifts. We can record the start time in onChanged, and end time in onEnded, and hence how long the user has been pressing down.
@State var touchDownTime: Date?
@State var impactTrigger = false
var body: some View {
Color.yellow
.simultaneousGesture(
DragGesture(minimumDistance: 0)
.onChanged({ value in
if touchDownTime == nil {
touchDownTime = value.time
impactTrigger.toggle()
print("Started")
}
})
.onEnded({ value in
if let touchDownTime,
value.time.timeIntervalSince(touchDownTime) >= 1 {
impactTrigger.toggle()
print("Ended")
}
self.touchDownTime = nil
})
)
.sensoryFeedback(.impact(weight: .light), trigger: impactTrigger)
}
Note that I have changed it to use sensoryFeedback to create the haptic feedback. If you are targeting an older version than iOS 17, using UIImpactFeedbackGenerator is fine too.
Note that unlike a LongPressGesture, which doesn't trigger when the user moves their finger too much after pressing down, DragGesture is still recognised if the finger moves. If this is undesirable, use the value.translation property to determine whether the finger has moved too much.
@State var shouldCancel = false
...
.onChanged({ value in
...
let threshold: CGFloat = 10 // decide a threshold
if hypot(value.translation.width, value.translation.height) > threshold {
shouldCancel = true
}
})
.onEnded({ value in
if let touchDownTime,
!shouldCancel, // <----
value.time.timeIntervalSince(touchDownTime) >= 1 {
impactTrigger.toggle()
print("Ended")
}
self.touchDownTime = nil
shouldCancel = false
})
| common-pile/stackexchange_filtered |
What are common design flaws of build-point game systems?
I'm designing my own RPG system and I want to avoid the most widely-recognized flaws, loopholes, and exploits that build-point character creation systems usually suffer from.
What are the most common ways players exploit point-based character creation and advancement systems?
So far I have precision based damage limited based on maximum build points so people can't just sink everything into that, and spell level access as well. Actions per round face a hard-and-fast cap at four (there's a base of two), and when switching between 'classes' (essentially just discounted rates on cost for a certain collection of abilities) there's a cost. How much should someone be able to max out their health? Mana? Weapon specialization? Two-weapon ability? I don't need an extensive list, just the most crucial game-breaking things.
My first play-test will be with my friend who is a notorious power-gamer and I'd like to already have the trivial loopholes tied off.
I can't give you a definitive list, but the immediate exploit I've seen, used, and inadvertently codified into my first BASIC chargen (on a CoCoII c. 1986) by proxy12 is the what I'll call the "mimeograph."3
The "mimeograph" is where having an otherwise optimized build in point spend, the next character is exactly the same as the first... to the point. Change the name, background, or other fluff detail, and the player is right back in the game.
1 the program would spit out the randomized or custom build and the player could just reuse the point spend manually, over and over, without ever returning to the source (figuratively and literally).
2 the game, Twilight:2000 1e by GDW
3 mimeograph does date me doesn't it. How many of us remember the pale blue/purple "dittos" from elementary school c. 1977?
I remember ....
TL;DR the whole is worth more than the sum of the parts; but point-buy systems only ever price out the parts.
The first rule of min-maxing is: certain abilities are worth more in combination than individually. For example, a powerful attack that leaves you vulnerable sounds like a fair trade-off. But if you are also invisible, then that mitigates the downside; so the powerful attack + invisibility together are more valuable than the individual prices would suggest.
The second rule of min-maxing is: trade non-combat abilities for combat abilities. This is why fighters dump Charisma. If your system allows this, expect it to happen, and expect this to be less fun. The combat-heavy PCs will have little to do outside of combat, and the ones who are great outside of combat will find fights boring. A little bit of trade-off is OK since players have different preferences, but if things become too uneven, most groups will not enjoy it.
The third rule of min-maxing is: Mitigate any disadvantages you have. (In a way this is a specialized application of the first rule.) For example, if you get points for lowering your speed but then buy teleport, or get points for having an enemy but then buy "untraceable," or be vulnerable to some damage type that you'll rarely get hit with (e.g. holy energy), or get points for a vow/compulsion to do something you want to do anyway ("compulsion: help the innocent", "vow: fight evil"). This is totally OK if the entire party is doing it! (See: GURPS.) In practice, some will get more free points than others.
In a class-based system, abilities are often packaged in such a way to minimize min-maxing. Like, in D&D 3.5/PF, if you want full sneak attack progression, you can't also play a fighter and get full attack progression. (Barring imbalanced Prestige Classes of course, which is why some people do not like PrCs.)
Point-buy systems let you take whatever you want and attempt to balance abilities with points that equate to the usefulness of the ability. This turns out to be very hard due to the first-rule of min-maxing. Point buy systems also allow the second rule of min-maxing in spades.
The best example I've seen of a point-buy system is Mutants & Masterminds because it very explicitly caps your attack/defense/damage/Toughness. It's very easy to hit the caps and very hard to get around them -- this puts the PCs on a very even footing, while still having points left over to spend on non-combat stuff. M&M also very clearly requires the GM to approve all characters to look out for players trying to get free points or side-step the caps. (For example, invisibility sidesteps the cap on defense by making you impossible to hit.)
Point 2 is easiest to deal with: Just limit the proportion of build points that can be spent on combat stuff. (Anima: Beyond Fantasy is a good example of this, though it's not purely a point-buy system.) Some games go even further, and have separate build point pools for both combat and social abilities.
Disadvantages that don't provide any disadvantage. For example, Taking the no-eyes disadvantage, then taking the ability to see without eyes.
Another example: Taking a wounded leg disadvantage, then taking the ability to fly 1 cm above the ground with perfect manoeuvrability, resulting in a net game of points.
A number of games (Champions I believe, and possibly GURPS) work around this by stating any disadvantage that is fully negated provides no points.
This is an complex flaw. I almost want to characterize disadvantages as something akin to proto-aspects a la Fate/Fudge. Consider that many disadvantages are taken to get more points ostensibly for in game, role-playing "pop." But they never get invoked, by player omission or referee distraction. Thus the advantages and disadvantages of the PC are like aspects that should be "taggable" (careful on using the mechanics, nouns, and verbs...I'm only drawing lines for clarity). "No point earn for disadvantages" or making them cost is nice, but somehow requiring use in RP is necessary too.
@javafueled; GURPS (explicitly in 3e relebook, and implicitly elsewhere) expects the GM to penalize a character who games the system to negate a disadvantage, by reducing earned character points if your disadvantage 'should' have affected the session: the minimaxer ends up worse off than the rest of the party.
With most point based system gamers tend to equate points with combat effectiveness. That a 400 point character is X times more effective than a 200 point character. Which in practice proves to be false. I could make a 400 point sage character with 90% of his points into knowledge skills who would be slaughtered by a 100 point fighter.
So the key thing is to come up with something that points represents. For example in GURPS 1 point in a skill represents 200 hours of instruction. Now GURPS doesn't apply this across the board as they make judgement calls on the relative utility of various options particularly for advantages particularly those used to build powers.
My recommendation that the varying point costs should reflect the premise of the genre or setting you are trying to emulate. Trying to build for utility or combat effectiveness will lead down a road of design toil unless you are creating a simplistic design. The more items a design has the more funky ways they can interact and it will quickly multiply beyond what resources you have.
By designing to a setting and genre you can make explicit WHY points are assigned the way they are. Magic is expensive because the game is about low fantasy, and so on. Also this approach naturally limits the work you need to do to balance the points cost of the various options.
A comment on disadvantages. There is no right way of doing this. In GURPS disadvantage, including ones like honesty, represent limitations on the scope of the character's ability to act. In contrast in HERO System disadvantages are a source of roleplaying complications. A subtle difference but it is why having allies in GURPS is an advantage and in HERO System a disadvantage.
Finally don't make points the sole means of creating NPCs/Monsters. In GURPS the advice of many is to just simply create the NPC or Monster with the desired elements without worry about the exact point cost. The problem is that there is little advice or aide on doing this this in the actual GURPS book.
+1. BESM (multi-genre anime game) deliberately created different skill costs for different genres, so that the most expensive skills are the ones that are most useful for the genre. Ranged Combat was expensive in, say, a game about war, but was dirt-cheap in a game about the relationships of high school students.
Be careful of buying extra actions-per-combat-round. You can easily hit the point where X points will give you 10% more damage on a particular attack, or you can spend X points to buy another action-per-round, which gets you much more.
One of my GURPS characters is now at a point where buying another point of DX or IQ gives more skill benefits than increasing all (those) skills individually. Doesn't mean I'm doing that (mostly because there's still a good reason to buy new skills or inrcease some specific skill quicker than waiting to get a stat increase)
Not as much of an exploit of build-point systems, but a weakness: when playing a build-point system, I've found that they require a lot of GM input, along with expert knowledge, to make balanced characters. I don't know if I've bought too much strength/damage/hit-points/magic/speed/other, or too little. It's very easy for inexperienced players to miss out on an important statistic, or inadvertently create glass cannons that have no staying power. It takes a lot more effort by the GM (and any other expert players) to ensure that all of the characters are viable.
Several point based systems I've played lack room for growth. This makes it hard to play a specialist.
I'm mostly talking about GURPS here, but it applies to my experience with WoD and to a lesser extent, Deadlands as well. When I play a character he usually has a significant amount of skill in something because I like playing characters who are competent at what they do. The problem with this is that if you start at the top, there's nowhere to go. In GURPS, if I have 18 in a skill and there are no penalties, there's no reason to ever buy the 19th point. In actual play there will be penalties, but you'll figure out what those are and stop there. There's almost always a sweet spot that you can reach to be effective and anything beyond that is just showing off.
What bothers me about this is that it rewards the generalist too much and lets the other characters catch up. I don't mind this from a power level perspective, but it bothers me when I try to have a character with a distinct niche. If I'm playing a specialist with nowhere to go in my specialty, by the end of the game I'm a generalist since all the other players have caught up. I want to feel like my character has gotten better at his favorite activity and the opposite happens in most point based games.
The one exception I've found is Dark Heresy. DH is a hybrid between point based and class based. Everyone gets a class and your class determines which skills and stats you can buy and how much they cost. This rewards the specialists without pigeon holing you too much and fixes the sweet spot problem I mentioned above, since each class will have its own set of sweet spots.
I find that all modifiers that tend to end up applying means I have a character with Guns(rifle) 19 and a rifle with an accuracy bonus of +6 and still end up having 14-15 as my target number.
There are two parts to this problem. The first is the difficulty of tasks not increasing as the game progresses, meaning that there's no reason to continue advancing a skill past the maximum effective level, and thus little reward for specialising. (Not all point-buy systems have non-scaling difficulties, but it is pretty common.) The second part of the problem is that there is no penalty for not specializing - and since the primary advantage of a point-buy system is not being bound to specific combinations of abilities, it's hard to do anything about it.
Having a top useful level is a limit to a design, but it doesn't have to be that way. There's a larger problem there when for some ability rating, the game designers and/or GM have not really thought out what the skill ranges mean, what sort of people should have what levels, and what the effects of great skill and great success is, etc. In GURPS there are often some good guidelines for this for some things (see contests of skill, too, if that applies), but for many skills, the GM should figure out these things for skills that are relevant.
Compare Legend of the Five Rings 1st/2nd Ed to 3rd and 4th. In the early editions, the points encouraged min/maxing to a nauseating degree. With 25 points, you could spend 8 for a trait which, yes, is a third of the points without disadvantages but provides a staggering bonus. Raise a single trait twice, and the XP you save (since it is scaled to level) is already earned back. Therefore, starting with a ring at two levels higher (maybe after a couple disads) provides you a large step in the direction of the next level of techniques, and you get to splash the XP you save into skill points left and right.
3rd and 4th corrected this by scaling even the creation points. Ultimately, in 4e the build points cost exactly the same as the XP with the caveat that they were "CP", and thus divisible. Where this becomes important is that you can say "You get a starting character plus X amount of XP to pad it", forcing them to make a balanced starting character because of (dis)ads.
Always be wary of min/maxing unless you want an extremely niche-based game.
Not a hole for a power-gamer or munchkin but every time I play a point-system game, I come up with a character concept that I think will be strong, put the numbers in places to back up my concept, and end up with a weakling that can be decimated by another character in one round.
Don't know how to fix that problem... I've been trying to figure out why this bites me EVERY POINT BASED SYSTEM I HAVE PLAYED. I create a fighter who gets beat up by the 98 pound weakling. It wouldn't be a problem if I sunk points in X attribute that I never use, but most of the time I end up using every stat on my sheet, and my character still gets turned into something resembling chunky-salsa.
EDIT:
GM Joe's comment brought to my attention that maybe I didn't answer from the perspective of blunting a munchkin/powergamer. If you have players with the same number of points and widely different power levels, then you have to either tailor the opponents to the powerful player, or the weak player. Tune to the munchkin, and the weaker character dies every combat. Tune to the weaker player and the munchkin gets bored/frustrated that they put all these points in powers they don't need to use.
I am not sure this will help a lot, but I'd like to give my 2cents anyway.
Are you trying to design a "generic" system? Like GURPS?
If not, maybe there are elements of the world universe that could be used to mitigate the min-max problems.
Usually minimaxing is mostly about combat (plus some niche cases like people putting a billions points in Force Power: Persuasion in a Star Wars game and then just converting everyone in an ally).
As others noted, in the thread, gamers tend to identify a winning combo of stats/skills, and then tend to repeat it ad-nauseam.
What if you could encourage a more balanced approach with in-game reasons?
I am thinking of stuff like CoC Sanity, Unknown Armies madness scales and Cyberpsychosis in old editions of Cyberpunk RPG.
I.e. introduce a mechanism that makes uber-powerful munchkin characters starting on the verge of psychosis, and if they go over the threshold they either become NPCs, or have to take some time off (like, in a Asylum) before adventuring again.
Bonus point: using non-combat skills helps relaxing and reduces the risk of going bonkers. So you need to buy (and use) some extra skills. Of course the better you are at these skills, the better results you will be able to roll (for example, as a painter... or cooking, etc.) and the more you will be able to take off from your Psychosis Index value.
Would this be too heavy-handed for you?
77IM got it right with the worst parts of build-point systems. Here's my suggestions:
Check the costs of the combinations and make them high enough to limit their effectiveness and desirability. And simply outlaw broken combinations.
If your game is a combat system this isn't a problem. It only becomes a problem if you want people to do non-combat things - and then make your non-combat rules a) boring (roll 3d6), b) exactly like combat and therefore its more effective and permanent to deal with a problem through combat and c) so cheap that you can buy combat and then throw a few half-points into diplomacy and charisma 'just in case'. Make non-combat rules effective, interesting and worthwhile to invest in.
NEVER allow player-defined disadvantages. "If it's not a disadvantage you don't get points for it!" is stupid. If it's not a disadvantage then DONT PUT IT IN THE GAME! Only put Disadvantages in that you want in the game and SPELL OUT every possible interaction. You can get away with allowing players choice if you list the choices EXPLICITLY and make sure you can live with every one of them. If you don't tell me my phobia can't be "fear of cheese" you deserve what you get...
If you give points for Disadvantages then either a) Make them so low that no one would want to take them except for role playing purposes or b) only give them out through extra experience.
Is this based on play experience, or game design experience?
| common-pile/stackexchange_filtered |
Capistrano 3.x capture output line by line
In Capistrano 2.x you could capture the output line by line using
run "ls -la" do |channel, stream, data|
puts data
end
This does not work in Capistrano 3.x, and the capture and execute commands do not seem to provide the same functionality.
Is there a way to replicate the 2.x behaviour in 3.x?
did you have a look at the stream method? http://rdoc.info/github/capistrano/capistrano/Capistrano/Configuration/Actions/Inspect#stream-instance_method
That seems to be a Capistrano 2.x method, it's not available on 3.x https://github.com/capistrano/capistrano/search?q=stream&ref=cmdform&type=Code . In 3.x it uses the sshkit methods as far as I can tell https://github.com/leehambley/sshkit/search?q=capture&type=Code
oh yeah, that's true. capistrano 3 is not "official" i guess
Huh, didn't know that. Just did a gem upgrade and it upgraded to 3.
well, i am not sure, just read something about the maintainer is going to retire blabla not releasing the new version bla bla.
The maintainer clearly had been suffering from overwork. It sounded like he didn't want to support Capistrano 2.x but has now confirmed it is supported. Clearly, it will take a few days before conclusions are drawn, but Capistrano has a lot of support.
output = capture('cat ~/file.cnf')
output.each_line do |line|
puts line
end
Thats how I read lines using capture. If you want to capture something specific on a line you can use
if line.include? 'user'
It's worth noting that this doesn't have quite the same behaviour as 2.x's method. capture waits for the command to finish before returning the output instead of streaming it back line by line as run did.
I could not figure out how to get streaming output in cap 4 either. For me in Cap 3.4.0 with sshkit 1.11.1, execute was not doing it.
But looking at the sshkit docs, here's one way to hack it, which kind of works:
class StreamOutputInteractionHandler
def on_data(_command, stream_name, data, channel)
$stderr.print data
end
end
# ...
execute :whatever, interaction_handler: StreamOutputInteractionHandler.new
It might do weird things, especially if you are executing on multiple hosts, it will of course interleave the output. You can use capistrano log similar to the way the built in MappingInteractionHandler does, but I wanted to print directly to console so I could get partial output before newlines (a progress bar from a rake task).
Discussion with sshkit maintainer here. https://github.com/capistrano/sshkit/issues/395#issuecomment-288489866
It's actual way simpler in Capistrano 3.x, you can just do:
execute "ls -a"
And the output will be streamed automatically, it's great for streaming log files etc.
It would be great if you could clarify what the problem you encountered was, I'm using this on 4 different Rails apps across ~30 hosts without any problems. So if there is a potential issue, it would be useful to know! E.g. I use this http://www.talkingquickly.co.uk/2013/12/tailing-log-files-with-capistrano-3/ to tail log files
execute "whatever" doesn't stream the output anywhere
Any chance you could link me to the code you're using. I tested it with an empty app here yesterday after I saw your post (both for individual commands and tail -f etc) and it streams as expected. execute is actually handled by SSHKit and this is exactly how it is supposed to behave.
Doesn't work that way for me in capistrano 3.4.0 either, I'm getting no output to console at all with execute. Hmm. But I'd really like to get streaming output.
| common-pile/stackexchange_filtered |
How to show comma separated values in mvc list
I have a Students and a Skills table, a student can have multiple skills, so I have a StudentSkills that have many to many relationship with Students and Skills.
I can insert successfully into my table, but I am unable to show my all skills in a single row in my listview. I have tried in different ways like StringBuilder or string join but I failed. I don't know what is the code to do that.
Linq doesn't support StringBuilder or string join.
This code I have provided results well except that, For each skills, different rows are being generated in List where other items are being repeated in each row.
Here is my code:
Students controller:
public ActionResult GetStudentsInfo ()
{
StringBuilder sb = new StringBuilder();
var students = (from stud in db.Students
join con in db.Countries on stud.CountryId equals con.CountryId
join ct in db.Cities on stud.CityId equals ct.CityId
join rsm in db.Resumes on stud.ResumeID equals rsm.ResumeId
join stsk in db.StudentSkills on stud.StudentId equals stsk.StudentId
//group stsk by stsk.StudentId into g
//group stud by stud.StudentId into sg
select new
{
studentName = stud.StudentName,
countries = con.CountryName,
cities = ct.CityName,
skills = stsk.Skill.SkillName.ToString(),
resumes = rsm.ResumeName,
dateOfBirth = stud.DateOfBirth,
}).ToList();
List<StudentListVM> studentLists = new List<StudentListVM>();
foreach (var item in students)
{
//var sk= sb.Append(item.skills + ",").ToString();
studentLists.Add(new StudentListVM
{
studentName = item.studentName,
countries = item.countries,
cities = item.cities,
skills = string.Join(",", item.skills).ToString(),
//skills = item.skills.ToString(),
resumes = item.resumes,
dateOfBirth = item.dateOfBirth
});
//sb.Remove(sb.ToString().LastIndexOf(","), 1);
}
return View(studentLists);
}
Students class:
public partial class Student
{
public Student()
{
this.Resumes = new HashSet<Resume>();
this.StudentSkills = new HashSet<StudentSkill>();
}
public int StudentId { get; set; }
public string StudentName { get; set; }
public int CountryId { get; set; }
public int CityId { get; set; }
public System.Guid ResumeID { get; set; }
public System.DateTime DateOfBirth { get; set; }
public virtual Country Country { get; set; }
public virtual ICollection<StudentSkill> StudentSkills { get; set; }
}
Skills class:
public partial class Skill
{
public Skill()
{
this.StudentSkills = new HashSet<StudentSkill>();
}
public int SkillId { get; set; }
public string SkillName { get; set; }
public bool IsSelected { get; set; }
public virtual ICollection<StudentSkill> StudentSkills { get; set; }
}
StudentsSkills class:
public partial class StudentSkill
{
public int StudentSkillsId { get; set; }
public int StudentId { get; set; }
public int SkillId { get; set; }
public virtual Skill Skill { get; set; }
public virtual Student Student { get; set; }
}
StudentListVM viewmodel class:
public class StudentListVM
{
public string studentName { get; set; }
public string countries { get; set; }
public string cities { get; set; }
public string skills { get; set; }
public string resumes { get; set; }
public DateTime dateOfBirth { get; set; }
}
Student List View:
@model IEnumerable<MVCOneSoft.ViewModels.StudentListVM>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "CreateFromVM")
</p>
<table class="table">
<tr>
<th>
Student Name
</th>
<th>
City
</th>
<th>
Country
</th>
<th>
Skills
</th>
<th>
Resume
</th>
<th>
Date Of Birth
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.studentName)
</td>
<td>
@Html.DisplayFor(modelItem => item.cities)
</td>
<td>
@Html.DisplayFor(modelItem => item.countries)
</td>
<td>
@Html.DisplayFor(modelItem => item.skills)
</td>
<td>
@Html.DisplayFor(modelItem => item.resumes)
</td>
<td>
@Html.DisplayFor(modelItem =>item.dateOfBirth)
</td>
//this section is commented
@*<td>
@Html.ActionLink("Edit", "Edit", new { id=item.StudentId }) |
@Html.ActionLink("Details", "Details", new { id=item.StudentId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.StudentId })
</td>*@
</tr>
}
</table>
You should get skills by string.Join(",", stud.StudentSkills.Select(a => a.Skill.SkillName).ToList() and use distinct to remove duplicated records
var students = (from stud in db.Students
join con in db.Countries on stud.CountryId equals con.CountryId
join ct in db.Cities on stud.CityId equals ct.CityId
join rsm in db.Resumes on stud.ResumeID equals rsm.ResumeId
join stsk in db.StudentSkills on stud.StudentId equals stsk.StudentId
//group stsk by stsk.StudentId into g
//group stud by stud.StudentId into sg
select new
{
studentName = stud.StudentName,
countries = con.CountryName,
cities = ct.CityName,
skills = string.Join(",", stud.StudentSkills.Select(a => a.Skill.SkillName).ToList()),
resumes = rsm.ResumeName,
dateOfBirth = stud.DateOfBirth,
}).Distinct().ToList();
and
foreach (var item in students)
{
//var sk= sb.Append(item.skills + ",").ToString();
studentLists.Add(new StudentListVM
{
studentName = item.studentName,
countries = item.countries,
cities = item.cities,
//skills = string.Join(",", item.skills).ToString(),
skills = item.skills.ToString(),
resumes = item.resumes,
dateOfBirth = item.dateOfBirth
});
//sb.Remove(sb.ToString().LastIndexOf(","), 1);
}
Sorry! I have specified already that, LINQ doesn't recognize StringJoin or StringBuilder! This doesn't work.
| common-pile/stackexchange_filtered |
Deleting empty albums on iOS 13.3 with iFunbox > User File System
My Canon PowerShot G7 X Mark II with the CameraConnect App has created almost 2000 empty albums to my iPhone XS (iOS 13.3).
Is there any way to delete a single/multiple files using iFunbox > User File System to delete/rebuilt photo albums or cache so that all empty folders or at least the folders mentioned would dissappear from my iPhone? Other methods are appriciated as well.
I had no luck with uninstalling CameraConnect App.
If you have a Mac, you can connect it via USB then on your mac import the photos you want to save from your phone. Then select all (CMD+A) and then delete it.
If you have Windows, you can try using the imyphone application
Best of luck!
No luck at all. There is some restrictions when it comes to 3rd party software and manipulating filesystem. This can be made via iFunbox but I am not sure what to delete.
| common-pile/stackexchange_filtered |
Prove that $\frac{ab}{c}+\frac{bc}{a}+\frac{ac}{b}\ge a+b+c$
How to prove that
\begin{equation*}\frac{ab}{c}+\frac{bc}{a}+\frac{ac}{b}\ge a+b+c,\ where \ a,b,c>0\end{equation*}
I tried the following:
\begin{equation*}abc(\frac{1}{a^2}+\frac{1}{b^2}+\frac{1}{c^2})\ge a+b+c\end{equation*}
Using Chebyshev's inequality
\begin{equation*}(\frac{1}{a}+\frac{1}{b}+\frac{1}{c})(\frac{1}{a}+\frac{1}{b}+\frac{1}{c})\le3(\frac{1}{a}\frac{1}{a}+\frac{1}{b}\frac{1}{b}+\frac{1}{c}\frac{1}{c})\end{equation*}
from first inequality follows
\begin{equation*}\frac{1}{3}(\frac{1}{a}+\frac{1}{b}+\frac{1}{c})^2abc\ge a+b+c\end{equation*}
equivalent to
\begin{equation*}\frac{abc}{3(a+b+c)}\ge (\frac{1}{\frac{1}{a}+\frac{1}{b}+\frac{1}{c}})^2\end{equation*}
and by amplifying both members by 9
\begin{equation*}\frac{3abc}{a+b+c}\ge (\frac{3}{\frac{1}{a}+\frac{1}{b}+\frac{1}{c}})^2\end{equation*}
now using mean inequality
\begin{equation*}\sqrt[3]{abc}\ge \frac{3}{\frac{1}{a}+\frac{1}{b}+\frac{1}{c}}\end{equation*}
the inequality in question becomes
\begin{equation*}3abc\ge (a+b+c)(\sqrt[3]{abc})^2\end{equation*}
which yields
\begin{equation*}3\sqrt[3]{abc}\ge a+b+c\end{equation*}
not what I wanted.
Multiplying both sides of your inequality with $abc>0$, you get equivalently that:
$ \displaystyle (ab)^2 + (bc)^2 + (ca)^2 \geq abc (a+b+c) $
This holds by the basic inequality $ \displaystyle x^2 + y^2 + z^2 \geq xy +yz+ xz $, which holds for all $x,y,z $ real.
edit: The basic inequality holds for all real, thank's to user26486, for pointing this out.
thank you, it was that simple
You are welcome.
The basic inequality is equivalent to $(x-y)^2+(y-z)^2+(z-x)^2\ge 0$, which is true. In fact, it holds for all real $x,y,z$, not only positive. It is also trivial by rearrangement inequality.
@user26486: Yes you are right, it is true for all reals. I forgot it, because I had in mind just the positive numbers, for which was the inequality in the problem.
This solution also shows that the inequality holds if $abc>0$ even if $a$, $b$, and $c$ are not all positive. (e.g. If $a$ and $b$ are negative, while $c$ is positive) The solution which I posted only works if $a,b,c>0$.
The inequality which you want to prove is symmetric, so we can assume without loss of generality that $a\geq b\geq c$.
Then $ab\geq ac\geq bc$ and $\frac{1}{c}\geq \frac{1}{b}\geq \frac{1}{a}$.
Thus, from the rearrangement inequality, we get that
$$\frac{ab}{c}+\frac{ac}{b}+\frac{bc}{a}\geq\frac{ab}{b}+\frac{ac}{a}+\frac{bc}{c}=a+c+b$$
which is what we wanted to show.
You seem to be using $\frac{bc}{a} \ge \frac{bc}{c}$, which is false.
thank you both yours and @passenger answers are true so I wont validate one
@TonyK actually he is correct it is a Chebyshev type inequality
@TonyK He cited rearrangement inequality, and it was all he was using.
Well, that's something I've learnt today!
We can do a slick AM-GM "pairwise" token that I picked up from the "Cauchy masters":
$\dfrac{ab}{c} + \dfrac{bc}{a} \geq 2\sqrt{\dfrac{ab}{c}\cdot\dfrac{bc}{a}}= 2b$, and similarly: $\dfrac{bc}{a}+\dfrac{ca}{b} \geq 2c$, and $\dfrac{ca}{b} + \dfrac{ab}{c} \geq 2a$. Add them up and divide by $2$ to get the answer.
| common-pile/stackexchange_filtered |
Not import all records to database
I try to import sql file that has about 70 MB so when I use command source in
xampp->mysql->bin
not all the records in the sql file imported
do you have idea about this problem ?
"I did something, and then something didn't happen" needs a lot more technical detail.
so what should I add to post ? I just do this and when check the table records I saw some records not exist so I can not show them in the post
You need to dig deeper. Is there a pattern? Did it import all tables, or skip a bunch? Often if an import fails you'll see that some tables are missing because it stopped at a certain point. Does that dump have the records or not?
actually all functions run without any problem when use source command and when I import the data no error were happen but when I want to use entities I cant find all records in tables
You're going to have to do a lot more research here. What records are missing? What pattern is there to the gaps? Do these records have something in common or not?
| common-pile/stackexchange_filtered |
How do I get a site unblocked from corporate firewalls
I have a pretty new site, nothing shady has ever happened with it, some of my friends have reported that they can't access said site at their company. How can I figure what lists I'm on and how to get off those lists? One of them indicated their firewall is Palo Alto Networks.
AFAIK there isn't really anything you can do to find what content filters you are blocked by. The databases are kept pretty secret. Your friends should report their problem to their IT department who will likely have a support contract with Palo Alto and will be able to submit the URL to them if it has been miss-classified in some way by their content filter. This all assumes your site is being classified incorrectly.
Many corporations block sites by default until they are categorized or submitted as a requirement. There are many public and paid 'blacklists' for email servers and addresses, I assume there are probably similar lists for websites. I would do a google search for 'website blacklist' and see if you're on any of them.
So our site isn't really listed on any blacklists I've found online. The only notes are around email sending. We don't really send email so we haven't setup reverse references etc etc. It sounds like we just haven't been whitelisted. I guess another question is how is every blog under the sun visible on corporate wifi then?
Are you using shared hosting? If your site's IP address is shared with 200 other sites, then if just one of them is shady then all could be blocked. Solution would be to ask the provider to move you to another server.
There are a whole host of companies that make firewalls and maintain their own lists of sites some categorizations some with risk ratings. These companies do allow you to submit a categorization for a site or request a review/change. The thing you should google for here is "URL Filtering" and "Firewall Companies".
By doing this I found that Palo Alto Networks classified our site as "porn". Why? I don't know. I found out by visiting: https://urlfiltering.paloaltonetworks.com (which is currently quite a broken page, but I got it to work with a little finagling)
Here are a list of companies and the urls to submit change requests:
Palo Alto Networks: https://urlfiltering.paloaltonetworks.com
Juniper Networks: http://mtas.surfcontrol.com/mtas/JuniperTest-a-Site.asp
BrightCloud: https://www.brightcloud.com/tools/url-ip-lookup.php
Barracuda: http://www.barracudacentral.org/report/website-category
Sonic Wall: http://cfssupport.sonicwall.com/Support/web/eng/newui/viewRating.jsp
Symantec Blue Coat: https://sitereview.bluecoat.com
| common-pile/stackexchange_filtered |
Object is not a primitive for response message models
I decorated an action as follows
[SwaggerResponse(HttpStatusCode.OK, "List of customers", typeof(List<CustomerDto>))]
[SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(NotFoundException))]
The OK model is shown correctly.
However, under Repsonse Messages, I get 'Object is not a primitive' for NotFound. The custom exception derives from Exception, implements ISerializable and also has [Serializable] and [DataContract()]
How can I show the actual data type instead of the message?
Also, do I incur a performance hit when using the WebApi normally, if I decorate all actions with such attributes?
How about something like:
[SwaggerResponse(HttpStatusCode.OK, "List of customers", typeof(IEnumerable<int>))]
[SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(BadRequestErrorMessageResult))]
[SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(NotFoundResult))]
public IHttpActionResult GetById(int id)
{
if (id > 0)
return Ok(new int[] { 1, 2 });
else if (id == 0)
return NotFound();
else
return BadRequest("id must be greater than 0");
}
http://swashbuckletest.azurewebsites.net/swagger/ui/index#!/IHttpActionResult/IHttpActionResult_GetById
| common-pile/stackexchange_filtered |
SonarQube warning: Unable to get default branch, defaulting to 'master': TypeError: Cannot read property 'defaultBranch' of null
We use Azure DevOps and YAML pipelines to build and analyze our code.
This all works fine, except for the code that uses main instead of master as the default branch name. Then SonarQube emits a warning: Unable to get default branch, defaulting to 'master': TypeError: Cannot read property 'defaultBranch' of null
The warning is a false-positive. When I go to the SonarQube portal everything looks fine for the project and it even displays the default branch is main.
We have a 'no warnings' policy, so it is very sad SonarQube is emitting this warning, which should be in my opinion Information.
I think I need to instruct SonarQube not to look for the master branch or tell it to also look for the main branch. But I can't figure out how to do this. The documentation is not very helpful at this point.
This is my yaml task:
- task: SonarQubePrepare@5
displayName: Prepare analysis on SonarQube ($(SonarProjectKey))
inputs:
SonarQube: 'SonarQube - Developer Edition'
projectKey: $(SonarProjectKey)
projectName: '${{ parameters.AnalyseProjectName }}'
projectVersion: '$(Build.BuildNumber)'
extraProperties: |
sonar.verbose=true
sonar.branch.name=$(Build.SourceBranchName)
sonar.branch.target=main
sonar.cs.opencover.reportsPaths=**/coverage.opencover.xml
sonar.cs.vscoveragexml.reportsPaths=$(Agent.BuildDirectory)\TestResults\*.coveragexml
sonar.exclusions=**\Tests\**\*, **\TestApps\**\*, **\GlobalSuppressions.cs
If needed I can make changes to our build agents.
Please advise.
I also asked this at the Sonar Community: https://community.sonarsource.com/t/unable-to-get-default-branch-defaulting-to-master-typeerror-cannot-read-property-defaultbranch/97789 But no solution from there either.
Following an extensive discussion with the SonarQube team, they have recently released a minor update to their Azure DevOps (AZDO) extension. I'm pleased to inform you that this new version has resolved the issue and no longer reports the warning.
| common-pile/stackexchange_filtered |
Is it possible for an unmanaged C++ app to only load the CLR when it needs managed types?
More to the point, I have a native C++ application, that may never need to use managed types. I would like the CLR to remain unloaded until I the codepath that actually depends on managed types is actually hit.
I was trying to accomplish this using the /clr switch in Visual Studio 2005, but as far as I can tell as soon as I use that switch, the entire C++ app becomes a managed app. Is there a way to specify it only for a certain compilation unit or function? I tried to mark my main() function in my test app with #pragma unmanaged, but that didn't stop it from loading the CLR at startup.
If you have a mixed mode C++ DLL the CLR will load as soon as your DLL / EXE is loaded into the process. There is no way to change this behavior.
The best way to achieve what you're looking for is to break up your DLL into 2 parts
Parts that are purely native
Parts that require the use of managed code.
You can control when the CLR starts up by controlling when #2 is loaded into the process. This requires a bit of setup work but should get the result you're looking for.
Thanks for this suggestion. Can you explain how to achieve this or point to a resource that explains it?
Would this be using delayed loading features in the linker?
| common-pile/stackexchange_filtered |
How to get data back from an okhttp call?
I have a method which calls an external API using okhttp library on android, I'm able to access the data that comes back inside that method/thread but I'm not able to return the data or use it somewhere else. What's the problem?
I have tried putting the data in another class (extended from AsyncTask) and it still didn't work.
public class DisplayImage extends AppCompatActivity {
ImageView imageView;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_image);
imageView = findViewById(R.id.mImageView);
textView = findViewById(R.id.textView);
Bitmap bitmap = BitmapFactory.decodeFile(getIntent().getStringExtra("image_path"));
imageView.setImageBitmap(bitmap);
String imagePath = getIntent().getStringExtra("image_path");
try {
//map returned here
HashMap<String, double[]> map = getCropInfo(imagePath);
//This text view doesn't update
textView.setText(String.valueOf(map.get("ID")[0]));
} catch (Exception e) {
e.printStackTrace();
}
}
HashMap getCropInfo(String imageUri) throws Exception {
final HashMap<String, double[]> map = new HashMap<>();
OkHttpClient client = new OkHttpClient();
MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpg");
File file = new File(imageUri);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file))
.build();
Request request = new Request.Builder()
.header("Prediction-Key", "") //predictionkey hidden
.header("Content-Type", "application/octet-stream")
.url("https://westeurope.api.cognitive.microsoft.com/customvision/v3.0/Prediction/7f5583c8-36e6-4598-8fc3-f9e7db218ec7/detect/iterations/Iteration1/image")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
public void onResponse(Call call, final Response response) throws IOException {
// Read data on the worker thread
final String responseData = response.body().string();
// Run view-related code back on the main thread
DisplayImage.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
JSONObject jsonObject = new JSONObject(responseData);
JSONArray jsonArray = jsonObject.getJSONArray("predictions");
double highestIDProbability = 0;
double highestVoltageProbability = 0;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject tempObject = jsonArray.getJSONObject(i);
if(tempObject.getString("tagName").equals("ID") && tempObject.getDouble("probability") > highestIDProbability) {
highestIDProbability = tempObject.getDouble("probability");
map.put("ID", getCoordinatesPixels(tempObject));
}
else if(tempObject.getString("tagName").equals("Voltage") && tempObject.getDouble("probability") > highestVoltageProbability) {
highestVoltageProbability = tempObject.getDouble("probability");
map.put("Voltage", getCoordinatesPixels(tempObject));
}
}
//setting text view works from here.
//textView.setText(String.valueOf(map.get("ID")[0]));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
//I am returning map
return map;
}
static double[] getCoordinatesPixels(JSONObject object) {
double[] arr = new double[4];
try {
JSONObject innerObject = object.getJSONObject("boundingBox");
arr[0] = innerObject.getDouble("left");
arr[1] = innerObject.getDouble("top");
arr[2] = innerObject.getDouble("width");
arr[3] = innerObject.getDouble("height");
} catch (JSONException e) {
e.printStackTrace();
}
return arr;
}
}
I need the map to return so I can use the data externally.
I believe you're running into an issue related to the asynchronous nature of OkHttp and network requests in general. When you do a new call, that call is queued and handled asynchronously. This means that the code will most likely execute return map; before the asynchronous call has completed and before the callback modifies the map. If you need access to the map outside of the scope of the callback you have two main options.
Make the call blocking. This essentially means that you will have to force the function to stall until the OkHttp callback is triggered before return map; occurs. I would absolutely not recommend doing this as it defeats the entire purpose of moving long running tasks to other threads.
Call a function inside the onResponse() callback. Construct the map inside the callback itself, then just call a function with that map as a parameter to handle any operations you need to do on that map. Alternatively you could also make the map a global variable so you can access it from practically anywhere.
On a sidenote, if this data is going to be used to propagate changes back to the UI or other program state, I would recommend using a ViewModel (it's a model object that holds data and can outlive Activity lifecycles) paired with something like MutableLiveData (which is a data wrapper that makes basically anything observable).
Using such a setup, you would have your map object inside your ViewModel. You would then register an observer from any context (Activity, Fragment, etc) where you need to know about updates on the map. Finally, in the callback, you would just need to update the ViewModel's map. This would automatically notify any registered observers.
Good luck!
Thank you for the in-depth explanation!
how can I make the call blocking as suggested in your first option?
@bronkers I'm not too familiar with OkHttp in particular, but this may be able to help you.
| common-pile/stackexchange_filtered |
How to insert where condition in mysql query
I will pass the query into this function query("SELECT * FROM table_name");
And the function is
public function query($sql) {
$resource = mysql_query($sql, $this->link_web);
if ($resource) {
if (is_resource($resource)) {
$i = 0;
$data = array();
while ($result = mysql_fetch_assoc($resource)) {
$data[$i] = $result;
$i++;
}
mysql_free_result($resource);
$query = new stdClass();
$query->row = isset($data[0]) ? $data[0] : array();
$query->rows = $data;
$query->num_rows = $i;
unset($data);
return $query;
} else {
return true;
}
} else {
trigger_error('Error: ' . mysql_error($this->link_web) . '<br />Error No: ' . mysql_errno($this->link_web) . '<br />' . $sql);
exit();
}
}
I want to add tenent_id = '1' in SELECT query also for INSERT query. Likewise I need to do it for UPDATE.
I want to bring the query like this
SELECT * FROM table_name WHERE tenent_id = 1 and user_id = 1
INSERT INTO table_name('tenant_id, user_id') VALUE('1','1')
UPDATE table_name SET user_id = 1 WHERE tenant_id = '1'
Can anyone give me the idea about how to insert tenant_id in select, insert and update
Thanks in advance
Why would you have WHERE in an INSERT query?
its hard to understand.Can you please give more details..
do you understand what insert and update means? if you insert that means you add new row to database (like you did in second query). when you want to change data for certain id already in database,than that is update.
I am using common function for all query(INSERT, DELETE and SELECT). And I want to make changes in tenant_id in all table while INSERTING, UPDATING and FETCHING. So i asked the logic to do this
It's better practice to use the correct mysql functions rather than just a query function.
For example, if you want to cycle through many items in a database, you can use a while loop:
$query = mysql_query("SELECT * FROM table WHERE type='2'");
while($row = mysql_fetch_array($query)){
echo $line['id'];
}
This would echo all the IDs in the database that have the type 2.
The same principle is when you have an object, using mysql functions, you can specify how you want the data to return. Above I returned it in an array. Here I am going to return a single row as an object:
$query = mysql_query("SELECT * FROM table WHERE id='1'");
$object = mysql_fetch_object($query);
echo $object->id;
echo $object->type;
echo $object->*ANY COLUMN*;
This would return as:
1.
2.
Whatever the value for that column is.
To insert your data, you don't need to do "query()". You can simple use mysql_query($sql).
It will make life much easier further down the road.
Also, its best to run one query in a function, that way you can handle the data properly.
mysql_query("INSERT...");
mysql_query("UPDATE...");
mysql_query("SELECT...");
Hope this helps.
Please don't suggest mysql_* functions as they are officially deprecated.
I know, over using a single function for a beginner they are sort of necessary. Unless you would like to introduce him to PDO?
The simple answer is: just add the condition to your query. Call query("SELECT * FROM table_name WHERE tenant_id = 1 and user_id = 1").
If you're concerned about escaping the parameters you pass to the SQL query (which you should be!), you can either do it yourself manually, e.g.
$query = sprintf("SELECT * FROM table_name WHERE tenant_id = %d", intval($tenant_id));
query($query);
Or better use prepared statement offered by mysqli extension (mysql_query is deprecated anyway):
$stmt = $mysqli->prepare("SELECT * FROM table_name WHERE tenant_id = ?");
$stmt->bind_param("i", $tenant_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
// ...
}
If I still haven't answered your question, you can use a library to handle your queries, such as dibi:
$result = dibi::query('SELECT * FROM [table_name] WHERE [tenant_id] = %i', $id);
$rows = $result->fetchAll(); // all rows
The last option is what I would use, you don't need to write your own query-handling functions and get query parameter binding for free. In your case, you may utilize building the query gradually, so that the WHERE condition is not part of your basic query:
$query[] = 'SELECT * FROM table_name';
if ($tenant_id){
array_push($query, 'WHERE tenant_id=%d', $tenant_id);
}
$result = dibi::query($query);
I got your idea but i have 1000s of mysql query. i cant edit "where condition" in all queries . using the function QUERY() i want to make the changes.
@user2269905 Dibi would solve your problem by doing $query = array($query); array_push($query, 'WHERE ...') or so. If you don't use ORDER BY or something that comes after WHERE, just append the WHERE condition to your query and handle inserts as a special case by another function. There's really no other solution - you don't want to implement a MySQL query parser yourself.
| common-pile/stackexchange_filtered |
SpringXD Job is still executing even after forceful Server shutdown
I'm trying to run a Job on SpringXD and the job has 7 steps, When I reach step 4 i'm shutting down the XD server. When I look into the Metadata of SpringXD I'm saving on OracleDB. I see that the Step 4 is in executing status and it will never change to failed. After restarting the server, I still see that the status of the Job is still executing and it never gets finished. If I launch the job it create a new job and the new one gets finished.
My config.xml for jdbc:
<jdbc:initialize-database data-source="dataSource"
enabled="false">
<jdbc:script location="org/springframework/batch/core/schema-oracle10g.sql" />
</jdbc:initialize-database>
From org/springframework/batch/core/schema-oracle10g.sql, I see that the sql queries are for creating a table. But when the tables are already existing, as i didn't drop them from my previous job. There was no error which said tables already exist. The new job got appended to previous existing table. HOW?
How can I force the job to fail when the XD server suddenly goes down?
How can I resume the same job that was stopped from the step where it stopped?
Thank you :)
How are you killing the container? If it's a kill -9 style, the job isn't going to shut down gracefully and doesn't have the opportunity to update the tables of it's state.
@MichaelMinella .. yes I'm killing it using kill -9. Is there any way we can restart the executing job after the spring XD server is up?
That's a manual process. Without giving the process the ability to gracefully shutdown, it's really a human decision as to what to do. Do we restart, do we not, at what point to we restart...all of those are very use case specific decisions.
@MichaelMinella .. I totally agree with you. But if there server is down for some reason, then the springXD container will also be down and once the container is up. we won't be able to restart the executing job?
Not automatically, no. There is no functionality within Spring XD to relaunch a job if a container fails because of the previously mentioned issues.
Can we manually do it?
Of course!!!!!!
@MichaelMinella.. Thank you for being patient with me.. i'm totally new to Spring and figuring my way. I have manually created another job and marking the job status in the BATCH_JOB_EXECTION to FAILED from STARTED.. But when I'm trying to restart the job using jobOperator.restart() the FAILED job is not getting restarted. Getting an exception for NoSuchJobExecutionException..
@MichaelMinella.. i'm trying to restart a jobA that is deployed from SpringXD and if the XD fails (kill -9) then I should be able to restart job A by running another job B, After the container is up. I was able to restart the jobA after marking it as FAILED and by using the XD SHELL by the command "job execution restart --id 0" I was able to restart the job from the point it stopped. Can I send this shell command from the jobB after making the jobA FAILED on the database. facing problem implementing the idea.
Thank you for Helping.. Means a lot to me
| common-pile/stackexchange_filtered |
Flask-Sqlalchemy seemingly "caching" queries
I'm writing a signup/login script for Flask, and I am using flask-sqlalchemy. To sign a user up, I INSERT their details into the db through flask-sqlalchemy, then commit the change. However, when they try to login, which fetches their details from the db, I get a NoneType error, indicating that the entry I am trying to find is not present.
I am using MySQL 5.5 and the latest version of Flask and Flask-Sqlalchemy.
Error:
AttributeError: 'NoneType' object has no attribute 'password'
Code:
newuser = User(username='username', email='email', valid=1, password='hashpass', rkey=rkey, score=0, ip=uip)
db.session.add(newuser)
db.session.commit()
pwhash = User.query.filter_by(username='username').first().password
return str(pwhash)
Model
class User(db.Model):
__tablename__ = 'users'
uid = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(50))
password = db.Column(db.Text)
email = db.Column(db.String(120))
rkey = db.Column(db.String(50))
role = db.Column(db.String(20))
valid = db.Column(db.Boolean)
ip = db.Column(db.String(110))
lastip = db.Column(db.String(110))
score = db.Column(db.Integer)
def __repr__(self):
return '<User %r>' % self.username
when do you add this user to the database? What is the context? Can you do a print(db.query.all()) and see if the database did anything with it?
When running print(db.query.all()), I get
File "<debugger>", line 1, in <module> print(db.query.all()) AttributeError: 'SQLAlchemy' object has no attribute 'query'. I set db = SQLAlchemy() in the beginning of the app, not sure if that makes a difference.
errr sorry, I meant User.query.all()
It echoes a list in this format: [<User u'cydrobolt'>, <User u'admin'> ...], but the new user I registered is not there.
This question seems to ask about the same issue: https://stackoverflow.com/questions/15406623/flask-sqlalchemy-give-empty-result-from-database-view
I believe your query should be:
pwhash = User.query.filter_by(User.username='username').first().password
The Model.fieldexpression syntax is used for filter. filter_by takes the field names as keyword arguments.
| common-pile/stackexchange_filtered |
How to build a post and comment editing form in a page?
This plugin enables you to submit a custom post type called 'Questions' using a form that can be embeded in a page via shortcode.
Is there a way of accomplishing the same, but this time, building a form and embedding it on a page to edit this custom post type and comments? (it doesn't have to be a shortcode).
Reference picture:
to edit or create?
@Bainternet To edit, because with that plugin you can already create 'Questions' (custom post type).
To edit is a bit harder then just creating, but not that hard
first you only display the edit link to the author so you add something like this to your loop:
global $current_user;
get_currentuserinfo();
while (have_posts()) : the_post();
//regular loop stuff
//and check if the post author is the current user
if ($post->post_author = $current_user->ID){
ehco '<a href="Editpage?qpost_id='.$post->ID.'">Edit</a>';
}
endwhile;
now if you look at that link
ehco '<a href="Editpage?qpost_id='.$post->ID.'">Edit</a>';
you will see that it is looking for a specific page, so create a new page, call it what ever you want and update it in the loop.
now create a new template page
can be an exact copy of your page.php and take out the loop part.
instead enter this code to display the edit form.
<?php
if (isset($_GET['qpost_id'])){
//check user again
global $current_user;
get_currentuserinfo();
$Qpost = get_post($_GET['qpost_id']);
if ($current_user->ID = $Qpost->post_author){
$html = '<h1>Edit - '. $Qpost->post_title .'<h1><form name="edit_q" id="edit_q" method="POST" action="">
<input type="text" class="question-title-box" value="' . $Qpost->post_title; . '" id="question-title-box" name="title" onfocus="if(this.value == \'' . __("Enter Question Title",'qna-forum') . '\'){this.value = \'\';}" onblur="if(this.value == \'\'){this.value = \'' . __("Enter Question Title",'qna-forum') . '\';}" />
<textarea class="question-box" cols="70" rows="20" id="question-box" name="question" onfocus="if(this.value == \'' . __("Enter Your Question Here",'qna-forum') . '\'){this.value = \'\';}" onblur="if(this.value == \'\'){this.value = \'' .__("Enter Your Question Here",'qna-forum') . '\';}">' . $Qpost->post_content . '</textarea>';
$html .= "<div class='question-form-bottom'>".__('Category','qna-forum').":<select name='category' id='category'>";
$categories = get_categories(array(
'type' => 'post',
'orderby' => 'count',
'order'=> 'DESC',
'hide_empty'=>0
));
foreach($categories as $cat){
if(get_option('q_cat_' . $cat->term_id) == "TRUE"){
$html .= '<option value="' . $cat->term_id . '">' . $cat->cat_name . '</option>';
}
}
$html .= "</select>";
$html .= "<input type='hidden' value='" . wp_create_nonce( 'edit_q_question_form' ) . "' name='nonce' />";
$html .="<input type='hidden' name='action' value='edit_q_ask_question' />";
$html .="<input type='hidden' name='q_to_update' value='".$qpost->ID."' />";
$html .="<input type='submit' name='submit' value='submit' /></form>";
echo $html;
}
}
?>
as you can see most of it is taken from the plugin, i just edited it a bit to fit your needs.
next you need to update the post and to do so you can use wp_update_post()
so add this code just above the code you've just added:
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "edit_q_ask_question") {
// Do some minor form validation and make sure there is content
$nonce=$_REQUEST['nonce'];
if (! wp_verify_nonce($nonce, 'edit_q_question_form') ) die('Security check');
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
}
if (isset ($_POST['question'])) {
$question = $_POST['question'];
} else {
echo 'Please enter some content';
}
$new_question = array(
'post_title' => $title,
'post_content' => $question,
'post_category' => array($_POST['category'])
'ID' => $_POST['q_to_update'];
);
// Update the post into the database
$new_id = wp_update_post( $new_question );
echo 'Qestion updated and you can see it <a href="'.get_permalink($new_id).'">here</a>';
}
I would probably add some Security check and data validation its not perfect but its a very nice start.
Thanks a lot! I've been asking this for weeks. I will study the code.
| common-pile/stackexchange_filtered |
return what was not found in array in MongoDB
say my database collection has
* user collection*
[
{id:'1'}
{id:'2'}
]
I have an array of object
[
{id:'1'}
{id:'2'}
{id:'3'}
]
I want the object that was not found in the collection.
I want
[
{id:'3'}
]
I'm currently have this
const records = await dbo
.collection('user collection')
.find({
'id': { $in: newArr },
})
.toArray();
I'm a bit stumped on what to do! ... hope someone can help Thanks!
Option 1:
Looks like this is what you need via the not in operation ( $nin ) when you need to check the not exisitng id in collection documents from provided array:
db.collection.aggregate([
{
$match: {
id: {
"$nin": [
1,
2
]
}
}
},
{
$group: {
_id: null,
"idnotIntheArray": {
$push: "$id"
}
}
}
])
Explained:
$match for any documents with id not in provided array.
$group all id's in an array
plaground1
Option 2:
And this is the option where you output only the array elements not existing in the collection:
db.collection.aggregate([
{
$group: {
_id: null,
ids: {
$push: "$id"
}
}
},
{
$project: {
missingFromCollection: {
"$setDifference": [
[
1,
5,
4
],
"$ids"
]
}
}
}
])
Explained:
Push all id elements from collection to array ids ( note this solution will not allow more then 16MB total size of id's )
Use $setDifference to identify the difference between the two arrays.
playground2
Hi, I think you misunderstand the question, the user collection has records with id: 1, 2, while provided input array is with id: 1,2,3. Post owner wants to get the (object) value from the input array which is { id: 3 } (not exist in the collection). Just curious the possibility of this outcome =)
Thanks @Yong Shun , since it was not very clear from the question I have added the two options to my answer.
You can use this aggregation:
db.entity.aggregate([
{
$match : {
"myObjList.id" : 1
}
},
{
$unwind : "$myObjList"
},
{
$match : {
"myObjList.id" : 1
}
}
])
and my aggregation result:
{
"_id" : ObjectId("6225a0f78d435fd2845f1dd1"),
"myObjList" : {
"id" : 1
}
}
| common-pile/stackexchange_filtered |
What changes would I have to make to the following code in order to use Bootstrap to style it.?
Normally I would just use basic PHP and MySQL and some simple CSS to style. However I like the look and feel of the Bootstrap framework and would like to incorporate it into my PHP, but am a relative newbie of where to begin. I would like to start with a simple hands-on example.
Using the code below, which is a simple login script using PHP and MySQL, which changes would I need to make in order to use Bootstrap.?
I have already downloaded the Bootstrap files..
<?php
$connect = mysqli_connect("db location","username","password", "forks") or die(mysql_error());
if(isset($_COOKIE['ID_your_site'])){ //if there is, it logs you in and directes you to the members page
$username = $_COOKIE['ID_site'];
$pass = $_COOKIE['Key_site'];
$check = mysqli_query($conect, "SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
while($info = mysqli_fetch_array( $check )){
if ($pass != $info['password']){}
else{
header("Location: login.php");
}
}
}
//if the login form is submitted
if (isset($_POST['submit'])) {
// makes sure they filled it in
if(!$_POST['username']){
die('You did not fill in a username.');
}
if(!$_POST['pass']){
die('You did not fill in a password.');
}
// checks it against the database
if (!get_magic_quotes_gpc()){
$_POST['email'] = addslashes($_POST['email']);
}
$check = mysqli_query($conect, "SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysqli_num_rows($check);
if ($check2 == 0){
die('That user does not exist in our database.<br /><br />If you think this is wrong <a href="login.php">try again</a>.');
}
while($info = mysqli_fetch_array( $check )){
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']);
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
die('Incorrect password, please <a href="login.php">try again</a>.');
}
else{ // if login is ok then we add a cookie
$_POST['username'] = stripslashes($_POST['username']);
$hour = time() + 3600;
setcookie(ID_your_site, $_POST['username'], $hour);
setcookie(Key_your_site, $_POST['pass'], $hour);
//then redirect them to the members area
header("Location: members.php");
}
}
}
else{
// if they are not logged in
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<tr><td>Username:</td><td>
<input type="text" name="username" maxlength="40">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="pass" maxlength="50">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
<?php
}
?>
Any help would be appreciated.
You really shouldn't use MD5 password hashes and you really should use PHP's built-in functions to handle password security. Make sure that you don't escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
Appart from the security problems inside your script you can check out: https://getbootstrap.com/examples/signin/
if you take a look at the source you'll see the familiar < form >
source:
<!-- here your php code -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Signin Template for Bootstrap</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form class="form-signin" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" name="username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" name="pass" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
</body>
</html>
@JayBlanchard The familiar (see source)
| common-pile/stackexchange_filtered |
Plotting Grouped Bar Chart with variables sharing the same time index (grouped bar chart) R
I am trying to plot some options data from Yahoo! finance - I'm sure this is super simple but I have simply hit a wall and have lost my patience.
This code downloads the options data for several maturities for a stock, cleans it up and assigns an index to it which is the maturity date for each option.
#Options data
maturity_dates <- c("2021-07-16", "2021-07-23", "2021-07-30", "2021-08-06",
"2021-08-13", "2021-08-20","2021-08-27", "2021-10-15",
"2022-01-21", "2023-01-20")
sndl_options <- getOptionChain("SNDL", Exp = maturity_dates)
#combine options data into a dataframe for puts and calls
#calls
options_df <- do.call("rbind", sndl_options[1:10])
calls_df <- rbind(options_df[1:10])
calls_df <- do.call(rbind.data.frame, calls_df)
calls_df$maturity <- substr(rownames(calls_df), start = 5, 10)
rownames(calls_df) <- 1:nrow(calls_df)
#fix maturity column and set as index
dates_vec <- 0
a <- 1
for(i in calls_df$maturity){
if(i == "210716"){
i <- "2021-07-16"
dates_vec[a] <- i
a <- a+1
} else{
if(i == "210723"){
i <- "2021-07-23"
dates_vec[a] <- i
a <- a+1
} else{
if(i == "210730"){
i <- "2021-07-30"
dates_vec[a] <- i
a <- a+1
} else{
if(i == "210806"){
i <- "2021-08-06"
dates_vec[a] <- i
a <- a+1
}else{
if(i == '210813'){
i <- "2021-07-30"
dates_vec[a] <- i
a <- a+1
}else{
if(i == "210820"){
i <- "2021-08-20"
dates_vec[a] <- i
a <- a+1
}else{
if(i == "210827"){
i <- "2021-08-27"
dates_vec[a] <- i
a <- a+1
}else{
if(i == '211015'){
i <- "2021-10-15"
dates_vec[a] <- i
a <- a+1
}else{
if(i == '220121'){
i <- "2022-01-21"
dates_vec[a] <- i
a <- a+1
}else{
if(i == '230120'){
i <- "2023-01-20"
dates_vec[a] <- i
a <- a+1
}
}
}
}
}
}
}
}
}
}
}
remove(i,a)
calls_df$maturity <- NULL; calls_df$LastTradeTime <- NULL
calls_df$ITM <- ifelse(calls_df$ITM == TRUE, 1, 0)
calls_df <- as.xts(calls_df, order.by = as.Date(dates_vec))
Now this should be OK with ggplot2 to create a grouped bar plot (a plot with bars sharing the same index, which in this case is : strike prices 1,...,K share the same index t. The y value here should be the Open Interest).
calls_plot <- ggplot(data = as.data.frame(calls_df), aes(x = index(calls_df), y = OI, fill = Strike))
calls_plot + geom_bar(stat="identity", position=position_dodge())
I am simply not getting the graph that I want. Any suggestions?
Thanks in advance.
Not sure about the plot you are trying to achieve. First you could simplify your code considerably by getting rid of the bunch of if statements and simply use as as.Date for a proper date conversion. Additionally, at least for plotting it's not necessary to convert to an xts object.
library(quantmod)
library(ggplot2)
library(dplyr)
maturity_dates <- c("2021-07-16", "2021-07-23", "2021-07-30", "2021-08-06",
"2021-08-13", "2021-08-20","2021-08-27", "2021-10-15",
"2022-01-21", "2023-01-20")
sndl_options <- getOptionChain("SNDL", Exp = maturity_dates)
calls_df <- lapply(sndl_options, `[[`, "calls")
calls_df <- bind_rows(calls_df, .id = "date")
calls_df$maturity <- substr(rownames(calls_df), start = 5, 10)
calls_df$maturity <- as.Date(calls_df$maturity, format = "%y%m%d")
calls_df$OI <- as.numeric(calls_df$OI)
ggplot(calls_df, aes(x = maturity, y = OI, fill = factor(Strike))) +
geom_col(position = "dodge")
| common-pile/stackexchange_filtered |
JQuery : Get div defined in same table row
I have an HTML table created dynamically using an MVC application and the output of the table is as shown below:
In the onclick event of the edit button I want to show divText and hide divLabel of the same row using jQuery.
I have tried to get divLabel as shown below:
function EditRecord(elem) {
var divlabel = $(elem).closest('tr').children('td div#divLabel');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>
<div id="divLabel">
value 1
</div>
<div id="divText" style="display: none">
<input type="text" value="value 1" />
</div>
</td>
<td>
<input type="button" value="edit" onclick="EditRecord(this);" />
</td>
</tr>
<tr>
<td>
<div id="divLabel">
value 2
</div>
<div id="divText" style="display: none">
<input type="text" value="value 1" />
</div>
</td>
<td>
<input type="button" value="edit" onclick="EditRecord(this);" />
</td>
</tr>
</table>
But it is not working for me.
You're pretty close. There are two issues:
Your HTML is invalid. You cannot reuse the same id for multiple elements. You can use a class instead:
<tr>
<td>
<!-- Note 'class' rather than 'id' below -->
<div class="divLabel">
value 1
</div>
<!-- Note 'class' rather than 'id' below -->
<div class="divText" style="display: none">
<input type="text" value="value 1" />
</div>
</td>
<td>
<input type="button" value="edit" onclick="EditRecord(this);" />
</td>
</tr>
closest is right, but children isn't. You want find instead, because the div isn't an immediate child of the row.
So assuming you change your HTML as per #1, we'd use find with a class selector for #2:
function EditRecord(elem) {
var divlabel = $(elem).closest('tr').find('div.divLabel');
}
Agreed that I cannot reuse the same id. Your solution also works just perfect. But I have a question just for knowledge that is it a good practice to set the class="divLabel" even we have not defined class? I know it will not throw any exception.
It is fine to set a class that is not defined in any css file. You can use it in JQuery as a type (like an ID). Avoid using html id where possible, use css classes instead. The benefit comes where you want to same functionality applied to more than one element, just give them the same css class.
@SpiderCode: Yes, that's absolutely fine (quite common, in fact). The class attribute is an HTML and DOM thing, not a CSS thing. CSS has class selectors: Selectors that work according to the HTML class. We frequently talk about "CSS classes," but that's not really accurate. (Amusingly, there was recently a link-post on http://css-tricks.com about this, but I can't find it now...) Think of it this way: Can you use a div even if you don't have any CSS selectors that target div elements? :-)
@T.J.Crowder : Agreed. Thanks for such a useful information.
Try This one It should work for me
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function EditRecord(elem) {
var chg = $(elem).closest('tr').children('td').siblings(':first-child');
chg.find('div:first-child').hide();
chg.find('div:nth-child(2)').show();
}
</script>
</head>
good one. But in future If I have to put some other div between this two and I have implemented this solution then I will have to change JS method as well.
Dont change whole js code only change this two line to this
chg.find('div#divLabel').hide();
chg.find('div#divText').show();
You don't need onclick="EditRecord(this);", delete that out. Doing it that way couples your javascript to your html which you can avoid using jQuery.
In jQuery do it like this
$("input[type='button'][value='edit']").click(function(event) {
var row = $(event.target).closest('tr');
row.find('.divText').show();
row.find('.divLabel').hide();
});
*Note change divText and divLabel to css classes because you can't have two id's in HTML with the same name.
| common-pile/stackexchange_filtered |
Message after a data is inserted
How to make a message appear in the top of the page when a form has been submitted and a record has been inserted in mysql below is my action.php page.
<?php $email =$_POST["email"];
include "includes/db_config.php";
$sql = "INSERT INTO subscribers(email)
VALUES('$email')";
if (mysqli_query($conn, $sql)) {
header('location:index.php?subscribe=yes');
} else {
echo "Failed" . $sql . "<br>" . mysqli_error($conn);
}
?>
and then at index.php
<?php
if ($_GET['subscribe'] =='yes'){
echo 'You succesully subscribe to our exclusive promos';
}
?>
What is the problem with the given code? It's vulnerable to SQL injection, but looks fine otherwise
the message wont appear in the top
Then why don't you structure your code such that this happens, Using CSS or changing the PHP code such that this echo is the first thing to happen?
You can use JavaScript alert box in page index.php for this purpose.
<?php
if ($_GET['subscribe'] =='yes'){
echo '<script language="javascript">';
echo 'alert("Form has been submitted")';
echo '</script>';
}
?>
Hope it helps.
| common-pile/stackexchange_filtered |
Price and settlement gain calculation in options on an index
The Cboe S&P 500 Index Options - SPX are peculiar in that there is no underlying stock or ETF - they trade the index. I want to make sure that I understand the pricing.
On the link above the following sentence can be read:
Large Notional Size -- around $200,000 per Contract with the SPX index at 2000 (10 times that of SPDR options).
Say the S&P 500 is at $2,668.$ Would then a contract have a notional (?) value of $\$266,800$?
Now say that I want to buy a single call option with a strike of $2,710$ expiring May 9, 2018 - it's for illustration only, but the contract does exist: SPXW180509C02710000.
The last trading price is very recent, and at $0.65.$ Assuming that there is no price further price movement, and leaving aside ask/bid differences.
How would I go about calculating the price of $1$ contract?
And assume that the index climbs to $2,800$ (to make things easy) by the expiration date. Evidently I would exercise my option to buy at the strike price of $2,710.$
But what would be the final calculus of the gain minus the purchase price?
Not sure about what follows, but now that the question is "answered" with a hyperlink, I'm taking my chances... Negative feedback will act as an answer by proxy...
The notional value is explained here and here, and compared to other securities trading the index:
Notional value tells us how much total value a security theoretically controls.
Standard equity option contracts control $100$ shares of an underlying. The notional value of these option contracts is $100$ times the current market price of the underlying.
$$\text{Contract Size } \times \text{ Underlying Price} = \text{ Notional Value}$$
If we purchase an at the money (ATM) call trading for $\$2.00$ in $XYZ$ while $XYZ$ is at $\$30.00,$ the notional value of the option will be $\$3,000.00$:
$$100 \text{ shares the option controls} \times \$30.00 \text{ price of the underlying}.$$
Alternatively, the market price of an option contract is how much it currently trades for in the market. In the above example, the ATM call has a market price of $\$200.00$
$$100 \text{ shares the option controls }\times \$2.00 \text{ price of the option contract}.$$
In the case in the question:
The notional value of the option is $\$2,710 \times 100= \$ 271,000.$
The market price is $100 \times \$0.65=\$65.$
In the fictional situation of the S&P 500 reaching $2,800$ before expiration, the payoff would be
$$\begin{align}
&100\,(\,\text{S&P @ selling time } - \text{ strike price }) - \text{option price}\\[2ex]
&=100\,(\,\$2,800-\$2,710)-\$65\\[2ex]&=\$8,935
\end{align}.$$
"The multiplier for CBOE listed S&P500 options is 100". That is all you have to remember, all the calculations you did follow from this.
Thank you, @AlexC. I take it that the calculations are correct. If you find any inclination to give me a formal answer, perhaps explaining a bit what we are trading here, and this "notional value", I'll be happy to accept your answer.
http://www.neweratrader.com/Resources/the-sap-e-min.html This should help explain the tick value and minimum incremental tick size
It's basically what I got directly from the Cboe, and the reason why I posted a question to avoid misunderstandings. It is considered bad form to answer with just a link. What is the added value? We all have Google.
Sorry I thought it was self explanatory
Maybe you should reflect on the fact that you are getting downvotes in all your answers. And teach yourself a much more self-explanatory and trivial thing - you don't just paste the URL; you embed it. This answer is worthless, and you should erase it. I think you are out of your depth in this site.
Have you ever traded? Unless I'm mistaken your profit would be 2800-2710 or $22,500 minus the cost of your option. Is that simple enough?
| common-pile/stackexchange_filtered |
HERE Maps API event delays
When panning a map with the HERE maps API, the 'mapviewchangeend' event is triggered a short time after the animation completes. This means that is difficult to synchronise, say, a Leaflet overlay without the overlaid objects lagging behind.
var map = new H.Map(document.getElementById('mapContainer'),
defaultLayers.normal.map, ...
var lMap = L.map('mapContainer', {zoomControl: false});
...
function onMapViewChange() {
lMap.setView(map.getCenter(), map.getZoom(), {animation: false});
}
map.addEventListener('mapviewchange', function () {
onMapViewChange();
});
map.addEventListener('mapviewchangeend', function () {
onMapViewChange();
});
Is there a way to remove this delay? I have experimented with different kinetic settings for H.mapevents.Behavior but so far without success.
See also http://leafletjs.com/reference.html#map-move
I think you can hook into the sync events being fired by the the view model and the viewport. I seem to recall that these events fire synchronously when the map renders...
After some digging, I found the example showing something very similar on github:
maps-api-for-javascript-examples/ground-overlay
Thanks for the suggestion @echom. It turns out that I was on the wrong track - Leaflet dragging needs to be disabled even if there is no base layer: lMap.dragging.disable() My original code, as well as modified using the viewModel and ViewPort as you suggest now both remove the lag.
| common-pile/stackexchange_filtered |
Prove that if the derivative $f'(x)$ of a function exists on the measurable set $E$, then $f'(x)$ is measurable on $E$.
Prove that if the derivative $f'(x)$ of a function exists on the measurable set $E$, then $f'(x)$ is measurable on $E$.
We are told to only consider 1 dimensional spaces,that f is a measurable function in one variable.that is, f is a measurable function in one variable.
Following is my solution, I am not sure whether I am on the right track.Can someone have a look? Many thanks, I can explain further if I should.
Thanks in advance!
Lovely neat work by you.
@JpMcCarthy,hi, so you think this done the job?
Possible duplicate of Differentiable function has measurable derivative?
Sorry for the late answer
It seems to me there are two flaws in your proof.
Actually, for $x \in E$, $h_n(x)$ needs not tend towards $f'(x)$. Consider for instance$$f : x \longmapsto\begin{cases}
1&\text{if $x \le 0$ or $x \notin \mathbb{Q}$}\\
1+x^2&\text{otherwise}
\end{cases}$$
Then you can check that $f$ is differentiable on $]-\infty,0]$ with derivative $0$, but $f$ is discontinuous on $]0,+\infty[$. Thus $g : x \mapsto\begin{cases}
1&\text{if $x \le 0$}\\
0&\text{if $x>0$}
\end{cases} \ \ $ so $h_n(0) \underset{n \to + \infty}{\longrightarrow} + \infty$, and so $\big(h_n(x)\big)_{n \ge 1}$ does not converge to $f'(0) = 0$. Note that, using a Cantor set, you can adapt this so that $h_n$ does not converge to $f'(x)$ on a subset of $E$ with positive measure.
Moreover, your last claim at the end of the proof (with some set being countable, or having zero measure) also seems false to me.
More constructively, I think that you can follow the standard reasoning to prove your result.
For $n \in \mathbb{N}^*$, denote $g_n : x \mapsto n \left ( f\big( x + \frac{1}{n} \big) - f(x) \right)$. We consider that $f'$ is defined on $E$. Then $(g_n)$ converges pointwise to $f'$ on $E$.
We take an closed set $C \subset \mathbb{R}$, and we want to prove that $f'^{-1} (C)$ is measurable.
For every $x \in f'^{-1}(C)$, for $k \in \mathbb{N}^*$, $d \big( g_k(x), C \big) \le d \big( g_k(x), f'(x) \big) \underset{k \to + \infty}{\longrightarrow} 0$. Now for $n \in \mathbb{N}^*$, we denote the open set $C_n = \left \{ y \in \mathbb{R},\ d(y, C) < \frac{1}{n} \right \}$. Using the previous inequality, we get that for all $n \in \mathbb{N}^*$, there exists $m>n$ such that $g_m(x) \in C_n$, so $x \in g_m^{-1} (C_n)$. Moreover, $x \in E$. Hence
$$ f'^{-1}(C) \subset \bigcap \limits_{n \in \mathbb{N}^*} \bigcup \limits_{m \ge n} E \cap g_m^{-1} (C_n)$$
Now for the other inclusion, with $x$ in the RHS set, you have a sequence of integers $(m_n)$ such that for all $n > 1$, $m_n \ge n\ $ and $\ d \big ( g_m(x), C \big) \le \frac{1}{n}$, so using pointwise convergence, as $x \in E$, $d \big( f'(x), C \big) = 0$, and $C$ is closed, so $f'(x) \in C$, and thus $x \in f'^{-1}(C)$.
Hence $f'^{-1}(C) = \bigcap \limits_{n \in \mathbb{N}^*} \bigcup \limits_{m \ge n} E \cap g_m^{-1} (C_n)$ and every set $g_m^{-1}(C_n)$ is measurable because $C_n$ is Borel and $g_m$ is measurable (because $f$ is measurable). As $E$ is also measurable, we get an intersection of unions of measurable sets, so $f'^{-1}(C)$ is measurable.
Finally, we get that $f'$ is measurable on $E$.
If $f:[a, b]\to\mathbb{R}$ arbitrary function, then the $$\text{upper derivative }\overline{D}f(x) := \limsup_{y\to x} \frac{f(x)-f(y)}{x-y}$$ and $$\text{lower derivative }\underline{D}f(x) := \liminf_{y\to x} \frac{f(x)-f(y)}{x-y}$$ are always measurable. Thus the set $E = \{x\in [a, b] : \overline{D}f(x) = \underline{D}f(x)\in\mathbb{R}\}$ is measurable, and so is $f':E\to\mathbb{R}$ since $f'\restriction_E = \overline{D}f\restriction_E$.
The proof that the upper and lower derivatives are measurable involves the following lemma:
Lemma. If $\mathcal{A}$ is an arbitrary family of closed non-degenerate intervals, then $\bigcup \mathcal{A}$ is measurable.
Proof: Let $\mathcal{K}$ the family of all closed non-degenerate intervals which are subsets of some $I\in\mathcal{A}$. Then $\mathcal{K}$ is a Vitali covering of $\bigcup \mathcal{A}$, so by Vitali's covering theorem there are intervals $I_1, I_2, ...\in \mathcal{K}$ such that $Z = \bigcup \mathcal{A}\setminus \bigcup_{n=1}^\infty I_n$ is of measure zero, so $\bigcup\mathcal{A} = Z\cup \bigcup_{n=1}^\infty I_n$ is measurable $\square$
Theorem. Upper and lower derivatives are measurable.
Sketch of proof: Consider some $r$ and sets $$E_n^k = \bigcup\left\{[c, d]\subseteq [a, b] : 0 < d-c\leq \frac{1}{k},\ \frac{f(d)-f(c)}{d-c}\geq r+\frac{1}{n}\right\},\ k, n\in\mathbb{N}.$$
From above lemma, the sets $E_n^k$ are measurable. Let $E = \{x\in [a, b] : \overline{D}f(x) > r\}.$ Its not hard to show that the equality $E = \bigcup_{n=1}^\infty \bigcap_{k=1}^\infty E_n^k$ is true (see comment after proof). Thus $E$ is measurable. Since $r$ was arbitrary, $\overline{D}f$ is measurable. Since $\underline{D}f = -\overline{D}(-f)$, the lower derivative is also measurable. $\square$
The inclusion $\bigcup_{n=1}^\infty\bigcap_{k=1}^\infty E_n^k\subseteq E$ in above proof might be trickier to see without some argument. To show it, note that if $x\in (c, d)$ then we can write $$\frac{f(d)-f(c)}{d-c} = \frac{d-x}{d-c}\cdot \frac{f(d)-f(x)}{d-x} + \frac{x-c}{d-c}\cdot\frac{f(x)-f(c)}{x-c}$$ where $\frac{d-x}{d-c}, \frac{x-c}{d-c}\geq 0$ and $\frac{d-x}{d-c}+\frac{x-c}{d-c} = 1$, which makes the above quotient a convex combination of quotients involving $x$.
| common-pile/stackexchange_filtered |
Javascript parse response text from xmlhttpresponse
I have the following text returned in an xmlhttpresponse and I need to parse it by the pipe separator. It should return an array where position 0 is Block1, position 1 is the nodename json data, position 2 is the userid data.
({"body": "Block1|[{\"nodeName\":\"DIV\",\"nodeIndex\":20,\"x_offset\":131,\"y_offset\":47}]|33|7|33|[{\"UserID\":\"d8b4e408-b013-417c08aaa-7cd3658f4160_05_01_2015_21_32_46_000\",\"os\":\"Windows\",\"browser_width\":1366,\"Count\":16}}]"})
I have tried this but having a brain lapse at the moment trying to figure out the solution.
function outputResult() {
var response = invocation.responseText;
var textDiv = document.getElementById("textDiv");
textDiv.innerHTML += response;
var arr = response.body.split("|");
console.log(arr[0])
}
Can you explain in more detail what you are trying to do in your function? It really doesn't make much sense to me. Why are you assigning the text to a div and then splitting it afterward? What is the data source and why does it insert these pipes in the data?
I am saving round trips to the server...get everything i need and return to the client, the Block1 data could have 10k items, so one shot saves the user time.
You need to parse the JSON data after split the string with '|' character, like the code in the for loop:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>result</h1>
<div id="textDiv"></div>
<script>
function outputResult() {
var response = ({"body": "Block1|[{\"nodeName\":\"DIV\",\"nodeIndex\":20,\"x_offset\":131,\"y_offset\":47}]|33|7|33|[{\"UserID\":\"d8b4e408-b013-417c08aaa-7cd3658f4160_05_01_2015_21_32_46_000\",\"os\":\"Windows\",\"browser_width\":1366,\"Count\":16}]"});
var textDiv = document.getElementById("textDiv");
textDiv.innerHTML += response;
var arr = response.body.split("|");
for(var i in arr){
if(arr[i].indexOf('[') === 0)
arr[i] = JSON.parse(arr[i]);
}
console.log(arr);
}
outputResult();
</script>
</body>
</html>
However, textDiv.innerHTML += response; will not show the response text as you may expect. Instead, it will be rendered as [object Object] , so you have to manually set the format to be displayed.
Don't think that will work as the incoming data is a string and not in a format that can be easily converted to an object. It would need to be cleaned up first before applying JSON.parse() or eval() to the parts. The best solution, if possible, would be to change the data source to output data in a more usable form.
@coderLMN I get undefined on the split...your suggestion is what would normally work if I were using jquery, but need it in javascript.
@Rob I updated my answer, putting the whole HTML file in. I tested it in Chrome browser. You can copy and save it to a .html file, open the file in a browser, and see the result in console output. It's pure javascript, and has nothing to do with jQuery or any other library.
| common-pile/stackexchange_filtered |
Why is the default port for my local react application 8080?
When I create a local react application, the default url is
http://localhost:8088/
But should it not better be port 80, since port 80 is the port for web server that listening to http requests?
I'm sorry by the way. It seems I've misread the 8088 for 8080.. For 8088 I would look at the answer from this post: https://serverfault.com/questions/398462/what-is-radan-http/398464
It seems that the port once WAS vendor specific but is now publicly used. In terms of what works it doesn't really matter which port it is, as long it isn't used by anything else. But it's always good to use standard ports. For example for https servers/services that would be 80 or 8080, etc...
[Edit: 26th August 2020]
I'm sorry by the way. It seems I've misread the 8088 for 8080.. For 8088 I would look at the answer from this post: https://serverfault.com/questions/398462/what-is-radan-http/398464
It seems that the port once WAS vendor specific but is now publicly used. In terms of what works it doesn't really matter which port it is, as long it isn't used by anything else. But it's always good to use standard ports. For example for http servers/services that would be 80 or 8080, etc...
[Original Answer]
To answer I qoute from the GRC:
port 8080 was often chosen as a convenient place to host a secondary or alternate web server.
For more information about that, here is the link to the definition. Look under "Background and Additional Information:"
https://www.grc.com/port_8080.htm
thanks for your answer. still confused, so why we need to use a secondary port? why not use port 80 directly?
| common-pile/stackexchange_filtered |
Does traffic policing reduce transmission speed or it reduces the speed of the interface in which it was configured?
I have a question about traffic policing and more specifically, related to traffic control (tc) in Linux. I'm not too familiar with networking, so please excuse my technical terms.
I have configured eth0 of my Linux test server (within LAN) to police incoming traffic to 56kbits. I then fired up WinSCP on my client and try copying a 10MB file to the test server. speed is indeed reduced to 56kbits.
In situation like these, does that mean that my even when I'm on a 100Mbits network, my transmission speed between client and server is only at 56kbits? Or is eth0 slows in accepting the incoming packets?
http://www.cisco.com/en/US/tech/tk543/tk545/technologies_tech_note09186a00800a3a25.shtml#policingvsshaping
It depends upon your config?
Don't you answer your own question?
my Linux test server (within LAN)
does that mean that my even when I'm on a 100Mbits network
Isn't your LAN test server on at least a 100Mbits network...?
However: Traffic shaping does not influence the network on layer 2. Your NIC will continue to accept packets at 100Mbit/s. But every traffic (of the shaped type) above the configured limit will be thrown away by the shaper. This gets detected (so far the theory) on higher levels (TCP or the UDP application) so that the communication partners reduce the amount of data they send respectively.
| common-pile/stackexchange_filtered |
Plugin dependency has package for which I get a "type <type> cannot be resolved" error
I don't know what I did, but what was once working no longer works.
I am calling a function that returns an instance of a particular class, call it MyClass. MyClass depends on another class, MyOtherClass that is defined in a package. This package (call it com.myotherpackage) is contained in a plugin (call it com.myotherplugin) listed in the dependencies section of my plugin manifest. When I call that function, I get the error "The type com.myotherpackage.MyOtherClass cannot be resolved. It is indirectly referenced from required .class file."
What could I have done to cause this error to crop up where previously the error wasn't present and my code ran just fine?
I've searched for solutions. They all seem to focus on non-plugin environments. One such solution had something that I could map to a plugin. It suggested I configure my build path (right click on project -> Build Path -> Configure Build Path). From this dialog, I selected the Libraries tab, clicked the arrow next to Plug-in Dependencies, then clicked the arrow next to com.myotherplugin, then clicked the arrow next to Access rules, and found that there is a checked check box next to the words "Accessible: com/myotherpackage/*". Thus the package appears to be available though I have no information from this view that MyOtherClass is contained in that package.
Any ideas would be appreciated.
You have to export com.myotherpackage in the manifest of com.myotherplugin. You can do so in the Plug-in Manifest Editor on the Runtime page.
Also Eclipse usually provides a Quick Fix for these kind of errors, which make the required changes in the manifest file.
Thanks for the response. It is already being exported (I just double-checked -- but this is also evidenced by the accessibility check of the package). Also, Quick Fix provides nothing of use.
I don't like this answer, but reinstalling the IDE did the trick (i.e., unzipping from source). Note that my instance of the IDE comes with com.myotherplugin.
I have no idea what I broke.
| common-pile/stackexchange_filtered |
Passing values into a Vector3f
I want to be able to pass 3 values to an object which are then stored in a class called Vector3f. Vector3f has x,y,z values;
I.e:
Object(Vector3f Position); //Class constructor
Object myObject(0,10,20); //Declare object
Is this right?
Or would I have to do:
Vector3f vect(0,10,20);
Object myObject(vect);
Any help please?
If the constructor takes a single Vector3f argument, you'll have to pass it a single Vector3f object, and three floats won't work. But you can write that in a single line:
Object myObject(Vector3f(0, 10, 20));
You could also declare an additional constructor that accepts three floats instead.
Or Object myObject({ 0, 10, 20 }) uniform initialization FTW.
@mfontanini In the compilers which support it.
the second one because multiple arguments constructor cannot be implicit converted
although with C++11 you can do Object myObject({0, 10, 20});
Without additional information, you should do as your second way:
Vector3f vect(0,10,20);
Object myObject(vect);
Or
Vector3f myObject(vect(0,10,20));
This will first create an object of Vector3f then pass it as parameter to Object class's constructor, which takes object of Vector3f as parameter.
| common-pile/stackexchange_filtered |
Creating an IF statement in Python that looks at previous IF statement output
I am having difficulty creating an IF statement that does the following:
If C1 = Buy, then Buy
If C2 = Sell, then Sell
If C1 & C2 = nan, then the current cell = previous cell
Please see an example below. I am hoping to create a column like 'C3'.
Sample Dataset:
index C1 C2
0 Buy nan
1 nan nan
2 nan Sell
3 nan nan
4 Buy nan
5 nan Sell
6 nan Sell
7 nan nan
8 nan nan
9 Buy nan
10 nan Sell
Output:
index C1 C2 C3
0 Buy nan Buy
1 nan nan Buy
2 nan Sell Sell
3 nan nan Sell
4 Buy nan Buy
5 nan Sell Sell
6 nan Sell Sell
7 nan nan Sell
8 nan nan Sell
9 Buy nan Buy
10 nan Sell Sell
You can use pd.DataFrame.ffill along axis=1 followed by pd.Series.ffill:
df['C3'] = df[['C1', 'C2']].ffill(axis=1).iloc[:, -1].ffill()
print(df)
index C1 C2 C3
0 0 Buy NaN Buy
1 1 NaN NaN Buy
2 2 NaN Sell Sell
3 3 NaN NaN Sell
4 4 Buy NaN Buy
5 5 NaN Sell Sell
6 6 NaN Sell Sell
7 7 NaN NaN Sell
8 8 NaN NaN Sell
9 9 Buy NaN Buy
10 10 NaN Sell Sell
Instead of doing the previous if statement, you can simply look at what has been previously put into the c3 list (as that is a result of the previous if statement).
Here is an example of how you can achieve this in python:
c1 = ["Buy", "nan", "nan", "nan", "Buy", "nan", "nan", "nan", "nan", "Buy", "nan"]
c2 = ["nan", "nan", "Sell", "nan", "nan", "Sell", "Sell", "nan", "nan", "nan", "Sell"]
c3 = []
for index in range(len(c1)):
if c1[index] == "Buy":
c3.append("Buy")
elif c2[index] == "Sell":
c3.append("Sell")
elif c1[index] == "nan" and c2[index] == "nan": # Implied if reached this point (so else would also suffice here)
c3.append(c3[index-1]) # look at previous result in list
print(c3)
Output:
['Buy', 'Buy', 'Sell', 'Sell', 'Buy', 'Sell', 'Sell', 'Sell', 'Sell', 'Buy', 'Sell']
Works perfectly. Thanks.
I would not recommend this solution as it is non-vectorised. The main benefit of Pandas is vectorised operations, i.e. avoidance of explicit for loops.
Here's a tidy way to do it using Pandas: Swap all the NaN for empty strings, and return whatever string value is in each row. If a row is empty, return what came before it.
import pandas as pd
def decide(data):
if len(data.sum()):
return data.sum()
return decide(df.iloc[data.name - 1])
df.fillna("", inplace=True)
df.apply(decide, axis=1)
Output:
index
0 Buy
1 Buy
2 Sell
3 Sell
4 Buy
5 Sell
6 Sell
7 Sell
8 Sell
9 Buy
10 Sell
dtype: object
Note: Making a couple of assumptions here. First, assuming only Buy or Sell occurs in a row. Second, assuming first row is not empty.
Data:
df = pd.read_clipboard(index_col="index") # copied from OP
| common-pile/stackexchange_filtered |
Inserting data to MySQL with VB .NET
Please help, whats wrong with my vb.net code to insert values in an MySQL database
Dim conn As New MySqlConnection(ConfigurationManager.ConnectionStrings("ibdm").ConnectionString)
Dim cmd1 As New MySqlCommand("INSERT INTO configs(configType, portsStatus, bandwidthLimit, ports, user) values(@config, @manage, @limit, @ports, @user)", conn)
Try
conn.Open()
cmd1.ExecuteNonQuery()
iReturn = True
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
iReturn = False
Finally
conn.Close()
End Try
Can you give some indication of the error you are getting to help solve yout problem?
User my be a reserved word, try putting it in square brackets:
Dim cmd1 As New MySqlCommand("INSERT INTO configs(configType, portsStatus, bandwidthLimit, ports, [user]) values(@config, @manage, @limit, @ports, @user)", conn)
I think you have to specify value in quote's like
Dim cmd1 As New MySqlCommand("INSERT INTO configs(configType, portsStatus, bandwidthLimit, ports, user) values('@config', '@manage', '@limit', '@ports', '@user')", conn)
| common-pile/stackexchange_filtered |
Update database with a live choice made by client
How to update a specific cell in phpmyadmin with jQuery after appending a specific div to a group, code is below
<div id="item1">Item 1
<input type="button" value="put me in Group1" name="I1G1"> <!-- I1=Item1 / G1=Group1-->
<input type="button" value="put me in Group2" name="I2G2">
</div><br><br>
<div id="item2">Item 2
<input type="button" value="put me in 1" name="I2G1">
<input type="button" value="put me in 2" name="I2G2">
</div><br><br>
<div id="Group1">Group 1</div><br>
<div id="Group2">Group 2</div><br>
<script>
$('input[name$="I1G1"]').click(function(){
$("#item1").appendTo("#Group1");
$(this).hide();
$('input[name$="I1G2"]').hide();
<?php $UPDATE = mysqli_query($conn, "UPDATE results SET round = 'Group 1' WHERE team = 'Item 1'"); ?>
});
$('input[name$="I1G2"]').click(function(){
$("#item1").appendTo("#Group2");
$(this).hide();
$('input[name$="I1G1"]').hide();
<?php $UPDATE = mysqli_query($conn, "UPDATE results SET round = 'Group 2' WHERE team = 'Item 1'"); ?>
});
//same jQuery code with 2nd item
</script>
the problem is when the item getting updated in database, it became always Group 2 which is the second update. So how to update the database with the selected group
on a side question is it better to use dropdown list or buttons in selecting groups
your code will never get the result you want. PHP is server side and will run before page load(so all your queries will run one after the other when your browser request the page). Javascript is client side and will run after the page is load. For what you need you have to remove the php statements frome the page and add an ajax call to php to update the db.
You need to create a <form> element that uses the POST method to a php script.
<form id='my_form' action='my_db_script.php' method='POST'>
// form elements
</form>
In your php script you would use $_POST['my_option'] to get a form option by its name... you can execute your sql in the php file.
Since you tagged jquery, you could also use the jquery onsubmit event with $.ajax: (documentation)
$("#my_form").onsubmit(function() {
$.post({
// my options
});
});
thank you but the problem is there will be 58 items needed to be appended to groups in-order to take items in each group and add its items in subgroups
| common-pile/stackexchange_filtered |
Affix NavBar overlaps the body when zooming
Is there any way to prevent the navbar(with bootstrap affix plugin) from overlaping the body as it's shown here ?
If it's on a touch device: https://github.com/twbs/bootstrap/issues/12157 -- the answer is no
okay i'll leave like that :(
| common-pile/stackexchange_filtered |
how to access many parameters from the GUI
I am writing a Java application that takes a lot of parameters as input (~100). I am exposing some of the in the GUI, but of course it is impossible to show all of them at once.
I am curious if there is a shared way to let a user access a large amount of parameters like that. Right now, I have some buttons in the GUI, and each of them opens a JPanel which show a sub-set of the parameters. Is this a common solution? or are there more efficient solution from a human-interface point of view?
Thank you in advance for your advices,
Simone
One way I've found effective is to have a single-selection JTree on the left side of the user interface. Whenever the user selects a tree node, a corresponding panel is shown on the right. I typically will place all the panels into a CardLayout to ensure the UI's preferred size accommodates all of them.
This has the advantage of allowing you organize your information hierarchically.
I think it makes a lot of difference how that mass of information is best understood by the user. Is it something organized in categories, that the user will want to browse through? Are there salient parameters that the user is more likely to want to know, and so should be made more easily accessible? You could have a tabbed panel with tabs for groups of parameters, you can alphabetize them and color them and put them in different fonts, etc., but there isn't going to be one answer regardless of what the parameters are.
I would suggest a wizard that guides the user through all parameters. All general information on user interface creating you can refer to ISO DIN 9241.
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.