text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
IndexOutOfRangeException With Array
I am attempting to iterate my array of points, but I am getting the below error:
Un unhandled exception of Type 'System.IndexOutOfRangeException' occured
This is my syntax -- and i have a comment above the line that is throwing the error
How should this syntax be written so I can retrieve i - 1 position?
private void btnMakeCalc_Click(object sender, EventArgs e)
{
Point[] pts = new Point[] { new Point { X = -100, Y = 0 }, new Point { X = 0, Y = 0 } };
for (int i = 0; i < pts.Count(); i++)
{
float X1value = pts[i].X;
//The below line throws the error
float X2value = pts[i-1].X;
MessageBox.Show("X1 Is: " + Convert.ToString(pts[i].X) + "Environment.NewLine" + "X2 Is: " + Convert.ToString(pts[i-1].X));
}
}
Start with i = 1, or use i and i - 1 and finish one early.
@Winnie - if I change my loop to be i < pts.Count() - 1 I still get the same error
This is because you are trying to point to a value before the first entry, try including a check to see that it is not the (very first entry-1) you are pointing at.
Something like:
private void btnMakeCalc_Click(object sender, EventArgs e)
{
Point[] pts = new Point[] { new Point { X = -100, Y = 0 }, new Point { X = 0, Y = 0 } };
for (int i = 0; i < pts.Count(); i++)
{
float X1value = pts[i].X;
//The below line throws the error (see fix)
if (i != 0)
float X2value = pts[i-1].X;
MessageBox.Show("X1 Is: " + Convert.ToString(pts[i].X) + "Environment.NewLine" + "X2 Is: " + Convert.ToString(pts[i-1].X));
else
continue;
}
}
I like to refer to these little checks as "sanity checks" i don't know if that is colloquially accepted.
| common-pile/stackexchange_filtered |
rebuilding raid array (rocket raid 1740)
so my rocketraid 1740 controller has 4 connectors ..
i set it up with raid 5.
drive on port 4 failed, but it comes back online after computer reboots. array saw this, and started to rebuild the faulty drive.
i replaced it with new one.
i do not see a way to rebuild the array (in rocket raid bios screen the new drive was showing up as "new", but it would not let me add it as a spare)
in windows web based admin panel, i was able to initialize the new drive, and add it as a spare, but the array is showing as "disabled" and still no option to rebuild..
after rebooting, in raid bios screen, i see the drives as:
1-1: WD500AAKS 500 configured
1-2: WD500AAKS 500 configured
1-3: WD500AAKS 500 configured
1-4: WD500AAKS 500 configured (Spare)
-
but array is still "disabled" .. and when i view the array, the 4th drive (new one) is showing up as "missing" in the array, but in the devices it is showing as configured(spare)
when i plug in the old faulty drive, it goes back to "critical" state and automatically continues rebuilding.... but the drive fails shortly into it and array goes into disabled state..
i am thinking that now that the rebuild started, the remaining 3 drives are not capable to rebuild onto the new drive ?
UPDATE
little by little i am rebuilding the bad drive (it usually works for few hours after rebooting). Hopefully once i get to 100% i will be able to swap in the spare.
RAID5: never again
UPDATE
rebuild of "bad" drive finally finished and i was able to plug in the good drive.
to my horror.. 2% into rebuilding the good drive, my raid controller started beeping and the 4th drive disappeared! So possibly it's the raid controller that is bad ?!
looks like the only thing i can do now, is get another nas and back up my data using RAID 1
"Automatic detect drive to rebuild degraded RAID"....http://www.highpoint-tech.cn/USA/rr1740.htm
Needs to be marked as a spare, see the user manual on the link I posted above.
it is set to automatic, and new drive is marked as spare.
new drive keeps showing up as missing in the array setup.. even though it shows as configured (spare) in the device setup
i was right in my assumptions that the array already started re-building using the bad drive, and i had to wait it out.
after it was done, i plugged in the new drive and it worked.
to my dismay however, after it rebuilt the good drive, it failed again.. so it looks like the controller is at fault.
Raid 5: never again.
| common-pile/stackexchange_filtered |
Get to intermediate values in middle of a functional programming chain
I'm wondering if there's a concise or specific way to access values in the middle of an FP chain in JavaScript. Example:
const somestuff = [true, true, false];
let filteredCount = 0;
somestuff.filter((val) => val)
.forEach((val) => console.log(val));
Above, I'd like to set filteredCount to the length of the array returned by the filter function. The most straight-forward way is:
const somestuff = [true, true, false];
const filteredStuff = somestuff.filter((val) => val);
let filteredCount = filteredStuff.length;
filteredStuff.forEach((val) => console.log(val));
This is certainly valid but it breaks our FP chain and introduces an additional holding variable. I'm wondering if there's a convention for accessing values in the middle of the chain. Something like .once() that runs once and implicitly returns the value passed in, but nothing like that exists.
I think you are confusing FP and OOP. There is no "chaining" in FP. Introducing multiple variables in multiple lines is simple and correct.
filteredStuff.forEach((val,i,me) => console.log(val, me.length)); or filteredStuff.forEach((val) => console.log(val, this), filteredStuff.length); i use this a lot in "functional" js, it's a great "extra" parameter that enables stuff like function gt(x){return x>this;} which is then used as [1,2,3,4,5].filter(gt, 3): intermediates are called this.
"it breaks our FP chain and introduces an additional holding variable" can you explain this or give me a resource what you mean and why?
For debugging, I often use a function called tap to temporarily add a side-effect (like your console.log) to a function:
const tap = f => x => (f(x), x);
This function returns whatever it is passed, but not before calling another function with the value. For example:
const tap = f => x => (f(x), x);
const tapLog = tap(console.log);
const x = tapLog(10);
console.log("x is", x);
Your snippet basically does this:
Filter a list
(log the list)
Retrieve a length property from an array
If you construct this function using pipe or compose, you can "inject" the console.log in between without interrupting the data flow:
const countTrues = pipe(
filter(isTrue),
prop("length")
);
const countTruesWithLog = pipe(
filter(isTrue),
tap(console.log),
prop("length")
);
In a snippet:
// Utils
const isTrue = x => x === true;
const prop = k => obj => obj[k];
const tap = f => x => (f(x), x);
const filter = f => xs => xs.filter(f);
const pipe = (...fns) => x => fns.reduce((res, f) => f(res), x);
// Logic:
// Filter an array using the isTrue function
// and return the length of the result
const countTrues = pipe(
filter(isTrue),
prop("length")
);
// Create a filter with a console.log side-effect
// and return the length of the result
const countTruesWithLog = pipe(
filter(isTrue),
tap(console.log),
prop("length")
);
// App:
const somestuff = [true, true, false];
console.log("pure:");
const countA = countTrues(somestuff)
console.log(countA);
console.log("with log:")
const countB = countTruesWithLog(somestuff);
console.log(countB);
The reason there's no Array.prototype method like that, is that it has a side effect. This is something that is specifically avoided in functional programming.
However if you don't care about writing 'Pure Functions', or even the functional paradigm, you could put the side effect in your callbacks, or write a function in the Array prototype.
ie.
Array.prototype.once = function(callback) {
callback(this)
return this
}
You also have other hacky options like in the other answer
I wonder though why you didn't put this method right on Object.prototype. Why should only array benefit from this? :-D
@Bergi Hah. Yeah Why not. I just mostly use arrays
I don't think there's something like that by default. What you can do is extend Array, but I'm not really fond of extending framework classes (clashes with other once implementations for example). In this case you'd end up with:
Array.prototype.once = function once(func) {
func(this);
return this;
}
which is called like:
var filteredStuff = somestuff
.filter((val) => val)
.once(function(array) {
console.log(array.length);
})
.forEach((val) => console.log(val));
On the other hand, you can try to use default functions. One of these function that can access all items at once is reduce. Define a function once, that will call its first parameter once (:)) and you'd end up with something like:
function once(func) {
return function(accumulator, currentValue, currentIndex, array) {
if(currentIndex === 1) {
func(array);
}
return array;
}
}
which you'd be able to call like this:
var filteredStuff = somestuff
.filter((val) => val)
.reduce(once(function(array) {
console.log(array.length);
}), [0])
.forEach((val) => console.log(val));
Notice the ugly [0] to ensure once calls the passed function at least once (empty array included).
Both solutions aren't too neat, but it's the best I can come up with given the criteria.
| common-pile/stackexchange_filtered |
how to see the data in DataLoader in pytorch
I see something like the following in the examples on Github.
How can I see the type of this data (shape and the other properties)?
train_data = MyDataset(int(1e3), length=50)
train_iterator = DataLoader(train_data, batch_size=1000, shuffle=True)
You can inspect the data with following statements:
data = train_iterator.dataset.data
shape = train_iterator.dataset.data.shape
datatype = train_iterator.dataset.data.dtype
You can iterate the data and feed to a network as:
for nth_batch, (batch,_) in enumerate(train_iterator):
feedable = Variable(batch)
#here goes neural nets part
As Ivan stated in comments Variable is deprecated (although it still works fine) and Tensor itself now supports autograd, so the batch can be used in neural net.
for nth_batch, (batch,_) in enumerate(train_iterator):
#feedforward the batch
You shouldn't use Variable, it has been deprecated, see here.
| common-pile/stackexchange_filtered |
Elliptic Integrals of the First Kind
Suppose I have $$F(\phi(x), k) = x$$ where the elliptic integral of the first kind is defined to be $$F(\phi, k) = \int_{0}^{\phi} \frac{1}{\sqrt{1-k^2\sin(\theta)}} \, d\theta $$
How could I invert this in order to make $\phi$ the subject?
Use Jacobi elliptic functions
Maple has this (in terms of the elliptic function sn):
That last function is more often denoted the Jacobian amplitude. Note that the Jacobian amplitude is not doubly periodic (it is quasiperiodic, however), and thus not elliptic, but composing it with trigonometric functions does yield elliptic functions.
Just to complement GEdgar's answer (+1):
This Wikipedia article gives the definition of the Jacobi elliptic function $sn(x)$ as the inverse of the incomplete elliptic integral of the first kind.
The article gives lots of other definitions of $sn(x)$ by means of either doubly periodic meromorphic functions or alternatively in terms of theta functions, but I believe you re going to be disappointed if you want an inverse function which is easily expressible in terms of elementary functions - sorry.
| common-pile/stackexchange_filtered |
How to make an object slide left and right automaticly in Unity 5.6?
I'm currently developing a game in Unity 3D with c#. I developed some levels, and now I want to make some levels with auto moving cubes(the thematic of the game is cubes). I searched a lot on the internet but I don't find nothing wich satisfy me. Can someone help me? I really need help. Sorry if there are some grammare errors.
What do you mean by slide "left and right"? Are they moving from one given position to the other and back?
I don't now if exactly that. I want to make a cube move left and right, smoothly, and never stop. Can you please help me? I can use .AddForce?
Could you please specify what your intentions are? There are numerous ways to do what you want, but if you don't specify what you need, no one will help you. Maybe you could create a scribble and upload it, so it is easier to understand your target.
Well, I will try to explain better. I have a 3d game made with Unity3d and C#.I have maked some levels and now I want to make a level when there are some cubes that can go from left to right. So start from a point and then when a certain distance or a certain point is hitted, the cube will go back to the starting point and it need to make that infinite times.
Create a new Script an name it SimpleTranslator.cs then copy and paste the below code.
using UnityEngine;
namespace TransformUtility
{
public class SimpleTranslator : MonoBehaviour
{
[Tooltip("The local target position towards we translate this gameObject. A red line is drawn.")]
public Vector3 m_localTargetPosition = new Vector3(0, 0, 5);
public float speed = 1;
public bool pingPong;
public bool translateOnAwake = true;
public new AudioSource audio;
Vector3 m_initialPosition, m_targetPosition;
Transform m_transform;
void Awake()
{
m_transform = transform;
m_initialPosition = m_transform.position;
SetTargetPosition(m_localTargetPosition);
enabled = translateOnAwake;
}
void FixedUpdate()
{
if (audio && !audio.isPlaying)
audio.Play();
m_transform.position = Vector3.MoveTowards(m_transform.position, m_targetPosition, speed * Time.deltaTime);
if (m_transform.position == m_targetPosition)
{
if (pingPong)
{
SwitchDirection();
}
else
{
enabled = false;
if (audio)
audio.Stop();
}
}
}
public bool isTranslating
{
get
{
return enabled;
}
}
public void SwitchDirection()
{
enabled = true;
if (m_transform.position == m_initialPosition)
{
SetTargetPosition(m_localTargetPosition);
}
else
{
m_targetPosition = m_initialPosition;
}
}
public void MoveToTargetPosition()
{
enabled = true;
SetTargetPosition(m_localTargetPosition);
}
public void MoveToInitialPosition()
{
m_targetPosition = m_initialPosition;
enabled = true;
}
public bool isInInitialPosition
{
get
{
return m_transform.position == m_initialPosition;
}
}
public bool isInTargetPosition
{
get
{
return m_transform.position == m_initialPosition + m_transform.TransformDirection(m_localTargetPosition);
}
}
private void SetTargetPosition(Vector3 localPosition)
{
m_targetPosition = m_initialPosition + transform.TransformDirection(localPosition);
#if UNITY_EDITOR
m_endPositionDebug = m_targetPosition;
#endif
}
#if UNITY_EDITOR
Vector3 m_endPositionDebug;
void OnDrawGizmos()
{
if (!Application.isPlaying)
{
Debug.DrawRay(transform.position, transform.TransformDirection(m_localTargetPosition), Color.red);
}
else
{
Debug.DrawLine(m_initialPosition, m_endPositionDebug, Color.red);
}
}
#endif
}
}
And that script I should put to the cube wich I want to make move?
Yes. Sorry. i forgot that :)
Thanks for the reply. But my cube go only in one direction, it does not come back and the go another time to the previous direction. How I make something like this?
i dont have unity installed here.... But...
I use that scrip in a lot of projects. Select the cube with the script attached an check the Ping Pong property in the Editor
Can you help me?
Thanks a lot I don't seen your last comment
Your Welcome. If you need some help with your project let me know.
Ok. I will remember that :D
| common-pile/stackexchange_filtered |
How to convert timestamp?
I am building an iOS app using Rubymotion.
I get data from a Rails 3.2.8 API and I want to convert the timestamp I get (2013-01-24T23:42:59Z) to 2013-01-24 23:42:59. How can I do that with Ruby?
What is this format called (2013-01-24T23:42:59Z)?
Do you mean printing a String from a timestamp formatted like 2013-01-24 23:42:59?
I need to convert this: 2013-01-24T23:42:59Z into this 2013-01-24 23:42:59. Simple loose the T and the Z.
By the way, I would recommend upgrading your Rails 3.2.8 to Rails 3.2.11 -- there are some very significant security issues in 3.2.10 and before.
Perhaps it is called ISO 8601. You can accept this form and turn it into a time object by doing this:
require "time"
Time.iso8601("2013-01-24T23:42:59Z")
# => 2013-01-24 23:42:59 UTC
Thanks! How can I loose the UTC part?
Play around with Time#strftime.
That is not available in Rubymotion unfortunately.
Wrongo - Time#strftime IS available in Rubymotion. Scroll down to the "Various ISO 8601 formats" section in Ruby's strftime documentation to see how to build the ISO-8601 formats from the strftime primitives.
| common-pile/stackexchange_filtered |
Replace Unicode escapes with the corresponding character
I'm trying to convert code points, such as \u00FC, to the character it represents.
import javax.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
String in = JOptionPane.showInputDialog("Write something in here");
System.out.println("Input: " + in);
// Do something before this line
String out = in;
System.out.print("And Now: " + out);
}
}
An example to explain what I mean:
First Console line: Input: Hall\u00F6
Second Console line: And Now: Hallö
EDIT: Because sometimes it didn't work with multiple Unicodes in The Trombone Willy's answer, here is the Code fixed:
public static String unescapeUnicode(String s) {
StringBuilder r = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.length() >= i + 6 && s.substring(i, i + 2).equals("\\u")) {
r.append(Character.toChars(Integer.parseInt(s.substring(i + 2, i + 6), 16)));
i += 5;
} else {
r.append(s.charAt(i));
}
}
return r.toString();
}
no I don't know what you mean, what is your problem so far?
Well if you enter "Hall\u00F6" when my code starts, it will also Write "Hall\u00F6" to the console both times, but I want that the second time it gives me "Hallö" because "\u00F6" is the unicode of "ö"
You'd need to explicitly parse those out. Escape sequences like \uXXXX are only in Java source code and don't exist in the console. This lightly touches on it
Joao's answer is probably the simplest, but this function can help when you don't want to have to download the apache jar, whether for space reasons, portability reasons, or you just don't want to mess with licenses or other Apache cruft. Also, since it doesn't have very much functionality, I think it should be faster. Here it is:
public static String unescapeUnicode(String s) {
StringBuilder sb = new StringBuilder();
int oldIndex = 0;
for (int i = 0; i + 2 < s.length(); i++) {
if (s.substring(i, i + 2).equals("\\u")) {
sb.append(s.substring(oldIndex, i));
int codePoint = Integer.parseInt(s.substring(i + 2, i + 6), 16);
sb.append(Character.toChars(codePoint));
i += 5;
oldIndex = i + 1;
}
}
sb.append(s.substring(oldIndex, s.length()));
return sb.toString();
}
I hope this helps! (You don't have to give me credit for this, I give it to public domain)
Try this:
StringEscapeUtils.unescapeJava("Hall\\u00F6")
In which API do we find this class? What does it do exactly? A little explaination does not hurt here.
It is found on commons-lang:
org.apache.commons
commons-lang3
${commons.lang3.version}
.
essentially it unescapes any Java String Literal which includes unicode string literals. Check the api here apache-commons-lang3
and you can find this in Maven Repository here.
Thank you, too. But because of the licenses and exporting stuff I will use the code from the other answer for now.
The preferred version of StringEscapeUtils is now in commons-text, not commons-lang3.
| common-pile/stackexchange_filtered |
Using two different versions of python but sqlmap needs 2.7
I've recently started using sqlmap and found out it needs python2.7. I installed 2.7 and added it to my PATH along with 3.4. My current path looks like this:
c:\Other-Programs\;c:\Python27;c:\Python34
So When I try to run sqlmap i follow these steps:
1. Open up cmd as admin
2. cd c\:sqlmap
3. python sqlmap.py
At this point, sqlmap informs me that Python 3.4 is incompatible.
I tried just doing:
3. python27 sqlmap.py
That returns an error stating that it's not a command.
Basically I want to know how I can specify the version of Python I want to use when running a command for sqlmap.
try using full path of python exe C:\Python27\python.exe sqlmap.py.
While you normally would try to do something clever with PATH definition here, a very simple solution would be to do something like this (unproven because I'm not on Windows but)
C:\Python2.7\bin\python.exe your_script_for2.7.py (make sure you are pointing to the right path of python.exe) and for 3.x
C:\Python3.x\bin\python.exe your_script_for3.x.py
What you're experiencing is probably the latest python installed, replaced the global python executable. You should be able to use python2.7 or python3.x as well though.
Me too had similar problem in windows, i was having python 3.5(and its path set in environment variables), so i installed python 2.7 from their site.then i did the following to start sqlmap
1) Got inside the folder of python 27 in cmd
2) executed the following command
python.exe "path to sqlmap-dev\sqlmap.py"
| common-pile/stackexchange_filtered |
Passing a string as a regex pattern to String.prototype.replace
How to convert a string to a regex pattern that works with the string.replace prototype?
Expected solution:
var regex = "/(\w+)_(\w+)/i";
var pattern = new RegExp(regex);
console.log("some_name".replace(pattern, "$1-$2"));
// expected output: some-name
// output: some_name
[Edit 1]
It appears to be that the regex pattern was part of the reason the code above would not work as expected, however, for some reason, passing the same pattern as a RegExp, as King Stone outlined, does.
Just as a heads up, \w also captures the _ character.
It turns out the regex was confusing me, since it works as a RegExp but it doesn't work as a string converted to RegExp.
Use the RegExp constructor only when your regular expression is dynamic.
Regular expressions aren't Strings, so you need to remove the quotation marks out of the expression. The forward slashes at the beginning and the end (sometimes followed by i and g) are what determine the bounds of the expression:
var regex = /(\w+)_(\w+)/i;
var pattern = new RegExp(regex);
console.log("some_name".replace(pattern, "$1-$2"));
Could you please elaborate on why does The fourth bird's regular expression work despite being enclosed within quotation marks?
@WaleedQidan probably because they omitted the forward slashes
var pattern = /(\w+)_(\w+)/i;
// var pattern = new RegExp(regex);
console.log("some_name".replace(pattern, "$1-$2"));
Output:
some-name
Hi, could you explain what you've changed ?
The problem with this is that the pattern is not actually being passed as a string but as a RegExp. The objective is to convert a string into an instance of RegExp and pass it to string.prototype.replace.
You are passing a regex to the constructor of RegExp. See Regular Expressions.
As \w also matches an underscore, you can match a word character except the underscore using a negated character class [^\W_]
([^\W_]+)_([^\W_]+)
Regex demo
Note to double escape the backslashes for the RegExp constructor.
If the objective is to convert a string into an instance of RegExp and pass it to string.prototype.replace you might use:
let str = "([^\\W_]+)_([^\\W_]+)";
let pattern = new RegExp(str);
console.log("some_name".replace(pattern, "$1-$2"));
@WaleedQidan It works because \w+ will first match all the characters in the string some_name, then it will backtrack to match the _ and then it will match the rest of the string with the second \w+ You can prevent the backtracking to match a word character without the underscore using [^\W_]
thank you for your explanation. However, my question is why does the same regex pattern "/(\w+)_(\w+)/i" return the expected result (some-name) when passed as an instance of RegExp var = /(\w+)_(\w+)/i?
@WaleedQidan That is explained on this page
| common-pile/stackexchange_filtered |
equivalent to hwclock in Solaris?
Hi all is there an equivalent in Solaris 10 (i86) for hwclock?
I'd like to read the bios time on a machine without rebooting and checking manually.
Thanks.
On Solaris the hardware and system clock are in sync and are both set to UTC (~GMT). You can use the "date -u" command to display that clock.
| common-pile/stackexchange_filtered |
Intersection of elements of sets
Even I try but I can not understand the following equation:
$
Poss(A) = \bigcap_{a \in A}\lbrace e | e \in Poss(a) \rbrace
$
where $A=\lbrace a1,a2,a3 \rbrace$
and $Poss(a)$ is a set of sets, for example:
$Poss(a1)=\lbrace \lbrace 2,7 \rbrace, \lbrace 1,2,5,7 \rbrace \rbrace $
$Poss(a2)=\lbrace \lbrace 3,6 \rbrace, \lbrace 1,3,6 \rbrace \rbrace $
$Poss(a3)=\lbrace \lbrace 4,6 \rbrace, \lbrace 1,4,6 \rbrace \rbrace $
So, I am not sure which one of the following two is right? Or both are wrong?
$Poss(A)= \emptyset$ because there is no common sets between Poss(a1) Poss(a2), and Poss(a3)
OR
$Poss(A)= \lbrace 1 \rbrace$ because 1 in $\lbrace 1,2,5,7 \rbrace $ of Poss(a1), in $\lbrace 1,3,6 \rbrace $ of Poss(a2), and in $\lbrace 1,4,6 \rbrace $ of Poss(a3).
Please help me.
Thank you very much.
Welcome to MSE. Please choos your tags with care. This has nothing to do with intersection-theory.
Your first guess is correct.
Since $\{e\mid e\in\text{Poss}(a)\}=\text{Poss}(a)$ you might as well write: $$\text{Poss}(A)=\bigcap_{a\in A}\text{Poss}(a)$$
So actually we have:$$e\in\text{Poss}(A)\iff\forall a\in A[e\in\text{Poss}(a)]$$
So if $A=\{a_1,a_2,a_3\}$ this comes to the same as:$$e\in\text{Poss}(A)\iff [e\in\text{Poss}(a_1)\wedge e\in\text{Poss}(a_2)\wedge e\in\text{Poss}(a_2)]\tag1$$
Can you find any set $e$ that satisfies the RHS of $(1)$?
Thank you very much. I am not quite good at these things. Can I ask you more. If $Poss(a1)=\lbrace \lbrace 2,7 \rbrace, \lbrace 1,2,5,7 \rbrace \rbrace $
$Poss(a2)=\lbrace \lbrace 2,3,7 \rbrace, \lbrace 1,3,6 \rbrace \rbrace $
$Poss(a3)=\lbrace \lbrace 2,4,7 \rbrace, \lbrace 1,4,6 \rbrace \rbrace $, --> is $Poss(A)=\lbrace \lbrace 2,7 \rbrace \rbrace $ ??? This one is different from the case above, because $ \lbrace 2,7 \rbrace $ already belongs to $Poss(a1)$
No. ${2,7}$ is an element of $Poss(a1)$ but definitely is not an element of $Pos(a_2)$ (which has 2 elements that are both not equal to ${2,7}$). Again the answer is $\varnothing$ here.
Thank you very much. One more question. If Poss(A) represents the intersections of each element of Poss(a1) with each element of Poss(a2) (and Poss(a3) and so on), how can I represent it by mathematical equation? I just want to make myself really understand math.
Then $\text{Poss}(A)={a\cap b\cap c\mid a\in\text{Poss}(a_1),b\in\text{Poss}(a_2),c\in\text{Poss}(a_3)}$. If my answer is enough for you to understand, then you should accept it.
Thank you very much for explaining.
| common-pile/stackexchange_filtered |
How can ClickOnce change the app.config from development to deployment one?
I have a development app.config and a deployment app.config. I need clickonce to change it on deployment.Is this posible to be done automatically?
An easy way would be to copy the app.config file in the pre-build script that you can define in the app's property page Build events.
You could do either:
1) Create a solution config used only for deploying to production, and switch on that in the script, e.g.
if ($(ConfigurationName)) == (PublishConfig) call ReplaceAppConfig.cmd
or, if you only build the publish config on a specific machine:
2) Always run the script in the pre-build event:
call CheckAndReplaceAppConfig.cmd
and the CheckAndReplaceAppConfig.cmd would in this case have:
IF (%MACHINENAME%)==(PUBLISH_SERVER) ReplaceAppConfig.cmd
If you don't want to re-build your application, you can try this approach that works on the deployed files directly.
As part of our testing workflow, we often setup multiple deployments of the same application with only differences in the .config file. We really don't want to have to re-publish every time we want to add a new deployment with a different config file. Since ClickOnce demands that everything will be signed and hashed, it's not possible to just change the myapp.exe.config.deploy file contents and expect everything to work. So what you can do is use mage.exe to update your manifests after you make the change.
As mentioned here, what you basically need to do is:
First, go to the "Application Files\MyApp_1_2_3_4\" directory in your deployment dir
You have to rename all the files from something.extension.deploy to something.extension
Then Run:
mage -Update "Application Files\MyApp_1_2_3_4\myapp.exe.manifest"
mage -Sign "Application Files\MyApp_1_2_3_4\myapp.exe.manifest" -CertHash my_ceritficate_thumbnail
Then rename the files back to their original names (add the .deploy extension)
Finally, run:
mage -Update MyApp.xbap -appmanifest "Application Files\MyApp_1_2_3_4\myapp.exe.manifest"
mage -Sign MyApp.xbap -CertHash my_certificate_thumbnail
Alternatively, to avoid renaming the files you can tell Visual Studio to not add the .deploy extension when publishing (go to Publish...Options in the visual studio project) and next time, when you publish, the files won't get that extension. My only guess at the danger of that is hitting firewall problems with certain users when they try to download .exe or .dll files.
If you are using the VS tools, then the config files are all part of the signed portion of the deployment. As such, the best way to do this is via your build tools - i.e. build a different version with dev/live/etc config files.
With 3.5SP1 you can opt out of the signing; I don't know if you can do this via the IDE - presumably you can do it if you do it manually (via mage), but this is a lot more work...
It can be done with Mage, but we generally opt for different build versions. As Marc says, it's simpler.
I think this is a better way of doing it:
http://blogs.msdn.com/b/vsto/archive/2010/03/09/tricks-with-app-config-and-clickonce-deployment-saurabh-bhatia.aspx
This link is dead. It would have been helpful if you had pasted some of the salient content.
| common-pile/stackexchange_filtered |
Pass Email Id as parameter in WCF restful service
Suppose I have a web service which accept email id and password as parameter in url . I have to authenticate user by email id and password. using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.Text;using System.ServiceModel.Web;namespace WebApp.Services{[ServiceContract]public interface IService { [WebInvoke(Method = "GET", UriTemplate = "/authenticate/{emailId}/{password}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] [OperationContract] Boolean Authenticate(string emailId, string password); }}
we call web service like it :
<EMAIL_ADDRESS>because email contain '.' which is not encoded by the web browser , so web service function is not called .
There is any solution to pass email id in url other than query string .
If You could use POST:
[ServiceContract]
public interface IMyService
{
[OperationContract]
bool Authenticate(EmailCredential request);
}
[DataContract]
public class EmailCredential
{
[DataMember]
public string EmailId {get; set;}
[DataMember]
public string Password {get; set;}
}
and call service using WebClient or WebHttpRequest with that xml (i don't know now how json looks like for this so xml)
<EmailCredential >
<EmailId<EMAIL_ADDRESS>>
<Password >123</Password >
</EmailCredential >
oh it is another way for doing it , but there is any alternative way for it with GET request .
Unfortunately every GET request will be refused cause problem u mention:/ So I see that only solution is POST.
There is a option if you send email id as base 64 encoded and in service function decoded it .
| common-pile/stackexchange_filtered |
loop through range and insert unique data to access database
Hope you're all having a good day. I'm looping through a range from an open workbook and for each loop i need to check if the details are in my access table and if not insert the details. I have the following code which i think should work well but seems excel has an issue with opening and closing a RecordSet each loop. Think that's the issue anyway as it doesn't throw any exception it just stops responding and i have to close the workbook
The loop it's self works great as I've tested without the SQL part and it completed over 100K records in under 1 minute. Any help on this would be really appreciated.
With dbConnection
.Provider = "Microsoft.ACE.OLEDB.12.0;"
.ConnectionString = dbConnectionString
.Open
ItemsAdded = 0
dbRecordSet.ActiveConnection = dbConnection
For i = 1 To DataFile.ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
oSQL = _
"Select * From " & TableName & " Where CompanyName = """ & Trim(DataRange(i, 1)) & """" & _
" And CommCode = """ & Trim(DataRange(i, 2)) & """;"
dbRecordSet.Open oSQL, dbConnection
If dbRecordSet.EOF = True Then 'Does not exist in the access database so add it
dbRecordSet.Close
dbConnection.Execute "INSERT INTO [" & SearchType & "Table_" & oYear & "] (CompanyName, CommCode, GoodsDescription, MonthsImported, " & _
"AddressLine1, AddressLine2, Town_City, County, PostCode) VALUES " & _
"(""" & DataRange(i, 1) & """, """ & DataRange(i, 2) & """, """ & Replace(DataRange(i, 3), """", "") & """, """ & DataRange(i, 4) & """, """ & _
Replace(DataRange(i, 5), """", "") & """, """ & DataRange(i, 6) & """, """ & DataRange(i, 7) & """, """ & DataRange(i, 8) & """, """ & DataRange(i, 9) & """);"
ItemsAdded = ItemsAdded + 1
Else: dbRecordSet.Close
End If
Next i
.Close
End With
I believe the dbRecordSet.Close should be within the Else: statement if you want to close it once the insertion query takes place?
Hi Fishing Code. Thanks for posting. I have the rs closing in the else statement "Else:dbRecordSet. Close" so think that's OK.
| common-pile/stackexchange_filtered |
BigDecimal 2.0 is coming equal to BigDecimal 2.00
I read the Java doc of BigDecimal.equals() says:
Compares this BigDecimal with the specified Object for equality.
Unlike compareTo, this method considers two BigDecimal objects equal
only if they are equal in value and scale (thus 2.0 is not equal to
2.00 when compared by this method).
But when I am testing it then somehow I am getting unexpected result and BigDecimal(2.0) is coming equal to BigDecimal(2.00). And I think for the same reason when I put BigDecimal(2.0) and BigDecimal(2.00) in HashSet then size comes as 1, while I was expecting size to be 2.Please see below code, and if someone could please point out if I am missing something?
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class CollectionTest {
public static void main(String[] args) {
System.out.println(new BigDecimal(2.0).compareTo(new BigDecimal(2.00))); // 0
System.out.println(new BigDecimal(2.0).equals(new BigDecimal(2.00))); // true -- ** UNEXPECTED **
HashSet<BigDecimal> hashset = new HashSet<>();
Set<BigDecimal> treeset = new TreeSet<>();
hashset.add(new BigDecimal(2.0));
hashset.add(new BigDecimal(2.00));
treeset.add(new BigDecimal(2.0));
treeset.add(new BigDecimal(2.00));
System.out.println("hashset.size(): " + hashset.size()); // 1 -- ** UNEXPECTED **
System.out.println("treeset.size(): " + treeset.size()); // 1
}
}
Do not use the new BigDecimal(double) constructor. Use the one with the String argument instead. See the notes on https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#BigDecimal-double-
At compile time the doubles 2.0 and 2.00 are the same. You need a String. Like,
System.out.println(new BigDecimal(2.0).equals(new BigDecimal("2.00")));
Outputs
false
Your current code is the equivalent of
System.out.println(2 == 2.00);
Which is obviously true.
To expand on that last example, consider
BigDecimal a = new BigDecimal(2.0);
BigDecimal b = a.setScale(2);
System.out.printf("%s equals %s is %s%n", a, b, a.equals(b));
which should explain why your current code behaves as it does; because
2 equals 2.00 is false
Thanks, +1 but does it mean that in case of BigDecimal("2.00"), it tries to compare BigDecimal as String, while in case of BigDecimal(2.00) it tries to compare BigDecimal as a decimal primitve?
@pjj No, the double literals 2.0 and 2.00 are the same double value, so the BigDecimal values you create have the same value.
@Elliott: could you please clarify my above doubt so that I can accept it as answer. I know it might be silly but it is hanging in my mind.
@pjj There is an internal scale part in BigDecimal, which is checked in the equals() method. When you have the number 42 with the scale of 2, that BigDecimal instance will be different (according to equals()) to a different BigDecimal instance with the same value 42, but with the different scale 5.
| common-pile/stackexchange_filtered |
IIS 7, MVC2 Web Service, HTTP 405 Error on PUT
This is a similar question as IIS 7.5, Web Service and HTTP 405 error but a little different. Instead of a WCF web service, I've got an MVC2 web service that returns a 405 error when a PUT is used in the request. And, in my case, POST works just fine.
I'm guessing I need to either add or tweak an IIS 7 Handler Mapping to get PUT to work but my hosting provider hasn't been much help. Anyone out there run into this and know how to get PUTs to work in an MVC2 web service running in IIS 7? My apologies if this has already been answered, I've been searching all day and haven't found the magical answer.
Any help would be greatly appreciated...
We had the same problem, and the solution was adding an element into section in the Web.config file:
<remove name="WebDAVModule"/>
thx, simple and worked! there's so many posts out there for this, and this should be the official answer for them all
Have a look at https://serverfault.com/questions/93424/how-to-enable-put-and-delete-in-iis7/93428#93428
dario-solera:
You can take a look at the "Handlers
Mappings" sections at either the
server or site level (IIS group).
Select a mapping for an extension
(e.g. .aspx) and select "Edit" from
the context menu. The "Verbs" tab
allows you to specify verbs to accept.
Thanks, Greg. Unfortunately, I don't know what mapping to select. I'm working with a RESTful MVC2 web service so there really isn't any file extension associated with the urls. I've tried tweaking the ExtensionlessUrl-Integrated-4.0 mapping, adding the PUT verb to it, but that didn't help. Perhaps I'll need to create a new one to allow PUTs?
| common-pile/stackexchange_filtered |
Populating dynamic select dropdown in json or xml (AND HOW)
I need to populate this type of drop-down dynamically.
First is visible by default and on select of a particular option the corresponding 2nd drop-down will show up with its relevant options and hiding others.
Then on select of its option the third level drop-down should open up with the corresponding options.
Is it better to handle this data in XML or JSON? I am having a tough time in parsing this data using jQuery and AJAX. Can somebody help me in getting this up in dynamic way. My HTML doesn't have any tags. It should all be populated dynamically.
Thanks.
Here is how the HTML should be rendered. Again by default Only the first drop-down will be visible on select of its option the second drop-down should be populated with its relevant options and so on...
http://jsfiddle.net/wNjLm/1/
I would definitely use JSON. Here is a small example:
var data = [
{
name: "English Languages",
values: ["English 1", "English 2", "English 3", "English 4"]
},
{
name: "French Languages",
values: ["French 1", "French 2", "French 3", "French 4"]
},
{
name: "Spanish Languages",
values: ["Spanish 1", "Spanish 2", "Spanish 3", "Spanish 4"]
}
];
for(var i = 0; i < data.length; i++) {
var category = data[i];
var optgroup = $("<optgroup>").prop("label", category.name);
for(var j = 0; j < category.values.length; j++)
optgroup.append($("<option>").text(category.values[i]));
$("#lang").append(optgroup);
}
http://jsfiddle.net/wNjLm/2/
This will populate a select with the JSON data (already loaded in this case).
Are you not taking the country names in json object, where will they go.
The country names could also be in JSON. A simple array would do.
Is it possible to post a fiddle
| common-pile/stackexchange_filtered |
How do I target arm64, excluding x86_64, in flutter run -d macos?
flutter run -d chrome runs with no issues, but -d macos triggers the following warning. I'm on arm64, and am happy compiling during development for just arm64. How do I target arm64 alone?
flutter run -d macos
Launching lib/main.dart on macOS in debug mode...
--- xcodebuild: WARNING: Using the first of multiple matching destinations:
{ platform:macOS, arch:arm64, id:00006000-0008299F2229401E }
{ platform:macOS, arch:x86_64, id:00006000-0008299F2229401E }
Building macOS application...
Why the downvote? Please add a comment.
When they don't say it's often just someone that gets off on downvoting.
Apparently setting the flags directly on the flutter run command no longer is an option, so you'll have to set the EXCLUDED_ARCHS manually. There are quite a few ways to do this, so I'll give you a couple of simple options:
Edit the Podfile in your project:
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings["EXCLUDED_ARCHS[sdk=macos*]"] = "x86_64"
end
end
end
Then pod install
Directly edit the project.pbxproj:
Modify your macos/Runner.xcodeproj/project.pbxproj file. Look for the EXCLUDED_ARCHS build setting and set it to x86_64.
As far as I know EXCLUDED_ARCHS is the only way to build for one particular architecture. You could poke around the file here, although that is not specific the the flutter run command.
This sounds exactly right, but something is off. Also googling for "FLUTTER_TARGET_PLATFORM_ARCH" doesn't bring up anything, which suggests there is a typo. Can you double-check?
Probably not an option now; see edit.
| common-pile/stackexchange_filtered |
Why are accented characters rendering inconsistently when accessing the same code on the same server at a different URL?
There is a page on our server that's reachable via two different URLs.
http://www.spotlight.com/6213-5613-0721
http://www.spotlight.com/interactive/cv/1/M103546.html
There's classic ASP behind the scenes, and both of those URLs actually do a Server.Transfer to the same underlying ASP page.
The accents in the name at the top of the page are rendering correctly on one URL and incorrectly on the other - but as far as I can tell, the two requests are returning identical responses (same markup, same headers, same everything) - and I have absolutely no idea why one URL should be rendering correctly whilst the other is corrupting the accented characters.
Is there anything else (content encoding?) that I should be examining - and if so, how can I tell what's being returned beyond the information displayed in Firebug?
I been in this problem in the past and the problem was that some file (maybe the asp file that do the transfer or some include) is not saved as ANSI.
Check that all files involved in the request has the same encoding in the server (try File -> Save As With Encoding)
Now you mention it, I think you're right - we've had similar issues with rogue file encoding before...
Which brings me to my next question:
http://stackoverflow.com/questions/2455106/how-can-i-determine-file-encodings-on-windows-iis
I have checked the character encoding in your headers and meta tags and they are consistent across both pages. I also agree that the output of the pages is largely similar - except for the special characters, which are "messed up" in the source file.
I don't think this issue exists in the browser, the must be something behind the scenes that causes this. How does the name containing these characters get from the data store to the page?
| common-pile/stackexchange_filtered |
Overwrite Wordpress Theme's star-ratings with default WooCommerce ones
My WordPress theme ("Function") uses an ugly "progress bar" style ratings system which overrides the default WooCommerce star-ratings. See below:
http://demo.woothemes.com/function/shop/castillo-cap/#tab-reviews
For the life of me I can't figure out how remove this and replace it with the default/original WooCommerce star-ratings, the ones that actually look like stars (font awesome I believe?)
I believe what needs to be done is to somehow overwrite or prioritize WooCommerce star-ratings css over the theme's. Ultimately I would like for all of the progress bars (shop page & individual product pages, review submission forms) to be replaced with the default WordPress stars, however at the moment I can settle for just the shop page where the ratings (progress bars) appear under the product's photos
I was able to find the css code controlling (creating?) the progress bars in Function->Includes->Integrations->woocommerce->css->woocommerce.css However, I also found some suspicious looking code in woocommerce.less located in the same css folder.
Here is code I found in woocommerce.css:
star-rating {
width: 80px;
height: 1em;
background: #eaeaea;
-webkit-border-radius: 3.631em;
border-radius: 3.631em;
-moz-background-clip: padding;
-webkit-background-clip: padding-box;
background-clip: padding-box;
clear: both;
}
.star-rating span {
background: #52a0cd;
height: 100%;
overflow: hidden;
float: left;
text-indent: -999em;
-webkit-box-sizing: border-box;
/* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box;
/* Firefox, other Gecko */
box-sizing: border-box;
/* Opera/IE 8+ */
-webkit-border-radius: 3.631em;
border-radius: 3.631em;
-moz-background-clip: padding;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
.star-rating span span {
display: none;
}
p.stars {
overflow: hidden;
zoom: 1;
}
p.stars span {
width: 80px;
height: 16px;
position: relative;
float: left;
background: #eaeaea;
-webkit-border-radius: 3.631em;
border-radius: 3.631em;
-moz-background-clip: padding;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
p.stars span a {
float: left;
position: absolute;
left: 0;
top: 0;
width: 16px;
height: 0;
padding-top: 16px;
overflow: hidden;
}
p.stars span a:hover,
p.stars span a:focus {
background: #52a0cd;
-webkit-border-radius: 3.631em;
border-radius: 3.631em;
-moz-background-clip: padding;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
p.stars span a.active {
background: #52a0cd;
-webkit-border-radius: 3.631em;
border-radius: 3.631em;
-moz-background-clip: padding;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
p.stars span a.star-1 {
width: 16px;
z-index: 10;
-webkit-border-top-left-radius: 3.631em;
-webkit-border-bottom-left-radius: 3.631em;
border-top-left-radius: 3.631em;
border-bottom-left-radius: 3.631em;
-moz-background-clip: padding;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
p.stars span a.star-2 {
width: 32px;
z-index: 9;
}
p.stars span a.star-3 {
width: 48px;
z-index: 8;
}
p.stars span a.star-4 {
width: 64px;
z-index: 7;
}
p.stars span a.star-5 {
width: 80px;
z-index: 6;
}
...and here is what I found in woocommerce.less:
// Single product
.single-product {
.summary {
.woocommerce-product-rating {
.clearfix;
.star-rating {
float: left;
margin: .327em 0 0;
}
.woocommerce-review-link {
float: right;
display: block;
}
}
// General WooCommerce
.star-rating {
width:80px;
height: 1em;
background: @border_main;
.border_radius(3.631em);
clear:both;
span {
background: @color_links;
height:100%;
overflow: hidden;
float: left;
text-indent: -999em;
.borderbox;
.border_radius(3.631em);
span {
display: none;
}
}
}
p.stars {
overflow: hidden;
zoom: 1;
span {
width: 80px;
height: 16px;
position: relative;
float: left;
background: @border_main;
.border_radius(3.631em);
a {
float: left;
position: absolute;
left: 0;
top: 0;
width: 16px;
height: 0;
padding-top: 16px;
overflow: hidden;
}
a:hover, a:focus {
background: @color_links;
.border_radius(3.631em);
}
a.active {
background: @color_links;
.border_radius(3.631em);
}
a.star-1 { width: 16px; z-index: 10; .border_radius_left(3.631em); }
a.star-2 { width: 32px; z-index: 9; }
a.star-3 { width: 48px; z-index: 8; }
a.star-4 { width: 64px; z-index: 7; }
a.star-5 { width: 80px; z-index: 6; }
}
}
...along with some more for the widget areas, reviews, etc. etc.
I've found a few posts on how to override default WooCommerce star-ratings with a Theme's, but I can't find anything on doing the reverse. I did come across this:
http://findnerd.com/list/view/How-to-show-stars-instead-of-theme-ratings-in-Woocommerce/3854/
However it didn't work for me...
Any help would be much MUCH appreciated. Thank you!
EDIT:
I was informed this might be caused by my functions.php file. Here is the code found in wp-content->themes->Function-Child->functions.php
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
/*-----------------------------------------------------------------------------------*/
/* Start WooThemes Functions - Please refrain from editing this section */
/*-----------------------------------------------------------------------------------*/
// WooFramework init
require_once ( get_template_directory() . '/functions/admin-init.php' );
/*-----------------------------------------------------------------------------------*/
/* Load the theme-specific files, with support for overriding via a child theme.
/*-----------------------------------------------------------------------------------*/
$includes = array(
'includes/theme-options.php', // Options panel settings and custom settings
'includes/theme-functions.php', // Custom theme functions
'includes/theme-actions.php', // Theme actions & user defined hooks
'includes/theme-comments.php', // Custom comments/pingback loop
'includes/theme-js.php', // Load JavaScript via wp_enqueue_script
'includes/sidebar-init.php', // Initialize widgetized areas
'includes/theme-widgets.php', // Theme widgets
'includes/theme-plugin-integrations.php' // Plugin integrations
);
// Allow child themes/plugins to add widgets to be loaded.
$includes = apply_filters( 'woo_includes', $includes );
foreach ( $includes as $i ) {
locate_template( $i, true );
}
/*-----------------------------------------------------------------------------------*/
/* You can add custom functions below */
/*-----------------------------------------------------------------------------------*/
This is the exact same as the code in my regular (non-child) theme's functions.php file. I do have some custom code below this, however none of it relates to anything that would be relevant here.
EDIT 2:
OK I think I'm getting closer here!! I found this file wp-content/themes/function/includes/integrations/woocommerce/woocommerce.php which included this code at the top:
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
global $woo_options;
add_theme_support( 'woocommerce' );
// Disable WooCommerce styles
if ( version_compare( WOOCOMMERCE_VERSION, '2.1' ) >= 0 ) {
// WooCommerce 2.1 or above is active
add_filter( 'woocommerce_enqueue_styles', '__return_false' );
} else {
// WooCommerce less than 2.1 is active
define( 'WOOCOMMERCE_USE_CSS', false );
}
// Load WooCommerce stylsheet
if ( ! is_admin() ) { add_action( 'wp_enqueue_scripts', 'woo_load_woocommerce_css', 20 ); }
if ( ! function_exists( 'woo_load_woocommerce_css' ) ) {
function woo_load_woocommerce_css () {
wp_register_style( 'woocommerce', esc_url( get_template_directory_uri() . '/includes/integrations/woocommerce/css/woocommerce.css' ) );
wp_enqueue_style( 'woocommerce' );
} // End woo_load_woocommerce_css()
}
When I deleted the above code, the progress bars changed a little, and in the add new review section I could actually see two blue STARS laid on top of the blank progress bar (which normally highlights blue when you scroll over to choose your rating). So it seems that removing this kinda half fixed the problem. Any further suggestions?
I'm not very familiar with WordPress but it is likely that the default WordPress rating system is being overrided in a php file (probably functions.php), and can't be fixed by amending the CSS alone. If that looks likely, could you update your question to include relevant php code. Thanks
| common-pile/stackexchange_filtered |
Put in / remove from the basket using Rx
I have two streams of data:
Boolean stream, which indicates whether the item exists in the basket.
Clicks stream, which initiates item put/delete into/from the basket.
Firstly, I want to change caption of the toggle button according to boolean stream. It's simple. Secondly, I want to combine the latest value from the Boolean stream and event from Clicks stream in order to initiate either put or delete request.
Here's what I've tried so far:
// handling the toggle button caption
inBasketStream.subscribe(inBasket -> {
mPurchaseButton.setText(inBasket ? "Already in basket" : "Purchase");
});
// handling clicks and deciding whether to add or remove item
Observable.combineLatest(
inBasketStream,
ViewObservable.clicks(mPurchaseButton),
(inBasket, onClickEvent) -> inBasket).subscribe(inBasket -> {
if (inBasket) {
mRemoveFromBasket.call(mItemId);
} else {
mAddInBasket.call(mItemId);
}
}
);
However, combineLatest doesn't do my job. Instead it results in recursion since at least one clicks event occured and inBasketStream is updated on operation completion. Zip won't help much as well since in basket stream might be changed from another place and there's, hence, a scenario for stacking multiple boolean values, which will make zip take obsolete(just the next one, while there could be more values already stacked upon) value on next click event.
So, I need a way to get the last value from the boolean stream and use it whenever click event happens. Of course, I could use a boolean field for that (subscribe to inBasketStream and update it onNext) but I don't feel that it complies with functional and there has to be a composition to handle this issue without additional fields/variables.
Thanks.
P.S. both observables are hot
Take a look at withLatestFrom. It will only propagate when the primary source emits while combining the latest values from the other sources.
ViewObservable.clicks(mPurchaseButton)
.withLatestFrom(inBasketStream,
(dontCare, inBasket) -> inBasket)
.subscribe(/*do your update*/);
Great! RxJava also has an experimental implementation here: https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md#experimental-operator
| common-pile/stackexchange_filtered |
How to replace PID controller with fuzzy controller so that it can work exactly the same as PID
I have a model in simulink as shown
The model has PID controller with Kp=36 Kd=54 Ki=6. Pid controller is minimizing the error given as its input to zero. Now I want to replace it with fuzzy controller so that it exactly works the same as PID. What to do?
Its very simple ....
In Matlab workspace type fuzzy . Fuzzy toolbox will open. You are required to assign the Inputs and Outputs there. Make Error e and Change in error de as inputs nad Kp , Ki, and Kd as Outputs. Then decide the range for each of of the membership functions of these inputs and outputs. [Refer some research paper for details]
Save the model as Model.fis and export this model to workspace.
Open the Simulink and like as the figure you have posted replace it with Fuzzy Logic Controller Block and call the Model.fis in block. and run the simulation. :)
| common-pile/stackexchange_filtered |
Reusable vector module with tests
I'm learning rust with mostly a background in managed languages. I have a little C background.
As a learning project I am re-implementing a linear-transformations library I've been working on in C#.
This is my first reusable library I've tried to make in Rust and I'd like feedback on creating and using modules, as well as rust programming in general.
Project structure
+ transforms
+ src
- lib.rs
- tests.rs
- transforms.rs
- vectors.rs
+ target
- Cargo.toml
I haven't made any changes to the automatic cargo.toml.
transforms.rs is empty and have the linear transformation code added to it in the future.
lib.rs
pub mod vectors;
mod tests; // tests don't get run if I don't have this, not sure why?
vectors.rs
use std::fmt;
pub struct KVector3{
pub x : f64,
pub y : f64,
pub z : f64,
}
pub trait Vector {
fn magnitude_squared(&self) -> f64;
fn magnitude(&self) -> f64;
}
pub trait Vector3 {
fn dot(&self, v : KVector3) -> f64;
fn cross(&self, v : KVector3) -> KVector3;
fn zero() -> KVector3;
fn i_hat() -> KVector3;
fn j_hat() -> KVector3;
fn k_hat() -> KVector3;
}
impl Vector for KVector3 {
fn magnitude_squared(&self) -> f64 {
self.x * self.x + self.y * self.y + self.z * self.z
}
fn magnitude(&self) -> f64 {
(self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
}
}
impl Vector3 for KVector3 {
fn dot(&self, v : KVector3) -> f64 {
self.x * v.x + self.y * v.y + self.z + v.z
}
fn cross(&self, v : KVector3) -> KVector3 {
KVector3 {
x : self.y * v.z - self.z * v.y,
y : self.x * v.z - self.z * v.x,
z : self.x * v.y - self.y * v.x
}
}
fn zero() -> KVector3 { KVector3 { x: 0., y: 0., z: 0. } }
fn i_hat() -> KVector3 { KVector3 { x: 1., y: 0., z: 0. } }
fn j_hat() -> KVector3 { KVector3 { x: 0., y: 1., z: 0. } }
fn k_hat() -> KVector3 { KVector3 { x: 0., y: 0., z: 1. } }
}
impl PartialEq<KVector3> for KVector3 {
fn eq(&self, other : &KVector3) -> bool {
self.x == other.x && self.y == other.y && self.z == other.z
}
}
impl fmt::Debug for KVector3 {
fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
write!(f, "<{},{},{}>", self.x, self.y, self.z)
}
}
tests.rs
#[cfg(test)]
mod tests {
use ::vectors::{Vector, Vector3, KVector3};
#[test]
fn unit_magnitude_squared() {
let mag_squared = KVector3::i_hat().magnitude_squared();
assert_eq!(1., mag_squared);
}
#[test]
fn v3_magnitude_squared() {
let triangle = KVector3 { x : 3., y : 4., z: 0. };
let mag_squared = triangle.magnitude_squared();
assert_eq!(25., mag_squared);
}
#[test]
fn v3_magnitude() {
let triangle = KVector3 { x : 3., y : 4., z: 0. };
let mag = triangle.magnitude();
assert_eq!(5., mag);
}
#[test]
fn cross_product() {
let product = KVector3::i_hat().cross(KVector3::j_hat());
assert_eq!(KVector3::k_hat(), product);
}
}
Welcome to Code Review! I changed the title so that it is more specific about this code. Feel free to [edit] and give it a different title if there is something more appropriate.
Unit tests should be put in the file they're testing
It's recommended to put the unit tests into the same file as the functions you're testing. This prevents your code from getting out of sync with your tests more easily. Also, you don't want one single large tests.rsfor all your unit tests.
Use proper types in traits
At the moment, as soon as we use any function from Vector3, we end up with a KVector3:
pub trait Vector3 {
fn dot(&self, v : KVector3) -> f64;
fn cross(&self, v : KVector3) -> KVector3; // here
fn zero() -> KVector3; // here
fn i_hat() -> KVector3; // here
fn j_hat() -> KVector3; // here
fn k_hat() -> KVector3; // here
}
That's probably not what you intended. Use Self instead here. Furthermore, all your functions are fixed to f64, but one can implement all functions from Vector3 for any number type. The following interface encapsulates that:
pub trait Vector3 {
type Output;
fn dot(&self, v: Self) -> Self::Output;
fn cross(&self, v: Self) -> Self;
fn zero() -> Self;
fn i_hat() -> Self;
fn j_hat() -> Self;
fn k_hat() -> Self;
}
Use derive for canonical implementations
If you use #[derive(PartialEq, Debug)] you don't have to implement both variants yourself.
Consider generics for your structs (and traits)
Your KVector3 only supports f64. However, we can imagine a situation where we want to store f32, for example for GPU calculation. We can use KVector3 also in that circumstance if we make it generic.
Add documentation and examples
Since you're working on a reusable library you want to have some documentation at hand. Furthermore, examples in your documentation are automatically checked with cargo test.
| common-pile/stackexchange_filtered |
What's the best speech recognition software for Ubuntu?
Can someone please suggest to me a good speech recognition software for Ubuntu?
I want a software which controls everything. Like for example, on the login screen instead of typing password I can say the password and it recognizes my voice and unlocks.
I have already tried Palaver but it didn't meet my needs
I want something to do tasks like: search with it, rename file, shutdown my PC, unlock my PC , etc with only my voice and control everything of my PC.
like this one http://www.youtube.com/watch?v=CAmQRpxrQlk?
I advise you to follow this guide http://ubuntuforums.org/showthread.php?t=751169&page=12
related: https://askubuntu.com/questions/161515/speech-recognition-app-to-convert-mp3-to-text
Check out Google2Ubuntu.
"The aim of this project is to let you use the Google speech
recognition API to control your linux computer."
It comes with a pretty nifty interface, which you can use to define your own commands, etc. Here's a demo.
the speech recognition api from google has been closed, I believe.
I haven't tried it extensively but i hear xvoice is a half decent one, i think it works with most X applications. That of course means you will hopefully be using the console strictly from X if you plan on being totally hands free.
Also, if you are someone or are installing this with special needs that needs to be able to control the OS from the regular, non-gui console, I think your better off with a "voice keyboard" (cant remember what they are called exactly) than having the software handle it, i am not sure if are out for retail use but I've heard of them being used at some universities.
I dont know if this really helps, but hopefully it might point someone in the right direction if it doesn't help you. I mainly posted as an answer because this was too big to be posted as a comment (or even 2 comments!).
-o-
PS: you could use xvoice, and use it ON TOP of virtualbox, and then control everything that way, which is fine if you have the virtualization extensions that most CPUs/GPUs/APUs offer these days (the newer the better). As far as commercial software goes, i cannot recommend any of them because they never seem to be anywhere near good enough for the price and require a rediculous amount of training...uck
| common-pile/stackexchange_filtered |
How can I make a POST on http using boost::asio?
Hello I'm trying to do a POST using boost::asio but I'm unable to do so. I'm looking at this example code: http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/example/http/client/sync_client.cpp How can I make this code using POST instead of GET?
I think cpp-netlib might be of use: http://stackoverflow.com/questions/2251361/boost-asio-based-http-client-library-like-libcurl
asio works on the transportation layer (e.g. tcp sockets) not on the application level. Your solution would be more maintainable if you select a wide-spread http client library instead of implementing the http protocol yourself.
curl, poco and cpp-netlib is mentioned frequently here at SO but there are tons of available clients.
Have a look at these comparisons:
http://curl.haxx.se/libcurl/competitors.html
C/C++ HTTP Client Library for Embedded Projects
http://kukuruku.co/hub/cpp/a-cheat-sheet-for-http-libraries-in-c
| common-pile/stackexchange_filtered |
I need help uploading files with a time delay
Hi can someone please help with with this. I wrote a code that moves files from folder to folder. The problem is that code moves all of them at the same time all at once.
I need a file to be moved then there is a delay then it will move the next file. I've been trying this all day and I can't figure it out.
import os
import shutil
import time
source_dir = 'C:/Users/bigwi/Desktop/Upload'
target_dir = 'C:/Users/bigwi/Dropbox/ytbin'
file_names = os.listdir(source_dir)
time.sleep(15)
for file_name in file_names:
shutil.move(os.path.join(source_dir, file_name), target_dir)
this is what I'm working with so far I just need to figure out how to move one file at a time so I can use a time delay so it moves one file then waits 10 seconds then moves another file...
Fix your formatting.
Include time.sleep in the loop
@ThierryLathuille they mean that the files are moved really quickly and they want a delay.
Your code should look like this:
import os , time , shutil
source_dir = 'C:/Users/bigwi/Desktop/Upload'
target_dir = 'C:/Users/bigwi/Dropbox/ytbin'
file_names = os.listdir(source_dir)
for file_name in file_names:
shutil.move(os.path.join(source_dir, file_name), target_dir)
time.sleep(15)
time.sleep(15) should be inside the for-loop.
Simple; add a time delay in the for loop.
for file_name in file_names:
shutil.move(os.path.join(source_dir, file_name), target_dir)
time.sleep(10) # replace 10 with however long you want your delay to be
thank you thank u are the best, sorrry i just got into all this and literly this is my first code i did on my own i dont even know how any of it works but i mode the time.sleep down under the FOR part and it worked!!!! thank you so much
| common-pile/stackexchange_filtered |
single tap (hittest) does not fit with subviews
After changing the uiview position (y = -50) the single tap does not fit to the position to my added subviews. Hittest means the touchview starts at -50 and not 0. How to fix this?
myview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, -50, mywidth, myheight)];
The single tap:
// SINGLE TAP
- (void)singleTapRecognized:(UIGestureRecognizer *)gestureRecognizer {
CGPoint touchPoint = [gestureRecognizer locationInView:self.view];
UIView *touchView = [myview hitTest:touchPoint withEvent:nil];
NSLog(@"Y touchPoint: %f",touchPoint.y);
NSLog(@"Y touchView: %f",touchView.frame.origin.y);
}
CGPoint touchPoint = [gestureRecognizer locationInView:myview]; // <-- not self.view
Everything happens in myview. :-)
| common-pile/stackexchange_filtered |
Sql query returns 0 rows
SELECT * FROM class c
Left join sub_inclass s on s.class_id=c.class_id
join subject sb on s.sub_id=sb.sub_id
The other two except class 'table' are empty, I have left join but class table is still not displaying
should be an outer join
If you use only join it is an inner join by default.
SELECT * FROM class c
Left join sub_inclass s on s.class_id=c.class_id
left join subject sb on s.sub_id=sb.sub_id
^-------------------you missed left here
I want the class table in every case so i have used left join there only, Is it necessary to write left join in the second place too?
You are using the class table as basis. And every table you join need to be left joined in order to prevent filtering records of class.
| common-pile/stackexchange_filtered |
cast with linqToEntity(Esql)
my code :
public List<Book> GetBook(string NameField, object Value)
{
var queryESQL = @"select VALUE Book from Book
where Cast(Book." + NameField + " as string) like '%M%'";
var query = this.Entities.CreateQuery<Book>(
queryESQL);
return query.ToList();
}
error :
Type 'string' could not be found. Make sure that the required schemas
are loaded and that the namespaces are imported correctly. Near type
name, line 2, column 51.
update :
new code :
public List<Book> GetBook(string NameField, object Value)
{
var queryESQL = @"select VALUE Book from Book
where Cast(Book." + NameField + " as EDM.string) like '%M%'";
var query = this.Entities.CreateQuery<Book>(
queryESQL);
return query.ToList();
}
error :
Type 'EDM.string' could not be found. Make sure that the required schemas are loaded and that the namespaces are imported correctly. Near type name, line 2, column 51.
The CreateQuery<> method uses the CLR types, instead of EDM types, so use System.String instead of EDM.String in the query.
This worked for me. Thanks. Although I can't understand why Edm.String doesn't work
Use Edm.String instead of string when casting.
error : Type 'EDM.string' could not be found. Make sure that the required schemas are loaded and that the namespaces are imported correctly. Near type name, line 2, column 51.
@mrJack: Did you make sure you capitalized the S in EDM.String?
@StriplingWarrior : yes .I am sure
| common-pile/stackexchange_filtered |
How to configure trusted proxy middleware for Heroku on Laravel 5.6
Heroku has the following documentation for configuring trusted proxies when working with Laravel:
https://devcenter.heroku.com/articles/getting-started-with-laravel#trusting-the-load-balancer
It says:
It is very important to also prevent Laravel from trusting the
Forwarded and X-Forwarded-Host headers, because Heroku’s router does
not set those, but Symfony’s Request component trusts them out of the
box once a trusted proxy is set.
The final configuration file should look like this:
<?php
return [
'proxies' => '*',
'headers' => [
Illuminate\Http\Request::HEADER_FORWARDED => null, // not set on AWS or Heroku
Illuminate\Http\Request::HEADER_CLIENT_IP => 'X_FORWARDED_FOR',
Illuminate\Http\Request::HEADER_CLIENT_HOST => null, // not set on AWS or Heroku
Illuminate\Http\Request::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
Illuminate\Http\Request::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT',
]
];
Laravel has it's own documentation on how to configure trusted proxies:
https://laravel.com/docs/5.6/requests#configuring-trusted-proxies
I'm confused because as you can see in the example from the Laravel docs here:
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array
*/
protected $proxies = [
'<IP_ADDRESS>',
'<IP_ADDRESS>',
];
/**
* The headers that should be used to detect proxies.
*
* @var string
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
The $headers property is a string, not an array. I was expecting to see an array where I can add the header mapping just like the Heroku docs say, but I don't see how I would do that with $headers string property.
What is the appropriate way to set up this middleware for Heroku so that I can still "prevent Laravel from trusting the Forwarded and X-Forwarded-Host headers" as Heroku recommends?
First, some background. You probably know this first part though.
The Heroku docs still refer to the time when TrustedProxy had not yet been brought into the laravel core itself which happened with 5.5. Since 5.5, we do these settings via the middleware included in Laravel, not by publishing the config file from trusted proxy as we did before 5.5 (which incidentally you can still do off of that package since it's installed - but shouldn't if you're on 5.5+ The docs confused me on that initially.). I think you got all that though.
On the main substance of your question.
I run 5.5 LTS (on Heroku) myself so I don't have this exact problem - on 5.5, the $headers property is still an array as seen here.
In 5.6 symfony was upgraded to version 4 which changes a lot. The 5.6 docs link to this which could be what to look at.
Sorry this isn't a full answer at this point. Thought I'd just set out what I know, hope it's helpful.
Thanks but yes this is basically everything I have already realized which is why I am asking the question. Still not clear has on how to appropriately set the headers variable.
They changed it to a bit field instead of an array. Request::HEADER_X_FORWARDED_ALL looks equivalent to trusting all five when it was an array. That page says you can pass a bit field. Looks like you need to pass a bit field trusting only the three of the five that Heroku sets. Could be 0b01011. So try that as your value for $headers? How to be sure it's correct of course... interested to know.
If anyone is looking for a 2024 Laravel 11 update on this topic:
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
\App\Http\Middleware\HandleInertiaRequests::class,
\Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
]);
$middleware->trustProxies(at: '*');
$middleware->trustProxies(
headers: Request::HEADER_X_FORWARDED_AWS_ELB
);
$middleware->trustHosts(at: ['mysite.com', 'www.mysite.com',], subdomains: false);
})
There is no \App\Http\Middleware\HandleInertiaRequests::class class in Laravel by default. I think this is something pertaining to your project.
According to the documentation, this is what you should pass:
HEADER_X_FORWARDED_AWS_ELB
It makes reference to AWS ELB, but it should be the same for Heroku as it does not send "X-Forwarded-Host"
| common-pile/stackexchange_filtered |
How do processors know the order of registers' values?
In assembly one can pass values via less volatile registers or volatile registers. I can for instance pass arguments to printf using edi and esi I can also instead use ebx and ecx This example is a very simple contrived one. I'm more curious to how this works with much more intricate programs calling multiple functions from libc.
For instance in Return Oriented Programming attacks, an attacker can use gadgets to use the same registers used for a previous function to pop new values from the stack into them and then return to another libc function that uses the same register(s), for instance with write and read one could use pop rsi in ROP attacks to use either function if they've leaked the global offset table. My overall question could be asked this way:
If an attacker inherits registers from a previous call to read like so:
0x00005555555552d0 <+107>: lea rcx,[rbp-0xd0] <- Memory address of buffer "msg"
0x00005555555552d7 <+114>: mov eax,DWORD PTR [rbp-0xe4] <- contains client fd 0x4
0x00005555555552dd <+120>: mov edx,0x400 <- 1024 (size of bytes to write to memory location/buffer)
0x00005555555552e2 <+125>: mov rsi,rcx
0x00005555555552e5 <+128>: mov edi,eax
0x00005555555552e7 <+130>: call 0x5555555550d0 <read@plt>
How does the processor know which arguments to supply write to if the registers passed to write are different:
0x00005555555552b1 <+76>: call 0x555555555080 <strlen@plt>
0x00005555555552b6 <+81>: mov rdx,rax <- store return value from strlen into rdx
0x00005555555552b9 <+84>: lea rcx,[rbp-0xe0] <- message to write
0x00005555555552c0 <+91>: mov eax,DWORD PTR [rbp-0xe4] <- client file descriptor
0x00005555555552c6 <+97>: mov rsi,rcx
0x00005555555552c9 <+100>: mov edi,eax
0x00005555555552cb <+102>: call 0x555555555060 <write@plt>
Clearly read does not use rdx and write does not use edx, so how does the processor know which to choose, for example if an attacker only used a gadget that pops a value into rsi?
I can't seem to understand how the processor knows which registers to chose from (rdx or edx). How do processors select values to pass to libc functions or functions/routines for that matter in general?
It's not the processor's choice. It's defined by the calling convention. Note that since read and write take the same number and type of arguments, they use the same registers. On x86-64 linux those are rdi, rsi and rdx for the fd, buf and count arguments respectively. It's unclear why you think they are different.
In particular for your write example, the mov eax,DWORD PTR [rbp-0xe4] can not be the count, since it is transferred to edi. It's clearly the file descriptor. The count is already put into rdx by earlier code that you did not show.
I see I modified the second example.
So because I overlooked eax being moved into edi I failed to see that rcx is an argument also. This still doesn't explain the difference between rcx and edx. Both are different registers, so how does the processor know which one to use?
rcx isn't an argument either (in this case). It's moved to rsi. Neither rax nor rcx are used to pass arguments. They are just temporaries in the code shown, they are moved into the correct argument registers before the function call.
Ok I see, if you add this as an answer I will accept it.
Yes, the order matters. The order in which they map to arguments, not the order in which you load the values. See calling convention documentation
@Jester so how does the processor know to choose between rdx and edx?
The processor doesn't know anything; the registers aren't indexable and the only order they have as far as the CPU is concerned are the register numbers used in machine code. (And for stuff like save-multiple-register instructions like legacy 32-bit mode pusha / popa, or xsave to save the FPU / SIMD state.)
What looks for args in certain places in the called function is... more code (software), generated by a compiler that compiled a function with its args declared a certain way. Remember, printf is just more software, not built-in to the CPU.
The compiler knows the standard calling convention for the target platform (defined in the x86-64 System V ABI in this case), so having both caller and callee agree on a calling convention results in calling code that will put args in the places that callees look for them.
Standardizing this calling convention is how we can link together code from different compilers into one program, and make calls into libraries.
BTW, the same goes for making system calls; you put a call number into a certain register and run an instruction that switches to kernel mode (e.g. syscall). Now the kernel is running, and can look at the values still in registers. It uses the call number to index a table of function pointers, calling it with the other args in the standard arg-passing registers. (Or wherever they need to go according to the C calling convention, which is typically different from the system-call calling convention.)
What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64
I just don't understand how the processor knows to choose rdx or edx. If you can answer that I will accept your answer.
@asd40732: Which choice when are you talking about? When decoding machine code, the difference between add eax, edx and add rax, rdx is 1 bit in the REX prefix that selects 64-bit operand size (REX.W=1). The dx / edx / rdx have the same register number in machine code, the size is set by the operand-size attribute of the instruction (prefixes and opcode). https://wiki.osdev.org/X86-64_Instruction_Encoding#REX_prefix.
@asd40732: If you mean how does the compiler decide which operand-size to use, usually it matches the type width of the C variable. (Writing a 32-bit register implicitly zero-extends to 64-bit, so mov edx, 1234 is how a compiler would pass a size_t or uint64_t arg, like the 3rd arg of write; Why do x86-64 instructions on 32-bit registers zero the upper part of the full 64-bit register?). But that's the compiler making the decision, not the processor, as I and old_timer have explained in both our answers.
also related: The advantages of using 32bit registers/instructions in x86-64
The processor is very dumb it knows nothing. Literally it only does what the instructions say to do and the instructions are ultimately written by the programmer directly or indirectly (via compilation). The compiler knows because of the calling convention decided on by the compiler authors and they are free to choose the convention they want for that target, they do not have to conform to an specific previously defined convention. If they happen to it is their free choice to do so. At the end of the day the compiler authors know and build the compiler around that...The processor does only what it is told it cannot think for itself.
| common-pile/stackexchange_filtered |
Split the "Elements" tab and the "Console" in Chrome dev Tools
Is there a way to have a view of both the Elements and the Console in two different windows or with the windows split in two part?
The Drawer offers the functionality you want. When on the elements panel, just press esc (when DevTools has focus) to open the drawer which contains a console.
And do you know if there is way to do that in an other window ? However its perfect :)
You can "undock" the DevTools. Search SO or Google and plenty of things will come up for that to show you how to do it.
Esc stands for Emerge semi-screen console. (Slaps forehead.)
| common-pile/stackexchange_filtered |
back transformation of log means and log standard deviations
I have a set of values reported as the 'log mean'. I know from elsewhere in the text that it is the natural log that is being referred to. I'm trying to ascertain if there is a way I can derive the mean from this 'log mean', and also if there is a way to work back from the reported value of the '+/- 1 log standard deviation', thus allowing me to include the data from this study in a meta analysis I am trying to put together.
Here's a copy of how the data is presented in the paper:
What's the log mean? It's not the same as the mean logarithm! If you mean the latter, then reverse whatever transformation you used in the first place, presumably either log base 10 or log base e (natural logarithms). Other bases are possible, but I doubt the question would arise in those contexts
More details and assumptions are needed for this question to be answerable.
Thanks guys, apologies for the vague question. If you have the time, take a look at my edited version. Any and all help appreciated here. You will be included in the acknowledgments of any published paper that arises from this work.
There is nothing in the extract to explain what the authors did beyond a statement that the log mean is measured in the original units. My wild guess is that it is a geometric mean. You can't recover the mean from such results without extra assumptions. This is on all fours with this example. The geometric mean is 10. What is the original mean? A geometric mean of 10 is consistent with original values of 1 and 100 (mean 50.5) and with original value (and mean) 10 and with many more such possibilities. If you make a heroic assumption that the data are (e.g.) lognormal you can do more.
But then again the data summarized are clearly pretty wild with values up to 39911.67 mm hr$^{-1}$. Those are precisely the circumstances in which straight means do not work well. I realise this doesn't help your goals usefully, but there it goes.
I will share some educated guesses, as a long-time consumer and interpreter of this kind of hydrogeologic information.
"Log mean" surely is the "geometric mean."
The relationships among the columns of the table are these:
Let $x_i$ be the "log mean" in row $i=1,2,3,4,5$. It is a statistical summary of data $x_{i1}, x_{i2}, \ldots, x_{in_i}$, individual measurements of hydraulic conductivity in mm/hr. The summary is obtained by taking the logarithms $$y_{ij} = \log(x_{ij}),\ j = 1, 2, \ldots, n_i.$$ Letting $$y_i = \frac{1}{n_i}\left(y_{i1} + y_{i2} + \cdots + y_{in_i}\right)$$ be the mean of the logs, we have $$x_i = \exp(y_i).$$ This is universally known as the geometric mean of the $x_{ij}$; the phrase "log mean" is unusual.
The "Antilog $S_1$" is the exponential of the standard deviations of the $y_{ij}.$ That is, $$\log(S_{1i}) = \sqrt{\frac{1}{n_i-1}\left((y_{i1}-y_i)^2 + \cdots (y_{in_i} - y_i)^2\right)}.$$ (It is possible the denominators of the fractions are the $n_i$. There's no way to tell from the information given.) $S_1$ is often called the "geometric standard deviation."
The "$\pm\text{s.d.}$" columns are the exponentials of $y_i \pm \log(S_{1i}).$ Equivalently, by virtue of properties of logarithms, the left column will be $x_i / S_{1i}$ and the right column will be $x_i S_{1i}$. I confirmed this by calculating the ratios of the right column to the "log mean" and of the "log mean" to the left column. In all cases they agree, to the stated precision, with the "Antilog $S_1$" values.
The "Range" reports the smallest and largest among the $x_{ij},j=1,2,\ldots, n_i$.
In other words, the authors were working with the logarithms of the hydraulic conductivities, the quantities I have named with "$y$". They computed the means and standard deviations of these logarithms, site by site. To report an interval of uncertainty--presumably because they wish to use these data to estimate average hydraulic conductivities at each site--they constructed a "one s.d. interval" of logarithms by subtracting and adding the standard deviation from each mean. Finally, to express these results in the original units (the $x$'s) rather than their logarithms, they exponentiated them all.
Incidentally, it doesn't matter what base of logarithms is used for these calculations. Indeed, we have no way of knowing, because this table displays all results in the original units: the logarithms are hidden.
Why do it this way instead of working with the hydraulic conductivities? Typically, they vary by orders of magnitude, even within relatively homogeneous units. Their logarithms, on the other hand, tend to have relatively symmetric distributions, with few outlying values. Basing statistical estimates on the logarithms therefore produces indications that are arguably more "typical" of the entire unit. Beware, though. When using hydraulic conductivities to estimate water speeds and related quantities, often the very largest conductivities can control the situation by offering preferential pathways of transport. That is why proper interpretation of this table requires not only a good understanding of how it was constructed, but also of hydrogeologic transport phenomena. To this end, it may be worthwhile to study the ranges of observed conductivities and watch for extremely high values compared to the "$\pm\text{ s.d.}$" intervals, such as at Site 3.
| common-pile/stackexchange_filtered |
cannot change wallpaper in Gnome
I recently installed Gnome on my Dell OptiPlex 755 computer. Everything seems to work, but I cannot add a wallpaper image on my desktop. I tried Wallch, to no avail. Is there a trick to adding wallpaper to Gnome, or is this system simply meant to use a jet-black background?
In Settings > Background you'll get options to change desktop background and lock screen background. But it only allows to choose images from a limited number of directories. If you want the full freedom to choose images from any directory, use GNOME Tweak Tool and look for Desktop menu.
| common-pile/stackexchange_filtered |
Refreshing a jsp on some change
How can I refresh a jsp on any change automatically?
Is there any way to do it?
In my application I am using JSP to design the header.
Now as per requirement I have to make a change in the jsp which is only reflecting when Iam manually refreshing the page.
I want this to be done automatically.
You cant refresh page automatically , unless you use timer kind of stuffs in it or you need a ajax for it
I have to make a change in the jsp which is only reflecting when Iam manually refreshing the page
Because once you run the jsp file , it renders the html content to the browser and it doesnt maintain any active connection with the browser unless you are creating a new request.
How can I refresh a jsp on any change automatically? Is there any way to do it?
You can use Ajax as it is meant for this purpose.
Poll the server for regular intervals using the window.setInterval method and update the contents.
Hope this helps !!
<c:if test="${commandObject.function.functionCode =='ELOG WELCOME'}">
if i want to refresh complete jsp is it possible .
yes it is possible . but probably ajax is not used for that purpose
Whatever you're trying to achieve specifically here, you will have to use Javascript in your .jsp page.
If by 'refreshing', you mean literally refreshing the page as if the user clicked the browser's refresh button, then you can use this Javascript code.
location.reload();
What you'll need to do is capture events, in your page, that should cause the page to reload, and then execute the Javascript command above when they occur.
This being said, san krish (above answer, at the moment I'm writing this) suggested AJAX. It is very likely that AJAX is actually the solution you're looking for -- what AJAX means is that you'll use Javascript to only refresh a specific part of the page, instead of reloading the entire page. In a nutshell, AJAX means using Javascript to make requests and retrieve the responses without 'leaving' the page. It's a bit complex to explain shortly, especially given that we are not sure what you are trying to build at the moment, so I will leave it at that.
<c:if test="${commandObject.function.functionCode =='ELOG WELCOME'}"> </c:if>
the above code is changing an image in the jsp based on a test condition. Now as this is an html content the image doesn't change automatically when the condition fails unless user refreshes the page automatically.
OK. Well essentially, you just need to hook the location.reload() command to whatever actions on your page.
| common-pile/stackexchange_filtered |
How to drop the imaginary part from numbers such as x + 0.0i in R
I guess this will be already answered somewhere, so apologies in advance, but I tried to search without luck, so.....
....What is the smart way to deal with numbers of the form x + 0.0i in R ?
For example suppose we have
y <- 1 + 0.0i
So of course:
y == 1
is true. So what is the best way to coerce y to be 1.
Edit:
I don't want to discard the imaginary part unless round(Im(y)) == 0 but I was hoping for a way to avoid having to explicitly test for this.
Thanks @joran but that discards the imaginary part even if it is not zero, doesn't it ?
Hmm, do you mean you want to drop the imaginary bit only if it is zero?
@JoeKing That definitely wasn't clear from your question. I suspect you're going to be stuck writing a function that checks the imaginary part.
@GavinSimpson yes, that's right. I'm sorry, that in hindsight I realise I didn't explain this well in my OP, so I have edited it now.
@joran yes, I am deeply sorry about that ! I should have made that clear in my OP and I have now edited the Q to reflect that.
@BenBolker thanks, that's really helpful. I love how I almost always learn something new on this website, every time I post a question.
Can't think of anything better than this (yes, it's surprising there's not a built-in imaginary-squashing feature ... or maybe someone will yet come up with one)
f <- function(x) {
if (all(Im(z <- zapsmall(x))==0)) as.numeric(z) else x
}
This is great - may I ask: why do you need the all() ?
because if requires a single criterion. More specifically, suppose I pass this function a length-2 complex vector x where Im(x[1]) is (close to) zero but Im(x[2]) is not; then I shouldn't do any zapping or setting to numeric, because the whole vector will still be complex.
| common-pile/stackexchange_filtered |
TelegramBot 400 Bad Request: media not found
I try to send album by telegram bot.
Sometimes I get error Telegram.Bot.Exceptions.ApiRequestException: Bad Request: media not found at Telegram.Bot.TelegramBotClient.MakeRequestAsync[TResponse](IRequest 1 request, CancellationToken cancellationToken). InputMedia not is empty. Whats is wrong?
var streams = new List<Stream>();
try
{
List<IAlbumInputMedia> inputMedia = new List<IAlbumInputMedia>();
foreach (var image in images)
{
var stream = new MemoryStream(image.Data, false);
var photo = new InputMedia(stream, image.Name);
inputMedia.Add(new InputMediaPhoto(photo) {Caption = image.Name});
streams.Add(stream);
}
var response = await _bot.SendMediaGroupAsync(inputMedia, chatId, cancellationToken: token);
}
I had the same problem, which was caused by image.Name in your code. it should be only like someImage.png or someImage.jpg. You probably have "C:\SomeStuff\someImage.png" over there which is FULL Name intead of name, so Stream is good but name is wrong and the Api is confused
| common-pile/stackexchange_filtered |
Backup multiple Exchange Accounts without direct access to exchange server
For e-mail, we use Microsoft Exchange and it is hosted by 1and1.com.
We have about 30 Exchange accounts that I would like to backup to a PST file. That is, for each account that we have (all 30), I would like to create a single PST file (1.pst thru 30.pst).
I do not have direct access to the Exchange server. Basically, for each Exchange account, I can supply:
The IP address for the Exchange server or the URL to the OWA.
The Username
The Password
Is there a tool out there that can do this for me?
It seems that Microsoft's "Online Services Migration Tools" comes awfully close, but it appears that its geared to pull data out of any Exchange server and push it into Microsoft Online. I don't believe it can be used to simply pull the data out and generate PST's.
Maybe I'm going about this all wrong. Maybe I should use a tool that backs-up stuff via IMAP? Is there a good batch-IMAP backup tool out there where I give it the credentials for 30 accounts and it goes through and downloads all the data?
The Exchange Migration Wizard will do what you want; it became the Online Services Migration Tool a version or two ago.
The simplest alternative is probably to set up a (physical or virtual) machine with 30 IMAP profiles in Outlook, each pointed to a different PST. Secure it appropriately and voila. Instant backup mechanism.
So does it then just send/receive all the emails at once, or do you have to go in and switch between profiles? I'm just fuzzy on how the details of this would be if I actually got it set up.
| common-pile/stackexchange_filtered |
mvc passing data between controller and view
I am developing an application. I have created a view and a controller. The view has a button, on the click of which I am supposed to do database operations. I have put the database operations in the model, I am creating the object of model in the controller. On clicking the button the action is handled by a method in the controller, and the object of the model is created to get the records from the database. I would like to know if there is any way to display this data in the view.Is the approach correct or the view is supposed to interact with model directly to get the data.
Following is the code in controller that gets invoked on the button click
public ActionResult getRecord()
{
DataModel f_DM = new DataModel();
DataTable f_DT = f_DM.getRecord();
return View();
}
DataModel is the model class with simply a method "getRecord".
Any help will be highly appreciated.
I would like to add that i am using vs2010 and mvc4
Regards
you should write the logic of retrieving data in your controller. Store all your data in view model and pass it to the view.
for eg.
Model
namespace Mvc4App.Models
{
public class Product
{
public string Name { get; set; }
}
public class ProductViewModel
{
public Product Product { get; set; }
public string SalesPerson { get; set; }
}
}
Controller
public class ProductController : Controller
{
public ActionResult Info()
{
ProductViewModel ProductViewModel = new ProductViewModel
{
Product = new Product { Name = "Toy" },
SalesPerson = "Homer Simpson"
};
return View(ProductViewModel);
}
}
View
@model Mvc4App.Models.ProductViewModel
@{ ViewBag.Title = "Info"; }
<h2>Product: @Model.Product.Name</h2>
<p>Sold by: @Model.SalesPerson</p>
This is the best known practice to pass data from controller to the view.
you may use other techniques also like,
1. ViewData
2. ViewBag
3. TempData
4. View Model Object
5. Strongly-typed View Model Object
I have done the above, but I am facing an issue. When the View.chtml gets executed it exceutes the for loop and as the data table is empty for the first time. Unless I click on CLick button I donot fill the data table. Can you please suggest.
Please update question with latest code, It would be more helpful to solve the problem.
Yes, it's possible, but actually now very logical way to to this.
Lets follow your way. You have some View were you have a button, that will trigger this action.
For ex:
public ActionResult Index()
{
return View();
}
Inside view you can have a Ajax link, that will trigget your getRecord method:
<div id="GetDataDiv"></div>
<div>
@Ajax.ActionLink("Get Record", "getRecord", "ControllerName", null, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "GetDataDiv" })
</div>
In the getRecord method you should have:
public ActionResult getRecord()
{
DataModel f_DM = new DataModel();
DataTable f_DT = f_DM.getRecord();
return PartialView(f_DT);
}
And in View it should be:
@model DataTable
@Model.PropertyOne @Model.PropertyTwo
It should works for you.
Actually same exaple here: http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=151
| common-pile/stackexchange_filtered |
Changing isVisible property of Xamarin Forms XAML buttons
I am trying to dynamically show/hide button inside Xamarin Forms ContentPage.
I have two buttons in my XAML code:
<StackLayout Orientation="Vertical">
<Button x:Name="start_btn" Clicked="startPanic">
<Button.Text>START</Button.Text>
</Button>
<Button x:Name="stop_btn" IsVisible="false">
<Button.Text>STOP</Button.Text>
</Button>
</StackLayout>
Corresponding C# code:
public partial class PanicPage : ContentPage
{
private Button startBtn;
private Button stopBtn;
public PanicPage ()
{
InitializeComponent ();
startBtn = this.FindByName<Button> ("start_btn");
stopBtn = this.FindByName<Button> ("stop_btn");
}
private void startPanic(object sender, EventArgs args){
Device.BeginInvokeOnMainThread (() => {
startBtn.IsVisible = false;
stopBtn.IsVisible = true; // DOESN'T WORK, button still will be hidden
});
}
}
When I set isVisible property in XAML, it doesn't react for any property change in event method (startPanic). How can I fix it?
Have you tried removing the Device.BeginInvokeOnMainThread usage? Not sure why you are using it.
Change your code in xmal file and write properties for start and stop button
<Button x:Name="start_btn" Clicked="startPanic" IsVisible="{Binding IsStartVisible}">
<Button.Text>START</Button.Text>
</Button>
<Button x:Name="stop_btn" IsVisible="{Binding IsStopVisible}">
<Button.Text>STOP</Button.Text>
</Button>
In ViewModel write following property and similar for start button and set IsStopVisible =true/false based on your logic
private bool _isStopVisible;
public bool IsStopVisible{
get {
return _isStopVisible;
}
set {
_isStopVisible= value;
RaisePropertyChanged ("IsStopVisible");
}
}
Maybe I'm late but I was searching this too without success. This may be useful for someone.
objectView.SetValue(IsVisibleProperty, false); // the view is GONE, not invisible
objectView.SetValue(IsVisibleProperty, true);
It should work just fine. I copied your code and cleaned it up a bit, it shows the STOP button, then I
A few remarks:
use the short property where possible <Button Text="X"/>, it's
easier to read
when you add a XAML page the IDE adds a .xaml.cs file next to it and generates another .g.cs that you don't see. The .g.cs file
contains generated code that finds all the x:Name'd elements and
defines placeholders for them, no need to find them by name yourself
all UI-initiated events are executed on the UI thread, no need to do that explicitly
Here's the XAML, same as yours just tighter and added Margin so the button is visible
<StackLayout Orientation="Vertical" Margin="20">
<Button x:Name="start_btn" Clicked="startPanic" Text="START" />
<Button x:Name="stop_btn" Text="STOP" IsVisible="false" />
</StackLayout>
And the code behind:
public partial class TestPage : ContentPage
{
public TestPage ()
{
InitializeComponent ();
}
private void startPanic(object sender, EventArgs args){
Device.BeginInvokeOnMainThread (() => {
start_btn.IsVisible = false;
stop_btn.IsVisible = true;
});
}
}
Thank you for your answer. I've tested your changes, but it didn't help in my case. What I've noticed,. that stop button shows for a short (half of second) moment and then desapears. What do you think about that?
I suggest you zip up your entire project and share it here via, say, dropbox. I'd also suggest resetting the simulator and running the code on hardware to make sure it isn't some fluke
When I'm doing that, I the error message Xamarin.Forms.Xaml.XamlParseException: Cannot assign property "isVisible": Property does not exists, or is not assignable, or mismatching type between value and property. Do you know what I'm doing wrong?
@Richh94 Possibly because you're using "isVisible" instead of "IsVisible" (notice the capitalized first letter)?
Use the Visibility property of view.
for example if u want to make your button invisible you can do
if(condition)
{
button.Visibility=ViewStates.Invisible;
}
else
{
button.Visibility=ViewStates.Visible;
}
add some explanation
| common-pile/stackexchange_filtered |
Why doesn't assigning a new value to a list element inside an if block (which is inside a for loop) not change the actual list itself?
I have a list of words (words_list), and w is used to iterate through it. If w is equal to word, which is a user-inputted string, then w is replaced with asterisks. If I print out the words individually inside the for loop, the string with the matched word asterisked-out comes, but if I print the original list itself, there's no change whatsoever. What am I not understanding?
for w in words_list:
if(w == word):
w = "*" * len(word)
print w,
print words_list
Assignment in Python doesn't mutate objects (unless you use the special indexed forms). It just changes the name to refer to a new object.
Read or watch Ned Batchelder's talk on Python names.
You need to change the element in the list
for i in range(len(words_list)):
if(words_list[i] == word):
words_list[i] = "*" * len(word)
print words_list[i]
print words_list
I've almost got what you're saying, but just clarify a bit more for me. The comment by strubbly on my question says assignment in Python doesn't mutate objects. So why will the third statement work? Is it because we're using indices of the list?
@SidharthSamant strubbly is right. In you code, line 1 for w in words_list what happens is - w gets a copy of an element from words_list. So it is a new variable with its own value, it is not referencing the value in the list. So when you change the value of w it is not reflected in the words_list.
@utkbansal More pythonic: Iterate over for i, word in enumerate(words_list).
@D.Everhard ageed! but normal iteration is what the OP was doing, so I did it the same way. And it seems to be easily understandable by new people.
for i, w in enumerate(words_list):
if w == word:
words_list[i] = '*' * len(word)
This way you iterate over the list and get the index along with the current list entry. Then you can access the current list conveniently with w, and replace it by accessing its index.
Thanks! This is a great way!
| common-pile/stackexchange_filtered |
Spring boot test how to import data.sql just once during of h2 testing
I want to test my spring boot application via h2 in memory database where I would like to use:
spring.jpa.hibernate.ddl-auto: update
However, once I want to run tests with this command:
mvn clean test
it will show some errors which are related to constraint violations (ID must be unique).
These ones were caused because the data.sql file (just with insert statements) is executed more times and hence the data cannot be inserted because of violation consistency.
Is there some way to solve this problem? It would be good to execute data.sql script just once but not sure. Or to load spring boot application context once.
| common-pile/stackexchange_filtered |
Android Bitmap syntax
I want to load bitmaps into ImageViews in Android, but I don't want to use the R.drawable syntax because I have a lot of images with a standard naming convention so it's much easier to get the image with some logic. For example, all my images are named:
img1.png
img2.png
img3.png
So if a user selects a value, let's say x, I show "img" + x + ".png" in the ImageView. Looks like Bitmap.decodeFile is what I need, but I need to know the syntax of how to get to my drawables folder since that's where the images are. Or if there's perhaps a better way.
I realize I could do this with a switch statement instead of concatenating the image name but that would be a lot of lines since I have so many images.
One alternative is to use reflection to load images from R. You can looking static variables by string name. Keep in mind that reflection can be slow though. If you are going to be loading the same image multiple times, you might want to keep a cache of name -> R id.
Edit:
You can also access them by URI. See referring to android resources using uris.
That sounds like it could work but I would imagine referencing the file by its path and name would be simpler.
The R.drawable value is a number by itself. You just need to use the first image id and add a fixed value to find the right image. For example:
R.drawable.image1 = 1234;
R.drawable.image2 = 1235;
etc.
So to get image 2 I would to R.drawable.image1 + 1.
Every time the R.java file is regenerated the numbers may change but the sequence will be the same. If you don't want to depend in this then you will have to look at the "assets" folder.
Looks like I've found a solution. The real problem is that I generate the resource names at runtime, but I can get the resource id like this:
getResources().getIdentifier("string1" + string2, "id", "com.company.package")
I can then pass that value to setImageResource or any other method that accepts a resource id.
| common-pile/stackexchange_filtered |
Prove that the Pell's Equation $x^2 −Dy^2 = 1$ always has a solution where $y$ is a multiple of $41$
$D$ is a positive integer that is not a perfect square
Recently I am taking a introductory number theory course and I met this question right after we learned Pell's equation and Diophantine Approximation. However, I can't see a connection between those 2 topics and this question.
I was trying to assume that $ y = 41k$ where k is an positive integer and substitute it into the equation and I hoped eventually this will simplify to an equation that conforms the form of the Pell's equation which is $x^2-Dy^2=1$. However I did not get any from there.
Also I tried to approach this problem from the Pell's Equation Theorem. Then I found it is impossible to get anything useful from expanding $(x+y{\sqrt D})^k$ plus I cannot determine the smallest solution for it because I don't know the value of D.
Could someone help me on this question? Thank you!
Sorry that was a typo.
I added the constraint to the question body. The title only allows 150 characters. Sorry about that. I appreciate your time!!
@Chad : The title really shouldn't be the problem statement. It should generally describe the problem. For instance "Constrained solution of several Pell's Equations" or whatever sums up your problem. The detailed statement should go in the body of the question.
Thanks for your advice! I edited the title. Does it look better now? I condensed some of the words.
Let $x_n+y_n\sqrt D=(x_1+y_1\sqrt D)^n$ the $n^{\text{th}}$ power of the primitive unit. Since there are only $41^2=1681$ possibilities for $(x_n,y_n)$ $\pmod{41}$ a duplicate must be encountered at some point: $x_n\equiv x_m\pmod{41}$ and $y_n\equiv y_m\pmod{41}$ for some $n>m\ge1$. Then $x_{n-m}=x_nx_m-Dy_ny_m\equiv x_n^2-Dy_n^2\equiv1\pmod{41}$ and $y_{n-m}=-x_ny_m+y_nx_m\equiv-x_ny_n+y_nx_n\equiv0\pmod{41}$.
EDIT: As an example let $D=3$ and the first solution to Pell's equation is $x_1+y_1\sqrt D=2+1\sqrt3$. Now let's make a table of values $\pmod{41}$:
$$\begin{array}{r|r|r}n&x_n&y_n\\\hline
1&2&1\\
2&7&4\\
3&26&15\\
4&15&15\\
5&34&4\\
6&39&1\\
7&40&0\\
8&39&40\\
9&34&37\\
10&15&26\\
11&26&26\\
12&7&37\\
13&2&40\\
14&1&0\\
15&2&1\end{array}$$
For example $(2+1\sqrt3)^2=7+4\sqrt3$, $(2+1\sqrt3)^3=26+15\sqrt3$, and $(2+1\sqrt3)^4=97+56\sqrt3$ so $x_4=97\equiv15\pmod{41}$ and $y_4=56\equiv15\pmod{41}$, thus explaining the row $n=4$, $x_n\equiv15$, $y_n\equiv15$. The first duplicate was $x_{15}\equiv x_1\equiv2\pmod{41}$ and $y_{15}\equiv y_1\equiv1\pmod{41}$, so that tells us that $x_{15-1}=x_{14}\equiv1\pmod{41}$ and $y_{15-1}=y_{14}\equiv0\pmod{41}$. Perhaps a bit anticlimactic since we already found $2$ solutions on our way to generating the first duplicate. Indeed $x_{14}^2-3y_{14}^2=50843527^2-3\cdot29354524^2=1$ and $y_{14}=29354524=41\cdot715964$.
EDIT: Oh yeah, the last $2$ lines: since $(x_n+y_n\sqrt D)(x_n-y_n\sqrt D)=(x_1+y_1\sqrt D)^n(x_1-y_1\sqrt D)^n=(x_1^2-Dy_1^2)^n=(1)^n=1$ we see that $(x_n+y_n\sqrt D)^{-1}=(x_n-y_n\sqrt D)$ so $(x_{n-m}+y_{n-m}\sqrt D)=(x_n+y_n\sqrt D)(x_m-y_m\sqrt D)=(x_nx_m-Dy_ny_m)+(-x_ny_m+y_nx_m)\sqrt D$
EDIT My program that finds the fundamental solution to $x^2-Dy^2=1$ and the first power $n-m$ for which $x_{n-m}\equiv1\pmod{41}$ and $y_{n-m}\equiv0\pmod{41}$
program pell
use ISO_FORTRAN_ENV
implicit none
integer(INT64) D
integer(INT64) sqD, r, s, a, p0, p1, p, q0, q1, q, n
integer(INT64) m
write(*,'(a)') ' D x_1 y_1 n-m'
do D = 1, 100
sqD = int(sqrt(D+0.5D0),INT64)
if(sqD**2==D) cycle
r = 0
s = 1
p0 = 0
p1 = 1
q0 = 1
q1 = 0
do n = 1, 200
a = (sqD+r)/s
p = a*p1+p0
p0 = p1
p1 = p
q = a*q1+q0
q0 = q1
q1 = q
r = a*s-r
s = (D-r**2)/s
if(mod(n,2) == 0 .AND. s == 1) then
write(*,'(i4,1x,i17,1x,i18)',advance='no') D,p,q
p0 = mod(p,41)
q0 = mod(q,41)
p1 = 1
q1 = 0
do m = 1, 1000000
p = p1*p0+D*q1*q0
q = p1*q0+q1*p0
p1 = mod(p,41)
q1 = mod(q,41)
if(p1 == 1 .AND. q1 ==0) then
write(*,'(1x,i4)') m
exit
end if
end do
exit
end if
end do
end do
end program pell
And its output:
D x_1 y_1 n-m
2 3 2 5
3 2 1 14
5 9 4 20
6 5 2 42
7 8 3 21
8 3 1 5
10 19 6 20
11 10 3 42
12 7 2 7
13 649 180 14
14 15 4 7
15 4 1 21
17 33 8 42
18 17 4 5
19 170 39 42
20 9 2 20
21 55 12 40
22 197 42 42
23 24 5 10
24 5 1 42
26 51 10 42
27 26 5 14
28 127 24 21
29 9801 1820 14
30 11 2 42
31 1520 273 5
32 17 3 5
33 23 4 40
34 35 6 21
35 6 1 42
37 73 12 20
38 37 6 42
39 25 4 40
40 19 3 20
41 2049 320 82
42 13 2 40
43 3482 531 10
44 199 30 21
45 161 24 10
46 24335 3588 20
47 48 7 7
48 7 1 7
50 99 14 5
51 50 7 20
52 649 90 14
53 66249 9100 14
54 485 66 14
55 89 12 7
56 15 2 7
57 151 20 40
58 19603 2574 42
59 530 69 10
60 31 4 21
61<PHONE_NUMBER> 226153980 5
62 63 8 20
63 8 1 21
65 129 16 42
66 65 8 10
67 48842 5967 42
68 33 4 42
69 7775 936 14
70 251 30 42
71 3480 413 21
72 17 2 5
73 2281249 267000 20
74 3699 430 20
75 26 3 14
76 57799 6630 21
77 351 40 40
78 53 6 8
79 80 9 7
80 9 1 20
82 163 18 82
83 82 9 4
84 55 6 40
85 285769 30996 2
86 10405 1122 20
87 28 3 40
88 197 21 42
89 500001 53000 42
90 19 2 20
91 1574 165 40
92 1151 120 5
93 12151 1260 7
94 2143295 221064 3
95 39 4 7
96 49 5 21
97 62809633 6377352 42
98 99 10 5
99 10 1 42
Sorry. I understand the sentence "there are only 1681 possibilities." However, I cant follow what is after that. Would you mind showing me that explicitly or have a little bit more explanation? Especially on the last two lines.
Thanks for your patient explanation, but why does it guarantee that there will be a duplicate for any value of D? I saw when n = 7, y is also a multiple of 41 but when n = 6, y is not a multiple of 41. I think I did not fully understand this method.
That's the pigeonhole principle: if you put $1682$ things (pairs $(x_n,y_n)$) in $1681$ boxes (the possible congruence classes $\pmod{41}$), then you have to put at least $2$ things in at least $1$ box. When we made up that table we were guaranteed to hit a duplicate by row $1682$ (actually $1681$ because $(x_n,y_n)\equiv(0,0)\pmod{41}$ is not possible).
Ok so there must be duplicates because of Pigeon Hole Principle, but why do we know that the row right before the row contains duplicates modulo 41 must have y as multiple of 41 in general? How should I explain that? Since this table is just one observation.
Well. I didn't actually say that. What I said was that if rows $n$ and $m$ are duplicates and $n>m$ then $y_{n-m}\equiv0\pmod{41}$. But since then $x_{n-m}\equiv1$ and $y_{n-m}\equiv0$ then $x_{n-m+1}\equiv x_{n-m}x_1+Dy_{n-m}y_1\equiv1\cdot x_1+D\cdot0\cdot y_1\equiv x_1$ and $y_{n-m+1}\equiv x_{n-m}y_1+y_{n-m}x_1\equiv1\cdot y_1+0\cdot x_1\equiv y_1$ it does it fact turn out that the first duplicate is between the first row and the row after the one the theorem promises we will find. It turns out that the first duplicate happens no later than row $1641$ and the first $D$ is $D=10$.
Thank you! I appreciate your patience!
Scratch what I said about the first duplicate no later than $1641$ -- there was a bug in my program. I will post my corrected program.
$$ 41^2 = 1681 $$
Since $D$ is positive and not a square, $1681D$ is positive and not a square.
Find a solution for
$$ u^2 - (1681D)v^2 = 1 $$
Then
$$ u^2 - D (41v)^2 = 1 $$
There is an old parametric solution for Pell equation that says, if x, y and D are certain functions of a parameter such as $m$ , there can be infinite solutions"
We rewrite equation as:
$x^2-1=Dy^2$
$1$ is odd and number of terms on LHS is even so one of terms must be odd. Suppose $x^2$ is odd and we have:
$x=2m^2+1$
$(2m^2+1)^2-1=D y^2$
$4m^2(m^2+1)=D.y^2$
So we must have:
$y^2=4m^2$ ⇒ $y=2m$
${D=m^2+1}$
So m can have any value in $\mathbb Z$, incuding all multiple of $41$.
For the smallest solution you can let $m=1$, then we have:
$D=1^2+1=2$
$x=2\times 1^2 +1=3$
$y=2\times 1=2$
If you want y a multiple of $41$, just let $m=41$, then:
$(x, y, D)= (3363, 82, 1682)$
Why does even number of terms on the LHS implies one of which must be odd?
I said one term must be odd, it can also be $Dy^2$, simply because $x^2$ and $Dy^2$ must be two consecutive numbers.
| common-pile/stackexchange_filtered |
C# remove all but two least significant bits of color
On this page, see the picture of the tree and its caption. I'm planning on implementing a plugin for Paint.NET to do just that... but I'm not sure how.
I'm already looping through every pixel (for those wondering, the Paint.NET API makes this efficient) as a ColorBgra (Can be converted to System.Drawing.Color), but now I need to modify the pixel to remove "all but the two least significant bits of each color."
How would I do this?
For each component (R, G, B, A) you need to mask off the unwanted bits, as in:
colour.R &= 3;
colour.G &= 3;
colour.B &= 3;
colour.A &= 3;
Works great! Although... could you perhaps provide a little more explanation on what the 3 signifies... and how I would remove other bits?
The 3 is the sum of the two least significant bits: 0x00000011 == 3
To remove other bits you can simply switch them on or off: Bit 7 is 0x01000000, Bit 3 is 0x00000100, Bit 1,3,5,7 is 0x01010101
careful; in C# 0x... signifies hexadecimal, where 3 == 0x03 (and 15 == 0x0F etc.)
If you need to do this with a System.Drawing.Color object at some point in time, you'll need to do Color NewColor = Color.FromArgb(baseColor.A & 3,baseColor.R & 3,baseColor.G & 3,baseColor.B & 3);, since the A, R, G and B are readonly properties here.
| common-pile/stackexchange_filtered |
How to SELECT value Where value = ''another SELECT"
First of all I searched for correct answer but I didn't find.
I have a function:
SELECT user_email
FROM `registracija_complete`
WHERE user_id = (SELECT `id`
FROM `base`
WHERE `sex` = 2
AND gimdat BETWEEN '1973-01-01' AND '1994-12-31');
but that function is not working, MySQL says that error is near SELECT id FROM `base
Why I'm getting this error? How to write that function correctly?
The query appears to be valid SQL syntax. Show us the table definitions (output of SHOW CREATE TABLE registracija_complete; and SHOW CREATE TABLE base;)
When MySQL says "error is near" it gives You a selection from query text starting from the symbol where the problem starts*. Your query text is valid (excluding the subquery may return more than 1 row). Check the text for invalid invisible symbols (CHR(160) instead of space, for example).
And copy MySQL error message from first to last char there, not only a little part of ot.
By the way, we don't see any function in the code you posted. Is that at typo and you meant query or is the code a part of the code you use to define a function? If that's the case, please post the whole code.
You can write:
SELECT user_email
FROM `registracija_complete`
WHERE user_id IN
(
SELECT `id`
FROM `base`
WHERE `sex` = 2
AND gimdat BETWEEN '1973-01-01' AND '1994-12-31'
);
The first (outer) select query expects one value to be returned for ID from the second (sub-) select, but actually the second select is returning more than one ID value. That is the issue.
Solution
Try to use IN instead of =.
| common-pile/stackexchange_filtered |
Jquery/ajax get object from a class and use it in a textbox in my view
I am working on a asp.net mv3 application.
In a helper class I have a method that return an object of a person based on his ID
public Person GetPersonByID(string id)
{
// I get the person from a list with the given ID and return it
}
In a view I need to create a jquery or javascript function that can call the GetPersonByID
function getPerson(id) {
//I need to get the person object by calling the GetPersonByID from the C#
//helper class and put the values Person.FirstName and Person.LastName in
//Textboxes on my page
}
how can I do that?
Can this be done by using and ajax call?
$.ajax({
type:
url:
success:
}
});
any help is greatly appreciated
Thanks
Javascript or jQuery for that matter doesn't know what a method means. jQuery doesn't know what C# is. jQuery doesn't know what ASP.NET MVC is. jQuery doesn't know what the Person .NET class means. jQuery doesn't know what a .NET class means.
jQuery is a javascript framework which (among many other things) could be used to send AJAX requests to a server side script.
In ASP.NET MVC those server side scripts are called controller actions. In Java those are called servlets. In PHP - PHP scripts. And so on...
So you could write a controller action that could be queried using AJAX and which will return a JSON serialized instance of the Person class:
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
and then:
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
This obviously assumes that your Person class has FirstName and LastName properties:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
I am trying to learn this as I am doing something very similar. In your $.ajax where does the value for the id string get set? That will be what gets passed into the ActionResult method correct? Also, what if my ActionResult method does not have or does not require an input parameter?
Sure you can! All you need to do in your server-side code, specifically in the controller, is return the Person serialized as a JSON object, like so:
[HttpPost]
public ActionResult GetPersonByID(string id)
{
return Json(person);
}
Then in your AJAX,
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize(),
error: function (xhr, status, error) {
//...
},
success: function (result) {
// result.FirstName
}
});
| common-pile/stackexchange_filtered |
Return data from $.ajax call
I want to return an array from an ajax call. Here is the code that I have come up with so far.
There are constraints that i need to follow. I cannot write additional functions outside of bookNames. The function signature of bookNames is fixed.
bookNames : function(bookUrl){
return $.ajax({
url: theUrl
}
I tried to separate out the book names by using the success callback but was not able to return the array since it is undefined. Here is the code written using success -
bookNames : function(bookUrl){
var allbooks = [];
$.ajax({
url: theUrl,
success : function(data){
for(var i=0; i<data.books.length; i++){
allBooks.push(data.books[i].name);
}
}
});
return allBooks;
}
Here is the json that is returned -
{
"books" : [
{ "name" : "b1" },
{ "name" : "b2" },
{ "name" : "b3" }
]
}
My problem is that i have to return an array of book names i.e ['b1', 'b2', 'b3']. I am kind of stuck now. How can i proceed?
Also function(){ return $.get(bookUrl).then(function(data){ return data.map(function(b){ return b.name; }); }); }
bookNames : function(bookUrl){
return $.get(bookUrl)
.then(function(data){
return data.map(function(b){
return b.name;
});
});
} ---- Somehow this does't work and undefined is returned :(
| common-pile/stackexchange_filtered |
Why one should try throw unchecked exception over checked exception?
I've been told that I should consider throwing Unchecked exception over Checked exception in my code and not only that, but to extend the RuntimeException with my own one.
Now, I do understand the difference between the two, but still doesn't understand why should I do that?
If I have this method header which throws 2 kinds of exceptions:
public static Optional<String> getFileMd5(String filePath) throws NoSuchAlgorithmException, IOException {}
Why should I replace them with one (less detailed) exception?
"Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception."
"Why should I replace them with one (less detailed) exception?" You shouldn't. The only thing you could replace these with is Exception, and that means you're telling the person calling the code that absolutely any exception might be thrown, and they'd have to handle all exceptions accordingly. It's like a method returning Object: anything can be returned, so you have to be prepared for anything. Declaring that you throw specific exceptions means they know only to handle those.
The IOException is acceptable. The caller can't be sure that the filePath exists and will still exist when the method is executed, and your method must be able to signal the problem. IOException is the conventional exception to throw in that case, although you could wrap it inside an UncheckedIOException if you prefer runtime exceptions. An unchecked IO exception would be as clear as a checked IOException. What you would lose (or gain, depending on the point of view) is that you wouldn't force the caller to deal with it.
The NoSuchAlgorithmException exception, on the other hand, should definitely be wrapped into an runtime exception. The caller has no way to do anything if your method uses an algorithm that doesn't exist. It's clearly a bug if that exception happens, and bugs should be signalled by runtime exceptions. So, write your own runtime exception, that wraps the original NoSuchAlgorithmException (so that you don't lose the root cause of the problem if you ever throw it), and don't bother all the callers of your code with an exception that should never, ever happen.
Regarding runtime vs. checked exceptions, it's mainly an opinion-based question, but a few things should be noted though:
AFAIK, no new Java API uses checked exceptions anymore. See java.time for example, which never throws checked exceptions although the old equivalent (like DateFormat) throws checked exceptions
Java is the only language to have checked exceptions.
Checked exceptions don't fit well with functional idioms (lambda expressions, streams, etc.) introduced in Java 8: No functional interface throws a checked exception.
I think it's safe to now say that checked exceptions were an interesting idea, but which proved to be a bad one. You should prefer unchecekd exceptions.
Now, if your question is: how to throw unchecked exceptions rather than checked exceptions, it's quite simple:
public static Optional<String> getFileMd5(String filePath) {
try {
// your original code
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
catch (NoSuchAlgorithmException e) {
throw MyCustomCryptoException(e);
}
}
| common-pile/stackexchange_filtered |
Github action - Pushing flask application to docker hub
Blessings,
I made a Flask API application and whenever I try to push it to docker hub repository via GitHub Action it fails, Also when I try to run it using docker build/run the build finishes but says This site can’t be reached.
While when running the flask application locally (running python file) works.
Dockerfile
FROM ubuntu
WORKDIR ./app
COPY . /app
RUN apt-get update && apt-get install -y python3 python3-pip firefox
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
EXPOSE 8777
CMD ["python3", "./simpleflask.py", "./main.py"]
I get the following error on Github :
Run docker build -t app .
Sending build context to Docker daemon 76.29kB
Step 1/8 : FROM python:3.8
3.8: Pulling from library/python
e756f3fdd6a3: Already exists
bf168a674899: Already exists
e604223835cc: Already exists
6d5c91c4cd86: Already exists
2cc8d8854262: Already exists
2767dbfeeb87: Pulling fs layer
e5a387f746e4: Pulling fs layer
54b770283d3a: Pulling fs layer
d829066ff47d: Pulling fs layer
d829066ff47d: Waiting
54b770283d3a: Verifying Checksum
54b770283d3a: Download complete
2767dbfeeb87: Verifying Checksum
2767dbfeeb87: Download complete
e5a387f746e4: Verifying Checksum
e5a387f746e4: Download complete
d829066ff47d: Verifying Checksum
d829066ff47d: Download complete
2767dbfeeb87: Pull complete
e5a387f746e4: Pull complete
54b770283d3a: Pull complete
d829066ff47d: Pull complete
Digest: sha256:1fbd81716d6d8d6081b11b058894533e36c93abd10d91560ac8011a27ca13947
Status: Downloaded newer image for python:3.8
---> 050b8443e26e
Step 2/8 : WORKDIR ./app
---> Running in 6b66a93bccbb
Removing intermediate container 6b66a93bccbb
---> 784f3185eb08
Step 3/8 : COPY . /app
---> f1ba4f56f664
Step 4/8 : COPY requirements.txt requirements.txt
---><PHONE_NUMBER>7c
Step 5/8 : RUN pip install --upgrade pip
---> Running in c635f7bc6af6
Requirement already satisfied: pip in /usr/local/lib/python3.8/site-packages (22.0.4)
Collecting pip
Downloading pip-22.1.2-py3-none-any.whl (2.1 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 50.0 MB/s eta 0:00:00
Installing collected packages: pip
Attempting uninstall: pip
Found existing installation: pip 22.0.4
Uninstalling pip-22.0.4:
Successfully uninstalled pip-22.0.4
Successfully installed pip-22.1.2
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Removing intermediate container c635f7bc6af6
---> eac8515be6c0
Step 6/8 : RUN pip install -r requirements.txt
---> Running in 00790d0d61fb
Collecting Flask
Downloading Flask-2.1.2-py3-none-any.whl (95 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 95.2/95.2 kB 16.6 MB/s eta 0:00:00
Collecting Flask-RESTful
Downloading Flask_RESTful-0.3.9-py2.py3-none-any.whl (25 kB)
Collecting itsdangerous>=2.0
Downloading itsdangerous-2.1.2-py3-none-any.whl (15 kB)
Collecting Jinja2>=3.0
Downloading Jinja2-3.1.2-py3-none-any.whl (133 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 133.1/133.1 kB 23.7 MB/s eta 0:00:00
Collecting importlib-metadata>=3.6.0
Downloading importlib_metadata-4.11.4-py3-none-any.whl (18 kB)
Collecting Werkzeug>=2.0
Downloading Werkzeug-2.1.2-py3-none-any.whl (224 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 224.9/224.9 kB 40.4 MB/s eta 0:00:00
Collecting click>=8.0
Downloading click-8.1.3-py3-none-any.whl (96 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 96.6/96.6 kB 19.9 MB/s eta 0:00:00
Collecting aniso8601>=0.82
Downloading aniso8601-9.0.1-py2.py3-none-any.whl (52 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 52.8/52.8 kB 12.0 MB/s eta 0:00:00
Collecting six>=1.3.0
Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)
Collecting pytz
Downloading pytz-2022.1-py2.py3-none-any.whl (503 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 503.5/503.5 kB 47.0 MB/s eta 0:00:00
Collecting zipp>=0.5
Downloading zipp-3.8.0-py3-none-any.whl (5.4 kB)
Collecting MarkupSafe>=2.0
Downloading MarkupSafe-2.1.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (25 kB)
Installing collected packages: pytz, aniso8601, zipp, Werkzeug, six, MarkupSafe, itsdangerous, click, Jinja2, importlib-metadata, Flask, Flask-RESTful
Successfully installed Flask-2.1.2 Flask-RESTful-0.3.9 Jinja2-3.1.2 MarkupSafe-2.1.1 Werkzeug-2.1.2 aniso8601-9.0.1 click-8.1.3 importlib-metadata-4.11.4 itsdangerous-2.1.2 pytz-2022.1 six-1.16.0 zipp-3.8.0
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Removing intermediate container 00790d0d61fb
---> 4d7bca1a1903
Step 7/8 : EXPOSE 5000
---> Running in 5d1710cfff1f
Removing intermediate container 5d1710cfff1f
---> 2d116ca965c0
Step 8/8 : CMD ["python", "./simpleflask.py", "./main.py"]
---> Running in bebab646ec94
Removing intermediate container bebab646ec94
---> 881954660c46
Successfully built 881954660c46
Successfully tagged app:latest
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 159, in _new_conn
conn = connection.create_connection(
File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 84, in create_connection
raise err
File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 74, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 665, in urlopen
httplib_response = self._make_request(
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 387, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/lib/python3.8/http/client.py", line 1256, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/lib/python3.8/http/client.py", line 1302, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/usr/lib/python3.8/http/client.py", line 1251, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/lib/python3.8/http/client.py", line 1011, in _send_output
self.send(msg)
File "/usr/lib/python3.8/http/client.py", line 951, in send
self.connect()
File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 187, in connect
conn = self._new_conn()
File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 171, in _new_conn
raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7f0a6dc8e610>: Failed to establish a new connection: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 439, in send
resp = conn.urlopen(
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 719, in urlopen
retries = retries.increment(
File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 436, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='<IP_ADDRESS>', port=5000): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f0a6dc8e610>: Failed to establish a new connection: [Errno 111] Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./main.py", line 7, in <module>
data = requests.post(url, json=(myobj, mysecobj))
File "/usr/lib/python3/dist-packages/requests/api.py", line 116, in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/lib/python3/dist-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='<IP_ADDRESS>', port=5000): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f0a6dc8e610>: Failed to establish a new connection: [Errno 111] Connection refused'))
Error: Process completed with exit code 1.
I also hope its okay to post external links here but here's the repository
https://github.com/awakzdev/Dockerized-API/
main.yml
name: CI
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Script
run: |
docker build -t app .
python ./main.py
echo ${{ secrets.DOCKER.SECRET }} | docker login -u ${{ secrets.DOCKER.USERNAME }} --password-stdin
docker tag app awakz/
docker push awakz/dockerized-flask
How are you pushing built image to docker hub ?
Also not sure why you are trying trying to run the server after built. Skip those steps and push to docker hub once built
@JishnuR I've edited the post with the main.yml
@JishnuR I was tasked with running it before pushing.
You cannot run python without setting up python on GHA. https://github.com/actions/setup-python
I've added python on GHA according to your guide and it still failed. I've changed the dockerfile image from ubuntu to python and it ran.. now flask takes up the whole terminal and wont let ./main.py run aftterwards, is there anyway to run it silently? https://i.imgur.com/YCPZEi4.png
Yeah im still not sure why you are running a server on GHA on merge. Once server runs it will wait there for request. GHA is not a place to run server. Build your image and push to dockerhub. Run your server containers on a place where its supposed to be run
@JishnuRamesh It was requested by my employer. an entrance exam for a devops job, anyway I had a problem logging in so I used uses: docker/login-action@v2
| common-pile/stackexchange_filtered |
Op-amp question: Is this circuit possible?
I was (re)doing some electronic learning, and tried to come with a "general solution" for all op-amp circuits.
I thought I could do so by having an op-amp with both negative and positive feedback, and both voltage accross + and -.
But, when I combine both equations V+ - Vs and V- - Vs, I end up with a solution where Vs cancel out. Am I missing something? In this general case, is V+ - V- still equal to zero?
Does this answer your question: https://electronics.stackexchange.com/questions/112472/how-are-positive-and-negative-feedback-of-opamps-so-different-how-to-analyse-a ?
LittleP, for your specific case I get:$$v_s=\frac{v_p\cdot\left(1+\frac{Z_n}{Z_{rn}}\right)-v_n\cdot\left(1+\frac{Z_p}{Z_{rp}}\right)}{\frac{Z_n}{Z_{rn}}-\frac{Z_p}{Z_{rp}}}$$It's not exactly a differential amplifier in the usual sense of that phrase. (If you need to see how that equation arrives, I can write it up.)
You can start by examining each half in isolation. Here, $v_-=\frac{v_n,\cdot, Z_{rn},+,v_s,\cdot,Z_n}{Z_n,+,Z_{rn}}$ and $v_+=\frac{v_p,\cdot, Z_{rp},+,v_s,\cdot,Z_p}{Z_p,+,Z_{rp}}$. Just equate those two to find $\frac{v_n,\cdot, Z_{rn},+,v_s,\cdot,Z_n}{Z_n,+,Z_{rn}}=\frac{v_p,\cdot, Z_{rp},+,v_s,\cdot,Z_p}{Z_p,+,Z_{rp}}$ and solve for $v_s$. That's all there is to it, I think. It's not complicated.
We can calculate everything - however, the result is valid only in case the negative feedback portion is larger than the positive one. Otherwise, the circuit is unstable. With other words: The shown equation V(+)-(V-) =0 assumes stability and linear operation with effective negative feedback
thanks @periblepsis, it is indeed not complicated, I did a mistake writing the i+ and i- equations where V+- are missing...which led me to my mistake. Is it possible to put your comment as an answer? So I can close my question.
@LittlePanic404 Done. I also added LvW's caution.
Start by examining each half in isolation, as voltage dividers:
$$\begin{align*}
v_-&=\frac{v_n\,\cdot\, Z_{rn}\,+\,v_s\,\cdot\,Z_n}{Z_n\,+\,Z_{rn}}
\\\\
v_+&=\frac{v_p\,\cdot\, Z_{rp}\,+\,v_s\,\cdot\,Z_p}{Z_p\,+\,Z_{rp}}
\end{align*}$$
Then, since the opamp attempts to keep this equal to each other, simply set them equal:
$$\frac{v_n\,\cdot\, Z_{rn}\,+\,v_s\,\cdot\,Z_n}{Z_n\,+\,Z_{rn}}=\frac{v_p\,\cdot\, Z_{rp}\,+\,v_s\,\cdot\,Z_p}{Z_p\,+\,Z_{rp}}$$
And then solve for \$v_s\$:
$$v_s=\frac{v_p\cdot\left(1+\frac{Z_n}{Z_{rn}}\right)-v_n\cdot\left(1+\frac{Z_p}{Z_{rp}}\right)}{\frac{Z_n}{Z_{rn}}-\frac{Z_p}{Z_{rp}}}$$
However, this only works when \$\frac{Z_n}{Z_{rn}}\gt\frac{Z_p}{Z_{rp}}\$. Otherwise, with the denominator negative, a positive change in \$v_p\$ would be met by a negative change in \$v_s\$ (wrong direction) or a positive change in \$v_n\$ would be met by a positive change in \$v_s\$ (also the wrong direction.) And, of course, \$\frac{Z_n}{Z_{rn}}=\frac{Z_p}{Z_{rp}}\$ is forbidden as well since that would be division-by-zero.
Here's an example run where \$v_s=3.5\times di\!f\!f\$ where \$-3\:\text{V}\le di\!f\!f\le 3\:\text{V}\$:
| common-pile/stackexchange_filtered |
Improving the convergence speed in a Leibniz series
I have read the proof for the Leibniz criterion. Underneath there was a remark that I did not understand it says that if we have a Leibniz series than one can obtain $s$ sometimes faster by calculating the (arithmetic) mean value and with index shift.
With Leibniz series I mean that $(a_n)$ is a monotonically decreasing zero-convergent sequence. And the Leibniz series $\sum_{n=0}^{\infty}(-1)^na_n$ converges. Let $s$ be the value it converges to
My Question why
$\frac 1 2a_0+\frac 1 2\sum_{n=0}^{\infty}(-1)^n(a_n-a_{n+1})$
also converges to $s$?
And if
$|s-\sum_{n=0}^k(-1)^na_n|\leq a_{k+1}$
Why is
$|s-\big(\frac 1 2a_0+\frac 1 2\sum_{n=0}^{\infty}(-1)^n(a_n-a_{n+1})\big)|\leq a_{k+1} a_{k+2}$
Thanks for helping
What I have thought so far is that the if we have
$\frac 1 2a_0+\frac 1 2\sum_{n=0}^{\infty}(-1)^n(a_n-a_{n+1})$
then the Right Hand side cannot converge to $s$ it must somehow compensate the influence of the Always constant $a_0/2$ in a way that it converges to $s$. Maybe one can do someting with the distributive law but I am not sure if I am allowed to use it.
In particular if $L=\sum (-1)^n \frac{1}{n+1}$
then also
$L=\frac{1}{2}+\frac{1}{2}\big(\frac{1}{1\cdot 2}-\frac{1}{2\cdot 3}+\frac{1}{3\cdot 4}-\frac{1}{4\cdot 5}+ …\big)$
Please give more context. Providing context not only assures that this is not simply copied from a homework assignment, but also allows answers to be better directed at where the problem lies and to be within the proper scope. Please avoid "I have no clue" questions. Defining keywords and trying a simpler, similar problem often helps.
To see what is going on, take a look at the simpler example of taking the sum from $n=0$ to $n=3$: $\frac12a_0+\frac12(a_0-a_1)-\frac12(a_1-a_2)+\frac12(a_2-a_3)-\frac12(a_3-a_4)=a_0-a_1+a_2-a_3+\frac12a_4$
I believe that $a_n=10^{-n}$ shows that the proposition about the error of the accelerated series doesn't hold; that is, $|s-\big(\frac 1 2a_0+\frac 1 2\sum_{n=0}^{\infty}(-1)^n(a_n-a_{n+1})\big)|\leq a_{k+1} a_{k+2}$
Generalizing on my comment:
$$
\begin{align}
\frac12a_0+\frac12\sum_{k=0}^n(-1)^k(a_k-a_{k+1})
&=\frac12a_0+\frac12\sum_{k=0}^n(-1)^ka_k-\frac12\sum_{k=0}^n(-1)^ka_{k+1}\\
&=\frac12a_0+\frac12\sum_{k=0}^n(-1)^ka_k-\frac12\sum_{k=1}^{n+1}(-1)^{k-1}a_k\\
&=\frac12a_0+\frac12\sum_{k=0}^n(-1)^ka_k+\frac12\sum_{k=1}^{n+1}(-1)^ka_k\\
&=\sum_{k=0}^n(-1)^ka_k+\frac12(-1)^{n+1}\,a_{n+1}
\end{align}
$$
If you are uncertain what you can use in an infinite sum, apply rules to a finite sum and then take the limit.
| common-pile/stackexchange_filtered |
Windows Phone string to color
There is no System.Windows.Media.ColorConverter in Windows Phone (or Silverlight) so I need another way to take a string containing a color name e.g. "Red" and generate a Color object from it.
I found this possibility but it doesn't work as colorType.GetProperty always returns null.
public static Color ConvertFromString(string colorString)
{
Color retval = Colors.Transparent;
Type colorType = (typeof(Colors));
if (colorType.GetProperty(colorString) != null)
{
object o = colorType.InvokeMember(colorString,
BindingFlags.GetProperty, null, null, null);
if (o != null)
{
retval = (Color)o;
}
}
return retval;
}
Any ideas?
I like both answers and both work fine. The only reason I didn't mark the XAML one as the answer was that it was not case insensitive. If colorName is "RED" it does not work. Not sure which is more efficient.
Try this :
public static Color GetColor(String ColorName)
{
Type colors = typeof(System.Windows.Media.Colors);
foreach(var prop in colors.GetProperties())
{
if(prop.Name == ColorName)
return ((System.Windows.Media.Color)prop.GetValue(null, null));
}
throw new Exception("No color found");
}
Not tried it on WP, but in SL you can hijack XAML for this (and also for SolidColorBrush and such):
private Color StringToColor(string colorName)
{
string xaml = string.Format("<Color xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">{0}</Color>", colorName);
try { return (Color)XamlReader.Load(xaml); }
catch { return Colors.Transparent; }
}
| common-pile/stackexchange_filtered |
How to find inputs of dask.delayed task?
Given a dask.delayed task, I want to get a list of all the inputs (parents) for that task.
For example,
from dask import delayed
@delayed
def inc(x):
return x + 1
def inc_list(x):
return [inc(n) for n in x]
task = delayed(sum)(inc_list([1,2,3]))
task.parents ???
Yields the following graph. How could I get the parents of sum#3 such that it yields a list of [inc#1, inc#2, inc#3]?
Delayed objects don't store references to their inputs, however you can get these back if you're willing dig into the task graph a bit and reconstruct Delayed objects manually.
In particular you can index into the .dask attribute with the delayed objects' key
>>> task.dask[task.key]
(<function sum>,
['inc-9d0913ab-d76a-4eb7-a804-51278882b310',
'inc-2f0e385e-beef-45e5-b47a-9cf5d02e2c1f',
'inc-b72ce20f-d0c4-4c50-9a88-74e3ef926dd0'])
This shows the task definition (see Dask's graph specification)
The 'inc-...' values are other keys in the task graph. You can get the dependencies using the dask.core.get_dependencies function
>>> from dask.core import get_dependencies
>>> get_dependencies(task.dask, task.key)
{'inc-2f0e385e-beef-45e5-b47a-9cf5d02e2c1f',
'inc-9d0913ab-d76a-4eb7-a804-51278882b310',
'inc-b72ce20f-d0c4-4c50-9a88-74e3ef926dd0'}
And from here you can make new delayed objects if you wish
>>> from dask.delayed import Delayed
>>> parents = [Delayed(key, task.dask) for key in get_dependencies(task.dask, task.key)]
[Delayed('inc-b72ce20f-d0c4-4c50-9a88-74e3ef926dd0'),
Delayed('inc-2f0e385e-beef-45e5-b47a-9cf5d02e2c1f'),
Delayed('inc-9d0913ab-d76a-4eb7-a804-51278882b310')]
| common-pile/stackexchange_filtered |
Display ReportViewer results on Load - ServerReport.Refresh() doesn't do anything
I have a ReportViewer control on my webpage. It loads properly and when I click on the "View Report" button, the results are properly displayed.
But now I want it to display the results when the page loads and not ask the user to click on the "View Report" button.
I see everywhere that I must use the ServerReport.Refresh() method, but it doesn't seem to do anything. I subscribed to the ReportRefresh event, it's not even fired.
The control is on a "regular" page, nothing else on it, no UpdatePanel.
I added a button that also executes ServerReport.Refresh() but it doesn't work either, nothing happens.
I tried to enable/disable most options that seem to relate to the issue (ShowRefreshButton, AsyncRendering...) and I've set all the parameters.
I also tried to put the initialization code in the Page_Init() method, without success.
The report won't load without clicking on the "View Report" button.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Sets credentials, URL & Path
ReportHelper.InitializeReportViewer(rptViewer);
rptViewer.ProcessingMode = ProcessingMode.Remote;
rptViewer.ShowReportBody = true;
rptViewer.ReportRefresh += rptViewer_ReportRefresh;
var v = rptViewer.ServerReport.GetParameters().Select(p => new ReportParameter(p.Name, p.Values.ToArray()));
rptViewer.ServerReport.SetParameters(v);
rptViewer.AsyncRendering = false;
rptViewer.ServerReport.Refresh();
}
}
I'm still looking for a better answer but until then, I hide the parameters panel (and might even hide the collapsed bar through CSS) and simulate a click on the button.
It's not ideal, but it works.
In the code behind :
rptViewer.PromptAreaCollapsed = true;
In the ASPX script header :
$(document).ready(function () {
var btnSubmit = $("#<%=rptViewer.ClientID%> :submit");
btnSubmit.trigger("click");
});
| common-pile/stackexchange_filtered |
How do we know what build top players use?
One of the sources we can use is http://diablo.somepage.com/popular/witch-doctor#builds
However, that's not good enough. Some build, for example, it is awesome for some set items and total junk for other set items. Haunt and Locust Farm are definetly needed for the Jade Harvester build but is not so useful on Helltooth builds.
Say I want to know who are the top players and what do they use? How do I find that?
You can use the Diablo 3 Leaderboards to see who is the top for this season you can also see what builds they use. By right clicking your portrait in the game and then right clicking the person in the leaderboards and then clicking View Hero Details
+1 Rankings let you see everything! But How do you know if that is their farming gear or the solo rift gear ?
The Hero Details button shows the build (items/skills) used to complete that level. So even if the player changes his equipment, the one used will still be there.
As fcm said.. Sorry for not putting it in the answer.
| common-pile/stackexchange_filtered |
Get the text from an external HTML document
My goal is to get the text from a HTML document which does not call any functions from my .jsp file.
I've looked around and I thought I had found the answer to my problem but it doesn't seem to be working, and other answers consist of using jQuery (which I am both unfamiliar with and not allowed to use).
This is my code so far:
function getText(divID) {
var w = window.open("test.html");
var body = w.document.body;
var div = document.getElementById(divID);
var textContent = body.textContent || body.innerText;
console.log(textContent);
//div.appendChild(document.createTextNode(textContent));
}
So as you can see, I'm trying to get the body of one HTML document and have it appear in another. Am I on the right tracks?
EDIT: Ok so I seem to have made my problem quite confusing. I call the function in a HTML document called html.html, but I want to get the text from test.html, then have it appear in html.html. It has to be like this because I can't assume that the HTML document I want to read from will include my .jsp file in its head.
At the moment I am getting the following error.
Uncaught TypeError: Cannot read property 'body' of undefined
The XMLHttpRequest object is better than opening a window.
Apart from what epascarello has said, elements don't have createTextNode method, document has. You've to create the text node to the document, and then append it to the div.
This isn't currently my problem, as you can see it is commented out. The problem is the console produces: "Uncaught TypeError: Cannot read property 'body' of undefined". test.html is in the same directory as the JSP, and I have another HTML file calling the function onload.
In that case you might want to edit your question, and tell us exactly what goes wrong.
The reason document.body in the other window is undefined, is because the other window has not loaded and rendered the document yet.
One solution would be to wait for the onload event.
function getText(divID) {
var w = window.open("test.html");
w.addEventListener("load", function() {
var body = w.document.body;
var div = document.getElementById(divID);
var textContent = body.textContent || body.innerText;
console.log(textContent);
});
}
Make sure you run the getText function on a user event like a click, else window.open will fail.
If all you want to do is get the contents of the other window, using AJAX would probably be a better option.
function getText(divID) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 ) {
var body = xhr.response.body;
var div = document.getElementById(divID);
var textContent = body.textContent || body.innerText;
console.log(textContent);
}
};
xhr.open("GET", "test.html", true);
xhr.responseType = "document";
xhr.send();
}
Using this I get: Uncaught TypeError: Cannot read property 'addEventListener' of undefined
As I said the test.html (The page to be read from) is in the same directory as both the jsp and html.html. Could it be a problem with my file structure?
@JamieBlue What browser are you using? window.open should not return undefined. Unless you are trying to run this outside a user event like a click?
I'm using google chrome, the problem was that it actually tried to open a new window, but blocked the pop-up. Thanks a lot for your help.
Sorry about this, is there a way to do this without the window actually opening in the browser each time I test it?
@JamieBlue Is there a reason you want to open the document in another window? You could just load the content via AJAX in the background.
No I don't need it visibly open in another window, I just need the text contents of test.html. I'm not familiar with AJAX, is it a language? If so, I'm required to use solely Javascript, HTML and CSS.
@JamieBlue AJAX is a way of requesting the contents of another file with JavaScript. I've added an example to my answer.
| common-pile/stackexchange_filtered |
Read .wav file data for every 160 microseconds
How to extract data corresponding to definite time intervals from a .wav file?
I have been given a few .wav files and asked to separate the header and data. From the obtained data, samples corresponding to every 160-microseconds should be separated and copied to buffers.
I have now separated the header and got the following information:
Channels: 2,
Frames: 632956
Sample Rate: 44100,
Block Align: 4
Valid Bits: 16,
Bytes per sample: 2
For separating samples corresponding to every 160-microseconds, I am not able to calculate. I tried the following way:
Total bits per 160-microsecond = ((sampling_rate * bit depth) / (time))
= ((44100 * 16) / (160 * 1000000)) = 0.00441 bits.
I am sure that there is a mistake in the above calculation since there exist 44100 samples per second and hence for 160-microseconds there should exist bits count which is a positive natural number and cannot be a decimal value.
Can someone help with this calculation?
Thanks.
Possible duplicate of Reading wav file in Java
@NikolayShevchenko No my question is different. I am attempting to read chunks of data equivalent to a particular time interval. And stuck in calculating the same.
Let's say, I read the wav file as mentioned in the other thread and obtain all the data in a byte buffer, how am I pull the data equivalent to 160-microseconds. This is my primary question.
The number of sampling intervals, which fit into time window
N = length_of_time_window / length_of_sampling_interval =
= length_of_time_window * sampling_frequency = 0.00016 s * 44100 = 7.056
Obviously, the 160 microseconds interval is not divisible by sampling interval, but you can use 7 samples, which corresponds to 158 microseconds. Since each sample should store data for 2 channels, each using 2 bytes, the number of bytes is
Bytes = N * channels * bytes_per_sample = 7 samples * 2 channel * 2 bytes_per_sample
= 28 bytes
| common-pile/stackexchange_filtered |
Two overloaded methods to move an e-mail message to another mailbox folder
I have an API for managing an email mailbox. There is a class called Message, and it has two Move overloads:
/// <summary>
/// Move this message to the mailbox folder whose path is provided.
/// </summary>
/// <param name="toFolderPath">The path to the mailbox folder to which this message will be moved.</param>
/// <param name="createFolder">If true, the destination folder will be created first if it doesn't exist.</param>
/// <exception cref="InvalidOperationException">
/// <para>An exception will be thrown if this message does not reside in a mailbox because
/// only messages in mailboxes can be moved between folders. Use <see cref="ContainingFolder"/> to determine if
/// the message resides within a mailbox and folder; that value will be null if it does not.</para>
/// <para>An exception will be thrown if the destination folder does not exist and if the provided <paramref name="createFolder"/> is false.</para>
/// </exception>
public void Move(string toFolderPath, bool createFolder)
{
ValidateMoveCopy();
Move(GetCreateFolder(toFolderPath, createFolder));
}
/// <summary>
/// Move this message to the provided mailbox folder.
/// </summary>
/// <param name="toFolder">The mailbox folder to which this message will be moved.</param>
/// <exception cref="InvalidOperationException">An exception will be thrown if this message does not reside in a mailbox because
/// only messages in mailboxes can be moved between folders. Use <see cref="ContainingFolder"/> to determine if
/// the message resides within a mailbox and folder; that value will be null if it does not.</exception>
public void Move(MailboxFolder toFolder)
{
ValidateMoveCopy();
ParentMailbox.MoveMessage(this, toFolder);
}
The first overload will retrieve the mailbox folder or create it if it doesn't yet exist, but only if the createFolder argument is true; then it will just call the second overload.
What I'd like to avoid is calling the ValidateMoveCopy twice when the first overload is used (once in that method, and once in the second overload); however, I don't want GetCreateFolder to be called in the first method if validation fails.
Here are GetCreateFolder and ValidateMoveCopy:
/// <summary>
/// Return the folder with the provided path, if it exists, from the parent mailbox,
/// or else create it if it should be created based on <paramref name="createIfMissing"/>
/// </summary>
/// <param name="withFolderPath"></param>
/// <param name="createIfMissing"></param>
/// <returns></returns>
private MailboxFolder GetCreateFolder(string withFolderPath, bool createIfMissing)
{
if (createIfMissing)
{
return ParentMailbox.CreateFolder(withFolderPath); // create or retrieve if existing.
}
else // folder won't be created if it doesn't exist.
{
var ret = ParentMailbox.GetFolder(withFolderPath);
if (ret == null) throw new InvalidOperationException(string.Format(@"The folder ""{0}"" does not exist in mailbox ""{1}"" and will not be created.", withFolderPath, ParentMailbox.Name));
return ret;
}
}
/// <summary>
/// Validate this message for a "move" or "copy" operation, and throw an exception if not valid.
/// </summary>
private void ValidateMoveCopy()
{
if (ParentMailbox == null) throw new InvalidOperationException("This message does not reside in a mailbox and cannot be moved or copied.");
}
Is there a good way to do this? Since both overloads are public, I don't want to do something like add a bool isAlreadyValidated to the second overload. I could use a private field:
/// <summary>
/// True only if a move operation is underway and it has already been validated.
/// </summary>
private bool _isValidatedForMove = false;
and use it like this:
/// <summary>
/// Move this message to the mailbox folder whose path is provided.
/// </summary>
/// <param name="toFolderPath">The path to the mailbox folder to which this message will be moved.</param>
/// <param name="createFolder">If true, the destination folder will be created first if it doesn't exist.</param>
/// <exception cref="InvalidOperationException">
/// <para>An exception will be thrown if this message does not reside in a mailbox because
/// only messages in mailboxes can be moved between folders. Use <see cref="ContainingFolder"/> to determine if
/// the message resides within a mailbox and folder; that value will be null if it does not.</para>
/// <para>An exception will be thrown if the destination folder does not exist and if the provided <paramref name="createFolder"/> is false.</para>
/// </exception>
public void Move(string toFolderPath, bool createFolder)
{
ValidateMoveCopy();
_isValidatedForMove = true;
Move(GetCreateFolder(toFolderPath, createFolder));
_isValidatedForMove = false;
}
/// <summary>
/// Move this message to the provided mailbox folder.
/// </summary>
/// <param name="toFolder">The mailbox folder to which this message will be moved.</param>
/// <exception cref="InvalidOperationException">An exception will be thrown if this message does not reside in a mailbox because
/// only messages in mailboxes can be moved between folders. Use <see cref="ContainingFolder"/> to determine if
/// the message resides within a mailbox and folder; that value will be null if it does not.</exception>
public void Move(MailboxFolder toFolder)
{
if(!_isValidatedForMove) ValidateMoveCopy();
ParentMailbox.MoveMessage(this, toFolder);
}
But that feels kind of like a code smell for some reason. I welcome any thoughts or suggestions. By the way, I'm aware this code isn't thread safe.
@DrProgrammer If you have suggestions to improve the code, then please write an answer. Critiquing the code in comments is not appropriate.
I think the best option would be to introduce a third, private method:
private void Move(MailboxFolder toFolder, bool requiresValidation)
{
if (requiresValidation)
{
ValidateMoveCopy();
}
ParentMailbox.MoveMessage(this, toFolder);
}
Then your other methods just call that one.
public void Move(MailboxFolder toFolder)
{
Move(toFolder, true);
}
public void Move(string toFolderPath, bool createFolder)
{
ValidateMoveCopy();
MailboxFolder toFolder = GetOrCreateFolder(toFolderPath, createFolder);
Move(toFolder, false);
}
I renamed GetCreateFolder to GetOrCreateFolder which is slightly easier to read IMO. I've also introduced a variable for toFolder as I don't like lines of code that do 2 things.
Edit:
Short and concise methods are brilliant and a very good thing to aim for. However, consider your method at a glance:
Move(GetCreateFolder(toFolderPath, createFolder));
How easy is it to spot the side effect there (possibly creating a new folder) vs my version:
MailboxFolder toFolder = GetOrCreateFolder(toFolderPath, createFolder);
Move(toFolder, false);
It's a stylistic thing without doubt and if you prefer the brevity then that's absolutely fine. I should have been more explicit about that being a preference thing rather than a rule!
Thank you, this is great. To your point about lines that do multiple things, I'm always looking to keep methods to as few lines as possible as a rule. Can you elaborate on why (other than ease of debugging) multiple lines is better than one line?
@roryap - added an update for you!
| common-pile/stackexchange_filtered |
Force linebreak after javadoc @see
I want to use the @see tag in javadoc to give a hint to multiple books. Something like this.
/**
* @see "Book 1"
* @see "Book 2"
*/
public void complexMethod() {}
Javadoc produces html code which separates the two books with a comma. I would prefer to separate them with a linebreak. Any ideas how this is possible?
The only solution I could figure out is to add an extra <br> after the first @see tag. But this would lead to an extra comma before the second booktitle.
You could try using:
/**
* @see
* <p>
* "Book1" </br>
* "Book2"
* </p>
*/
public void complexMethod() {}
| common-pile/stackexchange_filtered |
Multiple ipc publishers and one subscriber using python-zmq
I'm wondering if is possible set multiple ipc publishers for one subscriber using zmq ipc...
Abstractly I have only one publisher like this, but I need run multiple instances of it getting several data types but publishing the same format every time.
context = zmq.Context()
publisher = context.socket(zmq.PUB)
publisher.connect("ipc://VCserver")
myjson = json.dumps(worker.data)
publisher.send(myjson)
My subscriber:
context = zmq.Context()
subscriber = context.socket(zmq.SUB)
subscriber.bind("ipc://VCserver")
subscriber.setsockopt(zmq.SUBSCRIBE, '')
while True:
response = subscriber.recv()
if response:
data = json.loads(response)
check_and_store(data)
My subscriber every time is checking the same parameters from the data and storing it on a db.I do not know if it is possible, as this mode of communication uses a shared file and maybe I should think in publisher-subscriber pairs for every instance...
EDITED:Every publisher will send 2kb aprox, 100 times/sec
You can definitely have multiple publishers, the only restriction is that you cannot have multiple binders on one IPC socket - each successive bind simply clobbers previous ones (as opposed to TCP, where you will get EADDRINUSE if you try to bind to an already-in-use interface). Your case should work fine.
The multiple binders doing clobbering vs. EADDRINUSE is subtle! Thanks!
| common-pile/stackexchange_filtered |
How to hit curl to Kong after applying RBAC authentication
We have authenticated kong with RBAC credentials. Before this, we are able to hit localhost:8001/default/apis?size=100. But after applying RBAC authentication, we are getting the below error
{
"message": "Invalid RBAC credentials. Token or User credentials required"
}
Please help with the steps to run this on browser or as curl request.
If you followed the installation instruction, Kong advised seeding Super Admin token.
This token can be used with appropriate header when calling Admin API.
For example using default header with token value 'password':
curl http://kong-ip:8001/ --header 'Kong-Admin-Token: password'
If you miss the step of seeding super admin. following this instruction to seed admin token and use it with header from prior reference.
| common-pile/stackexchange_filtered |
ON DUPLICATE KEY UPDATE ... with WHERE or subselection?
i am a bit concerned about one of my mysql queries... The following query receives a variable $DB_id... if a row with that primary key already exists the query performs an update.
$this->db->query(" INSERT INTO modules_text
( module_id,
module_content,
module_index
)
VALUES ( '{$DB_id}',
'{$content['text']}',
'{$index}'
)
ON DUPLICATE KEY
UPDATE module_content = '{$content['text']}',
module_index = '{$index}'
");
NOW THE THING THAT CONCERNS ME... There is no relation if the affected rows actually belong to the user. I would like to add a where statement to the UPDATE part or first make a subselecion of the rows which are permitted to be affected. SOmething like:
[...]
ON DUPLICATE KEY
UPDATE module_content = '{$content['text']}',
module_index = '{$index}'
WHERE module_post_id = '{$post]}'
Is this somehow possible... Until now i didnt find a solution... Any help would be very appreciated... THANKS A LOT!!!!!
Saludos Sacha!
This isn't how ON DUPLICATE KEY works. The update portion of the INSERT will only occur if there's a match for the UNIQUE key(s) or PRIMARY key for the table. (i.e.: The UNIQUE/PRIMARY key(s) are effectively the WHERE clause.)
See the full MySQL docs for more information.
I know... But the id's get passed by the client... so a user could try to modify those keys... In my case this is somehow insecure...
@Bosh - That's not MySQLs fault. If you're directly passing in database IDs from a query string then that's your design flaw. (Why not store a unique textual module reference and use that instead?)
I know ;-) Because of that design flaw i am looking for a solution ;-) Actually i obfuscate the id's already to make it more secure but its not one of the most strongest algorythms because of performance... What do you mean exactly with unique textual module reference... I googled but didnt find an axplanation... Thank You!
@Bosh Instead of using an ID, use a text reference (e.g.: "testmodule") and store this reference in the database table along with the ID. As such, instead of having to do a lookup on an ID, you do the lookup on the text name, which unlike an ID can't be easily guessed.
Hmm... okay i understand... I'll give that a try if i don't find a simpler solution. I am a little bit worried how this effects performance selecting by textual ids rather than numeric id's... Furthermore I already have the necessary data to make it secure i just need to find the best way to handle it. Adding another column should be the last choice... As you mentioned its a design flaw not a lack of data ;-) So i should first try to modify my queries not the data ;-) Thank you very much...
@Bosh as long as the module reference field is an index it'll be just as fast. It also means you can create SEO friendly URLs, etc. in the future. :-)
hehe... I already use textual id's for nicer urls... but till now only for the main table entries and not this part of the application ;-)
| common-pile/stackexchange_filtered |
Keycloak clustering setup issue
I created a test virtual machine to apply Keycloak clustering.
I installed Keycloak version 26 there and set it up as follows.
conf/cache-ispn-tcpping.xml
<infinispan
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:infinispan:config:15.0 http://www.infinispan.org/schemas/infinispan-config-15.0.xsd"
xmlns="urn:infinispan:config:15.0">
<jgroups>
<stack name="tcpping" extends="tcp">
<TCP bind_port="7805" bind_addr="<IP_ADDRESS>" external_addr="<IP_ADDRESS>" />
<TCPPING
initial_hosts="<IP_ADDRESS>[7805],<IP_ADDRESS>[7805]"
port_range="0"
/>
<FD_SOCK bind_port="57805"/>
<pbcast.GMS print_local_addr="true" join_timeout="3000"/>
<pbcast.STABLE stability_delay="1000" max_bytes="50000"/>
<pbcast.NAKACK2 use_mcast_xmit="false" discard_delivered_msgs="true"/>
<UNICAST3 xmit_table_num_rows="1024" xmit_table_msgs_per_row="1024"/>
<MERGE3 min_interval="10000" max_interval="30000"/>
</stack>
</jgroups>
<cache-container name="keycloak">
<transport lock-timeout="60000" stack="tcp"/>
...
conf/keycloak.conf
...
cache=ispn
cluster=default
cache-stack=tcp
cache-config-file=cache-ispn-tcpping.xml
cache-remote-port=7805
However, when I run it, the following message is executed.
[root@vm-test keycloak-26.0.1]# ./bin/kc.sh start
2024-10-24 01:20:44,085 WARN [org.keycloak.quarkus.runtime.cli.Picocli] (main) The following used run time options are UNAVAILABLE and will be ignored during build time:
- cache-remote-port: Available only when remote host is set.
2024-10-24 01:20:47,021 INFO [org.keycloak.quarkus.runtime.storage.infinispan.CacheManagerFactory] (main) Starting Infinispan embedded cache manager
2024-10-24 01:20:47,798 INFO [org.infinispan.CONTAINER] (Thread-5) ISPN000556: Starting user marshaller 'org.infinispan.commons.marshall.ImmutableProtoStreamMarshaller'
2024-10-24 01:20:48,263 WARN [org.jgroups.stack.Configurator] (Thread-5) JGRP000014: ThreadPool.thread_dumps_threshold has been deprecated: ignored
2024-10-24 01:20:48,279 INFO [org.infinispan.CLUSTER] (Thread-5) ISPN000078: Starting JGroups channel `ISPN` with stack `tcp`
2024-10-24 01:20:48,280 INFO [org.jgroups.JChannel] (Thread-5) local_addr: b2234e0f-3122-402a-9b7c-daea16717644, name: vm-test-20791
2024-10-24 01:20:48,301 INFO [org.jgroups.protocols.FD_SOCK2] (Thread-5) server listening on *.57800
2024-10-24 01:20:50,308 INFO [org.jgroups.protocols.pbcast.GMS] (Thread-5) vm-test-20791: no members discovered after 2002 ms: creating cluster as coordinator
2024-10-24 01:20:50,318 INFO [org.infinispan.CLUSTER] (Thread-5) ISPN000094: Received new cluster view for channel ISPN: [vm-test-20791|0] (1) [vm-test-20791]
2024-10-24 01:20:50,396 INFO [org.infinispan.CLUSTER] (Thread-5) ISPN000079: Channel `ISPN` local address is `vm-test-20791`, physical addresses are `[<IP_ADDRESS>:7800]`
2024-10-24 01:20:50,864 INFO [org.keycloak.connections.infinispan.DefaultInfinispanConnectionProviderFactory] (main) Node name: vm-test-20791, Site name: null
2024-10-24 01:20:50,872 INFO [org.keycloak.broker.provider.AbstractIdentityProviderMapper] (main) Registering class org.keycloak.broker.provider.mappersync.ConfigSyncEventListener
2024-10-24 01:20:52,061 WARN [io.agroal.pool] (main) Datasource '<default>': JDBC resources leaked: 7 ResultSet(s) and 0 Statement(s)
2024-10-24 01:20:52,378 INFO [io.quarkus] (main) Keycloak 26.0.1 on JVM (powered by Quarkus 3.15.1) started in 9.176s. Listening on: https://<IP_ADDRESS>:8443
2024-10-24 01:20:52,378 INFO [io.quarkus] (main) Profile prod activated.
2024-10-24 01:20:52,378 INFO [io.quarkus] (main) Installed features: [agroal, cdi, hibernate-orm, jdbc-mssql, keycloak, narayana-jta, opentelemetry, reactive-routes, rest, rest-jackson, smallrye-context-propagation, vertx]
I applied 7805 to the cache port that exists in all settings, but it operates as the default port 7800.
The IP also operates only as the internal docker IP <IP_ADDRESS>:7800.
I can't find the cause at all.
How can I change the port number and the IP of the physical addresses???
| common-pile/stackexchange_filtered |
Python how to check the dictonary have value in list and change to string type?
I have below dictionary in which value for some of keys are appeared as list.
i need to find those values which are list type and need to convert to string
details=
{
"dsply_nm": [
"1981 test test"
],
"eff_dt": [
"2021-04-21T00:01:00-04:00"
],
"exp_dt": [
"2022-04-21T00:01:00-04:00"
],
"pwr": [
"14"
],
"is_excl": [
"true"
],
"is_incl": [
"false"
],
"len": [
"14"
],
"max_spd": [
"14"
],
"id": "58",
"type_nm": "single",
"updt_dttm": "2021-04-21T13:40:11.148-04:00",
"nbr": "3",
"typ": "premium",
"nm": "test"
}
below code not seems to be working and its not returning as string
test={}
for k,v in details.items():
if isinstance(v, list):
test[k]="".join(str(v))
test[k]=v
print(test)
expected should be as below
{'dsply_nm':'1981 test test',
"eff_dt": "2021-04-21T00:01:00-04:00",
"exp_dt":"2022-04-21T00:01:00-04:00",
"pwr":"14",
"is_excl":"true",
"is_incl": "false",
"len":"14",
"max_spd":"14",
"id":"58",
"updt_dttm":"2021-04-21T13:40:11.148-04:00",
"nbr":"3",
"typ": "premium",
"nm":"test"
}
anybody can help on this?
Your code is just an overly-elaborate way of making a copy of data.
@ScottHunter i didn't get your answer
Your code is almost correct - you forgot else clause and should not use str(v) before join.
This code works fine:
test={}
for k,v in details.items():
if isinstance(v, list):
test[k]="".join(v)
else:
test[k]=v
print(test)
| common-pile/stackexchange_filtered |
Is my guitar action too high or is the bridge too high?
I've been trying to play barre chords for a few weeks now, but I can never make the G string to sound properly. Also, I feel like I'm putting on more pressure to play the barre chords than is required.
I just wanted to know if it's just improper technique or whether my action is too high.
At which fret are you having trouble?
I’m wondering if it’s the nut (at the first fret)? I’ve seen some luthiers online that have talked about the height of the troughs each string lies in.
Action, to an extent, is due to the height of the bridge. Which does look like it could be lower. It's way higher than the bridges on my guitars, but I do like as low an action as possible. The strings look like maybe .011 - 054 ish, so again, there's not a lot in your favour for learning to play barre chords. They are heavy-ish and will present more tension making them difficult to hold down. G string problem may be because it's wound, and will be tight compared with a plain G, although wound is commonplace on acoustics.
If you don't want to change to lighter strings, tune down a tone. It will make the strings easier to barre. but the bridge needs lowering. If it's a fixed bridge with no adjustment, it's a job that can be done, but not then undone! Go too low, and there will be problems.
The strings are 0.011-0.05 light gauge as per the packet.
I wasn't far out! .050 is heavier than I use, and will be fairly tight for a beginner learning to barre.
Is the relief alright for the guitar? Would lowering or increasing relief help? I live far away from a guitar shop and it would take almost a day to travel to and fro
Relief doesn't look too bad. I'd start by lowering the bridge, until one string starts to rattle on a fret (any fret, try all), then raise a little.Increasing relief will make the problem worse!
The action will be a result of the height of the nut, the height of the bridge, and the amount of relief in the neck.
Your action lower down the neck does look high to me. It's hard for me to tell if that's due to the bridge height, or also due to the amount of neck relief.
If you can find a reasonably-priced local tech or music shop, I'd suggest taking it to them for a check-up.
Get a second bridge and make it slight lower than the one on it. Than replace the first bridge with that one. If it helps great if not you can put the other one back on. IMPORTANT; You just want to replace the ivory part of the bridge - not the wood part. You can find the part at a local music store. Anything else would be too risky by a non-luthier.
is the saddle ( the white part) attached to the wooden part through glue or is it just held in place by the string tension ?
It is usually not glued or is lightly glued just try to gentle pry it out. I've never saw one glued in, but you never know for sure.
The best thing to do is take it to a music store with a real technician and let them do a full setup on the instrument for you. They'll set it up perfectly to factory specifications and can make any adjustments for you.
| common-pile/stackexchange_filtered |
Injecting Beans in JSF 2.0
I have a Session scoped bean
import javax.faces.bean.SessionScoped;
import javax.inject.Named;
@Named
@SessionScoped
public class SessionBean implements Serializable{
I inyect the object in one Filter...
public class FiltroSeguridad implements Filter{
@Inject
private SessionBean sessionBean;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
sessionBean.setRutaRedirect(httpRequest.getRequestURI());
}
}
But, I inyect SessionBean in the next interaction...
@Model
public class CuentaUsuarioWebBean implements Serializable{
@Inject
private SessionBean sessionBean;
public void loginUsuario() throws IOException{
sessionBean.getRutaRedirect();
}
}
But the property getRutaRedirect() returns null
I change the import by CDI annotations it still doesn't work (javax.enterprise.context.SessionScoped), same with JSF annotation (javax.faces.bean.ManagedBean and @ManagedProperty).
Thanks.
PD: Sorry for my English!
This works only if you have a /WEB-INF/beans.xml file (which a bit sane IDE would already autogenerate when you choose the CDI facet and/or which is already mentioned in a bit sane CDI tutorial, if you've read a tutorial). Do you have this file?
You can't mix annotations from those two packages you're using javax.faces.bean.SessionScoped for JSF, and import javax.inject.Named for CDI. Both reflect different injection mechanisms and cannot be mixed on the same bean. You have to pick both annotations(for Injection and Bean Scoping) from the same package. Use the following sets from their corresponding packages
For CDI-based bean definitions
javax.enterprise.context.SessionScoped //for bean scoping
javax.inject.Named //for bean declaration
javax.inject.Inject //for injection
For JSF-based bean definitions
javax.faces.bean.SessionScoped //for bean scoping
javax.faces.bean.ManagedBean //for bean declaration
javax.faces.bean.ManagedProperty //for bean injection
EDIT: Now I understand your requirements better, use the following construct to inject a JSF managed bean
@ManagedProperty(value="#{yourBeanName}")
SessionBean yourSessionBean;
Also note that within JSF, you can inject only beans of a wider scope than their targets e.g. you can inject a @SessionScoped bean into a @RequestScoped bean and not the other way around
But since JSF managed beans are deprecated, better to use the CDI managed ones. In that case you can inject shorter scoped beans in wider scoped ones
Hello, I try that. But dont works. I import javax.faces.bean.SessionScoped with javax.faces.bean.ManagedBean. I import import javax.inject.Named with javax.inject.Named but the bean dont change the property when I set a value. Thanks.
@JuanPabloGómezUribe, you can't use @Inject for a JSF bean. @inject is only applicable to beans within the context of CDI. For beans under JSF, use @ManagedProperty. See updated answer
Hi, thanks for reply. I prove with JSF-Based bean definitions and try inject the bean SessionBean with @ManagedProperty(value="#{sessionBean}"), but this is injected as null (the bean have set and get). And use de CDI-Based and have the initial problem. Thanks.
@JuanPabloGómezUribe what's your environment(JSF version and App server)?
Hi, JSF 2.0 and GlassFish 3.1
Forget about managed beans. It won't work with a Filter that way. If you insist on using it then do it properly by follow the answer provided here:
How implement a login filter in JSF?
Now regarding CDI, if you problem is that a specific value is null and you have verified this by actually getting a NPE or so (Since for example Eclipse debugger sometimes get's it wrong). Then double check that you used correct SessionScoped like described by kolossus and also check what BalusC said (beans.xml).
A good way to see if CDI is working is to ask the manager for the bean. Put this debug code somewhere and try it:
@Inject
BeanManager manager;
@PostConstruct
private void test() {
Bean<?> bean = (Bean) manager.resolve(manager.getBeans("ANY_NAMED_BEAN_EL_NAME"));
System.out.println(bean);
}
Hi, thanks fir reply. I try with that How implement a login filter in JSF?.
If you want to. I much prefer CDI myself.
I agree with @KarlKildén.. why using JSF managed beans if we have CDI beans
| common-pile/stackexchange_filtered |
add back button to first screen of navigation controller in iOS
I know that a push segue automatically adds a back button so that the presentee can return to the presenter on click. What I want is for the back button to be available on the first UIViewController of the NavigationController (basically the only view controller in the chain that does not have a back button). How do I force add the back button?
I cannot simply add a custom image because I want the exact same chevron that comes with the iOS back button.
What are you trying to do? What should happen when the user tap the button?
Yes that doesn't make sense. You can do it adding a UINavigationItem but what's supposed to happen when they click back? Unless you add a UINavigationItem that serves as a menu or has any other functionality.
What is that button supposed to take you "back" to?
@Aaron, @LucaBartoletti if this is really a sticking point, @KonsolLabapen pointed it out: UITabBar programatically took me to DogVC, which as the leader of its Navigation thread has no back button. I want to streamline the user experience by adding a back button, which would take the user back to the caller/presenter. That's all. The big issue is I want the exact same chevron that iOS is using, and that has proven to be very difficult to get. So I figure forcing in the same back button should give me the chevron. I am free to modify the @selector after all.
The reason you can't get the exact. same. chevron. is because you're not using a navigation controller properly.
@learner did you ever figure this out?
The easiest (yet hackish) way to achieve this is probably adding a dummy view controller in the stack before the actual first one, so you will get a proper back button. Use dummy's backBarButtonItem to customize the button title if you need, and -viewWillAppear: to respond to the button being tapped.
This is a good answer. I thought about it, but was hoping for something more wholesome. +1. If I can't find better, I will use this and will customize the @selector of the back button.
I once tried to hack UINavigationController's navigation item hierarchy to achieve something similar, but it turned out really bad. Had to implement the entire thing from scratch instead. Not really worth the pain, I should say.
What I want is for the back button to be available on the first UIViewController .... How do I force add the back button
This whole thinking and logic is wrong. This is not how iOS UINavigationControllers work. You have a starting page (mainViewController) in a UINavigationControllers and from there you "move on" to something else. But you always come back to the main view controller. Just think about it, if you put a back button on the main view controller, where will the user go back to?
If you have a situation like this.
SomeViewController --> UINavigationController --> MainViewController
Once user is on SomeViewController and you take him to MainViewController which is part of UINavigationController then back button makes sense.
Just a FYI - you can easily drag and drop a UIBarButtonItem to any UINavigationController in Xcode and call it "Back". You will have to then connect that back button to another view controller.
The OP precisely says I want the exact same chevron. Unfortunately, there is "Back" for UIBarItem. There is "Rewind" which is not the image I seek. I seek the "Back" chevron.
This answer is presumptuous and learner is right in pointing to the lack of imagination on your parts. This is indeed a simple question and an explanation for what learner wants to do is irrelevant here. Still I can think of one: UITabBar programmatically leads to the page and a back button would take the user back to the presenter.
Maybe it doesn't make sense but why can't you add a custom image? If all you want is "Back" chevron, can't you take a screenshot of this button and then put this image on your custom UIBarButtonItem?
I tried that it does not look quite the same. And apparently others have tried and it didn't work for them either.
| common-pile/stackexchange_filtered |
How to integrate Struts 2 with Hibernate and PostgreSQL
How to integrate Struts 2 with Hibernate and PostgreSQL?
hibernate.cfg.xml:
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost/jvmhubtutorial</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">password</property>
org.postgresql.Driver
jdbc:postgresql://localhost/gps
erp
1
http://stackoverflow.com/a/31557968/1654265
You can integrate Hibernate and Struts 2 via servlet context where you can share the session factory. The session factory is used to open Hibernate session and use it to perform queries to the database.
In Struts 2, there are no official plugins to integrate the Hibernate
framework. But, you can workaround with the following steps :
Register a custom ServletContextListener.
In the ServletContextListener class, initialize the Hibernate session and store it into the servlet context.
In action class, get the Hibernate session from the servlet context, and perform the Hibernate task as normal.
In Struts 2 there's unofficial plugin called Struts 2 Full Hibernate Plugin or struts2-s2hibernate that provides an integration with Hibernate. There's an example:
Struts 2 + Hibernate integration with “Full Hibernate Plugin”
Also, you can integrate Hibernate to Struts 2 with Spring. Here an examples of such integration:
Struts-Spring-Hibernate-Example
Spring – integration Spring 4, Struts 2 and Hibernate
Struts - Spring - Hibernate Integration Tutorial Part 2 (Java-Based and Annotations)
| common-pile/stackexchange_filtered |
No instance for show, in Lambda function?
This works fine in ghci:
printRobot (fight killerRobot gentleGiant)
But this throws me a "No instance for show" error, and I can't seem to see why.
threeRoundFight a b =
(\a b -> printRobot (fight a b))
This is the error:
• No instance for (Show
((((t40, t50, t50) -> t50) -> t60)
-> (((t20, t10, t60) -> ((t20, t10, t60) -> t0) -> t0)
-> (([Char], a10, a0) -> [Char]) -> t30)
-> t30))
arising from a use of ‘print’
(maybe you haven't applied a function to enough arguments?)
• In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it
Here is the necessary functions to consider:
fight aRobot defender = damage defender attack
where attack = if getHP aRobot > 10
then getAttack aRobot
else 0
printRobot aRobot = aRobot(\(n,a,h)->n ++ " attack:" ++ (show a) ++ " hp: " ++ (show h))
robot (name,attack,hp) = \message -> message (name,attack,hp)
Here are the Robots(what I put in as parameters, namely killerRobot and gentleGiant):
killerRobot = robot ("killer",25,200)
gentleGiant = robot ("Mr.Friendly", 10, 300)
Also as you can see I'm trying to make this a threeRoundFight, with the help of overwriting the robots with nested lambdas. But I can't seem to understand how to continue on from the first fight if I get it working.
Why do you here use aRboto (..)? in `printRobot?
So I can choose which robot to print? aRobot is just a variable?
Well you make it rather hard to understand by not using a datatype, but representing a fobot essentially as a function that maps a function that maps 3-tuple to something, to that something. Although that is essentially how one "stores" data in lambda calculus, it here makes things a lot more complicated.
ah, yeah I can understand that.. this is my second attempt to learn and understand haskell and the book hasn't come to datatypes yet so I just stay out of it until it says otherwise.
What book is this?
"Get programming with haskell", but I have to say that Datatypes started right after this chapter.
The line
threeRoundFight a b = (\a b -> printRobot (fight a b))
is equivalent to
threeRoundFight x y = (\a b -> printRobot (fight a b))
-- ^^^ unused variables
(If you enable warnings, GHC helps you in detecting this error)
This is not what you want. You likely want
threeRoundFight = (\a b -> printRobot (fight a b))
-- or
threeRoundFight a b = printRobot (fight a b)
Oh, that makes total sense but the first line you gave me I have already tried before. It doesn't work. I get this "Ambiguous type variable ‘a0’ arising from a use of ‘printRobot’" when I do that. And the second line I can't do because I'm working with lambdas and trying to understand what the book means by overwriting variables with nested lambdas :/. Either way your explanation helped me understand a little bit better.
@ruubel Ambiguous type variables arise when your code does not clearly specify which types to use. I'd recommend to annotate your source code, adding an explicit type signature to all the top-level functions (or at least enough of them). Often, that fixes many issues.
Yeah, I totally agree. I think it's weird that the book hasn't covered that yet. It just told me to do these exercises without them. Thank you for your help.
| common-pile/stackexchange_filtered |
react-native-navigation V2 : How to nest sideMenu inside stackView
I have an initialScreen that checks if the user has logged in before. If yes, user is navigated to the main screen and if not, the user is navigated to the signUp screen(using stack navigation).
This works fine but I am trying to use both stack and sideMenu navigation. When the user is navigated to the main screen, I want open a sideMenu when the user clicks on the sideMenu icon or swipe-to-right.
This is my Initalzing screen
import React from 'react'
import {
View,
Text,
StyleSheet,
AsyncStorage
} from 'react-native'
import { goToSignUp, goToMain } from './navigation'
import { USER_KEY } from './Config/config'
export default class Initialising extends React.Component {
async componentDidMount() {
try {
const user = await AsyncStorage.getItem(USER_KEY)
console.log('user: ', user)
if (user) {
goToMain()
} else {
goToSignUp()
}
} catch (err) {
console.log('error: ', err)
goToSignUp()
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Loading</Text>
</View>
)
}
}
const styles = StyleSheet.create({
welcome: {
fontSize: 28
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})
This is where I want to nest sideMenu inside mainScreen
import { Navigation } from 'react-native-navigation'
//if user not sign in go to signUpScreen
export const goToSignUp = () => Navigation.setRoot({
root: {
stack: {
id: 'StackId',
children: [
{
component: {
name: 'SignUpScreen',
},
},
],
}
}
});
//if user has signed in go to mainScreen
//I want to nest sideMenu in here!!
export const goToMain = () => Navigation.setRoot({
root: {
stack: {
id: 'App',
children: [
{
component: {
name: 'MainScreen',
}
}
],
}
}
})
My question is, how could I nest sideMenu inside the root navigation? Any comments or advise would be really helpful. Thanks in advance! :)
maybe createSwitchNavigator can help you out
@flix thanks but I was wondering if I could do it with react-native-navigation-V2
ahh sorry, i'm miss reading the title, i thought you are used react navigation
| common-pile/stackexchange_filtered |
look into a way to convert a string to date with python
I have a list of date with this format : "190802 (2 august2019)".
I would like to format it to "02-08-19" using datetime. Is there a fucntion to do?
Thanks
Possible duplicate of Converting string into datetime
Please post expected output of given sample along with what you have tried
from datetime import datetime;d = datetime.strptime('190802', '%y%m%') Will this work? Post your input and expected output
@Chris , thanks; The expected format is 02-08-19
If I understand your question, you have a list of string inputs and you want to format them.
from datetime import datetime
input_list = ["190802 (2 august2019)"]
for input in input_list:
date = datetime.strptime(input[:6], "%y%m%d")
formated_output = date.strftime("%d-%m-%y")
print(formated_output)
>>>'02-08-19'
| common-pile/stackexchange_filtered |
Angular momentum conservation during motorbike jump - modelling
I have now found 2 ways of describing this phenomenon and I would like to know which way is correct or better:
When the rear wheel rotates, we can take a look at the angular momentum (around the rotational axis of the rear wheel).
First way: We then take a look at the angular momentum of the rest of the motorbike (frame, person, front wheel) around the rotational axis of the rear wheel and use conservation of angular momentum to explain, why breaking lowers the front wheel.
Second way: We then take a look at the angular momentum of the whole system (frame, person, front wheel AND rear wheel) around the center of mass and use conservation of angular momentum to explain, why breaking lowers the front wheel.
The first way seems to lack an explanation of why an upright standing motorbike driver rotates less quickly than a crouched down one - clearly the rotational axis goes through the center of mass.
Thank you for your ideas.
How? If I don't consider heat dissipation or friction with air, then the system is closed? And breaking will reduce angular momentum of the wheel and increase angular momentum of the whole bike?
For a free body you need to look at net angular momentum about the center of mass, and not the wheel center. Then you see how angular momentum is conserved (when heat/friction/drag is ignored). When braking ang. momenum transfers from the wheel to the chassis.
I was thinking during flight. While accelerating, momentum isn't conserved.
| common-pile/stackexchange_filtered |
Why is my Laravel Auth not responding as expected?
I've created a Laravel project in which I've run the following commands:
composer require laravel/ui
php artisan ui vue --auth
npm install
This sets up the controllers and a few other auth related files for the project. The second and third command are there to import vue into the project. Regardless, according to the Laravel docs, I've done what is needed to set up Auth for the project. To verify this, check out: https://laravel.com/docs/7.x/authentication
For some reason, after I serve up the app locally and try to either register a user or login a user, I get the following errors:
register:
Illuminate\Contracts\Container\BindingResolutionException
Target class [Auth\RegisterController] does not exist.
login:
Illuminate\Contracts\Container\BindingResolutionException
Target class [Auth\LoginController] does not exist.
Any thoughts? I can assure you that the class RegisterController.php does exist.
Here's the photo example:
Did you clear Laravel cache? And composer dump-autoload -o ?
well it should be App\Http\Controllers\Auth\RegisterController and App\Http\Controllers\Auth\LoginController ... Auth::routes() is in web.php? ... its almost like the auth routes were registered in a group that doesn't declare a namespace
this would make me assume you are using Laravel 8, not Laravel 7; in Laravel 8 your routes are not in a group with a namespace defined by default (in a fresh install)
https://stackoverflow.com/a/63807793/2109233
You're using Laravel 8, so make sure you're looking at the documentation for Laravel 8. Your question specifies you were looking at the docs for Laravel 7.
| common-pile/stackexchange_filtered |
how to join 3 tables, topic, comment and user
I have 3 tables, tbl_topic, tbl_comment, tbl_user.
I want to select all the topics created by the user and also the topics that he commented on even if he is not the creator. Here is my database:
tbl_topic
----------
topic_id
topic_title
user_id
tbl_comment
----------
comment_id
comment_message
user_id
topic_id
tbl_user
----------
user_id
user_name
Need it so badly. Thanks!
So far i got this
select * from tbl_topic T inner join tbl_comment C on T.topic_id = C.topic_id inner join tbl_user U on T.user_id = U.user_id GROUP BY T.topic_id
My problem is it only returns the topics that has comments on it. I want to include the topics created by the user even if it has 0 comments.
I want the result to be like this:
+-----------+-----------+----------+-------------+----------------+----------+-------
| topic_id | topic_title | user_id | comment_id | comment_message | user_id | topic_id |
+-----------+-----------+----------+-------------+----------------+----------+--------
| 1 | my topic | 1 | 1 | comment me | 1 | 1
| 2 | others | 2 | 2 | comment me | 1 | 2
| 3 | my nocoment| 1 | NULL | NULL | NULL | NULL
+-----------+---------+--------+-------------+----------+----------+---------+--------
----------+-----------+
user_id | user_name |
-----------+-----------
1 | me |
2 | someone |
1 | me
-----------+---------+--
I messed up with my fields in my tables, the user_id beside comment_message should be comment_user_id but i already created my database that way. Can you help make this possible?
Better paste what you have tried already..!
You are referring to the activities done by the user am I right?
if that's the case you have to use left outer join for comments, then UNION for the activities.
The query below uses UNION in the subquery. The first SELECT gets all topics created by user. The second SELECT statement gets all comments of the user and joins it to table tbl_topic so we can get the topic_title.
SELECT topic_ID, topic_title
FROM
(
SELECT a.user_ID, b.topic_ID, b.topic_title
FROM tbl_user a
INNER JOIN tbl_topic b
ON a.user_ID = b.user_ID
UNION
SELECT a.user_ID, c.topic_ID, c.topic_title
FROM tbl_user a
INNER JOIN tbl_comment b
ON a.user_ID = b.user_ID
INNER JOIN tbl_topic c
ON b.topic_ID = c.topic_ID
) x
WHERE x.user_ID = ?
Sir, see the update? What if the user has a post and with no comment? I think you have to use outer join for that.
@BlackHatShadow that's the reason why i'm using UNION. This can also be done using outer join but still need a subquery.
@BlackHatShadow as i've read the question select all the topics created by the user and also the topics that he commented on even if he is not the creator -- didn't say post that needs comment.
I got it, so the 1st subquery will determine the post and the 2nd subquery will determine the comments done by the user.
Thank you @J W! This works just fine. I forgot the union thing. Thank you so much.
@J W, one problem, i need to display the creator of the topic and also its comments. The problem with your script is that it only reads 1 user_id, so when I echo the username, only 1 user is appearing.
can you give sample record with your desired result in tablular format just like this question?
I mean all the topics echoes the same creator, my problem is even if the user is not the creator, it should appear when he commented on it. In my query above, this is not a problem and my only problem to that is it doesn't echo topics that has zero comments. please update. Thanks
there is a little misunderstanding here. Do you want to get the topics created and commented on a specific user? As you can see there are two queries being unioned above. the first select statement gets all topics created by the user (whether it has comments or not). On the second query, table tbl_user is linked to tbl_comment to get all the topics commented and joined it with tbl_topic to get the title of the topic. So what is the problem here?
i just want to echo the topic along with its creator. When I use your script, It only echoes 1 user, which is the value of x.user_id. Try it.
can you give sample records? how can I try if i have no records available?
Try the query below. This will show all the fields.
SELECT tt.*, tc.*, tbl_user.*
FROM tbl_topic AS tt INNER JOIN tbl_comment AS tc ON tt.topic_id = tc.topic_id INNER JOIN tbl_user as tc ON tc.user_id = tu.user_id;
WHERE tu.user_id = x
If you have to filter add to the WHERE clause to the query.
don't forget to add a WHERE user_id = x :)
Go with a left join. But there is still a Problem left, you will only get ONE table-comment and ONE user. To get more, you can use the GROUP_CONCAT function, like here: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
select * from tbl_topic T
LEFT JOIN tbl_comment C on T.topic_id = C.topic_id
LEFT join tbl_user U on T.user_id = U.user_id
WHERE T.user_id = x
GROUP BY T.topic_id
EDIT: the where clause was missing
how will this satisfy the problem? this will return all topics available whether the user has created or not.
| common-pile/stackexchange_filtered |
The link changes, but the contents don't change. What should I do?
I don't know what the problem is. No matter how hard I look, I can't see the problem. Please help me! I used React-router. The address of the link points to where I want to go, but the content inside is not what I wanted. The screen of "OpenChats" (the text that appears to be "오픈채팅") shows the same screen as the screen of "Chat" (the text that appears to be "채팅"). I want each screen to appear. The link is different, but why does the same screen appear? The content inside is different.
Openchat Data file
import React from "react";
import OpenChatPresenter from "./OpenChatPresenter";
-import image file-
const OpenChatContainer = () => {
const title = {
title: [
"보더대마왕-보더콜리견주모임...",
"경기도 보더콜리 모임 (타견종가···",
"이름/27/지역/강아지이름",
],
};
const image = {
src: [User, Open],
};
const content = {
message: [
"동영상을 보냈습니다.",
"반갑습니다",
"대화 중인 오픈채팅방이 없습니다.",
],
};
const time = {
time: ["오후 11:01", "오전 11:29", "오후 06:36"],
};
const icons = {
bell: [Bell, Bell, ""],
};
const member = {
num: [78, 19, ""],
};
return (
<OpenChatPresenter
title={title}
image={image}
content={content}
time={time}
icons={icons}
member={member}
/>
);
};
export default OpenChatContainer;
Openchat Presenter file
import React from "react";
import styled from "styled-components";
import ChatHeader from "../../Components/ChatHeader";
const OpenChatPresenter = ({ title, image, content, time, icons, member }) => {
console.log(OpenChatPresenter);
return (
<Wrapper>
<ChatHeader />
{Object.values(title.title).map((title, i) => {
return (
<Profile>
<div style={{ marginRight: "5px" }}>{title}</div>
<span>{member.num[i]}</span>
<img src={icons.pin[i]} alt="" />
<img src={icons.bell[i]} alt="" />
<ChatTime>{time.time[i]}</ChatTime>
</Profile>
);
})}
</Wrapper>
);
};
export default OpenChatPresenter;
Chat files are similar to open chat files, but they are slightly different. However, the difference does not appear on the screen.
Chat presenter file
import React from "react";
import styled from "styled-components";
import ChatHeader from "../../Components/ChatHeader";
import Ad from "../../Assets/images/ad.jpg";
const ChatsPresenter = ({ title, content, time, image, icons, member }) => {
return (
<Wrapper>
<ChatHeader />
<AdContainer>
<img src={Ad} alt="" />
</AdContainer>
{Object.values(title.title).map((title, i) => {
return (
<Profile>
<div style={{ display: "flex" }}>
<ProfileImg src={image.src[i]} />
<div>
<MeChatContainer>
<div style={{ marginRight: "5px" }}>{title}</div>
<span>{member.num[i]}</span>
<img src={icons.pin[i]} alt="" />
<img src={icons.bell[i]} alt="" />
</MeChatContainer>
<MeChat>{content.message[i]}</MeChat>
</div>
</div>
<ChatTime>{time.time[i]}</ChatTime>
</Profile>
);
})}
</Wrapper>
);
};
export default ChatsPresenter;
Chat data file
import React from "react";
import ChatsPresenter from "./ChatPresenter";
-import image file-
const ChatContainer = () => {
const title = {
title: ["MEMO", "김은진", "단톡방"],
};
const image = {
src: [Me, User],
};
const content = {
message: ["나와의 채팅", "안녕 보리야", "오늘 애견운동장 가고싶다!"],
};
const time = {
time: ["어제", "오후 12:03", "오후 04:36"],
};
const icons = {
pin: [Pin, "", Bell],
bell: [Bell, "", ""],
};
const member = {
num: ["", "", 6],
};
return (
<>
<ChatsPresenter
title={title}
content={content}
time={time}
image={image}
icons={icons}
member={member}
/>
</>
);
};
export default ChatContainer;
Router file
import React from "react";
import {
HashRouter as Router,
Route,
Switch,
Redirect,
} from "react-router-dom";
import Navgation from "../Components/Navgation";
import StatusBar from "../Components/StatusBar";
import Friends from "../Screens/Friends";
import Chats from "../Screens/Chats";
import News from "../Screens/Shap/News";
import More from "../Screens/More";
import Setting from "../Screens/Setting";
import OpenChat from "../Screens/OpenChat";
import Covid19 from "../Screens/Shap/Covid19";
import KakaoTV from "../Screens/Shap/KakaoTV";
import Entertain from "../Screens/Shap/Entertain";
import Fun from "../Screens/Shap/Fun";
import Sports from "../Screens/Shap/Sports";
const Routers = () => {
return (
<Router>
<StatusBar />
<Switch>
<Route path="/" exact component={Friends} />
<Route path="/chats">
<Switch>
<Route path="/chats" component={Chats} />
<Route path="/chats/openchats" component={OpenChat} />
</Switch>
</Route>
<Route path="/shap">
<Switch>
<Route path="/shap/covid19" component={Covid19} />
<Route path="/shap" component={News} />
<Route path="/shap/kakaotv" component={KakaoTV} />
<Route path="/shap/fun" component={Fun} />
<Route path="/shap/entertain" component={Entertain} />
<Route path="/shap/sports" component={Sports} />
</Switch>
</Route>
<Route path="/more" component={More} />
<Route path="/setting" component={Setting} />
<Redirect from="*" to="/" />
</Switch>
<Navgation />
</Router>
);
};
export default Routers;
First image is file list
Second image is Screen image
the issue is at your switch route. React-router-dom will pick the first Route that has a path that satisfies desired path /chats/openchats, but not necessary an exact match. /chats satisfies the condition, because any /chats/something contains /chats.
you can overcome this by passing a exact prop to your Route component. this way you are explicitly stating that it must be an exact match to this route be picked:
<Switch>
<Route path="/chats" component={Chats} exact />
<Route path="/chats/openchats" component={OpenChat} />
</Switch>
| common-pile/stackexchange_filtered |
Accessing Vuex state object property from component
I'm trying to change value of a state object property from a component but I can't find the proper way to do it
Here is my state:
state: {
articles: [ {
title: "Lorem ipsum",
position: 7
}, {
title: "Lorem ipsum",
position: 8
}
]
}
In the computed property of the component :
return this.$store.state.articles.filter((article) => {
return (article.title).match(this.search); /// just a search field, don't mind it
});
I would like to change every article.position under 10 to article.position = +'0'article.position.
I tried :
let articlesList = this.$store.state.articles
if(articlesList.position < 10) {
articlesList.position = +'0'articlesList.position
}
I know this is not the good way to do it but this is all I have. Any tips? :)
you should change the state only with mutations. (https://vuex.vuejs.org/guide/mutations.html) then you can call the mutaion with store.commit('ajustPosition')
Thank you for your help. How should I access to the state.articles.position in the mutation?
You should put all Vuex state change code into the Vuex store itself, via a mutation or an action. Mutations are for synchronous data changes that will update all reactive components. Actions are for asynchronous events, such as persisting state changes to the server.
So, when the change occurs, it should call a method on your component, which should in turn call the appropriate mutation or action on the Vuex store.
You don't give your full code, but here is a hypothetical example:
(Edited to reflect question about accessing data from within the mutation method.)
Template:
<input type="text" name="position" :value="article.position" @input="updatePosition">
Method on Component:
methods: {
updatePosition(e) {
this.$store.commit('changeArticleOrder', article.position, e.target.value)
}
}
Mutation on Vuex Store:
mutations: {
changeArticleOrder(state, oldPosition, newPosition) {
for (var i = 0; i < 10; i++) {
state.articles[i].position = i + 1;
/* Or do whatever it is you want to do with your positioning. */
}
}
Thank you for your help. I just want to change all the article.position when they are < 10, without an event. I get them from an API in an action, and I should use a mutation to change the data. How can I access the state.articles.position in a mutation?
First argument of mutation is a state object, that should be used to mutate state. More in Vuex documentation
| common-pile/stackexchange_filtered |
THREE.js, BufferGeometry, array.length / itemSize != numItems?
Take a look at the example http://mrdoob.github.com/three.js/examples/webgl_buffergeometry_particles.html
The way the positions buffer is setup is as follows:
var particles = 500000;
var geometry = new THREE.BufferGeometry();
geometry.attributes = {
position: {
itemSize: 3,
array: new Float32Array( particles * 3 ),
numItems: particles * 3
},
Should it not always be the case that, if T = geometry.attributes.position, then T.array.length / T.itemSize === T.numItems? If the array has a length of L slots, and each item occupies K slots, it would stand to reason there are L / K items. Yet it seems the example sattes the array has L items? L items would occupy L * K slots :s
I hit this issue with positions as well, and only the first 1/3rd of my vertices were being rendered, because I used the number of vertices as numItems, and itemSize = 3, with a Float32Array of length numItems * itemSize.
What am I misunderstanding?
Thanks!
You are not misunderstanding anything. The nomenclature could be improved.
Think of it this way:
itemSize = (number of components) / vertex
numItems = (number of components)
= (number of vertices) * itemSize
Think of numItems as the number of items in the array sent to the GPU.
three.js r.57
Wouldn't .numItems always be === array.length, then? (So redundant)
It is a little confusing. Just follow the pattern in the examples.
| common-pile/stackexchange_filtered |
skype: symbol lookup error: skype: undefined symbol:
I am using Ubuntu 12.04 32 bit, skype used to work, but suddenly it stopped. Now when I try to execute through terminal I am getting this error:
skype: symbol lookup error: skype: undefined symbol:
I tried all these solutions:
"skype: symbol lookup error: skype: undefined symbol"
Unable to launch Skype in Ubuntu 13.10 64bit - Symbol Lookup Error
but nothing worked. Here's the output of ldd /usr/bin/skype | grep Qt:
libQtDBus.so.4 => /usr/local/qt_lib/libQtDBus.so.4 (0xb581f000)
libQtWebKit.so.4 => /usr/local/qt_lib/libQtWebKit.so.4 (0xb44bf000)
libQtXml.so.4 => /usr/local/qt_lib/libQtXml.so.4 (0xb4474000)
libQtGui.so.4 => /usr/local/qt_lib/libQtGui.so.4 (0xb391b000)
libQtNetwork.so.4 => /usr/local/qt_lib/libQtNetwork.so.4 (0xb37cd000)
libQtCore.so.4 => /usr/local/qt_lib/libQtCore.so.4 (0xb34f9000)
Content of /usr/share/applications/skype.desktop:
[Desktop Entry]
Name=Skype
Comment=Skype Internet Telephony
ec=env PULSE_LATENCY_MSEC=30 LD_LIBRARY_PATH=/usr/local/qt_lib/ skype %U
Icon=skype.png
Terminal=false
Type=Application
Encoding=UTF-8
Categories=Network;Application;
MimeType=x-scheme-handler/skype;
X-KDE-Protocols=skype
EDIT:
Full error:
skype: symbol lookup error: skype: undefined symbol:
_ZN19QAbstractProxyModel11setItemDataERK11QModelIndexRK4QMapIi8QVariantE
dpkg --status skype
OUTPUT:
Package: skype
Status: install ok installed
Priority: extra
Section: partner/net
Installed-Size: 61
Maintainer: Steve Langasek<EMAIL_ADDRESS>Architecture: i386
Version: <IP_ADDRESS>-0ubuntu<IP_ADDRESS>
Depends: skype-bin
Conffiles:
/etc/dbus-1/system.d/skype.conf d09fd2adb2487dbaaeb97c43f6cdc08d obsolete
Description: client for Skype VOIP and instant messaging service
Skype is software that enables the world's conversations. Millions of
individuals and businesses use Skype to make free video and voice calls,
send instant messages and share files with other Skype users. Every day,
people also use Skype to make low-cost calls to landlines and mobiles.
.
* Make free Skype-to-Skype calls to anyone else, anywhere in the world.
* Call to landlines and mobiles at great rates.
* Group chat with up to 200 people or conference call with up to 25 others.
* Free to download.
Homepage: http://www.skype.com
Can you provide the full error message? It would be helpful to know, which symbol is undefined. How did you install Skype? What's the output of dpkg --status skype?
It's generally assumed Skype uses the version of Qt that comes with Ubuntu, not your locally-compiled version of Qt (although it should still run with a newer version of Qt). Instead of env PULSE_LATENCY_MSEC=30 LD_LIBRARY_PATH=/usr/local/qt_lib/ skype %U, try env PULSE_LATENCY_MSEC=30 LD_LIBRARY_PATH=/usr/lib/i386-linux-gnu/ skype %U.
| common-pile/stackexchange_filtered |
Accessing property that is filled by an AsyncTask returns null
I am trying to get values from my User class (holding all the user information for the logged in user.
It is set once logged in, and it is printing out in the log just fine, but then when calling from the class that instantiates it, it returns a null? Here is the code:
public ApiConnector api;
public String ID;
public String USERNAME = null;
public String NAME = null;
public String LASTNAME = null;
public String PASSWORD = null;
public String EMAIL = null;
public User(String id) {
this.ID = id;
this.api = new ApiConnector();
new GetUserDataClass().execute(api);
}
private class GetUserDataClass extends AsyncTask<ApiConnector,Boolean,JSONArray> {
@Override
protected JSONArray doInBackground(ApiConnector... params) {
return params[0].getAllUserData(ID);
}
@Override
protected void onPostExecute(JSONArray jsonArray) {
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = null;
try {
json = new JSONObject();
json = jsonArray.getJSONObject(i);
if(!json.getString("username").isEmpty()) {
setUsername(json.getString("username"));
Log.d("username", getUsername());
}
if(!json.getString("firstname").isEmpty()) {
setName(json.getString("firstname"));
Log.d("name", getName());
}
if(!json.getString("lastname").isEmpty()) {
setLastName(json.getString("lastname"));
Log.d("lastname", getLastName());
}
if(!json.getString("email").isEmpty()) {
setEmail(json.getString("email"));
Log.d("email", getEmail());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
Log.d("hey", "hey");
}
}
The logcat output is:
05-19 02:03:55.996: W/EGL_emulation(4367): eglSurfaceAttrib not implemented
05-19 02:03:55.996: D/username(4367): Me
05-19 02:03:55.996: D/name(4367): Me
05-19 02:03:55.996: D/lastname(4367): Mememe
05-19 02:03:55.996: D/email(4367<EMAIL_ADDRESS>
I have all appropriate getters and setters in the class (as you can see in the above code, working fine.
Here is the Menu class (that is returning the null):
public class Menu extends Activity {
private String ID;
private User user;
public TextView tvusername;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
init();
}
public void init() {
Bundle bundle = getIntent().getExtras();
ID = bundle.getString("id");
user = new User(ID);
tvusername = (TextView) findViewById(R.id.tvUsername);
tvusername.setText(ID + " " + user.getEmail());
}
}
Here is what it looks like on the emulator:
I have spent the last day and a half looking for solutions, but came up empty. Please would you help?
could You Show us what Your method getEmail() is doing?
create a pojo classes and pass the Class object and try.. i hope that mite solve your problem
it is returning the email, as shown in the logcat as it is instantiated
@RajeshM what is a pojo class?
class with private variable and public get() set() methods
i,e:
'public class MyBean {
private String someProperty;
public String getSomeProperty() {
return someProperty;
}
public void setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
}'
@RajeshM thats what the user class is though?
you have to store that class object somewhere..and call the object ..
your creating a new User Class object which contains null ..
your are not using the old class object which u assigned all the details ..
Let us continue this discussion in chat.
you can use
new GetUserDataClass().execute(api).get();
so that system will wait to complete AsyncTask. and you will get the id.
If for some reason the network operation takes too long : you will have an "Activity Not Responding" crash with this solution. Additionally : the UI will be unresponsive during the whole network operation.
This does not work, I had to surround with a try and catch as well.
You are loading user data in an AsyncTask... and that's good because it seems to perform some network operation.
It means that user data loading is performed asynchronously... and so not available immediately.
You have a callback onPostExecute in the AsyncTask : use it to update the UI with something like this code :
//you need to initialize it in the AsyncTask constrtuctor
final Activity myActivity;
@Override
protected void onPostExecute(JSONArray jsonArray) {
//json parsing code
//...
//and finally update the UI
new Handler(Looper.getMainLooper()).post(
new Runnable(){
public void run(){
TextView tvusername = (TextView) myActivity.findViewById(R.id.tvUsername);
tvusername.setText(ID + " " + getEmail());
}
}
);
}
It gives me the following error: Handler cannot be resolved as a type
import android.os.Handler and you also need to pass the Activity to your AsyncTask so that you can call findViewById (I will edit my post)
but I need to be able to user User.getName(); etc throughut the app, now just onPostExecute()
You can't. As explained : the user data is not immediately available, so you must take care of that in your application code.
Just like in PHP, I cam creating a class to hold all the data to refer to at a later stage. I am setting variables in the User class and should be able to call those variables from another class, just like the methods, they return the variables that are set in the class, so I should be able to do that.
Yes, you can read the variables from your instance as soon as they are set. If you try to read the variables before they are inialized: you will only read null values. That's what I mean when I say that your application must take care of the fact that you never know when user-data is there (except AFTER clean execution of the onPostExecute). Please read this : http://developer.android.com/reference/android/os/AsyncTask.html
I think you forgot to use static word in User class object creation while setting data.
other wise it will create new instance every time and that object will not show your data.
I solved it by using the Singleton Design Pattern in my User class. Just so people can look that up to solve this if they are having the same issues!
Cheers and thanks for all the replies!
Why down vote? it is a method to solve it? and I am the poster of the question?
| common-pile/stackexchange_filtered |
Looking up a deactivated widget's ancestor is unsafe) flutter
this is my splash screen and I provide the future method to navigate automatically to another screen,
class SplashScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
Provider.of<DataBaseProvider>(context).getAllEmployees();
Future.delayed(Duration(seconds: 2)).then((value) {
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => ListViewEmployees()));
});
return Scaffold(
body: Container(
child: Center(
child: GestureDetector(
onTap: (){
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => ListViewEmployees()));
},
child: Text(
'Hello!' ,
style: TextStyle(
color: Colors.deepPurple ,
fontSize: 18 ,
),
),
),
),
),
);
}
}
and this is the error message
E/flutter ( 8699): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/flutter ( 8699): At this point the state of the widget's element tree is no longer stable.
E/flutter ( 8699): To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
E/flutter ( 8699): #0 Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> (package:flutter/src/widgets/framework.dart:3825:9)
E/flutter ( 8699): #1 _Closure.call (dart:core-patch/function.dart)
E/flutter ( 8699): #2 Element._debugCheckStateIsActiveForAncestorLookup (package:flutter/src/widgets/framework.dart:3839:6)
E/flutter ( 8699): #3 Element.findAncestorStateOfType (package:flutter/src/widgets/framework.dart:3958:12)
E/flutter ( 8699): #4 Navigator.of (package:flutter/src/widgets/navigator.dart:2185:40)
E/flutter ( 8699): #5 SplashScreen.build.<anonymous closure> (package:gsg_sqlitedb/ui/splash_screen.dart:12:17)
E/flutter ( 8699): #6 _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter ( 8699): #7 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 8699): #8 _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
E/flutter ( 8699): #9 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
E/flutter ( 8699): #10 Future._propagateToListeners (dart:async/future_impl.dart:725:32)
E/flutter ( 8699): #11 Future._complete (dart:async/future_impl.dart:519:7)
E/flutter ( 8699): #12 new Future.delayed.<anonymous closure> (dart:async/future.dart:322:16)
E/flutter ( 8699): #13 _rootRun (dart:async/zone.dart:1182:47)
E/flutter ( 8699): #14 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 8699): #15 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter ( 8699): #16 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter ( 8699): #17 _rootRun (dart:async/zone.dart:1190:13)
E/flutter ( 8699): #18 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 8699): #19 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
E/flutter ( 8699): #20 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter ( 8699): #21 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
E/flutter ( 8699): #22 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
E/flutter ( 8699): #23 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
when I delete future delayed, and make the navigate by a button click, the error disappear
SOLVED !!!!!! here
Test breaks when using Future.delayed
Solved https://stackoverflow.com/questions/54021267/test-breaks-when-using-future-delayed
Does this answer your question? Test breaks when using Future.delayed
@WasAsh You should add the answer as a reply to the question and accept it.
The reason for this error is that you're trying to Navigate to a page while the current screen is still being rendered. Future.delayed() can be potentially used as it provides a delay while the current screen is being built. What happens when the screen being built is still not finished and Future.delayed() is that the workaround causes issues.
Another workaround is setting a fixed Timer
Timer(const Duration(seconds: 4), () {
// Navigate to next screen
});
It's still best to avoid automatically navigating to a next screen if possible.
| common-pile/stackexchange_filtered |
Adding a second html page in a Create React App project
I've been developing an embeddable widget using CreateReactApp. It works great when initialised from the index.html
Now I want to test what happens when the user changes page in the html. Ill need to save the app's state in storage etc.
When I add a second html page to the public folder (two.html) and navigate to it - I get the error:
URI Error: Failed to decode param '/%PUBLIC_URL%/favicon.ico'
..and the app js does not run.
How can update my app so I can use a second html page?
The issue maybe caused due to babel not able to transpile the % .
Please try updating this in index.html :
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
to this:
<link rel="icon" href="/public/favicon.ico" />
| common-pile/stackexchange_filtered |
Map Literals to Object Properties/Values
For eg, my input XML is look like this.
<root>
<myelemt>
<input type="variable">
<variable>STARTDATE</variable>
<variable>CUSTOMERNAME</variable>
</input>
</myelemt>
</root>
it is deserialized and loaded into the object MyXmlElemtObj
in my code i have written like this,
if(MyXmlElemtObj.input.variable.ToUpper() == "STARTDATE")
ProcessObjectB(ObjectA.OrderDate);
if(MyXmlElemtObj.input.variable.ToUpper() == "CUSTOMERNAME")
ProcessObjectB(ObjectC.UserName);
Here I am mapping those input literals to some objects value.
The one thing that scares me is seeing some ** hard-coded literals** all over my code.
Instead i would like to write something like ProcessObjectB(Common.GetMappedvalue(MyXmlElemtObj.input.variable));
Is there a way to isolate this mapping thing to common class, where i will predefine
which literal is mapped to which values. The problem is the values are of objects created at the run time.
If my question is making sense then So how do i achieve this?
I think i have given all the necessary details. if anything is missing please metnion. Thx Much.
The question is worded a little confusing, but from what I gather you are just looking for an intermediary class to perform the mapping of an input variable to a string. You mention that you don't want there to be hard-coded string literals; The logical remedy here would be to declare a series of constants for them (perhaps at the top of your intermediary mapping class?).
public class Common
{
public const string STARTDATE = "STARTDATE";
public const string CUSTOMERNAME = "CUSTOMERNAME";
public static string GetMappedValue(string inputVariable)
{
string mappedTo = null;
switch(inputVariable)
{
case "abc":
mappedTo = SOME_OTHER_CONSTANT_HERE; //map it
break;
case "xyz":
mappedTo = FOO;
break;
//etc etc...
}
return mappedTo;
}
| common-pile/stackexchange_filtered |
Can’t access DOM elements created by `createDocumentFragment`
In my tutorial project, I fill the page with elements created using DocumentFragment. Everything happens as it should: the elements are created, drawn on the page, and displayed in the DOM. The problem is that when I try to access these elements for further work through querySelectorAll, I get an empty array. Why is this happening?
Using the tag <template>, I create and place elements in the right place for me:
var renderPicture = function(photo) {
var pictureElement = pictureTemplate.cloneNode(true);
pictureElement.querySelector('.picture__img').src = photo.url;
pictureElement.querySelector('.picture__stat--comments').textContent = photo.comments.length;
pictureElement.querySelector('.picture__stat--likes').textContent = photo.likes;
return pictureElement;
};
var fragment = document.createDocumentFragment();
for (var i = 0; i < photo.length; i++) {
fragment.appendChild(renderPicture(photo[i]));
}
picturesList.appendChild(fragment);
I refer to the created elements for further interaction:
var pictureImg = document.querySelectorAll('.picture__img');
var pictureImg = document.querySelectorAll('.picture__link');
The browser ignores the elements (even though they are present in the DOM), and returns either an empty collection (with querySelectorAll) or null (if I use querySelector):
NodeList []
length
:
0
[[Prototype]]
:
NodeList
What is the problem?
Where do you place the elements into the document? Have you inspected the elements which are supposedly in the DOM? Do they have the correct class names?
Can you provide your full code?
I place the elements in a block intended for them. The class names are correct. if I fire a click event then I can catch the target on them. But I need to work with an array of all created elements.
You need to access the DocumentFragment of the <template> before using querySelector. The fragment of a template is in the content property.
If you change this line to use the content property it should fix your issue.
pictureTemplate.content.cloneNode(true);
I changed the line as you showed and now the browser is showing an error on that line.
Uncaught TypeError: Cannot read properties of undefined (reading 'cloneNode').
I use .content when I access template via querySelector
var pictureTemplate = document.querySelector('#picture').content.querySelector('.picture__link');
| common-pile/stackexchange_filtered |
How to localize some specifics missing expressions in rails
I'm using rails_admin which use devise. Some words still displays in english. I have many yml files for i18n (fr, rails_admin.fr, devise.fr). Is there a quick way to find what yml [tree] I have to put in one of those to i18n these missing expressions ?
Devise 2.0 (which is just released) does internationalization much better, check https://github.com/plataformatec/devise under the I18n section, which also has a link to some examples. Not sure about rails_admin.
Nearly all RailsAdmin keys are namespaced with :admin.
Nearly all Devise keys are namespaced with :devise.
Rest would be Rails'.
And eventually it doesn't really matter, you can add them anywhere, and I suggest you put them in a custom project file to keep your libraries' i18n easily updatable.
I post on SO not to bother you but you are everywhere ! On the signup page sign_in sign_up and forgot_your_password? are not localized...How can I guess since they are not grouped with email and password which are indented under activerecords-user
I get it. You are supposed to override templates, there is no i18n in Devise's views: https://github.com/plataformatec/devise/blob/master/app/views/devise/sessions/new.html.erb
| common-pile/stackexchange_filtered |
retrieve data from a thread in python
I have a thread in python which handled receive OSC packets...
I need to retrieve datas from osc in my main function. How could get data from thread out of the thread ?
Here's the code to demonstrate my issue:
TRY WIH CLASS, BUT STILL "DATA IS NOT DEFINED
import OSC
import threading
import atexit
#------OSC Server-------------------------------------#
receive_address = '<IP_ADDRESS>', 7402
# OSC Server. there are three different types of server.
s = OSC.ThreadingOSCServer(receive_address)
# this registers a 'default' handler (for unmatched messages)
s.addDefaultHandlers()
class receive:
def printing_handler(addr, tags, data, source):
if addr=='/data':
self.data=data.pop(0)
s.addMsgHandler("/data", printing_handler)
return data
def main(self):
# Start OSCServer
#Main function...I need to retrieve 'data' from the OSC THREAD here
print "Starting OSCServer"
st = threading.Thread(target=s.serve_forever)
st.start()
reception=receive()
reception.main()
plouf = data.reception()
print plouf
thanks in advance
Do you mean you want to use content of parameter data from function printing_handler in function main?
Change plouf = data.reception() to plouf = reception.data
thanks Thomas !
Now It gives me this error: receive instance has no attribute 'data'
I'm keeping searching
Your code is very screwed up. Change def printing_handler(addr, tags, data, source) to def printing_handler(self, addr, tags, data, source), or make it a static method. Also, rename the main function to __init__, and remove the reception.main() call. You never actually call the printing_handler() function, so there's no data to retrieve. That's why you're getting an error.
thanks...my issue is that printing_handler() is never evoked because it owns in a thread...Thanks anyway !!
Use a Queue from the standard library, or use Global variables.
Friends don't let friends use Global variables in python :-)
Although they're bad practice, in very small multithreaded scripts (such as the OP's), they work nicely.
ok but..class with self.handled seem more complex and I'm still stuck
:-(
| common-pile/stackexchange_filtered |
Syntax for nested IF statements in SPARQL
I'm trying to run the following SPARQL query, but it keeps returning SR171: Transaction timed out.
SELECT ?isBusAvailable WHERE {
SELECT DISTINCT IF (
(
SELECT ?value2 WHERE {
GRAPH data: { ?obsValueID2 ontology:value ?value2 }
GRAPH data: { ?obsValueID2 rdf:label "Availability" }
GRAPH data: { ?obsValueID2 ontology:isObservedValueOf ?obsID2}
GRAPH data: { ?obsID2 ssn:observationResultTime ?time2 }
GRAPH data: { ?obsID2 ssn:observedBy ?id2 }
GRAPH meta: { ?id2 rdf:label "MyBusService" }
} ORDER BY DESC (?time2) LIMIT 1) > 1, "Take Bus", (
SELECT ?isBikeAvailable WHERE {
SELECT DISTINCT IF (
(
SELECT ?value3 WHERE {
GRAPH data: { ?obsValueID3 ontology:value ?value3 }
GRAPH data: { ?obsValueID3 rdf:label "Availability" }
GRAPH data: { ?obsValueID3 ontology:isObservedValueOf ?obsID3}
GRAPH data: { ?obsID3 ssn:observationResultTime ?time3 }
GRAPH data: { ?obsID3 ssn:observedBy ?id3 }
GRAPH meta: { ?id3 rdf:label "MyBikeService" }
} ORDER BY DESC (?time3) LIMIT 1
) > 0, "Take Bike", "Take Taxi") as ?isBikeAvailable WHERE { ?1 ?2 ?3}})) as ?isBusAvailable WHERE { ?4 ?5 ?6}}
If I run them individually, it runs in under 1 second. The following example works.
SELECT ?isBusAvailable WHERE {
SELECT DISTINCT IF (
(
SELECT ?value2 WHERE {
GRAPH data: { ?obsValueID2 ontology:value ?value2 }
GRAPH data: { ?obsValueID2 rdf:label "Availability" }
GRAPH data: { ?obsValueID2 ontology:isObservedValueOf ?obsID2}
GRAPH data: { ?obsID2 ssn:observationResultTime ?time2 }
GRAPH data: { ?obsID2 ssn:observedBy ?id2 }
GRAPH meta: { ?id2 rdf:label "MyBusService" }
} ORDER BY DESC (?time2) LIMIT 1) > 1, "Take Bus", 'Take Bike') as ?isBusAvailable WHERE { ?4 ?5 ?6}}
If the result from the first query is true, return 'Take Bus'; else, run the second query, and return either 'Take Bike' or 'Take Taxi'.
Apparently the problem is with the second query (from the false condition on the first query). After "Take Bus", if I change the second query to "Take Bike", it works.
According to sparql.org's query validator, this (regardless of how long it takes to execute) isn't a legal SPARQL query. The same probably applies to the answer you posted. Have you considered rephasing the query a bit?
That is correct. The syntax of the query posted in this question is incorrect. That is my question is all about. The query from the answer I posted works. Can you please let me know what do you mean by "rephasing"? Also, please improve the answer I posted.
My point was that the syntax in your answer, even if some SPARQL engine accepts it, is not legal SPARQL syntax either. E.g., select distinct if( ... ) isn't legal SPARQL. By rephrase, I meant that you should consider restructuring your SPARQL query so that it's legal. Once it's legal, we can help in making it more performant. Also, it would help if you can tell us what the query is trying to accomplish, and what the data is like. It looks like the query could be written more simply, but it's hard to say, since we don't know what it's supposed to do.
I have two services: BusService and BikeService. The query is trying to retrieve the "Available" property of the bus. If a bus is available, it will return "Take Bus". If the bus is not available, check to see if there are any bikes available. If there are bikes available return "Take Bike", otherwise return "Take Taxi". Basically, I have 2 graphs. One is with the metadata (i.e., meta:) of services and the other one contains the data (i.e., data: in the example) produced by the services. It picks the id of the service from the meta and checks the last reading in the data graph.
Given the service name, and the property which I'm interested in (e.g., Availability), I want to retrieve the last reading for that service. Based on the values returned, I want to take some decisions, as described above.
@andrei -- I think your ?isBusAvailable confuses matters -- given the literal values you return in the end, this might be better ?travelMethod.
As I read things, the question here was really how to properly construct the nested IFs -- and the title of the question should perhaps be "What is correct syntax for nesting IF statements in SPARQL?"
In simple flow, I think what you're doing is checking for an available bus, and returning "Take bus" if such exists; if not, you check for an available bike, and return "Take bike" if that exists; if not, you return "Take taxi". In psuedo-code, IF AVAIL bus, THEN take bus, ELSE ( IF AVAIL bike, THEN take bike, ELSE take taxi ).
@joshua-taylor was right about one thing — SELECT DISTINCT IF (…) isn't strictly valid, but the fix is just an extra paren wrapper -- e.g., the following is valid (and validates) --
SELECT DISTINCT ( IF ( ( 1 = 1 )
, "true"
, "false"
) AS ?test )
WHERE { ?x ?y ?z }
LIMIT 1
But fixing this in your query doesn't get any better output from the validator. In fact, replacing the inner (SELECT ?value … LIMIT 1) queries with 1 makes the whole large query validate --
SELECT ?travelMethod
WHERE
{
SELECT DISTINCT
( IF
(
(
1 > 0
)
, "Take Bus"
, (
IF (
(
1 > 0
)
, "Take Bike"
, "Take Taxi"
)
)
) AS ?travelMethod
)
FROM data:
WHERE { ?1 ?2 ?3 }
}
-- and those inner (SELECT ?value … LIMIT 1) queries validate on their own, too --
SELECT ?value
WHERE
{
GRAPH data: { ?obsValueID ontology:value ?value }
GRAPH data: { ?obsValueID rdf:label "Availability" }
GRAPH data: { ?obsValueID ontology:isObservedValueOf ?obsID }
GRAPH data: { ?obsID ssn:observationResultTime ?time }
GRAPH data: { ?obsID ssn:observedBy ?id }
GRAPH meta: { ?id rdf:label "MyBusService" }
}
ORDER BY DESC (?time)
LIMIT 1
I believe the following is valid syntax -- even though the sparql.org validator chokes on it -- but I can't be sure it executes because I don't have time to rejigger the query to run against a random endpoint and data set. If you rework the query to run against, say, DBpedia, you could help the next person!
SELECT ?travelMethod
WHERE
{
SELECT DISTINCT
( IF
(
(
( SELECT ?value
WHERE
{
GRAPH data: { ?obsValueID ontology:value ?value }
GRAPH data: { ?obsValueID rdf:label "Availability" }
GRAPH data: { ?obsValueID ontology:isObservedValueOf ?obsID }
GRAPH data: { ?obsID ssn:observationResultTime ?time }
GRAPH data: { ?obsID ssn:observedBy ?id }
GRAPH meta: { ?id rdf:label "MyBusService" }
}
ORDER BY DESC (?time)
LIMIT 1
) > 0
)
, "Take Bus"
, (
IF (
(
( SELECT ?value
WHERE
{
GRAPH data: { ?obsValueID ontology:value ?value }
GRAPH data: { ?obsValueID rdf:label "Availability" }
GRAPH data: { ?obsValueID ontology:isObservedValueOf ?obsID }
GRAPH data: { ?obsID ssn:observationResultTime ?time }
GRAPH data: { ?obsID ssn:observedBy ?id }
GRAPH meta: { ?id rdf:label "MyBikeService" }
}
ORDER BY DESC (?time)
LIMIT 1
) > 0
)
, "Take Bike"
, "Take Taxi"
)
)
) AS ?travelMethod
)
FROM data:
WHERE { ?1 ?2 ?3 }
}
Having spent a little time away from it, and re-reading what you said about your data in the comments above, I can refine this query further, which may also make it execute faster --
SELECT ?travelMethod
WHERE
{
SELECT DISTINCT
( IF
(
(
( SELECT ?value
WHERE
{
GRAPH data: { ?obsValueID ontology:value ?value
; rdf:label "Availability"
; ontology:isObservedValueOf ?obsID
. ?obsID ssn:observationResultTime ?time
; ssn:observedBy ?id
}
GRAPH meta: { ?id rdf:label "MyBusService" }
}
ORDER BY DESC (?time)
LIMIT 1
) > 0
)
, "Take Bus"
, (
IF (
(
( SELECT ?value
WHERE
{
GRAPH data: { ?obsValueID ontology:value ?value
; rdf:label "Availability"
; ontology:isObservedValueOf ?obsID
. ?obsID ssn:observationResultTime ?time
; ssn:observedBy ?id
}
GRAPH meta: { ?id rdf:label "MyBikeService" }
}
ORDER BY DESC (?time)
LIMIT 1
) > 0
)
, "Take Bike"
, "Take Taxi"
)
)
) AS ?travelMethod
)
FROM data:
WHERE { ?1 ?2 ?3 }
}
How is this different from my answer?
While yours may be successfully executed by some endpoints, it's not valid SPARQL, so that success is a bit of a gamble. Also, I detailed more of what's going on -- what I changed and why. I hoped to make it clearer with my extra whitespace. Trimming those spaces and line feeds, your query starts SELECT ?isBusAvailable WHERE { SELECT DISTINCT IF ( ( SELECT ?value WHERE while mine is SELECT ?travelMethod WHERE { SELECT DISTINCT ( IF ( ( ( SELECT ?value WHERE -- and the parentheses I added (one before the IF and one before the second SELECT) are required by SPARQL 1.1 syntax.
I tested this query and it works. Again the only difference from my answer is the wrapping the if statement into parantheses. Also, adding the semicolons and the dot makes the query not very intuitive a newbie in sparql. Can you explain in your answer why do you think this will run faster? Also, I assume that the semicolon is used to avoid repetion, but what it is the purpose of the dot before "?obsID" ?
I replaced 5 sentences with 2 — one with 2 predicates about ?obsID and one with 3 predicates about obsValueID. In more detail — where you had 5 references to the data: graph, each a separate quad wrapped in { }, I made these a single reference to the data: graph with 5 triples. This may speed things (depending on the processing engine) because the engine may load/process this graph once instead of 5 times. Within that, the semicolon is just syntactic sugar which decreases query string length (when the padding whitespace is removed). The dot was implied by the } it replaced.
Also note that there was a second parenthetical wrapping I added -- the complete "test" expression in the IF construction gets wrapped in parens -- IF ( ( test1 = test2 ) , "true" , "false" ). You had IF ( ( SELECT ?value … LIMIT 1 ) > 0 , "Take Bike" , "Take Taxi" ). I have IF ( ( ( SELECT ?value … LIMIT 1 ) > 0 ) , "Take Bike" , "Take Taxi" ). I know these are hard to see; I hope my indentation and padding helps.
The query in the false condition needs to respect the format of IF conditional statement from SPARQL since it returns a value. Remove the "SELECT DISTINCT"
SELECT ?isBusAvailable WHERE {
SELECT DISTINCT (IF(
(
SELECT ?value WHERE {
GRAPH data: { ?obsValueID ontology:value ?value }
GRAPH data: { ?obsValueID rdf:label "Availability" }
GRAPH data: { ?obsValueID ontology:isObservedValueOf ?obsID}
GRAPH data: { ?obsID ssn:observationResultTime ?time }
GRAPH data: { ?obsID ssn:observedBy ?id }
GRAPH meta: { ?id rdf:label "MyBusService" }
} ORDER BY DESC (?time) LIMIT 1) > 0,'Take Bus', (
IF (
(
SELECT ?value WHERE {
GRAPH data: { ?obsValueID ontology:value ?value }
GRAPH data: { ?obsValueID rdf:label "Availability" }
GRAPH data: { ?obsValueID ontology:isObservedValueOf ?obsID}
GRAPH data: { ?obsID ssn:observationResultTime ?time }
GRAPH data: { ?obsID ssn:observedBy ?id }
GRAPH meta: { ?id rdf:label "MyBikeService" }
} ORDER BY DESC (?time) LIMIT 1
) > 0, "Take Bike", "Take Taxi")
)) AS ?isBusAvailable) FROM data: WHERE { ?1 ?2 ?3 }}
EDIT: select distinct if( ... ) isn't legal SPARQL, so the if statement needs to be wrapped into parentheses. The query becomes: select distinct (if( ... ))
I don't understand the notation you've put before this query... and further cannot tell whether this is meant as an answer to your original question, or as a followup. If a followup, better to edit the question to include this information, hopefully expressed more clearly (and then to delete this answer).
This is my answer, and the query that worked. I used http://virtuoso.openlinksw.com/dataspace/doc/dav/wiki/Main/VOSSPARQL
| common-pile/stackexchange_filtered |
Convert C++ to Python (For Loop multiple assignment)
Convert to python:
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
for (int i = 0, j = i + 3; i < 100; ++i, j= i+3)
cout << i << " j: " << j << endl;
getchar();
return 0;
}
I try:
for i in range(99):
j = i + 3
print i, " j: ", j
How to make it one for loop?
I mean I want to make the python program only 2 lines like the C++ reall tis
Like 0ne python FOR LOOP to do the same job the C++ for l00p d03s
It already looks like one loop to me. How many do you see?
Wow, if this use-case was any more real world, it would be the actual REAL WORLD
The C++ is way more than two lines. And the idea that code is better because there are fewer lines is misguided.
If you add another copy of the j = i + 3 line into your python code, it'll look more like your C++ code. You should note that your C++ code is two lines, but 87 characters, while your python code is three lines, but only 57, and it doesn't repeat itself.
Just change 99 to 100
for i in range(100):
j = i + 3
print i, " j: ", j
Or
for i,j in [(i, i+3) for i in range(100)]:
@jleedev: Your post was not there when I was typing. So why a downvote?
I would use a generator expression instead of a list comprehension there, were I to do it this way.
These are identical except for the upper bound in the loop (98 vs 99). What is the question?
On one line (but please don't do this):
for i,j in [(i, i+3) for i in range(100)]:
Since j is always dependent on the value of i you may as well replace all instances of j with i + 3.
I dont get it, it is exactly one python for loop there. What is the question? Do you want the j declaration inside the loop declaration like in c++? Check Prasson'S answer for the closest python equivalent. But why have a j variable in the first place? j=i+3 seems to always be true, so why not this?
for i in range(100):
print i, " j: ", i+3
for (i,j) in zip(range(100), range(3, 100+3)):
for i in range(100):
j = i + 3
print i, "j:", j
raw_input()
C++: http://ideone.com/7Kdmk
Python: http://ideone.com/nATEP
| common-pile/stackexchange_filtered |
Solana RPC Endpoint (metaplex.devnet.rpcpool.com) returns 403 Forbidden - Alternative solutions?
I'm developing an application using Solana's devnet and trying to connect to the RPC endpoint https://metaplex.devnet.rpcpool.com/. However, I'm consistently getting a 403 Forbidden error.
Here are the details:
RPC Endpoint: https://metaplex.devnet.rpcpool.com/
Network: Solana devnet
Error: 403 Forbidden
My current configuration and error:
azzurri@Hihi:~/studihub-nfts$ solana config get
Config File: /home/azzurri/.config/solana/cli/config.yml
RPC URL: https://metaplex.devnet.rpcpool.com/
WebSocket URL: wss://metaplex.devnet.rpcpool.com/ (computed)
Keypair Path: /home/azzurri/studihub-nfts/Owner.json
Commitment: confirmed
azzurri@Hihi:~/studihub-nfts$ solana airdrop 2 /home/azzurri/studihub-nfts/Owner.json
Requesting airdrop of 2 SOL
Error: RPC request error: cluster version query failed: HTTP status client error (403 Forbidden) for url (https://metaplex.devnet.rpcpool.com/)
azzurri@Hihi:~/studihub-nfts$
I've tried the following:
Double-checking my connection parameters
Waiting and retrying after some time in case it was a temporary issue
Checking for any official announcements about changes to the endpoint's access policy
Questions:
Is anyone else experiencing this issue with this specific RPC endpoint?
Are there any known requirements or authentication needed for this endpoint that I might be missing?
Can you suggest alternative RPC endpoints for Solana devnet that are reliable and accessible?
If this endpoint is no longer publicly available, what are the recommended best practices for selecting an RPC endpoint for Solana devnet development?
Is there a way to troubleshoot or bypass this 403 error when using the Solana CLI?
Any insights or solutions would be greatly appreciated. Thank you in advance for your help!
Please have a look at the [tour] and [ask]. Questions on StackOverflow should focus on one programming-related question at the time
This is not a public endpoint anymore, therefore you are receiving that 403 error.
You could use free tiers of paid rpc providers like extrnode, quicknode etc.
| common-pile/stackexchange_filtered |
What URL is needed to be sent in the Cloudrail AdvancedRequestSpecification to get the LinkedIn Experience or Education profile sections?
I implemented the Login with LinkedIn Social Sample, and successfully got back the Id, Name, Email, Gender, PictureUrl, Description and BirthDate using the Github Cloudrail-Xamarin example.
The documentation suggests to use the AdvancedRequestSpecification feature to request the “Education” or “Experience” sections of the LinkedIn profile. But only gives a dropbox example.
What URL is needed to be sent in the AdvancedRequestSpecification(“url goes here”) to get the “Education” or “Experience” sections of the LinkedIn profile?
As far as I know, it should be the same URL but you need to apply for the "Apply with LinkedIn program" to get the full response. Here is a list of all the available fields: https://developer.linkedin.com/docs/fields
| common-pile/stackexchange_filtered |
Drupal Non-Admin Toolbar
Is there a module I can add a Toolbar on top of the page, like Admin Toolbar but for Authenticated users ? Simple Menu sorta worked, but had way too many bugs. Anything else?
There is Administration menu module.
You can turn on the permissions for authenticated users, the panel will only show those links that you approved for authenticated users too. There is also a built-in module called Dashboard that you need to check for authenticated users.
So you turn on these two, and you check those (under Node in permissions) that you want to approve for authenticated users.
Hope that helps.
Ya I use that module right now for administrator account. The issue is I need different menu items on the toolbar. Can I put different menus on the administrator toolbar then on the built in toolbar?
| common-pile/stackexchange_filtered |
XCode bundle identifier formatting from {PRODUCT_NAME}
Assume I have an iPhone application whose Product Name is "My App" (with a space between words) in XCode build settings. In my info.plist, the Bundle identifier is specified as com.mycompany.${PRODUCT_NAME:rfc1034identifier}
In the resulting info.plist in the application bundle, the bundle identifier is shown as com.mycompany.My-App. I need it to be com.mycompany.MyApp. How do I change the Bundle Identifier setting so it would convert the product name the way I want?
ps.
If I change the ${PRODUCT_NAME:rfc1034identifier} to ${PRODUCT_NAME:identifier}, the resulting bundle identifier will be com.mycompany.My_App. I just need to remove the space character in the product name completely in the result.
Just type it in?
i.e. instead of com.mycompany.${PRODUCT_NAME:rfc1034identifier} just type com.mycompany.MyApp
If you have more than one target that need different bundle names, one way of doing it is to create your own variable and use that instead.
In the build menu (select your project and choose Get Info), you can add your own variables to the project. If you make one called MY_BUNDLE_NAME and set it to MyApp, you can then put com.mycompany.${MY_BUNDLE_NAME} in the plist file. You should be able to set MY_BUNDLE_NAME to different values for different targets.
Thanks for ur answer, but my situation is not as simple as that!
Of course u have understood my question, but what I haven't told is that I have several "targets" of the same application that needs to have different bundle identifiers. So I need to configure the bundle identifier dynamically according to the build settings each of these targets have.
for example, one target may have "My App1" as the product name and another target may have "My App2" as the product name. That's why I need to do this dynamically instead of hard coding.
Ah, that makes more sense! I've edited my answer; hope that's more helpful!
Thanks dean! that would do it for me and I can see that these user-defined build settings will be useful for me in some other places as well. Thanks for the tip!
Extending that idea and depending on how many targets you've got, you could consider using schemes + build configurations and build scripts allowing you to have only a single target, everything configured dynamically. Just a tip :)
same bundle id should be on xcode and itunnes:
in this file
$ touch Info.plist
Bundle Identifier (App ID Suffix)
Enter a unique identifier for your App ID. The recommended practice is to use a reverse-domain name style string for the Bundle Identifier portion of the App ID.
Example: com.domainname.appname
The accepted answer hasn't worked for me correctly. It seemed to change the bundle identifier however it messed up the whole app. In my case this solution worked fine:
Change bundle identifier in Xcode when submitting my first app in IOS
| common-pile/stackexchange_filtered |
How do I allow the Documents library in an Office 365 Group site allow ASPX pages to be viewed?
If I upload an ASPX file to the documents library in a regular SharePoint site, it renders properly when a user clicks on the file.
If I do the same for an ASPX file uploaded to the documents library in a SharePoint site that backs an Office 365 Group, the ASPX file is not rendered, but downloaded instead. Is there any way to get SharePoint to render ASPX files?
Additional information:
Setting the "Default open behavior for browser-enabled documents" in the advanced library settings to "open in the browser" does not help.
A SharePoint site behind an Office 365 group has a Pages library that obviously allows ASPX files. I am unable to upload to that library via the browser, but I suspect I could do this via code. I wonder if there is some specific setting on the document library that turns on this behavior. If so, I couldn't find it.
I am aware of permissive file handling and that the default value for this does not allow rendering of HTML files. However, this does not appear to affect ASPX files. Interestingly, I am now unable to perform a set-spotenant -PermissiveBrowserFileHandlingOverride $true in my test tenant. I get back a message indicating that "Permissive browser file handling setting is deprecated and can't be enabled."
Wondering if you found any workarounds, facing the same issue with onedrive online ..
I don't think I looked into the answer from Zach below. Maybe that would help. If it does, please respond here. I don't recall what I ended up doing :-S.
Custom scripts are likely disabled on the group site. By default, scripts are not enabled on sites that are created by non administrators (groups are generally considered self service sites). One of the side effects on having this feature enabled is the inability to upload files like .aspx. The tenant admin can disable this using the SharePoint Online PowerShell.
Set-SPOSite <url> -DenyAddAndCustomizePages 0
Allow or prevent custom scripts article
AS i remember, this is only possible through ghost pages in the SP Farm on Prem, as ghost pages are not available on SP 365 i think this is not possible anymore
It works in O365 if the site is not within an Office 365 group.
| common-pile/stackexchange_filtered |
What are the pros and cons of learning English from movies and radio?
I dedicate one to two hours each day to learning English. I'm focusing on listening and speaking (and improving my accent, of course). I want to know what the pros and cons are of learning English from movies and television (usually U.S. series such as 24, Lost, Prison Break etc.) and radio (on stitcher.com and other online stations).
Sorry, I'm voting to close. This is an interesting question by itself, but there is no definitive answer to it, only various opinions, which may only lead to a discussion. Maybe try using the chat and ask people there.
Pros:
You'll learn pronunciation and accent.
You'll pick up slang and and vernacular.
Cons:
You'll learn Hollywood/fit-for-broadcast pronunciation and accent.
You won't pick up real-life everyday slang and vernacular.
You won't learn spelling or formal written rules or grammar.
I definitely recommend watching and listening to English TV, films, radio, podcasts and even music from a wide range of sources as part of learning a language, although of course it shouldn't be the only method.
Actually I am considering to follow an internet radio of English to listen at work when I free. It must be a suitable to understand accent for student of English. Do you know a radio channel I have mentioned? Thanks
You could try BBC Radio 4, it has a varied selection of mostly spoken content.
Thanks for your suggestion. Now I am listening the channel. Its English accent but I can listen.
| common-pile/stackexchange_filtered |
CrossEntropyLoss loss function type problem
I am trying to solve a classification problem but something is not working for me in the code.
I have a network that receives 30 inputs and outputs 4 actions.
Each action can receive an integer value from 0 to 4 (that is, receive a number between 0 and 4, a total of 5 options \ 5 classes)
I tried to implement this code but something is not working properly. I'm sure I have a problem with the dimensions
Would appreciate help !! :)
This is my code:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
# Load data from CSV file
file_path = '/content/30_1_output.csv'
df = pd.read_csv(file_path)
# Extract features and target outputs
X = df.iloc[:, :-4].values # Assuming the last 4 columns are the target outputs
Y = df.iloc[:, -4:].values # Extracting the last 4 columns as target outputs
# Map the values according to the specified mapping
Y = np.where(Y == -2, 0, # If value is -2, map it to 1
np.where(Y == -1, 1, # If value is -1, map it to 2
np.where(Y == 0, 2, # If value is 0, map it to 3
np.where(Y == 1, 3, # If value is 1, map it to 4
np.where(Y == 2, 4, Y) # If value is 2, map it to 5
)
)
)
)
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
# Convert to PyTorch tensors
X_train_tensor = torch.tensor(X_train, dtype=torch.float32)
y_train_tensor = torch.tensor(y_train, dtype=torch.long)
X_test_tensor = torch.tensor(X_test, dtype=torch.float32)
y_test_tensor = torch.tensor(y_test, dtype=torch.long)
# Create datasets and dataloaders
train_dataset = TensorDataset(X_train_tensor, y_train_tensor)
test_dataset = TensorDataset(X_test_tensor, y_test_tensor)
# Adjust the batch sizes in DataLoader to match the batch size of the model outputs
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)
# Define the neural network model
class NeuralNetwork(nn.Module):
def __init__(self, input_size, num_actions):
super(NeuralNetwork, self).__init__()
self.layer1 = nn.Linear(input_size, 64*2)
self.relu = nn.ReLU()
self.layer2 = nn.Linear(64*2, 32*2)
self.output_layer = nn.Linear(32*2, num_actions * 5) # 5 probabilities for each action
def forward(self, x):
out = self.layer1(x)
out = self.relu(out)
out = self.layer2(out)
out = self.relu(out)
out = self.output_layer(out)
out = torch.softmax(out.view(-1, 5), dim=1) # Reshape output and apply softmax
return out
# Initialize the model
input_size = X.shape[1] # Number of input features
num_actions = Y.shape[1] # Number of actions
model = NeuralNetwork(input_size, num_actions)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Training loop
num_epochs = 30
for epoch in range(num_epochs):
total_loss = 0
for inputs, labels in train_loader:
# Forward pass
outputs = model(inputs)
# Reshape outputs back to [batch_size, num_actions, 5]
outputs = outputs.view(-1, num_actions, 5)
# Take argmax along the last dimension to get the index of the class with the highest probability
#outputs2 = torch.argmax(outputs, dim=2)
#labels = labels.view(-1)
loss = criterion(outputs, labels)
# Backward pass and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item()
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {total_loss / len(train_loader):.4f}')
print("Training complete")
and this is the shape of the output and the labels:
enter image description here
Thank you so much!!
this is the error I get:
RuntimeError: Expected target size [64, 5], got [64, 4]
The label data Y is 4 columns:
Y = df.iloc[:, -4:].values # Extracting the last 4 columns as target outputs
whereas the model is outputting 5 columns:
out = torch.softmax(out.view(-1, 5), dim=1) # Reshape output and apply softmax
There needs to be a matching number of columns between Y and the model's prediction, otherwise they can't be directly compared and the loss can't be computed.
Either drop the redundant column from the model to make it exactly align with Y, or add the required column to Y to match model's output. The columns need to match in size and meaning, so you need to establish what the missing column represents, and where it should go.
If the data has 5 classes, and a sample can only be one of those at a time, then you can discard a class and represent the data using 4 classes (when all 4 classes are zero, it implies the 5th class). Alternatively, if you have 4 classes to begin with for a 5-class problem, you can append an extra/redundant column that explicitly flags the 5th class.
| common-pile/stackexchange_filtered |
How to get old input array in blade laravel
I have some code like this
<div class="form-group">
<label for="tag">Tag</label><br>
<input type="text" data-role="tagsinput"
class="form-control form-control-lg @error('tag') is-invalid @enderror"
id="tag" name="tag[]" value="{{old('tag')}}" placeholder="Enter tag">
@error('tag') <div class="text-danger"> {{ $message }} </div> @enderror
</div>
how to get old value array in laravel blade, in this case i want to get old value of tag?
Do you have multiple inputs with name=tag[] ?
https://laracasts.com/discuss/channels/laravel/input-old-and-array
i have multiple value
Roman pointed you in the right direction. Good luck!
However, I think what you mean is you have one input field, and you use that to have many tags, right?
use dot notation with index
as suggested here https://laracasts.com/discuss/channels/laravel/input-old-and-array
<input type="text" data-role="tagsinput"
class="form-control form-control-lg @error('tag') is-invalid @enderror"
id="tag" name="tag[]" value="{{old('tag.0')}}" placeholder="Enter tag">
...
<input type="text" data-role="tagsinput"
class="form-control form-control-lg @error('tag') is-invalid @enderror"
id="tag" name="tag[]" value="{{old('tag.1')}}" placeholder="Enter tag">
@roman can u help me with this question https://stackoverflow.com/questions/58990038/laravel-filter-reset-after-next-page-click-in-paginate
I think the better solution for this is to do it with javascript if you have one input so you need to store the array in javascript variable then just add the value to the input.
<select name="groups[]" class="multi-default" id="groups" placeholder="Groups" multiple>
<option value="" placeholder>Groups</option>
@foreach ($groups as $group)
<option value="{{ $group->id }}" title="{{ $group->id }}"
{{is_array(old('groups',$groups??[]))&&in_array($group->id,old('groups',$group_data??[]))?'selected':null}}</option>
@endforeach
</select>
It will definitely work
@if (!is_null(old('product_highlights')))
@foreach (old('product_highlights') as $highlight)
{{$highlight}}
@endforeach
@endif
| common-pile/stackexchange_filtered |
Google geocode API returns location of motorway rather than postcode area supplied
I get the same result if I use the URL or javascript APIs.
If I pass (as an address) the location "M5" for geocoding, rather than returning the location of the M5 Postal Area (Salford, Manchester) the location returned is the centre of the M5 Motorway.
Interestingly in the old google maps (http://maps.google.co.uk) I get the same behaviour but the new google maps (same URL) returns the correct area.
Is there another way I can define the location (rather than 'address') that will be more accurate? The only other requirement is that the user may enter a town / city / county name rather than a post code so the solution needs to be flexible enough to handle this.
The geocoder (at least the javascript version) gives me Salford as the second result, are you checking all the results? Found 25 results for M5 [ 0 ]: M5, Droitwich WR9, UK (51.5157456, -2.6464826999999786) [ 1 ]: Salford M5, UK (53.4796425, -2.2810638999999355)
Same with me. And using region: 'uk' the only result is Salford M5, UK (53.4796425, -2.2810638999999355).
It seems adding the region as UK solves this problem. Strange as all the results returned were in the UK anyway but thank you for suggesting this - big help.
Did you ever get a fix for this? I've run into the same issue recently.
Possible duplicate of Incorrect results returned from a partial UK postcode
| common-pile/stackexchange_filtered |
String Format Constraint On PostgreSQL Column Not Working
I am moving a database from SQL Server to PostgreSQL and hitting some issues with a check constraint in one of the tables. PostgreSQL version is 9.5.1.
I have a table that I created with a check constraint on one of the columns to enforce format. This worked in SQL Server. The idea is that only values beginning with the letters AF and followed by three numeric characters (e.g. AF001) can be entered in one of the columns.
The SQL looked like this to create the table:
CREATE TABLE TableName (
referenceID VARCHAR(5) NOT NULL CHECK (referenceID LIKE 'AF[0-9][0-9][0-9]'),
comment VARCHAR(50) NOT NULL,
PRIMARY KEY (referenceID)
);
But when I try to enter any data it fails. Example of data entry:
INSERT INTO TableName (reference, comment) VALUES ('AF000','A comment');
The error I get is:
ERROR: new row for relation "tablename" violates check constraint "tablename_referenceID_check"
DETAIL: Failing row contains (AF000, A comment).
********** Error **********
ERROR: new row for relation "TableName" violates check constraint "tablename_referenceID_check"
SQL state: 23514
Detail: Failing row contains (AF000, A comment).
I'm assuming the issue is with the actual check constraint, but I'm unsure.
Relevant: Pattern matching with LIKE, SIMILAR TO or regular expressions in PostgreSQL
The LIKE clause does not use regular expression patterns in PostgreSQL. Instead of LIKE you should use the SIMILAR TO clause:
CREATE TABLE TableName (
referenceID VARCHAR(5) NOT NULL CHECK (referenceID SIMILAR TO 'AF[0-9]{3}'),
comment VARCHAR(50) NOT NULL,
PRIMARY KEY (referenceID)
);
| common-pile/stackexchange_filtered |
Normal Plane and Tangent Line of 2 intersected surfaces without a point
Is there a way to find the normal plane and the tangent line to the following surfaces without having a point of intersection, I know you can use Newton-Raphson method to find the approximate intersection point but, is there any way or is even possible?
$$ 1) \hspace{0.3cm} x^2 + y^2 + z^2 = 14 $$
$$ 2) \hspace{0.3cm} x + y + z = 6$$
What do you mean by tangent line? There are infinite tangent lines, as there are infinite curves on those surfaces.
I mean a point where there is a tangent line and a normal plane to both surfaces at the same time
Your question is much confused. Surfaces have normal lines and tangent planes, not vice versa. It is not at all clear what you are after. A common point to both surfaces where the normal lines and tangent planes are the same? That doesn't exist. There is a single line that is normal to both surfaces (to surface (1) twice). The tangent planes at the same points will be parallel, but not identical. There is no point where the two surfaces share a tangent plane. This can be easily seen if one recognizes what these surfaces are.
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.