text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
How to sort an array of object using object's key?
I am trying to write an function to sort an array like this:
[
{score:10, name:foo},
{score:-10, name:bar},
{score:0, name:newNAME}
]
into
[
{rank:1, score:10, name:foo},
{rank:2, score:0, name:newNAME},
{rank:3, score:-10, name:bar}
]
But i found it is difficult to access the key(using score to sort and add a rank into each object).Is anyone can give me some hints to write such function?
A:
You can use a custom sort and Array.prototype.map to add extra key rank to the array of objects.
let arr = [{
score: 10,
name: "foo"
}, {
score: -10,
name: "bar"
}, {
score: 0,
name: "newNAME"
}];
arr.sort((c1, c2) => {
return c2.score - c1.score;
});
arr = arr.map((val, index) => {
val.rank = index + 1;
return val;
})
console.log(arr);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to generate random vector in Spark
I want to generate random vectors with norm 1 in Spark.
Since the vector could be very large, I want it to be distributed, And since data in RDD has no order, I want to store the vector in the form of RDD[(Int, Double)], because I also need to use this vector to do some matrix-vector multiplication.
So how could I generate this kind of vector?
Here is my plan for now:
val v = normalRDD(sc, n, NUM_NODE)
val mod = GetMod(v) // Get the modularity of v
val res = v.map(x => x / mod)
val arr:Array[Double] = res.toArray()
var tuples = new List[(Int, Double)]()
for (i <- 0 to (arr.length - 1)) {
tuples = (i, arr(i)) :: tuples
}
// Get the entries and length of the vector.
entries = sc.parallelize(tuples)
length = arr.length
I think it not elegant enough because it goes through a "distributed -> single node -> distributed" process.
Is there any way better? Thanks:D
A:
try this:
import scala.util.Random
import scala.math.sqrt
val n = 5 // insert length of your array here
val randomRDD = sc.parallelize(for (i <- 0 to n) yield (i, Random.nextDouble))
val norm = sqrt(randomRDD.map(x => x._2 * x._2).sum())
val finalRDD = randomRDD.mapValues(x => x/norm)
| {
"pile_set_name": "StackExchange"
} |
Q:
Identity management framework in ASP.NET
A new application is being built with an Angular Client and a ASP.Net Web API back end. The back end will be consumed by the Angular Client only in the short term (1 year), but will be consumed externally (mobile and 3rd parties) in the long run.
What are the pros and cons of using ASP.NET Identity vs IdentityServer4 initially in securing the API? How difficult will it be to switch over to IdentityServer from ASP.NET Identity down the road and is it worth the effort of using IdentityServer from the beginning.
A:
ASP.NET Identity is a user store, with some helper libraries that enable cookie authentication on top of it. Using ASP.NET Identity to protect HTTP APIs is not what it was designed for.
IdentityServer 4 is an OAuth & OpenID Connect authorization server. Using IdentityServer to protect HTTP APIs is exactly what it was designed for.
| {
"pile_set_name": "StackExchange"
} |
Q:
Send API-key inside HTML Form
So I have an API Key for my Webservice. Everytime a user registers I send him an email for him to verify his account. This looks like this:
public class EmailSender {
private static final String username = "[email protected]";
private static final String password = "uthoughiwillshowyoumypassword?";
public static void sendVerificationCode(String receiverusername, String receiveremail, String code) throws Exception {
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true"); //TLS
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
MimeMessage message = new MimeMessage(session);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiveremail));
message.setSubject("Verification Code");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("<form action=\"https://pathtomywebserviceurl.com/verify/"+code+"\">\n" +
"<input type=\"submit\" value=\"Verify\" />\n" +
"</form>", "UTF-8", "html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
}
When he clicks on the button the user actually makes a request to my webservice with his token as a parameter. But now I want also that my API-Key is send as eg. an http header so that I can extract the API-Key from the user verify request and check if the API-Key equals to the actually API-Key. Right now I only send the code but not the API-Key.
A:
Use a hidden form element:
<input type="hidden" id="myApiKey" name="myApiKey" value="myApiKeyValue">
| {
"pile_set_name": "StackExchange"
} |
Q:
Ошибка переноса проекта
Перенёс проект из репозитория на компьютер. После переноса всплывает ошибка.
Вроде как все должно решаться просто, но не выходит.
Build.gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.0'
classpath 'com.jakewharton.sdkmanager:gradle-plugin:0.10.0'
classpath 'me.tatarka:gradle-retrolambda:3.2.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Текст ошибки:
ERROR: Failed to install the following Android SDK packages as some licences have not been accepted. build-tools;28.0.3 Android SDK
Build-Tools 28.0.3 platforms;android-28 Android SDK Platform 28 To
build this project, accept the SDK license agreements and install the
missing components using the Android Studio SDK Manager.
Alternatively, to transfer the license agreements from one workstation
to another, see http://d.android.com/r/studio-ui/export-licenses.html
Using Android SDK: C:\Users\jone1\AppData\Local\Android\Sdk Install
missing SDK package(s)
A:
"Tools"->"SDK Manager".
На вкладке "SDK Tools" поставьте галочку "Show Package Details".
Убедитесь, что в разделе "Android SDK Build-Tools", рядом с версией 28.0.3 стоит галочка.
Если отметите ее, он предложит скачать после нажатия на "ОК". Необходимо будет принять лицензию.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to generate "make install" action using gyp?
I'm using gyp to generate makefiles for my project. Makefiles work, cause working binaries to pop up in "out" directory, all is dandy here.
However, I would like my makefiles to have some "standard" actions/targets, namely "install" "uninstall", and "clean".
I've added "install" target to .gyp files, but I have doubts if that is the correct way of doing that, especially that it seems there is no way to exclude "install" target from "all" in make using gyp.
I am also wondering if there is a tool to generate ./configure files for gyp, or if those should be written by developer and only run gyp with some needed options.
What is the correct way to add those targets ("install"...) to makefiles generated by gyp? Can it be made in such way, that once specified those actions will work with other build systems too? (ninja, etc.)
A:
The best way I found to do it, is to generate makefiles with gyp in subdirectory of project directory, and then have manually written makefile with "install", "clean" etc. targets that executes Makefile generated by gyp.
To make sure that gyp is called with proper arguments, I call it from ./configure
Directory structure:
+ build
|- Makefile (generated by gyp)
|- Makefile (written by hand)
|- configure (written by hand)
|- build.gyp (written by hand)
./configure:
#!/bin/bash
PREFIX=/usr/local
BUILDTYPE=Release
for i in "$@"
do
case $i in
-p=*|--prefix=*)
PREFIX="${i#*=}"
;;
esac
case $i in
-b=*|--buildtype=*)
BUILDTYPE="${i#*=}"
;;
esac
done
gyp -D prefix="$PREFIX" -D configuration="$BUILDTYPE" --depth=. --generator-output=./build -f make
echo -e "prefix=$PREFIX\n" > ./config.mk
Makefile:
include config.mk
prefix ?= /usr/local
builddir=build/out
abs_builddir := $(abspath $(builddir))
all: config.mk
$(MAKE) -C "./build" builddir="$(abs_builddir)"
binaries=$(prefix)/bin/foo $(prefix)/bin/bar
$(binaries): $(prefix)/bin/%: $(builddir)/%
cp $< $@
install: $(binaries) $(directories)
# $(directories), uninstall, clean, .PHONY, etc.
build.gyp:
{
'variables': {
},
'target_defaults': {
// (...)
},
'targets': [
{
'target_name': 'foo',
'type': 'executable',
'defines': [],
'include_dirs':[
'src/headers'
],
'sources': [
'src/foo.c'
],
'libraries': [
'-lcrypto'
]
},
// (...)
]
}
And then, all I need to do to install is classic and inimitable:
./configure --prefix="/home/me/local_builds"
make
make install
| {
"pile_set_name": "StackExchange"
} |
Q:
ROW_NUMBER() OVER (PARTITION BY giving Syntax error in mysql5.7
I am using partition by to get duplicate rows and this query returning syntax error in mysql5.7
select column1,ROW_NUMBER() OVER (PARTITION BY column2, column3 ORDER BY column2 DESC) as RowNumber
from tableA
Error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(PARTITION BY column1, column2 ' at line 1
Or any other query
Or any other query that retrun the only rows that duplicates(both column2 and column 3 contains same values repectivley) in this case the output will return row 1, 3, 5, 6
All rows in table:
Desired output by query:
Thanks for your help.
A:
With EXISTS:
select t.* from tablename t
where exists (
select 1 from tablename
where column1 <> t.column1 and column2 = t.column2 and column3 = t.column3
)
| {
"pile_set_name": "StackExchange"
} |
Q:
Learning Audio Manipulation
I want to learn how applications like CakeWalk, Cubase, and ProTools are built. Are there any good resources out there to learn this type of development?
Resources
Digital Signal Processing Basics
A:
If you want to learn about how the capabilities of these programs are implemented (I'm talking about filtering, synthesis, mixing, etc.), read as much as you can about digital signal processing (DSP). If you happen to be in a position to take a DSP class at a college or university, you'd probably get a lot of good information out of that. (I've taken a couple such classes myself and they were fantastic) Beyond that, there are dozens of books and research papers out there concerning various aspects of DSP; just try to find a good one (or several) and dive in. A Google search can definitely get you started.
If you want to know more about audio programming in general, i.e. how to access the operating system's audio resources (microphone/speakers/etc.), I guess I could echo Dan's suggestion of looking at Audacity...
| {
"pile_set_name": "StackExchange"
} |
Q:
Thread-Safety in a class
Please can you have a look at the following code and advise whether ClassA is thread-safe or not? If it is not thread-safe, could you please advise where it is breaking?
public class ClassA {
private List<Player> players;
public ClassA() {
this.players = Collections.synchronizedList(new ArrayList<Player>());
}
public Player play(Player player){
int score = 0;
.
.
.
if (players.contains(player)) {
player = players.get(players.indexOf(player));
player.addScore(score);
} else {
player.addScore(score);
players.add(player);
}
return player;
}
}
A:
No, it is not.
For example, two threads could fail the players.contains test and both add their version of a player (a better way would just add the player every time to a set). Also, unless Player.addScore is thread-safe, score adding could be subtly wrong.
Synchronizing over the whole play method (and reverting of players to a normal list) would solve these problems.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to print a string without including '\n' in Python
Suppose my string is:
' Hai Hello\nGood eve\n'
How do I eliminate the '\n' in between and make a string print like :
Hai Hello Good eve
?
A:
If you don't want the newline at the end of the print statement:
import sys
sys.stdout.write("text")
A:
You can use the replace method:
>>> a = "1\n2"
>>> print a
1
2
>>> a = a.replace("\n", " ")
>>> print a
1 2
A:
In Python 2.6:
print "Hello.",
print "This is on the same line"
In Python 3.0
print("Hello", end = " ")
print("This is on the same line")
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Extend a Bounty?
I have put up a bounty here worth 100 reputation. Its going to expire in few hours from now.
However till date I have not received the relevant answers,
I would like to extend the bounty to another week and also increase the bounty reputation by a substantial value.
Is this possible? How do I go about doing this?
A:
http://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/
This is effectively completed, because
bounty system is no longer tied to accepting an answer in any way
you can issue multiple bounties on your question if necessary
| {
"pile_set_name": "StackExchange"
} |
Q:
Tensor of inertia of a hollow cube
I have found the tensor of inertia of a rectangle of sides $a$ and $b$ and mass $m$, around its center, to be $$I_{11}=ma^2/12,$$ $$I_{22}=mb^2/12,$$ $$I_{33}=(ma^2 + mb^2)/12.$$ All other elements of that tensor are equal to zero. I would now like to use this result to determine the tensor of inertia of a hollow cube of side a around its center of mass.
I realise I have to use the parallel axis theorem. I also knoww that the correct equation is I$_{11}$=I$_{22}$=I$_{33}$=ma$^2$/12+ma$^2$/12+ma$^2$/6+4(ma$^2$/12 + m(a/2)$^2$)=5/3*ma$^2$
I simply do not understand why this is correct. Could anyone please explain why this is the correct way to calculate the desired tensor of inertia? Also, why would I be summing all the diagonal elements in my tensor for the rectangle?
A:
We will work in units where the mass of each face is $1$ and where the length of the side of the cube is $1$.
The contribution to the moment of inertia of each of the top and bottom faces is, using your result for the moment of inertia of a rectangle, $\frac{1}{6}$.
By symmetry, each of the four other faces has the same contribution to the moment of inertia. Let's calculate the contribution of one of them. Let's project the system along the axis about which we are calcuating the moment of inertia. This operation has no effect on the moment of inertia. Our face now becomes a rod. We know the moment of inertia through the center of the rod is $\frac{1}{12}$, but we are calculating the moment of inertia at a distance $\frac{1}{2}$ away from the center of the rod. Using the parallel axis theorem, we get that the moment of inertia is $\frac{1}{12} + (\frac{1}{2})^2 = \frac{4}{12} = \frac{1}{3}$. Then our total moment of inertia is $\frac{1}{6} + \frac{1}{6} + 4*\frac{1}{3}= \frac{5}{3}$. (The first two terms come from the top and bottom face, the last term comes from the four side faces.)
Putting units back in we get the moment of inertia is $I=\frac{5}{3} M a^2$, where $M$ is the mass of a face and $a$ is the side length of the cube (also the side length of a face).
| {
"pile_set_name": "StackExchange"
} |
Q:
Errno 22 Invalid Argument Python
I'm trying to copy one file's content to another, and error appears, what do i do wrong?
for file in os.listdir('offer'):
if '.css' in file:
print(file)
with open(f'offer/{file}', 'r+') as f:
with open('offer/id.css', 'w+') as style_file:
shutil.copyfile(f'offer/{f}', f'offer/{style_file}')
Traceback (most recent call last):
File "C:/Users/Katerina/Desktop/python/test_attempt.py", line 50, in <module>
shutil.copyfile(f'offer/{f}', f'offer/{style_file}')
File "C:\Users\Katerina\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 120, in copyfile
with open(src, 'rb') as fsrc:
OSError: [Errno 22] Invalid argument: "offer/<_io.TextIOWrapper name='offer/id.css' mode='r+' encoding='cp1251'>"
A:
I guess you are looking for something like
with open('offer/id.css', 'w') as style_file:
for file in os.listdir('offer'):
if '.css' in file:
#print(file)
with open(f'offer/{file}', 'r+') as f:
for line in f:
style_file.write(line)
The purpose of shutil.copyfile is different; it doesn't really allow you to access or modify the contents of either file, it just copies one to the other.
| {
"pile_set_name": "StackExchange"
} |
Q:
If $S$ is subnormal in $G$, $S$ is simple and nonabelian and $S \subseteq H \subseteq G$, then $S \subseteq \textrm{Soc}(H)$.
I suspect I have missed some easier way to show this claim, and there might be a mistake in my approach. I know this is a very lengthy proof, but I spent a lot of time on trying to solve this problem and I have tried to make my solution clear and easy to read, so I would really appreciate if someone checked my approach. Still, a different solution will be appreciated as well.
This is a part of exercise 2A.7. in Isaacs' finite group theory, which is:
If $S$ is subnormal in a finite group $G$ and $S$ is simple and nonabelian, then $S^G$ is a minimal normal subgroup of $G$.
The hint points out that we should first show that if a subgroup $H$ of $G$ satisfies $S \subseteq H$, then $S \subseteq \textrm{Soc}(H)$, and that we should should do this by induction on the order of $G$. I can do the rest of this exercise, but I've had some trouble showing this claim mentioned in the hint is true.
My attempt at proving this claim:
1, Suppose $G = S$. Then $S$ normal in $G$, and thus it's a minimal normal subgroup, and so it is contained in the socle of $G$, so the claim is true in this case.
2, By induction, suppose the claim is true in any $\tilde{G}$ of order less than $k$ satisfying the assumptions, and suppose $G$ is of order $k$ and satisfies the assumptions. Let $H$ be a subgroup such that $S \subseteq H < G$. Then $S$ is subnormal in $H$ by Lemma 2.3., and since the order of $H$ is lower than the order of $G$, we see that $S$ is contained in the socle of $H$ by the induction hypothesis.
3, It remains to show that $S \subseteq \textrm{Soc}(G)$. If $S$ is normal in $G$, then this is clear, so we can assume it is not.
4, First we will show that $S$ is contained in a normal subgroup $M$ of $G$, and this $M$ is a direct product of non-abelian simple groups.
Since $S$ is subnormal in $G$, we can find a subgroup $S_1$ such that $S$ is subnormal in $S_1$ and $S_1$ is normal in $G$, and we can assume that $S_1$ is strictly smaller than $G$. By the induction hypothesis, we see that $S$ is contained in the socle of $S_1$.
By an previous exercise, we know that the socle of a finite group can be expressed as a direct product of simple groups, so we have $S \subseteq A_1 \times ... \times A_n$. If we consider the projection $\pi_i : A_1 \times ... A_n \rightarrow A_i$, then we see that $\pi_i (S)$ is a subgroup of $A_i$, and because it's an homomorphic image of $S$, it is either $S$ or $1$, because $S$ is simple. It follows that if $A_i$ is an abelian simple group, then $\pi_i(S)$ must be $1$, as otherwise $A_i$ would contain the nonabelian subgroup $S$. Thus, we can conclude that $S$ is contained in some $A_{l_1} \times ... \times A_{l_m} \subseteq A_1 \times ... \times A_n = \textrm{Soc}(S_1)$, where $A_{l_j}$ are non-abelian simple groups.
Notice that the socle of $S_1$ is normal in $G$, because it is characteristic in $S_1$ and $S_1$ is normal in $G$. Consider the subgroup $M \subseteq \textrm{Soc}(S_1)$ that is generated by all non-abelian simple subgroups that are normal in $\textrm{Soc}(S_1)$. This subgroup is characteristic in $\textrm{Soc}(S_1)$ by definition, it contains $A_{l_1} \times ... \times A_{l_m}$, and it is also expressible as a direct product of simple non-abelian groups. It follows that $S \subseteq A_{l_1} \times ... \times A_{l_m} \subseteq M_1 \times ... M_r = M$ (in fact, $A_{l_1} \times ... \times A_{l_m}= M$ because by the same argument as previously, the projection of $M$ to $A_i$ is $1$ for all $A_i$ abelian, but that isn't necessary to show), where $M_i$ are simple, non-abelian, normal subgroups of $\textrm{Soc}(S_1)$.
5, We will now show that $M \subseteq \textrm{Soc}(G)$, which also shows that $S\subseteq \textrm{Soc}(G)$.
5.1, Suppose that some $M_i$ aren't contained in $\textrm{Soc}(S_1)$. Then each such $M_i$ satisfies $M_i \cap \textrm{Soc}(G) = 1$, because $M_i \cap \textrm{Soc}(G)$ is normal in $M_i$ (because $\textrm{Soc}(G)$ is normal in $G$), so the intersection must be $1$ or $M_i$, as $M_i$ is simple. Take the subgroup $L=M_{k_1} \times ... \times M_{k_t} \subseteq M$ of all such $M_i$. Then $L \cap \textrm{Soc}(G) = 1$, because the this intersection is a normal subgroup of $L$, its intersection with each $M_{k_i}$ is trivial, and thus all the projections of $L \cap \textrm{Soc}(G)$ into $M_{k_i}$ are contained in the center of $M_{k_i}$, which is trivial. For more detail, see
Why is a normal subgroup of $G_1\times G_2$ with trivial intersections with $G_1$ and $G_2$ is abelian?
5.2 We have shown that $L = M_{k_1} \times .. \times M_{k_t} \subseteq M$ has a trivial intersection with $ \textrm{Soc}(G)$. We will now show that $L$ is normal, which is a contradiction - it contains a minimal normal subgroup that has a trivial intersection with $\textrm{Soc}(G)$, which is a contradiction.
Consider an element $g \in G$. The subgroup $M$ is normal in $G$, and so conjugation of $M$ by $g$ can be expressed as automorphism $\varphi : M \rightarrow M$. We will show that $\varphi$ permutes the subgroups $M_i$. An automorphism preserves normality, so $\varphi(M_i)$ is a normal, simple subgroup of $M$, and all $M_i$ are normal and simple in $M$ too, so either $\varphi(M_i) \cap M_j =1$, or $\varphi(M_i) = M_j$. If $\varphi(M_i) = M_j$ for some $j$, we are done, so we will suppose $\varphi(M_i) \cap M_j =1$ for all $j$ and derive a contradiction. The subgroup $\varphi(M_i)$ is a normal subgroup of $M$, it has a trivial intersection with all $M_i$, and so it is contained in the direct product of the centers of $M_i$ - for more detail, again see
Why is a normal subgroup of $G_1\times G_2$ with trivial intersections with $G_1$ and $G_2$ is abelian?
i.e. $\varphi(M_i) \subseteq Z(M_1) \times ... \times Z(M_n)$. But $M_i$ are all non-abelian and simple, so $\varphi(M_i)$ is the trivial subgroup, which is a contradiction. Thus, we see that $\varphi(M_i) = M_j$ for some $j$.
A nice, simple example to give some intuition behind this claim - for a non-abelian simple group $Q$, if we take the diagonal injection $q \mapsto (q,q)$ of $Q$ into $Q \times Q$, then this subgroup is not normal in $Q \times Q$.
5.3, Now since $\textrm{Soc}(G)$ is normal, we see that if $M_i \subseteq \textrm{Soc}(G)$, then $\varphi(M_i) =(M_i)^g \subseteq \textrm{Soc}(G)$. It follows that if we consider the group $L$ described in 5.1, $L=M_{k_1} \times ... \times M_{k_t}$ where $M_{k_i}$ are all such $M_i$ in $M=M_1 \times ... \times M_n$ that are not contained in $\textrm{Soc}(G)$, then by the previous sentence we see that $\varphi(M_{k_i}) =(M_{k_i})^g =M_{k_j} \subseteq L$, so $\varphi(L) = L$, and thus $L$ is normal in $G$.
This shows that $L$ is a non-trivial, normal subgroup of $G$, that has a trivial intersection with $\textrm{Soc}(G)$, which is a contradiction. Thus, there cannot be any $M_i$ in $M$ that is not contained in $\textrm{Soc}(G)$, and so $M \subseteq \textrm{Soc}(G)$. Since $S \subseteq M$, it follows that $S \subseteq \textrm{Soc}(G)$, which finishes the proof.
A:
I think it might be easier to prove the whole thing by induction on $|G|$. We prove that for any subnormal nonabelian simple subgroup $S$ of $G$, $S^G$ is a minimal normal subgroup of $G$ and is the direct product of the distinct conjugates of $S$ in $G$.
So suppose $S \lhd \lhd H \lhd G$, and let $K = S^H$. Then by induction $K = S_1 \times \cdots \times S_r$ is minimal normal in $H$, where the $S_i$ are the distinct conjugates of $S$ in $H$.
Now let $K = K_1,K_2,\ldots,K_t$ be the distinct conjugates of $K$ in $G$. These are all minimal normal in $H$, disjoint, and have trivial centres, so they generate their direct product, and hence $S^G = K^G = K_1 \times \cdots \times K_t$.
The critical fact that you need is that the only normal subgroups of a direct product of nonabelian simple groups $T_i$ are the direct products of some of the direct factors. To prove that, consider the projection of a normal subgroup $N$ onto one of the factors $T_i$. This is either trivial or the whole $T_i$, and in the second case, we get $[N,T_i] =T_i \le N$.
So we see now that $S^G = K_1 \times \cdots \times K_t$ is the direct product of the distinct conjugates of $S$ in $G$ and, since the only normal subgroups of $S^G$ are direct products of some of these conjugates, it follows that $S ^G$ is a minimal normal subgroup of $G$. This also proves the claim in the hint that $S \le {\rm Soc}(G)$.
Answers to questions: For any two groups $G$ and $H$, we have $Z(G \times H) = Z(G) \times Z(H)$. Nonabelian simple groups have trivial centres, and hence so do direct products of nonabelian simple groups. So $Z(K_i) = 1$.
Yes, you are correct in saying that the fact that $\langle K^G \rangle = K_1 \times \cdots \times K_t$ requires $Z(K_i) = 1$, and your proof of this is also correct. This is not true in general for abelian simple groups.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to handle HTTP code 4xx responses in fetch api
I was wondering how we should handle 400 from backend when we use ajax function. We can make if statement in promise resolve function and check if res status is 400. Different approach is making wrapper service for fetch, and when we got 400 from server we throw exception. How to deal with that problem ?
A:
I'd suggest a wrapper that checks response.ok which will be true if the response code is 2xx.
Note this statement from the MDN page on fetch():
An accurate check for a successful fetch() would include checking that
the promise resolved, then checking that the Response.ok property has
a value of true. An HTTP status of 404 does not constitute a network
error.
Here is a wrapper like this:
function fetchData() {
return fetch.apply(null, arguments).then(function(response) {
if (!response.ok) {
// create error object and reject if not a 2xx response code
var err = new Error("HTTP status code: " + response.status);
err.response = response;
err.status = response.status;
throw err;
}
return response;
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
format axis tick labels
I'm using a map chart where area's are colored based on a percentage. The legend shows a mapping between the colors and their percentages. But the legend only shows numbers, not percentages. It should be obvious that these numbers are percentages. So there should be a % symbol after each number or a % symbol at the top of the chart.
It seems there is such a thing as chart tick formatting but I cannot find a way to change it. Maybe this could be done with stacklabels I would expect something like this with d3.js. I tried this with highCharts, but it seems to ignore these properties.
I also tried changing the format properties of several other objects. Changing it on the legend object get's you closest, but it's only one text on the wrong position.
Edit: something that complicates this is that I don't think the chart has an x or y-axis. Instead there's a colorAxis object. Maybe it's possible to add text with CSS3 with the itemStyle property.
A:
Its pretty simple, all you need to do is use formatter
xAxis: {
labels: {
formatter: function() {
return this.value+"%";
}
},
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Scikit-Learn Classification and Regression with Weights
How can I do classification or regression in sklearn if I want to weight each sample differently? Is there a way to do it with a custom loss function? If so, what does that loss function look like in general? Is there an easier way?
A:
To weigh individual samples, feed a sample_weight array to the estimator's fit method. This should be a 1-d array of length n_samples (i.e. the same dimension as y in most tasks):
estimator.fit(X, y, sample_weight=some_array)
Not all models support this, check the documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make a string variable literal?
You know how you make a string literal or "escaped" with the @ sign right?
string foo = @"\escaped\string"
I was searching all over the internet, and I cannot find a way to make a string variable do that. If you are curious why I want to do that, here is a bit of backstory:
I was making a C# addon for my batch script, which would base64 a string and save it in a file. However, I kept getting an error by the name of "Illegal characters in path name" or something among those lines. So naturally, I went away googling and the only "fix" I could find is to @ the string. However, the problem is, I don't have just a simple plain text string variable. I get the location of the executable and then put it into a variable, so I can create the file right where the executable is located (the same folder). And, as I said previously, I cannot do that, because of weird path errors. I tried String.Replace and Regex.Escape but none of them worked, because it seems like the error is right when I call the function to get the location. For reference, this is the "command" I'm using to get the location of the executable.
System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location)
And yes, I did try other tricks, like AppDomain.CurrentDomain.BaseDirectory and a bit more but none of them seem to work.
Any way to solve this? I'm getting really frustrated because this is supposed to be easy...
A:
Maybe you could try using the static methods Path.Combine when working with string/path manipulation.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the use case of declaring functions methods within bodies other functions?
I came across this piece in FreeRTOS source:
void vApplicationIdleHook( void )
{
/* The simple blinky demo does not use the idle hook - the full demo does. */
#if( mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 0 )
{
extern void vFullDemoIdleHook( void );
//* Implemented in main_full.c. */
vFullDemoIdleHook();
}
#endif
}
Why would one declare functions/methods like this? What is the advantage? I have seen similar code in Java as well.
A:
I am assuming that this is the only place in the project where vFullDemoIdleHook is used, so it's clear & concise to just keep the declaration and function call all in these few lines of code.
What would be the advantage of putting the declaration elsewhere? Consider the alternative... this is probably what you're more used to seeing:
/* The simple blinky demo does not use the idle hook - the full demo does. */
#if( mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 0 )
extern void vFullDemoIdleHook( void );
#endif
void vApplicationIdleHook( void )
{
/* The simple blinky demo does not use the idle hook - the full demo does. */
#if( mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 0 )
{
//* Implemented in main_full.c. */
vFullDemoIdleHook();
}
#endif
}
I see no advantage to this
| {
"pile_set_name": "StackExchange"
} |
Q:
is $\mathbb{Q} ^{|\mathbb{R}|} \times \{1 \}$ divisible subgroup of $ \mathbb{Q} ^{|\mathbb{R}|} \times \mathbb{Z}_2$?
According to Unit Groups of Classical Rings by Karpilovsky, p.107 we know that:
If $F$ is a real-closed field, then $F^*\simeq \mathbb{Q} ^{|F|} \times \mathbb{Z}_2$.
Now, we know that $\mathbb{R}$ is a real-closed field. So we should have $\mathbb{R}^*\simeq \mathbb{Q} ^{|\mathbb{R}|} \times \mathbb{Z}_2$.
Also we know that $\mathbb{R}^*$ is not divisible but there is a divisible maximal subgroup $(\mathbb{R}^*)^+$ of $\mathbb{R}^*$. So there must exists a divisible maximal subgroup of $\mathbb{Q} ^{|\mathbb{R}|} \times \mathbb{Z}_2$ corresponding to $R^+$.
I think this divisible maximal subgroup is $\mathbb{Q} ^{|\mathbb{R}|} \times \{1 \}$, but I don't know how I should prove the divisibility of $\mathbb{Q} ^{|\mathbb{R}|} \times \{1 \}$.
A:
Being a direct product of copies of $\mathbb{Q}$, the subgroup you are considering is divisible. Given $y=(x_c)_{c\in \mathbb{R}}$ in the group and an integer $n$, define $y'=(x_c/n)_{c\in\mathbb{R}}$. Then $ny'=y$, so the divisibility condition is satisfied. Indeed, the $\mathbb{Q}^{|\mathbb{R}|}$ factor is $\mathbb{R}^+$, and the $\mathbb{Z}_2$ factor is $\{-1,1\}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
figsize has no impact on Figures in Jupyter Notebook
this question is similar to others but in the end I can't find a way to make figsize works in Jupyter Notebook. I am probably missing something
I have a plot and I would like it to appear as a square.
However, it has a rectangular shape and I can't change it with figsize.
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1, 6],[9, 4], "o")
plt.xlim(0,10)
plt.ylim(0,10)
plt.figure(figsize=(1,1))
I tried with and without the first line and I tried various numbers in figsize but nothing happens, my plot stays the same.
Thanks for your help!
A:
Insert:
plt.axes([1, 1, .7, 1])
before your plot (below the import), this will set the axis of the plot, and you can play around with the numbers to make it larger/smaller
The axes is specified by: [left, bottom, width, height]
| {
"pile_set_name": "StackExchange"
} |
Q:
What stands in the way of rapid mass transportation in Faerûn?
The level of technology and civilization in Faerûn seems similar to early modern Europe just before the industrial revolution. However, there is strong magic in the setting. There are some powerful city-states who can certainly afford the services of powerful wizards, so why is the transportation system so undeveloped? It is basically limited to sailing ships on water, and long walks or slow, ox-driven carriages on muddy and unkept roads. Not that there would be no need for it, there is trade between the major cities, but it is still done the slow and tedious way (weeks spent traveling by cart).
If there is powerful enough magic to change the weather, teleport, summon matter from nothing, why is the transportation system so undeveloped? What stands in the way of making "magitech" trains, aircraft, or just hire a wizard to teleport a vehicle to the destination town?
A:
Amongst other reasons, the culture of Faerûn has developed in and supports a more-or-less feudal system. It's basically never in the local lord's interest to increase the mobility of the populace.
Peasants that can easily (and safely - the wilderness is full of danger) travel from place to place might decide to migrate to somewhere with lower taxes, less political oppression, or even better weather.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trouble getting data from a URL in another PHP script
I have two PHP scripts. The first displays an HTML page based on a variable (noob.php?id=2). It has a form in it, and sends the data to the second script (not displayed to the user) which updates a database based on the given info. However, I need the "id" variable from the URL. I've tried using the $_GET['id'] function, but get an undefined index error.
A:
In the form on the first page add:
<INPUT type="hidden" name="id" value="<?=$_GET['id']?>">
| {
"pile_set_name": "StackExchange"
} |
Q:
Добавление нескольких значений в одну запись MySQL
Ребят нужен ваш совет, есть таблица заказов с записями. Так же есть таблица продуктов. В запись заказа нужно добавлять продукты (неограниченное количество). Как лучше это делать? До записывать данные в одну запись не хотеться, создавать большое количество столбцов под продукты тоже. Какие ещё есть варианты?
A:
Создать связывающею таблицу:
Номер заказа
Продукт
Кол-во
Праймери ключ - первые два поля
Запрос From из трех таблиц, в Where сравниваем номер заказа и продукт между таблицами. Получим все заказы и продукты, что можно отфильтровать если нужны не все а только определенного заказа.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to rank an Object using views and date of creation and like count?
Lets say you have an object of Type Item and it has attributes of name, view_count, like_count and a created_at time, and I want to create a feed of these objects so that I can still get the latest objects but also according to the view count and like count.
Using a sorting by created at time and by rank = view_count + like_count like
a.sort_by{|x| [x.rank, -x.created_at]}
will result in sorting by rank then by created_at which will be only used in ties of objects, so I was hoping someone could help me figure out a way in doing so.
Thank you in advance.
A:
First off: if you have a lot of objects/records you'll probably want to be doing the ordering in the database so that you can properly filter them out. This will have a couple advantages in most cases:
1) You can limit the number of items you fetch after sorting them (meaning you don't have to load as many into memory)
2) If you're using indexes properly, it will be very fast
Ordering by multiple rows is straight forward, and explained in the answers to this question: Ruby on Rails: how do I sort with two columns using ActiveRecord?
As far as the actual sorting goes, if you'd like to sort the array in memory the code you gave should work:
a.sort_by{|x| [x.rank, -x.created_at]}
Could you explain what the problem is? This seems like it sorts by the rank, and then by the time, as you specified. Where you looking to sort by another means (such as some score made up by the rank and how recent the item is)?
Edit:
Alright, so by your comment you wish to make a score that mixes rank with how recent the item is. This will be a tricky subject, for several reasons. First off, exactly how you model/score the results will be up to you, and you'll have to tweak it accordingly (so maybe it will be some fraction of Time.now - item.created_at multiplied by the rank, or something. It will basically be something you'll have to play with).
On second thought, it might be better to just use the unix-style timestamp, rather than Time.now - item.created_at, because, unless somebody severely messes with your security, the higher the number, the more recent it will be. (Epoch issues notwithstanding). Plus this might make other things easier later on.
For example, maybe it would be something like:
rank*(item.created_at - 1300000000)/60000000,
which for the current time would result in 0.7453 * rank, and for an item made a day from now would result in: 0.7467 * rank (so a bit higher). Maybe your solution would be something more complex. It's really up to you to figure out an equation that works for your situation.
The other issue is it might make your SQL queries and indexes a bit more complex (though you can index a table based on multiple columns with math (i.e. your scoring system) included; here's an example: http://use-the-index-luke.com/sql/where-clause/obfuscation/math; this may seem a bit trickier for you because how recent it is will constantly be changing, so maybe it should just be a function of the timestamp itself (which increases with time, so recent items will inherently have higher values)).
Basically, your first step will be figuring out exactly what sort of mathematical model best suits your needs. Experiment a bit. After that you'll just have to get things efficiently implemented up in Rails (correct database queries, indexes, etc.)
| {
"pile_set_name": "StackExchange"
} |
Q:
PDF Script Tool - adds JavaScripts to PDF files
This is a Windows Forms application that adds JavaScripts to PDF files. It supports multiple files at the same time. Right now, the only supported script is a "time-stamp on print" script, but any others I add in the future would work exactly the same in principle.
My company uses the "time-stamp on print" script for time-sensitive documents. We originally manually added the script to each individual PDF document, then switched to an Adobe Acrobat Pro batch process script. The licenses for Acrobat Pro are expensive, and it can be buggy/slow, so we are looking for a better solution. While I was working on that, figured I might as well make it a GUI app with room to expand for future needs (and open-source third-party use).
I tried a somewhat new method for limiting the length of lines in this project. In short, I inserted a line break before each parameter to a method. Let me know if the code is readable or not (because of the line breaking or any other reasons).
PdfScriptTool
using iTextSharp.text.exceptions;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.draw;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static PdfScriptTool.PdfScriptToolConstants;
namespace PdfScriptTool
{
internal partial class PdfScriptTool : Form, IProgress<ProgressReport>
{
#region Folders
private static string RootPath = Path.Combine(
Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments),
RootFolderName);
private static string ConfigurationPath = Path.Combine(
RootPath,
ConfigurationFolderName);
private static string OutputRootPath = Path.Combine(
RootPath,
OutputFolderName);
private static string ProcessingPath = Path.Combine(
RootPath,
ProcessingFolderName);
private static string TimeStampScriptPath = Path.Combine(
ConfigurationPath,
TimeStampScriptFileName);
#endregion Folders
internal PdfScriptTool()
{
InitializeComponent();
InitializeOpenFileDialog();
Directory.CreateDirectory(RootPath);
Directory.CreateDirectory(OutputRootPath);
Directory.CreateDirectory(ConfigurationPath);
Directory.CreateDirectory(ProcessingPath);
}
private static string TimeStampScript
{
get
{
var timeStampScript = string.Empty;
if (File.Exists(TimeStampScriptPath))
{
using (var reader = new StreamReader(TimeStampScriptPath))
{
timeStampScript = reader.ReadToEnd();
}
}
else
{
timeStampScript = DefaultTimeStampScript;
}
return timeStampScript;
}
}
public void Report(ProgressReport progressReport)
{
if (InvokeRequired)
{
Invoke((Action)(() => Report(progressReport)));
}
else
{
progressBar.Value = progressReport.Percent;
progressLabel.Text = progressReport.CurrentCount
+ ProgressLabelDivider + progressReport.Total;
}
}
private async Task PerformTask(Task task)
{
if(documentsView.CheckedItems.Count > 0)
{
try
{
await task;
}
catch(Exception e)
{
MessageBox.Show("Exception: " + e.Message);
}
progressBar.Value = 0;
progressLabel.Text = string.Empty;
Enabled = true;
}
else
{
MessageBox.Show("Please select at least one document.");
}
}
private static string GetOutputPath(string inputPath)
{
return Path.Combine(OutputRootPath, Path.GetFileName(inputPath));
}
// TODO
private string ConvertToPdf(string filename)
{
string pdfPath = Path.Combine(
ProcessingPath,
Path.GetFileNameWithoutExtension(filename) + ".pdf");
return pdfPath;
}
private void InitializeOpenFileDialog()
{
openFileDialog.Filter = OpenFileDialogFilter;
openFileDialog.Multiselect = OpenFileDialogAllowMultiple;
openFileDialog.Title = OpenFileDialogTitle;
}
private void selectDocuments_Click(object sender, EventArgs e)
{
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult == DialogResult.OK)
{
foreach (var file in openFileDialog.FileNames)
{
documentsView.Items.Add(file, DocumentsViewFileIsChecked);
}
}
}
private async void timeStampDocuments_Click(object sender, EventArgs e)
{
await PerformTask(TimeStampPdfs());
}
private Task TimeStampPdfs() => Task.Run(() =>
{
for (int i = 0; i < documentsView.CheckedItems.Count; i++)
{
if (!string.Equals(
Path.GetExtension(
documentsView.CheckedItems[i].ToString()),
".pdf",
StringComparison.InvariantCultureIgnoreCase))
{
documentsView.CheckedItems[i] = ConvertToPdf(
documentsView.CheckedItems[i].ToString());
}
TimeStampPdf(documentsView.CheckedItems[i].ToString());
Report(new ProgressReport
{
Total = documentsView.CheckedItems.Count,
CurrentCount = i + 1
});
}
}).ContinueWith(t =>
{
MessageBox.Show("Timestamped all files.");
},
CancellationToken.None,
TaskContinuationOptions.OnlyOnRanToCompletion,
TaskScheduler.FromCurrentSynchronizationContext()
);
private void TimeStampPdf(string filename)
{
try
{
using (var pdfReader = new PdfReader(filename))
{
using (var pdfStamper = new PdfStamper(
pdfReader,
new FileStream(
GetOutputPath(filename),
FileMode.Create)))
{
var parentField = PdfFormField.CreateTextField(
pdfStamper.Writer,
false,
false,
0);
parentField.FieldName = TimeStampFieldName;
var lineSeparator = new LineSeparator();
for (var pageNumber = PdfFirstPageNumber;
pageNumber <= pdfReader.NumberOfPages;
pageNumber++)
{
var pdfContentByte = pdfStamper.GetOverContent(
pageNumber);
var textField = new TextField(
pdfStamper.Writer,
new iTextSharp.text.Rectangle(
TimeStampFieldTopLeftXCoordinate,
TimeStampFieldTopLeftYCoordinate,
TimeStampFieldBottomRightXCoordinate,
TimeStampFieldBottomRightYCoordinate),
null);
var childField = textField.GetTextField();
parentField.AddKid(childField);
childField.PlaceInPage = pageNumber;
}
pdfStamper.AddAnnotation(parentField, 1);
var pdfAction = PdfAction.JavaScript(
TimeStampScript,
pdfStamper.Writer);
pdfStamper.Writer.SetAdditionalAction(
PdfWriter.WILL_PRINT,
pdfAction);
}
}
}
catch (InvalidPdfException e)
{
MessageBox.Show(e.Message + " " + filename);
}
}
}
}
ProgressReport
using static PdfScriptTool.PdfScriptToolConstants;
namespace PdfScriptTool
{
internal class ProgressReport
{
public int CurrentCount { get; set; }
public int Percent
{
get
{
return PercentMultiplier * CurrentCount / Total;
}
}
public int Total { get; set; }
}
}
PdfScriptToolConstants
namespace PdfScriptTool
{
internal static class PdfScriptToolConstants
{
internal const string DefaultTimeStampScript
= "var f = this.getField('Timestamp');"
+ "f.alignment = 'left';"
+ "f.multiline = false;"
+ "f.textSize = 11;"
+ "f.richText = true;"
+ "var style = f.defaultStyle;"
+ "style.fontFamily = ['Calibri', 'sans-serif'];"
+ "f.defaultStyle = style;"
+ "var t = new Array();"
+ "t[0] = new Object();"
+ "t[0].text = 'Uncontrolled 24 hours after ';"
+ "t[1] = new Object();"
+ "t[1].text = util.printd('mm/dd/yy h:MM tt', new Date());"
+ "f.richValue = t;";
internal const string RootFolderName = "PDFScriptTool";
internal const string OutputFolderName = "Output";
internal const string ConfigurationFolderName = "Configuration";
internal const string ProcessingFolderName = "Processing";
internal const string TimeStampScriptFileName = "TimeStampScript.txt";
internal const string OpenFileDialogFilter
= "Documents (*.pdf)|*.pdf";
internal const string OpenFileDialogTitle = "Select documents...";
internal const bool OpenFileDialogAllowMultiple = true;
internal const bool DocumentsViewFileIsChecked = true;
internal const string TimeStampFieldName = "Timestamp";
internal const int PdfFirstPageNumber = 1;
internal const int TimeStampFieldTopLeftXCoordinate = 36;
internal const int TimeStampFieldTopLeftYCoordinate = 792;
internal const int TimeStampFieldBottomRightXCoordinate = 576;
internal const int TimeStampFieldBottomRightYCoordinate = 756;
internal const int TimeStampFieldUnderlineLeftXCoordinate = 36;
internal const int TimeStampFieldUnderlineRightXCoordinate = 576;
internal const int TimeStampFieldUnderlineYCoordinate = 768;
internal const int PercentMultiplier = 100;
internal const string ProgressLabelDivider = " of ";
}
}
A:
It's time to get through separation of concerns.
Whatever you are trying to do with your PDFs, your form is not the place to do it.
At the very least you should move the functionality to a different class with static methods.
If you do that you will realise that TimeStampPdfs() will need two parameters.
One is the list of the files that you need to process, and the other is the component that does the report on IProgress interface,
in this case that is your form.
Continuing, will also realise that if sometime will want to use this class on web for instance you can not have any
MessageBox showing on TimeStampPdf, so we will just remove that try catch
lineSeparator and pdfContentByte are never being used there. Remove them.
Some folks like to write nested using statements without defining a new scope (increasing the indentation),
I learned with those folks and I now prefer that way.
I will not clutter my answer with a lot of code since you should be able to do most of the refactoring,
but I will still give an implementation of TimeStampPdfs
public static Task<IEnumerable<string>> TimeStampPdfs(IEnumerable<string> files,
IProgress<ProgressReport> progress) => Task.Run(() =>
{
int i = 0;
int count = files.Count();
var list = new List<string>();
foreach (var file in files)
{
string outFile = file;
if (!".pdf".Equals(Path.GetExtension(file),
StringComparison.InvariantCultureIgnoreCase))
{
outFile = ConvertToPdf(file);
}
list.Add(outFile);
TimeStampPdf(outFile);
progress.Report(new ProgressReport
{
Total = count,
CurrentCount = ++i
});
}
return list;
});
The usage on the form should be something along the lines of:
private async void timeStampDocuments_Click(object sender, EventArgs e)
{
var files = documentsView.CheckedItems.Cast<object>().Select(o => o.ToString());
try{
await PerformTask(TimeStampPdfs(files));
}catch(Exception e){
//when you work with tasks you normally get AggregateExceptions
//catch your exception according to its type
//at the moment you don't have a way to tell which file failed, I will leave that on your side
MessageBox.Show(e.Message);
}
//my answer to your previous question also missed the opportunity to show the message here
MessageBox.Show("Timestamped all files.");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Possible to pass a Map object to HQL
Is it possible to pass a whole map object to a HQL query without iterating over it? I would if I have to but thought there might be a cleaner way.
For example:
def aMap = ["foo":"bar", "bar":"foo"]
Foo.executeQuery("select p from p where p.bar in (:mapObj)", [mapObj: aMap])
Then have it automatically uses the key on the aMap?
If I try it it just throws this error:
Remember that ordinal parameters are
1-based!
A:
That cryptic error says executeQuery() just expects a different Map as a last parameter - with a different data type or key names.
No, it won't automatically use Map's keys. If it ever did, I'd suppose that it should use values() instead. Anyway, it would be counter-intuitive.
So just use aMap.keySet(), it is about the absolute minimum of overhead you can get from Map.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Change Sql Developer's Encoding?
Whenever I try to change the character encoding on Sql Developer a loading symbol appears:
I have not been able to change the encoding anywhere in the program. How can I change the encoding to UTF-8?
A:
I had to change my jdk to java 7
| {
"pile_set_name": "StackExchange"
} |
Q:
Time overlaps from Nesting queries
Based on the current schema I have been asked to find
-- people who were untested and exposed to some one infectious
-- Do not list anyone twice and do not list known sick people
-- Exposed = at the same place, and overlap in time (No overlap time needed for simplicity)
From the query below I find my answer except I cannot remove the people who are 'postive' because the second part my query i.e the time lapse depends on the first part i.e the time the positive people went to the same locations.
select * from (
select DISTINCT person.PersonID, Register.LocID, Register.Checkin, Register.CheckOut
from person
join Register on Person.PersonID = Register.PersonID
join testing on person.PersonID = testing.PersonID
where testing.Results is 'Positive' ) a
join (
SELECT DISTINCT Person.PersonID, Register.LocID , Register.Checkin, Register.CheckOut
from person join Register on Person.PersonID = Register.PersonID
where person.PersonID
not in (SELECT DISTINCT testing.PersonID from testing)) b on a.LocID = b.LocID
and b.checkin >= a.CheckIn and b.CheckIn <= a.CheckOut
So my question is, What modification does this query need to show the results of the results of the second part only?
I consider the first part to be
select * from (
select DISTINCT person.PersonID, Register.LocID, Register.Checkin, Register.CheckOut
from person
join Register on Person.PersonID = Register.PersonID
join testing on person.PersonID = testing.PersonID
where testing.Results is 'Positive' ) a
And the second part to be
join (
SELECT DISTINCT Person.PersonID, Register.LocID , Register.Checkin, Register.CheckOut
from person join Register on Person.PersonID = Register.PersonID
where person.PersonID
not in (SELECT DISTINCT testing.PersonID from testing)) b on a.LocID = b.LocID
and b.checkin >= a.CheckIn and b.CheckIn <= a.CheckOut
A:
For readability you can create CTEs like this:
with
-- returns all the untested persons
untested as (select p.* from person p left join testing t on t.personid = p.personid where t.testingid is null),
-- returns all the infected persons
infected as (select * from testing where results = 'Positive'),
-- returns all the locids that infected persons visited and the start and dates of these visits
loc_positive as (
select r.locid, i.timestamp startdate, r.checkout enddate
from register r inner join infected i
on i.personid = r.personid and i.timestamp between r.checkin and r.checkout
)
-- returns the distinct untested persons that visited the same locids with persons tested positive at the same time after they were tested
select distinct u.*
from untested u
inner join register r on r.personid = u.personid
inner join loc_positive lp on lp.locid = r.locid
where lp.startdate <= r.checkout and lp.enddate >= r.checkin
| {
"pile_set_name": "StackExchange"
} |
Q:
Insert into with variables php mysql
Im having some trouble getting my SQL query to 'insert into' my database, is it allowed to use variables as table name, field name, and values?
Here my code:
$nameOfDBFromA = "vagtplanA" . $_GET["from"];
$flytnedToQ1 = $con->prepare("SELECT * FROM $nameOfDBToA WHERE ansatId='$_GET[ansatId]' ORDER BY id DESC");
$flytnedToQ1->execute();
$flytnedTo1 = $flytnedToQ1->fetch();
$nameOfFieldToA1 = "a" . $_GET["to"] . "1";
$nameOfFieldToA2 = "a" . $_GET["to"] . "2";
$nameOfFieldToA3 = "a" . $_GET["to"] . "3";
$nameOfFieldToA4 = "a" . $_GET["to"] . "4";
$nameOfFieldToA5 = "a" . $_GET["to"] . "5";
$nameOfFieldToA6 = "a" . $_GET["to"] . "6";
$nameOfFieldToA7 = "a" . $_GET["to"] . "7";
$redigeringsTidspunkt = date("j M Y");
$flytnedTA = $con->prepare(
"INSERT INTO $nameOfDBFromA
(ansatId, edit, $nameOfFieldToA1, $nameOfFieldToA2,
$nameOfFieldToA3, $nameOfFieldToA4, $nameOfFieldToA5,
$nameOfFieldToA6, $nameOfFieldToA7)
VALUES($_GET[ansatId], $redigeringsTidspunkt,
$flytnedTo1[$nameOfFieldToA1], $flytnedTo1[$nameOfFieldToA2],
$flytnedTo1[$nameOfFieldToA3], $flytnedTo1[$nameOfFieldToA4],
$flytnedTo1[$nameOfFieldToA5], $flytnedTo1[$nameOfFieldToA6],
$flytnedTo1[$nameOfFieldToA7]) ")
or die(mysql_error());
$flytnedTA->execute();
SOLVED! I just put my arrays into it own variable
$intoVarToA1 = $flytnedTo1[$nameOfFieldToA1];
$intoVarToA2 = $flytnedTo1[$nameOfFieldToA2];
$intoVarToA3 = $flytnedTo1[$nameOfFieldToA3];
$intoVarToA4 = $flytnedTo1[$nameOfFieldToA4];
$intoVarToA5 = $flytnedTo1[$nameOfFieldToA5];
$intoVarToA6 = $flytnedTo1[$nameOfFieldToA6];
$intoVarToA7 = $flytnedTo1[$nameOfFieldToA7];
A:
One of your mistakes is when you want to access a value in an array inside of a string, you can't do:
"$flytnedTo1[$nameOfFieldToA1]"
You have to do it like this:
"{$flytnedTo1[$nameOfFieldToA1]}" // use curly brackets
| {
"pile_set_name": "StackExchange"
} |
Q:
Global mouse hook on click events in X11
I've read a lot of information about X11 graphic system and found a lot of questions about this issue without answer. So let me ask onу more time.
I need classic implementation of hook mechanism (like SetWindowsHookEx) or any other approach in UNIX-like operation systems with ONLY ONE CONDITION : ability to listen events without blocking original event (like XGrabButton and XUngrabButton do).
P.S. Ben, this is Danila. I need help! ®
A:
I've ended up by grabbing source code from Xnee - it allows record all input events, including keyboard and mouse with non-blocking logic. The only restriction is that I have to ask if there any events in loop with 100ms interval, but it's ok for me - there is no processor loading at all.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create Sub menu through Clickonce
It's known that clickonce creates an entry point of the application in Start->Programs->PublisherName->ProductName. But is it possible to create a sub-menu after the PublisherName? For example, I have two clickonce applications which currently shows up in the Start->Programs like this:
Start->Programs->XYZ->Application.exe // This is a trial version of the app
Start->Programs->XYZ Corporation->Application.exe // This is the full version of the app
I need to change this into:
Start->Programs->XYZ Corporation->TrialVersion->Application.exe
|
->FullVersion->Application.exe
I can't get a screenshot of what I meant. I hope my question is clear. Is this possible in clickonce?
EDIT
Just came to know about another clickonce application Blu which can be downloaded from here. This application creates a sub menu after the PublisherName.
A:
If you are using VS2010 or VS2012, you can specify a Suite Name in addition to Publisher and Product Name. The Suite Name will appear on the start menu between the publisher (the top menu entry under Start) and the product name.
For example, if you set Company Name to "MyCompany", SuiteName to "MySuite", and product name to "MyProduct", you will see MyCompany under start menu, MySuite under the MyCompany folder, and MyProduct under the MySuite folder.
| {
"pile_set_name": "StackExchange"
} |
Q:
Referring to an object's ID in a jQuery append statement
I have this element:
<div class="isthisyou" id="unique_identifier"></div>
I want to use jQuery to insert a link into the div:
$('isthisyou').append('<a href="auth/create_account/'+this.id+'">Is this you?</a>');
Right now this.id is returning undefined instead of unique_identifier. What am I doing wrong?
Thanks!
A:
There's always this
$this = $('.isthisyou');
$this.append('<a href="auth/create_account/'+$this.attr('id')+'">Is this you?</a>');
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add item to list using a thread
I have a list of reservations, but some ones has a conflict (they are booked in the same day for the same room). In order to solve this problem, I want to create a new list without conflicts. I can change only the room number, but not the reservation date, so I do that in the following method:
public List<Reservation> ResolveConflicts()
{
var groupedReservationByDate = _reservations.GroupBy(reservation => reservation.CheckInDate);
var resolvedReservations = new List<Reservation>();
foreach (var reservations in groupedReservationByDate)
{
foreach (var currentReservation in reservations)
{
var nextReservations = reservations.Skip(reservations.ToList().IndexOf(currentReservation) + 1)
.ToList();
foreach (var nextReservation in nextReservations)
{
if (currentReservation.RoomNumber == nextReservation.RoomNumber)
{
var thread = new Thread(() => ChangeRoomNumber(reservations, currentReservation));
thread.Start();
}
}
resolvedReservations.Add(currentReservation);
}
}
return resolvedReservations;
}
private void ChangeRoomNumber(IEnumerable<Reservation> reservations, Reservation currentReservation)
{
var roomNumber = GetRoomNumber();
foreach (var reservation in reservations)
{
if (roomNumber == reservation.RoomNumber)
roomNumber = GetRoomNumber();
}
currentReservation.RoomNumber = roomNumber ;
}
private int GetRoomNumber()
{
var randomNumber = new Random();
return randomNumber.Next(1, _reservations.MaxBy(reservation => reservation.RoomNumber).RoomNumber);
}
When I do that with a thread, I get a kind of correct list, but is not correct, that returned list should have no conflicts. The same output is produced when I use Thread.Sleep(1000) Console output with reservation conflicts using a thread.
And if I don't use a thread, the returned list is totally incorrect, for the same room are a lot of conflicts Console output with reservation conflicts without using a thread.
I think is a problem with the thread, the algorithm is correct or at least I hope is correct.
A:
Thanks to Kevin, I've solved the problem:
Without looking very far, your ChangeRoomNumber method is broken. You get a random room number, then iterate over the reservations and generate a new room number if the previous number was already assigned. This is wrong, if you generate a new number then you have to check all the reservations over again – @Kevin Gosse
The solution is:
private void ChangeRoomNumber(List<Reservation> reservations, Reservation currentReservation)
{
while (IsConflict(reservations, currentReservation))
currentReservation.RoomNumber = GetRoomNumber();
}
private bool IsConflict(IEnumerable<Reservation> reservations, Reservation currentReservation)
{
return reservations.Any(reservation =>
!ReferenceEquals(reservation, currentReservation) &&
reservation.RoomNumber == currentReservation.RoomNumber);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ListView layout not showing elements
Hello dear Stackoverflow community. I'm coming to you for help, as you can guess.
I have a ListView for which each row should follow this layout, row_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="@color/brownish">
<ImageView
android:id="@+id/passport_flag"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="6dp"
android:contentDescription="@string/country_flag" />
<TextView
android:id="@+id/exp_date"
android:layout_width="wrap_content"
android:layout_height="16dip"
android:ellipsize="marquee"
android:singleLine="true"
android:text="@string/exp_date"
android:textSize="12sp"
android:textColor="@color/white"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginStart="6dp" />
<TextView
android:id="@+id/birth_date"
android:layout_width="wrap_content"
android:layout_height="16dip"
android:ellipsize="marquee"
android:singleLine="true"
android:text="@string/birth_date"
android:textSize="12sp"
android:textColor="@color/white"
android:layout_above="@+id/exp_date"
android:layout_alignStart="@+id/exp_date" />
<TextView
android:id="@+id/document_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:layout_alignStart="@+id/exp_date"
android:layout_above="@id/birth_date"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:text="@string/document_number"
android:textSize="16sp"
android:textColor="@color/white" />
</RelativeLayout>
I implemented a custom ArrayAdapter, for which here is the code:
public class CustomArrayAdapter extends ArrayAdapter<EPassport> {
public static final String TAG = "CustomArrayAdapter";
private final String DOCUMENT_NUMBER = "Passport number: ";
private final String DATE_OF_BIRTH = "Date of birth: ";
private final String DATE_OF_EXPIRY = "Date of expiry: ";
private Context context;
private List<EPassport> ePassportsList;
private static class ViewHolder {
public TextView documentNumber;
public TextView birthDate;
public TextView expDate;
public ImageView flag;
}
public CustomArrayAdapter(Context context, List<EPassport> ePassportsList) {
super(context, R.layout.row_layout, ePassportsList);
this.context = context;
this.ePassportsList = ePassportsList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater =
(LayoutInflater) context
.getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row_layout, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.documentNumber = (TextView) rowView.findViewById(R.id.document_number);
viewHolder.birthDate = (TextView) rowView.findViewById(R.id.birth_date);
viewHolder.expDate = (TextView) rowView.findViewById(R.id.exp_date);
viewHolder.flag = (ImageView) rowView.findViewById(R.id.passport_flag);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
EPassport rowPassport = this.ePassportsList.get(position);
holder.expDate.setText(DATE_OF_EXPIRY + rowPassport.getDateOfExpiry());
holder.birthDate.setText(DATE_OF_BIRTH + rowPassport.getDateOfBirth());
holder.documentNumber.setText(DOCUMENT_NUMBER + rowPassport.getDocumentNumber());
if (rowPassport.getCountryCode() != null) {
String alpha2CountryCode = null;
try {
alpha2CountryCode = ISO3166Database.getAlpha2Code(rowPassport.getCountryCode());
} catch (IllegalCountryCodeException e) {
Log.e(TAG, e.getLocalizedMessage());
}
holder.flag.setImageResource(
getContext()
.getResources()
.getIdentifier(alpha2CountryCode, "drawable", getContext().getPackageName()));
}
return rowView;
}
}
I work with Android Studio 1.4 and the 'Design' tab of my row_layout.xml looks exactly how I want it to be.
When I run the application however, of the three text fields only one shows up on the screen.
I can't figure out the why. If anyone would like to give me a hand with this one, it would be greatly appreciated.
Image of the row layout as rendered by android studio:
(Click image to enlarge)
Image as shown on the screen:
A:
Try to use this as row:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF664747"
android:padding="8dp">
<TextView
android:id="@+id/documentNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Document number: " />
<TextView
android:id="@+id/birthDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/documentNumber"
android:paddingTop="12dp"
android:text="Birth date: " />
<TextView
android:id="@+id/expireDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/birthDate"
android:text="Expire date: " />
<ImageView
android:id="@+id/passportFlag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/documentNumber"
android:src="@android:drawable/ic_dialog_email" />
</RelativeLayout>
Just change your data and color.
| {
"pile_set_name": "StackExchange"
} |
Q:
React - Components to create and update db model, inheritance or composition?
I'm relatively new to React. My use case implies a create page for a database model and an update page. I have a lot of duplicate code in those and coming from regular OOP design I would create a base class for it and let the two component inherit.
However, after reading several forums, I saw that you should mostly prefer composition over inheritance with React. Would that also apply in this use case? It seems odd to model this via composition.
A:
I think composition also applies to your use case. From what I understand you will have almost the same page for update and create, all your model files will be the same in both cases. So you can make a reusable component, some form. And use it in create and update page, just perform the right action for each of them.
| {
"pile_set_name": "StackExchange"
} |
Q:
dmidecode show 6 * 8GB DIMM but free -m only show 16GB?
I have CentOS 6.4 running on the top of HP ProLiant BL460c G7 blade server. I have 6 * 8GB DIMM memory installed on HP blade server.
When i use dmidecode --type memory, i get the following output
Handle 0x1000, DMI type 16, 23 bytes
Physical Memory Array
Location: System Board Or Motherboard
Use: System Memory
Error Correction Type: Single-bit ECC
Maximum Capacity: 192 GB
Error Information Handle: Not Provided
Number Of Devices: 6
Handle 0x1001, DMI type 16, 23 bytes
Physical Memory Array
Location: System Board Or Motherboard
Use: System Memory
Error Correction Type: Single-bit ECC
Maximum Capacity: 192 GB
Error Information Handle: Not Provided
Number Of Devices: 6
Handle 0x1100, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: No Module Installed
Form Factor: DIMM
Set: 1
Locator: PROC 1 DIMM 1D
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: Unknown
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: Unknown
Configured Clock Speed: Unknown
Handle 0x1101, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 8192 MB
Form Factor: DIMM
Set: 2
Locator: PROC 1 DIMM 2A
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: 2
Configured Clock Speed: 1333 MHz
Handle 0x1102, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: No Module Installed
Form Factor: DIMM
Set: 3
Locator: PROC 1 DIMM 3E
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: Unknown
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: Unknown
Configured Clock Speed: Unknown
Handle 0x1103, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 8192 MB
Form Factor: DIMM
Set: 4
Locator: PROC 1 DIMM 4B
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: 2
Configured Clock Speed: 1333 MHz
Handle 0x1104, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: No Module Installed
Form Factor: DIMM
Set: 5
Locator: PROC 1 DIMM 5F
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: Unknown
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: Unknown
Configured Clock Speed: Unknown
Handle 0x1105, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 8192 MB
Form Factor: DIMM
Set: 6
Locator: PROC 1 DIMM 6C
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: 2
Configured Clock Speed: 1333 MHz
Handle 0x1106, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1001
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: No Module Installed
Form Factor: DIMM
Set: 7
Locator: PROC 2 DIMM 1D
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: Unknown
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: Unknown
Configured Clock Speed: Unknown
Handle 0x1107, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1001
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 8192 MB
Form Factor: DIMM
Set: 8
Locator: PROC 2 DIMM 2A
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: 2
Configured Clock Speed: 1333 MHz
Handle 0x1108, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1001
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: No Module Installed
Form Factor: DIMM
Set: 9
Locator: PROC 2 DIMM 3E
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: Unknown
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: Unknown
Configured Clock Speed: Unknown
Handle 0x1109, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1001
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 8192 MB
Form Factor: DIMM
Set: 10
Locator: PROC 2 DIMM 4B
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: 2
Configured Clock Speed: 1333 MHz
Handle 0x110A, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1001
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: No Module Installed
Form Factor: DIMM
Set: 11
Locator: PROC 2 DIMM 5F
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: Unknown
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: Unknown
Configured Clock Speed: Unknown
Handle 0x110B, DMI type 17, 34 bytes
Memory Device
Array Handle: 0x1001
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 8192 MB
Form Factor: DIMM
Set: 12
Locator: PROC 2 DIMM 6C
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: Not Specified
Serial Number: Not Specified
Asset Tag: Not Specified
Part Number: Not Specified
Rank: 2
Configured Clock Speed: 1333 MHz
but when i type free -m, its just showing 16GB. I don't understand what is the issue here. Please help.
total used free shared buffers cached
Mem: 15914 4697 11216 0 226 3385
-/+ buffers/cache: 1085 14828
Swap: 18095 52 18043
A:
You have to use a 64-bit system to address that much primary memory. The fact that you're able to address anything beyond ~4G is thanks to PAE, which is a way of logically extending the memory map for 32 bit systems. It doesn't scale very far, as you can see.
So reinstall with an amd64 distribution, and you will be able to address the rest of your memory.
| {
"pile_set_name": "StackExchange"
} |
Q:
GIMP Python-Fu plugin will not register if some pdb methods are called
I'm trying to do some batch processing with Python-fu and just can't get my script to work.
When I try to call some methods in pdb, such as pdb.plug_in_nlfilt(), the plug in won't register.
I'm building off the test_batch_invert.py example here. That example works and it processes files as intended, but the code below does not register. All these pdb functions work individually in the python console when I have an image up to process.
Any ideas? Also, when I comment out all the problematic pdb calls and the plugin does register, it shows up grayed out in the menu unless I have an image open. Is there a way to make it functional in the menu without having to manually open another image file?
Thanks everyone!
-- EDIT: Fixed some typos with the name 'layer' but that did not solve it.
#!/usr/bin/env python
# Repurposed from https://github.com/jfmdev/PythonFuSamples (see copyright at bottom)
import os
from gimpfu import *
def process_card(img, layer, inputFolder, outputFolder):
''' Display the message "Hello world" in the bottom of GIMP.
Parameters:
img : image The current image.
layer : layer The layer of the image that is selected.
'''
for file in os.listdir(inputFolder):
try:
# Build the full file paths.
inputPath = inputFolder + "\\" + file
outputPath = outputFolder + "\\" + file
# Open the file if is a JPEG or PNG image.
image = None
if(file.lower().endswith(('.png'))):
image = pdb.file_png_load(inputPath, inputPath)
if(file.lower().endswith(('.jpeg', '.jpg'))):
image = pdb.file_jpeg_load(inputPath, inputPath)
# Verify if the file is an image.
if(image != None):
if(len(image.layers) > 0):
layer = image.layers[0]
# THIS INVERT WORKS
pdb.gimp_invert(layer)
# (image, 2 for replace, x, y, width, height)
pdb.gimp_image_select_rectangle(image, 2, 865, 680, 1270, 2020)
# Including any of the rest of these pdb calls EXCEPT for pdb.file_jpg.save()
# will prevent plugin from registering.
pdb.gimp_selection_invert(image)
pdb.gimp_edit_clear(layer)
# Run alpha trimmed filter 3x
pdb.plug_in_nlfilt(image, layer, 1.0, 1.0, 0)
pdb.plug_in_nlfilt(image, layer, 1.0, 1.0, 0)
pdb.plug_in_nlfilt(image, layer, 1.0, 1.0, 0)
#run optimal smoothing once
pdb.plug_in_nlfilt(image, layer, 1.0, 1.0, 1)
#Edge enhance
pdb.plug_in_nlfilt(image, layer, 0.5, 0.7, 2)
#Select all
pdb.gimp_selection_all(image)
#zealous crop
pdb.plug_in_zealouscrop(image, layer)
#resize image
pdb.gimp_image_scale(image, 600, 955)
pdb.file_jpeg_save(image, layer, outputPath, outputPath, 0.9, 0, 0, 0, "Card", 0, 0, 0, 0)
except Exception as err:
gimp.message("Unexpected error: " + str(err))
register(
"python_fu_process_card",
"Card Scan",
"Process scanned image with jig, output to scaled jpg",
"My library",
"Open source (BSD 3-clause license)",
"2020",
"<Toolbox>/Filters/Process Card",
"*",
[
(PF_DIRNAME, "inputFolder", "Input directory", ""),
(PF_DIRNAME, "outputFolder", "Output directory", "")
],
[],
process_card)
main()
#
# -------------------------------------------------------------------------------------
#
# Copyright (c) 2013, Jose F. Maldonado
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# - Neither the name of the author nor the names of its contributors may be used
# to endorse or promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
Error provided by GIMP verbose output:
Querying plug-in: 'C:\Users\dried\AppData\Roaming\GIMP\2.10\plug-ins\img_BSG_card.py'
C:\Program Files\GIMP 2\bin\gimp-2.10.exe: LibGimpBase-WARNING: gimp-2.10.exe: gimp_wire_read(): error
A:
Works for me, sort of, after a couple of fixes but these aren't the PDB calls:
Your registration declares 2 args (in & out directories) and your function takes 4. There used to be default image and layer args, but the registration mantras have changed a bit over time. Image and layer as the first two args are processed specifically, but if you want them you need to declare them in the registration. The menu location <Toolbox> is deprecated since Gimp 2.6 so your example is vastly outdated.
The "\" as a file separator doesn't work on Linux and OSX. "/" works everywhere, even on Windows, but it is more proper to use os.path.join().
Once this is done the script runs for me (Gimp 2.10.14 on Linux). I assume it looks for file with specific characteristics because if it runs the results are strange :)
The menu is grayed out until you open an image because your image type is "*" which is an image of any type, instead of "" (empty string) that doesn't need any image.
This said, you don't need to register the script/plugin to use it in batch mode, see here for an example.
Some hints to debug Gimp python scripts on Windows here.
PS: as far as I know, the gimp_wire_read(): error message can be ignored, it it not caused by your script/plugin.
| {
"pile_set_name": "StackExchange"
} |
Q:
Displaying NFC card data in Binary, Hex, String, etc
I am working on an Android application for reading NFC cards. I came to a point when I needed to design an abstract class to streamline the process of creating views for visualizing and editing various forms of data by subclassing the abstract class with views like BinaryView, HexView, StringView, et cetera.
I became aware that I wanted to use what I later discovered is named the "Back Stack", so I wrote up a small "testing" application project in Eclipse. developer.android.com kindly provided just what I needed; and after some research I was finally able to discover a reliable way of transmitting data to the child Activity during onCreate, and lastly a method for the parent Activity to accept data from the child Activity via all three finish() equivalents (the Action Bar "back" button, the previously hardware "back" button, and lastly a custom button within the child activity's view).
The following small files are the result of this morning's adventurous discovery:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tests"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="23" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="app_label" >
<activity
android:name=".MainActivity"
android:label="app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ChildActivity"
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
</application>
</manifest>
MainActivity.java
package com.example.tests;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
public static final String EXTRA_LABEL = "extra";
private EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
text = new EditText(this);
text.setText("initial value");
Button button = new Button(this);
button.setText("call");
final MainActivity parent = this;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Activity child = new ChildActivity();
Intent intent = Intents.addStackActivity(parent, child);
intent.putExtra(EXTRA_LABEL, text.getText().toString());
startActivityForResult(intent, ChildActivity.EXTRA_LABEL_CODE);
}
});
layout.addView(button);
layout.addView(text);
this.setContentView(layout);
}
@Override public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ChildActivity.EXTRA_LABEL_CODE) {
runOnUiThread(new Runnable() {
@Override public void run() {
text.setText(data.getStringExtra(ChildActivity.EXTRA_LABEL));
}
});
}
}
}
Intents.java
package com.example.tests;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class Intents {
public static Intent addStackActivity(Context parent, Activity activity) {
int id = 1;
Intent resultIntent = new Intent(parent, activity.getClass());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(parent);
// Adds the back stack
stackBuilder.addParentStack(activity.getClass());
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
parent);
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) parent
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, builder.build());
return resultIntent;
}
}
ChildActivity.java
package com.example.tests;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class ChildActivity extends Activity {
public static final String EXTRA_LABEL = "mwahahaha";
public static final int EXTRA_LABEL_CODE = 12345678;
private EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String data = intent.getExtras().getString(MainActivity.EXTRA_LABEL);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
text = new EditText(this);
text.setText(data);
Button button = new Button(this);
button.setText("return");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setTextResult();
finish();
}
});
layout.addView(button);
layout.addView(text);
this.setContentView(layout);
// setContentView(R.layout.activity_main);
}
private void setTextResult() {
Intent intent = new Intent();
intent.putExtra(ChildActivity.EXTRA_LABEL, text.getText().toString());
this.setResult(ChildActivity.EXTRA_LABEL_CODE, intent);
}
@Override public void onBackPressed() {
setTextResult();
finish();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Before I port this code back into my project, how can it be improved?
A:
Style
You're a little inconsistent about how you're placing your @Overrides. Sometimes, you place them like this:
@Override
public void foo( ... ) {
...
}
Other times, you place them like this:
@Override public void foo( ... ) {
...
}
Personally, I'd prefer the top version, but as long as you're being consistent, either style is probably okay.
The code contained in the file MainActivity.java suffers from a lack of blank lines, and whitespace in general, which makes it very hard to read. I took the liberty of adding a few blank lines, and some whitespace in there, and this was the result:
...
public class MainActivity extends Activity {
public static final String EXTRA_LABEL = "extra";
private EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
text = new EditText(this);
text.setText("initial value");
Button button = new Button(this);
button.setText("call");
final MainActivity parent = this;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Activity child = new ChildActivity();
Intent intent = Intents.addStackActivity(parent, child);
intent.putExtra(EXTRA_LABEL, text.getText().toString());
startActivityForResult(intent, ChildActivity.EXTRA_LABEL_CODE);
}
});
layout.addView(button);
layout.addView(text);
this.setContentView(layout);
}
@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ChildActivity.EXTRA_LABEL_CODE) {
runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText(data.getStringExtra(ChildActivity.EXTRA_LABEL));
}
});
}
}
}
There are more blank lines, but it's overall, much easier to read.
Nitpicks
This line here:
int id = 1;
Should be either of these two things:
A constant.
A function parameter.
I'd personally go with the function parameter, as it's a pain to go and change a constant variable to a different value each time you need it to have a different value, but if id is always going to be equal to 1, then it should probably just look like this:
final int ID = 1;
If there's anything else you want me to review, just mention it in the comments, and I'll see what I can do.
| {
"pile_set_name": "StackExchange"
} |
Q:
Doppler effect in light (Observer moving away from source)
I understand this intuitively and can picture it in my head, but when I do it on paper, the result is a sign difference that I cannot understand
According to this diagram the wavelength = ct-vt = t(c-v)
then the periodic time T = t-(vt/c) which should be t+(vt/c) instead of minus, because the second wavefront takes a longer time to pass the observer, if the error was in the direction, why should the velocity v be negative if the velocity of light in the ---> direction is positive and the observer is moving in the same direction as the light waves? Thanks
A:
For a stationary source the wavelength is $\lambda=cT$. The wavelength does not depend on the motion of the observer. The position of wavefront n is $x=ct-n\lambda=ct-ncT$.
The position of the observer is $x=vt $. Setting those two equal, the observer receives wavefront n at $vt=ct-ncT$ which gives $t_n=\frac{c}{c-v}nT$. Wave front 0 is received at $t_0=0$ and wavefront 1 is received at $t_1=\frac{c}{c-v}T$.
The frequency is the inverse of that so $f_o=\frac{c-v}{c}f_s$ which has the correct sign for an observer moving away from the source.
| {
"pile_set_name": "StackExchange"
} |
Q:
Enforcing rules on "non-type" template parameters
I want to be able to enforce certain rules on the "non-type" template parameters of classes. Is this possible?
For example, consider a templated "Cycle" class that cycles through values of type "TYPE", between the values "MIN" and "MAX".
A basic first step might look something like this:
template <class TYPE, TYPE MIN, TYPE MAX>
class Cycle
{
public:
Cycle() :
m_value(MIN)
{
}
const TYPE & value() const
{
return m_value;
}
void up()
{
if (m_value == m_max)
m_value = m_min;
else
++m_value;
}
void down()
{
if (m_value == m_min)
m_value = m_max;
else
--m_value;
}
private:
TYPE m_value;
static TYPE m_min;
static TYPE m_max;
};
template <class TYPE, TYPE MIN, TYPE MAX>
TYPE Cycle<TYPE, MIN, MAX>::m_min = MIN;
template <class TYPE, TYPE MIN, TYPE MAX>
TYPE Cycle<TYPE, MIN, MAX>::m_max = MAX;
How would I change the above so that the rule MIN <= MAX always holds? I.e. How do I make sure a programmer using the line
Cycle<int, 0, 23> hoursInADay;
would be allowed, but a programmer using the line
Cycle<int, 23, 0> hoursInADay;
would be warned at compile-time that the declaration in unacceptable?
A:
You can add a static assertion:
static_assert(MIN <= MAX, "Invalid bounds");
Pre-C++11 you'll have to cook up your own construct that produces a compile-time error when invoked on a false bool; e.g. take Boost's version of static-assert.
Otherwise something like this:
template <bool B> struct i_must_be_true; // no definition!
template <> struct i_must_be_true<true> { };
template <typename T, T MIN, T MAX> class Cycle
{
i_must_be_true<MIN <= MAX> m_check;
// ...
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Potly on Nodejs - "socket hang up and read ECONNRESET"
I have some error when use Plotly on Nodejs, can you help me?
I write a demo to generate image from splotly api, every 20 seconds, server will create a chart image. Some images is good, but then throw err as image:
My code:
setInterval(function() {
plotly.getImage(figure, imgOpts, function(error, imageStream) {
if (error) return console.log(error);
var time = new Date();
console.log("1--" + new Date());
var fileStream = fs.createWriteStream(time + '.png');
console.log("2--" + new Date());
imageStream.pipe(fileStream);
// setTimeout(function(){
// console.log("3--"+new Date());
// //createPdfkit(time);
// },10000);
// imageStream.on('end',function(){
//
// });
});
}, 20000);
A:
"ECONNRESET" in general, means that the connection your making has closed.
I assume that this error is being logged after the plotly.getImage()? In this case, you'll need to simply handle the error. if (error) //don't continue The reason for the error could be that the image you're trying to get is not there, if it's not handled accordingly by plotly. You may have better luck posting on plotly's github issues.
| {
"pile_set_name": "StackExchange"
} |
Q:
Did Martin Luther believe the Church needed to be reformed before the Great Schism of 1054AD, or after?
I think its safe to say that Martin Luther, being one of the fathers of Protestantism, was primarily at odds with the Roman Church. He posted his 95 theses to confront what he thought to be corruption that centered around Roman Catholic indulgences. Later on he became convinced that the Pope was the Anti-Christ.
Nevertheless, since few know this glory of baptism and the
blessedness of Christian liberty, and cannot know them because of the
tyranny of the pope, I for one will walk away from it all and redeem
my conscience by bringing this charge against the pope and all his
papists: Unless they will abolish their laws and traditions, and
restore to Christ's churches their liberty and have it taught among
them, they are guilty of all the souls that perish under this
miserable captivity, and the papacy is truly the kingdom of Babylon,
yes, the kingdom of the real Antichrist! For who is " the man of sin"
and "the son of perdition" but he that with his doctrines and his laws
increases sins and the perdition of souls in the Church, while he sits
in the Church as if he were God? All this the papal tyranny has
fulfilled, and more than fulfilled, these many centuries. It has
extinguished faith, obscured the sacraments and oppressed the Gospel.
(Babylonian Captivity of the Church, Page 536, chapter 3 - emphasis added)
From what I understand, Roman Catholicism and Eastern Orthodoxy are basically the same doctrinally, with the exception of a few points, such as the Filioque, Papal Supremacy, etc. I also understand it to be true that it is an historical fact that, before the Great Schism, there was only one Church consisting of both the "Eastern lung" and the "Western lung."
My question is this:
Did Luther believe that the Church needed to be doctrinally reformed even before the Great Schism? If not then why didn't he just embrace Eastern Orthodoxy, and in turn direct his "reforming" constituents toward the East?
I haven't read all of Luther's works to know whether or not he conscientiously protested Rome exclusively, or the sacramental lineage of the unified East/West Fathers and ecumenical councils of the early Church altogether.
A:
Luther saw the church becoming significantly corrupted much earlier than we might think. Generally I would say that Luther perceived a split between the 'real' church and the 'false church' basically around the time of St. Augustine, for he always separated the ritualistic ecclesiastical doctrine of religion, from the Augustinian spiritual doctrine of saving grace. To garner direct quotes from Luther in establishing a factual date of the church apostasy, we would do well to start at St. Gregory and the establishment of the papacy, according to Luther, right after at around 603 AD.
While having some respect for Pope Gregory, primarily in that he refused to become a pope in the modern sense of the word, Luther heaps more blame upon St. Gregory (540-604 AD) than anyone before him. In some ways he begins to be a point for galvanizing all the heresies and abominations slowly and gradually building up to that time, making a good first landmark to answer the question.
Gregory alone is the originator of the fables about purgatory. He also originated the Masses for the dead. Somewhere he tells that there was a certain steward in his monastery who by chance and negligence left three guldens among his papers. When Gregory found these after the man’s death, he had made a terrific uproar about the deceased man and had cried out that the man was accursed because of the crime of thievery and would be subject to eternal punishments, although it was likely that this monk had had greater opportunity to steal in other respects; yet nothing had been pilfered by him, but this money had lain hidden among his papers without his knowledge. Yet Gregory declares that by this example and as a result of his shouting the others were so terrified that from then on no one of them was willing to keep back even a heller. Finally, however, Gregory ordered 30 Masses to be said for the man, and when these had been completed—so he writes—this steward appeared to him and thanked him profusely for the great service by which he had been freed from punishments and the curse of God.
This was undoubtedly the “strong delusion” referred to in 2 Thess. 2:11, and from this example of Gregory there spread into the whole world that infinite multitude of abominations and the offering of the sacrament for the dead. But the specter which appeared to him was the devil in all his wickedness, who came out of hell to mock the whole human race. For the horrible and rash falsehood of purgatory and Masses for the dead exceeds all understanding and power of speech. (Luther's Works Vol 7.297)
Another landmark the more direct to the answer would be just after, in Pope Boniface III who Luther technically thought was the first Pope (603 AD) (Unlike the Catholic church of course who assumes the Papacy started way back with Peter).
It is very easy to prove that the pope is neither the commander or head of Christendom, nor lord of the world above emperor, councils, and everything, as he lies, blasphemes, curses, and raves in his decretals, to which the hellish Satan drives him. He himself knows full well—and it is as clear as the dear sun from all the decrees of the ancient councils, from all the histories, from the writings of the holy fathers, Jerome, Augustine, and Cyprian, and from all of Christendom before the first pope, who was called Boniface III* —that the bishop of Rome was nothing more than a bishop and should still be that. St. Jerome dared to say freely, “All bishops are equal, all together they have inherited the throne of the apostles,” and adds the example, “as the bishop of a small city—like Engubium67 and Rome, Regium and Constantinople, Thebes and Alexandria. (Luther's Works Vol 41.290)
On the topic of the papacy Luther does not speak negatively about Gregory at all, rather he seems to admire him in spite of his other low opinions.
In addition, St. Gregory, when it [the title “universal pope”] was offered to him by several great bishops, sharply refused it and writes that none of his predecessors had been so bold as to accept or wish to carry such a title,71 although the sixth council in Chalcedon72 had offered it to them; he closes by saying briefly and to the point that no one should call himself the highest bishop or head of the whole of Christendom, as many decrees also say, and furthermore, that the bishop of Rome too, though he is one of the greater ones, is nonetheless not to be called universalis, the head of “all” Christendom. (Luther's Works Vol 41.291)
It is after Gregory that Luther truly pins the fall of the church under the papacy:
But after Gregory’s death Sabinianus was a bishop for a year and a half; I count him among the popes, for he was a big monster, like a pope is, and wanted to burn the books of St. Gregory, his immediate predecessor—perhaps because in his writings St. Gregory did not want the papacy to be tolerated. Boniface III was elected after him. This is when God’s wrath began. This Boniface persuaded the regicide Phocas that he should be pope, or chief of all the bishops in the whole world. The bell was cast then, and the Roman horror accepted with joy, as the one who was now lord over all the bishops in the world. (Luther's Works Vol 41.291)
One could trace some of the other streams of perceived corruptions by investigating the origins of many practices Luther opposed but I think starting with St Gregory but absolutely occurring with Pope Boniface III (603 AD) followed by the Popes after him is really where the true church under the Augustinian faith split from the ritualistic ecclesiastical church under the corrupt doctrines of the papacy, according to Luther.
| {
"pile_set_name": "StackExchange"
} |
Q:
Undefined method `image' for #<Article::ActiveRecord_Relation.Rails 4
I installed gem 'paperclip' and used it as show in railscasts.Image appears in the page "show", but in the page "index" show me error:
undefined method `image' for #<Article::ActiveRecord_Relation:0x007fbab4814310>
This is my index.html.erb
<% @article.each do |article| %>
<div class="main-page-blocks">
<%= image_tag @article.image.url(:small) %>
<h3><%= article.title %></h3>
<div class="main-page-articles"><%= article.body %></div>
</div>
<% end %>
this is my model article.rb
class Article < ActiveRecord::Base
has_attached_file :image, :styles => { :small => "150x150"}
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
where is wrong?
A:
Here is where the problem is:
<%= image_tag @article.image.url(:small) %>
You're calling image on @article when it should just be article which is the instance variable defined in the each block.
Update as follows:
<% @article.each do |article| %>
<div class="main-page-blocks">
<%= image_tag article.image.url(:small) %>
<h3><%= article.title %></h3>
<div class="main-page-articles"><%= article.body %></div>
</div>
<% end %>
| {
"pile_set_name": "StackExchange"
} |
Q:
Get the 1st and next value inside an array
Lets say I have an array like this
var data = [1,2,3,4,5,6,7,8,9,0];
How can I get the output like this?
console.log(1,2);
console.log(2,3);
console.log(3,4);
and so on.. as of now this is my code
for (var i = 0; i < data.length; i++) {
/* Dont know what to do */
}
A:
You just need to stop one step before the end of the array in your cycle and print the current and next value
var data = [1,2,3,4,5,6,7,8,9,0]
for (var i = 0; i < data.length -1; i++) {
console.log(data[i], data[i+1]);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why Disallow Special Characters In a Password?
The culprit in this case is a particular (and particularly large) bank that does not allow special characters (of any sort) in their passwords: Just [a-Z 1-9]. Is their any valid reason for doing this? It seems counter productive to stunt password strength like this, especially for a system protecting such valuable information.
The only thing I have been able to come up with is a weak attempt to thwart SQL injections, but that would assume the passwords are not being hashed (which I sure hope isn't true).
A:
One explanation I haven't seen here is that many financial institutions are tightly integrated with older systems and are bound to the limitations of those systems.
The irony of this is that I have seen systems that were built to be compatible to older systems but now the older systems are gone and the policy still must exist for compatibility with the newer system that was built to be compatible with the older system.
(the lesson here is that if you have to be compatible with an old system, allow for some future elimination of those limitations).
A:
What about the support cost? Let's say that we allowed anyone to create password consists of € chars. Hurray, we are able to use special characters in our passwords. But wait - how on earth we can type that password if we want to get the access to our bank from the mobile-phone? It's easier to type € from our keyboard than from the mobile phone.
What about holidays? We are in the UK, which only access to the UK-keyboard. Instead of € we can easily type £. The word easily is very important here. For some average users, typping that chars for the "new" keyboard could be a problem. How will he be trying to solve it? He will probably call bank-support to ask them to change his password or ask why the € character dissapeared from his keyboard.
A:
This can be (weakly) justified as a defense-in-depth measure - if there is an injection or other data interpretation bug, limiting the password character set and length may be able to prevent it from being exploitable. It also somewhat simplifies implementation, since if they only deal with 7-bit ASCII characters, Unicode and multibyte character string handling is irrelevant, and simpler implementations are as a rule less likely to contain bugs.
However, assessing this decreased risk against the increased risk due to lower password quality is not simple - I would expect that as the number of users of a system increases, the number of passwords that could be compromised also increases, making an investment in lifting such restrictions more worthwhile. All that said, most users' passwords will be terrible even if the field is completely unrestricted.
| {
"pile_set_name": "StackExchange"
} |
Q:
ERROR: The Android Gradle plugin supports only Butterknife Gradle plugin version 9.0.0-rc2 and higher
I am update android studio to 3.3, in my project I get this error:
ERROR: The Android Gradle plugin supports only Butterknife Gradle plugin version 9.0.0-rc2 and higher.
The following dependencies do not satisfy the required version:
root project 'MyProject' -> com.jakewharton:butterknife-gradle-plugin:8.8.1
Affected Modules: app
and I am ready update Butterknife to 9.0.0-rc2
implementation 'com.jakewharton:butterknife:9.0.0-rc2'
annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0-rc2'
A:
Are you using androidx in your app/library?
If so, I would bump the butterknife version to the stable 10.0.0 version, otherwise update to the stable 9.0.0 one.
Without androidx:
implementation 'com.jakewharton:butterknife:9.0.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0'
With androidx:
implementation 'com.jakewharton:butterknife:10.0.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.0.0'
You can find more about it in the change log here.
A:
You need to update the Butter Knife plugin inside your project build.gradle to something like this:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.jakewharton:butterknife-gradle-plugin:9.0.0-rc2'
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Get (g) graphics from jpanel
How do I get the g element from a jpanel in java, how can I pass it to another object draw on it and pass it back. Just to be clear, I can use g or graphics to draw on the jpanel; but cannot seem to pass this to another object to draw on it else where. Thanks in advance, I have searched for a solution and cannot find anything, might be that I am not using the right terminology, sorry.
A:
The cleanest way to pass a Graphics object from a JPanel to another (helper) object is to pass the object from the paintComponent method. This way, you can be sure that the object will always be instantiated.
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
myGraphicsHelper.drawStuff(g);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fetch data from web service in background and then update the UI
What i am doing is applying push view controller to move to next view from table view's didSelectMethod. And on next view controller data is fetched for that view. So, the problem is the view switches only when the data is fetched completely, and it contains images and text both. But i have already applied the lazy loading for images but the issue is to move to next view immediately and then fetch data and update the UI and tableview. Below is code i am trying.
On next view controller's didLoad method.
[NSThread detachNewThreadSelector:@selector(setImage) toTarget:self withObject:nil];
the method setImage fetching all data images and text.
-(void)setImage
{
if([type isEqualToString:@"Organisation"])
{
self.mGetDataDict = [MyEventApi members:self.mUserIdDict];
self.mRecievedDataDict = [self.mGetDataDict valueForKey:@"members"];
}
if([type isEqualToString:@"Individual"]){
self.mGetDataDict = [MyEventApi friends:self.mUserIdDict];
self.mRecievedDataDict = [self.mGetDataDict valueForKey:@"friends"];
}
if([self.mGetDataDict valueForKey:@"friends"] == [NSNull null])
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"alert" message:@"You have not added any friend yet." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
else
{
self.mFrndNameArr = [[NSMutableArray alloc]init];
self.mFrndImgArr = [[NSMutableArray alloc]init];
self.mFirstNameArr = [[NSMutableArray alloc]init];
self.mLastNameArr = [[NSMutableArray alloc]init];
self.mFrndIdArr = [[NSMutableArray alloc]init];
self.mFrndMSinceArr = [[NSMutableArray alloc]init];
self.mFrndDescArr = [[NSMutableArray alloc]init];
self.mFrndNameArr = [self.mRecievedDataDict valueForKey:@"username"];
self.mFrndImgArr = [self.mRecievedDataDict valueForKey:@"image"];
self.mFirstNameArr = [self.mRecievedDataDict valueForKey:@"firstName"];
self.mLastNameArr = [self.mRecievedDataDict valueForKey:@"lastName"];
self.mFrndIdArr = [self.mRecievedDataDict valueForKey:@"id"];
self.mFrndMSinceArr = [self.mRecievedDataDict valueForKey:@"memberSince"];
self.mFrndDescArr = [self.mRecievedDataDict valueForKey:@"description"];
[self.mFriendsTable reloadData];
}
}
Please guide for above, is i am using correct method or there is another way to do this.
Thanks in advance.
A:
you can use GCD
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
//Fire api
dispatch_async(dispatch_get_main_queue(), ^{
//update ui
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Snowflake invalid materialized view definition
When running in Snowflake the following command:
CREATE MATERIALIZED VIEW MV_CUSTOMER_PREFERENCE as select * from V_CUSTOMER_PREFERENCE;
I get the following error:
SQL compilation error: error line {0} at position {1} Invalid materialized view definition. More than one table referenced in the view definition
V_CUSTOMER_PREFERENCE is an existing and functioning view (it can be queried separately), that joins information from different tables. I get the same error when I put the original query instead of the view, it's just a long and complicated SQL query.
What can be the problem with the query in the view? I cannot understand it from the error description and I didn't find related restrictions in https://docs.snowflake.net/manuals/user-guide/views-materialized.html
A:
A materialized view can query only a single table. You can see the list of limitations for working with materialized views here:
https://docs.snowflake.net/manuals/user-guide/views-materialized.html#limitations-on-creating-materialized-views
| {
"pile_set_name": "StackExchange"
} |
Q:
How to resolve special character exception issue in UTF8 byte code conversion in C#?
I am converting a string into UTF8 byte code,where as it is not accepting any special character and not converting it. so please help me to know convert these special char also in c#.
byte[] bytes = Encoding.UTF8.GetBytes("<Shipper>A & G VENLO BV</Shipper>");
A:
Do not lead people astray. Your code throws a System.Xml.XmlException while parsing the XML.
The fact is that the string <Shipper>A & G VENLO BV</Shipper> is not well formed XML. The & symbol in XML must be escaped.
You have to create XML using the right approach:
XmlDocument xmlDoc = new XmlDocument();
XmlElement shipper = xmlDoc.CreateElement("Shipper");
shipper.InnerText = "A & G VENLO BV";
xmlDoc.AppendChild(shipper);
As a result, you will get the well-formed XML
<Shipper>A & G VENLO BV</Shipper>
Now you can work with it
byte[] bytes = Encoding.UTF8.GetBytes(shipper.OuterXml);
| {
"pile_set_name": "StackExchange"
} |
Q:
When scrolling to top of div hide another div
this is what I have so far:
$("#main").each(function() {this.scrollTop = this.scrollHeight;
if ($(this).scrollTop()>0)
{
$('#navigation').addClass("nav-hide");
}
else
{
$('#navigation').addClass("nav-normal");
}
});
So basically, I am trying to figure out when you scroll to the top of a div it will hide the navigation bar. So you could read the div without the navigation bar over it. Any ideas? Thanks.
Here's my JSFiddle: https://jsfiddle.net/qb15p5g7/3/
A:
You need to use jquery's window scroll function and not each function unless you are going to have more than one section that you need to hide the navigation on there is no reason to use each and I'm assuming that you don't because you are using an id for #main and Id's are supposed to be unique. Also you don't need to add more than one class you can just add the class and remove the class. So if im correct in assuming that you don't have more than one section that you need to hide the nav in multiple instances on your page then your code should look something like this:
$(window).scroll(function() {
if ($(this).scrollTop() >= $('#main').offset().top) {
$('#navigation').addClass("nav-hide");
}else {
$('#navigation').removeClass("nav-hide");
}
});
And you will just add the nav-hide class and then remove it when scrolling back up.
Here is a fiddle of this working JSFiddle Demo
I assume this is what you are looking for if not let me know so I can edit my answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
cumulative probabilities for standard normal density vs confidence interval
Lets say I have a 90% confidence interval. It's Z score is 1.645 (so 90% of values are between -1.645 and 1.645 standard deviations from the mean) and and it's got error margin of 5% in each tail of the snd curve. How come it's probability is between .9495 and .9505? Shouldn't probability be 90% or so?
Can someone explain to me why this isn't the case?
A:
The table you are looking at probably shows the cumulative probability which equals 1-probability in the upper tail (approx. 0.05 in your case).
| {
"pile_set_name": "StackExchange"
} |
Q:
Web Storage types
After arguing with a few colleages We didnt get an agreement...
My point is the next one:
Why Should I use Local Storage? I don´t like (as user) that someone stores information in my computer. As longer as I saw, whatever information which I need to store in a Local Storage I can store it in a Session Variable in back side. It´s more confidential and I like to handle this information in our serves.
The only case I would consider to store information in front side will be if that storage could slow down the performance´s server or information related with the UI.
Can you give me any argument? Can you provide me examples where local storage is really necessary, usefull or better?
Thanks mates.
A:
Well,
After asking in different forums and read different articles my conclusions are the next ones:
We must use Web Storage when the information which we want to storage is not confidential. Like web storage is storaged in the local computer, this information could be recover by others and changed or read it.
The original purpouse for this storage methods is for storaging information related with the user and the UI experience of himself.
In my specific case this web storage style is nor recommended. We want to storage the footprint of the changes in DDBB for recovering them after... If someone get access to this footprint (storaged in the local computer) and change it, when we recover them the integrity of DDBB will be affected...
Cheers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Subsetting list of dataframes based on ranked column in dataframes R
I have a list of dataframes. I want to subset only the dataframes which contain a row with a score 10 fold lower than the second ranking score, removing all other dataframes. Any idea how to approach this? Thanks!
>Output
$E1
ID model score
E1 AAA 2
E1 BBB 100
E1 CCC 130
E1 ZZZ 120
E1 YYY 128
$E2
ID model score
E2 XXX 130
E2 ASD 144
E2 DFE 142
E2 FGS 145
E2 GFH 124
Preferred result:
>Output_subset
$E1
ID model score
E1 AAA 2
E1 BBB 100
E1 CCC 130
E1 ZZZ 120
E1 YYY 128
A:
You can write a function to check for the condition between the two scores :
check_data <- function(df) {
x <- sort(df$score)
x[1] < (x[2]/10)
}
You can use this function in Filter in base R :
Filter(check_data, Output)
#$E1
# ID model score
#1 E1 AAA 2
#2 E1 BBB 100
#3 E1 CCC 130
#4 E1 ZZZ 120
#5 E1 YYY 128
Or keep in purrr :
purrr::keep(Output, check_data)
data
Output <- list(E1 = structure(list(ID = c("E1", "E1", "E1", "E1", "E1"),
model = c("AAA", "BBB", "CCC", "ZZZ", "YYY"), score = c(2L,
100L, 130L, 120L, 128L)), class = "data.frame", row.names = c(NA,
-5L)), E2 = structure(list(ID = c("E2", "E2", "E2", "E2", "E2"
), model = c("XXX", "ASD", "DFE", "FGS", "GFH"), score = c(130L,
144L, 142L, 145L, 124L)), class = "data.frame", row.names = c(NA, -5L)))
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best way to marshall data in/out of the plug-ins?
I am building my workstation Agent application using MEF and EntityFramework 4.
The application is a simple agent that runs on a computer with a plug-in architecture (and many plugins in the form of .dll files).
Each plug-in will query their own plugin-specific table. The master program (or agent) needs to pass information to the plug-in, and receive information from the plug-in.
The plug-ins will use the Entity Framework 4.1 to retrieve the data, so it will already have the data formatted as objects (perhaps heavy objects since they are tied to the EF context). Also, the data I am pulling back from the database is a series of joins, so the data doesn't match any of the POCO identities/classes I had already created.
What is the best way to marshall data in/out of the plug-ins? Taking into consideration that I am using MEF to tie the pieces together, and that I already have objects for the data in the plug-ins. Should I create a new POCO and move the Entity Data into it, then shuffle arrays? Should I create a List? I am not only interested on what can be done, but what are best practices!
A:
This is a good article on Data Transfer Objects. It touches on the points you are bringing up here with the POCO objects. Since your building an application with the explicit intent of further expansion and customization, I think that the POCO objects are the way to go. Otherwise, any further components will require dependencies on EF which may be burdensome for the plugin developers. With the POCO/DTO objects, you will have a lot more control over what gets sent and what structures it gets sent in.
The plugins should either implement a (virtual?) base class or an interface. I would probably choose interface because - again - it will be easier for plugin developers to add an interface to their code than a base class.
Really, I'm not saying anything new that you, Omar and Adventure haven't already said. Basically I am saying that I think you've already got a good handle on it :)
| {
"pile_set_name": "StackExchange"
} |
Q:
For any $m \times n$ matrix $A$, the matrices $A^{t}A$ and $AA^{t}$ are positive semi- definite.
For any $m \times n$ matrix $A$, then $A^{t}A$ and $AA^{t}$ are
positive semi-definite.
How do I prove the theorem using the definition of positive semi-definiteness? I know the definition, but the definition is not helping me. Please give me hints. How do I work out the given problem?
A:
As stated the result is not true as you can see by taking the null matrix. But for all matrices $A$ the products $AA^t$ and $A^tA$ are positive semidefinite.
Hint: Just use the definition and use the fact that $(AB)^t=B^tA^t$ and that vectors can be seen as matrices, too.
| {
"pile_set_name": "StackExchange"
} |
Q:
Event Handling in Android (setOnClickListener)
I'm new to Java and Android Development in General. I found a sample which uses the following statement.
sButton.setOnClickListener(this);
in the onCreate() method of the Activity which implements View.OnClickListener where sButton is a Button variable. As far as I understand this register the on click event handler
Later in the sample
public void onClick(View v) {
if(v.getId() == R.id.button_s)
{
//some work
}
this happens.
My question is if it uses the 'this' keyword from inside the activity shouldn't it pass an object of class Activity? If that happens then the Button ID would never match.
I know there are other methods to implement the Button click.
I have a bit of experience with C# and Windows Phone. The procedure there was that the methods were called for the respective buttons without any need for registering them.
Also what is the difference between event handlers and listeners?
Any help would be appreciated! Thanks
A:
The OnClickListener (in this case the Activity instance) is used to declare the behaviour of your application when it consumes click event. However, your application's Main (UI) Thread registers all (UI) events and it will dispatch the appropriate View object as a parameter to your onClick(View v) function.
The snippet you provided - sButton.setOnClickListener(this) simply instructs your application to use the implemented OnClickListener inside your Activity implementation to respond to user clicks. It doesn't forward the this instance as the parameter to the onClick() function, Android OS does that.
In conclusion: The View v parameter in your onClick(View v) function will correspond to the View that the user clicked, regardless of the OnClickListener that has been attached to that View
EDIT: This is (perhaps outdated but) Android's source-code for the performClick() method of the View class. As you can see, inside that method it calls the mOnClickListener.onClick(this) if there's a listener attached, and that's how the view that has been clicked is forwarded to the onClick() method of the appropriate onClickListener object.
| {
"pile_set_name": "StackExchange"
} |
Q:
Min and max of NA sequences
I have a data frame in which the column foo contains running sequences of NA values. For example:
> test
id foo time
1 1 <NA> 2018-11-19 00:00:48
2 1 <NA> 2018-11-19 00:10:51
3 1 <NA> 2018-11-19 00:21:15
4 1 <NA> 2018-11-19 00:31:02
5 1 x 2018-11-19 00:40:59
6 1 x 2018-11-19 00:50:49
7 1 x 2018-11-19 01:01:15
8 1 <NA> 2018-11-19 01:11:07
9 1 <NA> 2018-11-19 01:20:49
10 2 <NA> 2018-11-19 01:30:50
11 2 <NA> 2018-11-19 01:40:43
12 2 x 2018-11-19 01:50:46
13 2 x 2018-11-19 02:01:02
14 2 x 2018-11-19 02:10:44
15 2 <NA> 2018-11-19 02:20:51
16 2 <NA> 2018-11-19 02:31:06
17 2 <NA> 2018-11-19 02:40:42
18 2 <NA> 2018-11-19 02:50:45
19 3 <NA> 2018-11-19 03:01:00
20 3 <NA> 2018-11-19 03:10:42
21 3 <NA> 2018-11-19 03:21:10
22 3 <NA> 2018-11-19 03:31:10
23 3 x 2018-11-19 03:40:44
24 3 <NA> 2018-11-19 03:50:46
25 3 <NA> 2018-11-19 04:00:46
My objective is to mark where each sequence begins by id and time for example - the above dataset would have an extra column called index which marks where the starts and ends of these NA values are. However, the last NA in the id series should be ignored, and a single NA value would be marked as "both". For example:
> test
id foo time index
1 1 <NA> 2018-11-19 00:00:48 na_starts
2 1 <NA> 2018-11-19 00:10:51
3 1 <NA> 2018-11-19 00:21:15
4 1 <NA> 2018-11-19 00:31:02 na_ends
5 1 x 2018-11-19 00:40:59
6 1 x 2018-11-19 00:50:49
7 1 x 2018-11-19 01:01:15
8 1 <NA> 2018-11-19 01:11:07 na_starts
9 1 <NA> 2018-11-19 01:20:49
10 2 <NA> 2018-11-19 01:30:50 na_starts
11 2 <NA> 2018-11-19 01:40:43 na_ends
12 2 x 2018-11-19 01:50:46
13 2 x 2018-11-19 02:01:02
14 2 x 2018-11-19 02:10:44
15 2 <NA> 2018-11-19 02:20:51 na_starts
16 2 <NA> 2018-11-19 02:31:06
17 2 <NA> 2018-11-19 02:40:42
18 2 <NA> 2018-11-19 02:50:45
19 3 <NA> 2018-11-19 03:01:00
20 3 <NA> 2018-11-19 03:10:42 na_starts
21 3 <NA> 2018-11-19 03:21:10
22 3 <NA> 2018-11-19 03:31:10 na_ends
23 3 x 2018-11-19 03:40:44
24 3 <NA> 2018-11-19 03:50:46 both
25 3 x 2018-11-19 04:00:46
How would one achieve this with rle or a similar function in R?
dput(test)
structure(list(id = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3), foo = c(NA, NA, NA, NA,
"x", "x", "x", NA, NA, NA, NA, "x", "x", "x", NA, NA, NA, NA,
NA, NA, NA, NA, "x", NA, "x"), time = structure(c(1542585648,
1542586251, 1542586875, 1542587462, 1542588059, 1542588649, 1542589275,
1542589867, 1542590449, 1542591050, 1542591643, 1542592246, 1542592862,
1542593444, 1542594051, 1542594666, 1542595242, 1542595845, 1542596460,
1542597042, 1542597670, 1542598270, 1542598844, 1542599446, 1542600046
), class = c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA,
-25L), class = "data.frame")
A:
Maybe this will work? I'm not entirely sure what relationship time has to the problem other than I think you wanted it sorted by id and time.
library("tidyverse") -25L), class = "data.frame")
test = test %>%
arrange(id, time) %>%
mutate(miss = is.na(foo))
# This will make the index column for a single run
mark_ends = function(n, miss){
if(!miss){
rep("", times = n)
}
else{
if(n == 1){"both"}
else(c("na_starts", rep("", times = (n-2)), "na_ends"))}
}
# This will use mark_ends across a single ID
mark_index = function(id){
runs = test$miss[test$id == id] %>%
rle
result = Map(f = mark_ends, n = runs$lengths, miss = runs$values) %>%
reduce(.f = c)
result[length(result)] = ""
result
}
# use the function on each id, combine, and put it in test
test$index = unique(test$id) %>%
map(mark_index) %>%
reduce(.f = c)
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.NET mvc 2 - How to add a "confirm your e-mail address" field?
Let's say I have a model that looks like this:
public class MyModel
{
[DisplayName("Email:")]
[Required(ErrorMessage = "Email is required")]
[Email(ErrorMessage = "Email is invalid")]
public string Email { get; set; }
}
In ASP.NET MVC 2, I'd render the text box and validation like so:
<%=Html.LabelFor(x => x.Email)%>
<%=Html.TextBoxFor(x => x.Email)%>
<%=Html.ValidationMessageFor(x => x.Email)%>
How do I add a second field to allow the user to confirm their email address using the display name and validation from the model's property?
A:
Decorate your Class with the following Attribute:
[PropertiesMustMatch("Email", "ConfirmEmail", ErrorMessage = "The Email Address and confirmation Email Address do not match.")]
public class MyModel
{
[DisplayName("Email:")]
[Required(ErrorMessage = "Email is required")]
[Email(ErrorMessage = "Email is invalid")]
public string Email { get; set; }
[DisplayName("Confrim Email:")]
[Required(ErrorMessage = "Email is required")]
[Email(ErrorMessage = "Email is invalid")]
public string ConfirmEmail { get; set; }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I utilize Sourcemaps when debugging Opalrb
Opal is generating source maps. I can enable JavaScript source maps in chrome, set breakpoints it even stops in debugger. But it is still not of much practical use.
I cannot investigate local variables. Even if I try to evaluate the same in chrome's console, they all appear as Nil.
I would like to be able to switch between the ruby sources and the generated Javascript (which is not that hard to understand).
up to now I was most successful by searching significant identifiers in the generated Javascript and not using source maps at all.
Any hints are welcome.
A:
Sourcemaps now work in Opal 0.8.0 using Opal Server
# config.ru
require 'bundler'
Bundler.require
#Opal::Processor.inline_operators_enabled = true
run Opal::Server.new { |s|
s.append_path 'public'
s.append_path 'src'
Opal.use_gem "vector2d"
Opal.paths.each { |p| s.append_path(p) }
#s.use_gem 'vector2d'
# s.debug = true
s.source_map = true
s.main = 'application'
s.index_path = 'index_opal.html.erb'
}
| {
"pile_set_name": "StackExchange"
} |
Q:
DataGridComboBoxColumn doesn't display my collection
I just want to do a simple thing, I just want to show my list of versions into a combobox in a datagrid.
The column "Versions" displays "Collections"... and I don't know why!
Here the code into my xaml:
<DataGrid Name="DataGridTableau" Grid.Column="0" Grid.Row="0"
AutoGenerateColumns="False"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Auto" CanUserAddRows="True"
ItemsSource="{Binding }"
>
<DataGrid.Columns>
<DataGridTextColumn Header="Sofware" Width="*" IsReadOnly="True" Binding="{Binding Path=Software}">
</DataGridTextColumn>
<DataGridComboBoxColumn Header="Version" Width="*" IsReadOnly="True"
ItemsSource="{Binding Path=Versions}">
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
And into xaml.cs :
public ObservableCollection<ElementTableau> Elements;
public VueEtapeSelection()
{
InitializeComponent();
Elements = new ObservableCollection<ElementTableau>();
List<string> versions = new List<string>();
versions.Add("3.0");
versions.Add("3.1");
Elements.Add(new ElementTableau("Excel", versions));
this.DataGridTableauEKs.DataContext = Elements;
}
public class ElementTableau
{
private string sofware;
public string Software
{
get { return software; }
set { software = value; }
}
private List<string> versions;
public List<string> Versions
{
get { return versions; }
set { versions = value; }
}
public ElementTableau(string software, List<string> versions)
{
this.software = software;
this.versions=versions
}
}
Thanks for your help!
A:
Try setting the ItemsSource using a style:
<DataGrid.Columns>
<DataGridTextColumn Header="Sofware" Width="*" IsReadOnly="True" Binding="{Binding Path=Software}" />
<DataGridComboBoxColumn>
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=Versions}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=Versions}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
Binding the ItemsSource property of the column doesn't work, because it is evaluated in the context of the column itself which has no parent FrameworkElement. Using the style instead sets the ItemsSource as soon as the ComboBox is being rendered. The ComboBox is integrated in the logical tree and its DataContext can be evaluated, that's why it works.
Edit:
To bind your selected items, add some setters like this:
<Setter Property="SelectedItem" Value="{Binding Path=SelectedVersion}" />
| {
"pile_set_name": "StackExchange"
} |
Q:
How to compare a column to a parameter in Oracle?
my code goes like this..
SELECT ALL TBL_MONITOR.ITEM_ID, TBL_MONITOR.CATEGORY,
TBL_MONITOR.BRANDNAME, TBL_MONITOR.PRICE, TBL_MONITOR.QUANTITY
FROM TBL_MONITOR
where
case when :pricetag = 'Great' then tbl_monitor.price >= :para_price end,
case when :pricetag = 'Less' then tbl_monitor.price >= :para_price end
this part does not work, it says.. missing keyword ==> >= :para_price end
==> >= :para_price end,
wat i want to do is if the user input 'Greater' the reports will show prices greater than the ':para_price'
how would i fix this? Thanks a lot in advance :)
A:
Try out this
WHERE
(:pricetag = 'Great' AND tbl_monitor.price >= :para_price)
OR
(:pricetag = 'Less' AND tbl_monitor.price <= :para_price)
A:
The SQL CASE statement (apart from the syntax errors you are making) is not a flow control instruction like in C or PHP. It's an expression that returns a value and not a way to decide which part of your code will be executed.
You didn't care to say what you are trying to accomplish or how is it failing, but it looks like you want a simple expression:
WHERE (:pricetag = 'Great' AND tbl_monitor.price >= :para_price)
OR (:pricetag = 'Less' AND tbl_monitor.price <= :para_price)
| {
"pile_set_name": "StackExchange"
} |
Q:
insert column datas of one table in mysql database into another table using php
I have two tables(measurementurl and webmeasurements) in a single database(probe_config)
The first table measurementurl has the following fields
id
url
comment
The second table webmeasurements has the following fields
timeout
url
wm(id of the particular table,set to autoincrement)
url_id
I have a php page(wm.php) for inserting webmeasurements datas to the database in the second table(webmeasurements).i have given the database connections and my job is to bring the id values of the first table(measurementurl) to the second table (webmeasurements) on clicking the submit button of the wm.php page.I have attached the coding.can anyone spot out the mistake.
details of wm.php:
timeout(text box)
url(two radio buttons) and a submit button.
Following is the coding of wm.php:
<?php
include_once("connection.php");
$sql="select * from measurementurl";
// _Execute query_
$result=mysql_query($sql,$conn);
?>
<form method="post" action="base.php">
Timeout :
<input type="text" name="timeout" />
<?php
while ($row = mysql_fetch_array($result))
{
?>
<input type="radio" name="urls" value="<?php echo $row['id']?>" /><?php echo $row['url']?>
<?php
}
?>
<input type="submit" value="submit" name="submit" />
</form>
<?php
if(isset($_POST)){
echo " < pre>";
print_r($_POST);
}
?>
following is base.php of the action part:
<?php
//Begin of Checking Loop
$idarray = array();
$db = mysql_connect("localhost:3306", "root","mysql") or die("Could not connect.");
if(!$db)
die("no db");
if(!mysql_select_db("probe_config",$db))
die("No database selected.");
$acc1="SELECT id from measurementurl";
$acc2=mysql_query($acc1) or die("Could not select accounts.");
while($acc3=mysql_fetch_assoc($acc2))
$idarray[] = $acc3[id];
echo "<table border=1>\n";
echo " <tr>\n";
echo " <td>\n";
echo "<b>id</b>";
echo " </td>\n";
echo " <td>\n";
echo "<b></b>";
echo " </td>\n";
echo " </tr>\n";
// Display the URLS being processed.
foreach($idarray as $K => $id)
{
echo "<tr>\n";
echo "<td>\n";
echo $id;
echo "</td>\n";
ob_flush();
flush();
}
echo "</table>\n";
$timeout=$_POST['timeout'];
$url=$_POST['url'];
$name=$_POST['name'];
$url_id=$_POST['acc3[$id]'];
echo "$timeout";
echo "<br />$name";
$sql= "INSERT INTO webmeasurements (url_id, name, timeout) values ($url_id,'$name',$timeout)";
if (!mysql_query($sql,$db))
{
die('Error: ' . mysql_error());
}
else
{
echo "adding Done";
}
mysql_close('$db');
?>
A:
$sql= "INSERT INTO webmeasurements (url_id) SELECT id FROM measurementurl";
| {
"pile_set_name": "StackExchange"
} |
Q:
Implementing a Pythonic "i, j" style for loop in Python 3?
What is an elegant, Pythonic solution to implementing a C-Style 'i, j' for loop in Python? Here's an example loop:
for (i = 0, j = list.length - 1; i < list.length; j = i++ ){
// Do stuff
}
I've encountered a few scenarios now where I would find this type of loop to be useful. However, I can't seem to find an elegant and Pythonic solution to solve this problem.
A:
In python you could just track the previous element:
previous = lst[-1] # j = len(lst) - 1
for current in lst: # i = 0; i < len(lst); i++
print current, previous # lst[i], lst[j]
# do stuff
previous = current # j = i before incrementing
Here current ranges over lst[0] to lst[-1], and previous starts out with lst[-1] then 'trails' current via lst[0] through to lst[-2].
You rarely need a loop over indices in Python, try to stick with looping over the iterable directly.
| {
"pile_set_name": "StackExchange"
} |
Q:
In Hartl's Rails Tutorial, what does the CSS for textarea refer to?
In section 5.1.2 one adds some custom CSS, including the following:
textarea {resize: vertical;}
but I can't find any textarea tags anywhere in the HTML. Is it tagged implicitly, or does this CSS just not refer to anything?
(A search of the github doesn't turn up any hits for textarea outside of styling sheets.)
A:
There is a text_area field here, in the micropost form:
https://github.com/mhartl/sample_app/blob/master/app/views/shared/_micropost_form.html.erb
You were probably searching the repo for 'textarea', which yields no results as Rails uses form helpers. f.text_field, f.date_field etc
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I check if SHIFT is pressed in AUTOLISP?
In my AutoLISP code I need to check if [SHIFT] button is pressed.
In C++ I can do it by GetKeyState from user32.dll, but how to call it in AutoLISP?
A:
(defun c:mx ()
(if (acet-sys-shift-down)
(Princ "Shift Key is Down")
(Princ "Shift Key is not Down")
)
(princ)
)
| {
"pile_set_name": "StackExchange"
} |
Q:
Pointer to member function using C++ lambda
I'm trying to find a way to provide pointers to a member functions between different class instances. For the moment I'm able to provide pointers to member function that takes no arguments but cannot manage to do so when the function to point to has an argument.
A sample code to illustrate my problem :
#include <iostream>
class Event
{
public:
std::string type;
Event(std::string type):type(type){}
};
class EventDispatcherBase
{
public:
void addEventListener(std::function<void(Event &event)> listener)
{
Event myEvent("Type of the myEvent object");
listener(myEvent);
}
};
class EventDispatcherClass:public EventDispatcherBase
{
public:
EventDispatcherClass()
{
addEventListener([](Event &event){std::cout << event.type << std::endl;});
//addEventListener([this]{listener(Event event);});
};
void listener(Event &event)
{
std::cout << event.type << std::endl;
}
};
int main()
{
EventDispatcherClass eventDispatcherClass;
return 0;
}
This code works with an anonymous lambda expression and output "Type of the myEvent object" in the console. But if I uncomment the line
addEventListener([this]{listener(Event event);});
in the constructor of the EventDispatcherClass in order to transmit a pointer to the void listener(Event &event) member function, the compiler throw the following error :
no viable conversion from '(lambda at .../main.cpp:27:26)' to
'std::function'
I don't understand why.
A:
but cannot manage to do so when the function to point to has an argument.
The lambda should take an argument of type Event&, which will be forwarded to the member function inside the lambda. So change it to
addEventListener([this](Event &event){listener(event);});
// ^^^^^^^^^^^^^^
LIVE
A:
The working line:
addEventListener([](Event &event){std::cout << event.type << std::endl;});
looks nothing like the broken one:
//addEventListener([this]{listener(Event event);});
so start by changing the working line bit by bit.
add the capture expression you will want, and it still works
addEventListener([this](Event &event){std::cout << event.type << std::endl;});
change the body to the one you want, and it still works
addEventListener([this](Event &event){ this->listener(event); });
If you're having trouble seeing what's different between the two versions - which is actually pretty common when you wrote them yourself and you're seeing what you intended to type instead of what's there - try changing the layout to line everything up (so you'd see the missing (Event &event)), or transforming one into the other step-by-step as above, or just replace one with the other and diff the file versions.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to improve OpsWorks node's boot time?
I like AWS OpsWorks but one big drawback I am facing now is boot time: nodes are booting super slowly.
In my case, for a t1.micro instance, it takes like 10 minutes before my cookbook can start running (although from EC2 console view, the instance should be ready after about 2 minutes: it can be accessed via SSH after this short period). You can also refer to this topic.
I tried using custom AMI but ran into another problem: the node kept booting forever. But that might be my fault while creating the AMI.
Back to the original question, how can I improve this boot time of OpsWorks nodes?
A:
In my case, using m1.small, I followed this doc to create a custom AMI.
I think the reason it kept booting forever is the opsworks-agent files are still there. See step 4 under To create a custom AMI from an AWS OpsWorks instance, you'd need to stop agent and delete it's files.
The complete cycle improved from ~25 minutes down to ~10 minutes. By the ~11th minute, it's on LB health checks stage.
Hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
java user input for Array - split by space
All,
Below code is working fine with the ArrayList. could you please help me on how to get user input for name gender and amountSpent (array size [4]), then split it by spaces so that it will have String, String and double.
Also, How to display the result of only the customer who has higher amount Spent then the other Customers.
thank you in advance!
Regards,
Viku
import java.util.Comparator;
public class Customer implements Comparable <Customer>{
public String name,gender;
public double amountSpent;
public Customer(String name, String gender, double amountSpent) {
super();
this.name = name;
this.gender = gender;
this.amountSpent = amountSpent;
}
public String getCustomername() {
return name;
}
public void setCoustomername(String name) {
this.name = name;
}
public String getgender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public double getamountSpent() {
return amountSpent;
}
public void setamountSpent(double amountSpent) {
this.amountSpent = amountSpent;
}
public static Comparator <Customer> CustomerNameComparator = new Comparator<Customer>() {
public int compare(Customer c1, Customer c2) {
String custName1 = c1.getCustomername().toUpperCase();
String custName2 = c2.getCustomername().toUpperCase();
//ascending order
//return custName1.compareTo(custName2);
//descending order
return custName2.compareTo(custName1);
}
};
public static Comparator <Customer> CustomerAmountSpentComparator = new Comparator<Customer>() {
public int compare(Customer aS1, Customer aS2) {
int custamtspent1 = (int) aS1.getamountSpent();
int custamtSpent2 = (int) aS2.getamountSpent();
//ascending order sort
// return custamtspent1 - custamtSpent2;
//descending order sort
return custamtSpent2 - custamtspent1;
}
};
@Override
public int compareTo(Customer o) {
return 0;
}
@Override
public String toString() {
return " Customer Name : " + name + ", Gender : " + gender + ", Amount Spent : " + amountSpent + "";
}
}
and Main Program:
import java.util.ArrayList;
import java.util.Collections;
public class MainProg {
public static void main(String args[]){
String nL = System.lineSeparator();
try {
ArrayList<Customer> arraylist = new ArrayList<Customer> ();
arraylist.add(new Customer ("Louis","Male", 4567.76));
arraylist.add(new Customer ("Daniela","Female", 7653.67));
arraylist.add(new Customer ("Jenny","Female", 3476.98));
arraylist.add(new Customer ("Arijit","Male", 9876.44));
System.out.println("Customer Name Decending Sort: " + nL);
Collections.sort(arraylist, Customer.CustomerNameComparator);
for (Customer str: arraylist) {
System.out.println(str);
}
System.out.println(nL + "Custmer Amount Spent [Hight to Low] Sorting: " + nL);
Collections.sort(arraylist, Customer.CustomerAmountSpentComparator);
for (Customer str: arraylist){
System.out.println(str);
}
System.out.println(nL + "Highest Amount Spent Custmer Detail: " + nL);
}
catch (Exception e){
System.out.println("Error: " + e);
}
finally {
System.out.println(nL + "Report Completed!");
}
}
}
A:
OPTION 1 (suggested):
If the user is to input the data, why do you need to split it up? Just do as follows:
System.out.println("Name:");
name = scn.nextLine();
System.out.println("Gender:");
gender = scn.nextLine():
System.out.println("Amt:");
amt = scn.nextDouble();
Customer c1 = new Customer (name,gender, amt);
OPTION 2:
Alternatively, if you want user to input everything in one single line (separated by spaces), just do this:
System.out.println("Input name, gender, amt:");
name = scn.next();
gender = scn.next():
amt = scn.next();
Customer c1 = new Customer (name,gender, amt);
PROGRAM OUTPUT: Input name, gender, amt: John Male 33.50
OPTION 3 (requested by you):
Lastly if you still insist of doing a split by space, and you want to accept the user input in one string separated by spaces:
System.out.println("Input name, gender, amt:");
input = scn.nextLine();
String[] token = input.split(" ");
String name = token[0];
String gender = token[1];
double amt = Double.parseDouble(token[2]);
Customer c1 = new Customer (name,gender, amt);
PROGRAM OUTPUT: Input name, gender, amt: John Male 33.50
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieving images to 3 image views (Firebase and Swift)
From this node in JSON structure:
{
"Devices" : {
"WDREMca1BOcaaW457Mg8ankzId32" : {
"Device1" : {
"Category" : "",
"Description" : "",
"DeviceName" : "",
"ImageUrl" : "https://firebasestorage.googleapis.com/v0/b/jabeerah-c27c3.appspot.com/o/Devices_Images%2F5F4E0AC2-8279-4CC4-AE99-E797655D4331.png?alt=media&token=5823ed16-e8ff-4b85-8a64-bfb00b965785"
},
"Device2" : {
"Category" : "",
"Description" : "",
"DeviceName" : "",
"ImageUrl" : "https://firebasestorage.googleapis.com/v0/b/jabeerah-c27c3.appspot.com/o/Devices_Images%2FF9E2EF8D-44B3-4BE6-9020-81D190A45AA3.png?alt=media&token=af17e9a5-53f4-4054-9496-fb86d1508a6f"
}
},
"a4gbFozO4gTZE6QT60b6qxQDriw2" : {
"Device1" : {
"Category" : "أخرى",
"Description" : "mmm",
"DeviceName" : "mmm",
"ImageUrl" : "https://firebasestorage.googleapis.com/v0/b/jabeerah-c27c3.appspot.com/o/Devices_Images%2FCF13F154-2B5F-4926-A979-2E187BD0E504.png?alt=media&token=bf1b876f-9f9a-4e78-9e8d-98d017fd0404"
}
}
I'm trying to retrieve the users' pictures to his/her profile.
The profile view has 3 image views (Since each user can have only 3 devices or less).
In viewDidLoad function I have made this:
if ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device1") != nil {
ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device1").observe(.value , with: {snapshot in
let ImageUrl = (snapshot.value! as AnyObject).object(forKey: "ImageUrl") as? String
self.ImageViewOne.downloadedFrom(link: ImageUrl!)
})
} else {
//
}
if ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device2") != nil {
ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device2").observe(.value , with: {snapshot in
let ImageUrl = (snapshot.value! as AnyObject).object(forKey: "ImageUrl") as? String
self.ImageViewTwo.downloadedFrom(link: ImageUrl!)
})
} else {
//
}
if ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device3") != nil {
ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).child("Device3").observe(.value , with: {snapshot in
let ImageUrl = (snapshot.value! as AnyObject).object(forKey: "ImageUrl") as? String
self.ImageViewThree.downloadedFrom(link: ImageUrl!)
})
} else {
//
}
But this actually gave me a signal SIGABRT error in
let ImageUrl = (snapshot.value! as AnyObject).object(forKey: "ImageUrl") as? String
Not sure why this happens!
For downloadedFrom Function, I'm using the extension from this answer
A:
Try replacing :-
let ImageUrl = (snapshot.value! as AnyObject).object(forKey: "ImageUrl") as? String
To -
if let deviceDict = snapshot.value! as? [String : AnyObject]{
let imageUrl = deviceDict["ImageUrl"] as! String
self.ImageViewThree.downloadedFrom(link: ImageUrl!)
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ignoring root role in a proxy enpoint
My subdomain sbd.example.org is a webservice that need to return an HTML static page when request is a GET to the root (/),
and is a proxy rewrite for any other case (eg. /t). So I need
GET http://sbd.example.org to usual root index and try_files
GET http://sbd.example.org/t rewrite to a proxy
but my /etc/nginx/sites-available/sbd is not working as expected. This is the problematic source:
server {
server_name sbd.example.org;
root /var/www/sbd/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ ^/[a-z].+$ {
rewrite ^/(.*)$ /$1 break;
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
default_type application/json;
proxy_hide_header Content-Location;
proxy_set_header Connection "";
proxy_http_version 1.1;
}
}
Error: the GET http://sbd.example.org/ is not an HTML page but an JSON with error message generated by proxy as a request for http://sbd.example.org/index.htm.
How to correct my Nginx script?
PS: all http://sbd.example.org/etc is working fine.
A:
Rather than identify what needs to be sent to the proxy, it may be easier to identify what files are static.
location / {
try_files $uri $uri/ @proxy;
}
location @proxy {
proxy_pass http://127.0.0.1:3000;
...
}
See this document for more.
| {
"pile_set_name": "StackExchange"
} |
Q:
Swipe to pop View Controller in Swift
I'm using the Slide menu controller pod in my project and have a little problem. When there are controllers in navigation stack and I want to swipe left, the burger menu appears instead of popping the contorller. How could that be changed? Could someone please guide me?
So I know it's a pretty basic functionality that you get for free, but it's overridden here.
I tried switching off the pan gesture for the slide menu, but it powered off the whole mechanism.
SlideMenuOptions.panGesturesEnabled = false
I also found the handleLeftPanGesture(_ panGesture: UIPanGestureRecognizer) method, which looks as follows:
open func isTargetViewController() -> Bool {
// Function to determine the target ViewController
// Please to override it if necessary
guard let navController = navigationController else { return true }
return navController.viewControllers.isEmpty
}
@objc func handleLeftPanGesture(_ panGesture: UIPanGestureRecognizer) {
if !isTargetViewController() {
navigationController?.popViewController(animated: true)
}
if isRightOpen() {
return
}
switch panGesture.state {
case UIGestureRecognizerState.began:
if LeftPanState.lastState != .ended && LeftPanState.lastState != .cancelled && LeftPanState.lastState != .failed {
return
}
if isLeftHidden() {
self.delegate?.leftWillOpen?()
} else {
self.delegate?.leftWillClose?()
}
LeftPanState.frameAtStartOfPan = leftContainerView.frame
LeftPanState.startPointOfPan = panGesture.location(in: view)
LeftPanState.wasOpenAtStartOfPan = isLeftOpen()
LeftPanState.wasHiddenAtStartOfPan = isLeftHidden()
leftViewController?.beginAppearanceTransition(LeftPanState.wasHiddenAtStartOfPan, animated: true)
addShadowToView(leftContainerView)
setOpenWindowLevel()
case UIGestureRecognizerState.changed:
if LeftPanState.lastState != .began && LeftPanState.lastState != .changed {
return
}
let translation: CGPoint = panGesture.translation(in: panGesture.view!)
leftContainerView.frame = applyLeftTranslation(translation, toFrame: LeftPanState.frameAtStartOfPan)
applyLeftOpacity()
applyLeftContentViewScale()
case UIGestureRecognizerState.ended, UIGestureRecognizerState.cancelled:
if LeftPanState.lastState != .changed {
setCloseWindowLevel()
return
}
let velocity:CGPoint = panGesture.velocity(in: panGesture.view)
let panInfo: PanInfo = panLeftResultInfoForVelocity(velocity)
if panInfo.action == .open {
if !LeftPanState.wasHiddenAtStartOfPan {
leftViewController?.beginAppearanceTransition(true, animated: true)
}
openLeftWithVelocity(panInfo.velocity)
track(.leftFlickOpen)
} else {
if LeftPanState.wasHiddenAtStartOfPan {
leftViewController?.beginAppearanceTransition(false, animated: true)
}
closeLeftWithVelocity(panInfo.velocity)
setCloseWindowLevel()
track(.leftFlickClose)
}
case UIGestureRecognizerState.failed, UIGestureRecognizerState.possible:
break
}
LeftPanState.lastState = panGesture.state
}
And I'm trying to count the navigaion ViewControllers, but it didn't help.
A:
Actaully I found the solution which might help someone.
You need to add this to ViewController and conform to UIGestureRecognizerDelegate protocol
override func viewDidAppear(_ animated: Bool) {
slideMenuController()?.removeLeftGestures()
navigationController?.interactivePopGestureRecognizer?.delegate = self
}
extension AdditionalInformationController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isEqual(navigationController?.interactivePopGestureRecognizer) {
navigationController?.popViewController(animated: true)
}
return false
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
TSQL-failing to parse XML(namespaces)
Here is a my SQL:
create table sqm (data xml)
insert into sqm
select '<DataSet xmlns="http://www.bnr.ro/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bnr.ro/xsd nbrfxrates.xsd">
<Cube date="2017-06-30">
<Rate currency="AED">1.0867</Rate>
<Rate currency="AUD">3.0665</Rate>
<Rate currency="BGN">2.3284</Rate>
</Cube>
</DataSet>'
select
m.c.value('@date', 'date') as valuta
from sqm as s
outer apply s.data.nodes('/DataSet/Body/Cube') as m(c)
After spending hours trying to find out why my SQL kept returning NULL in the db, I discovered that my problem was due to Hyperlink references at the very beginning of the XML(after DataSet).
I really want to know why is this happening and who can I delete everything between <DataSet end >. Is there any other option?
if you can think of a better title, please edit.
A:
You need to declare the namespace using WITH XMLNAMESPACES
Also your example XML has no Body element so I removed that from the Xpath.
Demo
WITH XMLNAMESPACES (DEFAULT 'http://www.bnr.ro/xsd')
select
m.c.value('@date', 'date') as valuta
from sqm as s
outer apply s.data.nodes('/DataSet/Cube') as m(c)
Or alternatively you can use
select
m.c.value('@date', 'date') as valuta
from sqm as s
outer apply s.data.nodes('/*:DataSet/*:Cube') as m(c)
| {
"pile_set_name": "StackExchange"
} |
Q:
Where I did mistake in query SQL (UNION ALL)?
I tried to use UNION ALL, but got an error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ') GROUP BY Product_id' at line 13
How to set correct alias to UNION tables and in result GROUP BY?
Example by sqlfiddle
A:
this is the right query structure, UNION/ALL does not require alias however the Derived table will.
SELECT
Product_id,
sum(Total) as sumOfTotal
FROM ((SELECT
b.Products_idProducts AS Product_id,
COUNT(b.Products_idProducts) AS Total
FROM products_has_colors a
RIGHT JOIN products_has_colors b
ON a.Colors_idColors = b.Colors_idColors
AND b.Products_idProducts <> a.Products_idProducts
WHERE a.Products_idProducts = 1
GROUP BY b.Products_idProducts)
UNION ALL
(SELECT
b.Products_idProducts AS Product_id,
COUNT(b.Products_idProducts) AS Total
FROM Products_has_ProductComposition a
RIGHT JOIN Products_has_ProductComposition b
ON (a.CompositionId = b.CompositionId
AND b.Products_idProducts <> a.Products_idProducts)
WHERE a.Products_idProducts = 1
GROUP BY b.Products_idProducts)) mytable
GROUP BY Product_id;
| {
"pile_set_name": "StackExchange"
} |
Q:
MVC5 cascading EditorFor in a collection
Given a controller method that returns an IList<Scope>
Where Scope contains a set of bool values, and some additional child objects.
public class Scope
{
public string Name { get; set; }
public bool A { get; set; }
public bool B { get; set; }
public bool C { get; set; }
public Investment Item { get; set; }
}
I have a main view with the following markup:
@model IList<Scope>
<div>
@Html.EditorForModel("Panel")
</div>
I have a view called Panel.cshtml inside EditorTemplates structured like this:
@model IList<Scope>
@for (int i = 0; i < Model.Count; i++)
{
<div class="panel panel-info">
<div class="panel-heading">
<p>@Model[i].Name</p>
</div>
<div class="panel-body">
@Html.EditorFor(_ => _[i])
</div>
</div>
}
The EditorFor(_ => _[i]) doesn't render the standard object template with and editor for each of the fields based on its type?
Why does EditorFor not render an editor for each of the properties when it is called from inside another editor?
If I move all the markup from the Panel.cshtml into the master view, it works correctly.
Is it not possible to get the same behavior from an editor template?
A:
You can iterate EditorFor for each property of model:
@model IList<Scope>
@for (int i = 0; i < Model.Count; i++)
{
<div class="panel panel-info">
<div class="panel-heading">
<p>@Model[i].Name</p>
</div>
<div class="panel-body">
@Html.EditorFor(_ => Model[i].A)
</div>
<div class="panel-body">
@Html.EditorFor(_ => Model[i].B)
</div>
.
.
.
</div>
}
or if you don't want iterate EditorFor for each property of model try this:
@foreach (var scope in Model)
{
@Html.EditorFor(model => scope);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
R conditional variable for longitudinal data
I have data for each month for a year on insured people. All variables are dummy variables and I need to create a new variable that shows when a person became uninsured. I am calling the variable duration. My dataset (df) looks something like this:
ID Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
101 1 1 1 1 0 0 1 1 1 1 1 1
102 1 1 1 1 0 0 0 0 0 0 0 0
103 1 1 1 1 1 1 1 1 1 1 1 1
104 1 1 1 1 0 1 1 0 1 1 1 1
In the dataset, 1 is insured and 0 is uninsured.My new variable would have the have the col position for when the person changed from 1 to 0. For instance in the first row, my variable duration would have the value 5 for may. I am only insterested in the first instance of 0. For example, in row 4, i only need 5 for may and can ignore august. Also, if the person does not become uninsured like in the case of 103, the new variable would just have the value "0".
I began by using ifelse statement below but it would take me a lot of time to keep repeating it. if you have an easier solution for this, please share. Thanks!
df$duration=ifelse(df$feb==1,0,2)
A:
There are more efficient alternatives, but maybe this is sufficient:
apply(DF[,-1], 1, function(x) which(x==0)[1])
#[1] 5 5 NA 5
| {
"pile_set_name": "StackExchange"
} |
Q:
Win conditions for Match 3 game
I have a randomly generated 10x5 array that I want to check when 3 numbers match both horizontally, and vertically. I can't figure out a good way to do the check to see if the numbers match. The way I am currently doing it, it would take me over 70 if statements, and I know there is a better way. I don't think I can use a for loop to check though because I need to know exactly which 3 numbers (and their location) are the same.
Here is the code I have so far, sorry if it is a little long. I only included the check for one row to save space.
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <cstdio>
using namespace std;
int col = 5;
int row = 0;
int board[9][4];
int i;
int main(int argc, char * argv[])
{
srand(time(NULL));
// generate the random board
cout << "==========\n";
while (row < 1)
{
for(i = 0; i < 5; i++)
{
board[row][i] = rand()%5 + 1;
cout << board[row][i] << " ";
}
cout << endl;
cout << "==========\n";
row++;
}
//----check for matches-----
// row 1
if (board[0][0] == (board[0][1] && board[0][2]))
{
cout << "Balls 1,2,3 match\n";
}
if (board[0][2] == (board[0][3] && board[0][4]))
{
cout << "Balls 3,4,5 match\n";
}
if (board[0][1] == (board[0][2] && board[0][3]))
{
cout << "Balls 2,3,4 match\n";
}
if (board[0][0] == (board[0][1] && board[0][2] && board[0][3]))
{
cout << "Balls 1,2,3,4 match\n";
}
if (board[0][1] == (board[0][2] && board[0][3] && board[0][4]))
{
cout << "Balls 2,3,4,5 match\n";
}
if (board[0][0] == (board[0][1] && board[0][2] && board[0][3] && board[0][4]))
{
cout << "Balls 1,2,3,4,5 match\n";
}
else
{
cout << "No balls match\n";
}
return 0;
}
A:
The only difference I see between this question and your previous question is that you want to know the location and direction of the match. In that case, here is a minor modification to @templatetypedef's function.
enum Direction { NONE, VERTICAL, HORIZONTAL, DIAGONAL_UP, DIAGONAL_DOWN };
Direction IsLineStartingAt(int x, int y) {
if (IsLinearMatch(x, y, 1, 0) return HORIZONTAL;
if (IsLinearMatch(x, y, 0, 1) return VERTICAL;
if (IsLinearMatch(x, y, 1, 1) return DIAGONAL_DOWN;
if (IsLinearMatch(x, y, 1, -1) return DIAGONAL_UP;
return NONE;
}
If you run that through a for loop, you already have the x and y starting locations, and this will return the direction, or none if there is no match.
| {
"pile_set_name": "StackExchange"
} |
Q:
ORA-06502 when connecting to Oracle 12c using new SQL credentials
Hi I'm trying to connect to an Oracle 12c instance using a connect descriptor and newly created SQL credentials. But when I try to connect using the credentials I get:
ORA-00604: error occurred at recursive SQL level 1
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 18
I managed to track down possible documentation on this to: https://support.oracle.com/knowledge/Oracle%20Database%20Products/1274538_1.html
But unfortunately I don't have an Oracle Support Account to view the details. My personal guess is some logon PL/SQL (a trigger or procedure) is running and there might be an issue with the information retrieved for the credentials I've been given. Because of the recursive SQL level error, I think something like NULLs are being returned for some expected entry in some kind of dictionary/lookup table when the PL/SQL runs. I'd appreciate if any one may know why this could happen. In the mean time I'll get in contact with the DBA to investigate.
Update
The DBAs got back to me and helped by modifying the trigger. Nothing additional was required by me.
A:
I've added in the oracle support link. The conjectures are true but the "character string buffer too small" error shows that the table has been worked to write a great value
that the column is allowed. Whichever table the trigger records in, you need to look at the column sizes in that table.
SYMPTOMS
A new user is created who tries to connect to Oracle:
SQL> create user test identified by default tablespace users;
User created.
SQL> grant create session to test;
Grant succeeded.
SQL> connect test/
ERROR:
ORA-00604: error occurred at recursive SQL level 1
ORA-06502: PL/SQL: numeric or value error
ORA-06512: at line 7
CHANGES
New user created.
CAUSE
Like in this case, the issue can be caused by an existing logon trigger.
SOLUTION
Connect as sysdba and disable the trigger.
SQL> select trigger_name from dba_triggers where triggering_event like '%LOGON%';
SQL> alter trigger disable;
| {
"pile_set_name": "StackExchange"
} |
Q:
Regarding window.onload in javascript
I'm taking a introduction javascript class and for one of our labs we were instructed to have only ONE script tag in the head section but gets delayed by the window.onload event handler.
I got everything to work but my question is why do my imageManipulator() function only work when I do window.onload = function() { imageManipulator() };
and the other 2 works fine without the {}.
Also for my if statement to loop through the hockey teams why won't == 0 work? I thought 0 is true -1 is false so shouldn't it be == 0 and not >= 0?
My code is here:
<html>
<head>
<script>
function christmasDayCalculation()
{
var currentDate = new Date();
var christmas = new Date(2016, 11, 25);
var ms = christmas - currentDate;
var seconds = ms / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
alert(Math.round(days) + " days until christmas");
}
function hockeyTeams()
{
var hockeyTeams = ['Anaheim Ducks', 'Arizona Coyotes', 'Calgary Flames', 'Edmonton Oilers',
'Los Angeles Kings', 'San Jose Sharks', 'Vancouver Canucks', 'Colorado Avalanch',
'Dallas Stars', 'Minnesota Wild', 'St.Louis Blues', 'Winnipeg Jets', 'Boston Bruins',
'Buffalo Sabres', 'Detroit Redw Wings', 'Florida Panthers', 'Montreal Canadiens',
'Ottowa Senators', 'Tampa Bay Lightning', 'Toronto Maple Leafs', 'Colombus Blue Jackets',
'New Jersey Devils', 'New York Islanders', 'New York Rangers', 'Philadelphia Flyers',
'Pittsburgh Penguins', 'Washington Capitals']
for(i = 0; i < hockeyTeams.length; i++)
{
if(hockeyTeams[i].indexOf("an") >= 0)
{
alert(hockeyTeams[i]);
}
}
}
function imageManipulator()
{
var numberOfImages = document.images.length;
for(i = 0; i < numberOfImages; i++)
{
document.images[i].style.border = "solid red"; // DOM 0 required per lab instructions
document.getElementsByTagName("img")[i].style.width = "100px"; // DOM 1 required per lab instructions
}
}
window.onload = christmasDayCalculation();
window.onload = hockeyTeams();
window.onload = function() { imageManipulator() };
</script>
</head>
<body>
<img src="cat.jpg">
<img src="dog.jpg">
<img src="bird.jpg">
</body>
</html>
Thanks!
A:
Running something in window.onload ensure that all the DOM elements will be loaded before the function runs. You need to use this if the function accesses or modifies the DOM.
christmasDayCalculation() and hockeyTeams() don't access the DOM, so they don't need to be run in window.onload. You're not actually running them when the window is loaded, because you didn't put function() around them. When you do
window.onload = hockeyTeams();
it runs the function immediately, and then assigns the value that it returns to window.onload.
When you write
window.onload = function() { imageManipulator(); };
That doesn't run imageManipulator() immediately, it creates a function that will call it. You could also write:
window.onload = imageManipulator;
Notice that there's no () after the function name. That sets the variable to a reference to the function, rather than calling the function.
Finally, it makes no sense to assign to window.onload multiple times. This is a single property, it can only hold one value. The repeated assignments replace the previous value, and when the document is loaded it will only execute the last one. If you want to do multiple things, you should combine them into a single function:
window.onload = function() {
christmasDayCalculation();
hockeyTeams();
imageManipulator();
};
For your second question, indexOf() returns the position of the found element in the array, or -1 if it's not found. So if you used == 0, it would not be true for New York Islanders, because indexOf() returns 12, not 0. indexOf doesn't return a true/false value, it returns a position.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot boot without USB stick after successful install
I installed Ubuntu yesterday via a bootable USB drive, created with unetbootin. Everything went very well, but now the computer does not boot unless the USB drive is plugged in. If it's not, then when the computer boots, the boot sequence screen just appears and if I select the hard drive, it will just reboot and go back to this boot sequence screen, until I plug in the USB drive.
Any ideas? Thanks a lot for your help!
UPDATE: Having some valuable data on the machine, I would prefer a solution that doesn't involve reinstalling, but from the first replies, I guess this may be what I have to do eventually. Thanks!
GM
==
EDIT: output of sudo fdisk -l below
Disk /dev/sda: 750.2 GB, 750156374016 bytes
255 heads, 63 sectors/track, 91201 cylinders, total 1465149168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x000742dc
Device Boot Start End Blocks Id System
/dev/sda1 2048 1449474047 724736000 83 Linux
/dev/sda2 1449476094 1465147391 7835649 5 Extended
Partition 2 does not start on physical sector boundary.
/dev/sda5 1449476096 1465147391 7835648 82 Linux swap / Solaris
Disk /dev/sdb: 4009 MB, 4009754624 bytes
255 heads, 63 sectors/track, 487 cylinders, total 7831552 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xc3072e18
Device Boot Start End Blocks Id System
/dev/sdb1 * 8064 7831551 3911744 b W95 FAT32
==
EDIT2 bootinfo output:
http://paste.ubuntu.com/1006423
A:
I have solved this problem thanks to help on another forum.
I used boot-repair, ticking "reinstall grub" as well as "purge and reinstall". When I had to reboot, the screen froze and I had to use the power button. But now it boots fine on the hard drive. I didn't have to make another partition.
Thanks everybody for your help.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sending ajax request by jquery doesn't working
I'm trying to send ajax request to api. My code is
$(".doit").click(function(){
console.log("GG");
$.ajax({
type: 'POST',
url: "localhost:8000/api/get-user/1",
data: {id:1},
success: function(res) {
console.log(res);
}
});
})
It's just a simple code. Everyone know. But it works in "console.log("GG"). Not working in ajax part.
I monitored the network traffic by firefox, but I ddin't see any network traffic.
Do you have any idea about that case?
A:
Update your ajax URL as below
url: "http://localhost:8000/api/get-user/1",
or
url: "api/get-user/1",
Hope this will fix your issue
| {
"pile_set_name": "StackExchange"
} |
Q:
Qt app on Android without Ministro
I want deploy app with Qt 4 or 5 libs (Core & GUI) in apk. Is it real? I use necessitas to create apps. google.com didn't help in this answer.
P.S.: sorry for my English, it's not my native language.
A:
If you mean that you don't want to use Ministro, then it should be possible. The page below gives some directions how to:
http://community.kde.org/Necessitas/QuickStartDevelop
On March 1, 2013, the page above has the following:
Deploy Configurations
Also on the Run view you can set the Deploy Configurations, by selecting Details at the right hand side these are the different options you can choose between.
Use device's qt libs
Deploy local qt libs
Install Ministro system
The Use devices qt libs option depends also on the Use local qt libs option. When Use local qt libs is unchecked your application will need the Ministro package to run. However if Use local qt libs is checked, Qt Creator will pass special parameters to the application, forcing it to use Qt libraries from the /data/local/qt path on the device.
The Deploy local qt libs option makes Qt Creator deploy qt libs found in the Qt SDK chosen (e.g. android-lighthouse-4.8.0). This option is useful when you hack on the Qt framework to test it. This option automatically selects the Use local qt libs option. This option get automatically unchecked after Qt Creator pushes the Qt libs. This option can be checked every time you need to push your local Qt modifications.
Install Ministro system option installs the Ministro package (you must provide the apk yourself; download it from from here). It is useful when you try to test your application on Android Virtual Devices.
If you want to go with Ministro for the libraries, here are directions on how to get it set up:
https://play.google.com/store/apps/details?id=eu.licentia.necessitas.ministro
http://sourceforge.net/p/necessitas/home/necessitas/
What is Ministro ?
Necessitas is also the Home of Ministro, an Android application which provides a system wide downloader and installer of the LGPL Qt shared libraries. You can find Ministro on the Android Market or as direct download here.
EDIT: Some more links:
http://community.kde.org/Necessitas
http://necessitas.kde.org/
http://qt-project.org/wiki/How_to_Create_and_Run_Qt_Application_for_Android
Hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
When using the pseudo-class :target, how can I reverse the animation?
I am working on a dropdown menu, and when I click on an image, it scales and rotates.
This is all working well, but when I click on it again, I want it to return to it's normale state.
#arrow {
z-index: 2;
position: absolute;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
-ms-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}
#arrow:target {
transform: scale(1.2) rotate(45deg);
-ms-transform: scale(1.2) rotate(45deg);
-webkit-transform: scale(1.2) rotate(45deg);
-moz-transform: scale(1.2) rotate(45deg);
-o-transform: scale(1.2) rotate(45deg);
margin-top: 1em;
}
Here is the jsfiddle: Click me =)
A:
The only way to "reverse" the application of :target that I'm aware of is to change the fragment in the link (or otherwise add a new class or something).
Aside from some <input> elements, there's no way to make state changes without a light application of JavaScript.
UPDATED DEMO
Edit
Here's an updated demo using a <input type="checkbox"> with :checked instead of :target that does not involve JavaScript. YMMV depending on required browser support.
#arrow {
position: absolute;
left: -9999px; /* hide the checkbox off-screen */
z-index: 2;
}
#arrow:before {
width: 96px;
height: 104px;
position: absolute;
top: 2px;
left: 9999px; /* undo the checkbox offset */
display: block;
content: ' ';
background: url(http://s23.postimg.org/s6m0zb4ev/arrow.png) no-repeat;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}
#arrow:checked:before {
-moz-transform: scale(1.2) rotate(45deg);
-webkit-transform: scale(1.2) rotate(45deg);
transform: scale(1.2) rotate(45deg);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding HTML object to DOM using JavaScript. Showing blank
I'm attempting to creat a HTML button using JavaScript (seemingly simple), yet for some reason the object isn't being placed on the page.
Do I need to append it to the DOM or somehow create an instance of it?
Here is my code:
function loadNavigation() {
var backButton;
backButton = document.createElement('input');
backButton.ID = 'backButton';
backButton.type = 'button';
backButton.innerHTML = 'Back';
backButton.onclick = 'function navigate(-1)';
}
A:
You will have to use appendChild Method to append the button You created to already exisiting DOM
| {
"pile_set_name": "StackExchange"
} |
Q:
Resume interrupted copy
I'm backing up an old hard drive and copying about 300GB of files. It had about 50GB left when I got a kernel panic and now I want to resume the copying. Is there a way to do this in Ubuntu? (A don't copy if file already exists but copy all files that don't already exist argument?)
A:
rsync usually only copies what's missing or changed, there seem to be also some GUIs for it.
The command for you might look like as follows, copying recursively and preserving permissions, timestamps etc. (archive), verbose output, use compression (zip) during transfer, showing Progress:
rsync -avzP /media/oldhd/ /media/newhd/ in some casese you may need to prepend sudo if files are from different users.
| {
"pile_set_name": "StackExchange"
} |
Q:
Okta oauth2 with external IdP
I have an Angular app with express server where Okta acts as an IdP. This is already setup and works well. Now, I need to support SSO from an external app which uses Amazon Cognito. They have enabled our app for OAuth2 Auth code flow by providing us the clientId and Secret.
What I want to understand is where I should exchange authCode with accessTokens and also how I should manage sessions for users who come via SSO in Okta. I have few options:
I tried in the angular app using "angular-oauth2-oidc" library but ran into CORS issue while calling /authorize endpoint with AWS Cognito. Further, it seems like exchanging authCode with accessToken in front channel may not be the most secure way.
For SSO users, I could write a new route handler in express to manage the token exchange and have this route as the callback url in the initial authorization call to Cognito. However, my express server already uses "express-stormpath" sdk which handles session management for our usual case where Okta acts as IdP. How do I have express manage both local Okta user sessions as well as SSO user sessions with Cognito IdP, in the same place.
I also tried setting up Okta federation to external IdP. But, I am not sure how to route the auth call to external IdP while Okta itself acts as an IdP for our internal users.
I am more inclined towards 3 where I only talk to Okta and it takes care of managing auth for our internal users (Okta IdP) as well as SSO users from external IdP (Cognito).
Any help here would be much appreciated..
Thanks,
RK
A:
That's an awful lot of questions in one, but here are some pointers:
1a. You need to add your SPA's domain to Okta as a trusted origin, as in step 7 of my write up
1b. You need to be more explicit about your concerns and what you mean when you say 'not the safe way'.
If you just want to get integrated with Okta as an SPA, try running my initial code sample.
2a. You need to have a strategy here, based on your goals. My personal views on best overall architecture for an SPA are summarised in my blog posts below, but there is a lot to understand here, and some people may have different views:
Architecture Goals
Access tokens in the browser
Refresh tokens in cookies
2b. If you are building an SPA you probably should avoid older web back end session management features, though some people use them.
3a. I agree with you that this is the preferred option. Aim to build your app so that it uses tokens from one provider, regardless of login method.
3b. When you redirect to Okta, you need to do one of these:
Send an idp parameter to the Cognito issuer Id when building the authorize request
Configure Okta to prompt the user for a login method, so that either Okta or Cognito can be used as the identity provider. This may happen by default once you configure an idp connection in Okta.
FEDERATION SCREENSHOTS
I had a quick look into this, and I'm not claiming it will be easy, or even possible, since it is common to run into vendor limitations. However, it is how the technology is supposed to work. It is better for this complexity to exist in the Authorization Server than in your application code.
In Cognito create an OAuth client:
Then get the metadata for Cognito, from a URL such as this:
https://cognito-idp.eu-west-2.amazonaws.com/eu-west-2_qqJgVeuTn/.well-known/openid-configuration
Then fill in the endpoints Okta needs:
This will generate the IDP value and give you a redirect URL:
Then enter the generated values in Cognito, to complete the configuration:
| {
"pile_set_name": "StackExchange"
} |
Q:
UWP serial port communication for character write and read (UWP and Arduino)
I am using this code but not working and throwing this exception: Object reference not set to an instance of an object
devices[0] giving me null value.
private async void ConnectToSerialPort()
{
string selector = SerialDevice.GetDeviceSelector("COM7");
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);
if (devices.Count > 0)
{
DeviceInformation deviceInfo = devices[0];
SerialDevice serialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);
Debug.WriteLine(serialDevice);
serialDevice.BaudRate = 9600;
serialDevice.DataBits = 8;
serialDevice.StopBits = SerialStopBitCount.Two;
serialDevice.Parity = SerialParity.None;
DataWriter dataWriter = new DataWriter(serialDevice.OutputStream);
dataWriter.WriteString("your message here");
await dataWriter.StoreAsync();
dataWriter.DetachStream();
dataWriter = null;
}
else
{
MessageDialog popup = new MessageDialog("Sorry, no device found.");
await popup.ShowAsync();
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ConnectToSerialPort();
}
Please help me to remove this error please , i will very thankful to you .
please help :(
A:
You need add serial device capability in Package.appxmanifest like this:
<Capabilities>
<DeviceCapability Name="serialcommunication">
<Device Id="any">
<Function Type="name:serialPort" />
</Device>
</DeviceCapability>
</Capabilities>
For more information you can reference Serial device capability usage.
| {
"pile_set_name": "StackExchange"
} |
Q:
Acid-catalyzed hydrolysis of diphenyl malonate
What are the complete, acid-catalyzed hydrolysis products (with application of heat) of diphenyl malonate?
According to me, they are phenol, carbon dioxide, and acetic acid.
The aqueous acid and heat conditions indicate to me that we are returning from the carboxylic acid derivative (ester) to the carboxylic acid. The mechanism involves protonation of the carbonyl oxygen and nucleophilic attack by water. This ejects alcohol (well, in this case, phenol).
The heat induces the malonic acid intermediate to decarboxylate and this results in the production of carbon dioxide and acetic acid.
Is my analysis correct?
A:
If the question is "What are the products of hydrolysis of diphenyl malonate?", then my answer would be 2 equivalents of phenol and one equivalent of malonic acid.
If the question is "What are the products of diphenyl malonate when heated in an acid aqueous solution?", then my answer would be 2 equivalents of phenol, one equivalent of acetic acid, and one equivalent of carbon dioxide.
I see it sort of as a semantic question, since the hydrolysis of an ester gives an alcohol and a carboxylic acid, as you suggest. I don't consider decarboxylation to be a hydrolysis reaction, literally defined as cleavage of bonds by addition of water. Water isn't incorporated into the products of the decarboxylation step.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wear OS: notifications won't show
I am developing a stand alone app on Wear OS (Android 8+) and I have issues with notifications.
I am running a Foreground Service, with an on-going notification. That on-going notification works very well and has no feature from the Wear OS (so the code can work on standalone Android).
However, whenever I want to display other notifications, it is impossible.
No error message, nothing: my notifications are not displayed.
I made sure to create separate channels and to have them enabled (via the settings).
Here is my code, running in the Looper.mainLooper() via a Handler.
final Notification notification = new NotificationCompat.Builder(MonitorService.this, LOGS_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_backup_logs) // vector (doesn't work with png as well)
.setContentTitle(getString(R.string.monitor_service_notification_log_file_backed_up_process))
.setContentText("test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build();
notificationManagerCompat.notify(LOGS_ID, notification); // unique final static id
Am I missing something here ?
Thanks for the help !
A:
Use this code
Notification.Builder b = new Notification.Builder(ctx);
//FIX android O bug Notification add setChannelId("shipnow-message")
NotificationChannel mChannel = null;
b.setSmallIcon(R.drawable.ic_backup_logs) // vector (doesn't work with png as well)
.setContentTitle(getString(R.string.monitor_service_notification_log_file_backed_up_process))
.setContentText("test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mChannel = new NotificationChannel("your-channel", "yourSubjectName",NotificationManager.IMPORTANCE_HIGH);
b.setChannelId("your-channel");
}
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(id, b.build());
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysqli multi query not updating all fields
I will preface by stating I am fairly new at any type of programming.
I am working on a school assignment for video store inventory system, and I am having trouble with a multi query statement. I am attempting to update 2 fields in different tables. I have successfully updated the video table's inventory with an increment operator, but the rental table's return date will not update. I do not get any errors. However, there is not change in the empty field in the database.
I'll upload what I believe to be relevant code.
This is the HTML for the form
<form class="form-horizontal" name="returnform" id="returnform" action="" method="post">
<div align="center" class="form-group">
<label class="col-sm-2">Rental number</label>
<div class="col-sm-10">
<input class="form-control" name="Rental_ref_num" type="text" name="s" placeholder="Enter reference number..." required="">
</div>
</div>
<input id="Returned_date" name="Returned_date" type="hidden">
<input id="Movie_id" name="Movie_id" type="hidden">
<div align="center">
<input type="submit" value="Return">
</div>
</form>
I have some Javascript which sets the current date and sends it to a hidden form field.
<script>
var mydate=new Date()
var theyear=mydate.getYear()
if (theyear < 1000)
theyear+=1900
var theday=mydate.getDay()
var themonth=mydate.getMonth()+1
if (themonth<10)
themonth="0"+themonth
var theday=mydate.getDate()
if (theday<10)
theday="0"+theday
var displayfirst=theyear
var displaysecond=themonth
var displaythird=theday
document.returnform.Returned_date.value=displayfirst+displaysecond+displaythird
The PHP and queries
<?php
if ( ! empty( $_POST ) ) {
$mysqli = new mysqli( 'localhost', 'root', 'AMerica12', 'videostoremodel' );
$rd = $mysqli->real_escape_string($_POST['Returned_date']);
$rrf = $mysqli->real_escape_string($_POST['Rental_ref_num']);
////////////////////////////////////////////////////////////////////
$result = mysqli_query($mysqli,"SELECT Movie_id FROM rental_table where Rental_ref_num ='".$rrf."'");
$row = mysqli_fetch_array($result);
$name = $row['Movie_id'];
/////////////////////////////////////////////////////////////////////
$sql = "UPDATE `rental_table`
SET (`Returned_date` = '$rd')
WHERE (`Rental_ref_num` = '$rrf');";
$sql = "UPDATE `video_table`
SET `Amount_inventory` = `Amount_inventory` + 1
WHERE (`Movie_id` = '$name');";
$result = mysqli_multi_query($mysqli, $sql);
I'm sorry for the long post. However, I've searched for hours, and no matter what, I cannot figure out why the return date will not update in the rental_table. Once again, I get no error prompts.
Any help would be greatly appreciated.
A:
There are multiple problems. One is the brackets you have in the first query in the SET statement. There is no reason for brackets there and they're not allowed there. use this instead:
$sql = "UPDATE `rental_table`
SET `Returned_date` = '$rd'
WHERE (`Rental_ref_num` = '$rrf');"
Second you have to concatenate the queries, at the moment you're overwriting the first query with the second one. so use this:
$sql = "UPDATE `rental_table`
SET `Returned_date` = '$rd'
WHERE (`Rental_ref_num` = '$rrf');";
$sql .= "UPDATE `video_table`
SET `Amount_inventory` = `Amount_inventory` + 1
WHERE (`Movie_id` = '$name');";
$result = mysqli_multi_query($mysqli, $sql)
Instead of doing that i would suggest to execute 2 seperate queries instead, you can also easily implement error catching this way:
$sql = "UPDATE `rental_table`
SET `Returned_date` = '$rd'
WHERE (`Rental_ref_num` = '$rrf');";
if (!mysqli_query($mysqli, $sql)) {
echo "Errormessage: ". mysqli_error($mysqli);
}
$sql = "UPDATE `video_table`
SET `Amount_inventory` = `Amount_inventory` + 1
WHERE (`Movie_id` = '$name');";
if (!mysqli_query($mysqli, $sql)) {
echo "Errormessage: ". mysqli_error($mysqli);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem in Rick Miranda: finding genus of a projective curve
I have just started learning Riemann surfaces and I am using the book by Rick Miranda: Algebraic curves and Riemann Surfaces. #F in section 1.3 asks to determine the genus of the curve in $\mathbb{P}^3$ defined by the two equations $x_0x_3=2x_1x_2$ and $x_0^2 + x_1^2 +x_2^2 +x_3^2 = 0$. #G also has a similar question in which he asks to determine the genus of the twisted cubic. Please explain how to approach this type of question.
A:
Here's a map from the curve $X$ in $\mathbb{P}^3$ defined by $x_1 x_4 = 2 x_2 x_3$ and $x_1^2+x_2^2+x_3^2+x_4^2 = 0$, to the elliptic curve $E$ in $ \mathbb{P}^2$ given by the Weierstrass equation
$$Y^2 Z = X^3 - \frac{17822265625}{62208} X Z^2 + \frac{2269744873046875}{40310784} Z^3,$$ which is topologically a torus:
$$ [x_1:x_2:x_3:x_4 ] \mapsto [y_1:y_2:y_3] \mapsto [a:b:c] \mapsto [X:Y:Z]$$
with
$$ \begin{align*} y_1 &= x_2 x_3^2 - \frac{i}{2}x_2 x_3 x_4 - \frac{i}{2}x_3^2x_4 - \frac{1}{4} x_3 x_4^2 - \frac{i}{4} x_4^3 \\
y_2 &= x_2 x_3 x_4 - \frac{i}{2} x_2 x_4^2 \\
y_3 &= x_3 x_4^2 - i x_4^3 \end{align*},$$
(note that $y_2$ has a simple pole at $[1:i:0:0]$, $y_1$ has a simple pole at $[1:0:i:1]$ and $y_3$ has a simple pole at $[0:0:i:1]$),
$$ \begin{align*} a &= \frac{625}{36} i y_1 - \frac{625}{72} i y_2 \\
b &= \frac{-390625}{1296} i y_1 \\
c &= \frac{-4}{5} i y_1 - \frac{8}{5} i y_2 - i y_3 \end{align*},$$
and
$$ [a:b:1] \mapsto \left [\frac{1}{36}a - \frac{71875}{15552} : \frac{1}{216}b - \frac{125}{288} a +
\frac{13671875}{124416} : 1 \right ].$$
The above maps then give you an explicit homeomorphism from your curve $X$ to the elliptic curve $E$ which is topologically a torus (these in fact form an algebraic isomorphism between the two curves).
(This was obtained from embedding $X$ in $\mathbb{P}^2$ through the divisor $([1:i:0:0]) + ([1:0:i:0]) +
([0:0:i:1])$ which is very ample, and then messing around to get a nice Weierstrass equation for the resulting elliptic curve.)
| {
"pile_set_name": "StackExchange"
} |
Q:
minimum requirement to be $f=g$ , $f$, $g$ are holomorphic
Given that $f,g:\mathbb{C}\rightarrow \mathbb{C}$ are holomorphic, $A=\{x\in\mathbb{R}:f(x)=g(x)\}$. The minimum requirement for $f=g$ is
$A$ is uncountable
$A$ has positive lebesgue measure
$A$ contains a nontrivial interval
$A=\mathbb{R}$
By identity theorem to be $f=g$ we just need a limit point inside $A$, so If $A$ has positive lebesgue measure then it will contain a interval so which will have one limit point. so $2$ is correct?
A:
The irrationals have positive measure and do not contain any interval so your argument is not correct. On the other hand, being uncountable is the weakest condition and it already imply the existence of a limit point on $A$. So the answer is 1.
A:
The minimum is the list is the requirement 1. The discrete subsets of $\Bbb C$ are necessarily countable, since $\Bbb C$ is separable (*). So if $A$ is uncountable, it's not a discrete set and it has a limit point, which proves that $f\equiv g$.
(*) Let $D\subset\Bbb C$ be discrete. For $z\in D$, consider $r_z$ such that $B(z,r_z)\cap (D\setminus \{z\})=\emptyset$. Then by separability, extract from the open cover $(B(z,r_z),z\in D)$ a countable subcover of $D$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Удаление записи из таблицы без использования GET
Доброго всем времени суток.
Обычная страница, обычная ссылка, с адресом типа *.php?n=180. Ведет на страницу, которая вылавливает переменную (методом GET), и удаляет из нужной таблицы определенную запись. Само собой, если ввести в строчку адреса *.php?n=число, то удаление тоже срабатывает.
Подскажите, как правильно организовать удаление записи, чтобы простым вписыванием в строку браузера удалить нельзя было?
A:
Проверять, чтоб страница удаляла, только если авторизован тот, кому положенно.
Как защита от случайных срабатываний - то обычно делается ссылка вида del.php?n=1&rand=123456
Где rand перегенерится при каждом обращении (а главное! при самом удалении) и пишется в сессию на стороне сервера. И проверять, чтоб то что прислали, сходилось с тем, что есть в сессии.
А самое страшное, это сделать промежуточную страницу со страшным вопросом "Точно удалить?". Ссылка "ДА" делается по методу описанному в П.2 (со случайным ключиком).
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery datepicker hover output date
I am using jQuery datepicker and I want to display out the date that the user is currently hovering over. I have the code below (you can also try the code with JSFiddle, http://jsfiddle.net/JGM85/):
$(function() {
$("#datepicker").datepicker();
$(".ui-state-default").live("mouseenter", function() {
$("h1").text($(this).text());
});
});
Currently when hovering over a date, the number of the date (ie. 23) is outputed to the h1 tags. I want to change this so that it outputs the whole date and stores it in a variable.
Any help with this would be appreciated.
A:
It's not the best way I did it, because I found nothing in the jQuery UI Datepicker documentation for getting the actual Date, but here you go:
$(function() {
$("#datepicker").datepicker();
$(".ui-state-default").on("mouseenter", function() {
$("h1").text($(this).text()+"."+$(".ui-datepicker-month",$(this).parents()).text()+"."+$(".ui-datepicker-year",$(this).parents()).text());
});
});
http://jsfiddle.net/JGM85/1/
The second version with saving the actual Date + alerting it afterwards:
$(function() {
$("#datepicker").datepicker();
$(".ui-state-default").on("mouseenter", function() {
$("h1").text($(this).text()+"."+$(".ui-datepicker-month",$(this).parents()).text()+"."+$(".ui-datepicker-year",$(this).parents()).text());
var actualDate=$('h1').text();
alert(actualDate);
});
});
http://jsfiddle.net/JGM85/2/
UPDATE: I previously had .live as an event handler but .live is no deprecated and .on() is the method to go.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to modify chartjs tooltip to add customized attribute
How I have to edit the tooltip template that i can add customized attributes from my json file ? Below the example:
ChartJS Example
In the x-axis are the Months with the first letter, but in the tooltip i want to show the first three letters of the month - How can i do this ?
EDIT: My JSON File:
{"modules":[{
"name":"Chart 1",
"link":"www.google.com",
"type":"Bar",
"series":"SeriesA",
"data":[[20,40,50,40,20,20,20,20,20,20,20,20]],
"labels":["M","J","J","A","S","O","N","D","J","F","M","A","M"],
"colors":[{
"fillColor":"blue"
}],
"options":{
"scaleShowGridLines":false
}
}]}
A:
Different Labels in Tooltip vs Scale
Just use the tooltipTemplate option
Preview
Script
function Label(short, long) {
this.short = short;
this.long = long
}
Label.prototype.toString = function() {
return this.short;
}
var data = {
labels: [
new Label("J", "JAN"),
new Label("F", "FEB"),
new Label("M", "MAR"),
new Label("A", "APR"),
new Label("M", "MAY"),
new Label("J", "JUN"),
new Label("J", "JUL")
],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
// create chart
var ctx = document.getElementById("chart").getContext('2d');
new Chart(ctx).Bar(data, {
tooltipTemplate: "<%if (label){%><%=label.long%>: <%}%><%= value %>",
});
Fiddle - https://jsfiddle.net/7z1s1feg/
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to center one column with content to the left in CSS
I have a design to implement that is supposed to have a centered column of shortcuts and then a text to the left of each.
It should look like this:
The column of the shortcuts should be centered below the title.
I can't get this to work with a responsive design.
The markup I have is ATM this:
<div class="ax-learn__shortcuts">
<h2>Learn shortcuts</h2>
<div class="ax-learn__shortcuts-row">
<div>Go to home:</div>
<div><kbd>g</kbd>then<kbd>h</kbd></div>
</div>
<div class="ax-learn__shortcuts-row">
<div>Go to search:</div>
<div><kbd>g</kbd>then<kbd>s</kbd></div>
</div>
<div class="ax-learn__shortcuts-row">
<div>Go to learn:</div>
<div><kbd>g</kbd>then<kbd>l</kbd></div>
</div>
And the current CSS, which doesn't center it perfectly at all, is this:
.ax-learn__shortcuts {
display: flex;
flex-direction: column;
}
.ax-learn__shortcuts h2 {
text-align: center;
}
.ax-learn__shortcuts-row {
display: flex;
justify-content: center;
align-items: center;
}
And here's an example on Codepen
A:
By adding a pseudo as a ghost element, that matches the labels on the left, you can set that and the left labels to flex: 1, and they will take all available space and leave the kbd in the middle.
Then text-align: right for labels and margin: 0 10px for kbd, and it will look nice too :)
I added these rules, to achieve that.
.ax-learn__shortcuts-row::after {
content: '';
}
.ax-learn__shortcuts-row::after,
.ax-learn__shortcuts-row div:nth-child(1) {
flex: 1;
}
.ax-learn__shortcuts-row div:nth-child(1) {
text-align: right;
}
.ax-learn__shortcuts-row div:nth-child(2) {
margin: 0 10px;
}
Updated codepen
Stack snippet
.ax-learn__shortcuts-row {
display: flex;
justify-content: center;
align-items: center;
}
.ax-learn__shortcuts-row::after {
content: '';
}
.ax-learn__shortcuts-row::after,
.ax-learn__shortcuts-row div:nth-child(1) {
flex: 1;
}
.ax-learn__shortcuts-row div:nth-child(1) {
text-align: right;
}
.ax-learn__shortcuts-row div:nth-child(2) {
margin: 0 10px;
}
.ax-learn__shortcuts {
display: flex;
flex-direction: column;
}
.ax-learn__shortcuts kbd {
padding: 7px 15px;
border: 2px solid black;
border-radius: 5px;
background: white;
display: inline-block;
}
.ax-learn__shortcuts kbd:first-of-type {
margin-right: 15px;
}
.ax-learn__shortcuts kbd:last-of-type {
margin-left: 15px;
}
.ax-learn__shortcuts h2 {
text-align: center;
}
<div class="ax-learn__shortcuts">
<h2>Learn shortcuts</h2>
<div class="ax-learn__shortcuts-row">
<div>Go to home:</div>
<div><kbd>g</kbd>then<kbd>h</kbd></div>
</div>
<div class="ax-learn__shortcuts-row">
<div>Go to search:</div>
<div><kbd>g</kbd>then<kbd>s</kbd></div>
</div>
<div class="ax-learn__shortcuts-row">
<div>Go to learn:</div>
<div><kbd>g</kbd>then<kbd>l</kbd></div>
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
C# foreach inside while loop
I have a list with strings, I want to use Levenstein algorithm(or any other) to check if the new record I am trying to insert into a database is similar to what I have already in the database. Algorithm should go thru every single item in the list and compare with one I want to insert. If similarity is high, then break the loop and return.
I have started, but not sure If i am on the right way. How to break from foreach loop in while loop?
public static bool IsSimilarValuesExist(string value)
{
bool result = false;
string valueFromList = string.Empty;
double similarityProduct = 0;
List<string> products = ServicesMail.GetProducts();
IStringMetric metric = new Levenstein();
while (metric.GetSimilarity(value, valueFromList) < 5)
{
foreach (var item in products)
{
// If current item not similar, continue
// If is similar, break from loop and assign current compareValue to similarityProduct
}
}
return result;
}
A:
How to break from foreach loop in while loop?
Don't. Solve the problem by refactoring. Suppose you were to replace the inner loop with a method. What would the inputs and outputs of that method have to be in order to make the outer loop correct? Now actually write a method with those semantics, and your problem is solved.
| {
"pile_set_name": "StackExchange"
} |
Q:
Looking for open source graph (as in data structure) database engine
I'm writing an application that manipulates some sort of social network data, so the ideal underlying data structure is weighted directed graph. I'd like to do the manipulation (and searching) directly on the data, without first loading the entire graph into memory and serializing after.
This could be simulated using a standard SQL database, or key/value store, but that would be very inefficient (for the graph-traversal algorithms I'd like to use, e.g shortest path, etc.).
I'm half a mind to write my own since googling didn't turn up any useful results, but I'd much rather use an existing solution (if there is any and I missed it) than reinvent the wheel. The project is for fun / personal research, so the software would have to be open source (and prefferably capable of running under Linux).
So, are there any projects that would fit the above description?
Thanks!
A:
If you're using Java you can try http://neo4j.org/
| {
"pile_set_name": "StackExchange"
} |
Q:
Customizing emmeans plot
I'm using emmeans and would like to learn how to customize plots.
For a reproducible example, I'm using warpbreaks data.
library(emmeans)
lm <- lm(breaks ~ wool * tension, data = warpbreaks)
emm <- emmeans(lm, ~ wool | tension)
plot <- plot(emm, horizontal=FALSE, comparisons=TRUE) + theme_bw()
plot
Instead of the default purple color, I'd like to customize confidence interval color by group, such that all six groups (L-A, L-B, M-A, M-B, H-A, H-B) would have confidence intervals in different colors. I'd also like to customize the shape of estimated means, instead of having them all as black dots.
Here's what I tried, but it didn't work.
plot +
scale_color_manual(values=c("#F8766D", "#B79F00", "#00BA38", "#00BFC4", "#619CFF", "#F564E3")) +
scale_shape_manual(values=c(1,2,3,4,5,6))
Any help would be appreciated!
A:
Best bet is to call it with plotIt=FALSE, and save the result, which is a data frame with all the plot info. Then you can plot that stuff any way you want.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.