text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How to run electrical wires in an exterior wall with a low-pitched roof?
I am hoping to run electrical wires in my exterior walls, but I have a very low pitched roof which makes it tough to get to that part of the attic. To give some examples:
One of my switches does not have a neutral wire, I'd like to run a 14/3 wire from the light to the switch to bring the neutral to the switch.
I only have one exterior light by my garage door (on one side of the garage), and I'd like to install a matching set of exterior lights, one on each side of the garage door, to better illuminate the driveway at night.
One of my bathrooms is near an exterior wall, and I want to rewire the switches so that the lights operate in a way that makes more sense. An electrician installed an extra can light, by tying it into the fan, rather than the same switch as the over-vanity light, leaving me with a situation where one switch has a light; and the other switch has a light and a fan. I'd like to adjust this so the lights are on one switch circuit, and the fan is on the second switch circuit. This isn't actually in the exterior wall, but just off of it, so it's the same problem of getting physically into the space.
This may seem like multiple questions at once, but the problem is actually all the same: Of course, it's tough to run wire through the exterior wall if I can't get physical access to the part of the attic. There just isn't the space for a human body to get in there.
So what is the solution? Is there a way to run electrical wires to a location in an exterior wall when you have a low-pitched roof? Or am I stuck with what I've got?
A:
I've run into this often and have become very successful at getting into corners of the attic I never thought I'd be able to. Sometimes you have to flat crawl on the joists.
What has also worked is cutting out a square in the wall inside the room at the ceiling height and using that as a pull station. You will probably have to drill through a sill plate but then shove the wire up into the attic, lots of it. Then go into the attic with your snake or a 10' piece of EMT with a 90 degree bend at the end and snag the wire and pull it toward you. Feed more from the inside room or pull out the slack. Use the same hole in the wall to drop the wire down to the switch location. When finished, repair the drywall using the piece you cut out. At times, you might have to cut the square into the ceiling too.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to get the Column of a matrix in Ocaml
I want to print out the column of a matrix but i keep getting an error.
Error: This expression has type 'a list but an expression was expected of type int
let rec get_column2 mat x = match mat with
| [] -> raise (Failure "empty list")
| h::t -> if x = 1 then h else get_column2 t (x-1);;
let rec get_column mat x= match mat with
| [] -> raise (Failure "empty list")
| []::tv -> get_column tv x
| hv::tv -> get_column2 hv x::get_column tv x;;
Matrix example [[2;5;6];[3;5;3][3;6;8]]
The first part works fine on type int list so I added the second part to go through the int list list and cut them into int list's and then tryed to get the columns of each separately.
I also tryed it this way:
let rec get_column mat x =
let rec column matr y =
if matr = [] then raise (Failure "empty list") else
if y = 1 then List.hd matr else
column (List.tl matr) y-1;
in column (List.hd mat) x :: get_column (List.tl mat) x;;
The second example translates fine but then doesn't work. I get an Exception "tl". (I'm not sure the function nesting is done right since I'm just learning Ocaml).
A:
get_column2 - your first function, works as it should. That is it will fetch the value of each row in the matrix. It's a good helper function for you to extract the value from a list.
Your second function get_column gets all the types right, and you're accumulating everything, except that instead of stopping when you have an empty list [] you end up throwing an exception. That is your matrix example will go through just nicely, until it has no more lists to go through, then it will always throw the exception. (because the recursion keeps going till it's an empty list, and Ocaml will do as you told it too, fail when it gets an empty list.
The only thing you were missing was the exception, instead of throwing an exception, just return an empty list. That way your recursion will go all the way and accumulate till it's an empty list, and at the final step where the matrix is empty, it will append the empty list to the result, and you're golden.
So your code should be:
let rec get_column2 mat x = match mat with
| [] -> raise (Failure "empty list")
| h::t -> if x = 1 then h else get_column2 t (x-1)
let rec get_column mat x= match mat with
| [] -> [] (*doesn't throw an exception here*)
| []::tv -> get_column tv x
| hv::tv -> (get_column2 hv x)::get_column tv x
Instead of throwing the exception when it's an empty list, maybe you could check if the value of x is more than the length of the inner list.
Also, here's my implementation of doing it. It's still fairly basic as it doesn't use List.iter which everyone loves, but it doesn't rely on any additional packages. It makes use of nested functions so you don't expose them everywhere and pollute the namespace.
(*mat is a list of int list*)
let get_col mat x =
let rec helper rows x = (*helper function that gets the value at x*)
match rows with
| [] -> raise (Failure "empty list")
| h::t -> if x = 1 then h else helper t (x-1)
in
let rec wrapper mat= (*function that walks through all the rows*)
match mat with
| [] -> []
| rows::tl -> (helper rows x)::(wrapper tl) (*keep accumulating value*)
in wrapper mat
How you can visualize the [] -> [] part is that when the recursion is at it's final stage (mat is reduced to an empty list), the wrapper function returns the empty list, which will be appended to the recursion stack (since we are accumulating the values in a list as per (helper rows x)::(wrapper tl)), and the recursion will complete.
You don't hit this error with your get_column2 as you tell ocaml to stop recursing and return a value when x=1.
Edit, Additional:
As Jeffrey mentioned, a much more elegant way of handling the error is adding the case for [row], where row is the last row in the matrix. You just return (helper row x) there. And you could have the empty matrix as a failure.
Example using your code:
let rec get_column mat x= match mat with
| [] -> raise (Failure "empty list") (*fail here, as we don't want to compute a matrix with no rows.*)
| [tv] -> get_column tv x (*just return the value*)
| hv::tv -> (get_column2 hv x)::get_column tv x
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Flash AS2 detecting dynamically attached components are initialised
OK, driving myself mad trying to remember AS2 here, hoping for someone with better memory to lend a hand...
Basically, my problem is using composition and 'waiting' for components - eg. a Button component - to be ready to attach a click handler..for various reasons I can't do anything about the whole setup so here's the situation...
I have a movieclip in the library, no class, just a linkage ID ("AttachMe"). That clip has an AS2 Button component inside it ('btn').
I have a class that gets a reference to a timeline, then attaches the mc from the library, then adds an event listener to the button. Simple right?
var foo:Foo = new Foo(this);
class Foo {
private var tl:MovieClip; // timeline
private var mc:MovieClip; // the attached movieclip
function Foo(t:MovieClip){
tl = t;
mc = tl.attachMovie("AttachMe", "mc", 10);
var b:Button = mc.btn;
b.addEventListener("click", Delegate.create(this, onClick));
}
private function onClick(e:Object):Void{
trace("Hi!");
}
}
This won't work, as b.addEventListener is undefined at the point I'm doing it...
So really, what is best practice here? i.e. this is a real pain, and I know it's the case of 'waiting' for the button component (in this case) to initialise before adding the event handler.
Could do an interval/timeout - hate the idea of that. Could do enterFrame on the mc, clear it on first call then add the handler..again, just seems wrong.
onLoad doesn't fire for the movieclip so can't add that (if I used inheritance and a custom sub class for the library movieclip I could use onLoad).
Each way seems to be a hack and the thought of doing many times is depressing! It must have been done to death over the years, but I really can't find anything directly mentioning the problem and accepted solutions...
Any thoughts appreciated!
Rich
A:
Right, third attempt, and I've marked the other answers for deletion. After getting into the UIObject and Button classes I came up with this, which seems to work:
import mx.utils.Delegate;
import mx.controls.Button;
import mx.events.EventDispatcher;
class Foo {
private var tl:MovieClip; // timeline
private var mc:MovieClip; // the attached movieclip
function Foo(t:MovieClip)
{
tl = t;
mc = tl.attachMovie("AttachMe", "mc", 10);
var b:Button = mc.btn;
EventDispatcher.initialize(b);
b.addEventListener("click", Delegate.create(this, onClick));
}
private function onClick(e:Object):Void
{
trace("Hi!");
}
}
This important bit is EventDispatcher.initialize(b); which seems to force the methods into existence straight away.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I fix the built-in Windows Firewall which is blocking packets despite a configured exception?
I have configured my built-in Windows Firewall (Windows XP SP3) to allow this box to serve as a local FTP server (FileZilla server). The configuration was working until <insert some recent date>.
Specifically, I had configured these exceptions on the Windows Firewall -> Exceptions tab:
File Transfer Program (C:\WINDOWS\system32\ftp.exe) scope of "Any computer"
FileZilla (C:\Program Files\FileZilla\FileZilla.exe) scope of "My network (subnet) only"
ftp-data01 (Port number: TCP 2001) scope of "My network (subnet) only"
. . . similar rules down to port 2010
As mentioned, this configuration was working until recently. If I look at the Windows Firewall Security Logging, I can see that the TCP SYN packets from my client to this server's port 21 are being dropped.
How should I configure Windows Firewall to allow the packets?
One solution that works is to use the "Advanced" tab -> "Local Area Connection" settings and enable "FTP Server", but the dialog box states that opens the exception for Internet access. I am looking for a solution that allows access for only the local subnet.
A:
First, try to figure out what happened on the date in question. Did your system install an update? Did you change the configuration of some other security related application, such as an Anti-Virus or Anti-Spyware application? Did something change your network configuration? Did you install a VPN or SSL-VPN client which may have affected your systems internal routing tables?
If you can figure out what changed, try and see if you can undo the change. Just be warned, undoing may not be possible for a variety of reasons. For the case that raised this question, it a change to the anti-spyware application coincided with the break in FTP service, but it was not possible to restore functionality by restoring the anti-spyware application configuration.
One solution is, on the Windows Firewall Exceptions tab, create an exception for Port 21 TCP and then scope the exception for "My network (subnet) only. Essentially, one is duplicating the functionality from the "Advanced Tab", but the Exceptions tab allows for the limit of scope.
This exception allows one to delete the "FileZilla" application exception and still permit access to the ftp server. The File Transfer Program exception is a red herring - that entry allows the ftp client on the server to access ftp servers on other hosts. The next time one tries to use the ftp client, Windows Firewall will pop-up a dialog box to create the exception, assuming a default configuration of Windows Firewall.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Saving Source of Self (PHP)
Okay, so I have this strange problem. And ah, no solution. Can somebody please help me or send me off in the right direction?
I have a simple HTML page, and I need to be able to have a 'Save' button on the page that the user will click. And upon clicking that save button, PHP will then save a copy of the current page the user is on to the same directory on my server.
Is this even possible?x
Thanks!
Any help at all is much appreciated
A:
You probably need to do something with Ajax. If you're using jQuery you could get the entire HTML of the page using $('body').html() and send that with an Ajax POST.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JTable in Swing has no header
For some reason my JTable won't display the headers that are in my table model. Also I need the the table in a scroll pane and that seems to delete the whole table. This is in Java Swing.
package table;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
public class TableIcon extends JFrame{
public TableIcon(){
TableModel tableModel = new TableModel();
JTable table = new JTable(tableModel);
JScrollPane spTable = new JScrollPane();
spTable.add(table);
this.add( spTable);
this.add(table);
}
//spTable = new JScrollPane();
//spTable.add(table);
public static void main(String[] args)
{
TableIcon frame = new TableIcon();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
package table;
import javax.swing.table.AbstractTableModel;
/*** Class that sets up a table model for a downloaded batch***/
@SuppressWarnings("serial")
public class TableModel extends AbstractTableModel {
public TableModel() {
super();
}
@Override
public int getRowCount() {
return 5;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int column) {
if (column == 0) {
return "Record Number";
} else {
return "happy";
}
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0)
return rowIndex + 1;
else
return 3;
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (columnIndex == 0)
return false;
else
return true;
}
}
A:
You should not add components to a scroll pane. Instead you set the view. That can be done easiest by using a constructor parameter:
JScrollPane spTable = new JScrollPane(table);
this.add(spTable);
Also, delete this row, the table is already in the scroll pane:
this.add(table);
Furthermore, it's better just to use a JFrame, instead of extending one. Finally, you should create the GUI in the event dispatch thread.
A:
You should create your JScrollPane using the constructor that takes a JTable like this:
JScrollPane spTable = new JScrollPane(table);
this.add( spTable);
There is no need to call either spTable.add(table); or this.add(table); because spTable already includes table.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
what is the best suggested way to design a form having more than 20 fields?
I am having a form having around 20-25 fields. I have put all these fields on one page and a submit button to complete my functionlaity. But i am not happy with the length of page and feel like users will be demotivated using this page can somebody help me with suggestions?
A:
Wizards are also more prone to errors,
What you could do (depends on the context and contents of your form) is try to hide parts of your form until they are relevant. For example, in a form where I can choose to receive annoying spam at my home address, I would tick the box "yes I want to be annoyed" and only then will the fields where I enter my address data (street, ZIP, city, etc.) appear.
How effective this is for you depends, of course, on the context of your form.
Perhaps you could shed some light on this?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to access Session from a custom data annotation in an ASP.NET MVC project?
For some experimental/exercise purposes, I'm trying to implement a primitive login system before proceeding to Identity services.
My idea was creating a custom data annotation -just like [Authorize] of Identity- and passing inputted form data carried by Session[]. Hence, I would use my custom annotation to authorize certain controllers or methods.
public class IdCheck: ValidationAttribute
{
public string currentId { get; set; }
public override bool IsValid(object value)
{
currentId = value as string;
if (currentId != null)
{
return true;
}
else
{
return false;
}
}
}
and I tried to use it like that:
[IdCheck(currentId = Session["UserId"])]
public class SomeController : Controller
{
//methods
}
However, I got an error with the message: "An object reference is required for the non static field, method or property 'Controller.Session'"
I can neither access the Session[] before a controller nor before method declaration. I have no idea how to instantiate or refere.
Is there a way to utilize Session[] in my case? Because I don't want to manually check each method with if statements like
if(Session["UserId"] != null) {}
Any alternative solution is more than welcomed.
Note: I am aware of that using Session is not a recommended way of implementing such a task. But my intention is to have an understanding of how login operations work before utilizing advanced Identity services.
A:
Is there a way to utilize Session[] in my case?
Not as you're doing now, but you could use HttpContext.Current.Session inside your custom attribute code instead of passing it as property.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to use `SqlDbType.Structured` to pass Table-Valued Parameters in NHibernate?
I want to pass a collection of ids to a stored procedure that will be mapped using NHibernate. This technique was introduced in Sql Server 2008 ( more info here => Table-Valued Parameters ). I just don't want to pass multiple ids within an nvarchar parameter and then chop its value on the SQL Server side.
A:
My first, ad hoc, idea was to implement my own IType.
public class Sql2008Structured : IType {
private static readonly SqlType[] x = new[] { new SqlType(DbType.Object) };
public SqlType[] SqlTypes(NHibernate.Engine.IMapping mapping) {
return x;
}
public bool IsCollectionType {
get { return true; }
}
public int GetColumnSpan(NHibernate.Engine.IMapping mapping) {
return 1;
}
public void NullSafeSet(DbCommand st, object value, int index, NHibernate.Engine.ISessionImplementor session) {
var s = st as SqlCommand;
if (s != null) {
s.Parameters[index].SqlDbType = SqlDbType.Structured;
s.Parameters[index].TypeName = "IntTable";
s.Parameters[index].Value = value;
}
else {
throw new NotImplementedException();
}
}
#region IType Members...
#region ICacheAssembler Members...
}
No more methods are implemented; a throw new NotImplementedException(); is in all the rest. Next, I created a simple extension for IQuery.
public static class StructuredExtensions {
private static readonly Sql2008Structured structured = new Sql2008Structured();
public static IQuery SetStructured(this IQuery query, string name, DataTable dt) {
return query.SetParameter(name, dt, structured);
}
}
Typical usage for me is
DataTable dt = ...;
ISession s = ...;
var l = s.CreateSQLQuery("EXEC some_sp @id = :id, @par1 = :par1")
.SetStructured("id", dt)
.SetParameter("par1", ...)
.SetResultTransformer(Transformers.AliasToBean<SomeEntity>())
.List<SomeEntity>();
Ok, but what is an "IntTable"? It's the name of SQL type created to pass table value arguments.
CREATE TYPE IntTable AS TABLE
(
ID INT
);
And some_sp could be like
CREATE PROCEDURE some_sp
@id IntTable READONLY,
@par1 ...
AS
BEGIN
...
END
It only works with Sql Server 2008 of course and in this particular implementation with a single-column DataTable.
var dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
It's POC only, not a complete solution, but it works and might be useful when customized. If someone knows a better/shorter solution let us know.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
The weak equivalences in the covariant model structure
Let $S$ be a simplicial set. Recall that there is a model structure, called the covariant model structure (see HTT ch. 2 and this question), on $\mathbf{SSet}/S$ such that:
The cofibrations are the monomorphisms.
A map $X \to Y$ of simplicial sets over $S$ is a weak equivalence if $X^\vartriangleleft \sqcup_X S \to Y^\vartriangleleft \sqcup_Y S$ is a categorical equivalence (i.e., a weak equivalence in the Joyal model structure -- that is, one such that when applying the simplicial category functor $\mathfrak{C}$ gives an equivalence of simplicial categories). Here the triangle denotes the left cone.
The fibrations are determined; the fibrant objects are the left fibrations $Y \to S$.
I think I understand the motivation for most of this: as Lurie explains, left fibrations are the $\infty$-categorical version of categories cofibered in groupoids (so the fibrant objects model a reasonable concept), and the cofibrations are as nice as can be. But I fail to understand the motivation for the weak equivalences -- not least because I don't have a particularly good picture of what these "left cones" are supposed to model. Why should the weak equivalences be what they are?
A:
Maybe it would be helpful to think about the analogous situation in ordinary category theory. Suppose you are given a category $\mathcal{E}$ and a functor $F$ from
$\mathcal{E}$ to the category of sets. There are several ways to encode this functor:
$(a)$: Via the Grothendieck construction, $F$ determines a category $\mathcal{C}$ cofibered in sets over $\mathcal{E}$, so that for each object $E \in \mathcal{E}$ you can identify $F(E)$ with the fiber $\mathcal{C}_E$ of the map $\mathcal{C} \rightarrow \mathcal{E}$ over $E$.
$(b)$: Using the functor $F$, you can construct an enlargement $\mathcal{E}_F$ of the category $\mathcal{E}$, adding a single object $v$ with
$$Hom(E,v) = \emptyset \quad \quad Hom(v,E) = F(E) \quad \quad Hom(v,v) = \{ id \} $$
Now suppose we are given another functor $G$ from $\mathcal{E}$ to the category of sets,
and a natural transformation $F \rightarrow G$. Then $G$ determines a category
$\mathcal{D}$ cofibered in sets over $\mathcal{E}$, and an enlargement $\mathcal{E}_G$ of $\mathcal{E}$. The natural transformation $F \rightarrow G$ determines functors
$$ \alpha: \mathcal{C} \rightarrow \mathcal{D} \quad \quad \beta: \mathcal{E}_F \rightarrow \mathcal{E}_G$$
In this situation, the following conditions are equivalent:
$(i)$: The natural transformation $F \rightarrow G$ is an isomorphism (that is, for each object $E \in \mathcal{E}$, the induced map $F(E) \rightarrow G(E)$ is bijective.
$(ii)$: The functor $\alpha$ is an equivalence of categories.
$(iii)$: The functor $\beta$ is an equivalence of categories.
Now observe that the category $\mathcal{E}_F$ can be described as the pushout (and also homotopy pushout) of the diagram $$\mathcal{E} \leftarrow \mathcal{C} \rightarrow \mathcal{C}^{\triangleleft},$$
where $\mathcal{C}^{\triangleleft}$ is the category obtained from $\mathcal{E}$ by adjoining a new initial object.
Let's now forget the original functors $F$ and $G$, and think only about the categories
$\mathcal{C}$ and $\mathcal{D}$ cofibered in sets over $\mathcal{E}$. The equivalence of conditions $(ii)$ and $(iii)$ shows that functor $\alpha: \mathcal{C} \rightarrow \mathcal{D}$ of categories cofibered over $\mathcal{E}$ is an equivalence of categories if and only if the induced map
$$ \mathcal{E} \amalg_{ \mathcal{C} } \mathcal{C}^{\triangleleft}
\rightarrow \mathcal{E} \amalg_{ \mathcal{D} } \mathcal{D}^{\triangleleft}$$
is an equivalence of categories.
Now go to the setting of quasi-categories. Assume for simplicity that $S$ is a quasi-category, and let $f: X \rightarrow Y$ be a map of simplicial sets over $S$. If
$X$ and $Y$ are left-fibered over $S$, then we would like to say that $f$ is a covariant equivalence if and only if it an equivalence of quasi-categories. However, we would like to formulate this condition in a way that will behave well also when $X$ and $Y$ are not fibrant.
Motivated by the discussion above, we declare that $f$ is a covariant equivalence if and only if it induces a categorical equivalence
$$ S \amalg_{X} X^{\triangleleft} \rightarrow S \amalg_{Y} Y^{\triangleleft}.$$
You can then prove that this is a good definition (it gives you a model structure with the cofibrations and fibrant objects that you described, and when $X$ and $Y$ are fibrant a map
$f: X \rightarrow Y$ is a covariant equivalence if and only if it induces a homotopy equivalence of fibers $X_s \rightarrow Y_s$ for each vertex $s \in S$).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Move semantics - what it's all about?
Possible Duplicate:
Can someone please explain move semantics to me?
Could someone point me to a good source or explain it here what are the move semantics?
A:
Forget about C++0x for the moment. Move semantics are something that is language independent -- C++0x merely provides a standard way to perform operations with move semantics.
Definition
Move semantics define the behaviour of certain operations. Most of the time they are contrasted with copy semantics, so it would be useful to define them first.
Assignment with copy semantics has the following behaviour:
// Copy semantics
assert(b == c);
a = b;
assert(a == b && b == c);
i.e. a ends up equal to b, and we leave b unchanged.
Assignment with move semantics has weaker post conditions:
// Move semantics
assert(b == c);
move(a, b); // not C++0x
assert(a == c);
Note that there is no longer any guarantee that b remains unchanged after the assignment with move semantics. This is the crucial difference.
Uses
One benefit of move semantics is that it allows optimisations in certain situations. Consider the following regular value type:
struct A { T* x; };
Assume also that we define two objects of type A to be equal iff their x member point to equal values.
bool operator==(const A& lhs, const A& rhs) { return *lhs.x == *rhs.x; }
Finally assume that we define an object A to have sole ownership over the pointee of their x member.
A::~A() { delete x; }
A::A(const A& rhs) : x(new T(rhs.x)) {}
A& A::operator=(const A& rhs) { if (this != &rhs) *x = *rhs.x; }
Now suppose we want to define a function to swap two A objects.
We could do it the normal way with copy semantics.
void swap(A& a, A& b)
{
A t = a;
a = b;
b = t;
}
However, this is unnecessarily inefficient. What are we doing?
We create a copy of a into t.
We then copy b into a.
Then copy t into b.
Finally, destroy t.
If T objects are expensive to copy then this is wasteful. If I asked you to swap two files on your computer, you wouldn't create a third file then copy and paste the file contents around before destroying your temporary file, would you? No, you'd move one file away, move the second into the first position, then finally move the first file back into the second. No need to copy data.
In our case, it's easy to move around objects of type A:
// Not C++0x
void move(A& lhs, A& rhs)
{
lhs.x = rhs.x;
rhs.x = nullptr;
}
We simply move rhs's pointer into lhs and then relinquish rhs ownership of that pointer (by setting it to null). This should illuminate why the weaker post condition of move semantics allows optimisations.
With this new move operation defined, we can define an optimised swap:
void swap(A& a, A& b)
{
A t;
move(t, a);
move(a, b);
move(b, t);
}
Another advantage of move semantics is that it allows you to move around objects that are unable to be copied. A prime example of this is std::auto_ptr.
C++0x
C++0x allows move semantics through its rvalue reference feature. Specifically, operations of the kind:
a = b;
Have move semantics when b is an rvalue reference (spelt T&&), otherwise they have copy semantics. You can force move semantics by using the std::move function (different from the move I defined earlier) when b is not an rvalue reference:
a = std::move(b);
std::move is a simple function that essentially casts its argument to an rvalue reference. Note that the results of expressions (such as a function call) are automatically rvalue references, so you can exploit move semantics in those cases without changing your code.
To define move optimisations, you need to define a move constructor and move assignment operator:
T::T(T&&);
T& operator=(T&&);
As these operations have move semantics, you are free to modify the arguments passed in (provided you leave the object in a destructible state).
Conclusion
That's essentially all there is to it. Note that rvalue references are also used to allow perfect forwarding in C++0x (due to the specifically crafted type system interactions between rvalue references and other types), but this isn't really related to move semantics, so I haven't discussed it here.
A:
Basically, rvalue references allow you to detect when objects are temporaries and you don't have to preserve their internal state. This allows for much more efficient code where C++03 used to have to copy all the time, in C++0x you can keep re-using the same resources. In addition, rvalue references enable perfect forwarding.
Have a look at this answer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I easily separate a set of strings stored in a larger NSString?
I had a UILabel with the following text:
Medium, Black
What I intended to do was grab the words in the string and insert each into a mutable array so I could use each title later on to identify something.
With the help of Stackoverflow I done it like this:
NSMutableArray *chosenOptions = [[[[cell tapToEditLabel] text] componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:@" ,"]] mutableCopy];
[chosenOptions removeObject:@""];
Now I can access this objects and they return the correct strings:
NSString *size = [chosenOptions objectAtIndex:0]; //Medium
NSString *colour = [chosenOptions objectAtIndex:1]; //Black
This is fine. But the problem starts when dealing with female sizes instead of males which are displayed like this:
[8 UK], [10 UK], [12 UK], [14 UK]
Let us say I now have a UILabel with the following text:
[8 UK], Black
Using the same code above my NSLog here:
NSLog(@"size label-> %@", size);
NSLog(@"colour label-> %@", colour);
Reads back:
size label-> [8
colour label-> UK]
Would appreciate a simple solution in code please.
The code that does the stripping doesn't take into account the way my female sizes are set in a string. I need a solution that will work with both male and female size string styles.
Thanks for your time.
A:
Simply use componentsSeparatedByString:@", ".
NSArray *chosenOptions = [[[cell tapToEditLabel] text] componentsSeparatedByString:@", "];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Nifi processor is not parsing JSON correctly
I am using EvaluateJsonPath to extract one particular value from JSON. I am using the follwoing JSONPath expression:
$.data[?(@.containerType == 'SOURCE' && @.path == 'SOURCE_KYLO_DATALAKE')].id
This is the JSON document I'm calling the JSONPath on :
{"data":[{"id":"dc18bf87-c5a6-4600-9584-e79fb988b1d0","path":["@[email protected]"],"tag":"0","type":"CONTAINER","containerType":"HOME"},{"id":"42e52055-4deb-4d5d-942f-4e1c4e48c35e","path":["BPM"],"tag":"3","type":"CONTAINER","containerType":"SPACE"},{"id":"49e3d118-e4f9-41ef-ad97-6b2745c75c4f","path":["DATABRICKS_USAGE_REPORT"],"tag":"0","type":"CONTAINER","containerType":"SPACE"},{"id":"613f52e9-64df-4c9c-b083-c282f349eb4e","path":["LIGHTHOUSE"],"tag":"3","type":"CONTAINER","containerType":"SPACE"},{"id":"f57bcd83-4d0e-481e-b880-0fb8b20798a1","path":["MDM"],"tag":"2","type":"CONTAINER","containerType":"SPACE"},{"id":"745cd2d5-7303-4c0a-9cab-f5205b9eec90","path":["NIELSEN"],"tag":"2","type":"CONTAINER","containerType":"SPACE"},{"id":"b40da338-c429-4bb3-b2ef-51295a143fc8","path":["PowerBI"],"tag":"0","type":"CONTAINER","containerType":"SPACE"},{"id":"dffd025c-b0f0-4b9b-9060-da4aa54204d1","path":["REFERENCE_DATA"],"tag":"1","type":"CONTAINER","containerType":"SPACE"},{"id":"14f9759a-2059-4728-acad-fe01f129f148","path":["SAP_ODP_MASTERDATA"],"tag":"1","type":"CONTAINER","containerType":"SPACE"},{"id":"063bb5e8-041a-4f69-98a3-d2509d5e89d0","path":["TRAX"],"tag":"1","type":"CONTAINER","containerType":"SPACE"},{"id":"9c737147-6632-4328-bf10-ba4959a2806f","path":["TRAX_API"],"tag":"0","type":"CONTAINER","containerType":"SPACE"},{"id":"99167858-17ca-406f-b887-62af3d0da68a","path":["DEPLETION"],"tag":"1","type":"CONTAINER","containerType":"SPACE"},{"id":"52f17de1-a66e-4f08-9077-04acf3914663","path":["SOURCE_ADLS_NIELSEN_PROD"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"bea0de9c-b579-46bd-89ff-4b9497c3910e","path":["SOURCE_KYLO_DATALAKE"],"tag":"5","type":"CONTAINER","containerType":"SOURCE"},{"id":"20985e83-cd31-469e-9a17-1e586bccfb27","path":["SOURCE_LIGHTHOUSE_UAT"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"47406901-c9ce-4fce-b0ab-37b07338949b","path":["SOURCE_MDM_UAT"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"f1feff7d-8ada-46bb-a5fe-0283a2c746b3","path":["SOURCE_MDS_UAT"],"tag":"0","type":"CONTAINER","containerType":"SOURCE"},{"id":"48a5d1b6-8d32-449d-a317-d242f2394e71","path":["SOURCE_NIELSEN_UAT"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"32eaeeb5-60d5-4d87-a983-1e71e3543920","path":["SOURCE_PROD_BPM"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"f4af00a5-a536-4272-93cb-891ec13ef8e4","path":["SOURCE_SAP_MDS_STAGING"],"tag":"3","type":"CONTAINER","containerType":"SOURCE"},{"id":"7250d605-75a9-4ef2-a01b-55c2bcb44dd9","path":["SOURCE_TRAX_UAT"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"38a8293e-72f4-42c2-be66-667b21a1ac55","path":["SOURCE_KYLO_HIVE2"],"tag":"10","type":"CONTAINER","containerType":"SOURCE"},{"id":"95cb9f2f-3421-451a-8635-bb8487dc1872","path":["dwlprd1"],"tag":"7","type":"CONTAINER","containerType":"SOURCE"},{"id":"ac9334e4-daf2-4c6f-92f1-0452440fb737","path":["dwlprd2"],"tag":"5","type":"CONTAINER","containerType":"SOURCE"},{"id":"c27af9bd-075b-4fb8-bcd4-8450f26ff7f9","path":["SOURCE_ADLS_NIELSEN_DEPLETION_UAT"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"}]}
When I use the configuration(that specific JSONPath query) from above on a JSONPath online testing tool (see attached image), I get the expected result. But somehow nifi is returning empty array.
Template:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><template encoding-version="1.2"><description></description><groupId>ae48862f-0165-1000-cc45-c1efcbb7ff08</groupId><name>dnu_jsonpath</name><snippet><connections><id>d84c0b8e-6983-3f0e-0000-000000000000</id><parentGroupId>5842a0b1-f01b-3160-0000-000000000000</parentGroupId><backPressureDataSizeThreshold>1 GB</backPressureDataSizeThreshold><backPressureObjectThreshold>10000</backPressureObjectThreshold><destination><groupId>5842a0b1-f01b-3160-0000-000000000000</groupId><id>7d993abd-1c1e-3cc5-0000-000000000000</id><type>PROCESSOR</type></destination><flowFileExpiration>0 sec</flowFileExpiration><labelIndex>1</labelIndex><name></name><selectedRelationships>success</selectedRelationships><source><groupId>5842a0b1-f01b-3160-0000-000000000000</groupId><id>509810d8-4798-30e5-0000-000000000000</id><type>PROCESSOR</type></source><zIndex>0</zIndex></connections><connections><id>02ff8ff3-ed1e-34b1-0000-000000000000</id><parentGroupId>5842a0b1-f01b-3160-0000-000000000000</parentGroupId><backPressureDataSizeThreshold>1 GB</backPressureDataSizeThreshold><backPressureObjectThreshold>10000</backPressureObjectThreshold><destination><groupId>5842a0b1-f01b-3160-0000-000000000000</groupId><id>8d45c558-a4a7-3529-0000-000000000000</id><type>PROCESSOR</type></destination><flowFileExpiration>0 sec</flowFileExpiration><labelIndex>1</labelIndex><name></name><selectedRelationships>failure</selectedRelationships><selectedRelationships>unmatched</selectedRelationships><source><groupId>5842a0b1-f01b-3160-0000-000000000000</groupId><id>7d993abd-1c1e-3cc5-0000-000000000000</id><type>PROCESSOR</type></source><zIndex>0</zIndex></connections><connections><id>6a3afe0c-951a-33fc-0000-000000000000</id><parentGroupId>5842a0b1-f01b-3160-0000-000000000000</parentGroupId><backPressureDataSizeThreshold>1 GB</backPressureDataSizeThreshold><backPressureObjectThreshold>10000</backPressureObjectThreshold><destination><groupId>5842a0b1-f01b-3160-0000-000000000000</groupId><id>ab89e6d1-f08e-32be-0000-000000000000</id><type>PROCESSOR</type></destination><flowFileExpiration>0 sec</flowFileExpiration><labelIndex>1</labelIndex><name></name><selectedRelationships>matched</selectedRelationships><source><groupId>5842a0b1-f01b-3160-0000-000000000000</groupId><id>7d993abd-1c1e-3cc5-0000-000000000000</id><type>PROCESSOR</type></source><zIndex>0</zIndex></connections><processors><id>8d45c558-a4a7-3529-0000-000000000000</id><parentGroupId>5842a0b1-f01b-3160-0000-000000000000</parentGroupId><position><x>607.0</x><y>151.0</y></position><bundle><artifact>nifi-standard-nar</artifact><group>org.apache.nifi</group><version>1.6.0</version></bundle><config><bulletinLevel>WARN</bulletinLevel><comments></comments><concurrentlySchedulableTaskCount>1</concurrentlySchedulableTaskCount><descriptors><entry><key>Log Level</key><value><name>Log Level</name></value></entry><entry><key>Log Payload</key><value><name>Log Payload</name></value></entry><entry><key>Attributes to Log</key><value><name>Attributes to Log</name></value></entry><entry><key>attributes-to-log-regex</key><value><name>attributes-to-log-regex</name></value></entry><entry><key>Attributes to Ignore</key><value><name>Attributes to Ignore</name></value></entry><entry><key>attributes-to-ignore-regex</key><value><name>attributes-to-ignore-regex</name></value></entry><entry><key>Log prefix</key><value><name>Log prefix</name></value></entry><entry><key>character-set</key><value><name>character-set</name></value></entry></descriptors><executionNode>ALL</executionNode><lossTolerant>false</lossTolerant><penaltyDuration>30 sec</penaltyDuration><properties><entry><key>Log Level</key><value>info</value></entry><entry><key>Log Payload</key><value>false</value></entry><entry><key>Attributes to Log</key></entry><entry><key>attributes-to-log-regex</key><value>.*</value></entry><entry><key>Attributes to Ignore</key></entry><entry><key>attributes-to-ignore-regex</key></entry><entry><key>Log prefix</key></entry><entry><key>character-set</key><value>UTF-8</value></entry></properties><runDurationMillis>0</runDurationMillis><schedulingPeriod>0 sec</schedulingPeriod><schedulingStrategy>TIMER_DRIVEN</schedulingStrategy><yieldDuration>1 sec</yieldDuration></config><name>LogAttribute</name><relationships><autoTerminate>false</autoTerminate><name>success</name></relationships><state>STOPPED</state><style/><type>org.apache.nifi.processors.standard.LogAttribute</type></processors><processors><id>ab89e6d1-f08e-32be-0000-000000000000</id><parentGroupId>5842a0b1-f01b-3160-0000-000000000000</parentGroupId><position><x>715.0</x><y>468.99999999999994</y></position><bundle><artifact>nifi-standard-nar</artifact><group>org.apache.nifi</group><version>1.6.0</version></bundle><config><bulletinLevel>WARN</bulletinLevel><comments></comments><concurrentlySchedulableTaskCount>1</concurrentlySchedulableTaskCount><descriptors><entry><key>Log Level</key><value><name>Log Level</name></value></entry><entry><key>Log Payload</key><value><name>Log Payload</name></value></entry><entry><key>Attributes to Log</key><value><name>Attributes to Log</name></value></entry><entry><key>attributes-to-log-regex</key><value><name>attributes-to-log-regex</name></value></entry><entry><key>Attributes to Ignore</key><value><name>Attributes to Ignore</name></value></entry><entry><key>attributes-to-ignore-regex</key><value><name>attributes-to-ignore-regex</name></value></entry><entry><key>Log prefix</key><value><name>Log prefix</name></value></entry><entry><key>character-set</key><value><name>character-set</name></value></entry></descriptors><executionNode>ALL</executionNode><lossTolerant>false</lossTolerant><penaltyDuration>30 sec</penaltyDuration><properties><entry><key>Log Level</key><value>info</value></entry><entry><key>Log Payload</key><value>false</value></entry><entry><key>Attributes to Log</key></entry><entry><key>attributes-to-log-regex</key><value>.*</value></entry><entry><key>Attributes to Ignore</key></entry><entry><key>attributes-to-ignore-regex</key></entry><entry><key>Log prefix</key></entry><entry><key>character-set</key><value>UTF-8</value></entry></properties><runDurationMillis>0</runDurationMillis><schedulingPeriod>0 sec</schedulingPeriod><schedulingStrategy>TIMER_DRIVEN</schedulingStrategy><yieldDuration>1 sec</yieldDuration></config><name>LogAttribute</name><relationships><autoTerminate>false</autoTerminate><name>success</name></relationships><state>STOPPED</state><style/><type>org.apache.nifi.processors.standard.LogAttribute</type></processors><processors><id>509810d8-4798-30e5-0000-000000000000</id><parentGroupId>5842a0b1-f01b-3160-0000-000000000000</parentGroupId><position><x>0.0</x><y>0.0</y></position><bundle><artifact>nifi-standard-nar</artifact><group>org.apache.nifi</group><version>1.6.0</version></bundle><config><bulletinLevel>WARN</bulletinLevel><comments></comments><concurrentlySchedulableTaskCount>1</concurrentlySchedulableTaskCount><descriptors><entry><key>File Size</key><value><name>File Size</name></value></entry><entry><key>Batch Size</key><value><name>Batch Size</name></value></entry><entry><key>Data Format</key><value><name>Data Format</name></value></entry><entry><key>Unique FlowFiles</key><value><name>Unique FlowFiles</name></value></entry><entry><key>generate-ff-custom-text</key><value><name>generate-ff-custom-text</name></value></entry><entry><key>character-set</key><value><name>character-set</name></value></entry></descriptors><executionNode>ALL</executionNode><lossTolerant>false</lossTolerant><penaltyDuration>30 sec</penaltyDuration><properties><entry><key>File Size</key><value>0B</value></entry><entry><key>Batch Size</key><value>1</value></entry><entry><key>Data Format</key><value>Text</value></entry><entry><key>Unique FlowFiles</key><value>false</value></entry><entry><key>generate-ff-custom-text</key><value>{"data":[{"id":"dc18bf87-c5a6-4600-9584-e79fb988b1d0","path":["@[email protected]"],"tag":"0","type":"CONTAINER","containerType":"HOME"},{"id":"42e52055-4deb-4d5d-942f-4e1c4e48c35e","path":["BPM"],"tag":"3","type":"CONTAINER","containerType":"SPACE"},{"id":"49e3d118-e4f9-41ef-ad97-6b2745c75c4f","path":["DATABRICKS_USAGE_REPORT"],"tag":"0","type":"CONTAINER","containerType":"SPACE"},{"id":"613f52e9-64df-4c9c-b083-c282f349eb4e","path":["LIGHTHOUSE"],"tag":"3","type":"CONTAINER","containerType":"SPACE"},{"id":"f57bcd83-4d0e-481e-b880-0fb8b20798a1","path":["MDM"],"tag":"2","type":"CONTAINER","containerType":"SPACE"},{"id":"745cd2d5-7303-4c0a-9cab-f5205b9eec90","path":["NIELSEN"],"tag":"2","type":"CONTAINER","containerType":"SPACE"},{"id":"b40da338-c429-4bb3-b2ef-51295a143fc8","path":["PowerBI"],"tag":"0","type":"CONTAINER","containerType":"SPACE"},{"id":"dffd025c-b0f0-4b9b-9060-da4aa54204d1","path":["REFERENCE_DATA"],"tag":"1","type":"CONTAINER","containerType":"SPACE"},{"id":"14f9759a-2059-4728-acad-fe01f129f148","path":["SAP_ODP_MASTERDATA"],"tag":"1","type":"CONTAINER","containerType":"SPACE"},{"id":"063bb5e8-041a-4f69-98a3-d2509d5e89d0","path":["TRAX"],"tag":"1","type":"CONTAINER","containerType":"SPACE"},{"id":"9c737147-6632-4328-bf10-ba4959a2806f","path":["TRAX_API"],"tag":"0","type":"CONTAINER","containerType":"SPACE"},{"id":"99167858-17ca-406f-b887-62af3d0da68a","path":["DEPLETION"],"tag":"1","type":"CONTAINER","containerType":"SPACE"},{"id":"52f17de1-a66e-4f08-9077-04acf3914663","path":["SOURCE_ADLS_NIELSEN_PROD"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"bea0de9c-b579-46bd-89ff-4b9497c3910e","path":["SOURCE_KYLO_DATALAKE"],"tag":"5","type":"CONTAINER","containerType":"SOURCE"},{"id":"20985e83-cd31-469e-9a17-1e586bccfb27","path":["SOURCE_LIGHTHOUSE_UAT"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"47406901-c9ce-4fce-b0ab-37b07338949b","path":["SOURCE_MDM_UAT"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"f1feff7d-8ada-46bb-a5fe-0283a2c746b3","path":["SOURCE_MDS_UAT"],"tag":"0","type":"CONTAINER","containerType":"SOURCE"},{"id":"48a5d1b6-8d32-449d-a317-d242f2394e71","path":["SOURCE_NIELSEN_UAT"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"32eaeeb5-60d5-4d87-a983-1e71e3543920","path":["SOURCE_PROD_BPM"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"f4af00a5-a536-4272-93cb-891ec13ef8e4","path":["SOURCE_SAP_MDS_STAGING"],"tag":"3","type":"CONTAINER","containerType":"SOURCE"},{"id":"7250d605-75a9-4ef2-a01b-55c2bcb44dd9","path":["SOURCE_TRAX_UAT"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"},{"id":"38a8293e-72f4-42c2-be66-667b21a1ac55","path":["SOURCE_KYLO_HIVE2"],"tag":"10","type":"CONTAINER","containerType":"SOURCE"},{"id":"95cb9f2f-3421-451a-8635-bb8487dc1872","path":["dwlprd1"],"tag":"7","type":"CONTAINER","containerType":"SOURCE"},{"id":"ac9334e4-daf2-4c6f-92f1-0452440fb737","path":["dwlprd2"],"tag":"5","type":"CONTAINER","containerType":"SOURCE"},{"id":"c27af9bd-075b-4fb8-bcd4-8450f26ff7f9","path":["SOURCE_ADLS_NIELSEN_DEPLETION_UAT"],"tag":"1","type":"CONTAINER","containerType":"SOURCE"}]}</value></entry><entry><key>character-set</key><value>UTF-8</value></entry></properties><runDurationMillis>0</runDurationMillis><schedulingPeriod>1 day</schedulingPeriod><schedulingStrategy>TIMER_DRIVEN</schedulingStrategy><yieldDuration>1 sec</yieldDuration></config><name>GenerateFlowFile</name><relationships><autoTerminate>false</autoTerminate><name>success</name></relationships><state>STOPPED</state><style/><type>org.apache.nifi.processors.standard.GenerateFlowFile</type></processors><processors><id>7d993abd-1c1e-3cc5-0000-000000000000</id><parentGroupId>5842a0b1-f01b-3160-0000-000000000000</parentGroupId><position><x>107.0</x><y>256.0</y></position><bundle><artifact>nifi-standard-nar</artifact><group>org.apache.nifi</group><version>1.6.0</version></bundle><config><bulletinLevel>WARN</bulletinLevel><comments></comments><concurrentlySchedulableTaskCount>1</concurrentlySchedulableTaskCount><descriptors><entry><key>Destination</key><value><name>Destination</name></value></entry><entry><key>Return Type</key><value><name>Return Type</name></value></entry><entry><key>Path Not Found Behavior</key><value><name>Path Not Found Behavior</name></value></entry><entry><key>Null Value Representation</key><value><name>Null Value Representation</name></value></entry><entry><key>dataset</key><value><name>dataset</name></value></entry></descriptors><executionNode>ALL</executionNode><lossTolerant>false</lossTolerant><penaltyDuration>30 sec</penaltyDuration><properties><entry><key>Destination</key><value>flowfile-content</value></entry><entry><key>Return Type</key><value>auto-detect</value></entry><entry><key>Path Not Found Behavior</key><value>warn</value></entry><entry><key>Null Value Representation</key><value>empty string</value></entry><entry><key>dataset</key><value>$.data[?(@.containerType == "SOURCE" && @.path == "SOURCE_KYLO_DATALAKE")].id</value></entry></properties><runDurationMillis>0</runDurationMillis><schedulingPeriod>0 sec</schedulingPeriod><schedulingStrategy>TIMER_DRIVEN</schedulingStrategy><yieldDuration>1 sec</yieldDuration></config><name>EvaluateJsonPath</name><relationships><autoTerminate>false</autoTerminate><name>failure</name></relationships><relationships><autoTerminate>false</autoTerminate><name>matched</name></relationships><relationships><autoTerminate>false</autoTerminate><name>unmatched</name></relationships><state>STOPPED</state><style/><type>org.apache.nifi.processors.standard.EvaluateJsonPath</type></processors></snippet><timestamp>09/24/2018 06:03:42 EDT</timestamp></template>
A:
As you are searching for value in path array, Enclose SOURCE_KYLO_DATALAKE in [](array) then processor will only result the matching id value as output content.
Change the Eval JsonPath property value as below
dataset
$.data[?(@.containerType == 'SOURCE' && @.path == ['SOURCE_KYLO_DATALAKE'])].id
Configs:
Output Flowfile Content:
["bea0de9c-b579-46bd-89ff-4b9497c3910e"]
UPDATE:
I have used NiFi-1.7.1 and EvaluateJson expression works fine in this version.
However if you are using other versions of NiFi then
1.if you are having only one element in array then use below expression in your EvaluateJsonPath processor.
dataset
$.data[?(@.containerType == 'SOURCE' && @.path[0] == 'SOURCE_KYLO_DATALAKE')].id
2.If you are having more than one element in array then
Flow:
Flow Description:
1.SplitJson
to split data array into individual messages
configure JsonPathExpression to
$.data
2.EvaluateJsonPath
To extract required content and keep as attribute to the flowfile
Now we are having id,containerType,path values as attributes to the flowfile
3.RouteOnAttribute:
in this processor we are checking the attribute values using NiFi expression language
Add new property as
required
${containerType:equals("SOURCE"):and(${anyDelineatedValue("${path:replace('[',''):replace(']','')}",","):equals('"SOURCE_KYLO_DATALAKE"')})}
Feed the required relationship to ReplaceText processor
4.ReplaceText
Now we are replacing the id values to the flowfile content
Now we are going to have the id value in your output flowfile content from ReplaceText processor.
If possible upgrade the NiFi version to 1.7.1 then you don't need to do all these workarounds :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL to automatically generate missing dates and price from immediately previous date for missing date in table
I have a table MKT which contains following fields value_date,stk_exch,security,mkt_price,source,currency,name
of say 500 securities for each day (excluding Saturday and Sunday and other Market Holidays).
I need an sql to automatically generate missing dates and price from immediately previous date for missing date. So if Friday is 26.07.2013 and Saturday and Sunday are 27th and 28th, then date and prices for 27th and 28th would be missing from this table.
So while spooling the prices for entire month July 2013 I should get all dates and for missing dates eg: 27 and 28 the sql would take price of 26th.
I am using Oracle
value_date stk_exch security mkt_price
-------------------------------------------------
26/07/2013 BSE BANKBARODA 565.85
29/07/2013 BSE BANKBARODA 585.85
Now SQL should Return
value_date stk_exch security mkt_price
-------------------------------------------------
26/07/2013 BSE BANKBARODA 565.85
27/07/2013 BSE BANKBARODA 565.85
28/07/2013 BSE BANKBARODA 565.85
29/07/2013 BSE BANKBARODA 585.85
A:
I've used your_table as one table with outerjoin, as used last_value to insert previous data,
have a look at this :)
SELECT last_value(m.data ignore nulls) over (order by n.mydate) data,
n.mydate
FROM
(SELECT DATA, mydate FROM your_table
) m,
(SELECT TRUNC(SYSDATE, 'MM')-1+LEVEL mydate FROM dual CONNECT BY LEVEL <= 30
)n
WHERE m.mydate(+) = n.mydate
ORDER BY n.mydate;
fiddle here
You could use lag() function also , but it won't fill data if date gap is more than one., it only fills immediate previous data,
nvl(m.data, lag(m.data)over(order by n.mydate))
-editing-
for your data:
SELECT n.mydate VALUE_DATE,
last_value(m.STK_EXCH IGNORE NULLS) OVER (ORDER BY n.mydate) STK_EXCH,
last_value(m.SECURITY IGNORE NULLS) OVER (ORDER BY n.mydate) SECURITY,
last_value(m.mkt_price IGNORE NULLS) OVER (ORDER BY n.mydate) MKT_PRICE
FROM
(SELECT VALUE_DATE, STK_EXCH, SECURITY, MKT_PRICE FROM MKT
) m,
(SELECT TRUNC(SYSDATE, 'MM')-1+LEVEL mydate FROM dual CONNECT BY LEVEL <= 30
)n
WHERE TRUNC(m.VALUE_DATE(+)) = TRUNC(n.mydate)
ORDER BY n.mydate;
or little more specific: use below:
SELECT full_date,
NVL(stk_exch,last_value(stk_exch IGNORE NULLS)OVER(ORDER BY full_date))stk_exch,
NVL(security,last_value(security IGNORE NULLS)OVER(ORDER BY full_date))security,
NVL(mkt_price,last_value(mkt_price IGNORE NULLS)OVER(ORDER BY full_date))mkt_price
FROM
(SELECT TRUNC(m.vd,'MM')-1+LEVEL FULL_DATE
FROM
(SELECT MIN(VALUE_DATE) vd FROM mkt
WHERE TO_CHAR( value_date, 'MM/YYYY') = TO_CHAR(sysdate-12,'MM/YYYY') -- this line may vary to your requirement
) m
CONNECT BY LEVEL <= TO_CHAR(LAST_DAY(M.VD), 'DD')
)first_q,
( SELECT value_date, stk_exch, SECURITY, mkt_price FROM mkt
)r
WHERE first_q.full_date = TRUNC(r.value_date(+))
ORDER BY full_date;
see fiddle here
|
{
"pile_set_name": "StackExchange"
}
|
Q:
c explanation of preorder binary tree traversal
Okay guys, I would like to know the following comments I made in this code. Thank you,
void visit(tree_t *t){
printf("%c ", t->e + 'A'); // why t->e + 'A', and not just t->e?
}
void tree_preorder(tree_t *t, void (*visit)(tree_t *)){ // i just don't know the parameter void (*visit)(tree_t *). what exactly is (*visit)(tree_t *)?
if (!t) return; // what's the condition (!t)?
visit(t);
tree_preorder(t->l, visit);
tree_preorder(t->r, visit);
}
A:
Here is a run down of the three questions.
printf("%c ", t->e + 'A'); // why t->e + 'A', and not just t->e?
This is making an ascii table assumption.
This will shift the character by 0x41 (65). So if you have a tree with an int range of 0 - 25 you can print out a valid character of A - Z
(*visit)(tree_t *)
This is a function pointer. It will be called on each node
// what's the condition (!t)?
This is a null check to make sure you are not at a leaf node in the tree structure.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to pass a list from one action to another in Struts 2 without using session?
I am displaying a list in my JSP as shown below:
<%@page contentType="text/html;charset=UTF-8"language="java"pageEncoding="UTF-8"%>
<%@taglib prefix="s"uri="/struts-tags"%>
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>xxx</title>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<s:form name="tableForm"method="post">
<th>
<s:submit action="verify" key="Add"></s:submit>
</th>
<s:hidden name="propagateList" value="%{formList}"/>
<table border="1">
<tr>
<th >ID</th>
<th>Name</th>
<th>Status</th>
<th>Type</th>
<th>System</th>
</tr>
<s:iterator value="formList">
<tr>
<td><s:checkbox name="checked" fieldValue="%{#attr.ID}" theme="simple" ></s:checkbox>
</td>
<td><s:property value="NAME"/></td>
<td><s:property value="STATUS"/></td>
<td><s:property value="TYPE"/></td>
<td><s:property value="UNIT"/></td>
</tr>
</s:iterator>
</table>
</s:form>
</body>
</html>
Here I want to pass the list formList to another action when I click on Add button without having to hit the database to fetch the list formList once again.
I tried using <s:hidden name="propagateList" value="%{formList}"/> but it does not work.
This list contains more than 1000 records , so is there any way to pass this list from the jsp to another action in Struts 2 without using session?
A:
To answer the question "how to pass a List from ActionA to ActionB without using the Session":
in case of a List<String> :
<s:iterator value="formList" status="row">
<s:hidden name="formList[%{#row.index}]" />
</s:iterator>
This will iterate through your whole List, and will generate an <s:hidden/> element for every element of the List; this way, you can pass an un-altered List from one Action to another.
in case of a List<Object> , where the object is that you've posted in the page:
<s:iterator value="formList" status="row">
<s:hidden name="formList[%{#row.index}].id" />
<s:hidden name="formList[%{#row.index}].name" />
<s:hidden name="formList[%{#row.index}].status" />
<s:hidden name="formList[%{#row.index}].type" />
<s:hidden name="formList[%{#row.index}].unit" />
</s:iterator>
Exactly as before, this will iterate through your whole List, generating five elements for every object of the List.
Using this concept, you can alter the List by using interactive tags (textfield, select, etc) instead of read-only tags (hidden, property etc):
<s:iterator value="formList" status="row">
<s:hidden name="formList[%{#row.index}].id" />
<s:textfield name="formList[%{#row.index}].name" value="name" />
<s:hidden name="formList[%{#row.index}].status" />
<s:property value="status" />
<s:textfield name="formList[%{#row.index}].type" value="type" />
<s:textfield name="formList[%{#row.index}].unit" value="unit" />
</s:iterator>
Of course your List will be vulnerable to client-side changes, every user able to press F12 will be able to modify your List, then you should be careful.
You could, for example, put only the ID**s in the **session, inject the List in the JSP, then when receiving the data back, match the *ID*s of List coming from the page with the *ID*s you have in Session, for checking the integrity of the data posted (no new IDs, no double IDs etc)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Script Failed! : script.raspbmc.settings
I just upgraded to the latest Raspbmc nightly build (xbmc-rbp-20130124) and now, when I go to Programs > Raspbmc Settings I only get a small notification on the lower right hand corner of the screen:
Script Failed! : script.raspbmc.settings
Somebody else previously had the same problem on raspbmc forum, yet:
I ensured /home/pi/.upgrade owner is pi
my ~/.xbmc/temp/xbmc.log is different
Any leads?
A:
Since the Raspbmc community proved to be so helpful, here is how I tackled the issue.
Short version:
One solution is to browse the "nightlies" and downgrade to the previous nightly build.
Long, detailed version:
SSH into the Raspberry Pi
switch to the upgrade folder:
/home/pi/.upgrade
get previous nightly build:
wget -c http://mirrors.arizona.edu/raspbmc/downloads/bin/xbmc/nightlies/xbmc-rbp-<older_version>.tar.gz †
extract:
tar xzvf xbmc-rbp-<older_version>.tar.gz xbmc-rbp-<older_version> †
destroy the .xbmc-current symlink
rm /home/pi/.xbmc-current
point the .xbmc-current symlink to the new folder:
ln -s /home/pi/.upgrade/xbmc-rbp-<older_version>/xbmc-bcm /home/pi/.xbmc-current †
grant full access to the xbmc-bin inside:
chmod 777 /home/pi/.xbmc-current/xbmc-bin/
reboot and check in Programs > Raspbmc Settings that it worked.
If anyone has a better / more elegant solution, please share.
† <older_version> — 20130121 in this specific case e.g., xbmc-rbp-20130121.tar.gz.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ReactJS - Super expression must either be null or a function, not undefined
I've been following along a course on udemy, but there's an error that keeps showing up no matter what I do:
Here's the components code:
import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
class WeatherList extends Component {
constructor(props) {
super(props);
}
renderWeather(cityData) {
...
}
render() {
return (
...
);
}
}
function mapStateToProps(state) {
return {
weather: state.weather
};
}
export default connect(mapStateToProps)(WeatherList);
Here's the Chart component that I'm importing:
import React from 'react';
import { Sparklines, SparklinesLine, SparklinesReferenceLine } from 'react-sparklines';
import _ from 'lodash';
function average(data) {
return _.round(_.sum(data) / data.length);
}
const Chart = (props) => {
return (
<div>
<Sparklines width={80} height={80} data={thisprops.data}>
<SparklinesLine color={props.color} />
<SparklinesReferenceLine type="avg" />
</Sparklines>
<div>
{ average(props.data) } { props.units }
</div>
</div>
);
};
export default Chart;
But apparently React.Component is undefined so it throws an error.
A:
I had the same problem. The bug is due to 'react-sparklines' . Downgrade the version by:
npm i --save [email protected]
It should work now.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Maths with countElements and UITextField
I am making a joke app for friends and to improve my swift coding by making a LoveCalculator. The calculator finds the length of the two names of the lovers, times the lengths together, then takes that number away from 100, giving your love percentage. However, each time I try the app, it displays the number -40906 each time. Any ideas? I have tried changing the UITextField to String conversion method. I am quite a novice at swift, any help would by appreciated!
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var outputLabel: UILabel!
@IBOutlet weak var personOne: UITextField!
@IBOutlet weak var personTwo: UITextField!
@IBAction func calculateButton(sender: AnyObject) {
var one = toString(personOne)
var two = toString(personTwo)
var oneLength = countElements(one)
var twoLength = countElements(two)
var firstCalc = oneLength * twoLength
var finalCalc = 100 - firstCalc
outputLabel.text = "%\(finalCalc)"
}
A:
personOne and personTwo are UITextFields, not texts.
Change your code to:
var one = toString(personOne.text)
var two = toString(personTwo.text)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AspectJ Load time weaving fails in AWS SWF using Java?
I added Default VM argument at Installed jre
-javaagent:E:\eclipse-jee-juno-SR2-win32-x86_64\aws-java-sdk\aspectj-1.7.3.jar
Followed instrucion from here
But Still Getting Below Error
Error occurred during initialization of VM
agent library failed to init: instrument
Failed to find Premain-Class manifest attribute in E:\eclipse-jee-juno-SR2-win32-x86_64\aws-java-sdk\aspectj-1.7.3.jar
A:
Working Now, I included the the path as per document provided by AWS which is here
Need to change this path to aspectjweaver.jar which is inside aspectj-1.7.3\lib
Now My New path is
-javaagent:"E:\eclipse-jee-juno-SR2-win32-x86_64\aws-java-sdk\aspectj-1.7.3\lib\aspectjweaver.jar"
and now working
[AppClassLoader@4f1799e7] info AspectJ Weaver Version 1.6.12 built on Tuesday Oct 18, 2011 at 17:52:06 GMT
[AppClassLoader@4f1799e7] info register classloader sun.misc.Launcher$AppClassLoader@4f1799e7
[AppClassLoader@4f1799e7] info using configuration /F:/AWS%20Workspace/HelloWorldWeb/build/classes/META-INF/aop.xml
[AppClassLoader@4f1799e7] info register aspect com.amazonaws.services.simpleworkflow.flow.aspectj.AsynchronousAspect
[AppClassLoader@4f1799e7] info register aspect com.amazonaws.services.simpleworkflow.flow.aspectj.ExponentialRetryAspect
and also include aspectj-1.7.3.jar
Click Project Properties.
Click AspectJ Build and then click the Aspect Path tab.
Click Add External JARs.
Jar is at location
E:\eclipse-jee-juno-SR2-win32-x86_64\aws-java-sdk\aspectj-1.7.3.jar
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unexplained 0.1% packets time out when pinging from router
I'm troubleshooting a customer who requires the ability to send 5000 pings from the router to their remote site over a satellite link with zero timeouts, yet they keep experiencing one to five packets lost per test.
Under ordinary circumstances, I'd be willing to chalk up such a low loss rate as the cost of a satellite link, but the drops only show up when pinging from the router to the remote site. To clarify, here's the involved network devices:
Outbound Traffic
192.1.1.51 Router Hub
192.1.1.52 TX Switch Hub
192.1.1.50 Encapsulator Hub
172.1.1.1 Remote Site Remote
Return Traffic
172.1.1.1 Remote Site Remote
192.1.1.28 Channel Unit Hub
192.1.1.53 RX Switch Hub
192.1.1.51 Router Hub
When pinging from the Router to the remote site, the losses show up. When pinging from a Sun server attached to the TX switch (bypassing the router), the 5000 pings complete without a single loss. This verifies the entire satellite path, and all equipment except for the router.
Then I tried sending 5000 pings from the router to all of the other devices aside from the remote site...and I got back all 5000 almost instantaneously with no drops, so the connection from the router to everything else in the path is verified good.
The router in question is a Cisco 7206VXR, and the cpu utilization doesn't appear to ever go above 50%. The highest process is only at 20%, so I'm not confident that it's simply a matter of the router dropping ICMP packets due to lower priority, particularly given the router will send 5000 packets to local devices with no issues.
I also looked into the possibility of a null route, but the only possible culprit is an essential route for remote access, according to the customer, and I can't post their running config here to get a second opinion.
Any suggestions would be greatly appreciated. I have very little networking experience, and I'm beating my head against the wall to reconcile these seemingly contradictory symptoms.
A:
Datagrams are a best effort service. If you have a requirement that data be reliably delivered, you cannot use datagrams It really is that simple. The entire design of the system, end to end, is not meant to meet this requirements. You can't just impose it on the system as a whole at the end like putting a cherry on a sundae.
A:
It turns out the problem was that CEF was enabled globally on the hub router, but explicitly disabled ("no ip route-cache cef") on the interface which connects to the hub LAN. Once the explicit disable statements were removed, the packet loss vanished.
I don't understand why that worked, given that there was no packet loss between the hub devices and the hub router, but I can't argue with the results.
Hopefully, this can help anyone else who is stuck trying to isolate a very minor packet loss.
Thanks again to everyone who offered advice on this issue.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to style an RSS feed similar to YouTube?
Hey everyone,
I'm looking to display multiple items in view of an iOS app. Typically I would use UITableView to accomplish this but now I'm looking for something a little fancier. The appearance that I hope to replicate is that of YouTube on iOS systems. A picture of this [youtube] is attached. I am particularly interested in how each video entry is styled. The box around the entry, the background. My guess as to how YouTube does this is through multiple UIViews or stylish UITableViewCell. Any class or framework recommendation would be of great assistance. I have spent hours searching google and stackoverflow to no avail.
Thanks in advance
A:
To mimic the style of the YouTube app, I just subclassed UITableViewController with an initialized style of UITableViewStyleGrouped.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to remove a user from item permision RoleAssignments does not contain RemoveById
I have the following code inside my remote event receiver, where i am trying to remove a user from a list item which have unique permission:-
User oUser = context.Site.RootWeb.EnsureUser(linemanagerUser.LookupValue);
context.Load(oUser);
context.ExecuteQuery();
currentItem.RoleAssignments.RemoveById(oUser.Id);
but seems RoleAssignments does not contain RemoveById as in the server-side object module.. so can anyone advice on this please?
Error i got on my above code:-
'RoleAssignmentCollection' does not contain a definition for 'RemoveById' and no accessible extension method 'RemoveById' accepting a first argument of type 'RoleAssignmentCollection' could be found (are you missing a using directive or an assembly reference?)
A:
You can try the below code :
currentItem.RoleAssignments.GetByUser(oUser.Id). DeleteObject ()
Or
currentItem.RoleAssignments.GetByPrincipal(oUser.Id). DeleteObject ()
For details example, you may refer to the below article :
Remove permission in Sharepoint List using Client Object Model
|
{
"pile_set_name": "StackExchange"
}
|
Q:
We need to change URL structure of our product page in PRESTASHOP theme
We are using PRESTASHOP theme. We need to change url structure of our site. Currently site URL structure is:
http://www.mydomain.com/index.php?id_product=3013&controller=product&id_lang=1
It should change to:
http://www.mydomain.com/categoryname/productname
So will it be possible? Please help.
A:
You can do that by going to Preferences > SEO & URLS
Then set Friendly URL to Yes in the Set up URLs section
Finally, on the same page, you can customize your urls (products, categories...) in the Options section
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to sync Google Docs with a folder in my filesystem?
I'd like to be able to edit my files offline and it would automatically send the changes to Google Docs and vice versa. Is that even possible? If so, how to do it?
A:
Try google-docs-fs
sudo apt-get install google-docs-fs
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I prove this function is bijective?
I know I have to show it's injective and surjective, but up until now it's always been simple equations that I can prove are equal to each other. This equation is a little bit more complex.
$$f(x) = (x-a)\frac{d-c}{b-a} + c$$
Im $99\%$ sure it's bijective, but I don't know how to prove it since there is nothing to set it equal to like other examples. Also $a \lt b$ and $c \lt d$
A:
I assume you operate in the set $\mathbb{R}$.
Let's use the abbreviation $m = \frac{d-c}{b-a}$
$$\color{blue}{f(x)} = m(x-a)+c = mx +c-ma \color{blue}{= mx + r} \mbox{ with } r = c-ma \mbox{ and } m>0$$
Injectivity:
$f$ is strictly increasing, hence it is injective:
$$x<y \Rightarrow mx+r < my+r \Rightarrow f(x) < f(y)$$
Surjectivity:
For each $y \in \mathbb{R}$ you need to find an $x \in \mathbb{R}$ such that $f(x) = y$:
$$y = mx+r \Rightarrow x=\frac{y-r}{m} \mbox{ is such an }x$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What size image is needed for the Application Image for an Xamarin.Forms application and how and where should I add this?
I am creating an application that I would like to run on Android and iOS devices with different screen sizes.
What size image do I need to use and where should I put this so that it shows as a thumbnail when the application is installed on the device before the application starts to run? In other words the image that a user clicks to start the application.
Also how can I get the best quality image. Should I use a png, jpg or is there another type of image that could be used? Any hints on creating this image would be much appreciated.
A:
What you want is called App Icon, there are a lot of questions about this on SO and Xamarin docs.
iOS
Open Assets.xcassets under iOS project
If there isn't and AppIcon image set created, right click some empty place on the left white area and create a new AppIcon set, then click the AppIcon and just drag and drop the differents images size (you can see all the sizes the app need)
Finally open the Info.plist file and choose AppIcon as Source for App Icons
That should be enough for iOS App Icon, you can check this for more info: Application Icons in Xamarin.iOS
Android
For Android you would need to create icons with different sizes:
hdpi=281*164
mdpi=188*110
xhdpi=375*219
xxhdpi=563*329
xxxhdpi=750*438
48 × 48 (mdpi)
72 × 72 (hdpi)
96 × 96 (xhdpi)
144 × 144 (xxhdpi)
192 × 192 (xxxhdpi)
512 × 512 (Google Play store)
Then check if under Resources folder on the Android project are some folders named mipmap-(size), if not create like below:
Then place the icons in the corresponding folder with their size.
Next you want to do is set the icon on the Android Manifest, so right click on the Android project and open Properties, then on Android Manifest tab (VS for Windows) or Android Application (VS for Mac) choose your icon, so it should look like @mipmap/MyIcon and on your Main Launcher Activity set the icon like Icon = "@mipmap/MyIcon".
All images should be png type.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Question about set log_slow_verbosity='query_plan' in MariaDB ans MySQL
I have a question about set log_slow_verbosity='query_plan'
I set log_slow_verbosity='query_plan' on MariaDB 10.
I check the slow log and find more detailed information such as: full_scan; Full_join; tmp_table_on_disk.
When I set set log_slow_verbosity='query_plan' on MySQL 5.7:
mysql> set session log_slow_verbosity='query_plan,innodb';
ERROR 1193 (HY000): Unknown system variable 'log_slow_verbosity'
How to enable this parameter on MySQL 5.7 and get more detailed information in slow log?
A:
The mysql manual shows you what parameters are accepted, and allow you to tune your system. It's possible this is limited to long_query_time and min_examined_row_limit, while log_slow_verbosity is specific for mariadb.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
null reference when declaring a class as a window resource
I have problems with accessibility to a class, from the MainWindow code behind.
I have written this class:
namespace WpfApp1.Management
{
public class BookManagement : INotifyPropertyChanged
{ ...
which is referenced in MainWindow:
<Window
x:Class="WpfApp1.MainWindow"
x:Name="mainWindow"
...
xmlns:mangmt="clr-namespace:WpfApp1.Management"
by:
<Window.Resources>
<mangmt:BookManagement x:Key="bookManagement" />
</Window.Resources>
the fact is that I need to access to bookManagement from MainWindow.cs, and I tried this:
BookManagement bm= Application.Current.Resources["bookManagement"] as BookManagement;
bm.SelectedTab = "summary";
but I get a null reference exception at runtime.
thank you.
A:
It is part of your MainWindow's resources, not part of the application:
<Window.Resources>
<mangmt:BookManagement x:Key="bookManagement" />
</Window.Resources>
Use this to retrieve it instead:
Application.Current.MainWindow.Resources["bookManagement"]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to remove space betwen node icon and node text in XtraTreeList
I have a WinForm app with tree list. Nodes in list have image index and TreeList binded to image list.
The problem is I could not find the way to remove space between icon and text.
if sombody can help me, I will be grateful
A:
That looks like you have selected an empty image.
The treelist supports a StateImageList and a SelectImageList. Make sure you are only using the one you require. (Try setting the StateImageList property back to "(None)")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
repaint() method doesn't work more than once
I am currently working on a gui project which is managing a sql database. I am currently adding,deleting logs and showing tables existing in mysql. The problem is my add and delete buttons on my panel are supposed to repaint/refresh the table on that panel as a record is added or deleted however while testing I discovered that repaint method doesn't refresh the table after the first use of the button. What can cause this problem? Thanks in advance..
public JTabbedPane addComponentToPane() {
//Container pane = new Container();
JTabbedPane tabbedPane = new JTabbedPane();
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
JPanel card3 = new JPanel();
JPanel card4 = new JPanel();
JPanel card5 = new JPanel();
JPanel card6 = new JPanel();
JPanel card7 = new JPanel();
JPanel card8 = new JPanel();
card1.setLayout(new BorderLayout());
card2.setLayout(new BorderLayout());
card3.setLayout(new BorderLayout());
card4.setLayout(new BorderLayout());
card5.setLayout(new BorderLayout());
card6.setLayout(new BorderLayout());
card7.setLayout(new BorderLayout());
card8.setLayout(new BorderLayout());
JScrollPane actor = new JScrollPane(createTables("actor"));
card1.add(actor, BorderLayout.CENTER);
card3.add(createTables("address"), BorderLayout.CENTER);
card4.add(createTables("category"), BorderLayout.CENTER);
card5.add(createTables("city"), BorderLayout.CENTER);
card6.add(createTables("country"), BorderLayout.CENTER);
card7.add(createTables("customer"), BorderLayout.CENTER);
card8.add(createTables("film"), BorderLayout.CENTER);
JButton button = new JButton("Yeni Kayıt");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addRecord("actor");
card1.remove(actor);
card1.add(createTables("actor"), BorderLayout.CENTER);
card1.validate();
card1.repaint();
}
});
JButton delButton = new JButton("Kayıt sil");
delButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
delRecord("actor");
card1.remove(actor);
card1.add(createTables("actor"), BorderLayout.CENTER);
card1.validate();
card1.repaint();
}
});``
card1.add(button, BorderLayout.SOUTH);
card1.add(delButton, BorderLayout.EAST);
tabbedPane.addTab("Şirketler", null, card1, "şirket tanımları");
tabbedPane.addTab("Sorumlular", card2);
tabbedPane.addTab("Varlık Grupları", card3);
tabbedPane.addTab("Bilgi Varlıkları", card4);
tabbedPane.addTab("Varlık Değerleri", card5);
tabbedPane.addTab("Açıklıklar", card6);
tabbedPane.addTab("Tehditler", card7);
tabbedPane.addTab("Ek-A", card8);
//pane.add(tabbedPane, BorderLayout.CENTER);
return tabbedPane;
}
Create tables method creating a Jtable from sql table.
private JScrollPane createTables(String tablename) {
Connection con = null;
Statement statement = null;
ResultSet result = null;
String query;
JScrollPane jsp = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "root", "root");
statement = con.createStatement();
query = "select * from " + tablename;
result = statement.executeQuery(query);
ResultSetMetaData rsmt = result.getMetaData();
int columnCount = rsmt.getColumnCount();
Vector column = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row = new Vector();
while (result.next()) {
row = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
row.add(result.getString(i));
}
data.add(row);
}
defTableModel = new DefaultTableModel(data, column);
table = new JTable(defTableModel) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
;
};
//table.setAutoCreateRowSorter(true);
TableRowFilterSupport.forTable(table).searchable(true).apply();
table.setRowSelectionAllowed(true);
jsp = new JScrollPane(table);
}
catch (Exception e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(null, "ERROR");
}
finally {
try {
statement.close();
result.close();
con.close();
}
catch (Exception e) {
//JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
return jsp;
}
A:
I could see couple of inconsistencies in the code:
The actor variable is not being set to the added component in the action listener.
First time you are adding new JScrollPane(createTables("actor")) and then onwards you only add createTables("actor").
The (1) might be causing the problem.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Multiple columns in a single row with CardView Widget
I have implemented two columns in a single row as with using grid view as follows. However I recently came to know there is card view widget, which makes much nicer. But I wonder how it is possible to make two columns in a single row?
If it is possible, do you recommend me to switch from grid view to card view ? Is it commonly used nowadays?
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="2dp"
android:horizontalSpacing="2dp"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</android.support.v4.widget.SwipeRefreshLayout>
Is the following xml right to make two columns in a single row?
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content">
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content">
</android.support.v7.widget.CardView>
</LinearLayout>
A:
I suggest you to use Recyclerview and also cardview. Gridview is an old view and that will be deprecated soon by google. Recyclerview is better than gridview.
You don't have to add two columns in a single row in a Gridview. Instead you can use Recyclerview to get it nice. Cardview is just a list item background of a view.
-Just design your list item that corredponding to your design
-Add that into RecyclerViewAdaper
-Attach this with RecyclerView
-Get it fixed.
Here is an example for recyclerview with grid item in a card view.
Recyclerview Grid Item with Cardview
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Space between inputs doesn't give exception on array index?
I'm not sure what to title this question(if anyone has input on what to name the question, please let me know). My program asks the user for 5 int and 5 doubles. Then those numbers are put in an array and passes it to a method to get the average. My question is if I separate the user input by spaces and press enter(like so, 5 space 6...enter; it allows me to enter more than what is allowed in the array index. Why doesn't it give you a error? and how do you prevent this? Also any advice on how I write code would be helpful too!
Here is the code.
import java.util.*;
public class Lab7A_BRC{
public static void main(String[] args) {
System.out.println("\t\t Average arrays ");
Scanner input = new Scanner(System.in);
//array count varriable
int n = 5;
//array declaration
int [] list1 = new int[n];
double [] list2 = new double[n];
System.out.print("Enter 5 integer values. ");
for(int i = 0; i < n; i++) {
list1[i]= input.nextInt();
if(i == (n - 1)){
System.out.println("\t The average of the 5 integers is "
+ average(list1, n));
}
}
System.out.println("Enter 5 double values. ");
for (int i = 0; i < n; i++){
list2[i]= input.nextDouble();
if(i == (n-1)){
System.out.println("\t The average of the 5 doubles is "
+ average(list2, n));
}
}
}
public static int average(int[] array, int n){
int sum = 0;
for(int i = 0; i < n; i++){
int holdNumber = array[i];
sum += holdNumber;
}
int average = sum / n;
return average;
}
public static double average(double[] array, int n){
double sum = 0;
for(int i = 0; i < n ; i++){
double holdNumber = array[i];
sum += holdNumber;
}
double average = sum / n;
return average;
}
}
A:
It doesn't give you an error because you only read the first 5 values, as stated in your for loop.
The first thing is you should decouple your input logic from your output logic, so you know for sure you're in your 5th number when you exit the for loop.
Then you can check if there's anything else than a blank string left, if there is then you can throw an exception stating it has too many numbers.
I've adapted the integer part, you can easily adapt the doubles logic.
Feel free to ask if you have any doubts.
The adapted code:
import java.util.Scanner;
public class Lab7A_BRC {
public static void main(String[] args) {
System.out.println("\t\t Average arrays ");
Scanner input = new Scanner(System.in);
//array count varriable
int n = 5;
//array declaration
int[] list1 = new int[n];
double[] list2 = new double[n];
System.out.print("Enter 5 integer values. ");
for (int i = 0; i < n; i++) {
list1[i] = input.nextInt();
}
if (!input.nextLine().equals("")) {
throw new RuntimeException("Too many numbers entered!");
}
System.out.println("\t The average of the 5 integers is "
+ average(list1, n));
System.out.println("Enter 5 double values. ");
for (int i = 0; i < n; i++) {
list2[i] = input.nextDouble();
if (i == (n - 1)) {
System.out.println("\t The average of the 5 doubles is "
+ average(list2, n));
}
}
}
public static int average(int[] array, int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
int holdNumber = array[i];
sum += holdNumber;
}
int average = sum / n;
return average;
}
public static double average(double[] array, int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
double holdNumber = array[i];
sum += holdNumber;
}
double average = sum / n;
return average;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
kickstart partitioning error with LVM
In Kickstart, I keep on getting the error;
Adding this partition would not leave enough disk space for already
allocated logical volumes in vg_ibus
I do not get why I am getting this error. This device (ciss/c0d1) is 450G. I simply want to make one Logical Volume inside that Volume Group.
These commands are from the Kickstart script that I am using;
part pv.d1 --size=1 --grow --ondisk=cciss/c0d1
volgroup vg_ibus pv.d1
logvol /ibus --vgname=vg_ibus --size=450000 --name=lv_ibus
A:
It's likely not exactly 450G. Try to set a smaller size and use --grow so that the logical volume will grow to capacity of the block device. (Same as you are already doing for the physical partiion.)
logvol /ibus --vgname=vg_ibus --size=1000 --name=lv_ibus --grow
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What type of iOS project template should I start with?
I'm building a project similar in design/scope to Invoice2Go and was wondering what the appropriate iOS project type would be to start with in XCode.
A:
It doesn't really matter, from the most basic template (Window-based Application) you can setup any app. It seems Invoice2Go makes use of a tab bar, so the Tab Bar application seems most convenient, though you can add a tab bar to the Window-based Application as well.
Personally I like to start with a Window-based Application most of the time, this gives me the most flexible starting-point.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does the limit set contain forward orbit?
I just started reading on dynamical systems and the author made a claim that I don't quite understand. If someone could elaborate it would be highly appreciated!
So here is the problem: Let $X$ be a topological space $F:X \times \mathbb{N}_0\to X$ a flow with $F(x,0) = x$ and $F(x, n+k) = F(F(x, n),k)$. For each $x\in X$, we put $x(n) = F(x,n)$.
Now, define the limit set of $x\in X$ by
$$
\omega(x) = \{y\in X : \forall \text{neighbourhoods $U$ of } y, \exists n \text{ arbitrarily large such that } x(n) \in U\}.
$$
The author claims that if $y\in \omega(x)$ then $y(n)\in\omega(x)$ for all $n\in \mathbb{N}$. Can someone explain why this is true?
A:
The problem takes the form "If $y\in \omega(x)$ then $y(n)\in\omega(x)$". Start by restating the problem in terms of the provided definitions:
You are given a hypothesis: for all neighborhoods $U$ of $y$, there exists $t$ arbitrarily large such that $x(t)\in U$.
You want to prove a conclusion: for all neighborhoods $V$ of $y(n)$, there exists $s$ arbitrarily large such that $x(s)\in V$.
Hint: In order to use the hypothesis, you need to describe some neighborhood $U$ of $y$. Your $U$ will have to depend somehow on the data provided for the conclusion: the number $n$ and the neighborhood $V$ of $y(n)$. Given $n$ and $V$, how can you construct an appropriate $U$? Then, feeding $U$ into the hypothesis, you will get arbitrarily large $t$. How can you turn this into arbitrarily large $s$ that satisfies the conclusion?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does ICommand's CanExecute method work?
I've looked at some examples of implementing ICommand and to me the following way is the simplest:
class Command : ICommand {
public Func<object, bool> CanDo { get; set; }
public Action<object> Do { get; set; }
public event EventHandler CanExecuteChanged {
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public Command(Func<object, bool> CanDo, Action<object> Do) {
this.CanDo = CanDo;
this.Do = Do;
}
public bool CanExecute(object parameter) => CanDo(parameter);
public void Execute(object parameter) => Do(parameter);
}
and that's how I've implemented in my test app. In addition to the Command class I've the following class:
class Person : INotifyPropertyChanged {
string firstName, lastName, enabled;
public string FirstName {
get => firstName;
set { firstName = value; Changed();}
}
public string LastName {
get => lastName;
set { lastName = value; Changed(); }
}
public string Enabled {
get => enabled;
set { enabled = value; Changed(); }
}
public Command MyCommand { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public Person() {
MyCommand = new Command(CanDo, Do);
}
void Changed(string name = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
bool CanDo(object para) {
if (FirstName == "test" && LastName == "test") {
Enabled = "true";
//Changed("Enabled");
return true;
}
else {
Enabled = "false";
//Changed("Enabled");
return false;
}
}
void Do(object para) {
FirstName = "first";
LastName = "last";
}
}
and in xaml I've these:
<Window ...>
<Window.Resources>
<local:Person x:Key="person"/>
</Window.Resources>
<Grid DataContext="{StaticResource person}">
<StackPanel>
<TextBox Text="{Binding FirstName}"/>
<TextBox Text="{Binding LastName}"/>
<TextBlock Text="{Binding FirstName}"/>
<TextBlock Text="{Binding LastName}"/>
<Button Content="Click" Command="{Binding Path=MyCommand}"/>
<Label Content="{Binding Enabled}"/>
</StackPanel>
</Grid>
</Window>
After launching the app, whatever I try to type in those TextBox gets deleted instantly if I call Changed() in the setter of Enabled. If I comment out the Changed() in setter and uncomment two Changed("Enabled") in bool CanDo(object para) it works as expected!
Shouldn't calling the Changed() once in setter be equivalent to those two Changed("Enabled") call in bool CanDo(object para)?
A:
You are missing the CallerMemberNameAttribute in Changed:
void Changed([System.Runtime.CompilerServices.CallerMemberName]string name = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
This obtains the calling property name so you don't have to call Changed("Enabled") but simply Changed() in the setter.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are the jquery plugins used in https://supercrowds.co/who/
I need to find what are the plugins used in this https://supercrowds.co/who/ site. I tried it through inspector but it didn't work.
A:
They are using CreateJS and a lot of custom code.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regarding memory size of android application
Hei, I had developed an android application by using phone-gap framework. The memory size of .apk file is 350 kb. After installation, the usage of memory by the application is 2.00 mb. I want to reduce the usage of memory after installation,actually that is the requirement. On surfing Google, I worked on Images and images are of required pixels only. Is there any alternative to reduce the memory size of application .... thanks in advance.
A:
Your project may have files that were compressed while generating apk file for you. These files are decompressed when you install the application.
Try to reduce the size of the files in your source code.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are these C# and Python code snippets functionally identical?
I have a bit of Python source code that I want to recreate in C#. The code is about reading and decrypting a binary file. I have tested the function on an existing file and it runs without errors; while the resulting string is not garbled or anything, it does not appear to be useful to me.
But that is outside the scope of this question. I only want to know if I have translated the function correctly to C# so it does the same as in Python.
The Python code:
filename = os.path.basename(path_and_filename)
key = 0
for char in filename:
key = key + ord(char)
f = open(path_and_filename, 'rb')
results = ''
tick = 1
while True:
byte = f.read(2)
if byte:
if tick:
key = key + 2
else:
key = key - 2
tick = not tick
res = struct.unpack('h', byte)[0] ^ key
results = results + chr(res)
continue
break
f.close()
return results
path_and_filename is an absolute path to the encrypted file.
Here is the C# code I wrote:
string path = _path;
string fileName = _fileName;
char[] chars = fileName.ToCharArray();
int key = 0;
foreach (char c in chars)
{
key += c;
}
StringBuilder builder = new StringBuilder();
using (FileStream file = new FileStream(path, FileMode.Open))
{
bool tick = true;
while (true)
{
int i = file.ReadByte();
if (i == -1)
break;
if (tick)
key += 2;
else
key -= 2;
tick = !tick;
//The next 2 lines are for parsing the short, equivalent(?) to struct.unpack('h', byte)
i <<= 8;
i += file.ReadByte();
i ^= key;
byte b = (byte)i;
char c = (char)b;
builder.Append(c);
}
}
string result = builder.ToString();
Never mind the dirtiness of the code. Will those 2 snippets give the same output to a certain input?
A:
This section seems wrong:
//The next 2 lines are for parsing the short, equivalent(?) to struct.unpack('h', byte)
i <<= 8;
i += file.ReadByte();
you're shifting the value in i 8 bits left and then reading another byte. I'm guessing because the original code read it in 2 bytes at a time. If your file isn't the right length then this will break it here. what about:
i <<= 8;
int secondByte = file.ReadByte()
if(secondByte != -1)
{
i += secondByte ;
}
Whats with this? It is casting an int to a byte to a char and it is truncating.
byte b = (byte)i;
char c = (char)b;
so you're better off ignoring the first byte and instead everything after tick = !tick;
could be:
i = file.ReadByte();
char c = (char)(i ^ (key & 255));
builder.Append(c);
In Python chr() will throw an exception if the value is greater than 255 anyway.
And IMHO it is a bad idea to roll your own encryption/decryption like this. Use a trusted known solution instead.
Question: I only want to know if I have translated the function correctly to C# so it does the same as in Python
Answer Its more of a transliteration rather than a translation but they should give the same output. If I were to re-write the python into c# it would look different as it seems inefficient to me.
A:
After a half-nighter, I finally found the solution. Running the code via Iron Python told me that os.path.basename(path_and_filename) in my case does return the file name, as pointed out in the comments, not the name of the last folder. That was the first problem, so I've been working with the wrong key.
The second issue was how I read the bytes to XOR with the key. Apparently, unpacking the two bytes read reverses their order in python, so in C# I have to read them in reverse order as well.
So my code would actually look something like this:
string path = _path;
string filename = _fileName;
//python os.path.basename()
char[] chars = filename.ToCharArray();
int key = 0;
foreach (char c in chars)
{
key += c;
}
StringBuilder builder = new StringBuilder();
using (FileStream file = new FileStream(path + filename, FileMode.Open))
{
bool tick = true;
while (true)
{
int i = file.ReadByte();
//it's ok to break here because if the first byte is present, then the second byte will also be present, because the data files are well formed.
if (i == -1)
break;
//we can skip the 2nd byte because the algorithm ignores it anyway
file.ReadByte();
if (tick)
key += 2;
else
key -= 2;
tick = !tick;
i ^= key;
char c = (char)(i & 255);
builder.Append(c);
}
}
string result = builder.ToString();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
'as.tibble' causes error in tibble 2.0.1 but not 1.4.2
I have written a function part of which converts a matrix to a tibble. This works without issues in tibble 1.4.2 but causes an error in 2.0.1.
The code that causes the error is as follows
library(tibble)
library(magrittr)
testmerge <- matrix( data = NA, ncol = 6 + 1, nrow = 0) %>%
as.tibble
The Error message is below
I can solve the problem by doing the following
testmerge <- matrix( data = NA, ncol = 6 + 1, nrow = 0) %>%
as.data.frame() %>%
as_tibble
But this seems a bit long winded.
What is happening that has caused this change? And how can I easily end up with a tibble of just empty columns?
A:
You need to specify .name_repair; see ?as_tibble:
library(tibble)
library(magrittr)
sessionInfo()
#> R version 3.5.2 (2018-12-20)
#> Platform: x86_64-pc-linux-gnu (64-bit)
#> Running under: Ubuntu 18.04.1 LTS
#>
#> Matrix products: default
#> BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
#> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1
#>
#> locale:
#> [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
#> [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
#> [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
#> [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
#> [9] LC_ADDRESS=C LC_TELEPHONE=C
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> other attached packages:
#> [1] magrittr_1.5 tibble_2.0.1
#>
#> loaded via a namespace (and not attached):
#> [1] Rcpp_1.0.0 digest_0.6.18 crayon_1.3.4 rprojroot_1.3-2
#> [5] backports_1.1.2 evaluate_0.11 pillar_1.3.1 rlang_0.3.1
#> [9] stringi_1.2.4 rmarkdown_1.10 tools_3.5.2 stringr_1.3.1
#> [13] yaml_2.2.0 compiler_3.5.2 pkgconfig_2.0.2 htmltools_0.3.6
#> [17] knitr_1.20
Your code worked just fine for me with tibble_1.4.2, as you describe, but after upgrading to tibble_2.0.1, I end up with the same error you had, but with a slightly more informative message that included the sentence Use .name_repair to specify repair.:
testmerge <- matrix( data = NA, ncol = 6 + 1, nrow = 0) %>%
as_tibble()
#> Error: Columns 1, 2, 3, 4, 5, … (and 2 more) must be named.
#> Use .name_repair to specify repair.
testmerge <- matrix( data = NA, ncol = 6 + 1, nrow = 0) %>%
as_tibble(.name_repair = "unique")
#> New names:
#> * `` -> `..1`
#> * `` -> `..2`
#> * `` -> `..3`
#> * `` -> `..4`
#> * `` -> `..5`
#> * … and 2 more
testmerge
#> # A tibble: 0 x 7
#> # … with 7 variables: ..1 <lgl>, ..2 <lgl>, ..3 <lgl>, ..4 <lgl>,
#> # ..5 <lgl>, ..6 <lgl>, ..7 <lgl>
Update, in the comments, @NelsonGon links to a GitHub issue, the discussion of which seems to have led to this new behavior.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change Letters to numbers (ints) in python
This might be python 101, but I am having a hard time changing letters into a valid integer.
The put what I am trying to do simply
char >> [ ] >> int
I created a case statement to give me a number depending on certain characters, so what I tried doing was
def char_to_int(sometext):
return {
'Z':1,
'Y':17,
'X':8,
'w':4,
}.get(sometext, '')
Which converts the letter into a number, but when I try using that number into any argument that takes ints it doesn't work.
I've tried
text_number = int(sometext)
But I get the message TypeError: int() argument must be a string or a number, not 'function'
So from there I returned the type of sometext using
print(type(sometext))
And the return type is a function.
So my question is, is there a better way to convert letters into numbers, or a better way to setup my switch/def statement
Heres the full code where its call
if sometext:
for i in range ( 0, len(sometext)):
char_to_int(sometext[i])
I've managed to get it working, ultimately what I changed was the default of the definition, I now set the definition to a variable before instead of calling it in another function, and I recoded the section I was using it.
Originally my definition looked liked this
def char_to_int(sometext):
return {
...
}.get(sometext, '')
But I changed the default to 0, so now it looks like
def char_to_int(sometext):
return {
...
}.get(sometext, 0)
The old code that called the definition looked
if sometext:
for i in range ( 0, len(sometext)):
C_T_I = int(char_to_int(sometext[i]))
I changed it to this.
if sometext:
for i in range ( 0, len(sometext)):
C_T_I = char_to_int(sometext[i])
TEXTNUM = int(C_T_I)
Hopefully this clarifies the changes. Thanks for everyone's assistance.
A:
in the python console:
>>> type({ 'Z':1, 'Y':17, 'X':8, 'w':4, }.get('X', ''))
<class 'int'>
so as cdarke suggested, you should look at how you are calling the function.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Looks like only a part of the API call is anwered in Ahsay
Some time ago I started to use the api call system of Ahsay and wasn't that difficult to understand.
In the webbrowser the API call works, but when I try to use C# only a part seems to get to Ahsay?
I'm using this code of CodeProject to do the API call:
http://www.codeproject.com/Tips/497123/How-to-make-REST-requests-with-Csharp
In this code I send as API call:
{SysUser: system, SysPwd: system, LoginName: test, Owner: , Password: test}
and get as error code:
<err>[Error] Parameter LoginName is null/empty!</err>
If I sent the same requist as an URL like:
http://SERVERIP/obs/api/AuthUser.do?SysUser=system&SysPwd=system&LoginName=test&Password=test`
it gives as error code: <err>[Error] The password must be at least 6 characters in length!</err>
Can somebody explain to me why the LoginName isn't send or received in the C# code?
A:
If someone encounters the same problem, here is the code I's using:
public void API_HTTP()
{
string url = "http://URL";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
String output = reader.ReadToEnd();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I remove a vdev from a ZFS pool by rolling back?
A curiosity related question:
Can a VDEV be removed from a ZFS pool by undoing the last pool transactions (zpool import -F) or rolling back to an earlier snapshot?
A:
No. You're mistaking data and pool geography/layout. The former is transactional with some ability to go backwards (zpool import -F), the latter is not. Once you change it, it's changed. There's no rolling ring of previous pool layouts you can 'roll back' to.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Counting Calories when Training for TKD Tournament
I'm training for a TKD tournament. My Master is a very big proponent of counting calories, but I don't want to eat too little when I'm training intensely for the rest of the year. I obviously don't want to go over or under my weight class either. That being said, is counting calories something I should do? Or should I just eat healthy (meats, fruits, and veggies) and not worry about caloric intake?
A:
In its most basic sense, just let the scale be your guide. Weigh yourself at the same time under the same conditions every day (Such as first thing when you get up in the morning), and watch the trends. If you notice that your weight is creeping up, you need to either increase your cardio/workouts a bit or cut back on the calories a bit. Be aware that if you ease off your workouts to taper/be fresh for a competition, you may need to cut calories slightly as well.
To some extent, the "3500 calories = 1 lb" is a bit of a myth. The base fact is that if you expend more calories than you consume, you will lose weight, and if you eat more than you expend you will gain.
As far as the composition, since you are not an endurance athlete, my personal recommendation is to aim for about 40-50% calories from lean proteins, 20% from healthy fats and 30-40% from carbohydrates (For comparison, endurance athletes will be in the 50-60% range for carbohydrates). You can get a lot of your carbs from fruits and vegetables, and any grains that you consume should be as unprocessed as possible. I generally tell people to "shop the edges" of the store, as that is usually the raw meats section, produce, bakery. The further into the boxes you get, the more processed/empty calories come into play.
Lean meats: Turkey, chicken, pork, lean ground beef, certain steak cuts. Healthy fats - Vegetable oils, avocado, nuts. Best oils for cooking are grapeseed, walnut and avocado. Avoid oils with high levels of saturated fats.
Depending on the style of tournament and the length, you may want to increase carbs slightly in the days leading up, but be aware that this will also cause a slight rise in weight as the muscles retain more glycogen and water. True carbo loading is a 1-2 week process, and generally only done by endurance athletes to maximize energy stores just before long events. You may also want to experiment in training with various food bars (Such as Lara bars, one of my personal picks) for energy/nutrition between matches.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does setTo not work (assertion failed)?
I am just learning OpenCV and, since I have some experience with Matlab's logical indexing, I was really interested to see the matrix method setTo. My initial attempt doesn't work though, and I can't work out why, so I'd be very grateful for your help!
I have a Mat containing image data, and want to set all values greater than 10 to zero. So, I did:
Mat not_relevant = abs(difference - frame2) > 10;
difference = difference.setTo(0, not_relevant);
This however gives me:
OpenCV Error: Assertion failed (mask.empty() || mask.type() == CV_8U) in
cv::Mat::setTo, file
C:\builds\2_4_PackSlave-win32-vc12-shared\opencv\modules\core\src\copy.cpp, line 347
I have tried converting not_relevant, difference and frame2 before doing this using, e.g.:
frame2.convertTo(frame2, CV_8UC1);
but that did not fix the error, so I'm not sure what else I could try. Does anyone have any idea what might be wrong?
Thank you for your help!
A:
I think the error is pretty clear.type of your mask image should be CV_8U.
so you need to convert not_relevent to grayscale.
Mat not_relevant = abs(difference - frame2) > 10;
cv::cvtColor(not_relevant, not_relevant, CV_BGR2GRAY);
difference = difference.setTo(0, not_relevant);
Why convertTo does not work here ?
CV_8U(or CV_8UC1) is type of image with one channel of uchar values.
convertTo can not change number of channels in image.
So converting image with more than one channel to CV_8U using convertTo does not work .
check this answer for more detailed explanations.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to modify this directive, so that once the input is visible, it won't be hidden unless the x is clicked?
http://plnkr.co/edit/fXo21LnphHZ3qWnuEMFt?p=preview
Right now, if you click anywhere outside of the input, the focusMe directive scope.$watch will trigger and turn showingTagSearchInput false.
This needs to only happen when the close x button is clicked.
Markup
<div class="sidebar" ng-controller="sidebar">
<div class="btn-search"
ng-hide="showingTagSearchInput"
ng-click="quickSearchTags()">Search</div>
<div class="search-tags-input container-fluid" ng-show="showingTagSearchInput">
<input type="text"
focus-me="showingTagSearchInput"
placeholder="search for a tag"
ng-model="tagSearchInput"
class="form-control">
<div>close x</div>
</div>
</div>
Controller functions
// search button stuff:
function quickSearchTags() {
vs.showingTagSearchInput = !vs.showingTagSearchInput;
}
function closeMe() {
console.log('closeMe clicked');
vs.showingTagSearchInput = false;
}
The focusMe directive:
.directive('focusMe', ['$timeout', '$parse', function($timeout, $parse) {
return {
link: function(scope, element, attrs) {
var model = $parse(attrs.focusMe);
scope.$watch(model, function(value) {
console.log('value ', value);
console.log('element ', element);
if (value === true) {
$timeout(function() {
element[0].focus();
});
}
});
element.bind('blur', function() {
scope.$apply(model.assign(scope, false));
})
}
}
}])
A:
Remove the blur event from focusMe directive which is hidding div on blur.
Instead of that call ng-click event that will set showingTagSearchInput to false & element will get hidden.
Markup
<input type="text"
focus-me="showingTagSearchInput"
placeholder="search for a tag"
ng-model="tagSearchInput"
class="form-control">
<div class="btn-close" ng-click="closeMe()">close x</div>
Code
$scope.hideInput = function(){
$scope.showingTagSearchInput = false;
};
Demo Plunkr
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to update to QGIS 2.0.1 on Mac?
I'm trying to upgrade to the newest version of qGIS but get the following error message when I open the installer:
QGIS requires the GEOS framework version 3.4 or newer.
I've had no luck maintaining my version of geos via the geos download page, and have instead installed it via homebrew. Is it possible to tell qGIS where the homebrew maintained version of GEOS lives?
I would maintain osgeo via http://trac.osgeo.org/geos/ but keep getting error messages when I run the newest installer (3.4.2) and all advice I've found elsewhere on debugging the installer suggest that I shouldn't bother messing around w/ all the dependencies and should instead use homebrew.
So this brings me back to where I started: is it possible to have homebrew maintain a version of osgeo that qgis can continue to locate? Or, am I forced to keep trying to debug the geos installer?
A:
The easiest way to upgrade is to use the binaries at http://www.kyngchaos.com/software/qgis
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reading app.config of a VB6 project from a C# dll library
I need to create a C# .NET DLL library that can read all the project configurations from a config file.
The main project was written in VB6, that calls my C# DLL library.
I created a test method that returns a cabled string and the call works correctly, so the VB6 to C# integration works.
My problem is that I use the System.Configuration.ConfigurationManager class to read the configuration file (App.config). It works if the call come from a C# test project but it doesn't work if the call became from VB6 project.
I think that the problem is caused by VB6 that don't read App.config file as project configuration file, how I can do that?
A:
The problem is solved:
I tried to rename App.config in myVB6AppName.exe.config but it doesn't work.
The solution is including myVB6AppName.exe.config file in VB6 project as document. Now it works!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use the selected date on the previous page?
How to use the selected date on the previous page?
We get the value date:
<%= form_tag :action => 'method_name' do %>
<%= text_field_tag('datetimepicker12', nil, options = { :onchange => "this.form.submit()"}) %>
<% end %>
Controller:
def selectday
end
def method_name
@date=params[:datetimepicker12]
redirect_to selectday_path(@date)
end
view selectday receives parameters:
Request
Parameters:
{"format"=>"24-06-2015"}
Here it is necessary to print the selected date. Call object in selectday view, but no output it:
<span> <%= @date %></span>
A:
You should use like:
def selectday
@date = params[:date]
end
def method_name
@date=params[:datetimepicker12]
redirect_to selectday_path(date:@date)
end
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Understanding Delphi MAP File
Here is the sample of MAP file from my test project...
.......
.......
.......
0001:001EFC14 00000020 C=CODE S=.text G=(none) M=Vcl.CategoryButtons ACBP=A9
0001:001EFC34 0000284C C=CODE S=.text G=(none) M=Vcl.SysStyles ACBP=A9
0001:001F2480 000407A8 C=CODE S=.text G=(none) M=Vcl.Styles ACBP=A9
0001:00232C28 00006998 C=CODE S=.text G=(none) M=MainU ACBP=A9
0002:00000000 000000B4 C=ICODE S=.itext G=(none) M=System ACBP=A9
0002:000000B4 00000008 C=ICODE S=.itext G=(none) M=SysInit ACBP=A9
.....
.....
My Unit (MainU) resides from 00232C28 to 00006998. Upto here, the memory address prefix with 0001. Starting from the next unit, it begins 0002 and so on.
What does it mean?
As well, what is 'C=', 'S=' 'G=' 'M=' and 'ACBP = '?
A:
The format is:
SegmentId:StartAddress Length C=SegmentClass S=SegmentName G=SegmentGroup M=ModuleName
The ACBP has something to do with alignment but I can't tell you what the hex numbers mean.
C=CODE: Code-Segment
C=ICODE: Initialization Code-Segment
C=DATA: (initialized) Data-Segment
C=BSS: (uninitialized) Data-Segment
C=TLS: Thread Local Storage
G=(none): No Segment-Group
A:
It mean that your asm code of your unit MainU start at $00232C28 address and the length of compiled unit is $00006998 bytes.
The segment class (C=) is CODE, defined at beginning of map file.
The segment name (S=) is .text
The segment group (G=) is none.
The segment module (M=) is MainU
The ACBP attribute = A9 mean:
Unnamed absolute portion of memory address space
A public combining
The segment may be larger than 64K
Check also: http://files.mpoli.fi/unpacked/software/programm/general/ss0288.zip/ss0288_4.txt
|
{
"pile_set_name": "StackExchange"
}
|
Q:
”不細工な皮で包み…" is this a metaphor?
So I'm reading part of a book, and one of the characters says this;
「不細工な皮で包みやがって」
When I tried to translate it and understand what it means, it didn't make too much sense to me "Hiding behind ugly skin" (?) leading me to believe this may be some sort of metaphor?
Context: character A is going towards B, about to launch an attack on him. Character B is defending himself behind a barrier he built using the lifeforms he created. I believe it is character A who then says the above line before aiming to attack B in order to make his barrier disappear.
A:
特にメタファーなどはないと思います。「a barrier he built using the lifeforms he created」が実際どのくらい「不細工」なのかはわかりませんが、それを指して、侮蔑的に・さげすんで「不細工な皮」と言っていて、文字通り「不細工な皮で(自分を)包みやがって!」あるいは「不細工な皮に隠れやがって!」と言いつつ、「こんなもの剝いでやる!」「こんなもの、破ってやる!」といったような気持ちだと思います。"What an ugly skin you're hiding yourself behind!" という感じだと思います。
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to concatenate multiple LWP get commands
I am using LWP to get html from three different web pages (defined dynamically) and assign it to a scalar $content. Sometimes one or more of the pages I search will not exist, so get will sometimes return undef. How should I handle this, such that $content will include all successful get commands?
I have the following which works if only one of my get requests returned a defined value:
unless ($content = get $page_one)
{
unless ($content = get $page_two)
{
unless ($content = get $page_three)
{
$content = "";
}
}
}
but obviously, it doesn't get all the content if more than one page was going to return a defined value.
A:
That's because you nest conditions and make them depend on success of previous gets, when they shouldn't.
my $result;
if ($content = get $page_one) { $result .= $content }
if ($content = get $page_two) { $result .= $content }
if ($content = get $page_three) { $result .= $content }
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTML documentation build issue with Wolfram Workbench 2 and MMA 9
Using the Wolfram Workbench 2 (and Mathematica 9) to build HTML documentation for a package I am developing, I am ending up with HTML pages that contain a lot of text elements that look like this:
Div[{class -> MCap}, {Change a few exchange reaction flux bounds to reflect an aerobic minimal glucose medium.}]
or
Div[{}, {XMLElement[a, {href -> javascript:input('i_9'), onmouseover -> javascript:return(true);}, {XMLElement[img, {src -> Files/Constraint-based modeling/I_10.gif, height -> 35, width -> 447, alt -> Click for copyable input}, {}]}]}]Div[{name -> i_9_out, id -> i_9_out, class -> IFL}, {}]
It looks a lot like a shadowing error and indeed a new Div function has been introduced to Mathematica 9. Is there a way to work around this for the moment? The HTML documentation builds fine with Mathematica 8.
A:
The Documentation Tools in Workbench 2.0 haven't been updated yet to work properly with Mathematica 9, so the easiest workaround is to use Mathematica 8 to build your HTML pages.
However, if this isn't a option for whatever reason, you could try to modify the code of Documentation Tools in order to solve this particular issue. I haven't tested the following, but I suspect there's a high chance it might work.
The culprit in your case is the file /Transmogrify/Kernel/Transmogrify.m, which can be found in the directory DocumentationBuild, whose value can in turn be read of from the first few log lines of a doc build in WorkBench. In Transmogrify.m, change the line
Div[ attr_List:{}, cont_ ] := TagElement["div", attr, cont];
(found at line number 2588) to
Unprotect[Div];
Div[ attr_List:{}, cont_ ] := TagElement["div", attr, cont];
Protect[Div];
Let me know if this did the trick!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does my print statement only work inside of a for loop?
Upon inputting a number, nothing happens. if I put the print statement inside one of the conditional statements, it prints it, but it will print it as many times as it loops.
Really curious about what is happening and how I can print the final list just one time in the simplest way.
number = input('Enter a Number')
newList = []
for i in range(1,10000000000001):
if int(number) % i == 0:
newList.append(i)
print(newList)
A:
You haven't waited long enough, your loop isn't done yet.
You are looping 10 ^ 13, or 10 trillion times, before printing:
for i in range(1,10000000000001):
That'll take Python a while, executing the loop body has a cost. On my laptop (a 2017 MacBook Pro with 2.9 GHz Intel Core i7 processor), I can run your loop body 10 million times in about 1 and a quarter second:
>>> import timeit
>>> timeit.timeit(
... "int(number) % i == 0", # loop body code
... "number = 42; i = 43", # set values for the variables
... number=10**7) # number of repetitions to time
1.259572982788086
10 trillion repetitions would take 10 ** 6 (1 million) times longer, so about 1259573 seconds.
1259573 seconds is 349 hours, 52 minutes and 53 seconds:
>>> from datetime import timedelta
>>> print(timedelta(seconds=1.259573 * 10 ** 6))
14 days, 13:52:53
You'll have to wait 2 weeks and 14 hours, before the loop is done!
You don't need to loop that often. If you are trying to find the divisors of a number, you only need to loop up to the square root of the number, because you can always find the 'other' divisor' by dividing number by the divisor again. The square root is the highest value a divisor can get before number // divisor produces numbers that are smaller than the divisor (and thus have already been tested):
number = int(input("Enter a number: ")
for i in range(1, int(number ** 0.5) + 1):
if number % i == 0:
# i is a divisor
print(i, end=' ')
# so is number // i
j = number // i
# but test if it is different from i
if j != i:
print(j, end=' ')
This prints out the divisors in a different order, of course:
Enter a number: 1002001
1 1002001 7 143143 11 91091 13 77077 49 20449 77 13013 91 11011 121 8281 143 7007 169 5929 539 1859 637 1573 847 1183 1001
You could reduce the number of iterations even further; odd numbers can only have odd divisors, so you may as well skip all the even numbers.
The following sets a step size for range(), either 1 (for even numbers) or 2 (for odd numbers):
number = int(input("Enter a number: ")
for i in range(1, int(number ** 0.5) + 1, 1 + (number % 2)):
if number % i == 0:
# i is a divisor
print(i, end=' ')
# so is number // i, but test if it is different
j = number // i
if j != i:
print(j, end=' ')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I use Xamarin.Forms.DependencyService in Visual Studio Unit Test (class library) project?
I am building a mobile application using Xamarin Forms and taking advantage of MVVM through Xamarin Forms Labs plugin. I have my solution set up as follows:
iOS project
UI Portable Class Library project (Views/Xaml only)
Core Portable Class Library project (ViewsModels/Models/everything else)
Testing Class Library project
I have successfully added the testing project with a reference to both Xamarin Forms and Xamarin Forms Labs, and can run tests instantiating the ViewModels. However as I am using Xamarin Forms Dependency Service for cross platform functionality and I thought I could use it as well in the Testing library to inject dummy implementations for those platform specific calls. This way I could more fully test the View Models and everything else.
However in the following code:
[TestMethod()]
public void TestingDependencyInjection()
{
string strInfo = Xamarin.Forms.DependencyService.Get<Interfaces.ITestingInterface>().GetInformation();
Assert.IsFalse(string.IsNullOrEmpty(strInfo));
}
There is an InvalidOperationException thrown from Xamarin.Forms.Core.dll with the following information: "You MUST call Xamarin.Forms.Init(); prior to using it."
But in the testing project "Init" is not a member of Forms!
I suppose I could use some other injection service on top of the one that already is in Xamarin Forms but I was hoping not to do that.
Anyone else tried to do this?
A:
You have to assign a class that implements IPlatformServices to Device.PlatformServices static property. Now, that is tricky because both IPlatformServices interface and Device.PlatformServices are internal. But it is doable.
Name your unittest assembly as "Xamarin.Forms.Core.UnitTests" because internals are visible to assembly named like that (among few other names).
Implement fake PlatformServices, i.e.:
public class PlatformServicesMock: IPlatformServices
{
void IPlatformServices.BeginInvokeOnMainThread(Action action)
{
throw new NotImplementedException();
}
ITimer IPlatformServices.CreateTimer(Action<object> callback)
{
throw new NotImplementedException();
}
ITimer IPlatformServices.CreateTimer(Action<object> callback, object state, int dueTime, int period)
{
throw new NotImplementedException();
}
ITimer IPlatformServices.CreateTimer(Action<object> callback, object state, long dueTime, long period)
{
throw new NotImplementedException();
}
ITimer IPlatformServices.CreateTimer(Action<object> callback, object state, TimeSpan dueTime, TimeSpan period)
{
throw new NotImplementedException();
}
ITimer IPlatformServices.CreateTimer(Action<object> callback, object state, uint dueTime, uint period)
{
throw new NotImplementedException();
}
Assembly[] IPlatformServices.GetAssemblies()
{
return new Assembly[0];
}
Task<Stream> IPlatformServices.GetStreamAsync(Uri uri, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
IIsolatedStorageFile IPlatformServices.GetUserStoreForApplication()
{
throw new NotImplementedException();
}
void IPlatformServices.OpenUriAction(Uri uri)
{
throw new NotImplementedException();
}
void IPlatformServices.StartTimer(TimeSpan interval, Func<bool> callback)
{
throw new NotImplementedException();
}
bool IPlatformServices.IsInvokeRequired
{
get
{
throw new NotImplementedException();
}
}
}
Take note that I am not returning any assembly in GetAssembly block (there assemblies are analyzed for types that implements the interfaces). Feel free to return an array of assemblies you need.
Assign an instance of PlatformServicesMock to Device.PlatformServices:
var platformServicesProperty = typeof(Device).GetProperty("PlatformServices", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
platformServicesProperty.SetValue(null, new PlatformServicesMock());
That's a dirty solution but it should work nevertheless. Also note that Visual Studio would probably draw a lot of squiggle lines indicating errors (internal not visible) but would compile just fine.
HTH
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I get the IP Server Parameter in a non-activity class
First let me explain what I'm doing...
I have a static class responsible to do my requisition SOAP to the server.
In there I have a static string URL with the IP Server.
It's all right and working fine, but now, I'm going to deploy in the customer's shop, and I need to configure the IP Server when I install the APK in the customer's tablet...
That's my problem. How can I set the IP Server programmatically? I have a "Login" interface, then I can enter like ADMIN Mode and import DB and set the IP...
In the requisition class is a non-activity class, don't have any context and is static...
A:
You must call it with a Context in the Constructor, or you can use a static context in it and set it from the activity, but of course the first solution is the ideal.
Then you can save the IP to the shared_preferences from your activity, and get it with your context from the class.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Burninate [players]. The tag, I mean
I've browsed through the players questions and found these ones:
Questions about issues with problem-players
Questions about social aspects of role-playing games or group-dynamics
Question about absent-players
Questions about a random TRPG problem, in which players are involved somehow
There are more descriptive tags for types 1-3 questions, and type 4 is basically the majority of questions on RPG.SE. Do we really need the players tag?
A:
We don't need it.
I will agree with what was stated in the answers of the Worth of "GM" and "players" tags question.
My opinion on tags is simple: if I go into the tag query, I should know what I will be looking at. IMO tags are mostly used for filtering and searching. If I have a metagaming problem and I want to check if it was already asked, I will search the metagaming tag. If I feel I have decent lawyering skills, I will put the rules-as-written in my favorites and look for answering these. Point being: the tags I personally consider useful are tags that describe what the question is about.
The players tag doesn't. As you said, if I look through this tag, I don't know if I'm looking at "I am a player" questions (which doesn't actually need a tag, imo), "I have a problem with a player" questions (which can be either my problem with him being as a player or as a person, so either problem-players or something social or group-dynamics as you said) or even simply "There are players involved" (which any question about an actual table will have, supposedly). Point being: I don't have a clue what I would be looking at if I went through the players tag. (tbh I didn't even know it existed until now). Many of the questions are actually gm-techniques questions, and I wouldn't expect that in a tag called "players".
Okay but how do we know that's not just you being dumb?
Well, I searched through the tag. I still don't know what the tag is about.
How can I interest a player in playing online? - this is simply online-roleplaying and possibly a system (in this case, tagged as agnostic, but I do think the system makes a difference here.)
How can I, as a player, help a struggling GM at a one-time game? - this is a question that I can't think of a good describing tag, but it's also not a question I would
Keeping the world alive whilst PCs take a rest mid-adventure? - the players tag doesn't tell me anything (actually it's more like a gm-techniques than anything actually related to players), the LMoP, dnd-5e and rests do. They are enough. I actually took the liberty to edit out the players tag and add the gm-techniques. :P
How to extract yuan-ti poison? - "There is a player involved and he wants to try something, are there rules for it?", really, we don't need a tag for the "there is a player involved and he wants to try something" part. The tags just need to tell what is "it" (monsters, poison) and where should we look for these rules (i.e. the system, dnd-5e), imo.
How to deal with a player missing the first session of a campaign - this is the only case where players was the only tag in the question. We have the absent-players for it, though, which actually describes something (that we are dealing with a problem related to players missing one or more sections). Reason I am saying "was" the only tag - I edited it :P
I'm not going to paste and justify all the questions, but I have at least read the title of most of the 123 questions and I didn't see a case where the tag was useful.
A:
Update: Done!
Background
This looks like a good candidate for blacklisting. It's the sort of tag a person might reasonably assume was useful, but doesn't really add anything to question. At 102 questions, removing the tag is right on the edge of being reasonable to do manually. Looking at the discussion here, I think I can safely eliminate the tag from most of the questions because they already have a more useful tag such as group-dynamic. But I'd like someone to look at questions that might need another tag. By my estimate, these questions could use another look:
[players] -[*-players] -[player-*] -[group-dynamics] -[social] -[gm-techniques]
(I don't know enough about this topic to make a call on this, but would it be helpful to also exclude questions with roleplaying? Maybe new-gm too, but that seems more a stretch.)
If that query gets down to 0, I'd be happy to just burninate the tag.
As for blacklisting, I need a blurb about why the tag isn't a good fit on the site. For instance, the [rules-as-written] tag has an error that reads:
Rules-as-written questions are however entirely welcome on this site and we embrace a plurality of playstyles. Please simply tag with the game and edition you're asking about. For more information see: Time to retire the [rules-as-written] tag?
A blurb for players doesn't need to be complicated, but it should be clear what askers should do instead. Once we settle on copy and the tag is gone from all questions, let me know and I'll blacklist it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
change format of a column in a element of a list with lapply
I have a list of data.frames and I want to change the class of one column of the data.frame (from factor to date). I was trying to use lapply but then, the original list only contains that column (not the whole data.frame). I don't understand this behaviour..to solve this I use a common loop, but I was wondering if anyone could have any suggestion.
Let's say, as an example, I have this simple data:
m1 <- data.frame("date"=c("2010-02-03","2010-01-05"),"value"=c(5,3))
m2 <- data.frame("date"=c("2010-02-03","2010-01-05"),"value"=c(1,3))
mylist <- list(m1,m2)
#change date
newlist <- lapply(mylist, function(x) as.Date(x$date))
newlist will have only the date..
Is there any way to use lapply for that..I am working with large dataset, and usually lapply works fine, but in this case, I don't know what I'm doing wrong.
Many thanks.
A:
We can use transform
lapply(mylist, transform, date = as.Date(date))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Replacing "localhost" in text file using sed
I have such file and I would like to replace $GLOBALS['SERVER_MEMCACHED']='localhost'; with $GLOBALS['SERVER_MEMCACHED']='mydomain.com'; using sed.
How to do this ? I don't want to replace the DB_HOST too.
<?php
$GLOBALS['DB_HOST']='localhost';
$GLOBALS['DB_NAME']='database';
$GLOBALS['DB_LOGIN']='login';
$GLOBALS['DB_PASSWORD']='password';
$GLOBALS['PORT_MYSQL']='3306';
$GLOBALS['PORT_MYSQLI']='3306';
$GLOBALS['SERVER_MEMCACHED']='localhost';
$GLOBALS['PORT_MEMCACHED']='11211';
$GLOBALS['CACHE_TIME']=600;
?>
A:
sed -i '/SERVER_MEMCACHED/s/localhost/mydomain.com/' input
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Components in JDialog not showing
First of all: I know this question seems to have been asked a few million times, but none of the answers given to other questions seem to work with me.
Sometimes, when I run Message.popup(String, int) in the code below, the text displays correctly, but sometimes the JDialog is empty, like if the component wasn't added at all.
public class Message extends JDialog {
private int width;
private int height;
private JLabel content;
public Message(String _content, int _margin) {
super();
this.content = new JLabel(_content);
content.setFont(new Font("Monospaced", Font.BOLD, 20));
this.margin = _margin;
this.width = content.getPreferredSize().width + _margin;
this.height = content.getPreferredSize().height + _margin;
createComponents();
setProperties();
}
public static void popup(String _content, int _time) {
if (SwingUtilities.isEventDispatchThread()) {
runPopup(_content, _time);
}
else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
runPopup(_content, _time);
}
});
}
}
private static void runPopup(String _content, int _time) {
final Message message = new Message(_content);
new Timer(_time, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
message.dispose();
}
}).start();
}
private void createComponents() {
setLayout(new BorderLayout());
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.add(content, BorderLayout.CENTER);
box.add(Box.createHorizontalGlue());
add(box);
}
private void setProperties() {
setSize(width, height);
setLocation(Coordinator.calculateCenteredWindowLocation(width, height));
setUndecorated(true);
setResizable(false);
setTitle(content.getText());
setVisible(true);
update(getGraphics());
}
}
Without the update(getGraphics());, the frame is always empty, but with it, it depends of what direction the wind is blowing... (go figure!)
A:
Are you sure your code is executing in the EDT ? indeed, if not (which is what I expect to be, since you sleep the current thread, what Swing would typically don't like), your frame will have trouble rendering.
To avoid those typical Swing threading issues, please take a look at the SwingUtilities class, which provide you methods to ensure you're running in EDT. Additionnaly, instead of directly sleeping your thread, you could repalce it with a Swing javax.swing.Timer (beware not to confuse it with the java.util.Timer).
A:
As mentioned by @Riduidel, it is important that anything Swing-related occur on the Event Dispatch Thread, or EDT. This is because Swing is not thread-safe. When invoking popup(), you ought to do the following
if(SwingUtilities.isEventDispatchThread()){
Message.popup(...);
}
else{
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
Message.popup(...);
}
});
}
This will ensure that the JFrame is created on the EDT. Also, from the code snippet you've posted, it would seem likely that Message should have a private constructor. In addition, since you're not doing any custom rendering, why not just make a JFrame member variable instead of extending the class? -- seems a bit superfluous to me.
Regardless, you should also never sleep in the EDT either, since this will make the GUI appear to "freeze" and blocks execution of other queued events. When performing long-running tasks, use either SwingWorker, or as @Riduidel mentioned, javax.swing.Timer. But if you prefer to use the java.util.Timer, use the SwingUtilities utility class as shown above to post the Runnable task on the EventQueue to be executed in the EDT.
EDIT
Here is what I'd do (and yes, it works)
public class Message {
// Private constructor to prevent external instantiation
private Message(){
}
public static void createAndShowDialog(final String content, final int time){
final JDialog dialog = new JDialog();
dialog.setLayout(new BorderLayout());
dialog.setUndecorated(true);
JLabel label = new JLabel(content);
label.setFont(new Font("Monospaced", Font.BOLD, 20));
Box b = Box.createHorizontalBox();
b.add(Box.createHorizontalGlue());
b.add(label, BorderLayout.CENTER);
b.add(Box.createHorizontalGlue());
dialog.add(b);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
// kick-off timer
Timer t = new Timer(time, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dialog.dispose();
}
});
t.setRepeats(false);
t.start();
}
}
And wherever you invoke createAndShowDialog(...), do the following
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
Message.createAndShowDialog("Content", 5000); // wait 5 seconds before disposing dialog
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Duda con timestamp
tengo una duda, no se como se utiliza el tipo de dato timestamp y no encuentro la manera de que con un input seleccionar la fecha y convertirlo en un timestamp para ingresarlo a la base de datos.
cualquier información me sirviria, muchas gracias
A:
Si lo que deseas es capturar una fecha de un input puedes hacer lo siguiente:
Ejemplo
-En el archivo HTML: "Recuerda cambiar el input a un tipo de dato date y recuerda el name asignado al input "
<input id="f_inicio" type="date" name="f_ini" class="form-control" placeholder="Cuando inicia...??" >
-En el archivo PHP: Por el metodo POST traemos el valor del input antes mencionado utilizando el name y lo asignamos a una variable.
$f_ini = $_POST["f_ini"];
-En el mismo codigo PHP reescribimos el valor con el tipo de dato date que se desee:
$f_inibd = date("d/m/Y", strtotime($f_ini));
Y esa ultima variable ("$f_inibd") es la que guardamos en la base de datos.
Comentarios: Luego de traer el valor de tipo date del input a php lo asignamos a una varible, y luego transformamos esa varible nuevamente para poder ordenar el formato en que queremos que ese tipo de dato se guarde en la base de datos, es por esa razon que reasignamos la varible.
Si desee saber los tipos de formato date que puede guardar verifique este link.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Date Range Validation making control turn into a datetime input type, just want text type
I have a Razor web page where I have a model
public class UploadModel
{
[Required]
[StringLength(25)]
public string PatientID { get; set; }
[DataType(DataType.Date)]
[DateRange("1000/12/01", "4010/12/16")]
public DateTime DrawDate { get; set; }
}
public class DateRangeAttribute : ValidationAttribute
{
private const string DateFormat = "yyyy/MM/dd";
private const string DefaultErrorMessage =
"'{0}' must be a date between {1:d} and {2:d}.";
public DateTime MinDate { get; set; }
public DateTime MaxDate { get; set; }
public DateRangeAttribute(string minDate, string maxDate)
: base(DefaultErrorMessage)
{
MinDate = ParseDate(minDate);
MaxDate = ParseDate(maxDate);
}
public override bool IsValid(object value)
{
if (value == null || !(value is DateTime))
{
return true;
}
DateTime dateValue = (DateTime)value;
return MinDate <= dateValue && dateValue <= MaxDate;
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture,
ErrorMessageString,
name, MinDate, MaxDate);
}
private static DateTime ParseDate(string dateValue)
{
return DateTime.ParseExact(dateValue, DateFormat,
CultureInfo.InvariantCulture);
}
}
That does validation for the datetime
However in the view,
when I run through all the elements in the model
@Html.EditorFor(m => m)
It is creating a datetime type which creates problems because I am using jquery to do the calendar date picking since it is cross broswer. Any way to force the datetime to become a text even with the validation class? Thanks!
A:
Since you are writing your custom validation, why don't you change
public DateTime DrawDate { get; set; }
to a string type and adjust your validation accordingly?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do omnivore mammals vary food preferences based on dietary needs?
I'm wandering if mammals that can eat many different kinds of food (omnivores) vary their preference for food not only based on the availability, but also based on dietary needs?
I'm looking at this site Food nutritional content and see that "not all foods are created equal" - the vitamin/mineral and amino acid contents can vary dramatically. Is there some part of an omnivore brain/digestive system that "monitors" the micronutrient density of digested food and adjusts food preferences towards foods that make the diet more complete?
A:
For what concerns amino acids, mice rapidly reject meals that are not balanced in essential amino acids and continue to look for other kind of foods. This behavior is called aversion response and it is an adaptive phenomena that can be observed already 20 minutes after exposure to the unbalanced food. The mechanism involves brain sensing of uncharged tRNAs. The significance of the aversion response is to minimize depletion of essential amino acids that can not be directly synthethized but are required for protein synthesis. You can find good reviews in PubMed, for instance Gietzen et al. 2007, Annual Review of Nutrition, and Gietzen and Aya 2012, Molecular Neurobiology.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to connect to server running on the system with password protection in java?
I am trying to use Runtime.exec to run a class file from my java code but not able to launch the new process on Linux,The same is working on the windows..
I want or launch the process from GUI (which I am running from a jar file named Launch.jar) on a button click.
So I used the following code.
String curpath=System.getProperty("user.dir");
Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "java -classpath"+curpath+File.separator+" Launch.jar LaunchNewProcess" });
A:
I think you need to leave a space after -classpath
Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c",
"java -classpath "+curpath+File.separator+" Launch.jar LaunchNewProcess" });
Update: try this:
Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c",
"java -jar "+curpath+File.separator+"Launch.jar" });
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to pass string to html page as code?
Is there anyway I can pass my html page a string variable and have it read it a code for a table?
Contents of string:
<tr> <td> temp/file.docx</td> <td> Safe</td> <td> 2018-06-18 14:58:14</td>
</tr><tr> <td> temp/doc.c</td> <td> Safe</td> <td> 2018-06-18 14:58:30</td>
</tr><tr> <td> temp/someCprogram.c</td> <td> Queued</td> <td> 2018-06-18 15:00:16</td> </tr>
I've tried passing the variable like so:
return render_template('analysis.html', table_=complete_table, version=__version__, escapse=False)
The html code for the table looks like this:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Path</th>
<th>Status</th>
<th>Time</th>
</tr>
</thead>
<tbody>
{{table_}}
</tbody>
</table>
I'm fairly new to html so any help is appreciated. (p.s. I'm also using flask app and python for the back-end)
A:
You need to use safe, so the templating engine knows to render the data passed as html:
<tbody>
{{table_|safe}}
</tbody>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Azure CLI 2: how to provide parameters in az group deployment create command?
I am using Azure CLI 2.0 on a windows machine and I am trying to create a Docker VM using this Microsoft documentation:
az group deployment create --resource-group myResourceGroup \
--parameters '{"newStorageAccountName": {"value": "mystorageaccount"},
"adminUsername": {"value": "azureuser"},
"adminPassword": {"value": "P@ssw0rd!"},
"dnsNameForPublicIP": {"value": "mypublicdns"}}' \
--template-uri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/docker-simple-on-ubuntu/azuredeploy.json
Putting everything in one line results in an "unrecognized arguments" error. Replacing the parameter single quotes by double quotes results in an "Expecting property name enclosed in double quotes" error and removing the parameters option gives an expected "Deployment template validation failed" error. What is the correct way to provide the parameter value?
A:
Please try this script:
az group deployment create --resource-group jason --parameters "{\"newStorageAccountName\": {\"value\": \"jasondisks321\"},\"adminUsername\": {\"value\": \"jason\"},\"adminPassword\": {\"value\": \"122130869@qq\"},\"dnsNameForPublicIP\": {\"value\": \"jasontest321\"}}" --template-uri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/docker-simple-on-ubuntu/azuredeploy.json
It works for me.
In cli 2.0, we can use --help to find the command help:
C:\windows\system32>az group deployment create --help
Examples
Create a deployment from a remote template file.
az group deployment create -g MyResourceGroup --template-uri
https://myresource/azuredeploy.json --parameters @myparameters.json
Create a deployment from a local template file and use parameter values in a string.
az group deployment create -g MyResourceGroup --template-file azuredeploy.json --parameters
"{\"location\": {\"value\": \"westus\"}}"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Stop listings going over page breaks
I am using Pandoc to generate Tex from Markdown. It automatically generates listings when it comes across the appropriate Markdown (code indented four spaces). It then uses the listings package to instantiate those listings in Tex. The resulting code is:
\begin{lstlisting}[language=bash]
# java -version
java version "1.7.0_09-icedtea"
OpenJDK Runtime Environment (rhel-2.3.3.el6_3.1-i386)
OpenJDK Client VM (build 23.2-b09, mixed mode)
\end{lstlisting}
Sometimes these code listings extend across a page break and I'd prefer if they were bumped to the next page if this happens. I've looked around and seen a few suggestions about adding a minipage to the listing but since my Tex is being auto-generated via Pandoc it's not clear how I can do that without manually editing the resulting Tex document to add the minipages before and after the lstlistings.
So I am looking for:
A way to bump the listings to the next page automatically, or
A way to tell LaTex to redefine the lstlisting to have minipages before and after it.
EDIT: I should have added for those unfamiliar with Pandoc that the template it uses to generate Tex is here.
Thanks!
A:
As pointed out by Werner the normal way to prevent listings to do any package breaks is the option float. However this can't be done globally without changing the internals of listing.
Another hack would be to surround the environment listings with a non breakable box. This can be achieved with the facilities of the package etoolbox and the provided commands \BeforeEnvironment and \AfterEnvironment:
\BeforeBeginEnvironment{listings}{\par\noindent\begin{minipage}{\linewidth}}
\AfterEndEnvironment{listings}{\end{minipage}\par\addvspace{\topskip}}
Of course instead of minipage you can use any other environment.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Shoud I close the Stream in WCF REST Service?
I have some WCF Rest Service with server side method and stream variable which is passed to it.
My question is: Should I close stream after saving file locally?
void ImportFile(Stream stream)
{
// Reading stream...
stream.Close(); // ??? is it really needed ???
}
A:
IT depends on the origin of the stream. If it is a stream you've created then Coder1409's answer is correct - you should wrap the stream creation statement in a using command. If however, since you specifically mention you are in a Rest Service, the stream is an HTTP request stream, it is a forward-only read-only stream and it's lifetime will be governed by the HTTP Context you got it from.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I deploy a Shiny app to Shiny Server?
I have created a Shiny app, which can run locally, however I would like to be able to share the apps with my collegues over the office.
I have set up a Shiny Server (free edition) on our local network, and as I go to the address, the sample app works fine. However, I have not found any information on how to deploy my app to the shiny server, only for shinyapps.io, which is not the thing I need.
Can you put me in the right direction? Do I need to copy my files via a file transfer app, or can I deploy from R directly?
A:
If you have Shiny Server up and running then all you should need to do is create a folder for your Shiny App in /srv/shiny-server/ on your Shiny Server and then copy your ui.R and server.R files into that folder.
Provided the necessary R package dependencies for your Shiny app are installed on the server then your Shiny app should be accessible via a browser (just use the sample app's URL and insert your folder name)
As far as I'm aware there is no way to deploy updates to your own local Shiny Server directly from R, but you should be able to achieve this with a source control/deployment toolchain e.g. Git and Gitlab
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I install xgboost for tox?
XGBoost needs to be compiled. For Docker, I install it like this:
RUN git clone --recursive https://github.com/dmlc/xgboost.git
WORKDIR xgboost
RUN ./build.sh && pip3 install -e python-package
How can I make sure it is available for tox?
A:
Option sitepackages=True makes tox create virtual envs that have access to globally installed packages. It's an option of virtual env section or global [testenv] section. Also can be set with --sitepackages command line option. Example:
[tox]
minversion = 1.8
envlist = py{27,34,35,36}
# Base test environment settings
[testenv]
basepython =
py27: {env:TOXPYTHON:python2.7}
py34: {env:TOXPYTHON:python3.4}
py35: {env:TOXPYTHON:python3.5}
py36: {env:TOXPYTHON:python3.6}
sitepackages=True
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why isn't /usr/local/bin/ checked in check_flexlm.pl ? Source included
Eventhough I have /usr/local/bin/lmstat the below script always fails with Cannot find "lmstat".
Can anyone see why that is the case?
use strict;
use Getopt::Long;
use vars qw($opt_V $opt_h $opt_F $opt_t $verbose $PROGNAME);
use FindBin;
use lib "$FindBin::Bin";
use lib '/usr/lib64/nagios/plugins';
use utils qw(%ERRORS &print_revision &support &usage);
$PROGNAME="check_flexlm";
sub print_help ();
sub print_usage ();
$ENV{'PATH'}='/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin';
$ENV{'BASH_ENV'}='';
$ENV{'ENV'}='';
Getopt::Long::Configure('bundling');
GetOptions
("V" => \$opt_V, "version" => \$opt_V,
"h" => \$opt_h, "help" => \$opt_h,
"v" => \$verbose, "verbose" => \$verbose,
"F=s" => \$opt_F, "filename=s" => \$opt_F,
"t=i" => \$opt_t, "timeout=i" => \$opt_t);
if ($opt_V) {
print_revision($PROGNAME,'2.2.1');
exit $ERRORS{'OK'};
}
unless (defined $opt_t) {
$opt_t = $utils::TIMEOUT ; # default timeout
}
if ($opt_h) {print_help(); exit $ERRORS{'OK'};}
unless (defined $opt_F) {
$opt_F = $ENV{'LM_LICENSE_FILE'};
unless (defined $opt_F) {
print "Missing license.dat file\n";
print_usage();
exit $ERRORS{'UNKNOWN'};
}
}
# Just in case of problems, let's not hang Nagios
$SIG{'ALRM'} = sub {
print "Timeout: No Answer from Client\n";
exit $ERRORS{'UNKNOWN'};
};
alarm($opt_t);
my $lmstat = $utils::PATH_TO_LMSTAT ;
unless (-x $lmstat ) {
print "Cannot find \"lmstat\"\n";
exit $ERRORS{'UNKNOWN'};
}
A:
Never assume you know what something is. Try printing the path to verify it is what you think it is:
unless (-x $utils::PATH_TO_LMSTAT ) {
print qq/Cannot find "lmstat" at <$utils::PATH_TO_LMSTAT>\n/;
exit $ERRORS{'UNKNOWN'};
}
If $utils::PATH_TO_LMSTAT is a relative path (such as lmstat by itself) the -x is looking in the current directory. If it's a full path, maybe you have the string wrong.
Note that your options handling can be a bit less unwieldy since you can specify multiple names for options in the same key:
GetOptions(
"V|version" => \$opt_V,
"h|help" => \$opt_h,
"v|verbose" => \$verbose,
"F|filename=s" => \$opt_F,
"t|timeout=i" => \$opt_t,
);
The "Secure Programming Techniques" chapter of Mastering Perl discusses many of the headaches of programs that call external programs.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Existential and Universal quantifiers in DBMS
I understand what they are and I have seen examples regarding these. One such example is
{t.Fname,t.Lname|Employee(t) AND (∃d)(Department(d) AND d.Dname='Research' AND d.Dnumber=t.Dno)}
Now what is the difference between above and this
{t.Fname,t.Lname|Employee(t) AND Department(d) AND d.Dname='Research' AND d.Dnumber=t.Dno}
And how is
(∀x) (P(x)) ≡ NOT (∃x) (NOT (P(x)))
Can someone please explain ?
A:
For every x P(x) means that all x satisfy P, which means that there doesn't exist an x which doesn't satisfy P, hence
(∀x) (P(x)) ≡ NOT (∃x) (NOT (P(x)))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
are particles "knots" or "kinks" of excitation in a field?
this is my mental picture for how they travel without a medium, how (like water waves) some can't stay still, why they have wave and particle properties, energy/mass equivalence, conservation, etc. it might capture uncertainty too -- i've heard that all waves have an uncertainty relation (say in their power spectrum), but i don't get why -- it seems like we can discuss waves with absolute precision.
A:
particles are ordinary quanta of the corresponding quantum fields - without any knots or other topologically nontrivial features. (You have to get used to the wave-particle duality, probabilities, and the uncertainty principle - they're fundamental features of the world around us.)
However, this is only true for "weakly coupled particles" that are directly described by a Lagrangian composed of "free fields" plus "weak interactions". On the other hand, there can be many other objects that are not just quanta of waves but they have "knots" on them.
We say that they are topological defects. Most typically, one can take the original fields and write down a classical solution of the equations of motion that is topologically nontrivial. The resulting configuration of fields has to exist in the quantum theory, too. It is preserved by the nontrivial topology.
In 1 spatial dimension, a topologically nontrivial configuration is one that drives a scalar field from 1 local minimum of the potential to another, as you move from the left to the right; it is known as the "kink".
In 2 spatial dimensions, there are solutions known as "vortices" (or one "vortex") in which the circular round trip around the center of the solution sees a field to go around a noncontractible curve in the configuration space.
In 3 spatial dimensions, we similarly find magnetic "monopoles" which are also some kinds of "knots" on the fields. More generally, the topological defects that correspond to real objects are known as "solitons". This is contrasted with the "instantons" which are objects localized in the Euclidean spacetime; they don't describe static objects but rather special histories that contribute to various probability amplitudes for processes that appear at one "instant" of time.
Another class of topologically nontrivial configurations are skyrmions, and if you want to see a representative that is really close to your "knots", see a paper about knitted fivebranes in M-theory:
http://arxiv.org/abs/hep-th/9803108
In the quantum theory, objects such as solitons - especially monopoles - may behave indistinguishably from the original quanta. There is sometimes a full symmetry between them - the most famous example is the S-duality of gauge theories in 4 dimensions. Electrically charged particles such as gauginos are exchanged with the magnetic monopoles - solitons - as the coupling $g$ is changed to $1/g$.
All these things, when done properly, still satisfy all the postulates of quantum mechanics such as the nonzero commutators between observables (uncertainty principle). In string theory, topological defects include objects such as D-branes, NS5-branes, and in extra-dimensional theories in general, one also has special "knitted" configurations of the metric such as the Kaluza-Klein monopoles (magnetic monopoles extended in extra dimensions).
Best wishes
Lubos
A:
Actually that's not too far off the mark, although I'm not sure "knot" or "kink" is the best word. Quantum field theory, the best theory we currently have to describe particles, says that particles correspond to excitations of a field, which are kind of like waves in water; you could consider the surface of a pond "excited" whenever it's not flat. Just as with water waves, there's an infinite variety of "shapes" you can have for these excitations. For example, you could have a repeating wave, in which the surface of the water cycles up and down over a large area, or you could have just one wave front that just propagates across the water without spreading out very much. The former case is pretty typical for things like light waves, and the latter case is pretty typical for particles of matter, although technically any kind of field (whether it's the electromagnetic field for light, or a quark field in matter, or whatever) can have any of the different types of excitations.
By the way, according to special (and general) relativity, even an object that is standing still is moving through time. So all of these excitations move through spacetime in one way or another. But only certain ones (the excitations in fields corresponding to massless particles) can move through space in such a way that they appear to us to be traveling at the speed of light.
A:
The short answer is no. Particles obey a very important property called "cluster decomposition principle", while those type of lumps that you mentioned do not.
What that means is that if you have a particle as an excitation of a theory, you might perfectly well have a two particle state as a solution when their separation goes to infinity. This is a essential ingredient to calculate S matrices and cross sections (that's almost everything that is useful in particle collision experiments). This is not true, in general, for these extended solutions.
Further details can be found in that excellent book Aspects of Symmetry, by Coleman. Check section 6.2.3: Lumps are like particles (almost).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ui-router issue, cant load child view from tab
Im trying to get a single nested view to load within a tab and it seems that anything I try it will not load the template. Im trying to pass a param from my main tab view to load a child view and display it. The page never loads but i see that the url has changed with my selected value from the list. I have followed the example from ionic tabs starter exactly, but this darn thing will not show the child page.
Here is my app.js with the appropriate code minus everything else.
// setup an abstract state for the tabs directive
.state('options', {
url: "/options",
abstract: true,
templateUrl: "templates/options-tabs.html"
})
// Each tab has its own nav history stack:
.state('options.create', {
url: '/create',
views: {
'options-create': {
templateUrl: 'templates/options-create.html',
controller: 'CreateCtrl'
}
}
})
.state('options.confirm', {
url: '/confirm/:id',
views: {
'options-confirm': {
templateUrl: 'templates/options-confirm.html',
controller: 'ConfirmCtrl'
}
}
})
.state('options.local', {
url: '/local',
views: {
'options-local': {
templateUrl: 'templates/options-local.html',
controller: 'LocalAuditCtrl'
}
}
})
My Controller
.controller('CreateCtrl', function($scope,$location,$state,rest) {
rest.getBases().success(function(data){
$scope.bases = data;
});
$scope.test = function(account){
console.log(account);
$state.go('options.confirm', {id:account});
}
})
My Main Tab View
<ion-view title="Create">
<ion-content>
<ion-list>
<ion-item ng-repeat="base in bases" type="item-text-wrap" ng-click="test(base.account)">
{{base.name}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>
Details View
<ion-view title="{{id}}">
<ion-content has-header="true" padding="true">
</ion-content>
</ion-view>
At this point Im completely confused on how this can be wrong following the example from Ionic but Im sure there is something Im missing =( Any help would be awesome!
A:
I had this problem and after 3 hours of debugging I found out that your top state (the abstract one) must be <ion-nav-view/>.
Ionic's doc doesn't mention it at all!
Try to include this in the index.html file.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Array with different row lengths
I have to output a Julian Calendar in java. I printed out each month, however I am unsure how to fix the row lengths to correspond to each month. For example, February, April, June, September and November do not have 31 days. This is my code so far:
import java.text.DateFormatSymbols;
public class testing {
public void Day() {
System.out.println();
for (int i = 1; i <= 31; i++) {
System.out.println(String.format("%2s", i));
}
}
public void MonthNames() {
String[] months = new DateFormatSymbols().getShortMonths();
for (int i = 0; i < months.length; i++) {
String month = months[i];
System.out.printf(month + " ");
//System.out.printf("\t");
}
}
public void ColRow() {
int dayNum365 = 1;
int array [][] = new int[31][12];
System.out.println();
for (int col = 0; col < 12; col++) {
for (int row = 0; row < 31; row++) {
array[row][col] += (dayNum365);
dayNum365++;
}
}
for (int col = 0; col < array.length; col++) {
for (int row = 0; row < array[col].length; row++) {
System.out.printf("%03d", array[col][row]);
System.out.print(" ");
}
System.out.println();
}
}
public static void main(String[] args) {
testing calendar = new testing();
calendar.MonthNames();
calendar.ColRow();
}
}
A:
We can create a matrix with a different number of columns for each row (called a jagged matrix) like this:
int[][] months = new int[12][];
months[0] = new int[31]; // January
months[1] = new int[28]; // February, assuming a non-leap year
months[2] = new int[31]; // March
// and so on...
Now, whenever we need to iterate over it, remember to take into account that each row will have a different length:
int dayNum365 = 1;
for (int month = 0; month < months.length; month++) {
for (int day = 0; day < months[month].length; day++) {
months[month][day] = dayNum365;
dayNum365++;
}
}
All of the above works because a 2D-matrix is nothing but an array of arrays, bear that in mind when working with matrices in Java.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
display data in promise call with vuejs and fetch()
I'm littlebit confused about the fetch function, this is my code:
<template>
<!-- above the fold -->
<section class="uk-section uk-section-primary">
<div class="uk-container">
{{ items }}
</div>
</section>
<!-- end above the fold -->
</template>
<script>
// @ is an alias to /src
export default {
name: 'Home',
data() {
return {
items: {}
}
},
mounted() {
this.getInfo()
},
methods: {
getInfo() {
fetch('mydomain.net/cockpit/api/singletons/get/frontpage' , {
headers: { 'Authorization': 'Bearer xxmySecretxx' }
})
.then(res => this.items = res.json())
.then(res => console.log(res));
}
},
}
</script>
In console.log I can view the items value, but on the browser the result is [object Promise] how fetch() works?
A:
res.json() is an async function as fetch; this is why you add the second "then". if you edit the code like below, you will get what you need:
getInfo() {
fetch('mydomain.net/cockpit/api/singletons/get/frontpage' , {
headers: { 'Authorization': 'Bearer xxmySecretxx' }
})
.then(res => res.json())
.then(res => this.items = res);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find out which shell PHP is using
I'm trying to execute a piped shell commands like this
set -o pipefail && command1 | command2 | command3
from a PHP script. The set -o pipefail part is to make the pipe break as soon as any of the commands fails. But the commands results in this:
sh: 1: set: Illegal option -o pipefail
whereas it runs fine from the terminal. Maybe explicitly specifying which shell PHP CLI should use (i.e. bin/bash) when executing shell commands could solve the problem or is there better way out?
A:
You can always run bash -c 'set -o pipefail && command1 | command2 | command3' instead.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is part of my image underexposed when using flash with shutter speed faster than sync speed?
Hardware
Neewer TT560 SpeedLite
Cannon T6i
Shutter Speed
1/200 shows full photo
1/400 shows 90% photo
1/640 shows 50% photo
1/1000 shows 10% photo
From what I can tell, the shutter is faster than the flash. I tried modifying the external flash settings but I get this message:
Flash Control > External flash func. setting
This menu cannot be displayed. Incompatible flash or flash's power is turned off.
Question
How can I get the shutter to time better with the flash if I'm not able to modify the settings? I've tried modifying the settings when the flash is powered on and attached to the hotshoe as well as when it's not attached.
A:
The subject of your question is flash synchronization. A little background information will help you understand.
Your camera sports a “focal plane” shutter design. This mechanism uses a curtain, not unlike a window shade to cover the entire image sensor chip. Thus its normal state is closed and since it is opaque, it prevents light from the lens from playing on the surface of the image sensor.
When you press the “go” button, the shutter curtain begins its journey. It travels the span of the image area. Now the curtain contains a slit. This slit uncovers a portion of the imaging sensor. That portion is the actual width of the slit. When the shutter is set high, say 1/1000 of a second, the silt width is tiny. The image sensor only sees light from the lens through this slit. The slit travels the entire distance exposing all entire image area but the travel time is longer than 1/1000 of a second. The shutter speed is the time it takes for the slit to travel just its width.
As you change shutter speeds, you are actually changing the slit width. Each time you slow down the shutter you are actually enlarging the slit width. On your camera at 1/200 of a second the slit width is just wide enough to expose the entire image area to the light from the lens.
When using an electronic flash, the duration of the flash is super quick. If your shutter is set faster than 1/200 of a second, the blitz of the flash catches an image of slit. Sorry to report that if you choose a shutter speed greater than 1/200, the result will be partially uncovered image area.
By the way, we call the setting you need “X” synchronization. In the early days of flash bulb photography, a voltage was applied to the flash bulb in advance of the opening of the shutter. This setting was called “M” synchronization. The “M” is for medium delay which was 20 milliseconds in advance of the shutter reaching full opening. Since electronic flash requires no delay, this zero delay was labeled “X”. Check your camera manual, you will find that your camera works with electronic flash at the “X” synchronization setting of 1/200 of a second shutter speed or slower. These slower shutter speeds provide a slit width that uncovers the entire image area.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting list of URL's and the Data from the Page as well as Pagination by BeautifulSoup
I am new to use Beautifulsoup. Actually, I want to get all the links from the page but only which came as result. Here is the example link: Daad1
Moreover, there are pages and i want to do get all the links also from all the other pages.
So far i am doing this to get the URL's but its also genearting output with extra text:
import requests
from bs4 import BeautifulSoup
getpage= requests.get(url)
getpage_soup= BeautifulSoup(getpage.text, 'html.parser')
url =https://www2.daad.de/deutschland/studienangebote/international-programmes/en/result/?q=°ree%5B%5D=1&fos=&cert=&admReq=&scholarshipLC=&scholarshipSC=&langDeAvailable=&langEnAvailable=&lang%5B%5D=2&cit%5B%5D=&tyi%5B%5D=&ins%5B%5D=&fee=&bgn%5B%5D=&dur%5B%5D=&sort=4&subjects%5B%5D=&limit=10&offset=&display=list&lvlEn%5B%5D=
all_links= getpage_soup.findAll('a')
for link in all_links:
link = link.get('href')
print (link)
Desired Output:
I would like a list of all the URLS ONLY from the search result as well as list of URLs from all the pages in pagination. The help will be appreicated :) I tried to find solution but didnt able to find.
A:
If you go to Network Tab under XHR you will get the following link which returns data in json format.
url="https://www2.daad.de/deutschland/studienangebote/international-programmes/api/solr/en/search.json?cert=&admReq=&scholarshipLC=&scholarshipSC=°ree%5B%5D=1&fos=&langDeAvailable=&langEnAvailable=&lang%5B%5D=2&fee=&sort=4&q=&limit=10&offset={}&display=list&isSep="
Code:
import requests
url="https://www2.daad.de/deutschland/studienangebote/international-programmes/api/solr/en/search.json?cert=&admReq=&scholarshipLC=&scholarshipSC=°ree%5B%5D=1&fos=&langDeAvailable=&langEnAvailable=&lang%5B%5D=2&fee=&sort=4&q=&limit=10&offset={}&display=list&isSep="
listofanchor=[]
pagenum=0
while pagenum<130:
finalUrl=url.format(pagenum)
print(finalUrl)
res=requests.get(finalUrl).json()
for item in res['courses']:
listofanchor.append(item['link'])
pagenum=pagenum+10
print(listofanchor)
Output:
['/deutschland/studienangebote/international-programmes/en/detail/6217/', '/deutschland/studienangebote/international-programmes/en/detail/5443/', '/deutschland/studienangebote/international-programmes/en/detail/4229/', '/deutschland/studienangebote/international-programmes/en/detail/3779/', '/deutschland/studienangebote/international-programmes/en/detail/4725/', '/deutschland/studienangebote/international-programmes/en/detail/6219/', '/deutschland/studienangebote/international-programmes/en/detail/4335/', '/deutschland/studienangebote/international-programmes/en/detail/6120/', '/deutschland/studienangebote/international-programmes/en/detail/5660/', '/deutschland/studienangebote/international-programmes/en/detail/4538/', '/deutschland/studienangebote/international-programmes/en/detail/5460/', '/deutschland/studienangebote/international-programmes/en/detail/5461/', '/deutschland/studienangebote/international-programmes/en/detail/3887/', '/deutschland/studienangebote/international-programmes/en/detail/4557/', '/deutschland/studienangebote/international-programmes/en/detail/4537/', '/deutschland/studienangebote/international-programmes/en/detail/4535/', '/deutschland/studienangebote/international-programmes/en/detail/4546/', '/deutschland/studienangebote/international-programmes/en/detail/4539/', '/deutschland/studienangebote/international-programmes/en/detail/6403/', '/deutschland/studienangebote/international-programmes/en/detail/4540/', '/deutschland/studienangebote/international-programmes/en/detail/4080/', '/deutschland/studienangebote/international-programmes/en/detail/3603/', '/deutschland/studienangebote/international-programmes/en/detail/4099/', '/deutschland/studienangebote/international-programmes/en/detail/5704/', '/deutschland/studienangebote/international-programmes/en/detail/4718/', '/deutschland/studienangebote/international-programmes/en/detail/3906/', '/deutschland/studienangebote/international-programmes/en/detail/4509/', '/deutschland/studienangebote/international-programmes/en/detail/5617/', '/deutschland/studienangebote/international-programmes/en/detail/4128/', '/deutschland/studienangebote/international-programmes/en/detail/3593/', '/deutschland/studienangebote/international-programmes/en/detail/4631/', '/deutschland/studienangebote/international-programmes/en/detail/3675/', '/deutschland/studienangebote/international-programmes/en/detail/4048/', '/deutschland/studienangebote/international-programmes/en/detail/4612/', '/deutschland/studienangebote/international-programmes/en/detail/3592/', '/deutschland/studienangebote/international-programmes/en/detail/3659/', '/deutschland/studienangebote/international-programmes/en/detail/4380/', '/deutschland/studienangebote/international-programmes/en/detail/3660/', '/deutschland/studienangebote/international-programmes/en/detail/3663/', '/deutschland/studienangebote/international-programmes/en/detail/3616/', '/deutschland/studienangebote/international-programmes/en/detail/3664/', '/deutschland/studienangebote/international-programmes/en/detail/3898/', '/deutschland/studienangebote/international-programmes/en/detail/5259/', '/deutschland/studienangebote/international-programmes/en/detail/3661/', '/deutschland/studienangebote/international-programmes/en/detail/3662/', '/deutschland/studienangebote/international-programmes/en/detail/4303/', '/deutschland/studienangebote/international-programmes/en/detail/4497/', '/deutschland/studienangebote/international-programmes/en/detail/4392/', '/deutschland/studienangebote/international-programmes/en/detail/4472/', '/deutschland/studienangebote/international-programmes/en/detail/4471/', '/deutschland/studienangebote/international-programmes/en/detail/4772/', '/deutschland/studienangebote/international-programmes/en/detail/6155/', '/deutschland/studienangebote/international-programmes/en/detail/4320/', '/deutschland/studienangebote/international-programmes/en/detail/4218/', '/deutschland/studienangebote/international-programmes/en/detail/4630/', '/deutschland/studienangebote/international-programmes/en/detail/4022/', '/deutschland/studienangebote/international-programmes/en/detail/3918/', '/deutschland/studienangebote/international-programmes/en/detail/3895/', '/deutschland/studienangebote/international-programmes/en/detail/3744/', '/deutschland/studienangebote/international-programmes/en/detail/4833/', '/deutschland/studienangebote/international-programmes/en/detail/6424/', '/deutschland/studienangebote/international-programmes/en/detail/6355/', '/deutschland/studienangebote/international-programmes/en/detail/4319/', '/deutschland/studienangebote/international-programmes/en/detail/4669/', '/deutschland/studienangebote/international-programmes/en/detail/6218/', '/deutschland/studienangebote/international-programmes/en/detail/6366/', '/deutschland/studienangebote/international-programmes/en/detail/4561/', '/deutschland/studienangebote/international-programmes/en/detail/6336/', '/deutschland/studienangebote/international-programmes/en/detail/4227/', '/deutschland/studienangebote/international-programmes/en/detail/3618/', '/deutschland/studienangebote/international-programmes/en/detail/3617/', '/deutschland/studienangebote/international-programmes/en/detail/4876/', '/deutschland/studienangebote/international-programmes/en/detail/5650/', '/deutschland/studienangebote/international-programmes/en/detail/4223/', '/deutschland/studienangebote/international-programmes/en/detail/4026/', '/deutschland/studienangebote/international-programmes/en/detail/6195/', '/deutschland/studienangebote/international-programmes/en/detail/4375/', '/deutschland/studienangebote/international-programmes/en/detail/4849/', '/deutschland/studienangebote/international-programmes/en/detail/5430/', '/deutschland/studienangebote/international-programmes/en/detail/4822/', '/deutschland/studienangebote/international-programmes/en/detail/4668/', '/deutschland/studienangebote/international-programmes/en/detail/4228/', '/deutschland/studienangebote/international-programmes/en/detail/4221/', '/deutschland/studienangebote/international-programmes/en/detail/4501/', '/deutschland/studienangebote/international-programmes/en/detail/4755/', '/deutschland/studienangebote/international-programmes/en/detail/5651/', '/deutschland/studienangebote/international-programmes/en/detail/4331/', '/deutschland/studienangebote/international-programmes/en/detail/4369/', '/deutschland/studienangebote/international-programmes/en/detail/6358/', '/deutschland/studienangebote/international-programmes/en/detail/3871/', '/deutschland/studienangebote/international-programmes/en/detail/5225/', '/deutschland/studienangebote/international-programmes/en/detail/4610/', '/deutschland/studienangebote/international-programmes/en/detail/3838/', '/deutschland/studienangebote/international-programmes/en/detail/4211/', '/deutschland/studienangebote/international-programmes/en/detail/3811/', '/deutschland/studienangebote/international-programmes/en/detail/4210/', '/deutschland/studienangebote/international-programmes/en/detail/6487/', '/deutschland/studienangebote/international-programmes/en/detail/3831/', '/deutschland/studienangebote/international-programmes/en/detail/5692/', '/deutschland/studienangebote/international-programmes/en/detail/5693/', '/deutschland/studienangebote/international-programmes/en/detail/5694/', '/deutschland/studienangebote/international-programmes/en/detail/5695/', '/deutschland/studienangebote/international-programmes/en/detail/5696/', '/deutschland/studienangebote/international-programmes/en/detail/5697/', '/deutschland/studienangebote/international-programmes/en/detail/5463/', '/deutschland/studienangebote/international-programmes/en/detail/4414/', '/deutschland/studienangebote/international-programmes/en/detail/3619/', '/deutschland/studienangebote/international-programmes/en/detail/3832/', '/deutschland/studienangebote/international-programmes/en/detail/6453/', '/deutschland/studienangebote/international-programmes/en/detail/3917/', '/deutschland/studienangebote/international-programmes/en/detail/4629/', '/deutschland/studienangebote/international-programmes/en/detail/4216/', '/deutschland/studienangebote/international-programmes/en/detail/4217/', '/deutschland/studienangebote/international-programmes/en/detail/4409/', '/deutschland/studienangebote/international-programmes/en/detail/4368/', '/deutschland/studienangebote/international-programmes/en/detail/6315/', '/deutschland/studienangebote/international-programmes/en/detail/4219/', '/deutschland/studienangebote/international-programmes/en/detail/4220/', '/deutschland/studienangebote/international-programmes/en/detail/4222/', '/deutschland/studienangebote/international-programmes/en/detail/6216/', '/deutschland/studienangebote/international-programmes/en/detail/5645/', '/deutschland/studienangebote/international-programmes/en/detail/6220/', '/deutschland/studienangebote/international-programmes/en/detail/6156/', '/deutschland/studienangebote/international-programmes/en/detail/4321/', '/deutschland/studienangebote/international-programmes/en/detail/6308/', '/deutschland/studienangebote/international-programmes/en/detail/6425/', '/deutschland/studienangebote/international-programmes/en/detail/4212/', '/deutschland/studienangebote/international-programmes/en/detail/4705/', '/deutschland/studienangebote/international-programmes/en/detail/4309/']
snapshot Network-Tab
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create empty csv file in R
I have an R script that runs a set of functions on multiple datasets and creates a set of concentration-response models. What I would like to do is save out the model parameters and other results to a csv file.
My plan is to have the script create an empty csv file and then as the script progresses, results are appended to that csv file. Every time the script is run I would like the results to be overwritten.
I've tried to create an empty file using
system("copy /y NUL results.csv > NUL")
to create the file, but the file is not created. This command (i.e., copy/y NUL results.csv > NUL) works properly when run directly in the Windows terminal.
Am I missing something simple? System is Windows XP.
Thanks all!
A:
Is there anything wrong with file.create(), which is portable across operating systems?
file.create("my.csv")
# [1] TRUE
You can then append to the file, e.g. using the append=TRUE argument to write.table(), perhaps like this:
df <- data.frame(a=1:4, b=4:1)
write.table(df, file="my.csv", sep=",", row.names=FALSE, append=TRUE)
write.table(df, file="my.csv", sep=",", row.names=FALSE,
col.names=FALSE, append=TRUE)
EDIT If you will be doing a ton of writes to each file, it can save considerable time to open a connection to the file once, and only close it when you're done. If that is not the case, the approach above works just fine.
A:
Because it is shell command you should use shell instead of system.
shell("copy /y NUL results.csv > NUL")
EDIT. More portable solution:
cat(NULL,file="results.csv")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
The date of yesterday in flutter
How can I calculate yesterdays date in dart/flutter?
I have the date of today:
DateTime.now()
But I can't just do -1.
A:
DateTime.now().subtract(Duration(days:1))
More info at https://api.flutter.dev/flutter/dart-core/DateTime-class.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
E_WC_14: Accept.js encryption failed?
I have a payment form as follows
<body>
<g:if test="${flash.message}">
<div class="message">${flash.message}</div>
</g:if>
<div class="content">
<h1>Secure Checkout</h1>
<g:form name="paymentForm"
method="POST"
action="processAcceptPayment" >
<input type="text" name="cardNumber" id="cardNumber" placeholder="cardNumber"/> <br><br>
<input type="text" name="expMonth" id="expMonth" placeholder="expMonth"/> <br><br>
<input type="text" name="expYear" id="expYear" placeholder="expYear"/> <br><br>
<input type="text" name="cardCode" id="cardCode" placeholder="cardCode"/> <br><br>
<input type="hidden" name="dataValue" id="dataValue" />
<input type="hidden" name="dataDescriptor" id="dataDescriptor" />
<button type="button" onclick="sendPaymentDataToAnet()">Pay</button>
</g:form>
</div>
<g:javascript>
function sendPaymentDataToAnet() {
var authData = {};
authData.clientKey = "valid key";
authData.apiLoginID = "valid id";
var cardData = {};
cardData.cardNumber = document.getElementById("cardNumber").value;
cardData.month = document.getElementById("expMonth").value;
cardData.year = document.getElementById("expYear").value;
cardData.cardCode = document.getElementById("cardCode").value;
var secureData = {};
secureData.authData = authData;
secureData.cardData = cardData;
// If using banking information instead of card information,
// send the bankData object instead of the cardData object.
//
// secureData.bankData = bankData;
Accept.dispatchData(secureData, responseHandler);
}
function responseHandler(response) {
if (response.messages.resultCode === "Error") {
var i = 0;
while (i < response.messages.message.length) {
console.log(
response.messages.message[i].code + ": " +
response.messages.message[i].text
);
i = i + 1;
}
} else {
paymentFormUpdate(response.opaqueData);
}
}
function paymentFormUpdate(opaqueData) {
document.getElementById("dataDescriptor").value = opaqueData.dataDescriptor;
document.getElementById("dataValue").value = opaqueData.dataValue;
document.getElementById("cardNumber").value = "";
document.getElementById("expMonth").value = "";
document.getElementById("expYear").value = "";
document.getElementById("cardCode").value = "";
document.getElementById("accountNumber").value = "";
document.getElementById("routingNumber").value = "";
document.getElementById("nameOnAccount").value = "";
document.getElementById("accountType").value = "";
document.getElementById("paymentForm").submit();
}
</g:javascript>
</body>
This generates the form as follows
I enter test credit card numbers and click Pay.
I get the following error in my javascript console.
I was just following the accept.js tutorial from the official page.
https://developer.authorize.net/api/reference/features/acceptjs.html
I appreciate any help as to the reason for this "Encryption Failed" error? Thanks!
UPDATE:
Ok so i did some more debugging. I put a test code "console.log("test");" inside responseHandler() function and noticed that it was called twice. I am now wondering why is responseHandler() being called twice.
A:
When Accept.js triggers the callback function twice due to some other Javascript error occurring on the page, you can pretty quickly track down the source of that error on the by wrapping the contents of your callback function in a try/catch block:
Accept.dispatchData(secureData, responseHandler);
...
function responseHandler(response) {
try {
if (response.messages.resultCode === "Error") {
var i = 0;
while (i < response.messages.message.length) {
console.log(
response.messages.message[i].code + ": " +
response.messages.message[i].text
);
i = i + 1;
}
}
} catch (error) {
console.log(error);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why was Spanish Fascist dictatorship left in power after World War II?
Throughout the Second World War, many people in Spain were under the hope that the victory of the Allies would trigger an invasion of Spain to defeat the dictatorship of Franco, a fascist who won the Civil War in 1939 thanks to the help of Mussolini's Italy and Hitler's Germany.
It is a known fact that Britain bribed Spain to stay out of Second World War. There are other reasons that are very well detailed in Why were Spain and Portugal neutral / not invaded in WWII?.
Despite all of this, there were quite a lot of volunteers, even many sent to Russia by the government itself (the División Azul to Russia).
Throughout the war, Spain's government moved from supporting the Axis Powers to calling themselves neutral. As it was fearing the defeat of the Axis Powers, things changed:
by 1942-1943, executions of former Republicans decreased
when Mussolini was captured in july 1943, Franco moved his position towards neutrality.
general Franco was pressured to stop selling tungsten to Germany (references in this page from Wikipedia in Spanish)
By February 1945, the Yalta Conference got an agreement that would be important to Spain:
The Big Three further agreed that democracies would be established, all liberated European and former Axis satellite countries would hold free elections and that order would be restored
However, the only thing that really happened was a gathering of volunteers for a guerrilla-like invasion:
Following the Spanish Civil War, many supporters of the former Republican government decided to start a movement to overthrow Franco; these members were called the Spanish Maquis. Several guerrilla raids occurred during the timeline of World War II, with most of them happening in 1944. One major confrontation happened in the Vale de Arán valley where a large group of rebels attacked and briefly occupied the north-western border of the Pyrenees. The government of France along with the Soviet Union organised, trained and armed a large group of Spaniards earlier liberated from the concentration camps where Spanish republicans had been held by the Front Populaire since they crossed the Spanish-French border at the end of the Spanish civil war in 1939. The battle lasted four days. The better trained and motivated Spanish Army under the command of the experienced General Moscardó immediately maneuvered to control the main strategic points of the valley and engaged the invaders, pushing them back across the border. The communists had underestimated popular support for the Francoist Regime, and no revolution began as they supposed.
Source: Spain during World War II
All in all, Spain got isolated, many war criminals got shelter in the country and the dictatorship managed to survive many years, until the death of Franco in 1975. This happened to the surprise of Republicans, who had already faced the coldness during the Civil War, when they suffered from the Non-intervention of the democracies.
Then, it was only by mid 1950s when Spain was on the focus again, when required to host some UNO's headquarters during the Cold War.
Why was this? What caused this coldness towards Spain despite being a Fascist regime? Were there any plans to force the fall of the regime?
A:
WW II was primarily a power struggle, and to a lesser degree an ideological struggle.
This means that your assumption about the motivations of WW II are incorrect. If it had been an ideological struggle, the US would not have allied with the Communist Soviet Union. (Read up on the Red Scare in the US: anti-Communist sentiment in the US was significant).
The Spanish government posed no threat to its neighbors
The other point is that even if Fascist, Spain wasn't expansionist Fascist, unlike the German and Italian Fascist governments during WW II. (Italy's conquest of Ethiopia preceded WW II). Spain was not the only Fascist / Autocratic regime that was not invaded after World War II. All you have to do is take a look at the various South and Central American republics that were also run by Fascists at the time. They weren't invaded either.
Wars Are Costly and Need to be Worth the Effort
Given how exhausted all sides were at the end of WW II, and given the major tension of the post-war world being Central Europe (and soon after that in Asia) the Iberian peninsula was not a high enough strategic priority to the World Powers to risk invading and continuing the war since Spain posed no threat to anyone. Even among the victors, the populations were war weary. (The lackluster support for the Korean War in the US in the early 50's is ample evidence that war weariness has political impact. TR Fehrenbach's book at the link is one of the best treatments of that war that I have read).
From the Western Perspective, Spain not being in the Communist camp meant that they could live with that imperfection and work via other means. War isn't the only way of dealing with nations whose government you don't care for.
The purpose of the Allied effort against Germany wasn't primarily "get rid of Fascism." (Though plenty of political rhetoric during and after was used as justification to keep the war effort going). The war was a power struggle. Fascism was the chosen government of Italy and Nazi Germany, whose aims were expansionist. The core problem was that Germany was a Major Power, and expansionist, while Italy was a lesser Power and expansionist. The third member of the Axis, Japan, was not Fascist (although there was an influence of militarism in their governmental structure leading up to the war, Fascism was not the Japanese political ideology). Their expansionist nature had been an issue since 1931, and more critically since 1937 when China was invaded.
Bottom Line
To put it bluntly: Spain was no threat to its neighbors, and it certainly wasn't worth the effort to start another war. Spain could be worked with despite that imperfection due to the other more pressing political issues inherent in the Cold War.
A:
The OP said this in a comment:
technically speaking, Spain was a satellite state. However, the treaty was mainly intended for the countries within the big blocks so I assume it was just ignored.
The second statement, that Spain was overlooked, is flatly not true as will be demonstrated once we look at the text of the agreements and the historical arguing about what to do with Spain.
The question of whether Spain counted as an Axis satellite state is one which was hotly debated in 1944 and 1945. This is the crux of the question.
What The Yalta Agreement Said
"Axis satellite state" is mentioned in the "Protocol Of Proceedings Of Crimea Conference", aka the Yalta Agreement, but it's never defined.
They jointly declare their mutual agreement to concert during the temporary period of instability in liberated Europe the policies of their three Governments in assisting the peoples liberated from the domination of Nazi Germany and the peoples of the former Axis satellite states of Europe to solve by democratic means their pressing political and economic problems.
However, section II "Declaration Of Liberated Europe" makes it clear what their goals were. It's worth reading in its entirety. Italics are mine to highlight relevant sections.
The Premier of the Union of Soviet Socialist Republics, the Prime Minister of the United Kingdom and the President of the United States of America have consulted with each other in the common interests of the people of their countries and those of liberated Europe. They jointly declare their mutual agreement to concert during the temporary period of instability in liberated Europe the policies of their three Governments in assisting the peoples liberated from the domination of Nazi Germany and the peoples of the former Axis satellite states of Europe to solve by democratic means their pressing political and economic problems.
The establishment of order in Europe and the rebuilding of national economic life must be achieved by processes which will enable the liberated peoples to destroy the last vestiges of nazism and fascism and to create democratic institutions of their own choice. This is a principle of the Atlantic Charter - the right of all people to choose the form of government under which they will live - the restoration of sovereign rights and self-government to those peoples who have been forcibly deprived to them by the aggressor nations.
To foster the conditions in which the liberated people may exercise these rights, the three governments will jointly assist the people in any European liberated state or former Axis state in Europe where, in their judgment conditions require,
(a) to establish conditions of internal peace;
(b) to carry out emergency relief measures for the relief of distressed peoples;
(c) to form interim governmental authorities broadly representative of all democratic elements in the population and pledged to the earliest possible establishment through free elections of Governments responsive to the will of the people; and
(d) to facilitate where necessary the holding of such elections.
The three Governments will consult the other United Nations and provisional authorities or other Governments in Europe when matters of direct interest to them are under consideration.
When, in the opinion of the three Governments, conditions in any European liberated state or former Axis satellite in Europe make such action necessary, they will immediately consult together on the measure necessary to discharge the joint responsibilities set forth in this declaration.
By this declaration we reaffirm our faith in the principles of the Atlantic Charter, our pledge in the Declaration by the United Nations and our determination to build in cooperation with other peace-loving nations world order, under law, dedicated to peace, security, freedom and general well-being of all mankind.
This isn't a denunciation of fascism. It isn't a call to arms to overthrow dictatorships worldwide. It's defining how the liberated nations and minor Axis powers will be treated after WWII.
The goal is "to solve by democratic means their pressing political and economic problems". Someplace like Romania, Hungary, or Bulgaria, Axis belligerents who were devastated by the war. Or Norway and the Netherlands who had puppet governments installed. These countries needed their governments replaced, economies rebuilt, and social order restored.
Spain, in contrast, was neither conquered by the Axis nor allied with them. They never declared war and they never allowed either power to move troops through their country (to the great relief of Britain and Gibraltar). Spain had a working, independent, if fascist, government. They were untouched by the war. By the scale of the rest of Europe they had no "pressing political and economic problems".
Was Spain an Axis Satellite?
This is not to say people didn't try to get Spain treated as an Axis satellite state. Spain was technically "non-belligerent" but they really, really pushed it. The Spanish civil war, a proxy battle between communism and fascism, and their support of the Nazis made Spain a hot button topic for communists and socialists after the war. In particular the French and the Soviets.
While Spain never officially sent Spanish troops to fight, they allowed an entire division of volunteers to fight the Soviets. The 250. Infanterie-Division aka División Española de Voluntarios aka División Azul (curiously, their emblem is red and yellow) was an all volunteer division, some professional soldiers, some anti-communists, trained and supplied by the Germans, and sent to fight on the Eastern Front in 1941. They fought in the Siege of Leningrad and earned the Soviet's ire by stopping a major attempt to break the siege in 1943. Eventually almost 50,000 Spaniards would fight the Soviets.
Pressed by the Allies, Franco ordered all volunteers to return to Spain in late 1943. This is an important point, by 1944 Franco could see the writing on the wall and was more and more cooperating with the Allies.
But many wanted to see Spain excluded from the growing United Nations. At the UN Conference on International Organization...
the Mexican delegate to the conference, a Spanish exiled anti-fascist named Luis Quintanilla, appealed for the exclusion of Spain from the UN on the grounds that the United Charter excluded all those countries ruled by regimes established with the help of Germany or Italy.
At the later Potsdam Conference in 1945...
the Soviets wanted to go one step further and
proposed on 19 July 1945 that all relations with Franco including diplomatic and economic links be severed.
The eventual statement was a bit softer.
In a joint statement, issued during the Potsdam Conference,
the three great powers, US, Britain and the USSR, expressed their wish that Spain should not apply for membership to the United Nations given the fact that her current regime was founded with the help of the Axis powers, was closely associated with the
Axis and did not posses the necessary qualifications to justify membership
The strongest statement made was the Tripartite Statement on Spain of March 4, 1946...
THE GOVERNMENTS of France, the United Kingdom, and the United States of America have exchanged views with regard to the present Spanish Government and their relations with that regime. It is agreed that so long as General Franco continues in control of Spain, the Spanish people cannot anticipate full and cordial association with those nations of the world which have, by common effort, brought defeat to German Nazism and Italian Fascism, which aided the present Spanish regime in its rise to power and after which the regime was patterned.
However this declaration had no teeth because it was considered an internal Spanish problem.
There is no intention of interfering in the internal affairs of Spain. The Spanish people themselves must in the long run work out their own destiny. In spite of the present regime's repressive measures against orderly efforts of the Spanish people to organize and give expression to their political aspirations, the three Governments are hopeful that the Spanish people will not again be subjected to the horrors and bitterness of civil strife.
But the idea of diplomatic and economic sanctions was floated.
Such recognition would include full diplomatic relations and the taking of such practical measures to assist in the solution of Spain's economic problems as may be practicable in the circumstances prevailing. Such measures are not now possible. The question of the maintenance or termination by the Governments of France the United Kingdom, and the United States of diplomatic relations with the present Spanish regime is a matter to be decided in the light of events and after taking into account the efforts of the Spanish people to achieve their own freedom.
UN Chapter VI: No Invasion Allowed
In 1946, Spain was having a hard time diplomatically.
Worldwide public opinion was moving against Franco. Canada publicly rebuffed Spain’s attempt to establish diplomatic relations. During spring 1946, six Communist, four Latin American, three Commonwealth and four other states severed diplomatic relations with Spain. There was also speculation that Italy might do the same.
Article 33, beginning Chapter VI of the UN charter, says:
The parties to any dispute, the continuance of which is likely to endanger the maintenance of international peace and security, shall, first of all, seek a solution by negotiation, enquiry, mediation, conciliation, arbitration, judicial settlement, resort to regional agencies or arrangements, or other peaceful means of their own choice.
The UN found that the issue of what to do about Spain fell under Chapter VI and thus had to be resolved by peaceful means, didn't matter that Spain was not then a UN member. There could be no invasion of Spain by UN states to topple Franco.
This culminated in December 1946 with UN Resolution 39 "Relations of Members of the United Nations with Spain" which called for the end to the Franco regime and its diplomatic isolation.
Spain may not be admitted to the United Nations...
Recommends that the Franco Government of Spain be debarred from membership in international agencies established by or brought into relationship with the United Nations...
Recommends that all Members of the United Nations immediately recall from Madrid their Ambassadors and Ministers plenipotentiary accredited there.
The Influence of the Cold War
Other sources talk about the desire of the US to take a gentle approach to Spain in order to bring her into the fold of a Western Alliance to defend against Communism. The US military found the prospect of a war and national uprising in Spain dubious saying:
there is no prospect of any form of popular rising taking place in Spain... a rising, caused by foreign intervention, if strong enough to avoid immediate suppression by the police with army backing, would almost inevitably result in the outbreak of another civil war... a civil war in Spain with French and Russian intervention would also be
likely to precipitate a crisis in France.
The US military increasingly looked at Spain and Italy as fallback positions against possible Soviet invasion of Europe. The Pincher Plan saw the possibility of using the Pyrenees as a natural defensive line to buy time against an overwhelming Soviet attack for a US build up.
The withdrawal of US forces across France into Spain also may prove feasible. This, too, will be largely dependent upon political considerations. It is probable that an anti-Communistic government will remain in power for at least the next year or two, and if Spain is willing to desert her position as a neutral, then the withdrawal of US forces into Spain would make a material contribution to any required defense of the Pyrenees. On the other hand, the Allies would probably be committed to the defense of Spain, which might well entail a substantial diversion of resources. Retention of an anti-Communist government in Spain would materially assist in maintaining the security of the western Mediterranean.
Here we see the beginnings of the Cold War idea that if you're anti-Communist, you're a potential US ally. That it's better to support a fascist dictatorship than to risk a left-leaning democratically elected government. Sir Victor Mallet, British Ambassador to Spain, wrote
A weak Government in Spain, whether of the Right or the Left, would pave the way for increased Soviet influence and pressure through the Spanish Communists. The one real merit of the present Government is that it does at least maintain order.
Sources
International Relations between the U.S. and Spain 1945-53
Economics, Ideology and Compromise (This covers the post-war Spanish narrative in detail)
The Spanish Government and the Axis from The Avalon Project.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JQuery Class Selector still firing after removeClass
I am creating a little voting mechanism that sends a quick database timestamp through AJAX.
A series of buttons with the class "vote" are the triggers to vote, while there is text below to show how many "votes" are for that particular item.
After I run the AJAX method from the click event, I remove the "vote" class such that there cannot be more than one from that item. However my problem is that even with the class removed the trigger can still fire and increment as many votes.
Here is the HTML of the element:
<div class="points">
<img class="vote" src="images/up.gif" alt="'.$idea['id'].'">
<p class="vote-'.$idea['id'].'">'.$points.' Points</p>
</div>
Here's the jQuery Call:
$('.vote').click(function(){
var iID = $(this).attr('alt');
var typeString = "id="+iID;
$.ajax({
type: "POST",
url:"vote.php",
data: typeString,
success: function (txt){
$('.vote-'+iID).html('<p>'+txt+' Points</p>');
}
});
$(this).attr('src', 'images/voted.gif');
$(this).removeClass('vote');
});
A:
You're attaching the event handler to the DOM element, and it stays intact. You can either
a. set .data('triggered', 1) like so:
if ( !$(this).data('triggered') ) {
// do code
$(this).data('triggered', 1);
}
b.
if ( $(this).hasClass('vote') ) {
// do code
}
c. use .live instead of .click, eg $('.foo').live('click', fn)
d. remove the event handler manually after invoking your code, $(this).unbind('click') as the last line, after the remove class bit
A:
The class of a DOM element is used to reference it, not to alter its Event binding behavior.
To remove a DOM elements click event use unbind.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
bash script execution date/time
I'm trying to figure this out on and off for some time now. I have a bash script in Linux environment that, for safety reasons, I want to prevent from being executed say between 9am and 5pm unless a flag is given. So if I do ./script.sh between 9am and 5pm it would say "NO GO", but if I do ./script.sh -force it would bypass the check. Basically making sure the person doesn't do something by accident. I've tried some date commands, but can't wrap that thing around my mind. Could anyone help out?
A:
Write a function. Use date +"%k" to get the current hour, and (( )) to compare it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Subclassing a JavaFX Application
This question is a follow up to a question I posted asking How do you call a subclass method from a superclass in Java?. Well I got my answer but my SuperClass is a JavaFX application that extends Application and whenever I attempt to use an abstract class as my application class I get the following error: java.lang.reflect.InvocationTargetException in the constructor. Even if the application class is not abstract I get that error if I attempt to call new SubClass().create("title");. What I'm looking to achieve is call a method exec(String command) in the SubClass when the enter key is pressed. Here is my current SuperClass code:
public abstract class Console extends Application {
private String title;
private static Text output = new Text();
public void create(String title) {
this.title = title;
launch();
}
public void start(Stage stage) {
stage.setOnCloseRequest((WindowEvent event) -> {
System.exit(0);
});
stage.setTitle(title);
stage.setResizable(false);
Group root = new Group();
Scene scene = new Scene(root, 800, 400);
stage.setScene(scene);
ScrollPane scroll = new ScrollPane();
scroll.setContent(output);
scroll.setMaxWidth(800);
scroll.setMaxHeight(360);
TextField input = new TextField();
input.setLayoutX(0);
input.setLayoutY(380);
input.setPrefWidth(800);
scene.setOnKeyPressed((KeyEvent event) -> {
if(event.getCode() == KeyCode.ENTER) {
exec(input.getText());
input.clear();
}
});
root.getChildren().add(scroll);
root.getChildren().add(input);
stage.show();
}
public static void appendOutput(String value) {
Platform.runLater(() -> {
output.setText(output.getText() + "\n" + value);
});
}
protected abstract void exec(String command);
}
A:
Instead of creating new instance of SubClass, try to call static method SubClass.launch(args) JavaFX will create new SubClass instance by itself.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
fill BufferedReader with data
All examples I find are filling the BufferedReader from files. I need to fill it with data from a "for" loop like this:
List<Nodes> nodes; //there are data here
BufferedReader bufRead = null;
for (Node node : nodes) {
//need to fill the BufferedReader with node data line by line
bufRead = new BufferedReader(new InputStreamReader(null, node.toString()+"\n"));
}
//use the BufferedReader later on
A:
You don't "fill" a Reader. Reader is a verb, saying that it reads something, so you have to provide the source that is being read from.
If you have Java code that generates text, which you later want to read, then use e.g. a StringWriter to write the text into a memory buffer. You can then later read that text using e.g. a StringReader.
Example
String text;
try (StringWriter strOut = new StringWriter()) {
try (PrintWriter out = new PrintWriter(strOut)) {
for (Node node : nodes) {
out.println(node);
}
}
text = strOut.toString();
}
try (BufferedReader in = new BufferedReader(new StringReader(text))) {
for (String line; (line = in.readLine()) != null; ) {
// use line here
}
}
UPDATE
From comment: I was wondering if there is a more "elegant", shorter solution
The use of PrintWriter is of course optional, and with the String versions of Reader and Writer, there is really no need to call close().
StringWriter out = new StringWriter();
for (Node node : nodes) {
out.write(node + "\n");
}
BufferedReader in = new BufferedReader(new StringReader(out.toString()));
for (String line; (line = in.readLine()) != null; ) {
// use line here
}
Alternatively, you can use a StringBuilder instead.
StringBuilder buf = new StringBuilder();
for (Node node : nodes) {
buf.append(node).append('\n');
}
BufferedReader in = new BufferedReader(new StringReader(buf.toString()));
for (String line; (line = in.readLine()) != null; ) {
// use line here
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Method working only with .select or .reject but not working with .map solution
I have to solve the following exercise:
"Implement a first method size_splitter which takes two parameters: an array, and a integer (the size). We will assume that the array only contains words, e.g. Strings, and that the arbitrary rule is to form two groups: the first one with words of the given size (second parameter of the method), and the other group with all the other words.
The size_splitter method should return an array of two arrays - the two groups defined above - with the contents sorted alphabetically."
My solution was that:
def size_splitter(array, size)
words1 = []
words2 = []
filtered_array = [words1, words2]
array.map { |word| words1 << word if word.length == size }
array.map { |word| words2 << word if word.length != size }
return filtered_array.sort
end
The exercise solution is:
def size_splitter(array, size)
first_subarray = array.select { |word| word.length == size }.sort
second_subarray = array.reject { |word| word.length == size }.sort
return [first_subarray, second_subarray]
# OR
# array.sort.partition { |word| word.length == size }
end
But i don't understand why my solution is not working, since it works on pry/irb :( can anyone help?
A:
The major difference between your solution and theirs, is that you are sorting filtered_arrays (which is an array of arrays) but you are required to sort each of the arrays inside filtered_arrays. You can simply change return filtered_array.sort to return filtered_array.map { |array| array.sort } or return filtered_array.map(&:sort).
By the way, it's not a good practice to use map when you don't make use of the return value. You can replace map with each and your code will work the exact same.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to Disable my App from Appearing on Android Wear Devices?
How to Disable my App from Appearing on Android Wear Devices?
It seems that my app integrates automatically with Android Wear (notifications mirroring) but I want to disable it...
A:
To keep your app's [phone] notification from being mirrored to Android Wear, call setLocalOnly(true) on the Notification.Builder (or NotificationCompat.Builder, if you're targeting SDK < 20) that you use to create the notification.
For example:
NotificationCompat.Builder bob = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(content)
.setLocalOnly(true);
(the last line is the important one)
Documented here: http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#setLocalOnly(boolean)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to mount an ISO file?
I'm running into trouble trying to mount a large iso:
dev@dev-OptiPlex-745:~$ sudo mount -o loop /home/dev/Hämtningar/matlab2011a_64.iso /cdrom
mount: warning: /cdrom seems to be mounted read-only.
dev@dev-OptiPlex-745:~$
Can you tell me how I should do it?
A:
Maybe, instead of installing additional software, you can use what the system has to this end:
Create a directory to serve as the mount location:
sudo mkdir /media/iso
Mount the ISO in the target directory:
sudo mount -o loop path/to/iso/file/YOUR_ISO_FILE.ISO /media/iso
Unmount the ISO:
sudo umount /media/iso
On your desktop will appear the mounted ISO.
A:
Try mounting it using a GUI.
Navigate to the *.iso file using a file manager, then Right click -> Open with Archive Mounter.
Or you can install the Furius ISO Mount. It is available in the Ubuntu Software Center:
sudo apt-get install furiusisomount
Here are some screenshots:
Furius ISO Mount - Project Page
A:
I found the easiest and fastest way to handle the ISO file in Ubuntu 14.04 was to right click on the ISO file, choose Disk Image Mounter and then simply proceed to the newly opened directory:
In case you don't have installed, you can use this command in terminal to install it:
sudo apt-get install gnome-disk-utility
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Query returning Max and Min of each column
I have a table like this:
A B C D E F G H
------------------------------
8 7 8 10 6 5 7 10
9 9 9 10 8 7 9 9
10 9 8 6 6 9 6 6
10 9 8 7 7 7 9 8
And I need a query that returns the maximum and minimum of each column, like this:
A B C D E F G H
------------------------------
8 7 8 6 6 5 6 6
10 9 9 10 8 9 9 10
I'm pretty new on SQL, and I'm stuck here.
A:
I think, this query should help you:
select MIN(A), MIN (B), MIN (C), MIN (D), MIN (E), MIN (F), MIN (G), MIN (H)
from yourTable
union all
select MAX(A), MAX (B), MAX (C), MAX (D), MAX (E), MAX (F), MAX (G), MAX (H)
from yourTable
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Where does "emphasis mine" go in a quotation?
I have often seen the term emphasis mine used whenever an author wishes to denote that emphasis in a given quotation originates from said author rather than from the original source.
What is the proper place for this phrase?
One possibility is immediately following the emphatic text, inside the quotation. But, see next question...
What if there are multiple emphatic sections marked within the quote?
If "emphasis mine" comes immediately after each phrase, it would end up repeated two or more times, which seems a bit messy. In this case, would it be OK to place "emphasis mine" at the end of the quotation? If so, should it be inside or outside?
How should the phrase "emphasis mine" be set off?
I believe I have seen parentheses () or brackets [], though brackets are also used to indicate words added by the one using the quotation.
A:
Wikipedia's Manual of Style, similar to most other style manuals, says:
Do not put quotations in italics unless the material would otherwise call for italics, such as for emphasis and the use of non-English words. Indicate whether italics were used in the original text or whether they were added later. For example, directly from the Manual of Style:
"Now cracks a noble heart. Good night sweet prince: And flights of angels sing thee to thy rest." [emphasis added]
A:
What I found most subtle among the different methods I've seen was to put it right between the introductory text and the quotation itself, between parentheses. Like so (emphasis mine):
Whatever.
In this way, it's easy for the reader not to focus on that if he doesn't care, and to be aware of it when actually reading the quotation if he does.
I wouldn't call that a rule, but I don't think there's much more but good practices adressing this question either.
In French¹, I stumbled on the interesting other technique of embedding this information in the surrounding text. Translating² :
[…] : « [book extract] Maintenant, […], blaguons… »³
Balzac emphasised that, then to comment : “[…] dazed, as it could have been hearing an angel blaspheming.” We emphasized that.
The author highlights Balzac's comment, but I'm the one who highlights the way he inserts it in the text.
¹ in which I don't see many such notices, because emphasis is seldom added, I reckon.
² It's about the etymology of “blague” (→blaguons), hence the importance of that word being emphasized by the original author.
³ Italics for being foreign ommited for the sake of it all.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to uninstall Intel C++ from Visual Studio
I just updated Intel C++ from 12.0 to 12.1. I uninstalled the 12.0 from the control Panel, but I notice it is still available in the Visual Studio 2010 platform toolset (in addition to Intel C++ 12.1). How to remove the entry? I'd appreciate if someone could help.
Blockquote
C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\PlatformToolsets\Intel C++ Compiler XE 12.0\Microsoft.Cpp.Win32.Intel C++ Compiler XE 12.0.targets(43,5): error : Could not expand ICInstallDir variable. PlatformToolset may be set to an invalid version number.
Blockquote
Version 12.0 certainly isn't available any more judging from what I'm getting in the output log
Edit: Is it safe to just delete the Intel C++ Compiler XE 12.0 folders from C:\Program Files\MSBuild..\ ?
A:
You need to uninstall Intel's add-in to VS, not only Intel compiler and libraries.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Query to get parent parts of materials using Recursive CTE
The intent of the query is to filter out certain materials to get to a list that will then be run through a recursive CTE to drill up through the BOM to the 0 level assembly.
P_Parts_CTE is filtering to get just purchased parts
P_Parts_Inv_CTE is getting the on hand inventory of the purchased parts
PartDtl_Sum_CTE is taking the same list of parts from the first CTE and summing all Supply and Demand records for each part
PartDtl_CTE is using the results of the prior two CTEs to take the on hand inventory, add in the supply, and subtract the demand to get to a projected balance
Parts_Neg_CTE is filtering to get the parts that have a negative balance
Reverse_Recursive_BOM_CTE takes the list of parts from prior CTE and explodes them upwards in the BOM to the 0 level
It works, but I ran it last night and was tired of waiting for it and killed it at 35 minutes. I'm not sure if I did something wrong or if the query is just that complex. I would love to do this all in one query, but if there is no way to improve this then I will create a table and run a stored procedure to populate it with the exploded BOM. Thanks in advance
Query
with P_Parts_CTE (Company, PartNum) --Identify purchased parts
as
(
select Company, PartNum
from dbo.Part
where Company = 'Comp' and TypeCode = 'P'
),
P_Part_Inv_CTE (Company, PartNum, OnHandQty) --Get on-hand inventory for parts
as
(
select a.Company, a.PartNum, Sum(OnHandQty)
from P_Parts_CTE as a
left outer join dbo.PartWhse as b
on a.Company = b.Company and a.PartNum = b.PartNum
group by a.Company, a.PartNum
),
PartDtl_Sum_CTE (Company, PartNum, Supply, Demand) --Get current supply & demand for parts
as
(
select c.Company, c.PartNum, Sum(case when d.RequirementFlag = 0 then d.Quantity else 0 end) as Supply, Sum(case when d.RequirementFlag = 1 then d.Quantity else 0 end) as Demand
from P_Parts_CTE as c
left outer join dbo.PartDtl as d
on c.Company = d.Company and c.PartNum = d.PartNum
group by c.Company, c.PartNum
),
PartDtl_CTE (Company, PartNum, Balance) --Find out the balance of inventory after supply and demand are factored in
as
(
select e.Company, e.PartNum, (e.OnHandQty + f.Supply - f.Demand) as Balance
from P_Part_Inv_CTE as e
left outer join PartDtl_Sum_CTE as f
on e.Company = f.Company and e.PartNum = f.PartNum
group by e.Company, e.PartNum, e.OnHandQty, f.Supply, f.Demand
),
Parts_Neg_CTE (Company, PartNum) --Get list of parts where balance is negative
as
(
select Company, PartNum
from PartDtl_CTE
where Balance < 0
),
Reverse_Recursive_BOM_CTE (Company, PartNum, [Level], MtlPartNUm) --As these are mainly materials that go into finished goods, blow out the BOM upwards
as
(
select h.Company, h.PartNum, 0 as [Level], h.MtlPartNum
from Parts_Neg_CTE as g
inner join dbo.PartMtl as h
on g.Company = h.Company and g.PartNum = h.PartNum
union all
select i.Company, i.PartNum, [Level] - 1, i.MtlPartNum
from dbo.PartMtl as i
inner join Reverse_Recursive_BOM_CTE as j
on i.MtlPartNum = j.PartNum
)
select *
from Reverse_Recursive_BOM_CTE
Execution Plan
<?xml version="1.0" encoding="utf-16"?>
<ShowPlanXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Version="1.1" Build="10.50.2500.0" xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan">
<BatchSequence>
<Batch>
<Statements>
<StmtSimple StatementCompId="1" StatementEstRows="43701.6" StatementId="1" StatementOptmLevel="FULL" StatementSubTreeCost="61.7944" StatementText="with P_Parts_CTE (Company, PartNum)
as
(
 select Company, PartNum
 from dbo.Part
 where Company = 'Bruce' and TypeCode = 'P'
),
P_Part_Inv_CTE (Company, PartNum, OnHandQty)
as
(
 select a.Company, a.PartNum, Sum(OnHandQty)
 from P_Parts_CTE as a
 left outer join dbo.PartWhse as b
 on a.Company = b.Company and a.PartNum = b.PartNum
 group by a.Company, a.PartNum
),
PartDtl_Sum_CTE (Company, PartNum, Supply, Demand)
as
(
 select c.Company, c.PartNum, Sum(case when d.RequirementFlag = 0 then d.Quantity else 0 end) as Supply, Sum(case when d.RequirementFlag = 1 then d.Quantity else 0 end) as Demand
 from P_Parts_CTE as c
 left outer join dbo.PartDtl as d
 on c.Company = d.Company and c.PartNum = d.PartNum
 group by c.Company, c.PartNum
),
PartDtl_CTE (Company, PartNum, Balance)
as
(
 select e.Company, e.PartNum, (e.OnHandQty + f.Supply - f.Demand) as Balance
 from P_Part_Inv_CTE as e
 left outer join PartDtl_Sum_CTE as f
 on e.Company = f.Company and e.PartNum = f.PartNum
 group by e.Company, e.PartNum, e.OnHandQty, f.Supply, f.Demand
),
Parts_Neg_CTE (Company, PartNum)
as
(
 select Company, PartNum
 from PartDtl_CTE
 where Balance < 0
),
Reverse_Recursive_BOM_CTE (Company, PartNum, [Level], MtlPartNUm)
as
(
 select h.Company, h.PartNum, 0 as [Level], h.MtlPartNum
 from Parts_Neg_CTE as g
 inner join dbo.PartMtl as h
 on g.Company = h.Company and g.PartNum = h.PartNum
 union all
 select i.Company, i.PartNum, [Level] - 1, i.MtlPartNum
 from dbo.PartMtl as i
 inner join Reverse_Recursive_BOM_CTE as j
 on i.MtlPartNum = j.PartNum
)
select *
from Reverse_Recursive_BOM_CTE" StatementType="SELECT" QueryHash="0x7FDBDBEEA130262E" QueryPlanHash="0x9402E43E7FD31267">
<StatementSetOptions ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" ARITHABORT="true" CONCAT_NULL_YIELDS_NULL="true" NUMERIC_ROUNDABORT="false" QUOTED_IDENTIFIER="true" />
<QueryPlan CachedPlanSize="168" CompileTime="100" CompileCPU="100" CompileMemory="5680">
<RelOp AvgRowSize="73" EstimateCPU="0.000218508" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="43701.6" LogicalOp="Lazy Spool" NodeId="0" Parallel="false" PhysicalOp="Index Spool" EstimatedTotalSubtreeCost="61.7944">
<OutputList>
<ColumnReference Column="Expr1066" />
<ColumnReference Column="Recr1028" />
<ColumnReference Column="Recr1029" />
<ColumnReference Column="Recr1030" />
<ColumnReference Column="Recr1031" />
</OutputList>
<Spool Stack="true">
<RelOp AvgRowSize="73" EstimateCPU="4.37016E-05" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="43701.6" LogicalOp="Concatenation" NodeId="1" Parallel="false" PhysicalOp="Concatenation" EstimatedTotalSubtreeCost="61.7937">
<OutputList>
<ColumnReference Column="Expr1066" />
<ColumnReference Column="Recr1028" />
<ColumnReference Column="Recr1029" />
<ColumnReference Column="Recr1030" />
<ColumnReference Column="Recr1031" />
</OutputList>
<Concat>
<DefinedValues>
<DefinedValue>
<ColumnReference Column="Expr1066" />
<ColumnReference Column="Expr1063" />
<ColumnReference Column="Expr1065" />
</DefinedValue>
<DefinedValue>
<ColumnReference Column="Recr1028" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="Company" />
</DefinedValue>
<DefinedValue>
<ColumnReference Column="Recr1029" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="PartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="PartNum" />
</DefinedValue>
<DefinedValue>
<ColumnReference Column="Recr1030" />
<ColumnReference Column="Expr1020" />
<ColumnReference Column="Expr1027" />
</DefinedValue>
<DefinedValue>
<ColumnReference Column="Recr1031" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="MtlPartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="MtlPartNum" />
</DefinedValue>
</DefinedValues>
<RelOp AvgRowSize="73" EstimateCPU="0.000437016" EstimateIO="0" EstimateRebinds="43701.6" EstimateRewinds="0" EstimateRows="1" LogicalOp="Compute Scalar" NodeId="2" Parallel="false" PhysicalOp="Compute Scalar" EstimatedTotalSubtreeCost="0.000437016">
<OutputList>
<ColumnReference Column="Expr1063" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="PartNum" />
<ColumnReference Column="Expr1020" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="MtlPartNum" />
</OutputList>
<ComputeScalar>
<DefinedValues>
<DefinedValue>
<ColumnReference Column="Expr1063" />
<ScalarOperator ScalarString="(0)">
<Const ConstValue="(0)" />
</ScalarOperator>
</DefinedValue>
</DefinedValues>
<RelOp AvgRowSize="40" EstimateCPU="0.00436224" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="43622.4" LogicalOp="Compute Scalar" NodeId="3" Parallel="false" PhysicalOp="Compute Scalar" EstimatedTotalSubtreeCost="22.3494">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="PartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="MtlPartNum" />
<ColumnReference Column="Expr1020" />
</OutputList>
<ComputeScalar>
<DefinedValues>
<DefinedValue>
<ColumnReference Column="Expr1020" />
<ScalarOperator ScalarString="(0)">
<Const ConstValue="(0)" />
</ScalarOperator>
</DefinedValue>
</DefinedValues>
<RelOp AvgRowSize="36" EstimateCPU="1.35964" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="43622.4" LogicalOp="Inner Join" NodeId="4" Parallel="false" PhysicalOp="Hash Match" EstimatedTotalSubtreeCost="22.3451">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="PartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="MtlPartNum" />
</OutputList>
<MemoryFractions Input="0.140598" Output="1" />
<Hash>
<DefinedValues />
<HashKeysBuild>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</HashKeysBuild>
<HashKeysProbe>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="PartNum" />
</HashKeysProbe>
<ProbeResidual>
<ScalarOperator ScalarString="[Epicor905].[dbo].[Part].[PartNum]=[Epicor905].[dbo].[PartMtl].[PartNum] as [h].[PartNum]">
<Compare CompareOp="EQ">
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="PartNum" />
</Identifier>
</ScalarOperator>
</Compare>
</ScalarOperator>
</ProbeResidual>
<RelOp AvgRowSize="20" EstimateCPU="1.02806" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="5321.06" LogicalOp="Inner Join" NodeId="5" Parallel="false" PhysicalOp="Hash Match" EstimatedTotalSubtreeCost="19.6618">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</OutputList>
<MemoryFractions Input="0.384615" Output="0.528321" />
<Hash>
<DefinedValues />
<HashKeysBuild>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</HashKeysBuild>
<HashKeysProbe>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</HashKeysProbe>
<ProbeResidual>
<ScalarOperator ScalarString="[Epicor905].[dbo].[Part].[PartNum]=[Epicor905].[dbo].[Part].[PartNum] AND (([Expr1005]+[Expr1011])-[Expr1012])<(0.00000000)">
<Logical Operation="AND">
<ScalarOperator>
<Compare CompareOp="EQ">
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</Identifier>
</ScalarOperator>
</Compare>
</ScalarOperator>
<ScalarOperator>
<Compare CompareOp="LT">
<ScalarOperator>
<Arithmetic Operation="SUB">
<ScalarOperator>
<Arithmetic Operation="ADD">
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1005" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1011" />
</Identifier>
</ScalarOperator>
</Arithmetic>
</ScalarOperator>
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1012" />
</Identifier>
</ScalarOperator>
</Arithmetic>
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(0.00000000)" />
</ScalarOperator>
</Compare>
</ScalarOperator>
</Logical>
</ScalarOperator>
</ProbeResidual>
<RelOp AvgRowSize="37" EstimateCPU="0.0235022" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="20811.9" LogicalOp="Compute Scalar" NodeId="6" Parallel="false" PhysicalOp="Compute Scalar" EstimatedTotalSubtreeCost="5.86434">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
<ColumnReference Column="Expr1005" />
</OutputList>
<ComputeScalar>
<DefinedValues>
<DefinedValue>
<ColumnReference Column="Expr1005" />
<ScalarOperator ScalarString="CASE WHEN [Expr1057]=(0) THEN NULL ELSE [Expr1058] END">
<IF>
<Condition>
<ScalarOperator>
<Compare CompareOp="EQ">
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1057" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(0)" />
</ScalarOperator>
</Compare>
</ScalarOperator>
</Condition>
<Then>
<ScalarOperator>
<Const ConstValue="NULL" />
</ScalarOperator>
</Then>
<Else>
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1058" />
</Identifier>
</ScalarOperator>
</Else>
</IF>
</ScalarOperator>
</DefinedValue>
</DefinedValues>
<RelOp AvgRowSize="37" EstimateCPU="0.0235022" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="20811.9" LogicalOp="Aggregate" NodeId="7" Parallel="false" PhysicalOp="Stream Aggregate" EstimatedTotalSubtreeCost="5.86434">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
<ColumnReference Column="Expr1057" />
<ColumnReference Column="Expr1058" />
</OutputList>
<StreamAggregate>
<DefinedValues>
<DefinedValue>
<ColumnReference Column="Expr1057" />
<ScalarOperator ScalarString="COUNT_BIG([Epicor905].[dbo].[PartWhse].[OnHandQty] as [b].[OnHandQty])">
<Aggregate AggType="COUNT_BIG" Distinct="false">
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartWhse]" Alias="[b]" Column="OnHandQty" />
</Identifier>
</ScalarOperator>
</Aggregate>
</ScalarOperator>
</DefinedValue>
<DefinedValue>
<ColumnReference Column="Expr1058" />
<ScalarOperator ScalarString="SUM([Epicor905].[dbo].[PartWhse].[OnHandQty] as [b].[OnHandQty])">
<Aggregate AggType="SUM" Distinct="false">
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartWhse]" Alias="[b]" Column="OnHandQty" />
</Identifier>
</ScalarOperator>
</Aggregate>
</ScalarOperator>
</DefinedValue>
</DefinedValues>
<GroupBy>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</GroupBy>
<RelOp AvgRowSize="33" EstimateCPU="0.158188" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="21827.1" LogicalOp="Inner Join" NodeId="8" Parallel="false" PhysicalOp="Merge Join" EstimatedTotalSubtreeCost="5.84084">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartWhse]" Alias="[b]" Column="OnHandQty" />
</OutputList>
<Merge ManyToMany="false">
<InnerSideJoinColumns>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartWhse]" Alias="[b]" Column="PartNum" />
</InnerSideJoinColumns>
<OuterSideJoinColumns>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</OuterSideJoinColumns>
<Residual>
<ScalarOperator ScalarString="[Epicor905].[dbo].[Part].[PartNum]=[Epicor905].[dbo].[PartWhse].[PartNum] as [b].[PartNum]">
<Compare CompareOp="EQ">
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartWhse]" Alias="[b]" Column="PartNum" />
</Identifier>
</ScalarOperator>
</Compare>
</ScalarOperator>
</Residual>
<RelOp AvgRowSize="20" EstimateCPU="0.0271213" EstimateIO="0.114603" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="24513" LogicalOp="Index Seek" NodeId="9" Parallel="false" PhysicalOp="Index Seek" EstimatedTotalSubtreeCost="0.141724" TableCardinality="98055">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</OutputList>
<IndexScan Ordered="true" ScanDirection="FORWARD" ForcedIndex="false" ForceSeek="false" ForceScan="false" NoExpandHint="false">
<DefinedValues>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</DefinedValue>
</DefinedValues>
<Object Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Index="[TypePart]" TableReferenceId="1" IndexKind="NonClustered" />
<SeekPredicates>
<SeekPredicateNew>
<SeekKeys>
<Prefix ScanType="EQ">
<RangeColumns>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="TypeCode" />
</RangeColumns>
<RangeExpressions>
<ScalarOperator ScalarString="'Bruce'">
<Const ConstValue="'Bruce'" />
</ScalarOperator>
<ScalarOperator ScalarString="'P'">
<Const ConstValue="'P'" />
</ScalarOperator>
</RangeExpressions>
</Prefix>
</SeekKeys>
</SeekPredicateNew>
</SeekPredicates>
</IndexScan>
</RelOp>
<RelOp AvgRowSize="33" EstimateCPU="0.0519766" EstimateIO="5.48894" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="47108.7" LogicalOp="Clustered Index Seek" NodeId="10" Parallel="false" PhysicalOp="Clustered Index Seek" EstimatedTotalSubtreeCost="5.54092" TableCardinality="135573">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartWhse]" Alias="[b]" Column="PartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartWhse]" Alias="[b]" Column="OnHandQty" />
</OutputList>
<IndexScan Ordered="true" ScanDirection="FORWARD" ForcedIndex="false" ForceSeek="false" ForceScan="false" NoExpandHint="false">
<DefinedValues>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartWhse]" Alias="[b]" Column="PartNum" />
</DefinedValue>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartWhse]" Alias="[b]" Column="OnHandQty" />
</DefinedValue>
</DefinedValues>
<Object Database="[Epicor905]" Schema="[dbo]" Table="[PartWhse]" Index="[PartNumWarehouseCode]" Alias="[b]" IndexKind="Clustered" />
<SeekPredicates>
<SeekPredicateNew>
<SeekKeys>
<Prefix ScanType="EQ">
<RangeColumns>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartWhse]" Alias="[b]" Column="Company" />
</RangeColumns>
<RangeExpressions>
<ScalarOperator ScalarString="'Bruce'">
<Const ConstValue="'Bruce'" />
</ScalarOperator>
</RangeExpressions>
</Prefix>
</SeekKeys>
</SeekPredicateNew>
</SeekPredicates>
</IndexScan>
</RelOp>
</Merge>
</RelOp>
</StreamAggregate>
</RelOp>
</ComputeScalar>
</RelOp>
<RelOp AvgRowSize="54" EstimateCPU="1.7495" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="23817.3" LogicalOp="Compute Scalar" NodeId="20" Parallel="false" PhysicalOp="Compute Scalar" EstimatedTotalSubtreeCost="12.7694">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
<ColumnReference Column="Expr1011" />
<ColumnReference Column="Expr1012" />
</OutputList>
<ComputeScalar>
<DefinedValues>
<DefinedValue>
<ColumnReference Column="Expr1011" />
<ScalarOperator ScalarString="CASE WHEN [Expr1059]=(0) THEN NULL ELSE [Expr1060] END">
<IF>
<Condition>
<ScalarOperator>
<Compare CompareOp="EQ">
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1059" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(0)" />
</ScalarOperator>
</Compare>
</ScalarOperator>
</Condition>
<Then>
<ScalarOperator>
<Const ConstValue="NULL" />
</ScalarOperator>
</Then>
<Else>
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1060" />
</Identifier>
</ScalarOperator>
</Else>
</IF>
</ScalarOperator>
</DefinedValue>
<DefinedValue>
<ColumnReference Column="Expr1012" />
<ScalarOperator ScalarString="CASE WHEN [Expr1061]=(0) THEN NULL ELSE [Expr1062] END">
<IF>
<Condition>
<ScalarOperator>
<Compare CompareOp="EQ">
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1061" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(0)" />
</ScalarOperator>
</Compare>
</ScalarOperator>
</Condition>
<Then>
<ScalarOperator>
<Const ConstValue="NULL" />
</ScalarOperator>
</Then>
<Else>
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1062" />
</Identifier>
</ScalarOperator>
</Else>
</IF>
</ScalarOperator>
</DefinedValue>
</DefinedValues>
<RelOp AvgRowSize="54" EstimateCPU="1.7495" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="23817.3" LogicalOp="Aggregate" NodeId="21" Parallel="false" PhysicalOp="Hash Match" EstimatedTotalSubtreeCost="12.7694">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
<ColumnReference Column="Expr1059" />
<ColumnReference Column="Expr1060" />
<ColumnReference Column="Expr1061" />
<ColumnReference Column="Expr1062" />
</OutputList>
<MemoryFractions Input="0.241026" Output="0.331081" />
<Hash>
<DefinedValues>
<DefinedValue>
<ColumnReference Column="Expr1059" />
<ScalarOperator ScalarString="COUNT_BIG([Expr1032])">
<Aggregate AggType="COUNT_BIG" Distinct="false">
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1032" />
</Identifier>
</ScalarOperator>
</Aggregate>
</ScalarOperator>
</DefinedValue>
<DefinedValue>
<ColumnReference Column="Expr1060" />
<ScalarOperator ScalarString="SUM([Expr1032])">
<Aggregate AggType="SUM" Distinct="false">
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1032" />
</Identifier>
</ScalarOperator>
</Aggregate>
</ScalarOperator>
</DefinedValue>
<DefinedValue>
<ColumnReference Column="Expr1061" />
<ScalarOperator ScalarString="COUNT_BIG([Expr1033])">
<Aggregate AggType="COUNT_BIG" Distinct="false">
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1033" />
</Identifier>
</ScalarOperator>
</Aggregate>
</ScalarOperator>
</DefinedValue>
<DefinedValue>
<ColumnReference Column="Expr1062" />
<ScalarOperator ScalarString="SUM([Expr1033])">
<Aggregate AggType="SUM" Distinct="false">
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1033" />
</Identifier>
</ScalarOperator>
</Aggregate>
</ScalarOperator>
</DefinedValue>
</DefinedValues>
<HashKeysBuild>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</HashKeysBuild>
<BuildResidual>
<ScalarOperator ScalarString="[Epicor905].[dbo].[Part].[PartNum] = [Epicor905].[dbo].[Part].[PartNum]">
<Compare CompareOp="IS">
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</Identifier>
</ScalarOperator>
</Compare>
</ScalarOperator>
</BuildResidual>
<RelOp AvgRowSize="46" EstimateCPU="0.00908534" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="90853.4" LogicalOp="Compute Scalar" NodeId="22" Parallel="false" PhysicalOp="Compute Scalar" EstimatedTotalSubtreeCost="11.0199">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
<ColumnReference Column="Expr1032" />
<ColumnReference Column="Expr1033" />
</OutputList>
<ComputeScalar>
<DefinedValues>
<DefinedValue>
<ColumnReference Column="Expr1032" />
<ScalarOperator ScalarString="CASE WHEN [Epicor905].[dbo].[PartDtl].[RequirementFlag] as [d].[RequirementFlag]=(0) THEN [Epicor905].[dbo].[PartDtl].[Quantity] as [d].[Quantity] ELSE (0.00000000) END">
<IF>
<Condition>
<ScalarOperator>
<Compare CompareOp="EQ">
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="RequirementFlag" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(0)" />
</ScalarOperator>
</Compare>
</ScalarOperator>
</Condition>
<Then>
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="Quantity" />
</Identifier>
</ScalarOperator>
</Then>
<Else>
<ScalarOperator>
<Const ConstValue="(0.00000000)" />
</ScalarOperator>
</Else>
</IF>
</ScalarOperator>
</DefinedValue>
<DefinedValue>
<ColumnReference Column="Expr1033" />
<ScalarOperator ScalarString="CASE WHEN [Epicor905].[dbo].[PartDtl].[RequirementFlag] as [d].[RequirementFlag]=(1) THEN [Epicor905].[dbo].[PartDtl].[Quantity] as [d].[Quantity] ELSE (0.00000000) END">
<IF>
<Condition>
<ScalarOperator>
<Compare CompareOp="EQ">
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="RequirementFlag" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(1)" />
</ScalarOperator>
</Compare>
</ScalarOperator>
</Condition>
<Then>
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="Quantity" />
</Identifier>
</ScalarOperator>
</Then>
<Else>
<ScalarOperator>
<Const ConstValue="(0.00000000)" />
</ScalarOperator>
</Else>
</IF>
</ScalarOperator>
</DefinedValue>
</DefinedValues>
<RelOp AvgRowSize="34" EstimateCPU="1.30515" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="90853.4" LogicalOp="Left Outer Join" NodeId="23" Parallel="false" PhysicalOp="Hash Match" EstimatedTotalSubtreeCost="11.0108">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="RequirementFlag" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="Quantity" />
</OutputList>
<MemoryFractions Input="0.615385" Output="0.374359" />
<Hash>
<DefinedValues />
<HashKeysBuild>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</HashKeysBuild>
<HashKeysProbe>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="PartNum" />
</HashKeysProbe>
<ProbeResidual>
<ScalarOperator ScalarString="[Epicor905].[dbo].[Part].[PartNum]=[Epicor905].[dbo].[PartDtl].[PartNum] as [d].[PartNum]">
<Compare CompareOp="EQ">
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Identifier>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="PartNum" />
</Identifier>
</ScalarOperator>
</Compare>
</ScalarOperator>
</ProbeResidual>
<RelOp AvgRowSize="20" EstimateCPU="0.0271213" EstimateIO="0.114603" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="24513" LogicalOp="Index Seek" NodeId="24" Parallel="false" PhysicalOp="Index Seek" EstimatedTotalSubtreeCost="0.141724" TableCardinality="98055">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</OutputList>
<IndexScan Ordered="true" ScanDirection="FORWARD" ForcedIndex="false" ForceSeek="false" ForceScan="false" NoExpandHint="false">
<DefinedValues>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="PartNum" />
</DefinedValue>
</DefinedValues>
<Object Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Index="[TypePart]" TableReferenceId="2" IndexKind="NonClustered" />
<SeekPredicates>
<SeekPredicateNew>
<SeekKeys>
<Prefix ScanType="EQ">
<RangeColumns>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[Part]" Column="TypeCode" />
</RangeColumns>
<RangeExpressions>
<ScalarOperator ScalarString="'Bruce'">
<Const ConstValue="'Bruce'" />
</ScalarOperator>
<ScalarOperator ScalarString="'P'">
<Const ConstValue="'P'" />
</ScalarOperator>
</RangeExpressions>
</Prefix>
</SeekKeys>
</SeekPredicateNew>
</SeekPredicates>
</IndexScan>
</RelOp>
<RelOp AvgRowSize="33" EstimateCPU="0.0750727" EstimateIO="9.48882" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="68105.2" LogicalOp="Clustered Index Seek" NodeId="25" Parallel="false" PhysicalOp="Clustered Index Seek" EstimatedTotalSubtreeCost="9.56389" TableCardinality="243402">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="PartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="RequirementFlag" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="Quantity" />
</OutputList>
<IndexScan Ordered="true" ScanDirection="FORWARD" ForcedIndex="false" ForceSeek="false" ForceScan="false" NoExpandHint="false">
<DefinedValues>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="PartNum" />
</DefinedValue>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="RequirementFlag" />
</DefinedValue>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="Quantity" />
</DefinedValue>
</DefinedValues>
<Object Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Index="[TypPartDate]" Alias="[d]" IndexKind="Clustered" />
<SeekPredicates>
<SeekPredicateNew>
<SeekKeys>
<Prefix ScanType="EQ">
<RangeColumns>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartDtl]" Alias="[d]" Column="Company" />
</RangeColumns>
<RangeExpressions>
<ScalarOperator ScalarString="'Bruce'">
<Const ConstValue="'Bruce'" />
</ScalarOperator>
</RangeExpressions>
</Prefix>
</SeekKeys>
</SeekPredicateNew>
</SeekPredicates>
</IndexScan>
</RelOp>
</Hash>
</RelOp>
</ComputeScalar>
</RelOp>
</Hash>
</RelOp>
</ComputeScalar>
</RelOp>
</Hash>
</RelOp>
<RelOp AvgRowSize="36" EstimateCPU="0.191065" EstimateIO="1.13259" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="173553" LogicalOp="Index Seek" NodeId="47" Parallel="false" PhysicalOp="Index Seek" EstimatedTotalSubtreeCost="1.32366" TableCardinality="384010">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="PartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="MtlPartNum" />
</OutputList>
<IndexScan Ordered="true" ScanDirection="FORWARD" ForcedIndex="false" ForceSeek="false" ForceScan="false" NoExpandHint="false">
<DefinedValues>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="Company" />
</DefinedValue>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="PartNum" />
</DefinedValue>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="MtlPartNum" />
</DefinedValue>
</DefinedValues>
<Object Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Index="[WhereUsed]" Alias="[h]" IndexKind="NonClustered" />
<SeekPredicates>
<SeekPredicateNew>
<SeekKeys>
<Prefix ScanType="EQ">
<RangeColumns>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[h]" Column="Company" />
</RangeColumns>
<RangeExpressions>
<ScalarOperator ScalarString="'Bruce'">
<Const ConstValue="'Bruce'" />
</ScalarOperator>
</RangeExpressions>
</Prefix>
</SeekKeys>
</SeekPredicateNew>
</SeekPredicates>
</IndexScan>
</RelOp>
</Hash>
</RelOp>
</ComputeScalar>
</RelOp>
</ComputeScalar>
</RelOp>
<RelOp AvgRowSize="73" EstimateCPU="0.00367094" EstimateIO="0" EstimateRebinds="43701.6" EstimateRewinds="0" EstimateRows="1.00182" LogicalOp="Assert" NodeId="55" Parallel="false" PhysicalOp="Assert" EstimatedTotalSubtreeCost="39.4443">
<OutputList>
<ColumnReference Column="Expr1065" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="PartNum" />
<ColumnReference Column="Expr1027" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="MtlPartNum" />
</OutputList>
<Assert StartupExpression="false">
<RelOp AvgRowSize="73" EstimateCPU="0.00367094" EstimateIO="0" EstimateRebinds="43701.6" EstimateRewinds="0" EstimateRows="1.00182" LogicalOp="Inner Join" NodeId="56" Parallel="false" PhysicalOp="Nested Loops" EstimatedTotalSubtreeCost="39.4443">
<OutputList>
<ColumnReference Column="Expr1065" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="PartNum" />
<ColumnReference Column="Expr1027" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="MtlPartNum" />
</OutputList>
<NestedLoops Optimized="false">
<OuterReferences>
<ColumnReference Column="Expr1065" />
<ColumnReference Column="Recr1023" />
<ColumnReference Column="Recr1024" />
<ColumnReference Column="Recr1025" />
<ColumnReference Column="Recr1026" />
</OuterReferences>
<RelOp AvgRowSize="73" EstimateCPU="0.000437016" EstimateIO="0" EstimateRebinds="43701.6" EstimateRewinds="0" EstimateRows="1" LogicalOp="Compute Scalar" NodeId="57" Parallel="false" PhysicalOp="Compute Scalar" EstimatedTotalSubtreeCost="0.000437016">
<OutputList>
<ColumnReference Column="Expr1065" />
<ColumnReference Column="Recr1023" />
<ColumnReference Column="Recr1024" />
<ColumnReference Column="Recr1025" />
<ColumnReference Column="Recr1026" />
</OutputList>
<ComputeScalar>
<DefinedValues>
<DefinedValue>
<ColumnReference Column="Expr1065" />
<ScalarOperator ScalarString="[Expr1064]+(1)">
<Arithmetic Operation="ADD">
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1064" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(1)" />
</ScalarOperator>
</Arithmetic>
</ScalarOperator>
</DefinedValue>
</DefinedValues>
<RelOp AvgRowSize="73" EstimateCPU="0.000437016" EstimateIO="0" EstimateRebinds="43701.6" EstimateRewinds="0" EstimateRows="1" LogicalOp="Lazy Spool" NodeId="58" Parallel="false" PhysicalOp="Table Spool" EstimatedTotalSubtreeCost="0.000437016">
<OutputList>
<ColumnReference Column="Expr1064" />
<ColumnReference Column="Recr1023" />
<ColumnReference Column="Recr1024" />
<ColumnReference Column="Recr1025" />
<ColumnReference Column="Recr1026" />
</OutputList>
<Spool Stack="true" PrimaryNodeId="0" />
</RelOp>
</ComputeScalar>
</RelOp>
<RelOp AvgRowSize="40" EstimateCPU="7.92129E-06" EstimateIO="0" EstimateRebinds="43700.6" EstimateRewinds="0" EstimateRows="79.2129" LogicalOp="Compute Scalar" NodeId="62" Parallel="false" PhysicalOp="Compute Scalar" EstimatedTotalSubtreeCost="39.4401">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="PartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="MtlPartNum" />
<ColumnReference Column="Expr1027" />
</OutputList>
<ComputeScalar>
<DefinedValues>
<DefinedValue>
<ColumnReference Column="Expr1027" />
<ScalarOperator ScalarString="[Recr1025]-(1)">
<Arithmetic Operation="SUB">
<ScalarOperator>
<Identifier>
<ColumnReference Column="Recr1025" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(1)" />
</ScalarOperator>
</Arithmetic>
</ScalarOperator>
</DefinedValue>
</DefinedValues>
<RelOp AvgRowSize="36" EstimateCPU="0.384354" EstimateIO="14.1888" EstimateRebinds="43700.6" EstimateRewinds="0" EstimateRows="79.2129" LogicalOp="Eager Spool" NodeId="63" Parallel="false" PhysicalOp="Index Spool" EstimatedTotalSubtreeCost="39.094">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="PartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="MtlPartNum" />
</OutputList>
<Spool>
<SeekPredicateNew>
<SeekKeys>
<Prefix ScanType="EQ">
<RangeColumns>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="MtlPartNum" />
</RangeColumns>
<RangeExpressions>
<ScalarOperator ScalarString="[Recr1024]">
<Identifier>
<ColumnReference Column="Recr1024" />
</Identifier>
</ScalarOperator>
</RangeExpressions>
</Prefix>
</SeekKeys>
</SeekPredicateNew>
<RelOp AvgRowSize="36" EstimateCPU="0.422568" EstimateIO="2.50312" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="384010" LogicalOp="Index Scan" NodeId="64" Parallel="false" PhysicalOp="Index Scan" EstimatedTotalSubtreeCost="2.92569" TableCardinality="384010">
<OutputList>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="Company" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="PartNum" />
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="MtlPartNum" />
</OutputList>
<IndexScan Ordered="false" ForcedIndex="false" ForceSeek="false" ForceScan="false" NoExpandHint="false">
<DefinedValues>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="Company" />
</DefinedValue>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="PartNum" />
</DefinedValue>
<DefinedValue>
<ColumnReference Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Alias="[i]" Column="MtlPartNum" />
</DefinedValue>
</DefinedValues>
<Object Database="[Epicor905]" Schema="[dbo]" Table="[PartMtl]" Index="[WhereUsed]" Alias="[i]" IndexKind="NonClustered" />
</IndexScan>
</RelOp>
</Spool>
</RelOp>
</ComputeScalar>
</RelOp>
</NestedLoops>
</RelOp>
<Predicate>
<ScalarOperator ScalarString="CASE WHEN [Expr1065]>(100) THEN (0) ELSE NULL END">
<IF>
<Condition>
<ScalarOperator>
<Compare CompareOp="GT">
<ScalarOperator>
<Identifier>
<ColumnReference Column="Expr1065" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(100)" />
</ScalarOperator>
</Compare>
</ScalarOperator>
</Condition>
<Then>
<ScalarOperator>
<Const ConstValue="(0)" />
</ScalarOperator>
</Then>
<Else>
<ScalarOperator>
<Const ConstValue="NULL" />
</ScalarOperator>
</Else>
</IF>
</ScalarOperator>
</Predicate>
</Assert>
</RelOp>
</Concat>
</RelOp>
</Spool>
</RelOp>
</QueryPlan>
</StmtSimple>
</Statements>
</Batch>
</BatchSequence>
</ShowPlanXML>
Schema
A:
Finally figured it out. Because I did a recursive CTE starting with component materials, I created an infinite loop (at least I think it is infinite, or pretty darn close).
Material Part Parent Part
a b
a b
a c
b c
As a quick example, I keep running through the above situation where a Material Part is in Parent Part b & c. So it runs through both of those Parent Parts and then will loop back with b as the Material Part which is in Parent Part c so it will loop through that again unnecessarily. This is why I say I'm not sure if it is infinite. It's doing a ton of redundancy but not sure if there is an end.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
interval of convergence of $e^x$
Can somebody explain how to find the interval of convergence for
$$
e^x=\sum_{n=1}^\infty\frac{x^n}{n!}
$$
I don't fully understand the ratio test/root test/integral test etc. and I don't understand what values to "pull" to get the final answer for the interval of convergance of $e^x$.
A:
It seems that you are asking about the interval of convergence of the series
$$
e^x=\sum_{k=0}^\infty\frac{x^k}{k!}\tag{1}
$$
The ratio test says that the series
$$
\sum_{k=0}^\infty a_k\tag{2}
$$
converges if there exists an $r\lt1$ and a $k_0$ so that for all $k\ge k_0$, we have
$$
\left|\frac{a_{k+1}}{a_k}\right|\le r\tag{3}
$$
Hint: In $(1)$, we have
$$
\left|\frac{a_{k+1}}{a_k}\right|=\left|\frac{x}{k+1}\right|\tag{4}
$$
Consider how $(4)$ relates to $(3)$ when $k\ge2|x|$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JSTL equivalents to jsp tags
I have a search application.
The result of my search is all set as properties in transfer object.
In my processor java class, I am putting the TO in context as:
ctx.putUserData("searchDetailsTO", searchDetailsTO);
Along with above object, several strings are also set as below:
ctx.putUserData("productName", productName);
ctx.putUserData("productNameCriteria", productNameCriteria);
ctx.putUserData("currency", currency);
In my jsp, I am accessing the TO as:
<jsp:useBean id="searchDetailsTO" scope="session" type="com.domain.SearchDetailsTO" />
and accessing the strings as:
<%
String productName =(String)session.getAttribute("productName");
String productNameCriteria =(String)session.getAttribute("productNameCriteria");
String currency =(String)session.getAttribute("currency");
int searchResultsSize = searchDetailsTO.getTotalResults();
SomeTO someTO = new SomeTO();
%>
And later on in the jsp, using above TO and Strings as:
<%
if (productNameCriteria .equals("NAME_BEGINS")) {
%>
<input type="radio" name="productNameCriteria" id="productNameCriteria" value="NAME_BEGINS" CHECKED/><b>Begins With</b>
<input type="radio" name="productNameCriteria" id="productNameCriteria" value="NAME_CONTAINS" /><b>Contains</b>
<input type="radio" name="productNameCriteria" id="productNameCriteria" value="NAME_IS" /><b>Exact Match</b>
<%
} else if (productNameCriteria .equals("NAME_CONTAINS")) {
%>
<input type="radio" name="productNameCriteria" id="productNameCriteria" value="NAME_BEGINS"/><b>Begins With</b>
<input type="radio" name="productNameCriteria" id="productNameCriteria" value="NAME_CONTAINS" CHECKED/><b>Contains</b>
<input type="radio" name="productNameCriteria" id="productNameCriteria" value="NAME_IS" /><b>Exact Match</b>
<%
}
else {
%>
<input type="radio" name="productNameCriteria" id="productNameCriteria" value="NAME_BEGINS"/><b>Begins With</b>
<input type="radio" name="productNameCriteria" id="productNameCriteria" value="NAME_CONTAINS"/><b>Contains</b>
<input type="radio" name="productNameCriteria" id="productNameCriteria" value="NAME_IS" CHECKED/><b>Exact Match</b>
<%
}
%>
And
<%
if (searchResultsSize > 0) {
for (int k = 0; k < searchDetailsTO.getResult().size(); k++) {
someTO = (someTO) searchDetailsTO.getResult().get(k);
%>
<Table>
<TR>
<TD class="gridrow<%=k%2%>" align="center" style="style" width="120">
<%=someTO.getSomething()%>
</TD>
<TD class="gridrow<%=k%2%>" align="left" style="style" width="372">
<A href="#"onclick="loadDetails('<%=someTO.getSomeId()%>', '<%=someTO.getSomethingMore()%>')"; ><%=someTO.getSomethingElse()%></A>
</TD>
</TR>
</Table>
<%
} }
%>
etc. etc.
My javascript function also uses value from TO. Something like:
function someFunc(){
if(option=='goto' && !(pageNum>0 && pageNum<=<%=searchDetailsTO.getTotalPages()%>))
{
alert("Please enter valid Page# (Range 1 to <%=searchDetailsTO.getTotalPages()%>)");
}
I want to switch over to using JSTL and EL and avoid using scriptlets as above.
However, EL and JSTL is kind of greek to me.
(1) What will be the jstl equivalents to above code blocks? Do I need to do some major changes to my backend to achieve the same using JSTL/EL ??
(2) I have some javascript functions in the jsp. Will they be affected by JSTL? For e.g. loadDetails function in above code and someFunc function above which uses the TO in it.
(3) How to call TO's flag functions in jstl/el
<%
if(searchDetailsTO.isPrevious() || searchDetailsTO.isNext()) {
%>
using
c:if test="${(searchDetailsTO.isPrevious()) or (searchDetailsTO.isNext())}"
is not working
I tried using
<c:when>
on the if else code for radio buttons above, however, I started getting 3 rows of 3 buttons (9 buttons).
Thanks for reading!!
A:
First import taglib for jstl <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Second..
For if..else use c:choose and c:when / c:otherwise.
For for use c:forEach.
To declare variable use c:set
To get data from session use ${pageContext.session.varName}. (replace varName with name of session data you want to get)
To get size in loop use fn:length(dataList). (to use this you need to import functions taglib <%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>)
To use jstl you need to add 2 jars in your project that are jstl.jar and standard.jar
JSTL will not affect java script behavior.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get value from datagridview combobox?
How to get value from datagridview combobox after selected value is changed?
A:
You can use:
var value = DataGridView.Rows[0].Cells[0].Value
NOTE: You would supply the correct row and cell number.
Or you can do something like this if it is bound to an object like ListItem
string value = DataGridView.Rows[RowIndex].Cells[ColumnIndex].Value.ToString();
if DataGridView.Rows[RowIndex].Cells[ColumnIndex] is DataGridViewComboBoxCell && !string.IsNullOrEmpty(value))
{
List<ListItem> items = ((DataGridViewComboBoxCellDataGridView.Rows[RowIndex].Cells[e.ColumnIndex]).Items.Cast<ListItem>().ToList();
ListItem item = items.Find(i => i.Value.Equals(value));
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to move to a separate file?
I've got a couple of animations as storyboards in window resources.
Is there a way to move them to a separate file and still access them?
If yes, please tell me how.
Just to be clear, I want to move the following generated code from my MainWindow.xaml file to a separate file so I can keep code tidy and organized:
<Window.Resources>
<Storyboard x:Key="sbShowWindow">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" Storyboard.TargetName="layoutRoot">
<EasingDoubleKeyFrame KeyTime="0" Value="0.874">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseInOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseInOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)" Storyboard.TargetName="layoutRoot">
<EasingDoubleKeyFrame KeyTime="0" Value="0.874">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseInOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseInOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="layoutRoot">
<EasingDoubleKeyFrame KeyTime="0" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseInOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseInOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="layoutRoot">
<EasingDoubleKeyFrame KeyTime="0" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseInOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseInOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="layoutRoot">
<EasingDoubleKeyFrame KeyTime="0" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseIn"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="0.595">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseIn"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseIn"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="sbHideWindow">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" Storyboard.TargetName="layoutRoot">
<EasingDoubleKeyFrame KeyTime="0" Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="0.874">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)" Storyboard.TargetName="layoutRoot">
<EasingDoubleKeyFrame KeyTime="0" Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="0.874">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="layoutRoot">
<EasingDoubleKeyFrame KeyTime="0" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="layoutRoot">
<EasingDoubleKeyFrame KeyTime="0" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode="EaseOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="layoutRoot">
<EasingDoubleKeyFrame KeyTime="0" Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<CubicEase EasingMode="EaseIn"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="0.245">
<EasingDoubleKeyFrame.EasingFunction>
<CubicEase EasingMode="EaseIn"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<CubicEase EasingMode="EaseIn"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
A:
You can put this code into a separate resource dictionary, either in the same assembly, or in another one. Then all you need is to add that dictionary into merged dictionaries collection of window's resources:
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Folder/YourResourceDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
Here's the syntax of pack URIs.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
vba VarType to distinguish between String and Integer
I am preparing a function in VBA to create a query to search a database. One of the parameters, "Value", can be a string (e.g.: "ON") or a number (e.g.: 123), if it's a string, I have to select values different from it (e.g.: "OFF") and if it's a number, I have to select values larger than it (e.g.: 234).
I have prepared the function summarised below, passing the value to compare "valueParam" as a Variant, then trying to detect if "valueParam" is a String or an Integer. The problem is that the function VarType treat each time "valueParam" as a String.
Function prepareQuery(ByVal valueParam As Variant) as String
Dim STR_Query as String
STR_Query = "Select * FROM tablename"
If VarType(valueParam) = vbInteger Then
STR_Query = STR_Query & " WHERE Value>" & valueParam
ElseIf VarType(valueParam) = vbString Then
STR_Query = STR_Query & " WHERE Value<>'" & valueParam & "'"
End If
prepareQuery = STR_Query
End Function
Has anyone an idea of why VarType does not recognise the Integer or has another idea to distinguish between numbers and strings?
Thank you very much
A:
You are probably entering the number in a String. Use IsNumeric to transform it beforehand or change your function call.
If IsNumeric(valueParam) Then
valueParam = CLng(valueParam) 'or CDbl, depending on what you want ...
End If
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.