source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"tridion.stackexchange",
"0000016028.txt"
] | Q:
SDL WEB 8 Save Component event couldn't be triggered
The OnComponentSave Event couldn't be triggered and no error is raised.
Below is the detailed code. The "initialized" and "event be subscribed" info can be found inside the Application log, but the "save component completed" message never is displayed. No other error or warning can be found neither. Any idea what's wrong here?
[TcmExtension("My Tridion Event System")]
public class Events : TcmExtension
{
public Events()
{
Logger.Instance.LogInfo("Initialized");
Subscribe();
}
public void Subscribe()
{
try
{
EventSystem.Subscribe<Component, SaveEventArgs>(OnComponentSaved, EventPhases.Initiated);
Logger.Instance.LogInfo("Event be subscribed");
}
catch (Exception ex)
{
Logger.Instance.LogError("Error : " + ex.Message);
throw ex;
}
}
private void OnComponentSaved(Component component, SaveEventArgs args, EventPhases phase)
{
Logger.Instance.LogInfo("Save component started");
}
}
A:
You do not say in your question that you have actually saved a component to test this. I'm going to assume that you have, but it's also possible that the server where you saved the component is not the one where you have the events system installed/configured.
This could easily happen in a scaled-out scenario.
|
[
"stackoverflow",
"0051437678.txt"
] | Q:
vuejs + d3: select returns element, but attr() returns null
I'm confused a bit, please help me to figure out a problem.
I am using VueJS + d3.js.
I have a code that looks like this:
<template>
<div class='chart-frame-chart-comp border-black-1 border-radius-1'>
<div class='plot'>
</div>
</div>
</template>
<script>
import * as d3 from 'd3'
export default {
name: 'chart-frame-chart-comp',
mounted () {
this.$nextTick(this.plot)
},
methods: {
plot () {
console.log(this.getPlotSize())
},
getPlotSize () {
let a = d3.select('.chart-frame-chart-comp .plot')
console.log('a', a)
let b = a.attr('tagName')
console.log('b', b)
return b
}
}
}
</script>
In getPlotSize I am trying to return an attribute of a selected element (the one with .plot class)
So in debugger, I see output:
Obviously, d3 managed to obtain a node (since it is the actual element, I was looking for plus selection return only one element that, again, I was looking for). But when d3 tries to return value of getAttribute, former returns null and hasAttribute returns false. But Chrome debugger sees that element has those attributes:
Obviously I'm missing something! So my question is: what am I doing wrong?
A:
This is a misconception as there is no attribute tagName on your node. What you see in your console is the tagName property of the Element you selected. At the time you are selecting the element—as shown in your second screenshot— there are two attributes, namely class and data-v-391ae376. Hence, neither .getAttribute("tagName") nor D3's .attr("tagName") will return any value.
If you are interested in the element's tagName you can simply call selection.node() to get the first element in the selection and access its tagName property afterwards. In your example this will print "div".
getPlotSize () {
let a = d3.select('.chart-frame-chart-comp .plot');
console.log('a', a);
let b = a.node().tagName; // Get the DOM node and read its tagName property
console.log('b', b);
return b;
}
|
[
"pt.stackoverflow",
"0000158943.txt"
] | Q:
Ajuda para essa query
Boa tarde Pessoal, tenho essas duas tabelas que se relacionam para saber quantas vezes um usuário acessou o sistema:
E tenho essa query:
select nome_usuario, count(id_log) as qtde from logs as l left join usuario as u on l.usuario_log = u.id_usuario group by usuario_log order by qtde desc
Hoje ele me traz o resultado de quantas vezes o usuário acessou. E gostaria que se não encontrar registros da tabela log atribua zero '0' como faço isso?
A:
Na SQL da pergunta, troque LEFT JOIN por RIGHT JOIN
select u.id_usuario, u.nome_usuario, count(l.id_log) as qtde from logs as l
right join usuario as u
on l.usuario_log = u.id_usuario
group by u.id_usuario, nome_usuario
order by qtde desc
|
[
"stackoverflow",
"0021035485.txt"
] | Q:
input and my array are baffling me
To save time, and what something I must be clearly passing over I am going to post my whole code. This is a console application I was sending a friend who is starting off in C#...
The problem is, when I enter exit from the get go, it exits. But, lets say I hit enter. Then I hit A for an array. Hit 5, or 6 or whatever number. Gives me the array. Lets say I want to sort it. It sorts. But, if I hit EXIT it says no match. I do not understand this. What is going on???
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication405
{
class Program
{
static void Main(string[] args)
{
// Instantiate the delegate.
Del handler = DelegateMethod;
string _a = "";
constructor con = new constructor();
bool control = true;
while (control)
{
Console.WriteLine("Enter EXIT to end the program.");
Console.WriteLine("Press enter for options");
ConsoleKeyInfo key = Console.ReadKey();
if (key.Key.Equals(ConsoleKey.Enter))
{
Console.WriteLine("Enter C for a constructor.");
Console.WriteLine("Enter M for a method.");
Console.WriteLine("Enter A for an array.");
Console.WriteLine("Enter D for a delegate.");
}
_a = Console.ReadLine();
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program.");
control = false;
break;
case "C":
Console.WriteLine(con.a);
Console.WriteLine("Would you like to test another scenario?");
_a = Console.ReadLine();
if (_a.ToUpper() == "Y")
{
continue;
}
control = false;
break;
case "M":
metroid();
break;
case "A":
Array();
break;
case "D":
// call the delegate
handler("This is how you call a delegate. Also, Pasta noodles taste like wontons!!! =)");
break;
default:
Console.WriteLine("No match");
break;
}
}
}
public delegate void Del(string message);
public static void DelegateMethod(string message)
{
Console.WriteLine(message);
}
public class constructor
{
public string a = "This a is a constructor!";
}
static public void metroid()
{
string b = "This is a method!";
Console.WriteLine(b);
}
static public void Array()
{
int temp, k;
string ssSize = "";
try
{
Console.WriteLine("This is a random array. Please enter the size.");
string sSize = Console.ReadLine();
int arraySize = Convert.ToInt32(sSize);
int[] size = new int[arraySize];
Random rd = new Random();
Console.WriteLine();
for (int i = 0; i < arraySize; i++)
{
size[i] = rd.Next(arraySize);
Console.WriteLine(size[i].ToString());
}
Console.WriteLine("Would you like to sort this array?");
ssSize = Console.ReadLine();
if (ssSize.ToUpper() == "Y")
{
for (int i = 1; i < size.Length; i++)
{
temp = size[i];
k = i - 1;
while (k >= 0 && size[k] > temp)
{
size[k + 1] = size[k];
k--;
}
size[k + 1] = temp;
}
Console.WriteLine("\nThe sorted array is as follows: ");
for (int i = 0; i < size.Length; i++)
{
Console.WriteLine(size[i]);
}
Console.WriteLine("Note that this uses an insertion sort.");
}
else
{
Console.WriteLine("Fine! Don't sort it -- your loss!!!");
}
}
catch (System.FormatException)
{
Console.WriteLine("Not correct format, restarting array process.");
Array();
}
}
}
}
A:
This happens because when you enter EXIT after displaying the first prompt, you use Console.ReadKey() to read the first character. So the value in _a variable doesn't have e and is only xit.
Move displaying options to be at the same level as the rest and the problem will go away:
static void Main(string[] args)
{
// Instantiate the delegate.
Del handler = DelegateMethod;
string _a = "";
constructor con = new constructor();
bool control = true;
while (control)
{
Console.WriteLine("Enter EXIT to end the program.");
Console.WriteLine("Enter O for options");
_a = Console.ReadLine();
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program.");
control = false;
break;
case "O":
Console.WriteLine("Enter C for a constructor.");
Console.WriteLine("Enter M for a method.");
Console.WriteLine("Enter A for an array.");
Console.WriteLine("Enter D for a delegate.");
break;
case "C":
Console.WriteLine(con.a);
Console.WriteLine("Would you like to test another scenario?");
_a = Console.ReadLine();
if (_a.ToUpper() == "Y")
{
continue;
}
control = false;
break;
case "M":
metroid();
break;
case "A":
Array();
break;
case "D":
// call the delegate
handler("This is how you call a delegate. Also, Pasta noodles taste like wontons!!! =)");
break;
default:
Console.WriteLine("No match");
break;
}
}
}
|
[
"stackoverflow",
"0062835641.txt"
] | Q:
Python array is only 1D and I cannot use reshape to convert it to 2D
I've created two programs to run a stochastic simulation on a system of chemical reactions. In the program I've got a function that's meant to update the elements of an array with the derivative of the changing molecule numbers popul_num and the stochastic rate constant of each reaction stoch_rate In the first program the function looks as follows:
popul_num = np.array([1.0E9, 0, 0])
stoch_rate = np.array([1.0, 0.002, 0.5, 0.04])
def update_array(popul_num, stoch_rate):
"""Specific to this model
will need to change if different model
implements equaiton 24 of the Gillespie paper"""
# calcualte in seperate varaible then pass it into the array
s_derviative = stoch_rate[1]*(2*popul_num[0] -1)/2
b = np.array([[1.0, 0.0, 0.0], [s_derviative, 0.0, 0.0], [0.0, 0.5, 0.0], [0.0, 0.4, 0.0]])
return b
This function returns b which is an array of shape(4, 3)
In the next program I've added more reactions and more reactants and the function is as follows:
popul_num = np.array([1.0E5, 3.0E5, 0.0, 1.0E5, 0.0, 0.0, 0.0, 0.0])
stoch_rate = np.array([0.015, 0.00016, 0.5, 0.002, 0.002, 0.8])
def update_array(popul_num, stoch_rate):
"""Specific to this model
will need to change if different model
implements equaiton 24 of the Gillespie paper"""
s_derivative = stoch_rate[0]*popul_num[1]*((popul_num[1] - 1)/2) # derivative with respect to S is a function of X
x_derivative = stoch_rate[0]*popul_num[0]*((2*popul_num[1] - 1)/2) # derivative with respect to X is a function of S
r_derivative = stoch_rate[1]*((popul_num[3]*(popul_num[3]))/2)
r2_derivative = stoch_rate[2]*popul_num[4] # derivative with respect to R is a function of Y type = numpy.float64
y_derivative = stoch_rate[3]*popul_num[3] # derivative with respect to Y is a function of R type = numpy.float64
x2_derivative = stoch_rate[4]*((popul_num[1] - 1)/2)
b = np.array([[x_derivative, s_derivative, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0,
r_derivative, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, r2_derivative, y_derivative, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, stoch_rate[3], 0.0, 0.0, 0.0, 0.0], [x2_derivative, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, stoch_rate[5], 0.0]])
b.reshape((6,8))
print("Shape b:\n", b.shape)
return b
Only this returns an array of shape(6,) and I need it to be a 2D array of shape(6, 8) I've tried using the reshape() method but this results in the following error:
ValueError: cannot reshape array of size 6 into shape (6,8)
Which is thrown on the line where I call the reshape() command
I don't understand whats different about the second function meaning it doesn't return a 2D array?
Cheers
A:
One value is missing. This list contains only 7 values:
[x2_derivative, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
|
[
"stackoverflow",
"0057842941.txt"
] | Q:
Use typescript interface & abstract class without specifying generic types
I have created an interface & abstract class along these lines:
interface ITest<A, B> {
testFunc: (input: A) => B;
}
abstract class AClass<A, B> {
abstract testFunc: (input: A) => B;
}
I have multiple subclasses that extend AClass and multiple objects that implement ITest using various types for A and B. For example:
class SubClass1 extends AClass<number, string> {...}
class SubClass2 extends AClass<string[], boolean> {...}
For an abstract class or interface, I assumed I would be able to declare variables that could hold these types without specific generic type parameters, as I just want it to be an instance of AClass without regards to the generic types, along these lines:
let aClass: AClass; // Could hold SubClass1 or SubClass2
let iTests: ITest[];
But I receive an error saying my generic type requires two type parameters. Is the only way around this to set a default type parameter and/or declare these variables with any as their generic type argument (e.g., ITest<any, any>[])?
A:
You'd use whatever concrete types are used by what aClass and iTests refer to. If they're going to refer to different types at different times, then you'd use a union listing the types they may refer to. For instance, if aClass may need to refer to an instance of SubClass1 or an instance of SubClass2, then:
let aClass: SubClass1 | SubClass2;
any, any is the worst case where you have no idea at all what the concrete types might be.
You've said you have 10+ of these. If you really need to use a single variable that may refer to instances of any of those 10+ classes, it's probably worth defining a union type:
type AnySubClass = SubClass1 | SubClass2 | SubClass3/*...*/;
...and then using that for aClass.
|
[
"stackoverflow",
"0043538517.txt"
] | Q:
undefined reference to `func()'
I'm making some change to an existing linux c project.
In /vobs/ua/HDL/VHDL/CmdUtil/src/help.c, I define func like this:
void func(){
...
}
In file /vobs/ua/HDL/Interface/cli/src/cliSystem.C, I write this code:
extern void func();
...
void func1(){
...
func();
...
}
In file /vobs/ua/HDL/VHDL/DsnMgr/src/shell.c, I write this:
extern void func();
...
void func2(){
...
func();
...
}
In file /vobs/ua/HDL/VHDL/DsnMgr/src/shell.c, I write this:
extern void func();
...
void func2(){
...
func();
...
}
In file /vobs/ua/HDL/VHDL/lib2v/src/asicLibCells.C, I write this:
extern void func();
...
void func3(){
...
func();
...
}
I didn't declare func in any header files.
The problem is, for the call to func in vobs/ua/HDL/Interface/cli/src/cliSystem.C and /vobs/ua/HDL/VHDL/lib2v/src/asicLibCells.C, there is error
undefined reference to `func()'
But for /vobs/ua/HDL/VHDL/DsnMgr/src/shell.c, there is no error.
After I declare func in vobs/ua/HDL/Interface/cli/src/cliSystem.C and /vobs/ua/HDL/VHDL/lib2v/src/asicLibCells.C like this:
extern "C" void func();
There is no error in /vobs/ua/HDL/VHDL/lib2v/src/asicLibCells.C, but the error in vobs/ua/HDL/Interface/cli/src/cliSystem.C persists.
What's wrong? What can I do to eliminate this error?
A:
The problem is that the function func is a C function, and you try to call it from a C++ function. This is problematic because C++ does something called name mangling to allow things like function overload.
That means when you do your declaration
extern void func();
the C++ compiler will mangle the symbol and that mangled symbol will not be found.
In C++ you have to inhibit this name mangling for functions that comes from C object files. This is done with a special extern declaration:
extern "C" void func();
On a slightly related note, in C a declaration like
void func();
doesn't mean that the function takes no arguments like it does in C++. In C that declaration means that func takes an unspecified number of unspecified arguments. In C you must use void to declare a function that takes no arguments:
void func(void);
|
[
"stackoverflow",
"0005664414.txt"
] | Q:
Enabling KMZ output with gzip
When I try enable gzip for an output the following error appears:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 634, in __call__
handler.get(*groups)
File "/base/data/home/apps/my-app-ip/django2.349712625627523096/main.py", line 2246, in get
self.response.out.write(compressBuf(output))
File "/base/data/home/apps/my-app-ip/django2.349712625627523096/main.py", line 1618, in compressBuf
zfile.write(buf)
File "/base/python_runtime/python_dist/lib/python2.5/gzip.py", line 204, in write
self.crc = zlib.crc32(data, self.crc)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 1075: ordinal not in range(128)
The code I have is
def compressBuf(buf):
zbuf = StringIO.StringIO()
zfile = gzip.GzipFile(None, 'wb', 9, zbuf)
zfile.write(buf)
zfile.close()
return zbuf.getvalue()
Can you tell me what I'm doing wrong?
Thank you
A:
It looks like you need to set encoding to utf-8. See this question.
|
[
"stackoverflow",
"0029977360.txt"
] | Q:
Making an array class so they act like vectors
I have to make a class that will make arrays act like vectors. When I try and pass the class into the method into my main I get an error telling me that "[" and "]" are incorrect operators. I was wondering if I'm just completely doing this wrong or if it's just a simple mistake. Help is greatly appreciated. Here is my header file:
#ifndef PROGRAM5HEADER_H
#ifndef PROGRAM5HEADER_H
#define PROGRAM5HEADER_H
#include <string>
using namespace std;
class FloatArray
{
int *rep;
int _size;
public:
FloatArray(int sz=100):_size(sz)
{
rep=new int[sz];
}
~FloatArray()
{
delete [] rep;
}
int size() const
{
return _size;
}
FloatArray(const FloatArray& x)
{
copy(x);
}
void copy(const FloatArray& x)
{
_size == x.size();
rep=new int[_size];
for(int k=0;k<_size;k++)
rep[k]=x.rep[k];
}
};
#endif
and here is my main program
#include <iostream>
#include <string>
#include <cstdlib>
#include "program5header.h"
#include <cmath>
using namespace std;
int meanstd(FloatArray x, int& std)
{
int sx=0,sx2=0,mean;
for(int i=0;i<x.size();i++)
{
sx+=x[i];
sx2+=x[i]*x[i];
}
mean=sx/x.size();
std=sqrt(sx2/x.size()-mean*mean);
return mean;
}
int main()
{ int f;
cout<<"How big of an array would you like: "<<endl;
cin>>f;
FloatArray x(f);
}
A:
There are a lot of issues with a lot of your implementation, I'd suggest doing some research on the subject. I'll touch on a few.
Firstly, you should make your FloatArray a templated class and allow for different types other than just int.
When you initialize a FloatArray x and then try to access it's underlying array through "[]" you are actually invoking the following:
x.operator[](...)
You haven't defined the '[]' operator on your FloatArray class so you are getting an error.
You need something similar to this:
int FloatArray.operator[](int index) {
assert(index < _size);
return _rep[index]
}
Your copy isn't doing what you want, it's not copying the size over to "this". It should look something similar to this:
void copy(const FloatArray& x)
{
_size = x._size;
rep=new int[_size];
for(int k=0;k<_size;k++)
rep[k]=x.rep[k];
}
However I would suggest not having a copy method and instead implement everything in your copy constructor.
|
[
"stackoverflow",
"0053904954.txt"
] | Q:
spring boot+netflix zuul app giving java.lang.ClassNotFoundException: com.netflix.zuul.monitoring.CounterFactory
I am developing a gateway for my micro services project using spring boot + netflix zuul. The gateway connects to netflix eureka server and filters the requests. But I am not able to bring up the zuul server
I have included following maven dependencies in my spring boot project
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-zuul</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
I got following exception when starting the spring boot application
java.lang.IllegalStateException: Error processing condition on org.springframework.cloud.netflix.zuul.ZuulProxyAutoConfiguration.discoveryRouteLocator
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:64) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:108) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:181) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:141) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:117) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:327) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:232) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:275) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:95) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:691) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:528) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at com.mywork.microservices.zuul.SpringZuulApplication.main(SpringZuulApplication.java:15) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_152]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_152]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_152]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_152]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.1.RELEASE.jar:2.1.1.RELEASE]
Caused by: java.lang.IllegalStateException: Failed to introspect Class [org.springframework.cloud.netflix.zuul.ZuulServerAutoConfiguration$ZuulMetricsConfiguration] from ClassLoader [sun.misc.Launcher$AppClassLoader@15db9742]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:686) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:583) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:568) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:626) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1688) ~[na:1.8.0_152]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:721) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:662) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:630) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1518) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1023) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry.addBeanTypeForNonAliasDefinition(BeanTypeRegistry.java:195) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry.addBeanTypeForNonAliasDefinition(BeanTypeRegistry.java:159) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry.addBeanType(BeanTypeRegistry.java:152) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry.updateTypesIfNecessary(BeanTypeRegistry.java:140) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at java.util.Iterator.forEachRemaining(Iterator.java:116) ~[na:1.8.0_152]
at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry.updateTypesIfNecessary(BeanTypeRegistry.java:135) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry.getNamesForType(BeanTypeRegistry.java:97) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.collectBeanNamesForType(OnBeanCondition.java:298) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getBeanNamesForType(OnBeanCondition.java:289) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getBeanNamesForType(OnBeanCondition.java:278) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchingBeans(OnBeanCondition.java:189) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchOutcome(OnBeanCondition.java:160) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
... 22 common frames omitted
Caused by: java.lang.NoClassDefFoundError: com/netflix/zuul/monitoring/CounterFactory
at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_152]
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_152]
at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_152]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:668) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
... 44 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.netflix.zuul.monitoring.CounterFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_152]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_152]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338) ~[na:1.8.0_152]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_152]
... 48 common frames omitted
2018-12-23 20:52:56.968 WARN 2125 --- [ restartedMain] o.s.boot.SpringApplication : Unable to close ApplicationContext
java.lang.IllegalStateException: Failed to introspect Class [org.springframework.cloud.netflix.zuul.ZuulServerAutoConfiguration$ZuulMetricsConfiguration] from ClassLoader [sun.misc.Launcher$AppClassLoader@15db9742]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:686) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:583) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:568) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:626) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1688) ~[na:1.8.0_152]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:721) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:662) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:630) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1518) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:507) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:477) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:598) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:590) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBeansOfType(AbstractApplicationContext.java:1204) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.boot.SpringApplication.getExitCodeFromMappedException(SpringApplication.java:905) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.getExitCodeFromException(SpringApplication.java:891) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.handleExitCode(SpringApplication.java:877) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:826) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at com.mywork.microservices.zuul.SpringZuulApplication.main(SpringZuulApplication.java:15) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_152]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_152]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_152]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_152]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.1.RELEASE.jar:2.1.1.RELEASE]
Caused by: java.lang.NoClassDefFoundError: com/netflix/zuul/monitoring/CounterFactory
at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_152]
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_152]
at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_152]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:668) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
... 26 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.netflix.zuul.monitoring.CounterFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_152]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_152]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338) ~[na:1.8.0_152]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_152]
... 30 common frames omitted
Appreciate any help. Thanks
A:
Use the dependency
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
instead of
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-zuul</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
|
[
"mythology.stackexchange",
"0000001851.txt"
] | Q:
Is it possible to take back an oath on the River Styx?
If I swear something on the River Styx, is it possible to take it back?
A:
TLDR: No. It was the one oath that was binding, but only used by heavenly beings.
In this link,
"[Hypnos (Hypnus), the god of sleep, insists Hera seal her pledge to him by an oath on the Styx :] ‘Come then! Swear it to me on Styx' ineluctable water. With one hand take hold of the prospering earth, with the other take hold of the shining salt sea, so that all the undergods who gather about Kronos may be witnesses to us.’"
If Hera pledges to Hypnos, and Hypnos insists that it is not enough, then suggests a River Styx oath, then I would say that means it's not able to be taken back.
Also, it was the strongest oath you could make!
"And Leto sware the great oath of the gods : ‘Now hear this, Gaia (Gaea, Earth) and wide Ouranos (Uranus, Heaven) above, and dropping water of Styx, this is the stongest and most awful oath for the blessed gods.’"
Virgil says that it is the one dreadful and binding oath
"This I [Jove, Zeus] swear by the source of the inexorable river, Styx--the one dreadful and binding oath for us heaven-dwellers."
Also note that it says heaven dwellers. This means that lesser mortals can't swear on the River Styx. That does not mean that they cannot witness it, as we see in the story of Semele, or Phaethon
Semele>
"The girl [Semele]. unwittingly, asked of Jove [Zeus] a boon unnamed. ‘Choose what you will’, the god replied, `‘There's nothing I'll refuse; and should you doubt, the Power of rushing Stygia shall be my witness, the deity whom all gods hold in awe’ [and she asked him to appear before her in his full glory, a request which Zeus could not now refuse and which doomed the girl]."
Phaethon
"[Helios (Helius, the Sun) swears an oath to his son Phaethon:] ‘Well you deserve to be my son’, he said, ‘Truly your mother named your lineage; and to dispel all doubt, ask what you will that I may satisfy your heart's desire; and that dark marsh [the river Styx] by which the gods make oath, though to my eyes unknown, shall seal my troth.’ He scarce had ended when the boy declared his wish - his father's chariot for one day with licence to control the soaring steeds . . . [Helios to Phaethon:] ‘By Stygia I swore and I shall not refuse, whate'er your choice: but oh! more wisely choose!’ So Sol [Helios] warned."
|
[
"security.meta.stackexchange",
"0000000381.txt"
] | Q:
Where is the review button?
I can access review through URL directly, but cannot see any links which brings me to that part of the site. Am I blind or has it maybe got lost in the new design?
A:
Don't be surprised. There's a lot of areas on the site that are (or, at least, used to be) like that. However, this isn't one of them anymore. The "review" link should be between your badge count and the "chat" link, in the top bar of the site. Here's a shot (box and arrow added) from my screen, on Meta in Firefox 5.
A:
For anon users at the top of the page:
log in blog careers chat meta about faq
For registered users with >= 200 rep at the top of the page
Username 500 review chat meta about faq
For registered users with >= 10k rep at the top of the page:
Username 10,000 tools chat meta faq
|
[
"stackoverflow",
"0057516634.txt"
] | Q:
Mockito Spying on Class that has an internal method reference
I'm seeing a different in behaviour when spying on a service using the @Spy annotation and having Mockito create the Server verses explicitly calling the constructor.
public class MyService {
private final Supplier<String> methodBCall;
public MyService() {
methodBCall = this::methodB;
}
public void methodA() {
methodBCall.get();
}
public String methodB() {
return "methodB";
}
}
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
@Spy
private MyService myService1;
@Spy
private MyService myService2 = new MyService();
@Test
public void testSucceeds() {
myService1.methodA();
verify(myService1, times(1)).methodA();
verify(myService1, times(1)).methodB();
}
@Test
public void testFails() {
myService2.methodA();
verify(myService2, times(1)).methodA();
verify(myService2, times(1)).methodB();
}
}
The failing test fails with
Wanted but not invoked:
myService2.methodB();
-> at com.phemi.services.policy.impl.MyTest.testFails
Why do these two behave differently? What is Mockito doing to initialize myService1 that enables it to spy on methodB?
This is a simplified example, in my case to test my service properly I need to call its constructor with an argument (and so cannot use the @Spy with a default constructor). However, when I do that I cannot properly verify method calls.
A:
The spy on myService2 is only created after the object has been constructed, so having a method call in the constructor is not helpfull as it contains a method reference to the initial object (which is not the spy object).
The difference becomes more evident when you compare the implementation for both cases:
Mockito.spy(Class)
public static <T> T spy(Class<T> classToSpy) {
return MOCKITO_CORE.mock(classToSpy, withSettings()
.useConstructor()
.defaultAnswer(CALLS_REAL_METHODS));
}
Mockito.spy(Object)
public static <T> T spy(T object) {
return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()
.spiedInstance(object)
.defaultAnswer(CALLS_REAL_METHODS));
}
As you can see the first case, based on a class (which is used if no instance for @Spy was created), creates a mock first and uses the constructor on the mocked object.
In the second case the constructor is not considered instead a different instance is created.
|
[
"chemistry.stackexchange",
"0000010569.txt"
] | Q:
Natural Bond Orbital analysis: Significance of stabilization energy determined by 2nd order perturbation
PREFACE: I am no expert on this topic. My questions at the bottom may be off base. I have some experience with symmetry-adapted perturbation theory (SAPT) when it comes to analyzing intermolecular interactions. The total interaction energy of a system can be quantified in four different energy components including exchange, induction, electrostatics, and dispersion.
Natural Bond Orbital (NBO) analyses translate the complex quantum-mechanical wavefunction into a more tangible Lewis-dot-like formalism (natural Lewis structure). The introduction of the following series of equations has been largely influenced by the presentation of Weinhold and Landis (2012).
Important Terms:
Lewis-type NBOs - filled 'donor' orbitals (e.g. $\sigma_{AB}, \sigma_{CD}, \cdots$)
Non-Lewis-type NBOs - vacant 'acceptor' orbitals (e.g. $\sigma_{AB}^{\ast}, \sigma_{CD}^{\ast}, \cdots$)
Lewis and non-Lewis NBOs mix:
Consider a wavefunction, $\Psi$, comprised of two components, a known natural Lewis structure wavefunction, $\Psi^{(L)}$, and a non-Lewis correction wavefunction, $\Psi^{(NL)}$, such that
$$\Psi = \Psi^{(L)} + \Psi^{(NL)}$$
The natural Lewis structure wavefunction is simply a fictitious representation of an exact physical system where resonance effects are non-existent.
Now imagine a corresponding Hamiltonian, $\hat{\mathcal{H}}$, which can also be treated as an additive scheme with corresponding components to each piece of the wavefunction:
$$\hat{\mathcal{H}} = \hat{\mathcal{H}}^{(L)} + \hat{\mathcal{H}}^{(NL)}$$
Given these two equations and the form of the Schrödinger Equation, $\hat{\mathcal{H}}\Psi=E\Psi$, there must also exist a similar construction of the energy of the system, $E$, such that
$$E = E^{(L)} + E^{(NL)}$$
These three equations provide the foundation for a "systematic 'perturbation theory' analysis", where $\hat{\mathcal{H}}^{(L)}$ is the unperturbed Hamiltonian with a corresponding (known) eigenfunction, $\Psi^{(L)}$, and energy eigenvalue $E^{(L)}$. Note that $\Psi^{(L)}$ is not only known, but it is related to an 'idealized single reference picture' in which each Lewis-type NBO has exact double occupancy for closed shell systems.
As with Hartree-Fock, the limit of a single-reference method can be reached by an infinite expansion of a basis ($\Omega)$ in the one-electron eigenvalue equation. For the natural Lewis structure, this can be written as
$$h^{(0)} \Omega_i^{(L)} = \varepsilon_i^{(L)}\Omega_i^{(L)} \qquad \mathrm{where~~} i = 1,2,\cdots,n$$
where $\varepsilon_i^{(L)}$ are orbital energies of Lewis-type NBOs.
Because $h^{(0)}$ also contains the non-Lewis contributions such that
$$h^{(0)} \Omega_j^{(NL)} = \varepsilon_j^{(NL)}\Omega_j^{(NL)} \qquad \mathrm{where~~} j = n+1,\cdots$$
Because natural Lewis structures contain zero resonance, the donor (Lewis-type NBOs) and acceptor (non-Lewis-type NBOs) orbitals do not interact due to their orthogonal nature
$$\int \Omega_i^{(L)\ast}h^{(0)}\Omega_j^{(NL)}d\tau=0 \qquad \mathrm{for~all~~} i,j$$
However, a real-world $1e^-$ Hamiltonian operator, $F$ (i.e. Fock operator, Kohn-Sham operator, etc.), will have donor-acceptor interactions such that
$$F_{ij} = \int \Omega_i^{(L)\ast}F\Omega_j^{(NL)}d\tau\neq0$$
leading to mixing (delocalization) which connects the non-Lewis type NBOs with Lewis-type NBOs.
Second-Order Perturbative Treatment of Delocalizations
This mixing of the donor and acceptor orbitals can be treated with second-order perturbation theory. Even though $\Psi^{(L)}$ ignores interactions with non-Lewis acceptors, it contains more than 99% of the total electron density, $\rho_L$, offering a good starting point for an unperturbed wavefunction.
The mixing of donors and acceptors lead to an overall energy lowering ("stabilization"), a quantum mechanical phenomenon. Consider two interacting orbitals, as schematized below. One is doubly-occupied with a lone electron pair, $n$, and the other is an unoccupied antibonding orbital (here a $\pi^{\ast}$ orbital).
$\hskip1in$
The overlap of the lone electron pair, $n$, with the vacant antibonding orbital, $\pi^{\ast}$ causes an change in energy of the lower occupied orbital, $x$. This change in energy between the non-mixing orbital with $n$ and the mixing orbital $x$ (denoted as $\Delta E$) is referred to as 'stabilization energy' of the electron delocalization. This energy (in kcal mol$^{-1}$) is determined via the following equation:
$$\Delta E_{ij}^{(2)} = \frac{-q_i \left| F_{ij} \right|^2}{\left(\varepsilon_j^{(NL)}-\varepsilon_i^{(L)}\right)}$$
where $\varepsilon_j^{(NL)}$ is the energy of the non-Lewis NBO (i.e. $\pi^{\ast}$), $\varepsilon_i^{(L)}$ is the energy of the orbital occupied by $n$, and $q_i$ is the occupancy of the orbital ($q=2$ in the above figure). The 'stabilization energy' $\Delta E_{ij}^{(2)}$ as determined by second-order perturbation treatments is commonly abbreviated as $E(2)$.
Recap:
So we have introduced (albeit very poorly) the concept of a separable wavefunction into natural Lewis and non-Lewis type formalisms. These two states mix, allowing for delocalization of electrons, a phenomenon which leads to lower energy states. This energy lowering is commonly called 'stabilization energy'.
Physical Significance?
Unfortunately, after such an introduction, I am still at a loss as to what all of this really means. As a theoretical chemist (I'm a chemist, theoretically speaking...), I am interested in the physical significance of this type of quantity [$E(2)$]. However, I am unsure how significant this type of value truly is. Do these delocalizations (energy stabilizations) lead to an overall lower energy of the system? Would a system with more of these delocalizations be expected to lie lower in energy than a comparable system without delocalizations? Can that type of correlation be made?
I guess I just do not see any usefulness in computing these $E(2)$ values for any reason because, while it may tell you that particular donor-acceptor interactions lead to this energy lowering, it doesn't offer much more than that. What am I missing here?
TL;DR - What can I use $\mathbf{E(2)}$ values for?
A:
TL;DR: Lewis $\to$ Non-Lewis $\mathbf{E(2)}$ values have no direct physical significance, are intrinsically un-measurable, and serve only to quantify the extent to which the "real" wavefunction for a system deviates from the fictional idealized Lewis-structure wavefunction.
$E(2)$ values do, however, correlate with a variety of trends in chemical bonding and reactivity, and thus can be helpful in interpreting experimental or computational data or in highlighting potentially interesting lines of inquiry.
From a comment:
LordStryker: This approximation is largely unphysical if I recall correctly.
You do recall correctly. I'm reading Weinhold's Valency and Bonding (1st ed.) currently, and the first chapter is peppered with definitions of artificial Hamiltonians and Fock operators. For example, the first example he gives is of a Hamiltonian operator for independent (not field-averaged!) electrons:
$$
\hat h = \hat t\!_\mathrm e + \hat v_\mathrm{ne},
$$
where $\hat t\!_\mathrm e$ and $\hat v_\mathrm{ne}$ are the kinetic energy and nucleus-electron interaction operators, and the electron-electron interaction operator $\hat v_\mathrm{ee}$ is completely absent! If I'm reading the text correctly, the proper Hartree-Fock Hamiltonian is then defined in terms of $\hat h$ and a "perturbation" operator that is essentially just the missing electron-electron interaction term:
$$
\hat H^\mathrm{\small HF} = \hat h + \hat H^\mathrm{\small (pert)} \equiv \hat h + \hat v_\mathrm{ee}
$$
I don't think he actually ever uses these definitions in the course of developing the NBO methodology, but it's instructive that this is the first example he chose in defining the perturbation approach that underlies it. To the best of my ability to determine:
The core of NBO analysis is founded upon selecting non-physical, but chemically intuitive, reference states, and quantifying the extent of the departure from these fictional references that is required in order to reach the "real" wavefunction of interest.
In other words, Martin is exactly right:
This value gives you a hint on how "accurate" your Lewis structure is. The smaller it is, the better it will be described by Lewis.
Responding to a couple of the specific questions at the end of the post:
Q: Do these delocalizations (energy stabilizations) lead to an overall lower energy of the system?
Absolutely, when compared to the fictitious idealized-Lewis reference. In his 2012 book, Discovering Chemistry with Natural Bond Orbitals (the one cited at the top of the original post), Weinhold illustrates quite explicitly how coercing the wavefunction not to exploit these delocalizations leads to appreciably more-positive energies. Again, though, the calculations carried out with these delocalizations prohibited are entirely unphysical, so it's not as though a system "knows it should delocalize as much as it can to get more stable"—any real system will already intrinsically exhibit all available delocalization that provides increased energetic stability.
Q: Would a system with more of these delocalizations be expected to lie lower in energy than a comparable system without delocalizations?
Yes. This is how NBO explains the spatial patterns of, e.g., hyperconjugation. In the Wikipedia article on the topic, for example, the role of hyperconjugation in establishing the energetic favorability of the staggered conformation of ethane is discussed. Per the below figure (public domain), the staggered conformation allows electrons in a given $\ce{C-H}$ $\sigma$-bonding orbital to delocalize into the $\sigma^*$-antibonding orbital of a parallel $\ce{C-H}$ bond on the vicinal carbon:
From Valency and Bonding, p228, this favorable hyperconjugative delocalization is reflected in $E(2)$ values of greater magnitude:
Second-order perturbative estimates [$E(2)$ values] indicate that each trans-like donor-acceptor [vicinal $\sigma \to \sigma^*$] interaction stabilizes the [staggered-conformation] molecule by $\pu{2.58kcal mol^-1}$, compared with only $\pu{0.89kcal mol^-1}$ for the cis-like interactions [in the eclipsed geometry]. The smaller gauche-like stabilizations ($\pu{0.20kcal mol^-1}$ at $60^\circ$ in the staggered conformer, $\pu{0.70kcal mol^-1}$ at $120^\circ$ in the eclipsed conformer) diminish the difference somewhat, but still preserve a significant hyperconjugative advantage for the staggered conformer.
So, while it's experimentally impossible to quantitatively "measure the energy" of an ethane molecule in which hyperconjugative delocalization is forbidden to occur, the $E(2)$ values provide support for the qualitative argument of hyperconjugation as a significant element of the preference of ethane for the staggered conformation. The relative (in)stability of various chemical features found across a wide range of systems can be examined by calculating judiciously selected $E(2)$ values.
Q: So say a model dimer system has an $E(2)$ of $\pu{-10kcal mol^-1}$ for a particular intermolecular interaction and has an overall electronic binding energy of $\pu{-20kcal mol^-1}$. Does that mean that half of the binding energy is due to this $E(2)$ value? Can that type of correlation even be made? (from this comment)
I agree with tschoppi: Based on my reading, yes, I think Weinhold would make exactly this kind of argument. I am ill-equipped to discuss in detail the validity of such an argument, however—though I think that there is at least qualitative, maybe semi-quantitative, value to it.
|
[
"math.stackexchange",
"0001932200.txt"
] | Q:
Verification: Give a definition of a $G$-Set so that it may be viewed as an algebra
A $G$-Set for those who may not be familiar with the terminology is as follows:
Let $G$ be a group and $S$ be a set. $G$ acts on $S$ define by the map $\star : G \times S \to S $ where $e \star s = s$ and $g\star (h \star s) = gh \star s, \forall s \in S, g,h \in G $ and so $\langle S, \star \rangle$ is a $G$-set
An algebra is a pair $\langle A, F \rangle $ where $A$ is the universe and $F$ is the family of operations on $A$
Now I need to give a definition that presents $G$-sets as an algebra which are equivalent to the above definition of a $G$-set
I thought one such definition would be :
$\langle S, \star \rangle =\langle S, \star_{g},\star_{h} ... \rangle$ (***) where we have $\star = \{\star_{g} : g \in G\}$
$\star_{g} s = g \star s, \forall g \in G, \forall s \in S$
That is for all elements of $G$, each element becomes associated with a unary operation in the signature of (***) .
so we would have $\star_{e}s = e \star s = s, \forall s \in S$
for $\star_{g}(\star_hs) = \star_g(h \star s) = g \star (h \star s)) = hg (\star s) = \star_{gh}s$
This seems valid as we have our universe $S$ with a signature of operations and can axiomatize it by the above equations.
A:
Yes, what you describe is the standard way of describing a $G$-set as an algebra. This is for fixed $G$. You can also give equational axioms for the theory of group actions (where the group is also allowed to vary), but you have to use multi-sorted logic.
|
[
"stackoverflow",
"0052214776.txt"
] | Q:
Python - matplotlib - differences between subplot() and subplots()
I'm kind of new in coding and thus in python so this may sound quite dumb, but what are the main differences between .subplot() and .subplots() methods from matplotlib in python?
I didn't find this explanation anywhere else and after reading the documentation from https://matplotlib.org/ I inferred that with both methods you can create as many figures and plots as you want...so for me both of them seem to be quite the same thing and they just differ the way you can handle plots, axes, etc...or am I wrong?
Btw, I am using python3 in jupyter notebook if it makes any difference.
A:
From the documentation page on matplotlib.pyplot.subplots():
This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call.
That means you can use this single function to create a figure with several subplots with only one line of code. For example, the code below will return both fig which is the figure object, and axes which is a 2x3 array of axes objects which allows you to easily access each subplot:
fig, axes = plt.subplots(nrows=2, ncols=3)
In contrast, matplotlib.pyplot.subplot() creates only a single subplot axes at a specified grid position. This means it will require several lines of code to achieve the same result as matplot.pyplot.subplots() did in a single line of code above:
# first you have to make the figure
fig = plt.figure(1)
# now you have to create each subplot individually
ax1 = plt.subplot(231)
ax2 = plt.subplot(232)
ax3 = plt.subplot(233)
ax4 = plt.subplot(234)
ax5 = plt.subplot(235)
ax6 = plt.subplot(236)
The code above can be condensed with a loop, but it is still considerably more tedious to use. I'd therefore recommend you use matplotlib.pyplot.subplots() since it is more concise and easy to use.
|
[
"unix.stackexchange",
"0000393430.txt"
] | Q:
Find details of device based on dns name using ip command
When I'm retrieving the mac address of a device
I execute following command
$ arp <dnsname> | grep "HWaddress" -A1 | awk '{print $1 "" $3}' |head -2 | tail -1
this will probably print
<dnsname> <mac address>
As I've seen from the manual of arp is that it is deprecated and alternate I have is to use 'ip' command instead of arp .
A:
arp is able to take names as input and print names in output. ip uses addresses only.
If you can deal with addresses, then modifying the output is pretty easy.
$ ip neigh show to 10.0.0.1
10.0.0.1 dev wlan0 lladdr dc:fb:02:xx:xx:xx REACHABLE
$ ip neigh show to 10.0.0.1 | awk '{print $1 " " $5}'
10.0.0.1 dc:fb:02:xx:xx:xx
I just noticed that your title specifically asks about DNS names. If that's the requirement, then you'll want to translate the name in your script.
$ ip neigh show to `getent hosts <dnsname> | awk '{print $1}'` | awk '{print $1 " " $5}'
$ 10.0.0.1 dc:fb:02:xx:xx:xx
|
[
"stackoverflow",
"0056890416.txt"
] | Q:
How to format a date with formatDate on angular
I try to get this format with angular formatDate
"2019-01-01T00:00:00Z"
So I use this code
formatDate(
'2019-01-01',
'yyyy-MM-ddT00:00:00Z',
'en-US'
)
The result is 2019-01-01T00:00:00+0200
Z is replaced by the zone. There is a valid way to make the format I need ?
A:
You have to escape Z as a string or it will be treated as per this
"yyyy-MM-ddT00:00:00\'Z\'"
formatDate(
'2019-01-01',
"yyyy-MM-ddT00:00:00\'Z\'",
'en-US'
)
|
[
"stackoverflow",
"0007633395.txt"
] | Q:
How do you perform a delayed loop in Opa?
What construct exists in Opa to perform a delayed loop; for instance, executing a function every 10 seconds.
Take the chatroom tutorial - if I wanted a bot in there then how would I have it write a statement every 10 seconds to the other users?
A:
What you are looking for is the Scheduler module. In particular the: Scheduler.timer function, or Scheduler.make_timer if you need more control over your timer (like stopping or changing the interval).
|
[
"es.stackoverflow",
"0000116878.txt"
] | Q:
No me muestra Mensaje después de eliminar
Hola tengo un ligero problema intente desde echo hasta print o algun script y nada no sale mensaje despues de eliminar:
para empezar este es mi codigo de mi pagina index.php que pregunta si desea eliminar o no bueno este mensaje si sale:
<script language="javascript" type="text/javascript">
function eliminar(idc)
{
if (confirm("Realmente desea eliminar el registro?"))
{
window.location="adservereditarie.php?idc="+idc;
}
}
</script>
</head>
el mensaje que no sale es este en mi pagina adservereditarie.php despues de eliminar osea si elimina mis datos hasta ahi bien me redirecciona a la pagina inicial pero no me muestra mensaje bueno me redirecciona por el header no por el windows location:
mysqli_query($connect, "DELETE FROM colegio WHERE idcolegio=$idc");
echo "<script type=''>
alert('Los datos del colegio fueron eliminados correctamente');
window.location='index.php';
</script>";
header('location: index.php');
A:
Debería funcionar así:
mysqli_query($connect, "DELETE FROM colegio WHERE idcolegio=$idc");
echo "<script type='text/javascript'>
alert('Los datos del colegio fueron eliminados correctamente');
location = 'index.php';
</script>";
Notas:
Esta verificación no será siempre exacta. Deberías invocar a un método como affected_rows para verificar que realmente alguna fila fue afectada en la consulta. El código como lo has planteado te dirá que siempre se eliminó el registro y puede que no siempre sea así.
Tu consulta es vulnerable a la Inyección SQL. Se recomienda usar consultas preparadas con las consultas que usan variables obtenidas desde fuentes externas. No lo ignores, es un problema que atañe seriamente a la seguridad de todo tu sistema.
|
[
"stackoverflow",
"0056287852.txt"
] | Q:
XML 2 Array Markup in Text Issue
I'm struggeling with the following problem. I try to convert an xml document to an array in PHP, which is working fine so far. But I do have some special elements which contain text with markup in it. The elements looks something like this:
<section>
<name>sectionname</name>
<subsection>
<subsectionname>one</subsectionname>
<element>
<text>some text <xref>a</xref>, <xref>b</xref>, <xref>c</xref></text>
</element>
</subsection>
<subsection>
<subsectionname>two</subsectionname>
<element>
<text>some text <xref>a</xref>, <xref>b</xref>, <xref>c</xref></text>
</element>
</subsection>
</section>
I tried to work with simplexml in the first place:
$xml = simplexml_load_string($string) or die("Error: Cannot create object");
$json = json_encode($xml);
$array = json_decode($json, TRUE);
but this will return an element containing "some text , , and some more" without the content of xref. What I actually want is the whole text "some text a, b, c and some more", but I am afraid I do not know how to achieve this.
And I already gave DOMDocument a shot, but had problems with the whole thing there as it is a quite complex xml.
Any ideas how I could receive what I want?
EDIT: I've added a more complex example of the xml. As you can see I would need to traverse over sections, then subsections and in there, the elements with markup and text.
A:
The problem with SimpleXML is that it tends to group text nodes into 1 lump. To be able to get the properly split text you tend to have to use DOMDocument.
As you can see this loads the document and then uses XPath to find the Element/Text nodes ( this is just to get to the right point - you can use getElementsByTagName() if you wish). Then inside that node it again uses XPath to find all of the text nodes (using descendant::text()) which will then fetch each piece of text in sequence from <text> node in the document.
For each Text node this creates a blank $text string and adds the content to it in the loop and then displays it...
$data = '<section>
<name>sectionname</name>
<subsection>
<subsectionname>one</subsectionname>
<element>
<text>some text <xref>a</xref>, <xref>b</xref>, <xref>c</xref></text>
</element>
</subsection>
<subsection>
<subsectionname>two</subsectionname>
<element>
<text>some text <xref>a</xref>, <xref>b</xref>, <xref>c</xref>d</text>
</element>
</subsection>
</section>';
$dom = new DOMDocument();
$dom->loadXML($data);
$xp = new DOMXPath($dom);
foreach ( $xp->query("//element/text") as $element ) {
$text = '';
foreach ( $xp->query("descendant::text()", $element) as $textNode ) {
$text .= $textNode->textContent;
}
echo $text.PHP_EOL;
}
This displays (I modified the second one to help)...
some text a, b, c
some text a, b, cd
Edit:
As ThW points out, using textContent will fetch all of the text including the child nodes, so you can shorten the inner loop to
foreach ( $xp->query("//element/text") as $element ) {
echo $element->textContent.PHP_EOL;
}
|
[
"physics.stackexchange",
"0000188482.txt"
] | Q:
Braiding in 3D Space
In arXiv:1005.0583 the authors wrote that in two dimensional space the configuration space of n particles is multiply-connected and therefore the fundamental group of the configuration space is the braid group.
Further, in the case of three dimensional space and when the particles are indistinguishable, then the fundamental group is equal to the permutation group. This means that the clockwise and anticlockwise exchange of two particles is equal and therefore we have only fermions and bosons in this case.
Is there a mathematical proof that in two(three) dimensional space the fundamental group of the configuration space is braid(permutation) group? And how I can show, that in three dimension the braid group breaks down to the permutation group and why then clockwise and anticlockwise exchange of two particles is equal?
A:
Intuitively this actually is very plausible, though you have to work your intuition a bit; fix a point in configuration space, this can be seen as a single point in something that locally looks like $\Bbb R^{2n}$ or $\Bbb R^{3n}$, but it is more convenient to think of $n$ distinct points of (something that locally looks like) $\Bbb R^2$ or $\Bbb R^3$.
A path through configuration space is a collection of paths based at these points. In the case of indistinguishable particles, we may also have paths starting at one point and ending at another, as long as at each point a path starts and a path ends. The only restriction is that the paths don't intersect for any given $t$, if $t$ is the (common) parameter of the paths. If the parameter runs from 0 to 1, the paths form a subset of $\Bbb R^2\times [0,1]$ and $\Bbb R^3\times [0,1]$. Two paths (in configuration space) are homotopic if there is a homotopy between all individual paths in $\Bbb R^2$ or $\Bbb R^3$ that leaves all end points fixed. In $\Bbb R^2$ it is quite easy to see that this gives the braid group.
Now for $\Bbb R^3$: you may be aware that in $\Bbb R^4$ there are no knots: all knots are homotopic to the circle. This may seem counterintuitive because we cannot visualize it, but in reality it's utterly trivial: it is the equivalent of having a circle in the plane with a point inside, it is not possible to continuously move the point outside the circle without intersecting it. However, when you add a dimension it is clear that this is not the case. Likewise for a circle in the $x-y$-plane around the $z$-axis is $\Bbb R^4$. This can be continuously untangled. Namely, move you circle in the $x-y$-plane into the parallel plane where $z = 0$, $w = 1$, if $w$ is the fourth coordinate. Every point of the circle has $w$-coordinate equal to 1. Move it within the $w = 1$, $z = 0$ plane to some large $x$. At every moment the $w$-coordinate of every point of the circle was 1, so it never intersected the $z$-axis.
Anyway, in 3D the braid of paths lives in $\Bbb R^4$ and can be untangled. Two paths in configuration space (i.e. braids of paths in $\Bbb R^3 \times [0,1]$) are homotopic to each other exactly when they connect the same initial and final points, i.e. when they define the same permutation. Paths twisting around eachother can all be transformed continously into each other.
|
[
"stackoverflow",
"0048000895.txt"
] | Q:
How can I use LokiJs in the browser?
I suspect this is a bit of a simple question, as I'm not very experienced with the frontend.
I'm trying to use lokijs as a datastore in a browser app, but I can't get it to run. I have <script src="lib/lokijs/src/loki-angular.js"></script> in my html, and
var db = new loki('test');
var users = db.addCollection('users');
users.insert({
name: 'joe'
});
console.log(users.data);
in my js as a trivial test. However, I'm getting the error Uncaught ReferenceError: loki is not defined. Please let me know where' I'm going wrong, and I apologize if this is something stupid!
A:
You are not far off. You mention you are referencing loki-angular.js in your html, however you should be referencing lib/lokijs/build/lokijs.min.js or even reference it from a cdn if you don't want to involve npm, I know cdnjs has it.
With that your example should run just fine.
|
[
"stackoverflow",
"0009490381.txt"
] | Q:
netlogo in java
I need to create a large library to determine turtles' behaviour and need an interface to show the results after they completed their behaviours. Is it possible to run Netlogo in Netbeans ? If possible , does it create problems after a while such as limited reaching to codes ,slows down or anything else?
A:
Actually, you can use the "HeadlessWorkspace" functionality to run NetLogo programs from within a Java program (or unit test). So, using this, you can definitely step through responses from a model within a NetBeans debugging session (e.g. querying reporters).
Please see the following page for the projects' description of this functionality:
https://github.com/NetLogo/NetLogo/wiki/Controlling-API
|
[
"stackoverflow",
"0045487483.txt"
] | Q:
Cordova application is showing 'old' package name in the plugins android.json file
I am running Cordova 5.x and have installed the camera plugins,
"installed_plugins": {
"cordova-plugin-whitelist": {
"PACKAGE_NAME": "com.mytechnologies.abc"
},
"cordova-plugin-camera": {
"PACKAGE_NAME": "com.mytechnologies.abc"
}
},
Although I should be expecting to see the package name that is currently within the config.xml (which is as follows)
com.mytechnologies.abc
Any suggestions why I am seeing my 'old' platform name and not the one in my config.xml file?
A:
Have you tried to re-install the plugins? When this error happened with me , it worked!
|
[
"ru.stackoverflow",
"0000696406.txt"
] | Q:
Ruby on Rails Activerecord - id в модели перепутаны
Дело обстоит в Ruby on Rails 4.2.0 на Ruby 2.1.0.
Есть следующая миграция:
class CreateStateTemplates < ActiveRecord::Migration
def change
create_table :state_templates do |t|
t.string :name
t.references :next
t.references :prev
t.timestamps null: false
end
end
end
...такая модель:
class StateTemplate < ActiveRecord::Base
has_one :prev, :class_name => "StateTemplate", :foreign_key => "prev_id"
belongs_to :state_template, :class_name => "StateTemplate", :foreign_key => "prev_id"
has_one :next, :class_name => "StateTemplate", :foreign_key => "next_id"
belongs_to :state_template, :class_name => "StateTemplate", :foreign_key => "next_id"
end
Если выполнить следующее:
StateTemplate.find(1).update(:next => StateTemplate.find(2))
StateTemplate.find(2).update(:next => StateTemplate.find(3), :prev => StateTemplate.find(1))
StateTemplate.find(3).update(:next => StateTemplate.find(4), :prev => StateTemplate.find(2))
StateTemplate.find(4).update(:next => StateTemplate.find(5), :prev => StateTemplate.find(3))
StateTemplate.find(5).update(:prev => StateTemplate.find(4))
Происходит нечто странное. Получение одного StateTemplate в консоли показывает следующее:
2.1.0 :007 > StateTemplate.find(2)
StateTemplate Load (0.1ms) SELECT "state_templates".* FROM "state_templates" WHERE "state_templates"."id" = ? LIMIT 1 [["id", 2]]
=> #<StateTemplate id: 2, name: "two", next_id: 1, prev_id: 3, created_at: "2017-07-22 11:51:30", updated_at: "2017-07-22 11:51:30">
Что неверно, next_id должен быть 3. При этом метод next показывает следующее:
2.1.0 :008 > StateTemplate.find(2).next
StateTemplate Load (0.1ms) SELECT "state_templates".* FROM "state_templates" WHERE "state_templates"."id" = ? LIMIT 1 [["id", 2]]
StateTemplate Load (0.0ms) SELECT "state_templates".* FROM "state_templates" WHERE "state_templates"."next_id" = ? LIMIT 1 [["next_id", 2]]
=> #<StateTemplate id: 3, name: "three", next_id: 2, prev_id: 4, created_at: "2017-07-22 11:51:30", updated_at: "2017-07-22 11:51:30">
А это уже верно.
Почему id в записи перепутаны местами, но получение ассоциированных записей при этом работает верно?
A:
Потому что вы перепутали has_one и belongs_to. Для обеих сторон.
К тому же, сейчас у вас дважды определена ассоциация state_template, работать будет только последнее из этих определений. Уже это указывает, что что-то с определениями не так.
Посмотрим на next.
Проблема тут:
has_one :next, :class_name => "StateTemplate", :foreign_key => "next_id"
belongs_to :state_template, :class_name => "StateTemplate", :foreign_key => "next_id"
Это должно быть:
belongs_to :next, :class_name => "StateTemplate"
И симметрично для prev.
Что происходит?
Вы, наверное, думаете, что эти две строчки ведут себя примерно одинаково:
StateTemplate.find(1).update(:next => StateTemplate.find(2))
StateTemplate.find(1).update(:next_id => 2)
Но из ваших ассоциаций следует, что первая строчка изменяет второй объект (который в аргументе), ставя ему next_id = 1. Несмотря на то, что обновляете вы, казалось бы, первый.
Вы неправильно определили ассоциацию next.
Сейчас ассоциированный — объект, у которого next_id равен id владельца. Ибо has_one.
А хотели вы наоборот: получить объект, id которого равен next_id владельца. Это belongs_to.
Запись, которая хранит в себе ключ ассоциированного объекта, относится к нему через belongs_to. А вот has_one и has_many хранят ключ не "в себе", а в ассоциированных объектах.
"Минус на минус даёт плюс". Апдейты сделали совсем не то, что вы подумали. И поиск ассоциированных записей работает не так, как вы хотите. Но оба пользуются одним определением и в сумме они работают верно: запись определённой записи в next действительно заставляет метод next у этого объекта возвращать эту запись.
|
[
"stackoverflow",
"0015400975.txt"
] | Q:
Building an installer that runs another installer
My company has a project for which I've developed an application in c#. I can create an installer for that application. However, the project requires users to install another application built in c++ that has an installer built using Visual Studio 10. Is there a way that I can build an installer that includes installation of the second product before installing my application?
A:
What you are looking for is a bootstrapper or chainer. The WiX Toolset provides this functionality in a tool called Burn. It allows you to provide a single user experience while installing all of your setup packages. You can read about it more in WiX .chm.
|
[
"stackoverflow",
"0054407886.txt"
] | Q:
When trait collection changes, constraint conflicts arise as though the stackview axis didn't change
I've a stackview with two controls.
When the UI is not vertically constrained:
Vertical1
When the UI is vertically constrained: Horizontal1
I get both UIs as pictured. There are no constraint conflicts when I show the UIs the first time. However, when I go from vertically constrained to vertical = regular, I get constraint conflicts.
When I comment out the stackview space (see code comment below), I don't get a constraint conflict.
class ViewController: UIViewController {
var rootStack: UIStackView!
var aggregateStack: UIStackView!
var field1: UITextField!
var field2: UITextField!
var f1f2TrailTrail: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
createIntializeViews()
createInitializeAddStacks()
}
private func createIntializeViews() {
field1 = UITextField()
field2 = UITextField()
field1.text = "test 1"
field2.text = "test 2"
}
private func createInitializeAddStacks() {
rootStack = UIStackView()
aggregateStack = UIStackView()
// If I comment out the following, there are no constraint conflicts
aggregateStack.spacing = 2
aggregateStack.addArrangedSubview(field1)
aggregateStack.addArrangedSubview(field2)
rootStack.addArrangedSubview(aggregateStack)
view.addSubview(rootStack)
rootStack.translatesAutoresizingMaskIntoConstraints = false
aggregateStack.translatesAutoresizingMaskIntoConstraints = false
field1.translatesAutoresizingMaskIntoConstraints = false
field2.translatesAutoresizingMaskIntoConstraints = false
f1f2TrailTrail = field2.trailingAnchor.constraint(equalTo: field1.trailingAnchor)
}
override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.verticalSizeClass == .regular {
aggregateStack.axis = .vertical
f1f2TrailTrail.isActive = true
} else if traitCollection.verticalSizeClass == .compact {
f1f2TrailTrail.isActive = false
aggregateStack.axis = .horizontal
} else {
print("Unexpected")
}
}
}
The constraint conflicts are here -
(
"<NSLayoutConstraint:0x600001e7d1d0 UITextField:0x7f80b2035000.trailing == UITextField:0x7f80b201d000.trailing (active)>",
"<NSLayoutConstraint:0x600001e42800 'UISV-spacing' H:[UITextField:0x7f80b201d000]-(2)-[UITextField:0x7f80b2035000] (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600001e42800 'UISV-spacing' H:[UITextField:0x7f80b201d000]-(2)-[UITextField:0x7f80b2035000] (active)>
When I place the output in www.wtfautolayout.com, I get the following:
Easier to Read Output
The second constraint shown in the above image makes me think the change to stackview vertical axis did not happen before constraints were evaluated.
Can anyone tell me what I've done wrong or how to properly set this up (without storyboard preferably)?
[EDIT] The textfields are trailing edge aligned to have this:
More of the form - portrait
More of the form - landscape
A:
Couple notes...
There is an inherent issue with "nested" stack views causing constraint conflicts. This can be avoided by setting the priority on affected elements to 999 (instead of the default 1000).
Your layout becomes a bit complex... Labels "attached" to text fields; elements needing to be on two "lines" in portrait orientation or one "line" in landscape; one element of a "multi-element line" having a different height (the stepper); and so on.
To get your "field2" and "field3" to be equal size, you need to constrain their widths to be equal, even though they are not subviews of the same subview. This is perfectly valid, as long as they are descendants of the same view hierarchy.
Stackviews are great --- except when they're not. I would almost suggest using constraints only. You need to add more constraints, but it might avoid some issues with stack views.
However, here is an example that should get you on your way.
I've added a UIStackView subclass named LabeledFieldStackView ... it sets up the Label-above-Field in a stack view. Somewhat cleaner than mixing it in within all the other layout code.
class LabeledFieldStackView: UIStackView {
var theLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
var theField: UITextField = {
let v = UITextField()
v.translatesAutoresizingMaskIntoConstraints = false
v.borderStyle = .roundedRect
return v
}()
convenience init(with labelText: String, fieldText: String, verticalGap: CGFloat) {
self.init()
axis = .vertical
alignment = .fill
distribution = .fill
spacing = 2
addArrangedSubview(theLabel)
addArrangedSubview(theField)
theLabel.text = labelText
theField.text = fieldText
self.translatesAutoresizingMaskIntoConstraints = false
}
}
class LargentViewController: UIViewController {
var rootStack: UIStackView!
var fieldStackView1: LabeledFieldStackView!
var fieldStackView2: LabeledFieldStackView!
var fieldStackView3: LabeledFieldStackView!
var fieldStackView4: LabeledFieldStackView!
var stepper: UIStepper!
var fieldAndStepperStack: UIStackView!
var twoLineStack: UIStackView!
var fieldAndStepperStackWidthConstraint: NSLayoutConstraint!
// horizontal gap between elements on the same "line"
var horizontalSpacing: CGFloat!
// vertical gap between "lines"
var verticalSpacing: CGFloat!
// vertical gap between labels above text fields
var labelToFieldSpacing: CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
horizontalSpacing = CGFloat(2)
verticalSpacing = CGFloat(8)
labelToFieldSpacing = CGFloat(2)
createIntializeViews()
createInitializeStacks()
fillStacks()
}
private func createIntializeViews() {
fieldStackView1 = LabeledFieldStackView(with: "label 1", fieldText: "field 1", verticalGap: labelToFieldSpacing)
fieldStackView2 = LabeledFieldStackView(with: "label 2", fieldText: "field 2", verticalGap: labelToFieldSpacing)
fieldStackView3 = LabeledFieldStackView(with: "label 3", fieldText: "field 3", verticalGap: labelToFieldSpacing)
fieldStackView4 = LabeledFieldStackView(with: "label 4", fieldText: "field 4", verticalGap: labelToFieldSpacing)
stepper = UIStepper()
}
private func createInitializeStacks() {
rootStack = UIStackView()
fieldAndStepperStack = UIStackView()
twoLineStack = UIStackView()
[rootStack, fieldAndStepperStack, twoLineStack].forEach {
$0?.translatesAutoresizingMaskIntoConstraints = false
}
// rootStack has spacing of horizontalSpacing (inter-line vertical spacing)
rootStack.axis = .vertical
rootStack.alignment = .fill
rootStack.distribution = .fill
rootStack.spacing = verticalSpacing
// fieldAndStepperStack has spacing of horizontalSpacing (space between field and stepper)
// and .alignment of .bottom (so stepper aligns vertically with field)
fieldAndStepperStack.axis = .horizontal
fieldAndStepperStack.alignment = .bottom
fieldAndStepperStack.distribution = .fill
fieldAndStepperStack.spacing = horizontalSpacing
// twoLineStack has inter-line vertical spacing of
// verticalSpacing in portrait orientation
// for landscape orientation, the two "lines" will be changed to one "line"
// and the spacing will be changed to horizontalSpacing
twoLineStack.axis = .vertical
twoLineStack.alignment = .leading
twoLineStack.distribution = .fill
twoLineStack.spacing = verticalSpacing
}
private func fillStacks() {
self.view.addSubview(rootStack)
// constrain rootStack Top, Leading, Trailing = 20
// no height or bottom constraint
NSLayoutConstraint.activate([
rootStack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20.0),
rootStack.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20.0),
rootStack.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20.0),
])
rootStack.addArrangedSubview(fieldStackView1)
fieldAndStepperStack.addArrangedSubview(fieldStackView2)
fieldAndStepperStack.addArrangedSubview(stepper)
twoLineStack.addArrangedSubview(fieldAndStepperStack)
twoLineStack.addArrangedSubview(fieldStackView3)
rootStack.addArrangedSubview(twoLineStack)
// fieldAndStepperStack needs width constrained to its superview (the twoLineStack) when
// in portrait orientation
// setting the priority to 999 prevents "nested stackView" constraint breaks
fieldAndStepperStackWidthConstraint = fieldAndStepperStack.widthAnchor.constraint(equalTo: twoLineStack.widthAnchor, multiplier: 1.0)
fieldAndStepperStackWidthConstraint.priority = UILayoutPriority(rawValue: 999)
// constrain fieldView3 width to fieldView2 width to keep them the same size
NSLayoutConstraint.activate([
fieldStackView3.widthAnchor.constraint(equalTo: fieldStackView2.widthAnchor, multiplier: 1.0)
])
rootStack.addArrangedSubview(fieldStackView4)
}
override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.verticalSizeClass == .regular {
fieldAndStepperStackWidthConstraint.isActive = true
twoLineStack.axis = .vertical
twoLineStack.spacing = verticalSpacing
} else if traitCollection.verticalSizeClass == .compact {
fieldAndStepperStackWidthConstraint.isActive = false
twoLineStack.axis = .horizontal
twoLineStack.spacing = horizontalSpacing
} else {
print("Unexpected")
}
}
}
And the results:
|
[
"stackoverflow",
"0033750179.txt"
] | Q:
Allow a slice of any type into as argument
I am new to Go (coming from python) and I am having a bit of a hard time here. I am trying to allow any type of slice into my struct/func and it just contains a count of the length of that slice.
import "go/types"
type Response struct {
Count int `json:"count"`
Results []types.Struct `json:"results`
}
func NewResponse(results []types.Struct) (r *Response) {
r.Count = len(results)
r.Results = results
return
}
A:
you can use interface{} as any type.
type Response struct {
Count int `json:"count"`
Results []interface{} `json:"results`
}
UPDATE
len(rsp.results) should work.
http://play.golang.org/p/RA2zVzWl2q
|
[
"stackoverflow",
"0031990672.txt"
] | Q:
How to handle Zim Error "The ZIM tree pool has overflowed"
I have the following code:
set output spoole
select * from displays where displayname='dsp020a'
select * from forms where formname in (select formname from displayforms where displayname='dsp020a')
select * from formfields where formname in (select formname from displayforms where displayname='dsp020a')
The third select is crashing ZIM with the following error:
*** ZIM System Error *** The Zim tree pool has overflowed. Type BYE to exit from Zim.
What am I doing wrong and how can I fix it?
A:
When trying to use SQL in ZIM, I also saw problems and unexpected errors. You should always try to use the native ZIM 4GL commands to access data as well as object definitions.
ZIM Data Dictionary contains some predefined internal relations which can help analyse the data model. For example, you could say:
list all Displays DispDispForms DisplayForms where Displays.DisplayName = "dsp020a"
to find out which forms are contained in the given display. Likewise you could do:
list all Forms FormFormFields FormFields where Forms.FormName in ("f020a", "f020b", "f020c")
to list all form fields which belong to the given forms. Unfortunately, there is no relation between DisplayForms and Forms, so you cannot achieve directly what you tried in your example using SQL.
OR (added after your comment):
You can achieve that using a small program. For this example, it would be:
set output output_file
find Displays DispDispForms DisplayForms where Displays.DisplayName = "dsp020a"
while $setcount > 0
let vStr = DisplayForms.FormName
list all Forms FormFormFields FormFields where Forms.FormName = vStr
let $setcount = $setcount - 1
next
endwhile
set output terminal
Now you have all form fields which belong to all forms of the given display listed in the output_file.
|
[
"english.stackexchange",
"0000451765.txt"
] | Q:
What are hard/flat buttons (on appliances) called?
What are the kind of push buttons used on modern appliances called:
Lies flush with the surface.
Have to press (not tap) to activate.
Button usually doesn't move much or at all when you press it.
Usually seamless or a slight seam with the surface.
Often the same material over the whole surface, including buttons.
Often seen on surfaces that need to be cleaned frequently or water/splash proof... Stove, washer/dryer, point of sale terminals, and most recently a new printer.
Originally I was writing a review and wanted to complain that the _____ type of buttons were hard to use, not like normal buttons. But now I just want to know since it seems like these are showing up everywhere.
A:
Membrane switch, where one contact of the switch assembly is embedded in a flexible substrate.
A:
Touch pad:
If the touch pads on your microwave oven do not respond but the display lights up, the problem is most likely with the membrane switch. This component, which is more commonly referred to as the touch pad, is actually a series of soft touch electrical switches.
I had originally thought of this as a "touch panel" and Googled that (along with "microwave"). But I then noticed that many of the repair sites referred to it as a "touch pad" (or "touchpad," without the space) instead.
Here, also, is what Merriam-Webster says about touch pad:
a keypad for an electronic device (such as a microwave oven) that consists of a flat surface divided into several differently marked areas which are touched to choose options
A:
“Touch-sensitive buttons” as sold here: https://gblockingsystems.co.uk/locking-systems/touch-sensitive-buttons/
GB Locking Systems range of high quality touch sensitive exit / entry buttons. An ideal replacement for conventional push buttons, door release buttons, call switches, etc. Ideal for the elderly and disabled – no pressure required operates with the lightest of touches.
If it’s a switch then it’s a “touch switch”:
A touch switch is a type of switch that only has to be touched by an object to operate. It is used in many lamps and wall switches that have a metal exterior as well as on public computer terminals.
https://en.m.wikipedia.org/wiki/Touch_switch
|
[
"english.stackexchange",
"0000223706.txt"
] | Q:
Meaning of 'subject to spells'?
The noise had ceased, and everything was quiet. Then she sat down on the side of her bed, and, feeling faint--she was subject to spells--("I told you that when I came, didn't
I, Rosie?" "Yes'm, indeed she did!")--she put her head down on her
pillow and--
(From 'Circular Staircase' by Mary Rinehart.)
It definitely wouldn't be 'letters' or some 'magical things'.
A:
When used without a qualifying prepositional phrase, a spell can be an old-fashioned term for a short period of diminished mental capacity. It can be used to mean a "spell of dizziness", a "spell of fainting", a "spell of lunacy", or even a "spell of epilepsy" (which would later take on the term "fit" rather than "spell"). The term is rarely used today without qualifying the specific type of spell the person is experiencing, but in olden times anything affecting one's brain was mysterious and hard to differentiate.
I can't find an online dictionary listing that old-time meaning, but the Google Ngram showing usage of the phrase "subject to spells" is interesting, and not only shows the declining usage over time, but searching the more recent works shows the phrase is essentially always qualified in modern times ("subject to spells of madness", etc) with the unusual exception of an income tax guide from 2000 (which likely is merely repeating the text of an earlier tax ruling or law). The phrase as a standalone seems to have died out in the 60's and 70's (see this example).
|
[
"stackoverflow",
"0036177049.txt"
] | Q:
angular unknown provider upload
I have a problem with upload module in Angular. I install module from https://github.com/nervgh/angular-file-upload
I use Angular 1.5.0
In index.html i have:
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-file-upload/dist/angular-file-upload.js"></script>
<script src="scripts/app.js"></script>
My app.js
var app = angular
.module('MyApp', [
'ngAnimate',
'ngCookies',
'datatables',
'ngResource',
'ngRoute',
'angularFileUpload',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider...
This is my main.js
angular.module('MyApp')
.controller('MainCtrl', ['$rootScope', '$scope','$upload','$location', 'myService', function ($rootScope, $scope,$upload,$location, myService) {
}]);
In console : Error: [$injector:unpr] Unknown provider: $uploadProvider <- $upload <- MainCtrl
$upload variable is undefined
Please help me.
A:
Just replace $uploader to FileUploader. there is some problem with fileuploader module, and updated FileUploader module using FileUploader service.
|
[
"stackoverflow",
"0016836347.txt"
] | Q:
Why is my Python instance being shared?
My code:
class Num:
nums = []
def add(self, num):
self.nums.append(num)
def __str__(self):
return str(self.nums)
a = Num()
b = Num()
a.add(5)
print str(a)
print str(b)
produces
[5]
[5]
even though nothing has been added to b
A:
Because nums is a class attribute and not an instance attribute.
class Num:
def __init__(self):
self.nums = []
def add(self, num):
self.nums.append(num)
def __str__(self):
return str(self.nums)
Implementing it like this will show the behavior you expect.
A:
class Num:
nums = []
Defining nums in the class definition statement makes nums a class variable. Define it in the __init__ method instead, by setting it as an attribute of the instance:
class Num:
def __init__(self): # self is the instance
self.nums = [] # setting nums on the instance
|
[
"math.stackexchange",
"0002766113.txt"
] | Q:
Continuity of functions in topology
I have this topology $\sigma$ on $\mathbb{R}^2$ given by the emptyset and all the union of $\Omega_r=\{(x,y)\in\mathbb{R}^2, x^2+y^2=r^2\}, r\geq0$
The question is to study the continuity of the following two functions given by
$ \Psi:(\mathbb{R},\lvert \cdot \rvert)\to (\mathbb{R}^2,\sigma)\\ \qquad x\mapsto (x,a)$ and $\Phi:(\mathbb{R}^2,\sigma)\to (\mathbb{R},\lvert \cdot \rvert)\\ \qquad(x,y)\mapsto x$
where $a$ is fixed in $\mathbb{R}$.
For the function $\Phi$ to study the continuity at each point of it's domain of definition, i think that it is enough to that the inverse image of any open set is open
But if i take $]\alpha,\beta[$ that $\Phi^{-1}(]\alpha,\beta[)=]\alpha,\beta[\times\mathbb{R}$ it is not open in $(\mathbb{R}^2,\sigma)$
so $\Phi$ is not continuous at any point from $\mathbb{R}$
is it correct ?
A:
Your argument (well, you don't prove that the inverse image is not open) shows that $\Phi$ is not globally continuous, but it does not study the pointwise continuity of $\Phi$, as you asked.
It's easy to see that each point has one minimal neighbourhood: the circle around the origin going through it, so:
A function $f(\mathbb{R}^2, \sigma) \to X$ is continuous at $(x,y)$ iff for every open set $O$ of $X$ with $f(x) \in O$ we have $f[B_r] \subseteq O$ where $r = \sqrt{x^2 + y^2}$.
As $B_0 = \{(0,0)\}$ this implies that all $f$ are continuous at $(0,0)$.
But as to $\Phi$, this criterion shows that $\Phi$ is only continuous there.
Also a function $f:X \to (\mathbb{R}^2, \sigma)$ is continuous iff $f^{-1}[B_r]$ is continuous for all $r \ge 0$.
Let $x$ be a point in $\Psi^{-1}[B_r]$. This means that $x^2 + a^2 = r^2$, which means that $r^2 \ge a^2$ and $x \in \{-\sqrt{r^2-a^2},\sqrt{r^2-a^2}\}$.
So $\Psi^{-1}[B_r]$ can be empty, but if it is not, then it is a finite subset of $\mathbb{R}$, so never open. In particular $\Psi^{-1}[B_{a^2}] = \{0\}$ for all $a$. So whatever $a$ is, $\Psi$ is not continuous.
|
[
"stackoverflow",
"0047904777.txt"
] | Q:
C# and dotnet 4.7.1 not adding custom certificate for TLS 1.2 calls
I have the following C# code, constructing an https call with a custom certificate. When using Tls 1.1, the call works fine. When using Tls 1.2 the call breaks. I using curl, using tls 1.2 works fine as well.
C# Code:
X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Import("C:\\SomePath\\MyCertificate.pfx", "MyPassword", X509KeyStorageFlags.PersistKeySet);
var cert = collection[0];
ServicePointManager.SecurityProtocol = ...;
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;
HttpClientHandler handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true;
handler.ClientCertificates.Add(cert);
var content = new ByteArrayContent(Encoding.GetEncoding("latin1").GetBytes("Hello world"));
HttpClient client = new HttpClient(handler);
var resp = client.PostAsync(requestUri: url, content: content).Result.Content.ReadAsStringAsync().Result;
Works with:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
Error with:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
.Net error message: SocketException: An existing connection was forcibly closed by the remote host
.Net version : 4.7.1
OS: Windows 10 version 1703 (supported cipher list: https://msdn.microsoft.com/en-us/library/windows/desktop/mt808163(v=vs.85).aspx) - and the server specifies TLS_RSA_WITH_AES_256_GCM_SHA384 to be used, which is among the supported ciphers.
In wireshark I can see that with the working calls (C#/Tls 1.1 and Curl Tls 1.2) the certificate is being sent to the server. Here is the wireshark dump for the C# tls 1.1 call:
However, also in wireshark, I can see that with C#/Tls 1.2 there is no certificate being sent from the client to the server. Here is the wireshark dump for the C# tls 1.2 call:
Can anyone see what I am missing here?
UPDATE
It seems the certificate has an md5 signature which is not supported by Schannel in windows in combination with tls 1.2. Our vendor has created another certificate to us as a solution.
I came across this random thread that discusses the issue: https://community.qualys.com/thread/15498
A:
You are right on the root cause of this problem: By default, schannel-based clients offer SHA1, SHA256, SHA384 and SHA512 (on Win10/Server 2016). So TLS 1.2 servers are not supposed to send their MD5 certs to these clients.
The client (HttpClient) does not list MD5 in the signature_algorithms extension, so the TLS 1.2 handshake fails. The fix is to use a secure server cert.
|
[
"stackoverflow",
"0058730802.txt"
] | Q:
How to pull ids from array of hashes on ruby?
Given:
data = [
{"id"=>nil, "votable_id"=>1150, "user_ids"=>"1120,1119,1118,1117,1116,1115,1114,1113,1112,1111,1110,1109,1108,1107"},
{"id"=>nil, "votable_id"=>1151, "user_ids"=>"1120,1119,1118,1117,1116,1115,1114,1113,1112,1111,1110,1109,1108,1107"}
]
I wish to return an array of all unique representations of integers in the strings g["user_ids"], taken over all hashes g that are elements of data; namely,
["1120", "1119", "1118", "1117", "1116", "1115", "1114",
"1113", "1112", "1111", "1110", "1109", "1108", "1107"]
A:
To get the unique ids:
unique_ids = data.flat_map { |d| d['user_ids'].split(',') }.uniq
Enumerable#flat_map walks through the Array and concatenate
the results provided in the code block.
String#split divides the string by the delimiter
into an Array.
Array#uniq removes the duplicates.
|
[
"stackoverflow",
"0023477563.txt"
] | Q:
How to import variable columns into fixed columns in Excel 2007
I have a text file that has the variable columns.
I need to convert the variable columns to fixed columns in Excel 2007 (or Access Database 2007 - whichever works better? or however better anywhere!).
How do?
Thanks!
Holly
A:
From the Data tab, touch From Text in the Get external data group.
This will invoke the Import Wizard to allow you to pick the file............You can tell the Wizard to use the tilde as the separator.
|
[
"stackoverflow",
"0015313654.txt"
] | Q:
inserting data in mysql
I would like to know how I can insert only in a particular column in mysql database?
I have 12 fields or column in my database. I would like to insert a data only in the last column. How can I do this in PHP?
A:
Use an INSERT statement that only has this one column listed. Whether that will work depends on the definition of the columns in the table. It may be that certain other columns are "required"
|
[
"stackoverflow",
"0039155810.txt"
] | Q:
Displaying an object within an array through DOM
var products = [{
"name": "Lusicious Jello Mix",
"description": ["Very Elegant", "Trending item", "Come in Purple"],
"price": 80.65
}, {
"name": "Tarnished Standing Desk",
"description": ["Modular", "Works for both Tall and Loud People", "Smells like Productivity"],
"price": 1654.99
}, {
"name": "Hand-made Hand Grenades",
"description": ["Such gift!", "Much boom!", "Very safe for kids"],
"price": 10.44
}, {
"name": "Pan-fried Cookie Dough",
"description": ["Chocolate", "Family-size", "Hot Mess"],
"price": 16.99
}, {
"name": "Fancy Dress Hanger",
"description": ["Keep organized", "On Sale"],
"price": 67.32
}, {
"name": "Snarky Britsh Mustache 3-Pack",
"description": ["Sharing is caring!", "Hugs not drugs", "As seen on 'So You Think You Can Dance - Nigeria!'"],
"price": 1.99
}, ];
for (var x=0; x<products.length; x++){
//PRODUCT NAME
var prodname = document.createElement("h3");
prodname.innerHTML = products[x].name;
var listname = document.getElementById("name");
listname.appendChild(prodname);
var proddesc = document.createElement("h3");
proddesc.innerHTML = products[x].description;
var listdesc = document.getElementById("description");
listdesc.appendChild(proddesc);
var prodprice = document.createElement("h3");
prodprice.innerHTML = products[x].price;
var listprice = document.getElementById("price");
listprice.appendChild(prodprice);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Shopping Cart</title>
<script src="js/app.js"></script>
<link rel="stylesheet" href="css/styles.css"></link>
</head>
<body>
<div>
<div id="shopHead"><h3>Shopping Cart<h3/>
<h3 id="name"></h3>
<h3 id="description"></h3>
<h3 id="price"></h3>
</div>
</div>
</body>
</html>
This is my object within an array called products. By which I am using an array and then using the DOM to display in my HTML page. However it is not coming out in order. I want to display the name in the array at position 0 and then the description at position 0 finally the priced at position 0. Instead it's displaying all my names followed by all of the description followed by all of the prices. It's a simple fix I'm sure but I'm stuck.
A:
Try this
var displayBox = document.createElement("h3");
displayBox.innerHTML = products[x].name + " "+ products[x].description + " "+products[x].price;
var listname = document.getElementById("name");
listname.appendChild(displayBox);
|
[
"stackoverflow",
"0027527793.txt"
] | Q:
Where clause on composite key in hibernate
I think I'm missing something pretty big but to me hibernate seems VERY limited.
I have the following table (simplified slightly):
USER_ID | USER | TARGET_ID | TARGET_USER | EFFECT_DATE | REQUEST_NO | EXPIRY_DATE |
------------------------------------------------------------------------------------
a11 | jon | a22 | steve | 21/12/2014 | 555324 | 28/12/2014 |
a11 | jon | a33 | jim | 23/12/2014 | 555324 | 28/12/2014 |
a11 | jon | a44 | bob | 24/12/2014 | 555324 | 28/12/2014 |
a22 | steve| a33 | jim | 24/12/2014 | 555324 | 28/12/2014 |
The huge issue is that there are 3 composite keys on:
USER_ID, TARGET_ID and EFFECT_DATE
I realise this isn't easy to work with but it's what I have been given so I don't have much control about the design of the table.
I have connected to my DB using hibernate using the following composite key mapping:
<composite-id name="actAsID">
<key-property name="userID" column="PROXY_USER_ID" type = "string" />
<key-property name="targetID" column="TARGET_USER_ID" type="string"/>
<key-property name="effectDate" column="EFFCT_DATE" type="date" />
</composite-id>
This works absolutely fine and I can add users remove them and search for them. The issue comes when searching for a user it seems I HAVE to provide values for User ID, Target ID and Effective date i.e. only pulling one row of data each time. This leads me to believe I can only get one row or I can get all of them which seems very limited.
I have four main use cases here:
1) Getting all rows in table
2) Searching a USER_ID to give me all the rows with that USER_ID
3) Searching a TARGET_ID to give me all the rows with that TARGET_ID
4) Searching based on a given USER_ID AND TARGET_ID
I did have in the mapping file just the ID set to USER_ID but then this only allows me to get all the users or all the rows with that USER_ID i.e. I can't use a where clause on TARGET_ID.
A:
I can either use HQL or Criteria within Hibernate.
For example the following code gives me all users with a USER_ID of A11:
List<ProxyUser> Users = session.createCriteria(User.class)
.add(Restrictions.eq("actAsID.userID", "11"))
.list();
Some good examples of HQL:
http://www.journaldev.com/2954/hibernate-query-language-hql-example-tutorial
Using criteria with composite keys:
Hibernate : how to get records from composite key using Criteria Query
|
[
"stackoverflow",
"0014650302.txt"
] | Q:
Javascript / jQuery: How do I remove a range of numbered classes?
Possible Duplicate:
Remove all classes that begin with a certain string
I have a script which adds one of six classes randomly to the body. The classes are numbered between 1 and 6, like this:
theme-1 to theme-6.
I need a clean way to remove all of them. Right now I have this:
$('body').removeClass('theme-1');
$('body').removeClass('theme-2');
$('body').removeClass('theme-3');
$('body').removeClass('theme-4');
$('body').removeClass('theme-5');
$('body').removeClass('theme-6');
But it's kind of clunky right? Is there a way I can say "remove any classes between theme-1 to theme-6"?
A:
You can use the loop index to generate class names.
classes = ""
for(i=1; i < 7; i++)
classes += 'theme-' + i + " ";
$('body').removeClass(classes);
|
[
"pm.stackexchange",
"0000003252.txt"
] | Q:
How to share project plans with the team
This may look a bit weird, but I stuck with the problem of sharing the project plans with team.
The main purpose I try to achieve (though not sure if it's right) is that everyone should know what to do next (and do not ask about this every time he ends with current item) and to see the full picture of upcoming tasks.
Here's a list of approaches with their cons I see:
Board. Problem - when priority (and even entire list) of tasks is changed it's difficult to re-write it.
Project management software. (we use Goplan currently). Problem - not all tasks/small projects are managing here, sometimes it's not possible/easy for a member to recognize the right priority.
Google docs spreadsheet. Problem - not sure how to be with e-mail notifications so the team know when something is changed.
Also I'd like to reduce the number of software/instruments I use in project management (currently, it's web-based project management software to collaborate with customers, assigning tasks/tickets + my mind maps + one of the above things) to concentrate more on other aspects and not just do the copy-paste from program A to program B.
If this helps, the team size is 3-4 people now, the projects are websites/web-systems.
UPD: The point is I'm not sure what's the most efficient approach:
say, every morning, tell everybody the list of tasks/bugs to be done this day
give a schedule of tasks for a week/month
task by task. When the work on task A is completed, tell about the task B.
UPD2: I guess I haven't clearly clarified this, but the problem is that requirements changes every day (and even during the day) and new important tasks/issues may arrive at anytime.
Hope this clarifies the initial question a bit.
Thanks.
A:
Everyone works differently, and everyone wants different things from the manager. Some want to be given a task, then complete it, then be given another task... and so on. Some want to know the big picture and be left to manage their own time and priorities within it, and only be told when something material changes. And others will be at different points between the two extremes. No tool can resolve this for you, because you are dealing with people who don't fit into with an idealised model.
What I would do is have a regular but short team session. 5 to 15 minutes should be plenty. Have this daily if that works for you, or less frequently if you prefer. If you are using an agile methodology (scrum) then you should be doing this anyway. At that meeting, give the headlines, listen for warning signals, and as appropriate, hand out the day's tasks. Follow up specific issues and concerns on a one-to-one level outside the meeting if necessary. By the way, if you are accepting revised requirements or changing priorities on a daily basis, something is wrong with either the team's work, or you have a flawed relationship with your customers, or you need to think again about the way that you react to external influences.
Question: do all issues and change requests come through you, or direct to the person in the team who is best able to deal with them? If they all come to you, ask yourself why. Why should you act as a buffer? Wouldn't it be better to set out guidelines for the team to help them to prioritise, and let them work within these guidelines, without you having to get involved all the time?
If you must have tools, try using a spreadsheet of "must do" tasks that you print out and stick on the wall every week. Have sufficient slack within this to allow you to accommodate new, unplanned demands, and use sticky notes to capture these and move them around as priorities change. Software solutions are possible, but the physical act of moving yellow stickies around a sheet of A3 paper gives a sense of ownership, for reasons that I can't quite understand. It also conveys a sense of urgency if they all start piling up against Friday afternoon...!
|
[
"stackoverflow",
"0020884766.txt"
] | Q:
Utilities function in Google App Scripts not working
Function Utilities.formatDate in Google App Scripts is not working correct for date in year 2013
Example-
date = Tue Dec 31 2013 18:43:12 GMT+0530 (IST)
after formatting it in YYYYMMdd format
using code-
Utilities.formatDate(date, "IST" ,"YYYYMMdd"))
result was- 20**14**1231
In the above result year is expected to be 2013 as per above mentioned date.
The same code is working correct for date in 2012 and 2014.
A:
Just change your pattern from YYYY to yyyy (lower case) and it will work, check this:
function myFunction() {
var date = new Date("Tue Dec 31 2013 18:43:12 GMT+0530 (IST)");
//after formatting it in YYYYMMdd format
var format = Utilities.formatDate(date,"IST", "yyyyMMdd");
Logger.log(format);
}
|
[
"stackoverflow",
"0002269750.txt"
] | Q:
CMake and including other makefiles
Lets say I have a CMakeLists.txt and I want to call another include another makefile in that file (similar to the #include syntax in C), how would I accomplish this?
A:
From the CMake documentation:
include: Read CMake listfile code from the given file.
include(<file|module> [OPTIONAL] [RESULT_VARIABLE <VAR>]
[NO_POLICY_SCOPE])
Example use:
CMakeLists.txt:
cmake_minimum_required(VERSION 2.8)
include (Project.txt)
Project.txt:
project (Project)
add_executable(Project project.c)
|
[
"stackoverflow",
"0011776844.txt"
] | Q:
What is the complexity (Big-O) of searching an indexed data in mongoDB?
This is for a design issue. Can you tell me if i am indexing the key words as shown below.
obj = {
name: "Apollo",
text: "Some text about Apollo moon landings",
tags: [ "moon", "apollo", "spaceflight" ]
}
Ensuring index like this .
db.articles.ensureIndex( { tags: 1 } );
and frequent query as follows.
db.articles.findOne( { tags: "apollo" } ).name
Please give me the performance of such query if i have n such documents inserted.
is it O(1) ?
And what is the performance for searching a regular expressions on such data.?
A:
This is a B-tree index, like in almost all databases, so it has O(log n) lookup time.
A regular expression search sounds like it needs to do a full table scan or a full index scan, both of which is O(n). If the expression is prefix-anchored, it would need to scan just a range, but I guess that still counts as O(n).
|
[
"stackoverflow",
"0025136508.txt"
] | Q:
jQuery date picker show half day blocked
I am using jQuery datepicker to show some blocked dates of apartments. I am just taking all the blocked dates into array and giving styles to all dates like this.
for (i = 0; i < activeDays.length; i++)
{
if($.inArray(y + '-' + (m+1) + '-' + d,activeDays) != -1) {
return [true, 'css-class-to-highlight', ''];
}
CSS
<style>
.css-class-to-highlight a{
background-color : Red !important;
background-image :none !important;
color: White !important;
font-weight:bold !important;
}
</style>
This is the result
And my requirement is I need to show first date and last date of the blocked dates as half available. which means half of the date in red color. How can I do it using css or javascript? any ideas?
A:
You can apply css's background : linear-gradient property to div as below:
.css-class-to-highlight a{
background : linear-gradient(red 50%, green 50%);
background-image :none !important;
color: White !important;
font-weight:bold !important;
}
You can even make beautiful gradients out of by calculating more colors and percentages. link.
JsFiddle Demo
|
[
"stackoverflow",
"0009259385.txt"
] | Q:
OnClickListener in a dialog button is called twice with a long processing
I have a bug on my application, it looks really strange but it is easy to reproduce.
Try this code on an activity :
public int myIncrement = 0;
protected Dialog onCreateDialog(int i, Bundle args)
{
if (i == DIALOG_TEST_MY_BUG)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Test");
builder.setNegativeButton("Test", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Log.i("Test", "<- myIncrement : " + myIncrement);
for (int i = 0; i < 1000000; i++)
myIncrement ++;
Log.i("Test", "-> myIncrement : " + myIncrement);
}
}
}
}
When you show this dialog, it's ok. When you click on the button "Test", it's ok. The log shows :
<- myIncrement : 0
-> myIncrement : 1000000
But if you click repetitively on the button "Test", the onClickListener will be called 2 or more times :
<- myIncrement : 0
-> myIncrement : 1000000
<- myIncrement : 1000000
-> myIncrement : 2000000...
Here this exemple is just to let you understand my problem. The equivalent of
for (int i = 0; i < 1000000; i++)
myIncrement ++;
is a long processing with file writting and a view change, and an other with synchronisation on a server. I tried lots of changes, like change a boolean in the onClick method, but without success.
Please, check your answer before proposing. Please also try this on your applications, when a click causes a long processing, try to click it many times.
A:
You're trying to start a long running task in the UI thread, which is completely prohibited. It may cause you bugs like this and ANRs too, if the task runs longer then 5 seconds. So for any long running tasks you should create a separate thread. I'd reccomend using the AsyncTask class since it's very simple to use and to synchronize with the UI thread to show your users that your application is not stuck. Hope this helps.
|
[
"stackoverflow",
"0011781715.txt"
] | Q:
Weird behaviour on fireTableDataChanged in JTable
Up till now I had a definition of the JTable like this:
JTable table = new JTable(model) {
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
TradeTableModel model = (TradeTableModel) getModel();
if ((Boolean) model.getValueAt(row, model.findColumn("Select"))) {
Side s = (Side) model.getValueAt(row, model.findColumn("Side"));
if (s == Side.BUY)
c.setBackground(Color.BLUE);
else
c.setBackground(Color.red);
}
else {
c.setBackground(Color.white);
}
return c;
}
};
This was to make sure the rows will change color based on selecting the boolean column value. At my AbstractTableModel I specified set value method as follows:
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
assert columnIndex == 5;
try{
Selectable t = trades.get(rowIndex);
t.setSelected((Boolean)aValue);
fireTableDataChanged();
//fireTableCellUpdated(rowIndex, columnIndex);
}
catch(Exception e){
throw new IllegalArgumentException("Object to set was not subtype of boolean");
}
}
If I use fireTableDataChanged() the color is updated as I click the checkbox on the gui. Howver, I really want to send the fireTableCellUpdated(rowIndex, columnIndex) as other handlers need to know the location of the cell. However, in this scenario, the row only changes if I click on other row in the table, as if it was delayed and waited for some other event to happen.
ANy ideas why that is the case?
A:
Your (unseen) TableModel should fireTableXxxXxxx() as required in order to notify all listeners. DefaultTableModel does this automatically; AbstractTableModel should do so in setValueAt(). One such listener is the table itself. If "other handlers need to know the location of the cell," they can register for TableModelEvent instances via addTableModelListener(). They can also listen for User Selections as needed.
|
[
"stackoverflow",
"0060925480.txt"
] | Q:
Creating a base_url(variable) in the config file - Laravel Config
I am currently migrating my .env settings to config files.
I have list of url's which I will be calling from the application. The BASE_URL will change, so I am looking to keep it as a variable..
In the .env file, I am able to call the BASE_URL as variable but in the config file, I am not getting any result.
.env file
BASE_URL = www.url.com
URL1 = ${BASE_URL}/url1,
URL2 = ${BASE_URL}/url2,
URL3 = ${BASE_URL}/url3,
In Config Folder > Created url.php file
url.php
<?php
return[
'BASE_URL' => 'www.url.com',
'URL1' => 'www.url.com/url1',
'URL2' => 'www.url.com/url2',
'URL3' => 'www.url.com/url3',
];
What I did(workaround) !!
<?php
return[
'URL1' => env('BASE_URL')'/url1',
'URL2' => env('BASE_URL')'/url2',
'URL3' => env('BASE_URL')'/url3',
];
I would like to know, is this the only solution or are any other better way. I would like to move every settings to the config file.
I had the same questoin while I was creating a laravel package. Hope an alternative solution could also be used for package development.
A:
As I understood you correctly you want to have one base url in your config file and use that for other config variables in the same file. Since config files are .php you can use something like:
In config/url.php:
<?php
$baseURL = 'http://www.example.com';
return [
'base_url' => $baseURL,
'url1' => $baseURL . '/login',
'url2' => $baseURL . '/about',
];
You can then access the variables using Laravel's dot notation. Remember that the part before the dot is the short name of the config file you used (url.php):
{{ Config::get('url.base_url') }}
{{ Config::get('url.url1') }}
{{ Config::get('url.url2') }}
Will output:
http://www.example.com
http://www.example.com/login
http://www.example.com/about
|
[
"math.stackexchange",
"0000464280.txt"
] | Q:
Probability of $P(A \cup B \cup C)$.
Let $A,B,C$ be events such that:
$P(A) = P(B) = P(C) = \frac{1}{2}$
$P(A \cap B) = P(A \cap C) = P( B \cap C) = \frac{1}{6}$
Determine $P(A \cap B \cap C)$.
I think that it is impossible because I don't know anything about $P(A \cup B \cup C)$.
A:
$$P(A \cup B \cup C) = P(A) + P(B) + P(C) - P(A \cap B) - P(B \cap C) - P(A \cap C) + P(A \cap B \cap C)$$
But $$0 \leq P(A \cup B \cup C) \leq 1$$
Therefore,
$$0 \leq P(A) + P(B) + P(C) - P(A \cap B) - P(B \cap C) - P(A \cap C) + P(A \cap B \cap C) \leq 1$$
What does that give you?
|
[
"stackoverflow",
"0012239320.txt"
] | Q:
error while using subquery in insert operator
I have table with the following structure:
FirstName|MiddleName|PatientID
I want in other table to store all distinct FirstNames. I have Created table named TBL and I want to insert into it all distinct FirstName rows. Let's assume first table name uis TBL1. I tried the following:
INSERT Into TBL(FirstName) VALUES (SELECT DISTINCT FirstName FROM TBL1)
But I've got error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, ! =, <, <= , >, >= or when the subquery is used as an expression.
What am I missing here? I am talking about Microsoft Sql Server 2008 R2.
A:
This should work just fine:
INSERT Into TBL(FirstName)
SELECT DISTINCT FirstName FROM TBL1
VALUES is for the values in a single row.
|
[
"stackoverflow",
"0022765865.txt"
] | Q:
Cannot apply bootstrap styling to an ASP:Button within Sharepoint
I am trying to apply Bootstrap's CSS styles to an ASP:Button and am currently experiencing some CSS conflicts from Sharepoint's corev15.css stylesheet for the button input type:
input[type="button"], input[type="reset"], input[type="submit"], button {
min-width: 6em;
padding: 7px 10px;
border: 1px solid rgb(171, 171, 171);
background-color: rgb(253, 253, 253);
margin-left: 10px;
font-family: "Segoe UI","Segoe",Tahoma,Helvetica,Arial,sans-serif;
font-size: 11px;
color: rgb(68, 68, 68);
}
From what I can tell Bootstrap applies these styles at a lower level (btn btn-primary btn-sm in my case) so the input[type="button"] styles being applied curtosy Sharepoint are taking precedence.
Any ideas on how to prevent this from occuring for my application without potential repurcussions elsewhere via editing Sharepoint's CSS?
I suspect what's needed is some custom CSS within a stylesheet that's rendered after my core bootstrap styles such as bootstrap3-custom.css, but I'm not sure what code would fix this specific issue.
A:
my recommendation is to inspect the button with ie dev toolbar or firebug and check the rendered html for css classes or inline styles.
if css classes exist, use them, otherwise use the button type to a copy of those styles in a separate stylesheet.
use !important if required.
its important to know that there is stylesheet priority, and markup matching priority, so later load stylesheets with more specific assignments will prevail. !important should force anything without further concerns, but use with caution, dont make it a standard
|
[
"workplace.stackexchange",
"0000124767.txt"
] | Q:
Multiple breaches of employer confidentiality
I was recently up for a disciplinary as I failed a drugs test for cannabis.
When the company received the scores back from the testers, they published the three peoples scores on each of the letters we received.
While I was on suspension a colleague from work was telling other staff when we would be receiving a letter.
I was told this and that letter showed up the next day so he was correct.
To add to this, one of the agency staff saw my other colleague who was also on suspension and told him
he knew our scores for the positive test results.
He was correct also.
I know this is breach of confidentiality, but how serious is it.
I want to make the complaint but don't know if I want him sacked if it warrants it.
Can someone tell me how serious this is. The person blabbing was a manager who was sitting in on the disciplinary process, being trained.
A:
You've been disciplined for using drugs and you want to take a few stabs on the way out.
You may want to rethink your priorities, you have some major and immediate problems that this will not fix or help with, and will add at least one bitter enemy to your tally.
|
[
"magento.stackexchange",
"0000232122.txt"
] | Q:
Product custom option delete while edit product programmatically
I have added a custom option in product from the back-end.
After that when I tried to update the product programmatically but Facing an issue: When I edited the product all the custom options of product has been deleted.
It removes all options while editing a product. I have checked all entries in the database that's also get deleted.
A:
Finally I found the solution of this.
Not great solution but it's working fine for me.
I have first getting all options of the product before save.
protected function getProductOptions($productObj)
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customOptions = $objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($productObj);
$options = [];
if($customOptions->count() > 0) {
foreach($customOptions as $customOption) {
$optionsValue = [];
$customOptionValues = $objectManager->get('Magento\Catalog\Model\Product\Option\Value')->getValuesCollection($customOption);
if($customOptionValues->count() > 0) {
foreach($customOptionValues as $customOptionValue) {
$optionsValue[] = array(
'record_id' => $customOptionValue->getRecordId(),
'title' => $customOptionValue->getTitle(),
'price' => $customOptionValue->getPrice(),
'price_type' => $customOptionValue->getPriceType(),
'sort_order' => $customOptionValue->getSortOrder(),
'sku' => $customOptionValue->getSku(),
'is_delete' => 0,
);
}
}
$sku = $customOption->getSku();
$title = $customOption->getTitle();
$type = $customOption->getType();
$price = $customOption->getPrice();
$price_type = $customOption->getPriceType();
$record_id = $customOption->getRecordId();
$options[] = array(
'sort_order' => $customOption->getSortOrder(),
'title' => $title,
'price_type' => $price_type,
'price' => $price,
'type' => $type,
'values' => $optionsValue,
'is_require' => 1,
);
}
}
return $options;
}
After that I have added that all options after save the product.
protected function addProductCustomOptions($product, $productOption)
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product->setHasOptions(1);
$product->setCanSaveCustomOptions(true);
foreach ($productOption as $arrayOption) {
$option = $objectManager->create('\Magento\Catalog\Model\Product\Option')
->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($arrayOption);
$option->save();
$product->addOption($option);
}
}
Now I am getting my all product options same as before.
|
[
"stackoverflow",
"0009298911.txt"
] | Q:
Can I use content negotiation to conditionally serve SVG?
In theory I should be able to see if a browser supports SVG by looking at the accept header, but as far as I can tell no modern browser accurately reports image/svg+xml. Has anyone successfully implemented conditionally serving SVG using content negotiation? It feels like a bit of a mirage...
A:
Browsers are trying to minimise the size of the http headers they send as they contribute overhead to every request. There are other better ways to figure out if a browser supports SVG e.g. modernizer
|
[
"stackoverflow",
"0021751503.txt"
] | Q:
Struts2 redirectAction is not https?
One of my result mapping type is a "redirectAction" in struts.xml
which when executed constructs a NON secure link... Why is that?
i wanted to constructs secure link using "redirectAction"
what should i do?
<result type="redirectAction" name="auth_stat">
<param name="actionName">auth_stat</param>
</result>
A:
Use a redirect result
<result type="redirect" name="auth_stat">
<param name="location">https://www.yourserver.com/auth_stat</param>
</result>
|
[
"stackoverflow",
"0011830967.txt"
] | Q:
How to I make a drop down beside a search box that searches the specific field selected in rails?
Okay so im new to this site but this is what I have:
Report.rb
def self.search(search)
if search
where('JOBLETTER_CD_NUMBER LIKE ? AND DATE LIKE? AND CUST LIKE ?', "%#{search}%")
else
scoped
end
end
end
index.html.erb
select_tag "search", options_for_select([ "Job Letter and CD #", "Date", "Cust", "Job", "Date shipped", "Date billed", "Billed by" ], params[:search])
form_tag reports_path, :method => 'get' do
text_field_tag :search, params[:search], :class=> "form-search", :align => "right"
<%= submit_tag "Search", :JOBLETTER_CD_NUMBER => nil, :class => "btn btn-success", :align => "right"
reports controller
def index
@report = Report.paginate(:per_page => 1, :page => params[:page])
@report = Report.search(params[:search]).paginate(:per_page => 1, :page => params[:page])
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @views }
end
end
The only field it will search is the Job Letter and CD # field I need it to allow me to search whatever is selected in the drop down box. Btw I am using bootstrap fro js and css functions.
A:
Your query has 3 placeholders ? but passed only one argument "#{search}" - if you run it like that, what you really should be getting is an exceptions stating
ActiveRecord::PreparedStatementInvalid: wrong number of bind variables (1 for 3) ...
Also, your select_tag is outside the form, so it won't be passed to the controller at all. If you move it into the form, you'd have to rename (e.g. to column) it since the name search is already used by the text field. Then you could pass both the column and the search parameters to your search function to construct the query.
HOWEVER, this is not safe, since nothing prevents a user to pass in any other column by manipulating the post request, and since you can't use placeholders for column names, there's a danger of SQL injection as well.
There are many solutions out there to construct searches, no need to reinvent the wheel. Take a look at the ransack gem. Here's a recent Railscast on how to use it.
|
[
"stackoverflow",
"0052717126.txt"
] | Q:
SSIS Get Date from a File Name
My file is called ... File - 20170101.xlsx
I have the following as a variable
FilePath, data type string, File - 20170101
as a derived column I have
(DT_I8)LEFT(RIGHT(@[User::FilePath],8),4)
I Got this to work, but only gives me part of the values..(only 3 numbers, I need 8)
gives me output of 101.. do I need to save the file name as a different date format? I have tried File - 01012017
I have tried this but it does not work
(DT_I4)LEFT(RIGHT(@[User::FilePath],8),4)
I am trying to get the 20170101, then I was going to add a data conversion to turn it into a date
it does not work..any ideas please
A:
So the value of the variable FilePath is not File - 20170101 as you stated, it is File - 20170101.xlsx right?
Please take care when writing your question.
You can solve these things yourself with just a bit of experimentation.
Firstly,
RIGHT(@[User::FilePath],8)
gives you
101.xlsx
Therefore,
RIGHT(@[User::FilePath],13)
will give you
20170101.xlsx
and
LEFT(RIGHT(@[User::FilePath],13),8)
will give you
20170101
To turn that into a date is trickier.
This explains how to do it
How to convert string in format yyyyMMdd to date using SSIS expression?
|
[
"superuser",
"0000615983.txt"
] | Q:
How to use virtualenv?
Today I saw an example of how virtualenv command is used. It was the following four commands:
virtualenv /tmp/vetest
source /tmp/vetest/bin/activate
pip install ipython-notebook
deactivate
The first command creates /tmp/vetest/ directory in which there are four subdirectories: lib, include, local, bin.
Then we use source. What does it do? As far as I understand it puts me into an virtual environment. Being there allows me to install different stuff (I cannot do it otherwise since I do not have root permissions).
With deactivate I leave the virtual environment. This is what I understand so far.
Few questions remain unclear to me. What this command has to do with Python? Is this command a "standard" for Unix systems? Does virtualenv does something more that just creating new directories? What is /tmp/ directory?
A:
Surprisingly, googling "virtualenv" leads you to the virtualenv documentation. If you want to use it, I suggest at least a quick read-through.
As the name suggests, virtualenv is a tool to create isolated or "virtual" environments for Python. It allows you to set up multiple independent instances for different projects, each with their own modules and even versions of Python. This is useful in a variety of circumstances, not least when you don't have admin access and want to install Python modules. From the docs:
The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.
Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.
Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.
In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).
So there you have it. lib/ is where the modules live. include/ is for headers and other shared stuff. local/ is for stuff that lives outside of the main site-packages`` (in lib/) module home, like your own applications. And finally, bin/` is where executables live.
The /tmp directory is, just as it sounds, a temp directory - used for storing things temporarily. Depending on the system, they may or may not be removed periodically, or when the system is rebooted. Or not, it depends. Your first command created a subdirectory of /tmp called vetest/.
Your second command, source, basically means "run the commands listed in this file". It is a built-in command, part of the shell. The result of this command is to start the virtual environment. You should now see (venv) prefixed to your shell prompt.
Once inside, you used the Python Installer Program, or pip, which is automatically included in every virtualenv. pip communicates with the Python Package Index or PyPI. This is the closest thing the Python community has to a central repository, similar to Perl's CPAN or Ruby's rubygems.org. In your case, pip was looking for the ipython-notebook module, which unfortunately does not exist (the notebook is part of the core IPython installation). Had you run pip install ipython you would have gotten something along the lines of:
Downloading/unpacking ipython
Downloading ipython-0.13.2.zip (6.4MB): 6.4MB downloaded
Running setup.py egg_info for package ipython
Installing collected packages: ipython
Running setup.py install for ipython
Installing ipcluster3 script to /tmp/vetest/bin
Installing irunner3 script to /tmp/vetest/bin
Installing ipcontroller3 script to /tmp/vetest/bin
Installing iptest3 script to /tmp/vetest/bin
Installing pycolor3 script to /tmp/vetest/bin
Installing iplogger3 script to /tmp/vetest/bin
Installing ipengine3 script to /tmp/vetest/bin
Installing ipython3 script to /tmp/vetest/bin
Successfully installed ipython
Cleaning up...
From /tmp/vetest, you could now type ipython3 notebook (assuming you have Python 3, which you should be using anyways) to start the IPython Notebook server, and a session in your browser. Unfortunately, it will fail because you lack a bunch of dependencies like tornado, but these are easily installed using pip. A list of basic dependencies is available on the IPython website. Additional functionality like pylab requires NumPy, SciPy, and matplotlib.
Finally, the deactivate command exits your virtualenv session.
|
[
"stackoverflow",
"0002744640.txt"
] | Q:
Word Automation search in range
This is how I define the find object:
Range rngDoc = m_oDocument.GetContent();
nEnd = rngDoc.GetEnd();
rngDoc.SetRange(nStart,nEnd);//do not search entire document -> faster
Find fn = rngDoc.GetFind();
However, when I execute the Find, it finds objects that lay before the given start.
Any idea how do I define where the find should search?
A:
Solved!
Problem was that the start of the Range was in a table cell and the end was the end of the document. For some reason, Find then searches entire cell, and not from the beginning of the range.
EDIT: It seems that problem occurs whenever there is a table in the range. Does anyone have a solution to this problem?
|
[
"stackoverflow",
"0003249477.txt"
] | Q:
Can an Android process host multiple Dalvik VM's?
Can an Android process ever host multiple Dalvik VM's? If so, what scenarios can cause this to occur, and what would be the benefit of having multiple VM's in the same process?
A:
No, multiple VMs per process is not supported.
|
[
"stackoverflow",
"0020549967.txt"
] | Q:
sending multidimensional objects in c# mvc, and rendering individual attributes, to c# mvc view
I'm not entirely sure I've worded the title to this issue correctly, so firstly my apologies.
I have an issue relating to values (and the count of said values) being rendered from a database query using LINQ within a C# MVC controller to a view. The view is to use the first value as a visible value, then use the second value to determine the CSS applied to the first value's element.
As an example, I have a sequence
1, 1, 1, 2, 2, 4, 5, 5, 5, 3, 3, 4, 4, 2, 2, 2 etc.
and the value of runs for this would be
3, 3, 3, 2, 2, 1, 3, 3, 3, 2, 2, 2, 2, 3, 3, 3 etc.
Each value is to be rendered in a separate div for screen wrapping, but depending on the run of said number will be coloured to reflect there being a run of numbers;
<div style="float:left; background-color:red">1</div> //
<div style="float:left; background-color:red">1</div> // three the same = red
<div style="float:left; background-color:red">1</div> //
<div style="float:left; background-color:yellow">2</div> // two the same = yellow
<div style="float:left; background-color:yellow">2</div> //
<div style="float:left; background-color:green">4</div> // single instance = green
<div style="float:left; background-color:red">5</div> // etc.
etc.
The controller contains an ActionResult:
public ActionResult getDataAndDisplay (int bar)
{
var runOfNumbers = new ???;
using (var foo = new Entities())
{
initialRunOfNumbers = (from n in foo.Numbers
where foo.bar == bar
select n.number).ToArray();
// loop through numbers and get counts set for each number - the code for calculating the run count is sorted
// end result should be pairs of values; number, countOfNumberRun
// assign eventual list(?) of pairs to runOfNumbers
}
return View("numbers", "show", new {RunOfNumbers = runOfNumbers} )
}
And the view simply prints out each number with suitable formatting:
@model NumberRunMachine.Models.NumberRunModel;
//traditional HTML header code, get to body
@foreach(var item in Model.RunOfNumbers)
{
<div class="[email protected]">@item.number</div>
}
CSS:
.run-of-number-style-1
{
background-color:green;
}
.run-of-number-style-2
{
background-color:yellow;
}
.run-of-number-style-3
{
background-color:red;
}
My main issue is how to best collate the numbers and run counts together to send to the view, which allows for rendering the separate aspects of each pair as needed? I've looked at anonymous objects, jagged arrays, multidimensional arrays, lists of arrays (explicit use of ToList() etc.) - and either I'm not getting code right, or there just aren't any intellisense helpers to show which one allows for the granularity I require in the view.
I can get a multidimensional array to send values, but the view doesn't let me pull individual values out. What is the best practice? What am I missing?
EDIT: Adding the model so people get the full MVC :)
public class PageRunModel : Model
{
// I am currently getting all information as a multidimensional array, but can't separate it out
public byte[,] RunOfNumbers { get; set; }
}
A:
An issue you have could be that you are sending an anonymous object as a model at the controller, but the view expects a specific class NumberRunMachine.Models.NumberRunModel.
In order to send data to the view, I can think of 3 alternatives:
1. Use ViewData to send additional data to view
You can use the ViewDataDictionary to send more data to the view, in order to not altering the main model. Suppose you have a UserInfo class that you want to send to the view:
Controller
public ActionResult getDataAndDisplay (int bar)
{
//...
ViewData["userInfo"] = userInfo;
//...
return View("numbers", "show", new NumberRunModel(){RunOfNumbers = runOfNumbers} )
}
View
@{
UserInfo user = ViewData["userInfo"] as UserInfo;
}
<b>User name:</b> @user.Name
<!-- And so on... -->
2. Create a new custom ViewModel class
You can define another ViewModel class just for this view, and add properties as needed:
ViewModel
public class DataDisplayViewModel
{
public UserInfo User { set; get; }
public byte[,] RunOfNumbers { set; get; }
}
Controller
public ActionResult getDataAndDisplay (int bar)
{
//...
return View("numbers", "show", new DataDisplayViewModel(){User = userInfo, RunOfNumbers = runOfNumbers});
}
View
@model DataDisplayViewModel
<!-- ... -->
@for (int i = 0; i < Model.RunOfNumbers.GetLength(0); i++)
{
<div class="[email protected][i,0].ToString()">
@Model.RunOfNumbers[i,1].ToString()
</div>
}
<!-- ... -->
<b>User name:</b> @Model.User.Name
<!-- And so on... -->
3. Use a dynamic model
As of MVC3, you can use a dynamic model for passing an anonymous type's object to views:
Controller
public ActionResult getDataAndDisplay (int bar)
{
//...
return View("numbers", "show", new {User = userInfo, RunOfNumbers = runOfNumbers});
}
View
@model dynamic
<!-- ... -->
@for (int i = 0; i < Model.RunOfNumbers.GetLength(0); i++)
{
<div class="[email protected][i,0].ToString()">
@Model.RunOfNumbers[i,1].ToString()
</div>
}
<!-- ... -->
<b>User name:</b> @Model.User.Name
<!-- And so on... -->
If you are using MVC below version 3, you can check this post: Passing anonymous objects to MVC views and accessing them using dynamic
|
[
"math.stackexchange",
"0002863571.txt"
] | Q:
Continuity and differentiability of elementary functions
Given a single-variable elementary function (not piecewise), I was wondering if it is continuous and differentiable in all of its maximum domain? (Not considering the trivial examples involving absolute value function)
Also by piecewise I mean functions that can only be expressed in a piecewise manner. E.g. $\cos x$ is not considered piecewise, although it can be expressed in a piecewise manner.
I think the definition of elementary function that I’m going for is the one found on wikipedia: https://en.m.wikipedia.org/wiki/Elementary_function
I think it is also required for the function’s domain to at least contain some interval, but I’m not sure.
Actually I know that if an elementary function is differentiable at some point, its derivative at that point is also given by an elementary function, but I am trying to find out if every elementary function is smooth given that it is defined at some point.
I haven’t been able to find anything useful online, so a rigorous proof would be greatly appreciated. Also please try to keep it as simple as possible as my math is bad.
A:
Elementary functions, as usually defined, are continuos in all the domain of definition but not always differentiable. Let consider as an example of elementary functions continuous but not differentiable at a point
$f(x)=\sqrt x$ at $x=0$
$f(x)=\sqrt[3] x$ at $x=0$
$f(x)=\arcsin x$ at $x=1$
|
[
"math.stackexchange",
"0000222671.txt"
] | Q:
Can the convergence of sequence lead to the convergence of function as $x\to+\infty$
When read Zorich's book Mathematical Analysis Vol I, I figure out a question concerning the Theorem 5, Page 133. That is:
Assuming function $f:(0,+\infty)\to\mathbb{R}, \text{ with } \lim\limits_{\mathbb{N}\ni n\to\infty} f(n)=A\in\mathbb{R}\cup\{+\infty,-\infty\},$ where $\mathbb{N}$ is the set of all positive integers. Is it true that $\lim_{x\to+\infty} f(x)=A$?
I guess that it may be true. But I am not so sure. Maybe it is just a corollary of Theorem 5, page 133 of Zorich's Book (see above). Can anyone help me? If it is false, give your counterexample, and if it is true, prove it. Thanks a lot!
A:
No.
Consider $f(x) = \sin \pi x$.
|
[
"stackoverflow",
"0036658331.txt"
] | Q:
Android EditText to int conversation error
This probably the most asked question, but it very difficult to find some answers. First I am newbie. I want to make simple quadratic equation formula app. That would allow to to find solution fast. I bump with the problem that Android Studio say Code is okey, but device crashes after opening app.
private Button mButton;
private EditText mEdit;
private EditText mEdit1;
private EditText mEdit2;
private TextView mText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mButton = (Button)findViewById(R.id.button2);
mEdit = (EditText)findViewById(R.id.editText);
mEdit1 = (EditText)findViewById(R.id.editText2);
mEdit2 = (EditText)findViewById(R.id.editText3);
mText = (TextView)findViewById(R.id.textView4);
//Int definēšana
final int i1 = Integer.parseInt(mEdit.getText().toString());
final int i2 = Integer.parseInt(mEdit1.getText().toString());
final int i3 = Integer.parseInt(mEdit2.getText().toString());
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Mainīgo ievade
int a = i1;
//Pārbauda vai a nav nulle
if (a == 0){
mText.setText(String.valueOf("Nav kvadrātvienādojums"));
} else {
int b = i2;
int c = i3;
//Diskriminanta aprēķināšana
double diskr = (b*b)-4*a*c;
//Kvadrātsakne no diskriminanta
double sd = (double) Math.sqrt(diskr);
//Sakņu aprēķināšana
double x1 = (-b+sd)/(2*a);
double x2 = (-b-sd)/(2*a);
//Rezultāta izvade
if (diskr < 0){
mText.setText(String.valueOf("Kvadrātvienādojumam nav sakņu"));
} else if (diskr == 0){
mText.setText(String.valueOf("Kvadrātvienādojumam ir viena sakne: " + x1));
} else {
mText.setText(String.valueOf("Kvadrātvienādojuma saknes: " + x1 + " un " + x2));
}
}
}
});
}
And logcat that may help detect a problem
FATAL EXCEPTION: main
Process: com.homemade.prtbust.kvadratvienadojums, PID: 4552
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.homem`enter code here`ade.prtbust.kvadratvienadojums/com.homemade.prtbust.kvadratvienadojums.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3133)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.homemade.prtbust.kvadratvienadojums.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:6609)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3086)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
A:
You are not assigning any layout to the Activity, therefore all your EditTexts, Button and TextView are not present, when you try to access any of them by code the program will crash.
Second, you should read the values for your variables when clicking the button, not in the oncreate, because that will cause you another error given that you'll try to parse something that is an empty string (unless you have set a value in the android:text tag in the xml).
I also wouldn't declare them as final (because you won't be able to modify them later.
Try using this code:
private Button mButton;
private EditText mEdit;
private EditText mEdit1;
private EditText mEdit2;
private TextView mText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.button2);
mEdit = (EditText)findViewById(R.id.editText);
mEdit1 = (EditText)findViewById(R.id.editText2);
mEdit2 = (EditText)findViewById(R.id.editText3);
mText = (TextView)findViewById(R.id.textView4);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Int definēšana
int i1 = Integer.parseInt(mEdit.getText().toString());
int i2 = Integer.parseInt(mEdit1.getText().toString());
int i3 = Integer.parseInt(mEdit2.getText().toString());
//Mainīgo ievade
int a = i1;
//Pārbauda vai a nav nulle
if (a == 0){
mText.setText(String.valueOf("Nav kvadrātvienādojums"));
} else {
int b = i2;
int c = i3;
//Diskriminanta aprēķināšana
double diskr = (b*b)-4*a*c;
//Kvadrātsakne no diskriminanta
double sd = (double) Math.sqrt(diskr);
//Sakņu aprēķināšana
double x1 = (-b+sd)/(2*a);
double x2 = (-b-sd)/(2*a);
//Rezultāta izvade
if (diskr < 0){
mText.setText(String.valueOf("Kvadrātvienādojumam nav sakņu"));
} else if (diskr == 0){
mText.setText(String.valueOf("Kvadrātvienādojumam ir viena sakne: " + x1));
} else {
mText.setText(String.valueOf("Kvadrātvienādojuma saknes: " + x1 + " un " + x2));
}
}
}
});
}
|
[
"stackoverflow",
"0009709268.txt"
] | Q:
HTML: Images in columns
How can I produce an HTML/CSS layout similar to this working example: http://mythoughtswouldscareyou.tumblr.com/
I basically want to replicate this general layout. I've tried using <li> with a float: left; attribute, but I know this is not the way to go.
Just a basic outline/explanation of an efficient way to do this would help me out a lot.
A:
Ah, there are tools for this:
http://masonry.desandro.com/index.html
Masonry is a dynamic grid layout plugin for jQuery. Think of it as the
flip-side of CSS floats. Whereas floating arranges elements
horizontally then vertically, Masonry arranges elements vertically,
positioning each element in the next open spot in the grid. The result
minimizes vertical gaps between elements of varying height, just like
a mason fitting stones in a wall.
|
[
"stackoverflow",
"0003702785.txt"
] | Q:
WPF application exits immediately when showing a dialog before startup
Update: I guess, what I need is to understand what is the "correct", "supported" way to show a dialog before application start in WPF.
Here's the code:
public partial class App : Application
{
[STAThread]
public static void Main()
{
var app = new App();
app.InitializeComponent();
new DialogWindow().ShowDialog();
app.Run( new MainWindow() );
}
}
The DialogWindow shows up as expected.
But after closing it, the application exits immediately. MainWindow doesn't show up at all!
I have done some debugging and traced the problem to this:
When the dialog is created, it becomes app's MainWindow, since there is no MainWindow at the moment.
Therefore, closing the dialog causes the application to post ShutdownCallback on the dispatcher queue.
However, the dispatcher doesn't run long enough to execute the callback.
Therefore, once app.Run is called subsequently, the first thing on the queue is ShutdownCallback, which, naturally, causes the app to close immediately.
Given this analysis, there is an obvious workaround: create MainWindow right after App, thus making it app's MainWindow, which would prevent DialogWindow from causing application closure.
However, here is what bothers me.
First, this looks like a dirty hack to me. I mean, there is no explicit reason for creating windows in this order, and I have only found this through some debugging. This can't be the supported way.
Second, this is clearly a bug. I mean, if creating a second window after shutdown wasn't supported explicitly, it should've thrown some InvalidOperationException, right?
Thirdly, not only is this a bug, but it looks like a very naive one, something like a multithreading beginner would create.
All this leads me to believe that maybe I don't get something fundamental here? Maybe I don't make sense at all? Maybe it all should be done in some different fashion?
Here's some background:
The application has to do some bootstrapping on startup. Check this and that, setup exception handlers, logging - you know, the usual stuff. In this process, it may become necessary to ask the user for some help - which is what the dialog is for.
I absolutely don't want to put all that in some kind of state machine that executes on MainWindow.IsVisibleChanged or something like that. I would like to keep it really simple, short and straightforward - the way bootstrap code is supposed to be, so that it's easy to spot bugs with a naked eye.
A:
By default, the ShutdownMode of a WPF application is OnLastWindowClose. In your code you show a single window and then close it. So the last window is closed and the application shuts down. Then while shutting down, you show another window. Since the application is shutting down, the window is immediately closed.
So everything is working as designed and programmed by you.
However, you want to do something different: The window you show first as the only window is supposed to be a "special window", and after closing it you want to continue executing, show your "main window" and then exit the application once it (or all windows associated with the app) closes.
The easiest way: First set the shutdown mode to OnExplicitShutdown, then after showing the main window set it to OnLastWindowClose or OnMainWindowClose. In code:
public static void Main()
{
var app = new App();
app.InitializeComponent();
app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
new DialogWindow().ShowDialog();
var mainWindow = new MainWindow();
app.MainWindow = mainWindow;
app.Run(mainWindow);
// When the window has loaded, it should then set the app.ShutdownMode to what you actually want.
}
EDIT:
I am not sure what exactly you are doing. The code you gave will not compile, since when properly using a WPF application class (with an App.xaml build-action as ApplicationDefinition), a Main method is already defined. If you just have a class derived from Application, you have no InitializeComponent() method. The only way to get you code to compile was by manually changing the build-action to Page. However, in that case, Application.Current == app.
So what occurs is the following:
The application starts. Since no WPF-application has been created so far, Application.Current is null. This also means no dispatcher-loop is running and dispatcher messages are unhandled (note that the dispatcher loop also handles windows messages).
A new App-object is created. Since Application.Current is null, it sets itself as Application.Current.
Application.Current.MainWindow is null and Application.Current.Windows is an empty list.
Since ShutdownMode is OnLastWindowClose, once the last window of the current application (i.e. app) closes, shutdown starts.
The DialogBox is shown modally. Since no dispatcher-loop is running, the ShowDialog() itself runs a "local" dispatcher-loop.
Actually this is two parts: First the window is created. It belongs to the current application, so it adds itself to Application.Current.Windows. Since it is the first window shown and Application.Current.MainWindow is null, it also sets itself as main window. Secondly, the window is shown modally.
Since Application.Current.Windows is now non-empty, once it is empty, shutdown will start.
The user closes the dialog window. As part of being closed, the window removes itself from Application.Current.Windows. Also, since it is the MainWindow, this is set to null. Since Application.Current.Windows is now empty, shutdown starts. However, since there is no dispatcher-loop running, nothing is done yet (only an internal flag or similar is set).
If you had used app.Run(new DialogWindow()); app.Run(new MainWindow());, you would have an exception while creating the MainWindow, since in this case the dispatcher-loop is running properly. Thus, it can actually shutting itself down, so when the MainWindow is created, it throws an exception since the dispatcher-loop is already shut down.
MainWindow is created. As above, it adds itself to Application.Current.Windows and sets itself as Application.Current.MainWindow.
However, the condition for shutting down the application has already been reached. But, so far, the application had no chance to do something.
Now Run() is called. The dispatcher-loop starts again and now has a chance to shutdown the application. So it shuts down the application and closes any open windows.
So again, no bug.
So one way to solve this is to change to OnExplicitShutdown. Then in step 4, no reason for shutting down is reached. Better (as in more like a normal WPF application) would be to have a proper ApplicationDefinition. Remove the StartupUri from the App.xaml and instead handle the Startup event:
private void OnStartup(object sender, StartupEventArgs e)
{
this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
new DialogWindow().ShowDialog();
var mainWindow = new MainWindow();
this.ShutdownMode = ShutdownMode.OnLastWindowClose; // or OnMainWindowClose
mainWindow.Show();
}
Since we have OnExplicitShudown while closing the dialog window, there is no reason for the application to start shutting down at that point. Then, after creating the MainWindow, we again have a window as main window and as (one of the) application windows. So then we can switch to the shutdown mode we actually want and show the main window.
|
[
"stackoverflow",
"0003664089.txt"
] | Q:
Calculate correct sprite direction image in bird's view game? (Math here might be speed vector to degrees angle?)
Background: I have 8 images for every sprite in my bird's view JavaScript game, representing top, top-right, right, right-bottom etc., depending on the player's space ship speed.
Question: Given the values sprite.speed.x and sprite.speed.y (which could be something like 4 and -2.5, or 2 and 0 for instance), how do I get the correct angle in degrees? Given that angle, I could then have a lookup for which degrees value represents which sprite image. Or perhaps there's an even easier way. (Currently I'm just using something like "if x below zero use left image" etc. which will result in diagonal images used almost all of the time.)
Searching around, I found ...
angle = Math.atan2(speed.y, speed.x);
... but somehow I'm still missing something.
PS: Zero speed can be ignored, these sprites will just use whatever was the last valid direction image.
Thanks so much for any help!
A:
Good question! I liked tom10's answer (on the mark, +1), but wondered if it can be done without much trigonometry. Here's a solution in short, followed by an explanation.
// slope is a constant, 0.414...; calculate it just once
var slope = Math.tan(Math.PI/8);
// do this for each x,y point
var s1 = x * slope + y > 0 ? 0 : 1;
var s2 = y * slope + x > 0 ? 0 : 1;
var s3 = y * slope - x < 0 ? 0 : 1;
var s4 = x * slope - y > 0 ? 0 : 1;
var segment = 4 * s4 + 2 * (s2 ^ s4) + (s1 ^ s2 ^ s3 ^ s4);
This sets the value of segment between 0 and 7. Here's an example with 2000 random points (full source code at the end of the answer). Using the x,y values of the sprite's speed, you can use the segment value to pick up the appropriate sprite image.
Tadaa!
So how does this work? Our segment expression does look a bit cryptic.
Observation one: we want to split the circle around the point into 8 segments of equal angular dimension. 360/8 = 45 degrees per segment. Four of the 8 segments are centered on one of the two sides of the x and y axes, sliced at 45/2 = 22.5 degrees each.
Observation two: The equation of a line on a plane, a*x + b*y + c = 0, when turned into an inequality, a*x + b*y + c > 0 can be used to test on which side of the line a point is located. All our four lines cross the origin (x=0, y=0), and hence force c=0. Further, they are all at a 22.5 degrees angle from either the x or the y axis. This gets us the four line equations:
y = x * tan(22.5); y = -x * tan(22.5);
x = y * tan(22.5); x = -y * tan(22.5)
Turned into inequalities we get:
x * tan(22.5) - y > 0;
x * tan(22.5) + y > 0;
y * tan(22.5) - x > 0;
y * tan(22.5) + x > 0
Testing the inequalities for a given point lets us know on each side of each line it lies:
Observation three: we can combine the test results to obtain the segment number pattern we want. Here's a visual breakdown:
In sequence: 4 * s4, 2 * (s2 ^ s4) and the sum 4 * s4 + 2 * (s2 ^ s4)
(The ^ symbol is the Javascript XOR operator.)
And here is s1 ^ s2 ^ s3 ^ s4, first on its own, and then added to 4 * s4 + 2 * (s2 ^ s4)
Extra credit: can we tweak the calculation to use only integer arithmetic? Yes -- if x and y are known to be integers, we could multiply both sides of the inequalities by some constant (and round off), resulting in completely integer math. (This would be lost, however, on Javascript, whose numbers are always double precision floating point.):
var s1 = x * 414 + y * 1000 > 0 ? 0 : 1;
var s2 = y * 414 + x * 1000 > 0 ? 0 : 1;
var s3 = y * 414 - x * 1000 < 0 ? 0 : 1;
var s4 = x * 414 - y * 1000 > 0 ? 0 : 1;
Full source code for our sample above: (just drop it in a new html file, and open in any browser)
(see as a live demo on jsbin)
<html>
<head>
<style type="text/css">
.dot { position: absolute; font: 10px Arial }
.d0 { color: #FF0000; }
.d1 { color: #FFBF00; }
.d2 { color: #7fcc00; }
.d3 { color: #00FF7F; }
.d4 { color: #00FFFF; }
.d5 { color: #5555FF; }
.d6 { color: #aF00FF; }
.d7 { color: #FF00BF; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $canvas = $("#canvas");
var canvasSize = 300;
var count = 2000;
var slope = Math.tan(Math.PI/8);
$canvas.css({ width: canvasSize, height: canvasSize });
for (var i = 0; i < count; ++i) {
// generate a random point
var x = Math.random() - 0.5;
var y = Math.random() - 0.5;
// draw our point
var $point = $("<div class='dot'></div>")
.css({
left: Math.floor((x + 0.5) * canvasSize) - 3,
top: Math.floor((y + 0.5) * canvasSize) - 6 })
.appendTo($canvas);
// figure out in what segment our point lies
var s1 = x * slope + y > 0 ? 0 : 1;
var s2 = y * slope + x > 0 ? 0 : 1;
var s3 = y * slope - x < 0 ? 0 : 1;
var s4 = x * slope - y > 0 ? 0 : 1;
var segment = 4 * s4 + 2 * (s2 ^ s4) + (s1 ^ s2 ^ s3 ^ s4);
// modify the point's html content and color
// (via its CSS class) to indicate its segment
$point
.text(segment)
.addClass("d" + segment);
}
});
</script>
</head>
<body>
<div id="canvas" style="position: absolute; border: 1px solid blue">
</div>
</body>
</html>
A:
What you suggest is exactly right! Note that the result of Math.atan2 is in radians, and you're probably more familiar with degrees; you can convert using angle_degrees = angle*(180./pi).
(Note also that you don't need to normalize as RCIX suggested, though you can if you want to. What you have, angle = Math.atan2(speed.y, speed.x);, should work just fine.)
|
[
"stackoverflow",
"0017770376.txt"
] | Q:
Using EXEC command as INSERT VALUE in SQL
I want to be able to do something like this:
My stored proc will always return a number (tinyint)
INSERT INTO CustomerSelections
([draw_date]
,[val1]
,[val2]
,[val3]
,[val4]
,[val5]
,[val6])
VALUES
(
'2013-07-05'
,EXEC GenerateRandomNumbers 1, 49, 1, 0
,EXEC GenerateRandomNumbers 1, 49, 1, 0
,EXEC GenerateRandomNumbers 1, 49, 1, 0
,EXEC GenerateRandomNumbers 1, 49, 1, 0
,EXEC GenerateRandomNumbers 1, 49, 1, 0
,EXEC GenerateRandomNumbers 1, 49, 1, 0
)
But i am not aware of how to get the values in there?
UPDATE:
I tried something like this:
I put the passed values into a stored proc called:
ALTER PROCEDURE [dbo].[GetUniqueLottoNumber]
AS
BEGIN
DECLARE @return_value int
EXEC @return_value = [dbo].[GenerateRandomNumbers]
@StartNumber = 1,
@EndNumber = 49,
@QuantityToOutput = 1,
@AllowDuplicates = 0
END
Then did this:
CREATE TABLE #tmp (Number TINYINT)
DECLARE @q nvarchar(4000)
DECLARE @return_value int
SET @q = 'EXEC @return_value = [dbo].[GetUniqueLottoNumber]';
INSERT INTO #tmp (Number)
EXEC sp_executesql @q
But it doesnt like it when i put @q in the insert values.
A:
why do you need to call the procedure 6 times? Why can't call the SP with a parameter of how many responses do you want?
anyway try something like this.
DECLARE @val1 INT
DECLARE @val2 INT
DECLARE @val3 INT
DECLARE @val4 INT
DECLARE @val5 INT
DECLARE @val6 INT
EXEC @val1 = GenerateRandomNumbers 1, 49, 1, 0
EXEC @val2 = GenerateRandomNumbers 1, 49, 1, 0
EXEC @val3 = GenerateRandomNumbers 1, 49, 1, 0
EXEC @val4 = GenerateRandomNumbers 1, 49, 1, 0
EXEC @val5 = GenerateRandomNumbers 1, 49, 1, 0
EXEC @val6 = GenerateRandomNumbers 1, 49, 1, 0
INSERT INTO CustomerSelections
([draw_date]
,[val1]
,[val2]
,[val3]
,[val4]
,[val5]
,[val6])
VALUES
(
'2013-07-05'
,@val1
,@val2
,@val3
,@val4
,@val5
,@val6
)
|
[
"unix.stackexchange",
"0000308463.txt"
] | Q:
I am trying to finding the files and to print ONLY size of those files
I am trying to finding the files and to print the size of that files
# find . -name "*.req" -size +1000c -mtime +1 -exec 'awk "{print $5}" "{}"' \;
OUTPUT:
find: awk "{print $5}" "./l16696092.req": No such file or directory
find: awk "{print $5}" "./l16696113.req": No such file or directory
find: awk "{print $5}" "./l16696114.req": No such file or directory
find: awk "{print $5}" "./l16696099.req": No such file or directory
find: awk "{print $5}" "./l16696096.req": No such file or directory
find: awk "{print $5}" "./l16696116.req": No such file or directory
find: awk "{print $5}" "./l16696100.req": No such file or directory
find: awk "{print $5}" "./l16696117.req": No such file or directory
But above files exist in that location.
# ls -lrt l16696092.req
-rw-r----- 1 applgrnt dba 1595 Sep 5 10:35 l16696092.req
A:
Others showed how to get the file sizes, here's the cause of your strange error:
Because of the single quotes, this part
find ... -exec 'awk "{print $5}" "{}"' \;
gives find three parameters, -exec, ; and the middle one that contains awk "{print $5}" "{}". The {} is replaced with the current file name, say ./l16696092.req, resulting in awk "{print $5}" "./l16696092.req". Since that was the first parameter to the -exec, it's taken as the name of the command to run spaces, quotes and all. Hence the errors.
find -exec works better without the outer level of quotes:
find ... -exec awk '{print $5}' {} \;
But this, of course will run awk to read the (contents of the) files found by find, not get their sizes. (We still need to quote the $ in $5 with single-quotes or a backslash, so that the shell doesn't try to expand it.)
A:
With GNU find(1):
find . -name '*.req' -type f -size +1000c -mtime +1 -printf "%s\n"
With BSD find(1) and BSD stat(1):
find . -name '*.req' -type f -size +1000c -mtime +1 -exec stat -f %z {} +
|
[
"stackoverflow",
"0007890076.txt"
] | Q:
Access to cell values of a DataGrid in WPF?
We have such a scenario that we have a page including a DataGrid, and now we want to get all data from this DataGrid, but without accessing to the underlying item source of it, i.e., we want to access to the data directly from the DataGrid. It seems to be tricky but not impossible. I found many articles, like this: DataGridHelper, and this: Get WPF DataGrid row and cell, and many other ones. They are basically the same thing: to define the extension methods on DataGrid with help of another GetVisualChild function to find the target DataGridCell object. However, when I am using it, I can't find the target cell. Specifically, Each row in the DataGrid corresponds to one item from a collection of the DataContext, let's say, it is a collection of type "Employee", and each column of the DataGrid corresponds one property of class Employee, e.g, the Name, Gender, Age. Now my problem is, the above-mentioned GetCell() function always finds a DataGridCell with one Employee object as its content (the property of Content in DataGridCell), and can't go further into each property, no matter what column index I give it.
For example, in the GetCell function, there is one line:
Dim cell As DataGridCell = DirectCast(presenter.ItemContainerGenerator.ContainerFromIndex(column), DataGridCell),
where the presenter is a DataGridCellsPresenter I got which representing the row I choose, and as soon as I give the column index, naturally I am expecting it to return the control for selected property at position I specified. But it just doesn't work as expected. Any help would be appreciated!
A:
The moment you use presenter.ItemContainerGenerator.ContainerFromIndex you fall into a limitation for it to work ONLY for non-virtualized items i.e. rows that are shown in the scroll view (plus some offset number of rows above and below the scroll view limits) of the datagrid.
For you to access values of all cells you will have to execute column level bindings for each row.
Access the DataGrid.Items collection. This is a view of items so any items hidden by filter criteria or custom paging etc will be excluded. If you dont want that then do DataGrid.ItemsSource.Cast<object>().ToList() call.
Now access all columns of the datagrid i.e. DataGrid.Columns. Assuming that they are of any type but DataGridTemplateColumn, step 3 below will extract the cell level value. For template columns you will have to specify some property value that represents the entire template of the cell. I find DataGridTemplateColumn.SortMemberPath a good candidate for this.
Extract the DataGridTextColumn.Binding, DataGridCheckBoxColumn.Binding, DataGridComboBoxColumn.SelectedValueBinding or DataGridComboBoxColumn.SelectedItemBinding. Then for each item from step 1, execute the binding to extract the value.
Code
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string gridContent = string.Empty;
foreach(var item in MyDataGrid.Items)
{
foreach (var column in MyDataGrid.Columns)
{
var textCol = column as DataGridTextColumn;
var checkCol = column as DataGridCheckBoxColumn;
var comboCol = column as DataGridComboBoxColumn;
var templateCol = column as DataGridTemplateColumn;
if (textCol != null)
{
var propertyName = ((Binding)textCol.Binding).Path.Path;
var value
= item.GetType().GetProperty(
propertyName).GetValue(
item,
new object[] {});
if (((Binding)textCol.Binding).Converter != null)
{
value
= ((Binding)checkCol.Binding).Converter.Convert(
value,
typeof(object),
((Binding)checkCol.Binding).ConverterParameter,
((Binding)checkCol.Binding).ConverterCulture);
}
gridContent = gridContent + "\t" + value.ToString();
}
if (checkCol != null)
{
var propertyName = ((Binding)checkCol.Binding).Path.Path;
object value
= item.GetType().GetProperty(
propertyName).GetValue(
item,
new object[] { });
if (((Binding)checkCol.Binding).Converter != null)
{
value
= ((Binding)checkCol.Binding).Converter.Convert(
value,
typeof(object),
((Binding)checkCol.Binding).ConverterParameter,
((Binding)checkCol.Binding).ConverterCulture);
}
gridContent = gridContent + "\t" + value.ToString();
}
if (comboCol != null)
{
var propertyName = string.Empty;
if (comboCol.SelectedValueBinding != null)
{
propertyName
= ((Binding)comboCol.SelectedValueBinding).Path.Path;
}
else if (!string.IsNullOrEmpty(comboCol.SelectedValuePath))
{
propertyName = comboCol.SelectedValuePath;
}
else if (!string.IsNullOrEmpty(comboCol.DisplayMemberPath))
{
propertyName = comboCol.DisplayMemberPath;
}
var value = item.GetType().GetProperty(
propertyName).GetValue(
item,
new object[] { });
if (comboCol.SelectedValueBinding != null
&& ((Binding)comboCol.SelectedValueBinding).Converter != null)
{
var bnd = (Binding)comboCol.SelectedValueBinding;
value
= bnd.Converter.Convert(
value,
typeof(object),
bnd.ConverterParameter,
bnd.ConverterCulture);
}
gridContent = gridContent + "\t" + value.ToString();
}
if (templateCol != null)
{
var propertyName = templateCol.SortMemberPath;
var value
= item.GetType().GetProperty(
propertyName).GetValue(
item,
new object[] { });
gridContent = gridContent + "\t" + value.ToString();
}
}
gridContent = gridContent + "\n";
}
MessageBox.Show(gridContent);
}
}
|
[
"apple.stackexchange",
"0000025972.txt"
] | Q:
Record / playback keystrokes
There are 3rd party apps but I'm not interested in those. I'm a web developer and during testing I find myself entering login credentials over and over again. If I could quickly "play" these keystorkes it would help my sanity. I'm assuming Automator can do this? I've never used Automater so a complete answer for that would be appreciated. However I would prefer something even more native if it's possible.
A:
Let me start by saying that there are lots of good third party apps for automatically logging in to web forms. I highly recommend using one of those.
To answer your question: Yes, you can do this with a combination of Automator and AppleScript. Here's how.
Open Automator. Go to File-> New. Select Service.
Type applescript into the search bar near the top left.
Drag the Run AppleScript item to the area on the right.
Replace the purple code that starts in the box with this:
tell application "System Events"
keystroke "username"
keystroke tab
keystroke "password"
end tell
Now replace the username text with your username, and replace the password text with your password.
This will have the computer type your username, hit tab, and type your password.
Now, at the top of the Automator window, set Service receives to no input and in to the app you need this to happen in.
Automator shoud now look like this:
Save this and give it a name. Now, go to the app you selected at the top right and put your cursor in the username field.
Go to the app's menu (next to the Apple menu) and choose Services-> {what you named your Automator app}.
It should run the Automator workflow and 'play back' the keystrokes.
Again, this is the hard, insecure way. I highly recommend apps like 1Password and LastPass.
|
[
"stackoverflow",
"0007455656.txt"
] | Q:
Setting PHP cookie from dropdown menu
I have a PHP script designed to allow users to decide which language a page is displayed in. The information is stored in a cookie and then read when needed to display the correct content.
Currently, I use an HTML dropdown box to allow the user to select the language and then they must press the form submit button to set the cookie. How can I make it so when they select the language in the dropdown menu it automatically selects that and submits the form? I hope you can understand my question.
My current PHP code is:
<?php
$user_lang = null;
if (isset($_POST["setc"])) {
$expire = time() + 60 * 60 * 24 * 30;
setcookie("mycookie", $_POST["sel"], $expire);
header("location: " . $_SERVER["PHP_SELF"]);
} else if (isset($_COOKIE["mycookie"])) {
$user_lang = $_COOKIE["mycookie"];
}
?>
<meta charset='utf-8'>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<select name="sel" size="1">
<option value="en"<?php echo (!is_null($user_lang) && $user_lang === "en" ? " selected" : ""); ?>>English</option>
<option value="es"<?php echo (!is_null($user_lang) && $user_lang === "es" ? " selected" : ""); ?>>Español</option>
<option value="fr"<?php echo (!is_null($user_lang) && $user_lang === "fr" ? " selected" : ""); ?>>Français</option>
<option value="de"<?php echo (!is_null($user_lang) && $user_lang === "de" ? " selected" : ""); ?>>Deutsch</option>
</select>
<input name="setc" value="save setting" type="submit">
</form>
A:
Change your select tag to:
<select name="sel" size="1" onchange="this.form.submit();">
to make the form submit when users selects a language.
If you wish to do that without JavaScript you can use multiple submit buttons method instead:
<input name="set_language[en]" value="English" type="submit">
<input name="set_language[es]" value="Español" type="submit">
<input name="set_language[fr]" value="Français" type="submit">
<input name="set_language[de]" value="Deutsch" type="submit">
Processing this form is simple as it is:
if (isset($_POST["set_language"])) {
$language = key($_POST["set_language"]);
// $language contains user-selected language code now
}
This can't be done with a select field but without JavaScript or any other client-side scripting language.
A:
You need to do it using JavaScript:
<select name="sel" size="1" onchange="this.form.submit();">
Or if you use jQuery:
$("select[name='sel']").change(function() {
$(this).parent().submit();
});
This will submit the form whenever a user changes value in the dropdown list.
|
[
"magento.stackexchange",
"0000115586.txt"
] | Q:
Add product to quote skips product randomly
I need to create an order with more than 60 products programmatically but it seems like Magento skips some(around 3 or 4) products randomly. I think it's a problem with itemsCollection of _quote but I have no idea what's wrong with my code. On repeated requests it skips different products. I disabled/deleted cache, reindexed everything.
Here's a snippet of my code:
$this->_quote = Mage::getModel( 'sales/quote' );
//assign customer, address code here
foreach($products as $product){
//add custom options
$buyRequest = array(
'product_id' => $product->getId(),
'qty' => $req['Quantity']
);
$product_request = $this->_getProductRequest( $buy_request );
$quote_item = $this->_quote->addProduct( $product, $product_request );
if( is_string( $quote_item ) ) {
//code never enters this if
throw new Exception( $quote_item );
}
}
$itemsCount = count($this->_quote->getItemsCollection());
//for more than 60? items it seems like skips some products randomly
//continue with order create process
No error or exception message is generated, order gets created with success. Another strange thing is that when I use PHPStorm's debugger and place a breakpoint inside foreach, all products get added to quote without any problem. Is there some sort of asynchronousness or collection caching in quote addProduct proccess?
LE: I'm using magento 1.9
A:
Solved
The problem was in my code where I was generating a random string for each product and add it as custom option to differentiate the products in cart. That random string was not unique, so if for any two products that random string was the same, the quantity for the first of products added to cart was increased.
I solved it by adding a counter variable to the random string so that each random string is unique for that cart
|
[
"math.stackexchange",
"0003657080.txt"
] | Q:
If $x$ is real find the maximum possible value of $10^x-100^x$
According to the person who gave this question it apparently has something to do with the range of a quadratic expression. But I can't see the connection with a quadratic equation.
So I tried to solve this by finding the maxima of the expression.
But I don't know how to do it as it's an exponential function.
All I can infer from this is that $x$ must be negative.
A:
$$F(x)=10^x-100^x=10^x(1-10^x)$$
Let $$f(a)=a(1-a)$$
$$f'(a)=1-2a$$
the maximum of $ f(a) $ is $$ f(\frac 12)=\frac 14.$$
Thus, the maximum of $ F(x) $ is $ \frac 14 $ attained for $ x$ such that
$$10^x=\frac 12 = e^{x\ln(10)}$$
|
[
"math.stackexchange",
"0001092693.txt"
] | Q:
Proof of Andrica when Assuming Oppermann
Proof of Andrica's conjecture by assuming Oppermann's conjecture.
Oppermann's conjecture:
$$n\geq2\wedge\pi\left(n^{2}-n\right) < \pi\left(n^{2}\right) < \pi\left(n^{2}+n\right).$$
Andrica's conjecture:
$$i\geq2\wedge\sqrt{p_{i+1}}-\sqrt{p_{i}}<1.$$
Insert Gottfried Helms' nice proof here$\ \ \Box$
A:
[update]: Upps, I see that while I'm just writing @Dan has undeleted his earlier answer. So priority (and thus also the bounty) is at Dan's, of course
I) Let's look at some examples due to Oppermann's consideration:
$$ \small \begin{array}{} m_{13}=13^2=169 & a_{13} = 169-13+1=157 & b_{13}=169+13-1 = 181 \\
m_{14}=14^2=196 & a_{14} = 196-14+1=183 & b_{14}=196+14-1 = 209 \\
m_{15}=15^2=225 & a_{15} = 225-15+1=211 & b_{15}=225+15-1 = 239 \\
\end{array}$$
or , written more compactly
$$ \small \begin{array}{}
m_{13}: & 157...168 & 169 &170... 181 \\
m_{14}: & 183...195 & 196 & 197... 209 \\
m_{15}: & 211...224 & 225 & 226...239 \\
\end{array}$$
We can see that the intervals for consecutive $m_k$ cover the integers except the numbers $n^2$, $n^2+n$ etc, which by definition are not prime.
Oppermann's conjecture is true, if in each of the intervals is at least one prime.
II) But because the intervals follow each other immediately, we can also look at the two intervals between the two consecutive squares $n^2$ and $(n+1)^2$.
$$ \small \begin{array} {rrrrr}
n^2 & \big[(n^2+1) \cdots (n^2+n-1)\big] & (n^2+n) & \big[(n^2+n+1) \cdots ((n+1)^2-1) \big] & (n+1)^2 \\
\end{array}$$
The endpoints $n^2$ , $(n+1)^2$ and the center $n^2+n = (n+1)^2-(n+1)$ are not prime by construction, so the maximal distance between two primes can - assuming Oppermann - at most be $((n+1)^2-1) - (n^2+1)$.
III) Now express the inner neighbours of the two endpoints as $p_0 = n^2+1$ and $p_1=(n+1)^2-1$ which mark the greatest possible distance between two numbers in that interval , then we can refer to the Andrica-formulation $\sqrt{p_1} - \sqrt{p_0}<1$ as
$$ \sqrt{((n+1)^2-1)} - \sqrt{(n^2+1)}\lt 1$$
But this is with a small $\small 0 \le \delta \lt 1$ and thus $\small \sqrt{n^2+1} \sim n+\delta $ and $ \small \sqrt{(n+1)^2-1} \sim (n+1)-\delta $
$$ \big((n+1)-\delta \big) - \big(n +\delta \big) = 1 - 2 \delta \lt 1$$
and thus always (for $n$ greater than some small value, perhaps even if greater than 1) true.
IV) From this follows, that Oppermann's conjecture implies Andrica's conjecture
|
[
"math.stackexchange",
"0003516614.txt"
] | Q:
Find tangent plane for z=y*f(x/y)
So I'm kinda new to partial derivatives and I'm supposed to find the tangent plane for $z=yf\left ( \frac{x}{y} \right )$ but I'm kinda thrown off by the $f\left ( \frac{x}{y} \right )$ part when it comes to finding the partial derivatives.
$\frac{\partial z }{\partial x} = 0\cdot f\left ( \frac{x}{y} \right )+ \left ( \frac{\partial f }{\partial x} \cdot \frac{1}{y} \right )\cdot y = \frac{\partial f }{\partial x}$
$\frac{\partial z }{\partial y} = 1\cdot f\left ( \frac{x}{y} \right )+ \left ( \frac{\partial f }{\partial y} \cdot \frac{-x}{y^2} \right )\cdot y = \frac{\partial f }{\partial y}\cdot \frac{-x}{y}+f\left ( \frac{x}{y} \right )$
is what I'm getting but I'm not sure whether it's right.
A:
One nitpick. The function $f$ is a function of a single variable, so $\partial f/\partial x$ and $\partial f/\partial y$ do not make sense here -- only $f'$. So if $z = yf(x/y)$, we have $$\frac{\partial z}{\partial x}(x,y) = f'\left(\frac{x}{y}\right) \quad \mbox{and} \quad \frac{\partial z}{\partial y}(x,y) = f\left(\frac{x}{y}\right) - \frac{x}{y}f'\left(\frac{x}{y}\right).$$
|
[
"stackoverflow",
"0062042362.txt"
] | Q:
Browser tab freezes after using useState hook in React
I have a blog app and it worked perfectly before I have added the user login feature. After that useState hook methods freeze the application tab in the browser. I am not sure what the problem is, I am guessing it has something to do with re-rendering.
Here is my App.js
import React, { useState, useEffect } from 'react'
import Header from './components/Header'
import Filter from './components/Filter'
import AddNewBlog from './components/AddNewBlog'
import Blogs from './components/Blogs'
import blogService from './services/blogs'
import Notification from './components/Notification'
import Button from './components/Button'
import LoginForm from './components/LoginForm'
import loginService from './services/login'
import './App.css'
const App = () => {
const [ blogs, setBlogs] = useState([])
const [ newTitle, setNewTitle ] = useState('')
const [ newAuthor, setNewAuthor ] = useState('')
const [ newUrl, setNewUrl ] = useState('')
const [ newLike, setNewLike ] = useState('')
const [ blogsToShow, setBlogsToShow] = useState(blogs)
const [ message, setMessage] = useState(null)
const [ notClass, setNotClass] = useState(null)
const [ username, setUsername ] = useState('')
const [ password, setPassword ] = useState('')
const [ user, setUser ] = useState(null)
useEffect(() => {
blogService
.getAll()
.then(initialBlogs => {
setBlogs(initialBlogs)
console.log(initialBlogs)
setBlogsToShow(initialBlogs)
})
.catch(error => {
showMessage(`Error caught: ${error}`, 'error')
})
}, [])
useEffect(() => {
const loggedUserJSON = window.localStorage.getItem('loggedBlogappUser')
if (loggedUserJSON) {
const user = JSON.parse(loggedUserJSON)
setUser(user)
blogService.setToken(user.token)
}
})
const handleLogin = async (e) => {
e.preventDefault()
try {
const user = await loginService.login({
username, password,
})
window.localStorage.setItem('loggedBlogappUser', JSON.stringify(user))
blogService.setToken(user.token)
setUser(user)
setUsername('')
setPassword('')
} catch (error) {
showMessage('wrong credentials', 'error')
}
}
const handleLogout = () => {
console.log('logging out')
setUser(null)
window.localStorage.clear()
}
const handleAddClick = (e) => {
e.preventDefault()
if(newTitle === '') {
alert("Input Title")
}
else if (newAuthor === '') {
alert("Input Author")
}
else if (newUrl === '') {
alert("Input Url")
} else {
let newObject = {
title: newTitle,
author: newAuthor,
url: newUrl,
likes: 0
}
console.log('step0');
blogService
.create(newObject)
.then(returnedBlog => {
setBlogs(blogs.concat(returnedBlog))
setBlogsToShow(blogs.concat(returnedBlog))
resetForm()
showMessage(`Added ${newTitle}`, 'success')
})
.catch(error => {
console.log(error.response.data)
showMessage(`${error.response.data.error}`, 'error')
})
//}
}
}
const handleDeleteClick = (id, title) => {
let message = `Do you really want to delete ${title}?`
if(window.confirm(message)){
blogService
.deleteBlog(id)
.then(res => {
setBlogs(blogs.filter(b => b.id !== id))
setBlogsToShow(blogs.filter(b => b.id !== id))
})
.catch(error => {
showMessage(`${title} has already been removed from the server`, 'error')
})
}
}
const handleLikeClick = (blog) => {
const updatedObject = {
...blog,
likes: blog.likes += 1
}
blogService
.update(updatedObject)
.then(() => {
setBlogs(blogs)
showMessage(`You liked ${updatedObject.title}`, 'success')
})
}
const resetForm = () => {
setNewTitle('')
setNewAuthor('')
setNewUrl('')
setNewLike('')
document.getElementById('titleInput0').value = ''
document.getElementById('authorInput0').value = ''
document.getElementById('urlInput0').value = ''
}
const showMessage = (msg, msgClass) => {
setMessage(msg)
setNotClass(msgClass)
setTimeout(() => {
setMessage(null)
setNotClass(null)
}, 5000)
}
const handleFilterOnChange = (e) => {
const filtered = blogs.filter(blog => blog.title.toLowerCase().includes(e.target.value.toLowerCase()))
setBlogsToShow(filtered)
//setBlogs(filtered)
}
const handleAddTitleOnChange = (e) => {
console.log(e.target.value)
console.log(newTitle)
setNewTitle(e.target.value)
}
const handleAddAuthorOnChange = (e) => {
setNewAuthor(e.target.value)
}
const handleAddUrlOnChange = (e) => {
setNewUrl(e.target.value)
}
if (user === null) {
return (
<div>
<Header text={'Bloglist'} />
<Notification message={message} notClassName={notClass} />
<LoginForm
handleLogin={handleLogin}
username={username}
setUsername={setUsername}
password={password}
setPassword={setPassword}
/>
</div>
)
}
return (
<div>
<Header text={'Bloglist'} />
<Notification message={message} notClassName={notClass} />
<p>{user.name} logged in</p><Button text={"logout"} handleClick={handleLogout} />
<AddNewBlog
handleAddTitleOnChange={handleAddTitleOnChange}
handleAddAuthorOnChange={handleAddAuthorOnChange}
handleAddUrlOnChange={handleAddUrlOnChange}
handleAddClick={handleAddClick}
/>
<Filter handleFilterOnChange={handleFilterOnChange} />
<Blogs blogs={blogsToShow} handleDeleteClick={handleDeleteClick} handleLikeClick={handleLikeClick} />
</div>
)
}
export default App
Anytime I call anyone of these methods: "setNewTitle, setNewAuthor, setNewUrl, setBlogsToShow", after logging in, the tab of the browser freezes. I tried with Chrome and FireFox.
Thank you for your help.
A:
The issue is with your useEffect
useEffect(() => {
const loggedUserJSON = window.localStorage.getItem('loggedBlogappUser')
if (loggedUserJSON) {
const user = JSON.parse(loggedUserJSON)
setUser(user)
blogService.setToken(user.token)
}
})
It is executed on each re-render since it has not been provided any dependency and so it send the app in an infinite loop as it itself triggers a re-render. So when you call any state updater, this useEffect is triggered causing you tab to freeze
You can make this useEffect run once on initial render by passing an empty array to it as dependency
useEffect(() => {
const loggedUserJSON = window.localStorage.getItem('loggedBlogappUser')
if (loggedUserJSON) {
const user = JSON.parse(loggedUserJSON)
setUser(user)
blogService.setToken(user.token)
}
}, [])
|
[
"drupal.stackexchange",
"0000260501.txt"
] | Q:
How do I embed an "EVA" view display in a twig template?
I installed the "Twig Tweak" module for Drupal 8
I created an "EVA" display. The view id is "contenu_relation_groupe" and the display id is "entity_view_1".
I added the following in the twig template for my nodes:
{{ drupal_view('contenu_relation_groupe', 'entity_view_1') }}
But nothing is displayed. Any idea why?
I've never managed to embed an "EVA" view in a twig template.
A:
EVAs get added as a field with name like VIEW_ID_DISPLAY_ID. They should appear in the content variable like any other field.
If you've added your EVA to the node's display you should be able to render your EVA, with the configuration from the Manage Display screen, like
{{ content.contenu_relation_groupe_entity_view_1 }}.
|
[
"history.stackexchange",
"0000034216.txt"
] | Q:
Why did not Spain manage to keep any colonial possessions in the new world?
It is well known that Spain had a huge presence in the colonisation and discovery of the new world. The Spanish empire is one of the largest in history and held vast territory in the Americas.
Still to this day other colonial powers such as France, United Kingdom and the Netherlands maintains control over several islands in the carribean, and even territory on mainland America.
But it seems like Spain lost control of all their former colonies in the Americas, while other nations managed to keep some of theirs. Why?
A:
As observed above, the only American colonies Spain did not lose to independence movements were Cuba and Puerto Rico, which it lost in the Spanish-American War. Worth noticing is the fact that Cuba was a particularly tempting prize for U.S. imperialists influenced by the Monroe Doctrine. The U.S. desire to control Cuba was so great that the eventual Spanish-American War leveraged local discontent to replace one empire with another. Cuba's resources and proximity to Florida made it a target for U.S. expansionism, and acquiring Puerto Rico at the same time was more than convenient.
A:
Spain lost control of its main colonies in America essentially for the same reasons as England lost the US: the colonies liberated themselves. Speaking of the Philippines and small islands, which remained, they were gradually wrestled from Spain by other European countries and the US. It so happened that when the competition for the colonies was fiercest (in 19th century), Spain experienced a decline, and could not compete with the strongest European powers. Portugal, the earliest European colonial power also lost Brazil, it's largest colony.
A:
Note that during the critical early years of Simon Bolivar's independence movement in Venezuela and New Granada Spain was being torn apart by the Peninsular War (1808-1814). Likewise the Hidalgo Movement in Mexico also occurred at this time.
Even after the Peace of Vienna it was some years before Spain was in a position to challenge these independence movements, due to domestic reconstruction being necessary after several years of war.
|
[
"stackoverflow",
"0038258926.txt"
] | Q:
Want to Remove all the Characters Except First character in the word
I am new to c#, i need to trim a sentence which has many words. I need only first characters in all the words. For example
If a sentence is like this.
input : Bharat Electrical Limited => output : BEL
how do i accomplish this in c#?
Thanks in advance
A:
Try
string sentence = "Bharat Electrical Limited";
var result = sentence.Split(' ').Aggregate("", (current, word) => current + word.Substring(0, 1));
EDIT: Here's a brief explanantion:
sentence.Split(' ') splits the string into elements based on space (' ')
.Aggregate("", (current, word) => current + word.Substring(0, 1)); is a linq expression to iterate through every word retrieve above perform an operation on it and
word.Substring(0, 1) returns the first letter of every word
|
[
"german.meta.stackexchange",
"0000000971.txt"
] | Q:
Translation questions from any language to German
On the Area 51 page about German.stackexchenge you can read this:
German Language
Beta Q&A site for students having questions about German, expert speakers of German wanting to discuss the finer points of the language and translation questions from any language to German.
So when I read this, I might think it is ok to ask questions like this:
What is the German translation for the finish word saippuakivikauppias? I've heard, that it is the worlds longest palindrome that is noted in a dictionary.
Auf einer koreanischen Speisekarte ist ein Mann abgebildet. In einer Sprechblase steht 배고파. Was heißt das auf Deutsch?
But when I read the rules in the help center, I can read this:
Translation requests to German should always be of general interest and should provide sufficient context. Please understand that we can not be an individual translation service.
So is it allowed to ask my example-questions? Both of them provide all context that can be given, and »general interest« is a very vague and unclear definition.
Shouldn't there be a more precise definition which translation-requests are allowed? Shouldn't there be a note on Area 51, that not every translation-request is on-topic?
A:
TL;DR: Translation requests to German should not be about understanding the meaning of a word or phrase from another language but sufficiently describe this meaning – we can only translate what we understand.
There is hardly any difference between the following:
A request for a single word or phrase that has a certain given meaning.
A request for the German equivalent of a given word of another language, if the word has a sufficiently clear and narrow meaning or the request is further specified for some meaning of the other language’s word.
The only difference between the two is that the desired meaning is not specified directly but by using a word in another language.
The central issue with such translation requests is that they should be about looking for a German word, and not about understanding the meaning of the other language’s word. In the latter case they first belong on the Stack Exchange of the respective language (if one exists). However, if the meaning of a word was successfully identified on another language’s Stack Exchange, this may form the basis of a translation request on our site.
English differs from other languages mainly by being well known amongst the visitors of this site; so if an English word or phrase is is not ambiguous, rare or exotic, it can be expected that a great deal of potential answerers understands it and thus that a further explanation of the word’s meaning is not necessary. With other languages, providing such an explanation is much more important, at least if you want an answer to your question.
That being said, the meaning of some words is very difficult to capture by means of other words (in another or the same language), e.g., the German word Heimat. So, if somebody understands the meaning of such a word and somewhat illustrates the problem of translating it (i.e., what does a dictionary say, etc.), it’s fine by me if they ask about it here. This question may not receive a good answer or take long to do so, but that does not invalidate the question – it’s okay or even good if some questions are difficult.
By the way, we have at least one translation question from a language other than English to German: Wie kann man 気持ちいい am besten auf Deutsch ausdrücken?
So is it allowed to ask my example-questions? Both of them provide all context that can be given, and »general interest« is a very vague and unclear definition.
I would vote to close them. There is no indication that you understand the respective words and it’s not clear to me that a general reference such as a dictionary would not have helped you. If you address these issues, the questions may be acceptable.
|
[
"stackoverflow",
"0038017699.txt"
] | Q:
Yii2 and Bundle Url
How can I get bundle url in a view if it was registered on the layout not in the view itself?
In the layout I have:
use yii\helpers\Html;
use app\assets\LoginAsset;
$bundle = LoginAsset::register($this);
And in the view I do:
<?php
use app\assets\LoginAsset;
$bundle = LoginAsset::register($this);
?>
<img src="<?php echo $bundle->baseUrl; ?>/img/avatar-sign.png" alt="">
But I want to avoid repeating bundle registration, other views use same layout but they do not need the bundle url.
Any ideas?
A:
You should simply use AssetManager::getBundle()
$bundle = Yii::$app->assetManager->getBundle('app\assets\LoginAsset');
|
[
"english.stackexchange",
"0000441138.txt"
] | Q:
In "pedophilia," why philos rather than eros?
Greek carefully distinguishes between philos (non-sexual love) and eros (sexual love). There are 100s of "phile" words (e.g. an audiophile is a person with a non-sexual love of stereo equipment) and almost all of them specifically refer to a non-sexual love of something. Yet "pedophilia," and fetishes such as Agalmatophilia (sexual arousal to statues), also end in "phile" rather than the accurate term "eros". Does anyone know why?
One theory I’ve come across is that the term “pedophile” was coined by pederasts themselves in an attempt to whitewash their image, but I’ve unable to locate any substantiation for this claim. My own hunch is that the term pedophilia was a euphemism coined by some very well mannered victorians who found "pedo-erotic" too explicit for polite conversation. But that's just a hunch.
Thanks in advance.
A:
I think the second paragraph has some sense of truth in it. In the Netherlands at least there is a very important legal distinction between pedophilia and pedosexuality.
The philia means attraction/love, while -erotic or -sexuality actually means following up on that philia. Whereas the latter is definitely illegal in most states, the former arguably is not. It is after all pretty hard to prove someone has certain feelings.
Here in the Netherlands there were organisations fighting for their right to exist on grounds of being pedophiliacs, instead of pedosexuals, however they lost a case in 2015 at the European Court for Human Rights: (translated from Dtuch)
The European Court for Human Rights has rejected the claims that pedophiliac organisation Martijn made to prevent closure of the organisation. This means the organisation will remain illegal. According to the Strassburg court it was unclear whether the person that requested attorney Spong to file the case, actually represented the organisation.
This caused the case to not make it to court. According to the office of attorney Spong, the European Court has taken a formal stance. "The court implies that a prohibited organisation cannot be represented", attorney Sidney Smeeds says.
According to him, the court in Strassburg had a chance to make a ruling about the freedom of organisation and speech. "In the last weeks, we have seen that in Europe people can be killed for their opinions and in a vulnerable society, even impopular opinions should be representable", according to Smeets. "The European Court had the ideal oppurtunity to have a say about that."
(...)
Last year's April, the [Dutch] High Court ruled that the organisation should be dissolved. The Judge went against an earlier ruling from a lower court. That court ruled that while the opinions and actions of Martijn were rejectable, but did not warrant a prohibition.
The High Court did find a prohibition fitting, "in the interest of protecting the health, rights and freedoms of children.
This does show at least an attempt to place a certain perspective on the term. That is, they suggest that pedophilia is relatable to an opinion rather than an action.
A:
Along with such terms as sadism, masochism, homosexual, bisexual, and gerontophilia, the word pedophilia first appeared in Richard von Krafft-Ebing's pioneering work on the psychology of human sexuality, Psychopathia Sexualis, first published in 1896.
Krafft-Ebing not only chose to title his book in Latin, but also composed more sensitive passages in that language so that discussions of the topic would remain among educated elites, all of whom would have studied Latin and Ancient Greek. In that sense, the word is more academic jargon than strictly speaking a euphemism. Since Krafft-Ebing, like the Greek Stoics before him, believed that any sexual activity outside of procreation was somehow pathological, then the term pedophilia was definitely not coined by an apologist. The Greek term, however, might still be considered a euphemism compared to the German Knabenschänder ‘defiler of boys’ first attested in Martin Luther’s translation of 1 Cor 6.9.
In using the component -philia or -phile to denote sexual excitement or desire directed toward the first part of the compound, Krafft-Ebing follows the lead of the French Belgian psychologist Joseph Guislain, who coined the term necrophilia around 1850 to describe the desecration of corpses for sexual gratification by François Bertrand, a soldier in the French army.
This time, however, the term quickly escaped the academy as Bertrand was reviled in the popular press as le Sergent nécrophile or le Vampire de Montparnasse [Cemetery].
The pattern set by Guislain and Krafft-Ebing remained productive throughout the twentieth century. The Dutch psychologist Frits Bernard, for instance, further refined the concept of pedophilia by coining the term ephebophilia in 1950 to describe an adult sexual attraction to mid- to late adolescents.
Why not Eros?
Modern words crafted from ancient languages are coined to fill a modern need, not to imitate the thought word of the ancients. Neither French, German, nor English preserves the distinction between erotic Eros and the non-erotic Philos, so native speakers of those languages likely feel not great urge to distinguish them either, especially in compound words. And while erato- can function as a prefix, as in eratomania, another modern coinage, I'm not sure how that word could function as the second element of a compound noun. The suffix -phile or -phil, however, had already entered those languages meaning ‘a lover of’, so -philia seemed like a ready solution. Besides, once Guislain or some scholar before him defined -philia to mean sexual attraction/gratification, it was available to his learned colleagues regardless of what long dead Greeks or Romans might have thought of the coinage.
|
[
"stackoverflow",
"0018841795.txt"
] | Q:
Using Perl to read list and format to a customized output file
I have a file with a list, call it tbl.lst:
a
b
c
d
e
I want to create an output file with the items enclosed in parentheses and separated by commas. Can someone show me how to do this in Perl?
Expected output:
MYTABLES=(a,b,c,d,e)
A:
perl -lne 'push @A, $_; END { print "MYTABLES=(", join(",", @A), ")";}' tbl.lst
Given the input file tbl.lst:
a
b
c
d
e
The output is:
MYTABLES=(a,b,c,d,e)
Every space in the Perl script is optional (but it is probably clearer for the spaces).
|
[
"stackoverflow",
"0012573859.txt"
] | Q:
Analyzing correlated data in R: Linear, Ridge regression, PCR
I've got a time series of observations of 5 variables y, x_1, x_2, x_3, x_4 and the task is to find which of the xes are responsible for the changes in y. Now the problem is that all of them are strongly cross-correlated and exhibit collinearity. x_1, x_2, x_3, x_4 don't have hidden components inside which are common to them pairwise or in any other way - they are just naturally correlated.
Predictably, linear regression gives unreasonable results with coefficients changing wildly after removing one of the variables, which is a normal picture for highly-collinear data.
As advised on wiki, some of the remedies for multicollinearity are using ridge regression and principal component regression. However, when I use lm.ridge method, it gives me exactly the same coefficients as lm.
Can PCR help in such a case and if so, what is an easy way in R to retrieve the coefficients and p-values from it? Something like a summary table for lm function.
A:
Have a look at
Dormann et al. (2012). Collinearity: a review of methods to deal with
it and a simulation study evaluating their performance.
paywall, alternative link
for a review of available methods.
R-Code and data is available here :)
|
[
"math.stackexchange",
"0002677979.txt"
] | Q:
How do you solve $(D^2+1)y=4\cos{x}$?
I'm stuck on this question:
$$(D^2+1)y=4\cos{x}$$
where $D^2$ denotes the differential operator $\frac{d^2}{dx^2}$
As far as I know for trig functions, I'm supposed to assume $y=A\sin{x}+B\cos{x}$ and substitute to get $A$ and $B$. But however, for such,
$$(D^2+1)y=0$$
for all values of $A$ and $B$. I don't know what other types of $y$ I should assume. I'm basically clueless here, so any hints would be great.
A:
$$(D^2+1)y=4\cos{x}$$
For $\cos(x)$ function use $(D^2+1)$
$$(D^2+1)^2y=0$$
$$(D^4+2D^2+1)y=0$$
The general solution is
$$y=\color{blue}{y_h}+\color{green}{y_p}$$
$$y=\color{blue}{c_1\cos(x)+c_2\sin(x)}+\color{green}{c_3x\sin(x)+c_4x\cos(x)}$$
Particular solution is therefore $y_p=c_3x\sin(x)+c_4x\cos(x)$
You need to find now the value of the constants $c_3,c_4$
|
[
"blender.stackexchange",
"0000005200.txt"
] | Q:
Sculpting brush tool only makes fancy triangles, no depth
So I want to sculpt on that object I have made, and when I do so, practicaly nothing happens. And then I try with a new project, with the original cube, and the factory settings but still nothing happens. I have dynamic topology enabled, and so when I get into wireframe mode, I can see the fancy triangle, but no depth to them, the brush tool only ads triangle... so if you have any idea of what's going on feel free
sculpt tool http://imageshack.com/a/img600/3905/by1v.jpg
A:
Now it works fine, I didn't change anything, I guess it was some sort of bug. I've had to close the program since the bug occured obviously so I can't provide any sort of example file, if it happens again I'll save it and send it back to you. Anyway thanks for the support!
|
[
"stackoverflow",
"0051581189.txt"
] | Q:
PHP load page only on Included page
I have a process.php page,
<p>This is process page</p>
And I have a index.php page:
<?php include_once 'process.php' ?>
When I type process.php or index.php in web URL both url prints the same result: This is process page.
What I want is,
I want to access this process.php page only when it is included or only from index.php page.
When I type process.php then it should redirect on somewhere else or print nothing.
How can I do that? Any help is appreciated.
A:
This is usually done through a variable, or a constant:
index.php
define('IN_APP', true);
include('process.php'); //APP will be defined
process.php
if (!defined('IN_APP')) {
//You can also add redirects here.
die('Do not access this script directly.');
}
|
[
"stackoverflow",
"0024015211.txt"
] | Q:
How to get filename of the test in mocha reporter
Is there a way to get the filename of current test in mocha reporter?
I couldn't find anything in the base and examples.
A:
Actually, file name is passed to Suite in file field in mocha starting from this pull request. It's just nowadays mocha most commonly is ran as a karma plugin (namely, karma-mocha plugin), and, talking of December'14, this plugin just does not pass file name information further.
To make this answer self-consistent, here's how Suite is formed in mocha (it's tdd implementation, but it it is similar for bdd):
context.suite = function(title, fn){
var suite = Suite.create(suites[0], title);
suite.file = file;
suites.unshift(suite);
fn.call(suite);
suites.shift();
return suite;
};
And here's how suits are formed in karma-mocha/lib/adapter.js:
runner.on('test end', function(test) {
var skipped = test.pending === true;
var result = {
id: '',
description: test.title,
suite: [],
success: test.state === 'passed',
skipped: skipped,
time: skipped ? 0 : test.duration,
log: test.$errors || []
};
var pointer = test.parent;
while (!pointer.root) {
result.suite.unshift(pointer.title);
pointer = pointer.parent;
}
tc.result(result);
});
But you know what, I guess this is a nice thing to issue as a feature request in karma-mocha project.
|
[
"stackoverflow",
"0029936793.txt"
] | Q:
Actionscript 3 : get time to specific timezone (not the computer one)
I have an UTC timestamp and I would like to display the corresponding date and hour in a specific timezone (e.g. France local time) which is not the local timezone of the computer which might be in US. It seems complicated to take into account Daylight saving time.
On Flash/as3 documentation, I only found the Date class which have no function to specify the timezone (only use local time or UTC).
A:
If I understand your problem, flash.globalization.DateTimeFormatter is your solution.
The DateTimeFormatter class provides locale-sensitive formatting for
Date objects and access to localized date field names. The methods of
this class use functions and settings provided by the operating
system.
|
[
"stackoverflow",
"0039435680.txt"
] | Q:
Replace DataSource bean with H2 DataSource at runtime
I'm working on a test framework.
I want to replace a MySQL DataSource bean with one for H2 (that isn't configured as a bean in XML) when some use cases require H2.
Some use cases still use MySQL, so I can't modify the DataSource bean config directly. Only one DataSource should be configured in the Spring XML configuration file (no H2 DataSource configured).
Is there any way to replace the DataSource bean in the sqlmapclient (ibatis) at runtime?
A:
One option is to use Spring's support for bean definition profiles and @ActiveProfiles in your test classes.
However, if you are not willing or able to do that, another option would be to implement a custom BeanFactoryPostProcessor that replaces the bean definition for the MySQL DataSource with a bean definition for the H2 DataSource. Keep in mind that, if you go that route, you will still need conditional logic (in your BeanFactoryPostProcessor) to decide whether or not to replace the MySQL DataSource bean definition.
|
[
"stackoverflow",
"0015479703.txt"
] | Q:
Lightweight web framework for mostly static site
I've many years experience with PHP and some good experience with Python/django.
I'm basically about to throw together a quick personal website because I've gone too long without one that really does anything. I don't want to use PHP (too ugly) and I'd rather avoid django since it's meant really for very dynamic sites and is hugely overkill for what I want. Something using Python would be highly preferable.
In particular I want something lightweight with the following features:
Full control of HTTP headers.
A good way of handling pretty urls.
A lightweight template engine.
Simple way to add static content on a somewhat regular basis.
I've had a look at Flask, which seems like my best bet so far, but even this seems geared towards generating mostly dynamic content. So I'm looking for other suggestions, or some justification that Flask is just fine.
A:
Flask is just fine. That you can chose to use dynamic content, does not in any way impair your ability to also serve static content.
Otherwise there's always Bottle. :)
EDIT
Of course if you must use Python 3, Flask is out, and you should probably look into something like Tornado and PyPy, which would also (probably) give you a significant performance boost.
|
[
"stackoverflow",
"0055683779.txt"
] | Q:
To update specific column values based on other columns in mssql
I have a huge table whereby i need to update the value on one column based on the values from 2 other columns, I extract the data and put it in other new #temp table
where the format of the snippet data is as follows
DOC_GUID NAME Value Timestamp
-------- ---- ----- ---------
1111 V1 AC 1134
1111 V2 AB 1134
1112 V1 N 1234
1112 V2 AB 1234
1113 V1 AC 1334
1113 V2 N 1334
1114 V1 N 1434
1114 V2 N 1434
I need to update the values to become like this
DOC_GUID NAME Value Timestamp
-------- ---- ----- ---------
1111 V1 AC 1134
1111 V2 AC 1134
1112 V1 AB 1234
1112 V2 AB 1234
1113 V1 AC 1334
1113 V2 AC 1334
1114 V1 N 1434
1114 V2 N 1434
I tried to write out the logic as follows, but it cant be executed at all
UPDATE #temp
SET Value = CASE WHEN (A.DOC_GUID = B.DOC_GUID
FROM #temp A inner join #temp B
ON A.Value= 'AC' OR
B.Value = 'AC')
THEN 'AC'
WHEN (A.DOC_GUID = B.DOC_GUID
FROM #temp A inner join #temp B
ON A.Value= 'AB' OR
B.Value = 'AB')
THEN 'AB' END
A:
DDL:
declare @tbl table (DOC_GUID int, NAME varchar(3), Value varchar(3), Timestamp int );
insert into @tbl values
(1111,'V1','AC',1134),
(1111,'V2','AB',1134),
(1112,'V1','AB',1234),
(1112,'V2','N',1234),
(1113,'V1','AC',1334),
(1113,'V2','N',1334),
(1114,'V1','N',1434),
(1114,'V2','N',1434);
Update query:
update t1 set t1.Value = t2.Value
from @tbl t1 join (
select *,
-- here I use case statement to make AC come before AB
row_number() over (partition by DOC_GUID order by case when [Value] = 'AC' then 'AA' else [Value] end) rn
from @tbl
) t2 on t1.DOC_GUID = t2.DOC_GUID
where t2.rn = 1
|
[
"tex.stackexchange",
"0000051079.txt"
] | Q:
Add "Retrieved", "Last accessed" or similar information to authoryear in biblatex
When citing online resources my university's regulation stipulates that we have to add information on when we accessed the specific website. This can for example be of the form "Retrieved: April 7, 2012".
When using the following simple setup for biblatex, is there a field in @online or so that allows me to have this printed automatically in the bibliography?
\usepackage[style=authoryear, backend=biber]{biblatex}
A:
As I recommend in the comment you need the field urldate. Here an example:
\documentclass{article}
\usepackage[style=authoryear, backend=biber]{biblatex}
\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@Online{ctan,
label = {CTAN},
title = {CTAN},
subtitle = {The Comprehensive TeX Archive Network},
date = {2006},
url = {http://www.ctan.org},
urldate = {2012-04-07},
}
\end{filecontents}
\addbibresource{\jobname.bib}
\DefineBibliographyStrings{english}{%
urlseen = {Retrieved},
}
\begin{document}
Text \cite{ctan}
\printbibliography
\end{document}
I also changed urlseen to your required string: "Retrieved".
If you want to format urldate you can use the following options of biblatex:
urldate=comp,dateabbrev=false
The result will be: April 7
The result is:
|
[
"stackoverflow",
"0055988738.txt"
] | Q:
Running rails in docker
I'm learning docker and create a Dockerfile which is exactly
FROM ruby:2.6
RUN bundle config --global frozen 1
WORKDIR /usr/src/app
COPY Gemfile Gemfile.lock ./
RUN bundle install
COPY . .
EXPOSE 3000
CMD ["rails", "server", "-b", "0.0.0.0", "-p", "3000"]
but when I try curl 0.0.0.0:3000 or open it in a browser it says connection is refused. It should not related with the rails app I think because it's just a completely new app.
after I input Ctrl-c then it show
=> Booting Puma
=> Rails 5.2.3 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.1 (ruby 2.6.3-p62), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
- Gracefully stopping, waiting for requests to finish
=== puma shutdown: 2019-05-05 04:00:42 +0000 ===
- Goodbye!
Exiting
I tried to attach shell into container and I saw puma with ps aux so what is wrong
A:
It's important how you start your container. By default you don't publish the port to the host machine so the opened port of your rails application is only accessible inside of your container. If you want to publish the port run it like that:
docker run -p 3000:3000 <image>
You can find more information in the documentation.
|
[
"stackoverflow",
"0019353271.txt"
] | Q:
Syntax Error with Code Php
I keep getting this syntax error with this line of code.
$subject = 'Message - General Inquiry from '.$field_name' with the email of '.$field_email;
Can someone please help?
A:
$subject = 'Message - General Inquiry from '.$field_name.' with the email of '.$field_email;
|
[
"stackoverflow",
"0028766692.txt"
] | Q:
Intersection of two graphs in Python, find the x value
Let 0 <= x <= 1. I have two columns f and g of length 5000 respectively. Now I plot:
plt.plot(x, f, '-')
plt.plot(x, g, '*')
I want to find the point 'x' where the curve intersects. I don't want to find the intersection of f and g.
I can do it simply with:
set(f) & set(g)
A:
You can use np.sign in combination with np.diff and np.argwhere to obtain the indices of points where the lines cross (in this case, the points are [ 0, 149, 331, 448, 664, 743]):
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 1000)
f = np.arange(0, 1000)
g = np.sin(np.arange(0, 10, 0.01) * 2) * 1000
plt.plot(x, f, '-')
plt.plot(x, g, '-')
idx = np.argwhere(np.diff(np.sign(f - g))).flatten()
plt.plot(x[idx], f[idx], 'ro')
plt.show()
First it calculates f - g and the corresponding signs using np.sign. Applying np.diff reveals all the positions, where the sign changes (e.g. the lines cross). Using np.argwhere gives us the exact indices.
A:
Here's a solution which:
Works with N-dimensional data
Uses Euclidean distance rather than merely finding cross-overs in the y-axis
Is more efficient with lots of data (it queries a KD-tree, which should query in logarathmic time instead of linear time).
You can change the distance_upper_bound in the KD-tree query to define how close is close enough.
You can query the KD-tree with many points at the same time, if needed. Note: if you need to query thousands of points at once, you can get dramatic performance increases by querying the KD-tree with another KD-tree.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.spatial import cKDTree
from scipy import interpolate
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('off')
def upsample_coords(coord_list):
# s is smoothness, set to zero
# k is degree of the spline. setting to 1 for linear spline
tck, u = interpolate.splprep(coord_list, k=1, s=0.0)
upsampled_coords = interpolate.splev(np.linspace(0, 1, 100), tck)
return upsampled_coords
# target line
x_targ = [1, 2, 3, 4, 5, 6, 7, 8]
y_targ = [20, 100, 50, 120, 55, 240, 50, 25]
z_targ = [20, 100, 50, 120, 55, 240, 50, 25]
targ_upsampled = upsample_coords([x_targ, y_targ, z_targ])
targ_coords = np.column_stack(targ_upsampled)
# KD-tree for nearest neighbor search
targ_kdtree = cKDTree(targ_coords)
# line two
x2 = [3,4,5,6,7,8,9]
y2 = [25,35,14,67,88,44,120]
z2 = [25,35,14,67,88,44,120]
l2_upsampled = upsample_coords([x2, y2, z2])
l2_coords = np.column_stack(l2_upsampled)
# plot both lines
ax.plot(x_targ, y_targ, z_targ, color='black', linewidth=0.5)
ax.plot(x2, y2, z2, color='darkgreen', linewidth=0.5)
# find intersections
for i in range(len(l2_coords)):
if i == 0: # skip first, there is no previous point
continue
distance, close_index = targ_kdtree.query(l2_coords[i], distance_upper_bound=.5)
# strangely, points infinitely far away are somehow within the upper bound
if np.isinf(distance):
continue
# plot ground truth that was activated
_x, _y, _z = targ_kdtree.data[close_index]
ax.scatter(_x, _y, _z, 'gx')
_x2, _y2, _z2 = l2_coords[i]
ax.scatter(_x2, _y2, _z2, 'rx') # Plot the cross point
plt.show()
A:
For those who are using or open to use the Shapely library for geometry-related computations, getting the intersection will be much easier. You just have to construct LineString from each line and get their intersection as follows:
import numpy as np
import matplotlib.pyplot as plt
from shapely.geometry import LineString
x = np.arange(0, 1000)
f = np.arange(0, 1000)
g = np.sin(np.arange(0, 10, 0.01) * 2) * 1000
plt.plot(x, f)
plt.plot(x, g)
first_line = LineString(np.column_stack((x, f)))
second_line = LineString(np.column_stack((x, g)))
intersection = first_line.intersection(second_line)
if intersection.geom_type == 'MultiPoint':
plt.plot(*LineString(intersection).xy, 'o')
elif intersection.geom_type == 'Point':
plt.plot(*intersection.xy, 'o')
And to get the x and y values as NumPy arrays you would just write:
x, y = LineString(intersection).xy
# x: array('d', [0.0, 149.5724669847373, 331.02906176584617, 448.01182730277833, 664.6733061190541, 743.4822641140581])
# y: array('d', [0.0, 149.5724669847373, 331.02906176584617, 448.01182730277833, 664.6733061190541, 743.4822641140581])
or if an intersection is only one point:
x, y = intersection.xy
|
[
"datascience.stackexchange",
"0000053388.txt"
] | Q:
Time Series:Outlier Detection
I have time series data which looks like the graph mentioned below.
I am familiar with the method of removing outliers based on the standard deviation and median values. Drawback of these methods are that they do not account for the neighboring data points.
For example, in the data show below I do not want to remove the values which are simply maximum or standard deviation away from the mean. I want to remove the points which are circled in the red. The other extreme values are common in the area should not be detected as outlier as these data points have similar nearby data points.
Is there any method to remove these points or is there any python library I can use to remove these points. Normal standard deviation and median filters do not work well for these as they also remove the points which are not circled.
A:
You could compute mean and standard deviations in sliding windows, and use those to remove outliers.
For example, taking windows of, say, length 100, you can compute the mean and std for for these 100 successive observations, and see whether any point falls above the 3 sigma rule. In this case, the circled outlier would still be recognized as such, while the others should not, as they are not so outlying w.r.t. neighboring data (i.e. within the window that includes them and their neighboring observations).
|
Subsets and Splits