text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How to create a tooltip "copied to clipboard" upon clicking copy button in reactjs
I am trying to create a tooltip "copied to clipboard" on clicking copy button.
Below is the code,
constructor(props) {
super(props)
this.state = {
tool_tip_content: '',
};
}
click = () => {
this.input_ref.current.select();
document.execCommand('copy');
this.input_ref.current.blur();
this.setState({ tool_tip_content: 'Copied to clipboard'});
};
<input readOnly ref={this.input_ref} value="hello"/>
<button onClick={this.click}>COPY</button>
<span style={tooltipStyle}>Copied to Clipboard </span>
What i have tried is as below,
constructor(props) {
super(props)
this.state = { on_copy_link_click: false }
}
click = () => {
this.setState({ on_copy_link_click: true);
this.input_ref.current.select();
document.execCommand('copy');
};
mouse_out = () => {
this.setState({ tool_tip_content: ''});
};
<div className="tooltip">
<input readOnly ref={this.input_ref} value="hello"/>
<button onClick={this.click} onMouseOut={this.mouse_out}>COPY</button>
<span className="tooltiptext">{this.state.tool_tip_content} </span>
</div>
Styling for the copylink tooltip is as below,
.tooltip {
position: relative;
display: inline-block;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 140px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 150%;
left: 50%;
margin-left: -75px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
The above code works as explained below,
1. on hovering on copylink button the tooltip with empty content is displayed
2. on clicking copylink button tooltip with content "copied to clipboard is displayed"
3. On mouseout tooltip is not displayed
Expected result:
Only on clicking copylink button i want the tool tip to be displayed with content "copied to clipboard". on mouserover and mouseout tooltip shouldn't be displayed.
Can someone please help me with this.thanks.
A:
In this case, you can use conditional rendering...
{this.state.tool_tip_content.length>0 && <span className="tooltiptext">{this.state.tool_tip_content} </span> }
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Show that $\lim_{(x, y) \to (0, 0)} \frac{y + \sin x}{x + \sin y}$ does not exist.
Show that the limit
$$\lim_{(x, y) \to (0, 0)} \dfrac{y + \sin x}{x + \sin y}$$
does not exist. I tried using two-path test but all of them gave the same value $1$. I tried using paths $y = 0, y = kx, y = \sin x$ but all of them give limit $1$. Since this is the only method taught as of now, I would like to know how I can use two-path test to show this.
A:
Let $y=-x$.
Thus, $$\lim_{x\rightarrow0}\frac{-x+\sin{x}}{x-\sin{x}}=-1.$$
But for $y=x$ we obtain:
$$\lim_{x\rightarrow0}\frac{x+\sin{x}}{x+\sin{x}}=1.$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does someone know the name of this equipment?
I think it is used to measure force or something like that. I broke it and have to buy a new one.
A:
There are different equipment used to measure force like pivot balance, strain gauge, spring balance, etc.
By seeing the image, we can easily figure out it is spring balance.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iOS App crashes on phone, works flawlessly in iPhone simulator
What is the best way to debug that? It just "crashes" on the phone, no message, nothing. Simulator is doing just fine. Happens on only one of the UIViewController's, not sure why...
A:
Attach the debugger when running on the device, see if it is produced that case. Otherwise, check the device logs in the organizer. Logs are left on the device when the app crashes. They can be symbolicated to find out this information.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java JVM Default Garbage Collector: is it configured the same across different applications?
Simply as specified in the title.
I ran a test and recorded its memory heap usage pattern over time using JMX. Then I reran my jar file later and studied its memory behavior again. The result was a slightly different memory pattern. In both cases I didn't preconfigure my garbage collector. So I want to know now if two default garbage collectors have the same configurations on the same machine.
If not, how can I ensure that my garbage collector is the same without specifying many parameters? Also what could contribute to my result if not the GC config?
A:
If you run the same application on the same machine, with the same JVM, the heap and GC parameters will be the same.
Ergonomics was a feature introduced way back in JDK 5.0 to try and take some of the guesswork out of GC tuning. A server-class machine (2 or more cores and 2 or more Gb of memory) will use 1/4 of physical memory (up to 1Gb) for both the initial and maximum heap sizes (see https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html). So different machines may have different configurations by default.
To find out exactly what flags you have set, use:
java -XX:+PrintFlagsFinal -version
The difference in memory usage pattern is simply the non-deterministic behaviour of your application. Even with the exact same set of inputs, I doubt you'd see exactly the same memory behaviour just down to so many other OS and hardware effects (cache, core affinity, etc.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Semicolons when creating a CSV file instead of colons
When creating a CSV file from an XLSX workbook with the new Excel for Windows 8, I get a file filled with semicolons instead of colons.
How can I change that? I even had to reopen the file with Wordpad to find out why my file could not be exported to a data management program.
A:
Your Windows regional settings are set to use semi-colons instead of commas as the list seperator symbol. You'll have to re-configure those in order to force Excel to use colons instead of semi-colons.
Check out this page to find out how to do that: http://www.rawcomputing.co.uk/windows8/windows-8-tip12.html The list seperator symbol should be configurable on the window that pops up when clicking the "Additional settings..." button on the "Region" window.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create or update existing postgres db container through kubernetes job
I have a Postgres DB container which is running in a Kubernetes cluster. I need to write a Kubernetes job to connect to the Postgres DB container and run the scripts from SQL file. I need to understand two things here
commands to run SQL script
how to load SQL file in Job.yaml file
Here is my sample yaml file for Kubernetes job
apiVersion: batch/v1
kind: Job
metadata:
name: init-db
spec:
template:
metadata:
name: init-db
labels:
app: init-postgresdb
spec:
containers:
- image: "docker.io/bitnami/postgresql:11.5.0-debian-9-r60"
name: init-db
command:
- psql -U postgres
env:
- name: DB_HOST
value: "knotted-iguana-postgresql"
- name: DB_DATABASE
value: "postgres"
restartPolicy: OnFailure
A:
You have to mount the SQL file as a volumen from a configmap and use the psql cli to execute the commands from mounted file.
To execute commands from file you can change the command parameter on the yaml by this:
psql -a -f sqlCommand.sql
The configmap needs to be created using the file you pretend to mount more info here
kubectl create configmap sqlCommands.sql --from-file=sqlCommands.sql
Then you have to add the configmap and the mount statement on your job yaml and modify the command to use the mounted file.
apiVersion: batch/v1
kind: Job
metadata:
name: init-db
spec:
template:
metadata:
name: init-db
labels:
app: init-postgresdb
spec:
containers:
- image: "docker.io/bitnami/postgresql:11.5.0-debian-9-r60"
name: init-db
command: [ "bin/sh", "-c", "psql -a -f /sqlCommand.sql" ]
volumeMounts:
- name: sqlCommand
mountPath: /sqlCommand.sql
env:
- name: DB_HOST
value: "knotted-iguana-postgresql"
- name: DB_DATABASE
value: "postgres"
volumes:
- name: sqlCommand
configMap:
# Provide the name of the ConfigMap containing the files you want
# to add to the container
name: sqlCommand.sql
restartPolicy: OnFailure
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Bandwidth usage maxed out
some people working with me ask me to look around for answers about a bandwidth problem they've been having. The problem is simple, when one user download something all connection (like RDP and terminal services for exemple) drop dead. I'm using windows server 2008 and i've been looking around my 3COM switch 3CREVF100-73 for some sort of bandwidth control. On this switch i have one port that is use for a dmz and a port for an other switch (24 port) that is use for my private network.
Thanx in advance for any ideas you can give me!
A:
The product page for that switch does mention that it has this feature:
Traffic shaping prioritizes traffic on
user-definable ports to guarantee
bandwidth
View chapter 12 of the manual for details about how to set this up. You will probably need to create a couple rules to priorities important types of traffic like RDP.
But realistically if a single download kills your connection you almost certainly need to work on getting more bandwidth. Traffic shaping can help a little, but if you link is saturated, it will won't really do anything other then slightly change what is using up all your bandwidth.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Use Kubernetes RBAC namespace roles?
I'm trying to give a service account my-service-account access to apply deployments within a namespace my-namespace in a Google Kubernetes Engine cluster running Kubernetes 1.14.
This is what my rolebinding looks like:
$ kubectl describe rolebinding -n my-namespace --context my-cluster
Name: my-namespace-service-account-policy
Labels: <none>
Annotations: <none>
Role:
Kind: Role
Name: edit
Subjects:
Kind Name Namespace
---- ---- ---------
ServiceAccount my-service-account my-namespace
However, when my service account goes to apply a manifest, I get an error that ends with:
deployments.apps "my-namespace" is forbidden: User "system:serviceaccount:my-namespace:my-service-account" cannot get resource "deployments" in API group "apps" in the namespace "my-namespace": RBAC: role.rbac.authorization.k8s.io "edit" not found
I also tried using "admin" instead of edit. If I instead create a clusterrolebinding with cluster-admin for the same service account, it works fine. How do I grant the account access just to the namespace?
A:
The predefined edit name is a ClusterRole, and thus making reference to it as a Role is not referring to the same entity.
The godoc for that declaration seems to imply that it's safe to create the ClusterRoleBinding to the edit ClusterRole since it is scoped to namespace-level editing, but I haven't studied that policy extensively and am not an RBAC wizard
|
{
"pile_set_name": "StackExchange"
}
|
Q:
adding items to deep List of KeyValuePairs
I wrote a deep list:
public static List<KeyValuePair<string,List<KeyValuePair<string,List<KeyValuePair<string,bool>>>>>> ListBoxes = new List<KeyValuePair<string,List<KeyValuePair<string,List<KeyValuePair<string,bool>>>>>>();
Anybody has an idea how to add to this list any items?
For example:
("A",LIST("B",LIST("C",true)))
A:
Easy:
ListBoxes.Add(
new KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>("A",
new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>
{
new KeyValuePair<string,List<KeyValuePair<string,bool>>>("B",
new List<KeyValuePair<string,bool>>() {
new KeyValuePair<string,bool>("C", true)
}
)
}
)
);
It looks like you could use some helper methods or something.
Edit
If you create a simple extension method, then the task becomes maybe a bit more readable.
public static List<KeyValuePair<TKey, TValue>> AddKVP<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> self, TKey key, TValue value)
{
self.Add(
new KeyValuePair<TKey, TValue>(key, value)
);
// return self for "fluent" like syntax
return self;
}
var c = new List<KeyValuePair<string, bool>>().AddKVP("c", true);
var b = new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>().AddKVP("b", c);
var a = new List<KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>>().AddKVP("a", b);
Edit #2
If you define a simple type, then it helps a bit more:
public class KVPList<T> : List<KeyValuePair<string, T>> { }
public static KVPList<TValue> AddKVP<TValue>(this KVPList<TValue> self, string key, TValue value)
{
self.Add(new KeyValuePair<string, TValue>(key, value));
return self;
}
var ListBoxes = new KVPList<KVPList<KVPList<bool>>>()
.AddKVP("A", new KVPList<KVPList<bool>>()
.AddKVP("B", new KVPList<bool>()
.AddKVP("C", true)));
Edit #3
One more and I promise I'll stop. If you define "Add" on the type, then you can use implicit initialization:
public class KVPList<T> : List<KeyValuePair<string, T>>
{
public void Add(string key, T value)
{
base.Add(new KeyValuePair<string,T>(key, value));
}
}
var abc = new KVPList<KVPList<KVPList<bool>>> {
{ "A", new KVPList<KVPList<bool>> {
{ "B", new KVPList<bool> {
{ "C", true }}
}}
}};
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Disadvantages when using dotConnect for Oracle in comparison to SQL Server?
I am currently evaluating dotConnect for Oracle as an alternative to switching to SQL Server at my company altogether.
We are currently developing ASP.NET MVC2 applications with datasets and oracle, but we would like to switch to entity framework for persistence. I understand that dotConnect offers support for visual designers in Visual Studio. Does anybody have any experience with the product? Does it have disadvantages to using the designers with SQL Server, or any other drawbacks?
Any hint or experience would be appreciated!
Thanks in advance,
Chris
A:
We are now using dotConnect for oracle in a project in which we are forced to use Oracle per client requirements (we usually use SQL Server). I have been using it for a short time but for now my impression can't be more positive. The product looks quite polished, and it integrates very well with Visual Studio.
About the visual designers, we are using a feature of dotConnect named Linq to Oracle, which is almost an exact clone of Linq to Sql: the visual designer is very similar, and the members of the DataContext class have basically the same names. This is being very useful for us, a team used to SQL Server/Linq to Sql and without previous Oracle experience.
Disadvantages? It is a paid product, while SQL Server tools are already integrated within Visual Studio. I can't think of any other. :-)
Devart has a trial version of the product anyway. I recommend you to give a try.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
G++ -D option adds digit 1
I know title is weird, so here is the explanation:
I have some code that I would rather not modify but I need to redefine some functions.
Minimal example is this:
int main()
{
strcpy_s(a,b);
}
But when I run this:
$ g++ -E -P -w -D"strcpy_s(D,S) strcpy(D,S) buahaha" test.cpp
I get:
int main()
{
strcpy(a,b) buahaha 1;
}
What is this 1? Ignore buahaha, it is just to show that PP does something.
A:
There are two ways you can use the -D option:
-Dname
-Dname=value
The first defines name as 1, the second defines name as value.
name is permitted to include parentheses, so that you can define function-like macros on the command line. Something like -Dfoo bar contains no equals sign, so it is interpreted as an attempt to define foo bar as 1. Macro names cannot include spaces, so this should probably cause an error message, but it does not get detected, and you end up confusing the compiler. Try -D"strcpy_s(D,S)=strcpy(D,S) buahaha" instead.
What I suspect is happening is that -Dname is translated to #define name 1, and -Dname=value is translated to #define name value, and error checking only happens after that. This would translate -D"strcpy_s(D,S) strcpy(D,S) buahaha" to #define strcpy_s(D,S) strcpy(D,S) buahaha 1, and explain the result you are getting.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Text() in front of TextField() blocking editing in SwiftUI
So I'd like my textfield to have a customizable placeholder text so I decided to put a Text() element in a ZStack in front of the text field. The only problem is, this Text() item blocks the selection of the textfield that is behind it (AKA when I click the placeholder I want the TextField to be clicked). Unfortunately, this Text() element blocks the click. I tried using the .allowsHitTesting() property as seen below but that also didn't work, and I'm not sure why.
struct ContentView: View {
@State var text: String = ""
var body: some View {
ZStack {
TextField("", text: self.$text)
.background(Color.red)
.foregroundColor(Color.white)
if text.isEmpty {
Text("Placeholder")
.allowsHitTesting(false)
}
}
}
}
A:
It can be done with custom text field style.
Here is a demo of solution (or parameters can be tuned). Tested with Xcode 12 / iOS 14 (border is just for visibility)
struct PlaceholderStyle: TextFieldStyle {
let isActive: Bool
var placeholder = "Placeholder"
var color = Color.white
var backgrond = Color.red
func _body(configuration: TextField<_Label>) -> some View {
Text("\(isActive ? placeholder : "")")
.foregroundColor(isActive ? color : .clear)
.background(isActive ? backgrond : .clear)
.frame(maxWidth: .infinity, alignment: .leading)
.overlay(configuration)
}
}
struct DemoView: View {
@State private var text = ""
var body: some View {
TextField("", text: $text)
.border(Color.gray).padding(.horizontal)
.textFieldStyle(PlaceholderStyle(isActive: text.isEmpty))
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JavaFX WebView won't show
I am having trouble with JavaFX, I only get an empty window when I try to load a web view. Any ideas?
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
/**
* Created by poa on 15.04.2014.
*/
public class GUI extends Application{
private Scene scene;
@Override public void start(Stage stage) {
stage.setTitle("Hello World!");
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
StackPane root = new StackPane();
root.getChildren().addAll(btn, browser);
stage.setScene(new Scene(root, 300, 250));
stage.show();
stage.setTitle("Web View");
}
public static void main(String[] args){
launch(args);
}
}
A:
You didn't load anything into the WebView, so there is nothing to see in it.
Because you put the web view and the button in a stack pane, which stacks nodes one on top of the other, the empty web view is on top of the button, so you can't see the button.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JSON array starting with bit 1
my JSON array is like this;
var foo = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"},{"aid":"3","atitle":"Anwar Syed"},{"aid":"4","atitle":"Aratrika"},{"aid":"5","atitle":"Bharti Nagpal"}]
if i select any element, for example,
alert(foo[0].atitle);
output: Ameya R. Kadam
the first element's atitle value shows up. i want to modify it so that the array starts from 1 instead of 0. like,
alert(foo[1].atitle);
output: Ameya R. Kadam
can it be done?
A:
First, this is almost certainly a mistake. If your programming language uses 0-indexed arrays, you should just accept that and move on.
Second, you could achieve a similar effect by pushing an empty element onto the front of your array.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++: Array with custom size in class
I want to do this:
class Graphic
{
int *array;
Graphic( int size )
{
int temp_array[size];
array = temp_array;
glGenTextures( size, array );
}
}
Will this work? And even if it will, is there a better way to do this?
Thanks.
A:
Using new means you have to remember to delete [] it; using compiler-dependent variable-size arrays means you lose portability.
It's much better to use a vector.
#include <vector>
class Graphic
{
std::vector<int> array;
Graphic( int size )
{
array.resize(size);
glGenTextures( size, &array[0] );
}
}
The language guarantees that vector elements will be contiguous in memory so it's safe to do &array[0] here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to infer a typed array from a dynamic key array in typescript?
I'm looking to type a generic object and have properties of that object return in a typed array. The ability to get a singular typed property from an object is documented and works, however i'm unable to get this to work with an array. Seems the 'union type'.
// from the documentation
// @ http://www.typescriptlang.org/docs/handbook/advanced-types.html
function getProperty<T, K extends keyof T>(o: T, name: K): T[K] {
return o[name];
}
const a = getProperty(person, 'age');
// a: number
const n = getProperty(person, 'name');
// n: string
const getProperties = <T>(obj: T, keys: Array<keyof T>) => keys.map((arg) => getProperty(obj, arg));
const [a2, n2] = getProperties(person, ['name', 'age']);
// result:
// a2: string | number
// n2: string | number
// what i want:
// a2: string
// n2: number
A:
The problem is that keys can be any key of T so when you call getProperty inside getProperties the result will be of T[keyof T] meaning any value of T. For getProperty(person, 'age') it works because name will be inferred as the string literal type 'age' and the result will thus be T['age'] which is number.
To accomplish what you want, we need a separate generic parameter for each key that will be passed. We can't support an arbitrary amount of keys but, using overloads, we can support a certain finite amount of keys which will be good enough for most cases (I added overloads for up to 3 keys, you can easily add more):
const person = {
age: 1,
name: ""
}
function getProperty<T, K extends keyof T>(o: T, name: K): T[K] {
return o[name];
}
function getProperties<T, K extends keyof T, K2 extends keyof T, K3 extends keyof T>(obj: T, keys: [K, K2, K3]): [T[K], T[K2], T[K3]]
function getProperties<T, K extends keyof T, K2 extends keyof T>(obj: T, keys: [K, K2]): [T[K], T[K2]]
function getProperties<T, K extends keyof T>(obj: T, keys: [K]): [T[K]]
function getProperties<T>(obj: T, keys: Array<keyof T>) {
return keys.map((arg) => getProperty(obj, arg));
}
const [a2, n2] = getProperties(person, ['name', 'age']); // a2: string, n2: number
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Simplifying a Resizing Method
I'm making a simple container class for fun and education, but my rebuilding/resizing method seems rather inefficient. Is there an easier way to do this?
// If FromFront is true, cells should be added or
// subtracted from the front of the array rather than the back.
void Rebuild(std::size_t NewSize, bool FromFront = false)
{
const std::size_t OldSize = Size;
Size = NewSize; // Size is used in other methods.
Datatype* TemporaryStorage = new Datatype[OldSize]; // Allocate space for the values to be preserved while a new main array is made.
for (std::size_t Index = 0; Index < OldSize; Index++) TemporaryStorage[Index] = BasePointer[Index]; // Copy values over to the temporary array.
delete[] BasePointer; // Delete the main array...
BasePointer = new Datatype[NewSize]; // ...And rebuild it with the appropriate size.
for (std::size_t Iteration = 0; (Iteration < OldSize) && (Iteration < NewSize); Iteration++)
{
std::size_t BasePointerIndex = Iteration;
std::size_t TemporaryStorageIndex = Iteration;
if (FromFront) // We need to take special measures to give the indices offsets.
{
if (NewSize > OldSize) BasePointerIndex += (NewSize - OldSize);
else TemporaryStorageIndex += (OldSize - NewSize);
}
BasePointer[BasePointerIndex] = TemporaryStorage[TemporaryStorageIndex]; // Copy values from the temporary array to the new main array.
}
delete[] TemporaryStorage; // Finally, delete the temporary storage array.
}
A:
void Rebuild(std::size_t NewSize, bool FromFront = false)
{
const std::size_t OldSize = Size;
Datatype* NewStorage = new Datatype[NewSize];
Rather then creating a temporary array and copying the existing data into it, just create the new array and copy into that.
int CopyLength = std::min(OldSize, NewSize);
We start by determining how many elements we will actually copy
if( FromFront )
{
std::copy(BasePointer + OldSize - CopyLength, BasePointer + OldSize,
NewStorage + NewSize - CopyLength);
}
else
{
std::copy(BasePointer, BasePointer + CopyLength, NewStorage);
}
I use std::copy to avoid having to write a copying for loop myself.
delete[] BasePointer; // Delete the main array...
BasePointer = NewStorage;
Size = NewSize; // Size is used in other methods.
delete the current array and replace it with my new array
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
if cells have equal value in same column
I'm trying to create a formula for a countback feature in google sheets if possible.
I have a list of competitors race times (W4:W93) and have them ranked (X4:X93) and but if I get Identical times it throws out another formula for overall results.
my sticking point is I can't work out how to compare if the value in any cell is equal to another cell in the same column excluding itself, I have found plenty of info on equal values but not if they are in the same column.
any help would be much appreciated.
A:
I note that this question has been voted down with no explanatory comments. The question is not on hold, it is not closed because it might be duplicate, or answered elsewhere, and no one has edited the question to provide greater clarity. That seems a pretty rough call to me.
In any event, I'm pretty sure that I've been in the situation described by the OP many times and I've had to be creative about finding and removing duplicate values. There are several ways to find/highlight/manipulate duplicate values, though Google doesn't seem to have as many options as Excel. One method is to use conditional formatting and this YouTube video explains it very well.
But I will use one of my all-time absolute favourite formulae to find duplicates. In addition, since the OP is working with 90 competitors, finding the duplicates is only the task, the OP also needs to arrange them in a way that assists analysis.
This Google spreadsheet shows the workings:
First, create a header, say, "Equal Rank" for column Y (the first column after "Ranking") and insert this formula in cell Y4:
=if(countif($W:$W,W4)=1,"Unique","Duplicate")
The formula has two components.
COUNTIF
IF statement
The COUNTIF looks at cell W4 (the race time) in the first row of results. The count range is Column W; the range could just as easily be limited to actual data but the key is that it is expressed as an "absolute" (note the $ signs in the range).The formula counts how many times the value in cell W4 appears in the range.
The IF statement evaluates the result of the COUNTIF. If the result appears only once, then the cell value is "Unique". If the value appears more than once, then it is a "Duplicate" value.
The OP has 90 competitors and will need to drill down to the duplicate results quickly. So, I suggest a variation of the classic formula, this:
=if(countif($W$4:$W$93,W4)=1,"",X4)
The formula still consists of two components, but if the result is unique, then no value is entered; conversely if the result is a duplicate, then the existing "Rank" (cell X4) is returned. BTW, this version shows how the range address would look if you evaluated only the populated range.
Now, sort the range A3:Y93 (I am assuming there is relevant data in columns A-V). FWIW, I inserted a column "Sequence" and gave it a numeric sequence so that once the "Equal Ranks" had been fixed, I could resort on the "Sequence" column to return the data to the original sort order - the OP may or may not need this.
To aggregate the duplicate values:
Select the Range> right-click > Sort range > "Data has Header Row" = checked> 'Sort by' "Equal Rank", Sort order: "A->Z".
From here, Race Times could be adjusted by a tenth, or hundredth, of a second to avoid duplicate times.
Once this is complete, select the full range again, and resort. In my case I used my "Sequence" column to return the data to the original sort order.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Creating object in Python
Is there any differences between these to declare an object?
class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
and
class MyStuff:
def __init__(self):
self.tangerine = "And now a thousand years between"
A:
Yes, there is a difference. At least, there's a difference in Python 2.
class MyStuff: creates an old-style class,
class MyStuff(object): creates a new-style class.
In Python 3, all classes are new-style.
From https://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes
Classes and instances come in two flavors: old-style (or classic) and
new-style.
Up to Python 2.1 the concept of class was unrelated to the concept of
type, and old-style classes were the only flavor available. For an
old-style class, the statement x.__class__ provides the class of x,
but type(x) is always <type 'instance'>. This reflects the fact that
all old-style instances, independent of their class, are implemented
with a single built-in type, called instance.
New-style classes were introduced in Python 2.2 to unify the concepts
of class and type. A new-style class is simply a user-defined type, no
more, no less. If x is an instance of a new-style class, then type(x)
is typically the same as x.__class__ (although this is not guaranteed
– a new-style class instance is permitted to override the value
returned for x.__class__).
The major motivation for introducing new-style classes is to provide a
unified object model with a full meta-model. It also has a number of
practical benefits, like the ability to subclass most built-in types,
or the introduction of “descriptors”, which enable computed
properties.
For compatibility reasons, classes are still old-style by default.
New-style classes are created by specifying another new-style class
(i.e. a type) as a parent class, or the “top-level type” object if no
other parent is needed. The behaviour of new-style classes differs
from that of old-style classes in a number of important details in
addition to what type() returns. Some of these changes are fundamental
to the new object model, like the way special methods are invoked.
Others are “fixes” that could not be implemented before for
compatibility concerns, like the method resolution order in case of
multiple inheritance.
While this manual aims to provide comprehensive coverage of Python’s
class mechanics, it may still be lacking in some areas when it comes
to its coverage of new-style classes. Please see
https://www.python.org/doc/newstyle/ for sources of additional
information.
Old-style classes are removed in Python 3, leaving only new-style
classes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sort Names Alphabetically in C
I have a C structure that contains contact info for a person, such as name, phone number, etc. The "contact" structures are contained within a linked list. I need to insert nodes in a way such that the linked list is sorted into alphabetical (ascending) order.
Is there a built-in sorting function in C that I can call? Or do I have to write my own sorting function? If there is a built-in function, could I get an example of how I'd call it on a structure within a linked list?
A:
There's no standard sorting method for a "list". The closest is qsort (which can indeed sort user-defined objects) but it only works on continuous ranges (arrays and the like).
You'll probably have to implement your own sorting procedure or use and array instead of a list.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why free presentations ? Why not permutation or matrix representations?
Two days ago, I asked why free presentations? and frankly I did not get a convincing answer.
I am trying here to ask the question in a different way :
We know that a group can be defined by a permutation or matrix representation.
What is the point of a presentation (I mean here free presentations) for which all the problems are undecidable?
Another point :
As I know, permutation representations are preferred for computational purposes (by "HANDBOOK OF COMPUTATIONAL GROUP THEORY" ). Then what's the advantage of free presentations? is it the space needed to store them ?
A:
Here are two reasons why group presentations are important. Firstly, they often provide the most compact and precise definition of the group. For example, when classifying groups of small order, they provide a uniform and concise method of description. For example, one of the groups of order $12$ has presentation $\langle x,y \mid x^4=y^3=1, y^{-1}xy=x^{-1} \rangle$. Other descriptions, such as semidirect product of cyclic group of order $3$ by cyclic group of order $4$ with nontrivial action, or subgroup $\langle (1,2,3), (2,3)(4,5,6,7) \rangle$ of $S_7$ are possible, but are less concise.
Even for infinite groups, a presentation is often convenient, such as the Heisenberg group $\langle x,y,z \mid [x,y]=z, [x,z]=[y,z]=1 \rangle$, which can of course also be described as the group of upper unipotent unitriangular $3 \times 3$ matrices over ${\mathbb Z}$.
The second reason is computational. You said that permutation and matrix representations are generally more convenient for computational purposed, and that is to a large extent true, but for some applications you need a presentation as well. For example, if to compute homomorphisms from a group $G$ to another group $H$ (which includes the important problems of the computation of automorphism groups, and isomorphism testing), you need a presentation of $G$. Presentations are also needed for various cohomologcal calcualtions involving groups extensions.
It is worth mentioning also that a particular type of presentation, a polycyclic presentation is the preferred data structure for computing in polycyclic groups (which includes finite solvable groups) - see Chapter 8 in the "Handbook of Computational group Theory". The above presentation of the Heisenberg group is an example.
I should add also that, in some contexts, such as the computation of fundamental groups in topology, the group in question can arise as a presentation, so it is necessary to have techniques for studying such groups.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AngularJS: Unable to make routes case insensitive
I am unable to make Angular (1.5) routes case insensitive. I've tried adding caseInsensitiveMatch: true to the route configs, but my app still won't load unless I use the proper case. I want to make the routes case insensitive. Here's what my route config looks like:
module SoftwareRegistration {
export class Routes {
static $inject = ["$routeProvider", "$locationProvider"];
static configureRoutes($routeProvider: ng.route.IRouteProvider, $locationProvider: ng.ILocationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: true
});
$routeProvider.caseInsensitiveMatch = true;
$routeProvider
.when("/",
{
controller: "SoftwareRegistration.ListOrdersController",
templateUrl: "app/views/order/listOrders.html",
controllerAs: "vm",
caseInsensitiveMatch: true
})
.when("/Orders",
{
controller: "SoftwareRegistration.ListOrdersController",
templateUrl: "app/views/order/listOrders.html",
controllerAs: "vm",
caseInsensitiveMatch: true
})
.when("/Orders/MyOrders",
{
controller: "SoftwareRegistration.ListOrdersController",
templateUrl: "app/views/order/listOrders.html",
controllerAs: "vm",
caseInsensitiveMatch: true
})
.when("/Orders/Create",
{
controller: "SoftwareRegistration.CreateOrderController",
templateUrl: "app/views/order/createOrder.html",
controllerAs: "vm",
caseInsensitiveMatch: true
})
.when("/Orders/PaymentInformation",
{
templateUrl: "app/views/order/paymentInformation.html",
caseInsensitiveMatch: true
})
.when("/Orders/:OrderId/AddRecipients",
{
controller: "SoftwareRegistration.AddRecipientsController",
templateUrl: "app/views/order/addRecipients.html",
controllerAs: "vm",
caseInsensitiveMatch: true
})
.when("/Account/Login",
{
controller: "SoftwareRegistration.LoginController",
templateUrl: "app/views/account/login.html",
controllerAs: "vm",
caseInsensitiveMatch: true
})
.otherwise({ redirectTo: "/", caseInsensitiveMatch: true });
}
}
}
When I navigate to https://myserver.com/SoftwareRegistration it works fine. However, if I navigate to https://myserver.com/softwareregistration I get this error:
angular.js:12165 Uncaught TypeError: Cannot read property 'replace' of undefined
Here's the source of angular.js:12165 :
function trimEmptyHash(url) {
return url.replace(/(#.+)|#$/, '$1');
}
I should note, it works fine on my local (case insensitive) but doesn't work when I deploy to IIS
A:
I got a workaround that I am satisfied with from this issue: https://github.com/angular/angular.js/issues/3703
I put this small script before angular is loaded to dynamically change the <base> to be whatever case the user typed in the URL
(function() {
var base = document.querySelector( "base" );
var normalized = RegExp( base.href, "i" ).exec( location.href );
base.href = normalized ? normalized[ 0 ] : base.href;
}());
This may not be suitable in all situations. As mentioned in https://github.com/angular/angular.js/issues/4056 , this may "break" caching. However, I like this solution the best because I dont have to mod the source (or remember to change it every time I update), nor do I have to mess with any server settings (on IIS anyway).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to store instance methods name of a class in a column in sql database?
I want to create a column that has nested hash structure.
structure of that column:
column_name: company
{ production=> {watch=> "yes",pen =>"no",pencil => "yes"}
quality => {life_test =>"yes", strong_test =>"yes", flexibility_test => "no"}
}
Here production, quality are my models and watch, pen, pencil, life_test,strong_test are my instance method of respective classes. each instance method will get the Boolean value from the view page.
How to achieve this structure.
A:
This is called serialization and it is pretty easy. You could do the following:
class Something < ActiveRecord::Base
serialize :company, JSON
end
bar = Something.new
bar.company = { :production=> {:watch=> true,:pen => false, :pencil => false}
:quality => {:life_test =>true, :strong_test =>true, :flexibility_test => false} }
bar.save
If you want more info go here: http://api.rubyonrails.org/classes/ActiveRecord/Base.html and read the part on "Saving arrays, hashes, and other non-mappable objects in text columns" just make sure your company column in the database is a text column.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Moving out before brackets with XOR
If I had the sum of products like z*a + z*b + z*c + ... + z*y, it would be possible to move the z factor, which is the same, out before brackets: z(a + b + c + ... y).
I'd like to know how it is possible (if it is) to do the same trick if bitwise XOR is used instead of multiplication.
z^a + z^b + ... z^y -> z^(a + b + ... + y)
Perhaps a, b, c ... should be preprocessed, such as logically negated or something else, before adding? z could change, so preprocessing, if it's needed, shouldn't depend on particular z value.
A:
From Wikipedia:
Distributivity: with no binary function, not even with itself
So, no, unfortunately, you can't do anything like that with XOR.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to purchase zen coins with real money?
I wish to purchase some zen coins with real money but can't seem to find a way to do so. At the zen market, I can see items costing zen coins being greyed out but there is no way to purchase zen coins in order to buy them.
At the moment, the only way I am aware of to obtain zen coins is to exchange astral diamonds for them ingame.
Am I missing something blatantly obvious?
A:
You might be just missing something, or you're a bit drunk?
Press Start, then go across to Store and choose Zen Market.
When you go to the Zen market, you'll see two tabs at the top left of the screen: Zen Market and Purchase Zen. You can move between these tabs by pressing LB and RB.
Once you're on the Purchase Zen screen, you can press A to buy the currently selected amount.
You'd think it'd be easier to give them your hard earned monies!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mailcore2 - search emails starting from specific date
Not sure is there anybody here with mailcore2 iOS IMAP framework experience.
But what I need is to retrieve all(or some of them) emails, which has send day after than a specific date.
Does mailcore2 provides this feature? I know that IMAP has this and guess mailcore2 will have it as well.
A:
For now, this feature is not available on mailcore2.
Though, it could be added: It's available at libetpan level.
Could you file a feature request on github issues so I can make progress on it?
A pull request would also be welcome.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to draw a rectangular area on a large google map and query database to find locations/points that exist inside the rectangle?
I've got an application where I would like to present the end user with a google map and allow them to select an area of the map with a simple rectangular drawing tool and then have all of the locations stored in the client's database that fall in that rectangular selection area show up as points on the map...
I have a simple understanding of google maps and can get google maps to plot all the locations on the database w/o a problem... my problem comes in allowing the end user to draw the rectangle. Not sure how to implement this.
Can someone explain or link me to an example of how it's done?
A:
Looks like this question was asked (and answered) a few months before Google posted about the new drawing tools in v3 API ...
I have to say that using the API's drawing tools gives a better user experience than @rcravens solution. Here's a very specific implementation that lets you "select" an area on the map by drawing a rectangle or polygon, and then checking to see if a marker is inside the shape: http://jsfiddle.net/JsAJA/306/.
A:
Interesting question. I love the google maps api. Here is a jsFiddle with your solution:
http://jsfiddle.net/JsAJA/2/
You will have to query your database for points between the minimum/maximum lat and lngs. Hope this helps.
Bob
P.S. Note that this breaks the natural user experience of google maps. The map is no longer dragged when you mouse down. It needs a better user experience.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I feed numpy.polynomial.chebyshev.Chebyshev coefficients?
How do I feed np.polynomial.Chebyshev coefficients? I'm finding the API to be unintuitive. It looks like it is assuming some coefficient values
> import numpy as np
> xf = 3
> P = np.polynomial.Chebyshev([0, xf]) # domain is [0, xf]
> P(np.linspace(0, 3, 5)) # evaluate at 5 x-points evenly spaced from 0 to 3
array([0. , 2.35619449, 4.71238898, 7.06858347, 9.42477796])
P(np.linspace(0, 3, 5), [1,2,3]) # evaluate the points with prescribed coefficients, implicitly asking for polynomials of 4 degrees
TypeError: __call__() takes exactly 2 arguments (3 given)
A:
If you look at the Chebyshev docs, you'll find that the first argument is the coefficients, not the domain. The domain is the optional second argument. For example,
np.polynomial.Chebyshev([0, 3])
is 0*T_0 + 3*T_1.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fulltext search against column value?
I've read this:
MySQL Fulltext search against column value?
but it is absurd, i don't understand why it is not possible doing this.
anyone knowing some workaround?
thanks
A:
This is my old procedure, try something like this in your case too-
BEGIN
declare done default 0;
declare csv1 varchar(100);
declare cur1 cursor for select csv from table;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
open cur1;
repeat
fetch cur1 into csv1;
-
-
-
-
update company set (something) where match(csv) against(concat("'",csv1,"'"));
until done end repeat;
-
-
close cur1;
select * from table;
END
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Neo4j delete nodes that have more that one relationship between them
I am trying to clear the database from wrong data.
I have nodes that have more than one relationship between each other and I am trying to delete those nodes.
An example of that would be:
(p:Person{id:'1'})-[r:SIBLING_OF]-(k:Person{id:'2'})
(p:Person{id:'1'})-[r:PARENT_OF]-(k:Person{id:'2'})
I have tried several queries but none of them were right.
Does anyone know what would be the best approach to achieve this?
A:
So you want to delete the nodes, not just the relationships, right?
MATCH (p1:Person)-[:SIBLING_OF]-(p2:Person),
(p2)-[:PARENT_OF]-(p1)
DETACH DELETE p1, p2
You should probably do RETURN instead of DETACH DELETE first to ensure you're deleting the right ones.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
getting about:blank in shouldStartLoadWithRequest while passing the data from javascript to objective-c using IFRAME in IOS 10
I am passing my data from javascript to objective-c. for that I am using IFRAME.
Here is my code:
context.html
function openCustomURLinIFrame(src)
{
alert(src);
var rootElm = document.documentElement;
var newFrameElm = document.createElement("IFRAME");
newFrameElm.setAttribute("src",src);
document.documentElement.appendChild(newFrameElm);
//remove the frame now
newFrameElm.parentNode.removeChild(newFrameElm);
newFrameElm = null;
}
Indoor.m
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@"Loading: %@", [request URL]);
NSURL *url = [request URL];
NSString *urlStr = url.absoluteString;
return [self processURL:urlStr];
}
I am getting
Loading: about:blank
I am using xCode 8.2.1 it is working well in IOS 9.3 but not working in iOS 10.2.
Edit:
My alert screenshot in .html file.
Edit:
Method in html file in which I call openCustomURLinIFrame method.
function calliOSFunction(functionName, args, successCallback, errorCallback)
{
var url = "js2ios://";
var callInfo = {};
callInfo.functionname = functionName;
//alert("Custom menu clicked !!"+functionName);
if (successCallback)
{
//alert("Success !!"+functionName);
callInfo.success = successCallback;
}
if (errorCallback)
{
//alert("Error !!"+functionName);
callInfo.error = errorCallback;
}
if (args)
{
//alert("args !!"+args);
callInfo.args = args;
}
url += JSON.stringify(callInfo)
openCustomURLinIFrame(url);
}
Help me to resolve this issue.
A:
Finally after long time I got my answer.
function calliOSFunction(functionName, args, successCallback, errorCallback)
{
var url = "js2ios:///"; /* Added one more "/" */
var callInfo = {};
callInfo.functionname = functionName;
//alert("Custom menu clicked !!"+functionName);
if (successCallback)
{
//alert("Success !!"+functionName);
callInfo.success = successCallback;
}
if (errorCallback)
{
//alert("Error !!"+functionName);
callInfo.error = errorCallback;
}
if (args)
{
//alert("args !!"+args);
callInfo.args = args;
}
url += JSON.stringify(callInfo)
openCustomURLinIFrame(url);
}
I add one more "/" in url variable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why are my Illustrator images blurry when placed in InDesign?
I am creating simple, clean designs in Illustrator, but when saved as .jpegs or .pngs and placed in an InDesign file at 100% resolution they are blurry as heck.
A:
Converting vector files to bitmaps always degrades quality. And since they are not vector anymore, your title is wrong.
There is no need to convert AI files to bitmaps to place them into InDesign. Place the native AI files instead.
A:
With nothing selected, right-click and go to display performance and make sure 'High Performance' is selected
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to filter out logs using Filter with two categories?
Using Google Chrome developer tool in Console.
I am aware that I can filter out logs using a "category" at a time, example "Warning", "Debug" and so on.
I am interested to know if there is a way to filter using two "categories" at the same time instead, example I would like to see only "Warning" and "Errors" and not the rest of logs.
Any idea how to achive this?
A:
Press Ctrl and click to select multiple filters.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What ways are there to extend an antenna?
I am using an arduino micro controller with a LoRa radio module to communicate. The shield has 2 ways of connecting an antenna: either a SMA jack or a hole for soldering.
Now my problem is this: I need to get the antenna away from the module itself, so that i can get the antenna out of the container of the arduino. What ways are there of doing this? Can I just use a wire? But on the other hand, would that wire not act as an antenna itself? Are there special cables or something?
A:
You have an SMA connector – use that! You can buy ready-made coax cables with SMA connectors on both ends.
As mentioned, what you want is a coax cable. The electromagnetic wave travels within the cable, so, no, if not damaged and properly attached to the radio and to an actual antenna, it won't double as antenna.
Very much like your TV cable doesn't emit radio waves.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does a width of 44 pixels equate to the same physical size for all devices?
I work based on the screen size of an iPhone 6 that is 1136x750 pixels at 326 ppi. I'm more concerned about the physical size of the buttons (for some reason) rather than their digital sizes.
If a button that has a width of 44 pixels on the iPhone 6 and a physical width of 0.2 inches has the same physical width on an iPhone 6 Plus that is 401 ppi?
If not, isn't this supposed to violate Apple's guidelines? They had originally tested 44 pixels to be the minimum width, but with bigger ppi the same width decreases physically.
Is this adjusted/scaled somehow?
EDIT: I have a feeling I'm being stupid and all this is obvious.
EDIT 2: My original concern was that across the screen an iPhone 6 can have a total of
T = 375.0 / 44.0 = 8 buttons.
While the iPhone 6 Plus can have a total of
T' = 540.0 / 44.0 = 12 buttons with each button being physically smaller.
The way to fix this is by figuring out the adjusted width of the buttons for the iPhone 6 Plus which is w' = 44.0 px * 401 ppi / 326 ppi = 54.0 pixels.
So, each button on the iPhone 6 Plus should have a width of 54 pixels to be of the same physical size.
Am I thinking correct?
A:
You're right about the math, points in iOS has nothing to do with physical size.
physicalSize = points * scale / ppi
5.5" 44*3/401 ≈ 0.33 inch
4.7" 44*2/326 ≈ 0.27 inch
So in order to guarantee the same physical size you need to calculate it manually for each device, which is not the best practice anyway.
From the above formula you get this:
points = physicalSize * ppi / scale
Swift function:
func points(fromInches inches: CGFloat) -> CGFloat {
return inches * ppi / UIScreen.main.scale
}
var ppi: CGFloat {
//return device ppi
}
Check this question about getting ppi programmatically:
Edit:
I would still recommend thinking in terms of points, not in terms of physical screen size.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Please reconsider the rule: Pseudocode, hypothetical code, or stub code should be replaced by a concrete example?
Related:
Why is hypothetical example code off-topic for Code Review?
Is pseudo-code alright when asking about performance?
The gray areas of Code Review: Hypothetical / Example code
My concrete examples usually contain some proprietary things. Even a variable name or package name can convey something that is not meant to be public.
From Stack Overflow I've learnt to simplify, minimize, and isolate the problem.
(ask specific questions, MCVE, ...)
Examples of question one may want to ask:
What is the recommended way of passing arguments to a function in JavaScript?
var f1 = function(firstname, lastname) { ... };
var f2 = function(options) { ... };
f1("Michal", "Stefanow");
f2({firstname: "Michal", "lastname": "Stefanow"});
It is hypothetical code, yet in my opinion it is a perfectly valid question about best practices in terms of code structure and readability.
Another one I would like to ask personally but I cannot post it to Code Review as it is hypothetical. And I cannot include the actual code because variable names convey some meaning and I want to avoid paying hefty compensation.
What would be the best way to ask the question about following code?
Option 1:
var iammicrowave = /(microwave)/.test(navigator.userAgent);
if (iammicrowave) {
var settings = { blah : 42 };
magicFunction(settings);
} else {
magicFunction();
}
Option 2:
var iammicrowave = /(microwave)/.test(navigator.userAgent);
var settings;
if (iammicrowave) {
settings = { blah : 42 };
}
magicFunction(settings);
Option 3:
var iammicrowave = /(microwave)/.test(navigator.userAgent);
var settings = imamicrowave ? { blah : 42 } : undefined; // or maybe {} here?
magicFunction(settings);
Should I:
Post on Code Review anyway?
Post on Stack Overflow?
Read more books?
Make friends with developers who are better than me?
The actual question asked here.
A:
We've all been there one time or another, so we understand what your problem is.
However, we simply can not throw this rule out of the window. It makes it unnecessarily hard on the reviewers and it would open the door for categories of questions we really don't want here. Please scour the meta for examples; I'll update this answer later with the most concrete examples if preferred.
The solution I prefer would be making a 'hobby' project which looks a lot like the real deal but with a different application. If you build a web server in a language on your work and you want to know whether you handled certain API calls correctly (just an example) but you can't disclose the code, consider writing a hobby version which contains most of the details you're interested in but isn't classified. This won't help you with the actual code, but it will point out flaws in your programming style and teach you to be a better programmer.
One of the typical things we review are variable names. If your variable names are foo, bar and f1, we will tell you to get better variable names. If you have better variable names but gave these place-holders because the actual variable names are classified, you wasted your own and our time.
And, if all else fails, consider one of the other Stack Exchange sites. There are quite a lot of them around.
A:
Let me quote the help center here:
However, if your question is not about a particular piece of code and
instead is a generally applicable question about…
Best practices in general (that is, it's okay to ask "Does this code
follow common best practices?", but not "What is the best practice
regarding X?")
Tools, improving, or conducting code reviews
[...]
then your question is off-topic for this site.
Your questions you lead as examples to allow hypothetical code are violating this rule, that is they are askin about best practices in general.
Allowing hypothetical code would breach this distinction, and as such I think hypothetical code being off-topic is just a consequence of this rule.
Code Review cannot provide a collection of general best-practices, while also providing guidance for specific questions. Additionally questions asking about hypothetical code are often too broad or unclear.
Context is extremely important for codereview. That said, there is a possibility to ask your questions anyway.
You could rewrite the variable names specifically for Code Review. I know that this has been done before¹
¹ As far as I know it's the less common case, though. e.g.: this vba question
A:
Looking at your profile on the main site, it seems that you have not yet answered any questions on Code Review. I think that by the time you have written a few tens of answers, then your opinion on this issue will have changed.
Source code is rarely an end in itself; it is nearly always a means to solving someone's problem. So when answering a question on Code Review, the issue that we always need to have in our minds is, how well does this code solve the poster's problem? In the absence of an actual problem to solve, there is no objective basis to build a review on. That's why hypothetical questions are off-topic here: they simply can't be answered.
To take your examples:
What is the recommended way of passing arguments to a function in JavaScript?
Recommended for what purpose? In some cases it is best to pass arguments by position, and in other cases it is best to pass arguments by name, and in yet other cases it probably doesn't make any difference. We have to see the actual case in order to answer the question for that case.
Similarly, in your magicFunction example, it really depends on the parameters taken by magicFunction, and what microwaves really put in their user agent strings, and how often this code gets called, and whether settings needs to be cached somewhere to avoid having to re-parse the user agent string, and so on. We need to see the actual details.
So what should you do?
"Post on Code Review anyway?" — no, hypothetical code is off-topic here.
"Post on Stack Overflow?" — no, subjective questions are off-topic there.
"Read more books?" — a good idea, but books are not likely to help you with this kind of style issue.
"Make friends with developers who are better than me?" — also a good idea, but no matter how good your developer friends are they won't be able to review your hypothetical code any better than we can here at Code Review!
I recommend not worrying about minor issues of style, and instead writing real code solving real problems. When you have a doubt about which way to write some bit of code, pick one way (as best you can) and see if it works out for you — do you still understand it when you come back a week later? did it turn out to have bugs in it that you might have been able to avoid if you had written it differently? was it easy to modify when your requirements changed? was it easy to debug when there was a problem? Then if you are still in doubt you can ask for a review here, and since you have real code it will be on topic.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get a stack trace in .NET in normal execution?
In VB .NET, I know I can get a stack trace by looking at the value of ex.StackTrace when handling an exception. How can I get the functions on the stack when I am not handling an exception? I am looking to implement a logging system of some sort to record the steps the user takes prior to a crash to assist in debugging.
A:
Environment.StackTrace gives you a string, but for more detailed information and options, use the StackTrace class.
To be more specific, check out the constructor options:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.stacktrace.aspx
If you need the stack trace starting at the caller's frame (e.g. in a logging function: you don't want everything to start with MyLogMethod), you should try this one, which takes an int parameter, the number of frames to skip.
http://msdn.microsoft.com/en-us/library/wybch8k4.aspx
If you need the stack trace without source information (e.g. if you don't want to give away information about your source code), try this one:
http://msdn.microsoft.com/en-us/library/6zh7csxz.aspx
Hope that helps!
A:
Environment.StackTrace
A:
System.Environment.StackTrace
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Running time and standard deviation of Marsaglia and Bray's Polar Method
I have some trouble calculating the standard Deviation and the mean running time of the polar method by Marsaglia and Bray. More specifically the repeat portion of the algorithm. In this case the $U_k$ values are independent uniform variables so they Change with each iteration.
The Basic algorithm goes as follows:
$$repeat:$$
$$V_1 = 2*U_1 - 1 ;U_1 \in (0,1) ;V_1 \in (-1,1)$$
$$V_2 = 2*U_2 - 1 ;U_2 \in (0,1) ;V_2 \in (-1,1)$$
$$S = V_1^2 + V_2^2 $$
$$until(S<1)$$
$$X_1 = V_1 * \sqrt(-2lnS/S) $$
$$X_2 = V_2 * \sqrt(-2lnS/S) $$
I would really appreciate some starting points. Thanks in advance.
In particular, I seek the running time of the repeat method and the standard deviation of that running time.
From what i can see the best case would be: $O(1)$ the worst case $O(n)$.
A:
For every single loop, the probability to succeed is $p=\frac{\pi}{4}$. The probability to succeed after $k$ iterations is $(1-p)^{k-1}p$, as it requires $k-1$ fails before that. The expectation is thus
$$
\sum_{k=1}^\infty k(1-p)^{k-1}p
$$
which is related to the geometric series. The variance requires to also compute
$$
\sum_{k=1}^\infty k^2(1-p)^{k-1}p
$$
You might be faster by computing the generating function of the moments
$$
\sum_{k=1}^\infty e^{-kt}(1-p)^{k-1}p
$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Nice scrolling parallax effect isn't working
This is the link to the website: http://codepen.io/zabielski/pen/MyoBaY/
I am following the instructions and code from this website to try and get a similar scrolling parallax effect. Below is my HTML, CSS and JavaScript code (basically just copying but with my own images and stuff).
<!DOCTYPE html>
<html lang="en">
<!--Meta equiv for the whole web page to be emulated into IE straight from the chrome styling, If this is not done, then the whole webpage is green instead of the gray and orange and the text on the opage is shoved onto the far left side of the page.-->
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7"/>
<!--Link to Favicon-->
<link rel="shortcut icon" type="image/x-icon" href="Favicon/Ulearn.ico">
<!--Links to CSS style sheet-->
<link rel="stylesheet" type="text/css" href="CSS style sheets/Main style sheet.css">
<link rel="stylesheet" type="text/css" href="CSS style sheets/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="CSS style sheets/animate.min.css">
<!--Links to JavaScript external sheets-->
<script type="text/javascript" src="JavaScript sheets/Main javascript.js"></script>
<script type="text/javascript" src="JavaScript sheets/jquery-2.2.3.js"></script>
<head>
<span class="header">Physics Level 3</span>
<!--Meta and links to make sure the webpage is dynamic-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Playfair+Display' rel='stylesheet' type='text/css'>
</head>
<body>
<div id='hero'>
<div class='layer-1 layer' data-depth='0.20' data-type='parallax'></div>
<div class='layer-2 layer' data-depth='0.50' data-type='parallax'></div>
<div class='layer-3 layer' data-depth='0.80' data-type='parallax'></div>
<div class='layer-4 layer' data-depth='1.00' data-type='parallax'></div>
</div>
<div id="content">
</div>
</body>
</html>
#hero {
height: 1000px;
overflow: hidden;
position: relative;
}
.header {
background-color: white;
border-style: solid;
border-width: 0px;
position: absolute;
text-align: left;
left: 1%;
top: 2.4%;
width: 97%;
padding-top: 1%;
padding-bottom: 1%;
padding-left: 0.7%;
padding-right: 0.2%;
z-index: 1;
}
.layer {
background-position: center;
background-size: auto;
width: 100%;
height: 800px;
position: fixed;
z-index: -1;
}
.layer-1 {
background-image: url("background-last.jpg");
}
.layer-2 {
background-image: url("background-middle.png");
background-repeat: no-repeat;
background-position: center;
}
.layer-3 {
background-image: url("background-top.png");
background-repeat: no-repeat;
}
.layer-4 {
background-image: url("background-verytop.png");
}
(function () {
window.addEventListener('scroll', function (event) {
var depth, i, layer, layers, len, movement, topDistance, translate3d;
topDistance = this.pageYOffset;
layers = document.querySelectorAll('[data-type=\'parallax\']');
for (i = 0, len = layers.length; i < len; i++) {
if (window.CP.shouldStopExecution(1)) {
break;
}
layer = layers[i];
depth = layer.getAttribute('data-depth');
movement = -(topDistance * depth);
translate3d = 'translate3d(0, ' + movement + 'px, 0)';
layer.style['-webkit-transform'] = translate3d;
layer.style['-moz-transform'] = translate3d;
layer.style['-ms-transform'] = translate3d;
layer.style['-o-transform'] = translate3d;
layer.style.transform = translate3d;
}
window.CP.exitedLoop(1);
});
}.call(this));
A:
You cant just copy and paste all off the contents, you must format it - the code was specially compiled.
Here's the formatted RAW page:
<html class="animated fadeIn">
<head>
<script src="//assets.codepen.io/assets/editor/live/console_runner-d0a557e5cb67f9cd9bbb9673355c7e8e.js"></script><script src="//assets.codepen.io/assets/editor/live/events_runner-21174b4c7273cfddc124acb0876792e0.js"></script><script src="//assets.codepen.io/assets/editor/live/css_live_reload_init-7618a0de08795409d8f6c9ef6805f7b2.js"></script>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<link rel="canonical" href="http://codepen.io/zabielski/pen/MyoBaY/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Playfair+Display" rel="stylesheet" type="text/css">
<link rel="stylesheet prefetch" href="//codepen.io/assets/reset/normalize.css">
<link rel="stylesheet prefetch" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet prefetch" href="//cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.3/animate.min.css">
<style class="cp-pen-styles">body {
padding: 0;
margin: 0;
background-color: #130d0a;
font-family: 'Playfair Display', serif;
color: #fff;
}
#hero {
height: 800px;
overflow: hidden;
position: relative;
}
#content {
background-color: #130d0a;
}
.layer {
background-position: bottom center;
background-size: auto;
background-repeat: no-repeat;
width: 100%;
height: 800px;
position: fixed;
z-index: -1;
}
#hero-mobile {
display: none;
background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/full_illustration.png") no-repeat center bottom/cover;
height: 320px;
}
.first-section {
padding: 50px 0 20px 0;
}
.text-header {
font-size: 50px;
text-align: center;
}
h1 {
line-height: 120%;
margin-bottom: 30px;
}
p {
color: #ede0d5;
font-size: 18px;
line-height: 150%;
}
#hero, .layer {
min-height: 800px;
}
.layer-bg {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_bg.jpg");
}
.layer-1 {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_03.png\a ");
background-position: left bottom;
}
.layer-2 {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_02.png");
}
.layer-3 {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_man.png\a ");
background-position: right bottom;
}
.layer-4 {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_01.png\a ");
}
.layer-overlay {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_overlay.png\a ");
}
@media only screen and (max-width: 768px) {
#hero {
display: none;
}
#hero-mobile {
display: block;
}
}
.tutorial-link {
color: #fff;
font-size: 18px;
text-decoration: underline;
}
.tutorial-link:hover {
color: #ede0d5;
}
</style>
</head>
<body>
<div id="hero">
<div class="layer-bg layer" data-depth="0.10" data-type="parallax"></div>
<div class="layer-1 layer" data-depth="0.20" data-type="parallax"></div>
<div class="layer-2 layer" data-depth="0.50" data-type="parallax"></div>
<div class="layer-3 layer" data-depth="0.80" data-type="parallax"></div>
<div class="layer-overlay layer" data-depth="0.85" data-type="parallax"></div>
<div class="layer-4 layer" data-depth="1.00" data-type="parallax"></div>
</div>
<div id="hero-mobile"></div>
<div id="content">
<div class="container">
<section class="first-section">
<div class="row">
<div class="col-sm-6">
<h1>You cannot hide the soul. Through all his unearthly tattooings, I thought I saw the traces of a simple honest heart.</h1>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<p>And besides all this, there was a certain lofty bearing about the Pagan, which even his uncouthness could not altogether maim. He looked like a man who had never cringed and never had had a creditor. Whether it was, too, that his head being shaved, his forehead was drawn out in freer and brighter relief, and looked more expansive than it otherwise would, this I will not venture to decide; but certain it was his head was phrenologically an excellent one.</p>
<p>It may seem ridiculous, but it reminded me of General Washington's head, as seen in the popular busts of him. It had the same long regularly graded retreating slope from above the brows, which were likewise very projecting, like two long promontories thickly wooded on top. Queequeg was George Washington cannibalistically developed.</p>
<p>Whilst I was thus closely scanning him, half-pretending meanwhile to be looking out at the storm from the casement, he never heeded my presence, never troubled himself with so much as a single glance; but appeared wholly occupied with counting the pages of the marvellous book. Considering how sociably we had been sleeping together the night previous, and especially considering the affectionate arm I had found thrown over me upon waking in the morning, I thought this indifference of his very strange. But savages are strange beings; at times you do not know exactly how to take them.</p>
</div>
<div class="col-sm-6">
<p>At first they are overawing; their calm self-collectedness of simplicity seems a Socratic wisdom. I had noticed also that Queequeg never consorted at all, or but very little, with the other seamen in the inn. He made no advances whatever; appeared to have no desire to enlarge the circle of his acquaintances. All this struck me as mighty singular; yet, upon second thoughts, there was something almost sublime in it. Here was a man some twenty thousand miles from home, by the way of Cape Horn, that is—which was the only way he could get there—thrown among people as strange to him as though he were in the planet Jupiter; and yet he seemed entirely at his ease; preserving the utmost serenity; content with his own companionship; always equal to himself.</p>
<p>Here was a man some twenty thousand miles from home, by the way of Cape Horn, that is—which was the only way he could get there—thrown among people as strange to him as though he were in the planet Jupiter; and yet he seemed entirely at his ease; preserving the utmost serenity; content with his own companionship; always equal to himself. Surely this was a touch of fine philosophy; though no doubt he had never heard there was such a thing as that.</p>
<a class="tutorial-link" href="https://medium.com/@PatrykZabielski/how-to-make-multi-layered-parallax-illustration-with-css-javascript-2b56883c3f27">
Learn how to create this parallax effect
</a>
</div>
</div>
</section>
</div>
</div>
<script src="//assets.codepen.io/assets/common/stopExecutionOnTimeout.js?t=1"></script>
<script>(function () {
window.addEventListener('scroll', function (event) {
var depth, i, layer, layers, len, movement, topDistance, translate3d;
topDistance = this.pageYOffset;
layers = document.querySelectorAll('[data-type=\'parallax\']');
for (i = 0, len = layers.length; i < len; i++) {
if (window.CP.shouldStopExecution(1)) {
break;
}
layer = layers[i];
depth = layer.getAttribute('data-depth');
movement = -(topDistance * depth);
translate3d = 'translate3d(0, ' + movement + 'px, 0)';
layer.style['-webkit-transform'] = translate3d;
layer.style['-moz-transform'] = translate3d;
layer.style['-ms-transform'] = translate3d;
layer.style['-o-transform'] = translate3d;
layer.style.transform = translate3d;
}
window.CP.exitedLoop(1);
});
}.call(this));
//# sourceURL=pen.js
</script>
</body>
</html>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android x86 emulator extremely slow
At the moment I'm developing an application with Android wear support but I have no smartwatch. Now I want to test my application on an emulator but that is the problem. The emulator need up to 1.5 hours to start. I created one with following settings:
<!-- language: lang-none -->
Target Google APIs (Google Inc.) API lev 22
CPU/ABI Google APIs Intel Atom (x86)
Device 5.1" WVGA (480x800: mdpi)
Skin No Skin
RAM 512 //also tried with 768
VM Heap 32
Internal Storage 200
Use Host GPU true //also tried with false
I installed HAXM, enabled it in the BIOS settings and if run
sc query intelhaxm
I get the status 4 like it is written here. I set the HAXM memmory to 2GB so it should be enought. I also do not run any other VM software and I have even reinstalled my Windows. The only interesting information from the LogCat is that there are many lines (up to 70%) of Suspending all threads
My computer has the following Hardware:
<!-- language: lang-none -->
Windows 7 x64
Intel Core 2 Quad Q6600
8GB RAM
Do you have any ideas why my emulator is so slow?
EDIT: Here I posted the target for a smartphone device but it's also so slow for wearable devices so Genymotion is no real alternative because it has no images for them.
A:
Well dont know for sure but all the native emulator in android are very slow.
I suggest that you use the Genymotion which is very faster emulators for android than native.
It will give you user experience almost as of devices though it does have the same limitation of android native emulators.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Passing url as parameter in ARM template from CLI
I am trying to deploy azure resources using Linked ARM template, for which i places the parameters file and template file on blob storage. Link for parameter file and blob storage i need to pass as parameter while executing the azure command from CLI. Below is my sample masterazuredeploy.json
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {},
"variables": {
"templateBaseUrl": "[parameters('templateBaseUrl')]",
"parameterBaseUrl": "[parameters('parameterBaseUrl')]",
"keyVaultDeployTemplateUrl": "[uri(variables('templateBaseUrl'), 'keyvaultdeploy.json')]"
},
"resources": [
{
"apiVersion": "[variables('apiVersionResourceDeployment')]",
"name": "keyVaultDeployment",
"type": "Microsoft.Resources/deployments",
"properties": {
"mode": "Incremental",
"templateLink": {
"uri": "[variables('keyVaultDeployTemplateUrl')]"
},
"parametersLink": {
"uri": "[variables('keyVaultparameterFileUrl')]"
}
}
}
]
}
To execute this i am giving following CLI command:
az group deployment create --resource-group abc-devops-test --template-file .\masterazuredeploy.json --parameters templateBaseUrl="https://test.blob.core
.windows.net/azurestackautomationtest/resourcetemplates/" parameterBaseUrl="https://test.blob.core.windows.net/azurestackautomationtest/parameters/dev/" --verbose
While executing i am getting following error:
unrecognized template parameter 'templateBaseUrl'. Allowed parameters:
command ran in 1.918 seconds.
I tried parameter values without inverted quotes, with single quotes. Still not working. Where exactly i am missing.
Also tried the another approach, placed both parameters in global.parameters.json as below,
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"templateBaseUrl": {
"value": "https://test.blob.core.windows.net/azurestackautomation/resourcetemplates/"
},
"parameterBaseUrl": {
"value": "https://test.blob.core.windows.net/azurestackautomation/parameters/dev/"
}
}
}
and uploaded this file to blob storage, and given path of blob storage as parameter
az group deployment create --resource-group abc-devops-test --template-file .\masterazuredeploy.json --parameters https://test.blob.core.windows.net/azur
estackautomationtest/parameters/dev/global.parameters.json --verbose
But getting below error:
400 Client Error: Bad Request for url: https://management.azure.com/subscriptions/XXXX-xx-x-x-x--x-x/resourcegroups/abc-devops-test/providers/Microsoft.Resources/deployments/masterazuredeploy?api-version=2018-05-01
command ran in 5.646 seconds.
A:
As I see in your template, you miss setting the parameters, what you did is to input the parameter values to the parameters in the template, no matter the both CLI command you have provided. But you did not set parameters so that no parameters you can use. I suggest you change the template into below:
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"templateBaseUrl": {
"type": "string"
},
"parameterBaseUrl": {
"type": "string"
}
},
"variables": {
"keyVaultDeployTemplateUrl": "[uri(parameters('templateBaseUrl'), 'keyvaultdeploy.json')]"
},
"resources": [
{
"apiVersion": "[variables('apiVersionResourceDeployment')]", #1
"name": "keyVaultDeployment",
"type": "Microsoft.Resources/deployments",
"properties": {
"mode": "Incremental",
"templateLink": {
"uri": "[variables('keyVaultDeployTemplateUrl')]"
},
"parametersLink": {
"uri": "[variables('keyVaultparameterFileUrl')]" #2
}
}
}
]
}
And you also miss setting the variables apiVersionResourceDeployment and keyVaultparameterFileUrl. You can use both parameter and variable as you like.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dirichlet series in terms of primitive characters
Let $\chi$ be a character mod $m$. Consider the Dirichlet series
$$ L(s,\chi)=\sum_{n=1}^{\infty}\chi(n)/(n^s)$$ We know that if $\chi$ is no trivial: $$L(s,\chi)=\prod_{p\nmid m}(1-\chi(p)/(p^s))^{-1}$$
Now if $\chi'$ is a character mod $d$ such that $d|m$ and $\chi'$ induces $\chi$, prove that $$ L(1,\chi)=\prod_{p|m,p\nmid d}(1-\chi'(p)/p)L(1,\chi')$$
I tried using the fact that if $\chi'$ induces $\chi$, then they should have same results, but failing.
I thought something like this, let $f$ denote the trivial character mod $m$, then $L(1,\chi)=\prod_{p}(1-(\chi'(p)f(p))/p)^{-1}=\prod_{p\nmid d}(1-(\chi'(p)f(p)/p)^{-1}$ but I'm not sure and I can't see how to proceed.
A:
If $a(n)$ is multiplicative (that is $gcd(n,m) = 1 \implies a(n) a(m) = a(nm)$) then as formal Dirichlet series $$\sum_{n=1}^\infty a(n) n^{-s} = \prod_p (1+\sum_{k=1}^\infty a(p^k) p^{-sk})$$
(Euler product)
Now $a(n)$ is completely multiplicative (that is $\forall n,m , a(n) a(m) = a(nm)$) iff $$\sum_{n=1}^\infty a(n) n^{-s} = \prod_p (1+\sum_{k=1}^\infty a(p)^k p^{-sk}) = \prod_p \frac{1}{1-a(p) p^{-s}}$$
Since a Dirichlet character $\chi(n)$ is completely multiplicative and periodic, $|\chi(n)|$ is bounded and so
$$L(s,\chi) = \sum_{n=1}^\infty \chi(n) n^{-s} = \prod_p \frac{1}{1-\chi(p) p^{-s}}$$ converges absolutely and is analytic for $Re(s) > 1$ (Note : an Euler product is said to converge iff the Dirichlet series for its logarithm converges)
From this, you easily get that if $\psi(n) = \chi(n) 1_{gcd(n,k)=1}$ is a non-primitive character induced by $\chi(n)$ a character modulo $m$ then
$$L(s,\psi) = \prod_p \frac{1}{1-\psi(p) p^{-s}}=\prod_p \frac{1}{1-1_{gcd(p,k)=1}\chi(p) p^{-s}}$$
$$=\prod_{p\, {\displaystyle\nmid}\, k} \frac{1}{1-\chi(p) p^{-s}} = L(s,\chi) \prod_{p | k} (1-\chi(p)p^{-s})= L(s,\chi) \prod_{p | k, p \, {\displaystyle\nmid}\, m} (1-\chi(p)p^{-s})$$
Finally, using some non-trivial theorems (see a proof of the prime number theorem and the PNT in arithmetic progressions) you get that the Euler product for $L(s,\chi)$ converges and is analytic on $Re(s) = 1$ whenever $\chi$ is non-principal, and so
$$L(1,\psi) = L(1,\chi) \prod_{p | k, p\, {\displaystyle\nmid}\, m} (1-\chi(p)p^{-1})$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
$A\subseteq B\subseteq X\implies f(A)\subseteq f(B)$. Show that, in general, the inclusions are proper.
Let $f:\mathcal P(X)\to\mathcal P(Y)$. Then $A\subseteq B\subseteq X\implies f(A)\subseteq f(B)$. Show that, in general, the inclusions are proper.
The function $f:\mathcal P(X)\to\mathcal P(Y)$ is a set-valued function induced from a function $f:X\to Y$, where $\mathcal P(X)$ and $\mathcal P(Y)$ are the power sets of $X$ and $Y$ respectively.
I dont understand this exercise (one of the first exercises of the Real analysis of Amann and Escher). If $f$ is a constant function then we have that the statement
$$A\subsetneq B\subsetneq X\implies f(A)\subsetneq f(B)$$
is not true because $f(A)=f(B)$. So, Im wrong in the interpretation of this problem? Can someone enlighten this question? Thank you in advance.
A:
I suspect it should be $f: X \to Y$, not ${\mathcal P}(X) \to {\mathcal P}(Y)$. Then it is true that $A \subseteq B \implies f(A) \subseteq f(B)$, where $f(A)$ means $\{f(a) \;: \; a \in A\}$.
EDIT: Ah, the extra bit "The function $f:P(X) \to P(Y)$ is a set-valued function induced from a function $f:X \to Y$" makes it clear that my interpretation is the correct one. This is exactly how a set-valued function on the power set is induced by a function from $X$ to $Y$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rsync statistics number of files
I'm using rsync with -vrlHh --delete --stats --force options to mirror two directories.
The first directory is the source and it's my external hd, the destination directory is empty because I've just created it.
I run rsync -vrlHh --delete --stats --force my_hd dest_dir and I get this output.
...
2012/05/12 11:59:29 [18094] Number of files: 189315
2012/05/12 11:59:29 [18094] Number of files transferred: 178767
2012/05/12 11:59:29 [18094] Total file size: 241.57G bytes
2012/05/12 11:59:29 [18094] Total transferred file size: 241.57G bytes
2012/05/12 11:59:29 [18094] Literal data: 241.57G bytes
2012/05/12 11:59:29 [18094] Matched data: 0 bytes
2012/05/12 11:59:29 [18094] File list size: 4.08M
2012/05/12 11:59:29 [18094] File list generation time: 0.002 seconds
2012/05/12 11:59:29 [18094] File list transfer time: 0.000 seconds
2012/05/12 11:59:29 [18094] Total bytes sent: 241.61G
2012/05/12 11:59:29 [18094] Total bytes received: 3.44M
2012/05/12 11:59:29 [18094] sent 241.61G bytes received 3.44M bytes 30.67M bytes/sec
2012/05/12 11:59:29 [18094] total size is 241.57G speedup is 1.00
My question is why Number of files and Number of file transferred are different if the destination directory was empty?
A:
I believe you are experiencing http://lists.samba.org/archive/rsync/2008-April/020692.html.
In short, rsync uses the word "file" in different ways depending on context. In your first "Number of files" count it counts everything. In your second "Number of files transferred", it does not count symbolic links and directories as files.
Example:
$ mkdir test
$ touch test/testfile
$ ln -s testfile test/testlink
$ ls -FR test
test:
testfile testlink@
$ rsync -vrlHh --stats test test2
sending incremental file list
created directory test2
test/
test/testfile
test/testlink -> testfile
Number of files: 3
Number of files transferred: 1
Total file size: 8 bytes
Total transferred file size: 0 bytes
Literal data: 0 bytes
Matched data: 0 bytes
File list size: 67
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 126
Total bytes received: 38
sent 126 bytes received 38 bytes 328.00 bytes/sec
total size is 8 speedup is 0.05
$ ls -FR test2
test2:
test/
test2/test:
testfile testlink@
A:
From author 'Mike Bombich' in [email protected] :
For stats, rsync uses the word "file" inconsistently. When reporting
the total "Number of files", it indicates a total number of filesystem
objects which consists of regular files, directories, symlinks,
specials, and devices. When reporting number of "files" transferred,
it refers only to regular files.
So if there are any non-regular files in there (inc. directories) they won't be included in the count.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Acer_wmi blocking my wifi
Every time I log in I have to type "sudo rmmod acer_wmi" to get wifi to work. How do I get this to run on startup or permanantly delete acer_wmi.
Thx
A:
Edit the blacklist:
sudo vi /etc/modprobe.d/blacklist.conf
And add the faulty module there (at the end):
blacklist acer_wmi
reboot and voilà
|
{
"pile_set_name": "StackExchange"
}
|
Q:
File System Transactions using .NET on WinXP
I'm using WinXP on clients and Win2003 on a server.
I need do atomic actions: create-moving files, insert-update database.
Are there any good practices for file system transactions using WinXP?
I know in Vista/Win2008/Win7 there are TxF transaction (NTFS) but not in WinXP.
I don't want use COM+, neither other complex solutions. Only need good sample code, for good practices.
Transactions and file-actions by Alberto Poblacion
In versions of Windows earlier than Vista, the filesystem is not
transactional, so you need a separate tool to do transactions on your files.
You could use Component Services (COM+) to implement a Compensating Resource
Manager (CRM). The CRM will provide the transaction log and will roll back
changes during a system restart if it crashed during the update of your
files, but you will have to provide the code (in your own DLL) to commit and
rollback the transation, typically by means of moving files in and out of a
temp folder. It can all be done in .Net by means of the
System.EnterpriseServices namespace. If I recall correctly, Microsoft
Official Course 2557 contains a chapter that teaches how to create a CRM,
and the example that they use is built precisely on changes to the
filesystem.
In newer versions of Windows, you can do transactional operations on
NTFS:
http://msdn.microsoft.com/en-us/library/bb986748(VS.85).aspx
http://msdn.microsoft.com/en-us/magazine/cc163388.aspx
http://codeproject.com/KB/vista/VistaKTM.aspx
Edit.
References:
https://transactionalfilemgr.codeplex.com/
http://www.codeproject.com/Articles/690136/All-About-TransactionScope
http://ayende.com/blog/4528/who-stole-my-transaction
http://www.chinhdo.com/20080825/transactional-file-manager/
http://bmegias.wordpress.com/2010/10/25/ejecutar-acciones-al-finalizar-la-transaccion-transactioncompleted-vs-enlistvolatile/
A:
You could create your own class that implements IEnlistmentNotification.
Here's an example of someone that did: http://www.chinhdo.com/20080825/transactional-file-manager/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to make synchronous http request in angular js
How to make blocking http request in AngularJS so that i can use the $http response on very next line?
In the following example, $http object doesn't return the result to the next line so that I can pass this result to fullcalender(), a JavaScript library, because $scope.data returns blank value.
This is the sample code:
$http.get('URL').success(function(data){
$scope.data = data;
});
$.fullCalender({
data: $scope.data
});
A:
You can use promises for that.
here is an example:
$scope.myXhr = function(){
var deferred = $q.defer();
$http({
url: 'ajax.php',
method: 'POST',
data:postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
//if request is successful
.success(function(data,status,headers,config){
//resolve the promise
deferred.resolve('request successful');
})
//if request is not successful
.error(function(data,status,headers,config){
//reject the promise
deferred.reject('ERROR');
});
//return the promise
return deferred.promise;
}
$scope.callXhrAsynchronous = function(){
var myPromise = $scope.myXhr();
// wait until the promise return resolve or eject
//"then" has 2 functions (resolveFunction, rejectFunction)
myPromise.then(function(resolve){
alert(resolve);
}, function(reject){
alert(reject)
});
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
getting marginal from the joint distributiion function
Given joint probability distribution function $F(x,y)= 1-e^{-x}-e^{-y}+e^{-x-y}$ for $x>0,y>0$.
How do we get the marginal distribution functions?
I thought of taking the derivative, but after taken the derivative with respect to x, the resulting function has a y term.
A:
Assuming that by "joint probability distribution" you mean the joint cumulative distribution function (CDF) defined by
$$
F(x,y) := \mathbb P(X\le x, Y\le y),
$$
you obtain the marginal CDFs by
$$
F_X(x) = \mathbb P(X\le x)
=
\lim_{y\to\infty} \mathbb P(X\le x, Y\le y)
=
\lim_{y\to\infty} F(x,y)
=
1-e^{-x}
$$
and similarly $F_Y(y) = 1-e^{-y}$. If you want to obtain the marginal probability densities, you just differentiate the CDFs and get $f_X(x) = e^{-x},\ f_Y(y) = e^{-y}$.
In your specific case, things can be obtained in an easier way, since the joint CDF factorizes (is a product of two marginal CDFs):
$$
F(x,y)
=
1-e^{-x}-e^{-y}+e^{-x-y}
=
(1-e^{-x})(1-e^{-y}),
$$
therefore $F_X(x) = (1-e^{-x})$ and $F_Y(y) = 1-e^{-y}$ can be seen directly.
A:
Remark: This response is not my own. Since it's been a day now and OP has not unaccepted this answer, on the recommendation of StubbornAtom I have edited this response to include the correct response of iljusch. This response belongs to iljusch, and OP should really, it seems, accept that response, whence I can delete this one
Assuming that by "joint probability distribution" you mean the joint cumulative distribution function (CDF) defined by
$$
F(x,y) := \mathbb P(X\le x, Y\le y),
$$
you obtain the marginal CDFs by
$$
F_X(x) = \mathbb P(X\le x)
=
\lim_{y\to\infty} \mathbb P(X\le x, Y\le y)
=
\lim_{y\to\infty} F(x,y)
=
1-e^{-x}
$$
and similarly $F_Y(y) = 1-e^{-y}$. If you want to obtain the marginal probability densities, you just differentiate the CDFs and get $f_X(x) = e^{-x},\ f_Y(y) = e^{-y}$.
In your specific case, things can be obtained in an easier way, since the joint CDF factorizes (is a product of two marginal CDFs):
$$
F(x,y)
=
1-e^{-x}-e^{-y}+e^{-x-y}
=
(1-e^{-x})(1-e^{-y}),
$$
therefore $F_X(x) = (1-e^{-x})$ and $F_Y(y) = 1-e^{-y}$ can be seen directly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
socat:get sender's IP address
I use following code to receive a connection:
socat TCP-LISTEN:4000,fork EXEC:"./myscrpit"
I need to have a sender's IP address in my script but SOCAT_PEERADDR is not set, what is the problem?
A:
use pktinfo option for TCP-LISTEN so use following code:
socat TCP-LISTEN:4000,pktinfo,fork EXEC:"./myscrpit
|
{
"pile_set_name": "StackExchange"
}
|
Q:
qTip: How to get the tip's outer div?
I have examined the API carefully but I have not found the way to do it.
What I need is: I have a link to qtip object. The baloon tip itself has the container div, all the stuff (title, content, borders) is inside. How can I get that outer div?
A:
From inspecting the DOM, it looks like all of the qTip elements are wrapped in one div with a class of qtip.
You should be able to use the jQuery parent method to select the outermost container from your reference. Assuming your reference is called tip:
var outer = tip.parent('.qtip');
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can $\mathbb Q$ be countable, when there is no "next" rational number?
I understand this proof that $\mathbb{Q}$ is countable:
The rational numbers are arranged thus:
$$\displaystyle \frac 0 1, \frac 1 1, \frac {-1} 1, \frac 1 2, \frac {-1} 2, \frac 2 1, \frac {-2} 1, \frac 1 3, \frac 2 3, \frac {-1} 3, \frac {-2} 3, \frac 3 1, \frac 3 2, \frac {-3} 1, \frac {-3} 2, \frac 1 4, \frac 3 4, \frac {-1} 4, \frac {-3} 4, \frac 4 1, \frac 4 3, \frac {-4} 1, \frac {-4} 3 \ldots$$
It is clear that every rational number will appear somewhere in this list.
Thus it is possible to set up a bijection between each rational number and its position in the list, which is an element of $\mathbb N$. $\square$
However, given any rational number, say $3$, there is no "next" rational number, as $\mathbb Q$ is dense in $\mathbb R$. But, given any natural number, we can determine the next natural number (i.e. its successor, given by $S(n)=n+1$).
This seems to contradict the fact that there's a bijection between $\mathbb Q$ and $\mathbb N$. Could someone clear this up?
(Forgive me for any misconceptions/mistakes- I'm an amateur in set theory)
A:
The 'next' rational after $\frac{3}{1}=3$, in this context, is $\frac{3}{2}$. If you like let $\varphi$ be the bijection $\varphi:\mathbb{N}\rightarrow \mathbb{Q}$. Then we do have
$$\varphi(12)=\frac{3}{1}=3$$
and perhaps we might write
$$S^\varphi_{\mathbb{Q}}(3):=\varphi(S(\varphi^{-1}(3)))=\varphi(S(12))=\varphi(13)=\frac{3}{2},$$
where $S:\mathbb{N}\rightarrow\mathbb{N}$ is the successor function $S(n)=n+1$ and we might call $S^\varphi_\mathbb{Q}$ is the successor function of $\mathbb{Q}$ with respect to $\varphi$ defined by
$$S_\mathbb{Q}^\varphi:\mathbb{Q}\rightarrow \mathbb{Q},\,\,q\mapsto \varphi(S(\varphi^{-1}(q)))$$
A:
First let's ask a different question.
How can $\Bbb Z$ be countable, if every number is a successor in the integers, whereas in $\Bbb N$ there is a number which is not a successor?
The answer to this question, and the answer to the question why is $\Bbb Q$ countable are the same answer: Because a bijection is not order preserving.
Cardinality of a set is what remains when you "shake off" any structure it has or might have had. Namely, cardinality is determined by functions which are not necessarily preserving any structure whatsoever (order, addition, multiplication, etc.).
It is true that it's harder to see why $\Bbb Q$ is countable compared to $\Bbb Z$, especially when $\Bbb R$ is not countable and both are dense ordered sets. But if you understand why $\Bbb Z$ is countable, then you shouldn't have any difficulties understand the case for $\Bbb Q$: we can prove that there is a bijection between $\Bbb Q$ and $\Bbb N$, and therefore it is countable.
A:
When you say "next", you are probably transferring a feature from $\Bbb N$ that $\Bbb Q$ lacks, namely well-orderedness in the natural order.
But $\Bbb Q$ can be given other orders that allow each element to have a successor, and your partial organized list is a case in point. Any bijection with the naturals would induce a well ordering on $\Bbb Q$ by simply enforcing the order on the natural numbers on their images. Conversely, you can create an order on the naturals by finding a bijection of $\Bbb Q$ with $\Bbb N$ and then using $\Bbb Q$'s natural order to put a new order on the natural numbers in which elements wouldn't have successors.
Having successors for elements in a particular order simply doesn't have much to do with cardinality. You can have sets of large size where elements have successors, and sets of large size that don't.
Density and cardinality are two distinct types of "largeness." Lack of successors does not cause the cardinality to go out of control. It just speaks to the organization of the ordered set.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Approximation by locally Lipschitz functions
Could you tell me what is the name and/or reference for the following theorem:
Let $M$ be a metric space. Then any continuous function $f:M\to\mathbb R$ can be a be uniformly approximated by a locally Lipschitz functions.
A:
Actually the uniform density of locally Lipschitz functions is quite an immediate consequence of the paracompactness of metric spaces (Stone's theorem), and of the fact that, of course, metric spaces admit locally Lipschitz partitions of unity. Note that this way you also have the general result for Banach-valued functions, that is, with a given Banach space as a codomain.
A close result is that uniformly continuous ($\mathbb{R}$-valued) functions can be uniformly approximated by (uniformly) Lipschitz functions. In this case, an explicit approximation for a function $f$ is obtained just taking $f_k:=$ the infimum of all $k$-Lipschitz functions above $f.$ Then $f_k$ is k-Lipschitz and $f_k\to f$ uniformly as $k\to \infty$ (moreover, the uniform distance of $f$ and $f_k$ can be evaluated in terms of the modulus of continuity of $f$), without need of Stone's theorem. I think that variant of this construction should work for locally Lipschitz approximation of continuous functions (always in the scalar-valued case).
A:
oh what a good question it is ! i think this question is from the following paper :
see : https://projecteuclid.org/download/pdf_1/euclid.rae/1230939175
and your question is the same with theorem 2 in this paper !
is it helpful ? thank you !
A:
In that case, take a look at:
Lipschitz-type functions on metric spaces
M. Isabel Garrido, Jesús A. Jaramillo
Journal of Mathematical Analysis and Applications
Volume 340, Issue 1, 1 April 2008, Pages 282-290
Abstract
In order to find metric spaces X for which the algebra Lip*(X) of bounded Lipschitz functions on X determines the Lipschitz structure of X, we introduce the class of small-determined spaces. We show that this class includes precompact and quasi-convex metric spaces. We obtain several metric characterizations of this property, as well as some other characterizations given in terms of the uniform approximation and the extension of uniformly continuous functions. In particular we show that X is small-determined if and only if every uniformly continuous real function on X can be uniformly approximated by Lipschitz functions.
Keywords: Lipschitz functions; Banach–Stone theorem; Uniform approximation
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sharing Set Not Working
I have a custom object called Requisition. The idea is that a community user will create a requisition. The requisition will be re-assigned to a queue for processing.
This is all working fine. I have defined a sharing set for the community so that the community users will still be able to view requisitions while they are being worked.
After a user creates a requisition it is re-assigned and the user immediately loses visibility. Am I Missing something with my sharing set?
Note
I am good enough with apex that I could write a trigger to automatically share the record whenever the owner changes. I just don't think that is/should be necessary.
Update
I noticed my list views were all set to "my requisitions" I changed them to show "all requisitions" instead and still no luck.
Update 2
When I copy/paste the Id of the requisition into the URL I get a page not found error.
A:
Based on your screen shot, it looks like you need to apply the Sharing Set to a Profile to get it to grant access:
Select the profiles of the users to whom you want to provide access.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Convert complex music score to simpler one
I am currently trying to implement a software that can convert a complex music score (example) to a simpler one (example).
Do you guys know any technique or work that have been done before in order to achieve that?
Thanks in advance.
A:
In your example there are two main differences between the advanced and the easy. The first is the number of notes played at one time. Each hand seems to only play one note at a time in the easy version. This could be accomplished automatically by limiting the note output notes to the highest and the lowest in some way. The other difference is the rhythm seems less complex in the easy version. This can be accomplished through quantization which many music programs can do. In addition there may be range considerations. I didn't listen to the whole examples so I'm not sure if they did that or not. But many easy versions is pieces will limit the range that is used. This can be accomplished by transposing your output to within a certain range.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Naming a UIImagePickerController according to an NSString
I'm programatically creating x number of UIPicker instances and I want to retrieve the images picked using the didFinishPicking method. I therefore need a way to uniquely identify each picker instance. I'm trying to name each picker in the format picker# where # is the number of the picker instance. But I can't seem to figure out how to name the picker according to an NSString. What I'm basically asking is in the code below how can I name the UIImagePickerController with the NSString pickerName?
-(void) loadLibrary:(UIButton *)sender{
NSString *pickerName = [NSString stringWithFormat:@"picker%d",pickerCount];
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
A:
There is no built in way to "name" an image picker.
Since you only present and process one image picker at a time, the simplest solution is to use an instance variable to store your "picker name". Set the ivar when you create the image picker and then make use of the picker name in the image picker delegate method.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Verify if google event already exist before creating it
I used the google documentation to be able to add a google calendar event using python coding.
But what i want, is to be able to verify if X date time slot is empty before able to add the event.
here is my code :
from __future__ import print_function
from datetime import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/calendar']
event_summary = 'test123'
event_location = 'h4n1p9'
event_start = '2020-04-22T05:00:00-00:00'
event_end = '2020-04-22T08:00:00-00:00'
new_event = {
'summary': event_summary,
'location': event_location,
'description': '',
'start': {
'dateTime': event_start,
'timeZone': 'America/New_York',
},
'end': {
'dateTime': event_end,
'timeZone': 'America/New_York',
},
'reminders': {
'useDefault': True,
},
}
class PostToGoogleCalendar:
def __init__(self):
self.creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
self.creds = pickle.load(token)
if not self.creds or not self.creds.valid:
if self.creds and self.creds.expired and self.creds.refresh_token:
self.creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
self.creds = flow.run_local_server()
with open('token.pickle', 'wb') as token:
pickle.dump(self.creds, token)
self.service = build('calendar', 'v3', credentials=self.creds)
def get_events(self):
now = datetime.utcnow().isoformat() + 'Z'
events_result = self.service.events().list(calendarId='primary', timeMin=now,
maxResults=500, singleEvents=True,
orderBy='startTime').execute()
return events_result.get('items', [])
def create_event(self, new_event):
if not self.already_exists(new_event):
event = self.service.events().insert(calendarId='primary', body=new_event).execute()
return event.get('htmlLink')
else:
return 'Event Already Exists'
def already_exists(self, new_event):
events = self.get_date_events(new_event['start']['dateTime'], self.get_events())
event_list = [new_event['summary'] for new_event in events]
if new_event['summary'] not in event_list:
return False
else:
return True
def get_date_events(self, date, events):
lst = []
date = date
for event in events:
if event.get('start').get('dateTime'):
d1 = event['start']['dateTime']
if d1 == date:
lst.append(event)
return lst
This code is suppose to verify the events in 2020-04-22. IF theres an event at the chosen time, returns me that event is found, if not, create the event in calendar.
But it's not working, i get no error, but nothing happens neither..
A:
Here is the answer.
It adds the event if time slot is free, or else display the registered event if no free.
from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar']
def main():
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 1 event on the user's calendar.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
event_summary = 'Test_Cal'
event_location = 'h4n1p9'
event_description = 'test'
event_start = '2020-04-29T19:00:00-00:00'
event_end = '2020-04-29T20:00:00-00:00'
# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print('Looking if already created - if not, will create')
events_result = service.events().list(calendarId='primary', timeMin=event_start,
maxResults=1, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
event = {
'summary': event_summary,
'location': event_location,
'description': '',
'start': {
'dateTime': event_start,
'timeZone': 'America/New_York',
},
'end': {
'dateTime': event_end,
'timeZone': 'America/New_York',
},
'reminders': {
'useDefault': True,
},
}
event = service.events().insert(calendarId='primary', body=event).execute()
print('new event created')
for event in events:
print('Cannot create new event because time slot already taken by : ')
start = event['start'].get('dateTime', event['start'].get('date'))
print(start, event['summary'], event['location'])
if __name__ == '__main__':
main()
Feel free to comment if existing code can be modified.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Weirdness adding a lightning component to a JS Array
I have a component that looks like this:
<aura:component >
<aura:handler name="init" value="{!this}" action="{!c.init}"/>
<aura:attribute name="invoiceItems" type="Object[]" access="public"/>
<aura:iteration items="{!v.invoiceItems}" var="i" indexVar="x">
{!i}
</aura:iteration>
</aura:component>
The controller looks like this:
({
init : function(cmp, event, helper) {
$A.createComponent(
"c:Line_Item",
{
"invoiceItems" : cmp.getReference("v.invoiceItems")
},
function(newItem){
var items = cmp.get("v.invoiceItems");
items.push("v.invoiceItems", newItem);
cmp.set("v.invoiceItems", items);
}
);
}
})
And the dynamically created component looks like this:
<aura:component >
<aura:attribute name="invoiceItems" type="Object[]" access="public"/>
TEST ME
</aura:component>
When the "init" function is called and the first line item is added to the array it's adding the view label as well. Every iteration/row of the invoiceItem array looks like this:
v.invoiceItems
TEST ME
when it should just look like this:
TEST ME
I console.log'ed the invoiceItems array and it looks like this:
[]
0
:
"v.invoiceItems"
1
:
componentConstructor
length
:
2
__proto__
:
Array[0]
Why is it adding the label as the first element of the array and then the actual object as the second?
A:
I would guess it's this line of code:
items.push("v.invoiceItems", newItem);
Array.prototype.push is a standard JS function, not Lightning. If you include multiple arguments, each one is added to the array. So you have instructed to add the string "v.invoiceItems" and then also add newItem. Change it to:
items.push(newItem);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python - Plotting velocity and acceleration vectors at certain points
Here, i have a parametric equation.
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
t = np.linspace(0,2*np.pi, 40)
# Position Equation
def rx(t):
return t * np.cos(t)
def ry(t):
return t * np.sin(t)
# Velocity Vectors
def vx(t):
return np.cos(t) - t*np.sin(t)
def vy(t):
return np.sin(t) + t*np.cos(t)
# Acceleration Vectors
def ax(t):
return -2*np.sin(t) - t*np.cos(t)
def ay(t):
return 2*np.cos(t) - t*np.sin(t)
fig = plt.figure()
ax1 = fig.gca(projection='3d')
z = t
ax1.plot(rx(z), ry(z), z)
plt.xlim(-2*np.pi,2*np.pi)
plt.ylim(-6,6)
#ax1.legend() # no labels
plt.show()
So i have this parametric equation that creates this graph.
I have defined my velocity and acceleration parametric equations above in my code.
What i am wanting to do is to plot the acceleration and velocity vectors in my position graph above at defined points. (Id est, t = pi/2, 3pi/2, 2pi)
Something like this:
Plotting a 3d cube, a sphere and a vector in Matplotlib
but i want to do something more straight forward since i have to define each point t into two equations.
Is such a thing possible? I can only find vector fields and what not.
Something like this.
Thank you.
Edit Question
# t = pi/4
t_val_start_pi4 = np.pi/4
vel_start_pi4 = [rx(t_val_start_pi4), ry(t_val_start_pi4), t_val_start_pi4]
vel_end_pi4 = [rx(t_val_start_pi4 ) + vx(t_val_start_pi4 ), ry(t_val_start_pi4 )+vy(t_val_start_pi4 ), t_val_start_pi4 ]
vel_vecs_pi4 = (t_val_start_pi4 , vel_end_pi4)
vel_arrow_pi4 = Arrow3D(vel_vecs_pi4[0],vel_vecs_pi4[1], vel_vecs_pi4[2], mutation_scale=20, lw=1, arrowstyle="-|>", color="b")
axes.add_artist(vel_arrow_pi4)
It'll give me an error saying Tuple out of index
A:
I feel like this is close... Even got the colors to match the sample picture :)
I'm not too experienced with plotting on polar coordinates, though (mostly confused on the third-dimension t coordinate).
Hopefully this will help and you could figure out how to extend it
I took what you had, added the Arrow3D class from this answer, and added a simple for-loop over some sample values from t.
#draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
class Arrow3D(FancyArrowPatch):
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
FancyArrowPatch.draw(self, renderer)
axes = fig.gca(projection='3d')
t_step = 8
for t_pos in range(0, len(t)-1, t_step):
t_val_start = t[t_pos]
# t_val_end = t[t_pos+1]
vel_start = [rx(t_val_start), ry(t_val_start), t_val_start]
vel_end = [rx(t_val_start)+vx(t_val_start), ry(t_val_start)+vy(t_val_start), t_val_start]
vel_vecs = list(zip(vel_start, vel_end))
vel_arrow = Arrow3D(vel_vecs[0],vel_vecs[1],vel_vecs[2], mutation_scale=20, lw=1, arrowstyle="-|>", color="g")
axes.add_artist(vel_arrow)
acc_start = [rx(t_val_start), ry(t_val_start), t_val_start]
acc_end = [rx(t_val_start)+ax(t_val_start), ry(t_val_start)+ay(t_val_start), t_val_start]
acc_vecs = list(zip(acc_start, acc_end))
acc_arrow = Arrow3D(acc_vecs[0],acc_vecs[1],acc_vecs[2], mutation_scale=20, lw=1, arrowstyle="-|>", color="m")
axes.add_artist(acc_arrow)
axes.plot(rx(t), ry(t), t)
plt.xlim(-2*np.pi,2*np.pi)
plt.ylim(-6,6)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
TALES expression to compare numeric input in Plone?
TALES expression is new to me. Can I get some good reference for the same? Actually I wish to define a content rule for numeric input field using ploneformgen. Something like:
python: request.form.get('amt', False) <= 5000
then apply the rule.
Here 'amt' is a numeric/whole number field on the input form.
A:
For reference, you should look at the official TALES specification, or refer to the TALES section of the Zope Page Templates reference.
In this case, you are using a plain python expression, and thus the normal rules of python code apply.
The expression request.form.get('amt', False) would return the request parameter 'amt' from the request, and if that's missing, return the boolean False, which you then compare to an integer value.
There are 2 things wrong with that expression: first of all you assume that the 'amt' parameter is an integer value. Even a PFG integer field however, is still a string in the request object. As such you'll need to convert in to an integer first before you can compare it.
Also, you fall back to a boolean, which in integer comparisons will be regarded as the equivalent of 0, better be explicit and use that instead:
python: int(request.form.get('amt', 0)) <= 5000
Note that for a PFG condition, you can also return a string error message instead of boolean True:
python: int(request.form.get('amt', 0)) <= 5000 or 'Amount must be not be greater than 5000'
|
{
"pile_set_name": "StackExchange"
}
|
Q:
apache ignite loading cache ClassCastException
I m trying to use apache ignite, I m generating my node using the ignite web console.
I needed to configure 2 caches from database and enabled the persistence storage since the two table have lot of data.
Here is what I have done (the console)
/**
* Configure grid.
*
* @return Ignite configuration.
* @throws Exception If failed to construct Ignite configuration instance.
**/
public static IgniteConfiguration createConfiguration() throws Exception {
IgniteConfiguration cfg = new IgniteConfiguration();
cfg.setClientMode(true);
cfg.setIgniteInstanceName("attiryak");
TcpDiscoverySpi discovery = new TcpDiscoverySpi();
TcpDiscoveryMulticastIpFinder ipFinder = new TcpDiscoveryMulticastIpFinder();
ipFinder.setAddresses(Arrays.asList("127.0.0.1:47500..47510"));
discovery.setIpFinder(ipFinder);
cfg.setDiscoverySpi(discovery);
AtomicConfiguration atomicCfg = new AtomicConfiguration();
atomicCfg.setCacheMode(CacheMode.LOCAL);
cfg.setAtomicConfiguration(atomicCfg);
DataStorageConfiguration dataStorageCfg = new DataStorageConfiguration();
dataStorageCfg.setPageSize(16384);
dataStorageCfg.setConcurrencyLevel(2);
dataStorageCfg.setSystemRegionInitialSize(52428800L);
dataStorageCfg.setSystemRegionMaxSize(209715200L);
DataRegionConfiguration dataRegionCfg = new DataRegionConfiguration();
dataRegionCfg.setInitialSize(536870912L);
dataRegionCfg.setMaxSize(1073741824L);
dataRegionCfg.setMetricsEnabled(true);
dataRegionCfg.setPersistenceEnabled(true);
dataStorageCfg.setDefaultDataRegionConfiguration(dataRegionCfg);
cfg.setDataStorageConfiguration(dataStorageCfg);
cfg.setCacheConfiguration(
cacheMInoutlineCache(),
cacheMInoutlineconfirmCache()
);
return cfg;
}
public static CacheConfiguration cacheMInoutlineCache() throws Exception {
CacheConfiguration ccfg = new CacheConfiguration();
ccfg.setName("MInoutlineCache");
ccfg.setCacheMode(CacheMode.LOCAL);
ccfg.setAtomicityMode(CacheAtomicityMode.ATOMIC);
ccfg.setCopyOnRead(true);
CacheJdbcPojoStoreFactory cacheStoreFactory = new CacheJdbcPojoStoreFactory();
cacheStoreFactory.setDataSourceFactory(new Factory<DataSource>() {
/** {@inheritDoc} **/
@Override public DataSource create() {
return DataSources.INSTANCE_dsOracle_Compiere;
};
});
cacheStoreFactory.setDialect(new OracleDialect());
cacheStoreFactory.setTypes(jdbcTypeMInoutline(ccfg.getName()));
ccfg.setCacheStoreFactory(cacheStoreFactory);
ccfg.setReadThrough(true);
ccfg.setWriteThrough(true);
ArrayList<QueryEntity> qryEntities = new ArrayList<>();
QueryEntity qryEntity = new QueryEntity();
qryEntity.setKeyType("java.lang.Long");
qryEntity.setValueType("com.gmail.talcorpdz.model.MInoutline");
qryEntity.setTableName("M_INOUTLINE");
qryEntity.setKeyFieldName("mInoutlineId");
HashSet<String> keyFields = new HashSet<>();
keyFields.add("mInoutlineId");
qryEntity.setKeyFields(keyFields);
LinkedHashMap<String, String> fields = new LinkedHashMap<>();
fields.put("adClientId", "java.lang.Long");
qryEntity.setFields(fields);
HashMap<String, String> aliases = new HashMap<>();
aliases.put("mInoutlineId", "M_INOUTLINE_ID");
qryEntity.setAliases(aliases);
ArrayList<QueryIndex> indexes = new ArrayList<>();
QueryIndex index = new QueryIndex();
index.setName("IDX$$_00010002");
index.setIndexType(QueryIndexType.SORTED);
LinkedHashMap<String, Boolean> indFlds = new LinkedHashMap<>();
indFlds.put("mAttributesetinstanceId", false);
indFlds.put("mInoutId", false);
qryEntity.setIndexes(indexes);
qryEntities.add(qryEntity);
ccfg.setQueryEntities(qryEntities);
/**
* @author taleb
*
* spec 1.0 : no schema needed solution
* https://stackoverflow.com/a/58930331/4388228
* */
ccfg.setSqlSchema("PUBLIC");
return ccfg;
}
I believe that I m miss configuring my storage since it is mandatory to help memory to use my disk space.
Here is the stack trace of the exception
[11:49:58] __________ ________________
[11:49:58] / _/ ___/ |/ / _/_ __/ __/
[11:49:58] _/ // (7 7 // / / / / _/
[11:49:58] /___/\___/_/|_/___/ /_/ /___/
[11:49:58]
[11:49:58] ver. 2.7.6#20190911-sha1:21f7ca41
[11:49:58] 2019 Copyright(C) Apache Software Foundation
[11:49:58]
[11:49:58] Ignite documentation: http://ignite.apache.org
[11:49:58]
[11:49:58] Quiet mode.
[11:49:58] ^-- Logging by 'JavaLogger [quiet=true, config=null]'
[11:49:58] ^-- To see **FULL** console log here add -DIGNITE_QUIET=false or "-v" to ignite.{sh|bat}
[11:49:58]
[11:49:58] OS: Linux 4.19.0-kali5-amd64 amd64
[11:49:58] VM information: Java(TM) SE Runtime Environment 1.8.0_201-b09 Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 25.201-b09
[11:49:58] Please set system property '-Djava.net.preferIPv4Stack=true' to avoid possible problems in mixed environments.
[11:49:58] Initial heap size is 124MB (should be no less than 512MB, use -Xms512m -Xmx512m).
[11:49:58] Configured plugins:
[11:49:58] ^-- None
[11:49:58]
[11:49:58] Configured failure handler: [hnd=StopNodeOrHaltFailureHandler [tryStop=false, timeout=0, super=AbstractFailureHandler [ignoredFailureTypes=[SYSTEM_WORKER_BLOCKED, SYSTEM_CRITICAL_OPERATION_TIMEOUT]]]]
[11:49:59] Message queue limit is set to 0 which may lead to potential OOMEs when running cache operations in FULL_ASYNC or PRIMARY_SYNC modes due to message queues growth on sender and receiver sides.
[11:49:59] Security status [authentication=off, tls/ssl=off]
[11:49:59] REST protocols do not start on client node. To start the protocols on client node set '-DIGNITE_REST_START_ON_CLIENT=true' system property.
[11:50:00] Nodes started on local machine require more than 80% of physical RAM what can lead to significant slowdown due to swapping (please decrease JVM heap size, data region size or checkpoint buffer size) [required=4979MB, available=7867MB]
[11:50:00] Performance suggestions for grid 'attiryak' (fix if possible)
[11:50:00] To disable, set -DIGNITE_PERFORMANCE_SUGGESTIONS_DISABLED=true
[11:50:00] ^-- Enable G1 Garbage Collector (add '-XX:+UseG1GC' to JVM options)
[11:50:00] ^-- Specify JVM heap max size (add '-Xmx<size>[g|G|m|M|k|K]' to JVM options)
[11:50:00] ^-- Set max direct memory size if getting 'OOME: Direct buffer memory' (add '-XX:MaxDirectMemorySize=<size>[g|G|m|M|k|K]' to JVM options)
[11:50:00] ^-- Disable processing of calls to System.gc() (add '-XX:+DisableExplicitGC' to JVM options)
[11:50:00] Refer to this page for more performance suggestions: https://apacheignite.readme.io/docs/jvm-and-system-tuning
[11:50:00]
[11:50:00] To start Console Management & Monitoring run ignitevisorcmd.{sh|bat}
[11:50:00] Data Regions Configured:
[11:50:00] ^-- default [initSize=512.0 MiB, maxSize=1.0 GiB, persistence=true]
[11:50:00]
[11:50:00] Ignite node started OK (id=7ad24962, instance name=attiryak)
[11:50:00] >>> Ignite cluster is not active (limited functionality available). Use control.(sh|bat) script or IgniteCluster interface to activate.
[11:50:00] Topology snapshot [ver=2, locNode=7ad24962, servers=1, clients=1, state=INACTIVE, CPUs=8, offheap=2.0GB, heap=3.4GB]
>> Loading caches...
Nov 19, 2019 11:50:01 AM org.apache.ignite.logger.java.JavaLogger error
SEVERE: Failed to activate node components [nodeId=7ad24962-e5c8-4f0b-8b99-1c42a3c91c01, client=true, topVer=AffinityTopologyVersion [topVer=2, minorTopVer=1]]
java.lang.ClassCastException: org.apache.ignite.internal.pagemem.impl.PageMemoryNoStoreImpl cannot be cast to org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryEx
at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.getOrAllocateCacheMetas(GridCacheOffheapManager.java:728)
at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.initDataStructures(GridCacheOffheapManager.java:123)
at org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManagerImpl.start(IgniteCacheOffheapManagerImpl.java:196)
at org.apache.ignite.internal.processors.cache.CacheGroupContext.start(CacheGroupContext.java:937)
at org.apache.ignite.internal.processors.cache.GridCacheProcessor.startCacheGroup(GridCacheProcessor.java:2251)
at org.apache.ignite.internal.processors.cache.GridCacheProcessor.prepareCacheStart(GridCacheProcessor.java:2146)
at org.apache.ignite.internal.processors.cache.CacheAffinitySharedManager.processCacheStartRequests(CacheAffinitySharedManager.java:898)
at org.apache.ignite.internal.processors.cache.CacheAffinitySharedManager.onCacheChangeRequest(CacheAffinitySharedManager.java:798)
at org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture.onClusterStateChangeRequest(GridDhtPartitionsExchangeFuture.java:1114)
at org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture.init(GridDhtPartitionsExchangeFuture.java:736)
at org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeWorker.body0(GridCachePartitionExchangeManager.java:2681)
at org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeWorker.body(GridCachePartitionExchangeManager.java:2553)
at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:120)
at java.lang.Thread.run(Thread.java:748)
>> Loading cache: MInoutlineCache
Nov 19, 2019 11:50:02 AM org.apache.ignite.logger.java.JavaLogger error
SEVERE: Failed to process custom exchange task: ClientCacheChangeDummyDiscoveryMessage [reqId=587e6edb-95ee-4208-a525-a35ca441bf7c, cachesToClose=null, startCaches=[MInoutlineCache]]
java.lang.ClassCastException: org.apache.ignite.internal.pagemem.impl.PageMemoryNoStoreImpl cannot be cast to org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryEx
at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.getOrAllocateCacheMetas(GridCacheOffheapManager.java:728)
at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.initDataStructures(GridCacheOffheapManager.java:123)
at org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManagerImpl.start(IgniteCacheOffheapManagerImpl.java:196)
at org.apache.ignite.internal.processors.cache.CacheGroupContext.start(CacheGroupContext.java:937)
at org.apache.ignite.internal.processors.cache.GridCacheProcessor.startCacheGroup(GridCacheProcessor.java:2251)
at org.apache.ignite.internal.processors.cache.GridCacheProcessor.prepareCacheStart(GridCacheProcessor.java:2146)
at org.apache.ignite.internal.processors.cache.CacheAffinitySharedManager.processClientCacheStartRequests(CacheAffinitySharedManager.java:438)
at org.apache.ignite.internal.processors.cache.CacheAffinitySharedManager.processClientCachesChanges(CacheAffinitySharedManager.java:637)
at org.apache.ignite.internal.processors.cache.GridCacheProcessor.processCustomExchangeTask(GridCacheProcessor.java:391)
at org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeWorker.processCustomTask(GridCachePartitionExchangeManager.java:2489)
at org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeWorker.body0(GridCachePartitionExchangeManager.java:2634)
at org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeWorker.body(GridCachePartitionExchangeManager.java:2553)
at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:120)
at java.lang.Thread.run(Thread.java:748)
what should I do to fix this ?
A:
This is a known issue and it stems from the fact that previously you started the same cluster but without persistence.
Please remove your Ignite work dir (%TMP%\ignite\work or /tmp/ignite/work or ./ignite/work) and restart your node.
UPD: There is also this issue about LOCAL cache on client node with persistence: IGNITE-11677. My recommendation is to avoid using LOCAL caches at all.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
add a non-comparable object to a set
i have a class named Point (in an external library, i can't modify the code) that is used to represent a point in a 3d space:
int x = 0; int y = 0; int z = 0;
Point my_point p(x,y,z);
It overloads the == and != operators but not < or > ones. I need to store them in an efficient way (no double element, no repetition). I thought my data structure is set, but if i try to use, i get this error:
error: no match for ‘operator<’ in ‘__x < __y’
some advice?
A:
Write a comparison operator, and instantiate the set with that:
struct ComparePoints
{
bool operator()( Point const& lhs, Point const& rhs ) const
{
if ( lhs.x != rhs.x ) {
return lhs.x < rhs.x;
} else if ( lhs.y != rhs.y ) {
return lhs.y < rhs.y;
} else {
return lhs.z < rhs.z;
}
}
};
std::set <Point, ComparePoints> mySet;
A:
You can define a comparison functor and pass it as second template argument to std::set. See here, look at Compare. You can also define bool operator<(const Point& lhs, const Point& rhs), but if you cannot touch the class, this requires that the comparison can be implemented via the public interface of Point.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pass arguments in ElapsedEventHandler C++/CLI
How do I pass arguments to my function with ElapsedEventHandler?
NewTimer->Elapsed+=gcnew ElapsedEventHandler(&TimerEvent(String1,String2)); ???
I get this error:
'System::Timers::ElapsedEventHandler' : a delegate constructor expects 2 argument(s)
Any help appreciated.
A:
ElapsedEventHandler defines a delegate that takes two parameters:
The object that raised the event (the timer object).
ElapsedEventArgs, which contains the time that the timer was triggered.
If you need other information in your event handler, store them in fields on your class, and reference them that way.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can GTIN be used in blockchain?
I am using hyperledger fabric to be able to trace products to check its provenance within a supply chain. This project is meant for a lot of products, especially for longer periods of time.
I am having trouble figuring out what kind of identifiers to use for identifying a product which needs to be transacted in the blockchain. All the data will be stored within it forever.
According to a source (https://www.gs1ca.org/files/How_to_Create_a_GTIN.pdf) I can only make a max amount of 100.000 unique codes per company. After that I am geussing it needs to be reused. What are the identifiers I can use for basically an unlimitted amount of unique-codes within blockchain? Are there standards to handle this? Or should I identify my assets with two identifiers?
A:
In the event a company exhausts their 100,000 GTIN's they can apply for a second, or a third, or so on, GS1 Prefix. So essentially you should map their GTIN's along with their GS1 prefix.
Do some research on IBM FoodTrust, it is the most well known GS1 standard-based system for tracking goods on a Blockchain (Hyperledger).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Random HTML Code generated by Javascript?
i have a simple question. I have this code for my audio player:
<audio class="audio-element" controls="true" preload="none">
<source src="mp3file.mp3" type="audio/mpeg" /><br>
<b>Your outdated browser does not support HTML5. <br>
Get Mozilla Firefox <a href="https://www.mozilla.org/pl/firefox/new/"> >HERE< </a>
</b>
</audio>
is it possible to randomly generate the source src using Javascript?
A:
What do you mean by random source? If you generate a random string for your source it probably wouldn't be valid. What I think you want is to have an array of valid sources and select one of those valid sources at random.
In which case you would do this:
HTML
<audio class="audio-element" controls="true" preload="none" id='audio'>
JavaScript
Math.randInt = function(min, max){
return Math.floor((Math.random()*((max+1)-min))+min);
};
var sources = [
"source1.mp3",
"source2.mp3",
"source3.mp3"
];
document.getElementById("audio").src = sources[Math.randInt(0, sources.length-1)];
This will pick a random source from an array of valid sources which I think is what you want. But if you want to generate a "random source" you can do something stupid like this:
HTML
<audio class="audio-element" controls="true" preload="none" id='audio'>
JavaScript
Math.randInt = function(min, max){
return Math.floor((Math.random()*((max+1)-min))+min);
};
document.getElementById("audio").src = Math.randInt(999999999,9999999999).toString(36);+".mp3";
That will generate a random string of numbers and letters as your source. But why?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get primary_key of last inserted record in database with Python
I'm trying to add some data to database using python. But I'm unable to get the auto increment primary_key of the last inserted record.
I've checked similar questions here and here, but it haven't worked.
My code is as follows:
def insert_vehicles_to_db(vehicle):
conn = db_connection()
cur = conn.cursor()
if vehicle_not_exists(vehicle, conn, cur):
try:
insert_vehicle(vehicle, conn, cur)
except Exception as e:
pass
else:
pass
conn.close()
Then it goes to insert_vehicle function. In that function I want:
to add a new vehicle to the database
to add a new price in vehicle_price table
for previous step I need the last inserted vehicle primary key from vehicles table
The function insert_vehicle is as follows:
def insert_vehicle(vehicle, conn, cur):
try:
query = "INSERT INTO vehicles (reference, data, price, reference_url, timestamp) VALUES (%s, %s, %s, %s, %s);"
cur.execute(query, (vehicle['reference'], "", vehicle['price'], vehicle['reference_url'], datetime.datetime.now()))
////////// I tried here vehicle_id = cur.lastrowid, it gives me always 0 //////////
insert_vehicle_price(vehicle['price'], vehicle_id, conn, cur)
conn.commit()
except Exception as e:
# TODO Handle error
pass
And insert_vehicle_price looks as follows:
def insert_vehicle_price(price, vehicle_id, conn, cur):
//// Here I need the correct vehicle_id to be able to insert a new record in `vehicle_price` table
pass
Any idea how to solve it?
A:
In case your primary_key is the ID then you can use cursor.lastrowid to get the last row ID inserted on the cursor object, or connection.insert_id() to get the ID from the last insert on that connection.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Substituting hazelnuts for almonds, baking
I simply prefer hazelnuts to almonds, especially in sweet applications. I've been recently gifted with a pound of very nice bittersweet chocolate so I've decided to do America's Test Kitchen's Sacher Torte, but I'm going to fill with some kind of Frangelico cream cheese or buttercream mixture instead of raspberries or apricots. That I'll just tweak until I like the results, but the cake itself (almost but not quite flourless) really needs to be right the first time. Here is the relevant portion of the recipe:
"Process remaining cup almonds until very finely ground, about 45 seconds. Add flour and salt and continue to process until combined, about 15 seconds. Transfer almond-flour mixture to medium bowl. Process eggs in now-empty food processor until lightened in color and almost doubled in volume, about 3 minutes. With processor running, slowly add sugar until thoroughly combined, about 15 seconds. Using whisk, gently fold egg mixture into chocolate mixture until some streaks of egg remain. Sprinkle half almond-flour mixture over chocolate-egg mixture and gently whisk until just combined. Sprinkle in remaining almond-flour mixture and gently whisk until just combined.
Divide batter between cake pans and smooth with rubber spatula. Bake until center is firm and toothpick inserted into center comes out with few moist crumbs attached, 14 to 16 minutes. Transfer cakes to wire rack and cool completely in pan, about 30 minutes."
Is there anything I should know about hazelnuts and almonds before I start? Perhaps a difference in the fat content? Is there anything I need to know about peeling the hazelnuts (I understand that task to be a bit notorious)? I'll buy the hazelnuts raw in the bulk aisle of the grocery. I would think that I should peel and lightly toast them. Can you anticipate any other way that this substitution could be problematic?
A:
According to the Mayo Clinic, hazelnuts are somewhat more fatty than almonds, per ounce by weight (the range is for whether they are roasted or not):
Almonds - 14 - 15 g
Hazelnuts - 17 - 17.7 g
As might be expected, hazelnuts are slightly lower in starch. These is unlikely to make any practical difference in the recipe, as both are fairly close.
You should be able to use them close to interchangeably in recipes, although their flavors will be deliciously different, of course.
As for peeling hazelnuts, there are many methods. One of the more effective techniques, which will work if you are going to toast them lightly afterwards is to blanch them in a baking soda solution. See, for example, this article from My Baking Addiction with a video of Alice Medrich and Julia Child embedded demonstrating the technique.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do ally kills count toward Phobos Junction?
One of the requirements for Phobos Junction on Mars is:
Defeat 150 enemies in a single mission on Mars
Does that mean I personally have to get 150 kills, or just my squad collectively?
A:
I ran a Defense mission on Mars to test this. One on my squadmates got 300+ kills while I only managed ~30 (Banshee is ridiculous at low levels) and I did not fulfill the 150-kill requirement for Mars Junction. The 150 kills must be your personal statistic, not the squad total.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AngularJS Route loading error
I wondered if you could help.
I am learning AngularJS and have decided to make use of the Angular Route lib.
I keep getting an error when trying to load it.
angular.js:38Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.0/$injector/modulerr?p0=jargonBuster&p1=Err…loudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.3.0%2Fangular.min.js%3A18%3A3)
Here is my code, I have changed up the links to the see what works with no enjoy.
HTML
<!DOCTYPE html>
<html ng-app = "jargonBuster">
<head>
<meta charset="utf-8">
<title>Angular.js Example</title>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular-route.js"></script>
</head>
<body>
<section ng-controller="MainCtrl"></section><!-- VIEW -->
</body>
</html>
<script src="script.js"></script>
JS
var app = angular.module('jargonBuster', ['ngRoute']);
//router
app.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl:'keyword-list.html',
controller: 'MainCtrl'
}).
otherwise({
redirectTo: '/'
});
});
// The Controller
app.controller('MainCtrl', function($scope, $http) {
$http.get("getdecks.php").success(function(data) { //Gets data from The Decks Table
$scope.deckData = data;});
$http.get("getcards.php").success(function(data) { //Gets data from The Cards Table
$scope.cardsData = data;});
$scope.sortField = 'keyword';
$scope.reverse = true;
});// End of the controller
Thanks, any ideas?
A:
The issue is actually your html markup. If you change it from
<section ng-controller="MainCtrl"></section>
to
<section ng-view></section>
You should see the template loading (provided other errors don't crop up down stream in your keyword-list.html file which you didn't provide.
I set up your code with a simple keyword-list.html file of my own and it works fine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
FTP create path with MKD command
I need to store a file on a FTP server using commands. For example FolderA/FolderB/FolderC/myfile.txt. Do I need to create each folder step by step? That would be:
MKD FolderA
MKD FolderB
MKD FolderC
STOR FolderA/FolderB/FolderC/myfile.txt
Or is there a quicker/better way to do this?
A:
Some servers understand complex paths, but the standard way is to create them one by one:
MKD FolderA
CWD FolderA
MKD FolderB
CWD FolderB
MKD FolderC
CWD FolderC
STOR myfile.txt
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What kind of anaerobic exercises should one avoid during lower back pain?
So, I went to an orthopaedic because I was experiencing lower back pain for several months and got an X-Ray done. The report says that my L5 is sacralised, L4 has spondylolisthesis, and a mild forward subluxation of L4 was noted in the neutral position. The doctor recommended me some medicines, physiotherapy, exercise, and diet for weight reduction as soon as possible. I asked him if anaerobic exercises can be done where the lower back may experience some sort of stress, like upper/lower back exercises, squats of various kind, and different combination of upper-mid-lower core-based exercises. He said he has almost no knowledge about resistance training, and so he can't emphasise upon that. He further added that I should stick to only cardio-based exercises and diet.
But my problem is that a 20-minute jog on the treadmill (for example) burns an average of 200-250 calories, and that can be gained by eating a doughnut, for instance. Sure, I can and will avoid all processed junk food but nonetheless, even if someone burns through an hour of cardio 800-900 calories, that can be easily replenished by eating complex carbohydrates or other macros. IMO, resistance training in combination with cardio would have been the best bet, but in my case, I'm not sure if I should even continue with resistance training. Or, if I do, which exercises (anaerobic) should I totally avoid till my lower back heals completely? Any advice would be really appreciated. Sorry if this question has been asked before, here.
A:
Firstly, imaging, such as x-rays and MRIs, to determine the cause of lower back pain is problematic because asymptomatic people tend to have all kinds of spinal degenerations which don't actually cause any problems, with a prevalence of approximately 70% of individuals younger than 50 years of age to >90% of individuals older than 50 years of age.(1) This means that you can't actually be certain that anything found through imaging is really the cause of the lower back pain, as it's quite likely that it was actually pre-existing, asymptomatic, and unrelated. A 2018 summary of various international clinical practice guidelines even explicitly recommended against routine imaging.(2)
Research strongly supports exercise as a treatment for chronic lower back pain, and in many cases specifically recommends strength training.
Exercise in the Management of Chronic Back Pain, Thomas E. Dreisinger, 2014:
"The goal of therapeutic intervention is to return patients to the normal activities of daily living—sitting, rising, bending, twisting, lifting,
walking, and climbing—by enhancing strength, flexibility, endurance, and balance. Only resistance (strength) training has been shown to result in increases in all 4 of these at the same time."(3)
A 2015 study specifically investigated free-weight resistance training, and found that "A free-weight-based resistance training intervention can be successfully utilised to improve pain, disability and quality of life in those with low back pain."(4)
If I were in your position, I'd probably just go ahead with resistance training, but then I already regularly practice weight training, so I'm in a slightly different starting position. If you're worried I'd strongly recommend getting a second opinion from a doctor who does have knowledge about resistance training, and who does not use imaging as a tool for diagnosing lower back pain.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does 'driving force of the engine' mean?
I am given this question: A truck of mass $2000\ \rm kg$ accelerates from $5\ \rm m/s$ to $20\ \rm m/s$ in $5\ \rm s$. Then i am asked to find the driving force of the engine. So, what does driving force means and is there a difference between finding a force and finding a driving force?
A:
You are just supposed to find the force $F$ that is responsible for accelerating the truck, $F=ma$. The presence of "driving" does not really contribute anything here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails each discard item nil
I have the next array
[nil,nil,object,object,nil,object]
are there any way to do an each who omit the nil values?
A:
Just use compact to remove nil values:
[nil, nil, object, object, nil, object].compact
#=> [object, object, object]
In combination with each:
[nil, nil, object, object, nil, object].compact.each do |obj|
# ...
end
|
{
"pile_set_name": "StackExchange"
}
|
Q:
[Error: PhantomJS exited with return value 127]
I have the following code that generates a webshot of my site. It works on my local machine(Windows environment) but on test server which is linux I get PhantomJS exited with return value 127. What does this error mean and how can I resolve it?
webshot(url, fileName, options, function(err) {
if(!err){
fs.readFile(fileName, function (err,data) {
if (err) {
console.log(fileName);
return console.log(err);
}
fs.unlinkSync(fileName);
fut.return(data);
});
}else{
console.log(url);
console.log(err);
fut.return("Error Occurred");
}
});
A:
Phantomjs was not installed on the linux server. Installation solved my issue.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change a background depending on the current day
I what to know how to make a background change based on the day it is (so like for example on the 31st it goes to a Halloween picture then on the rest to a other background)P.S I what to try not use JavaScript as I don't like using JavaScript.
A:
In your comments you said javascript would be ok, so here it is in javascript.
This will do it for you: https://jsfiddle.net/4p18mxg9/5/
JAVASCRIPT
function myFunction() {
switch (new Date().getDay()) {
case 0:
day = "Sunday";
document.body.style.backgroundImage = "url('http://lorempixel.com/400/200/sports/1/')";
break;
case 1:
day = "Monday";
document.body.style.backgroundImage = "url('http://lorempixel.com/400/200/sports/1/')";
break;
case 2:
day = "Tuesday";
document.body.style.backgroundImage = "url('http://lorempixel.com/400/200/sports/1/')";
break;
case 3:
day = "Wednesday";
document.body.style.backgroundImage = "url('http://lorempixel.com/400/200/sports/1/')";
break;
case 4:
day = "Thursday";
document.body.style.backgroundImage = "url('http://lorempixel.com/400/200/sports/1/')";
break;
case 5:
day = "Friday";
document.body.style.backgroundImage = "url('http://lorempixel.com/400/200/sports/1/')";
break;
case 6:
day = "Saturday";
document.body.style.backgroundImage = "url('http://lorempixel.com/400/200/sports/1/')";
break;
}
document.getElementById("demo").innerHTML = "Today is " + day;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
About libgdx, android and IntelliJ
I thought it would be fun to try this out, and I have previous experience with android and Java, using intelliJ idea. But when I get my 'project' up and running, I don't know where to go from there, can someone show me how to make something show up somewhere on the screen?
This is what I have after setting it up:
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
initialize(new MyGdxGameTest(), config);
}
}
Where can I find tutorials on actual coding for this? Maybe I have got it all wrong somehow, I hope so, please tell me all you know about libgdx for android, or show me an example, if u have the time!
A:
Try following and working through this youtube series by dermetfan.
Java Game Development (LibGDX)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Slow Excel report with MySQL queries inside nested foreach loops [Laravel 5.3]
I'm facing a problem with slow times creating XLS/XLSX reports using Maatwebsite plugin for Laravel (around 5 - 30, 30 - 60 mins depending on the conditions of the report) which is a lot of time!!.
Searching through the web I encountered that Maatwebsite uses PHPExcel, which is slow and memory consuming if there's a lot or registers in the generation of the XLS/XLSX file.
Checking times, I have encountered that my queries grow almost exponentially because of nested foreach loops, the basic generation of the report is this:
$clients = Client::all(); // can change depending on conditions, worse case with all clients
Excel::create('Client Statement', function($excel) use ($clients) {
$excel->sheet('Sheet 1', function($sheet) {
$row = 1; // row number
foreach($clients as $client) {
$sheet->row($row++, [$client->data1,...,$client->dataN]);
$charges = Charge::get_ByClient($client->id);
foreach($charges as $charge) {
$sheet->row($row++, [$charge->data1,...,$charge->dataN]);
$payments = Payment::get_ByCharge($charge->id);
foreach($payments as $payment) {
$sheet->row($row++, [$payment->data1,...,$payment->dataN]);
}
}
}
});
});
The basic explination is:
Get all clients
For every client, get all the charges
For every charge, get all the payments
The problem is, I have around 1500 clients, every client can have betwee 10 - 100 charges, and every charge can have between 1 - 5 payments which results in slow performance. To that, sum the time the library takes to generate the XLS/XLSX file.
Any suggestions? Thanks in advance.
A:
Just to clarify this, I indeed used Eloquent's relationships as @Mark Baker suggested to speed up things, my problem was the typical N + 1 Problem. To resolve this issue I used Laravel's Eager Loading
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pass value on styled-component within usage
I want to make Header (own component) to be a styled-component. However I get
Uncaught TypeError:
WEBPACK_IMPORTED_MODULE_4_styled_components.a.Header is not a function
class Header extends Component {
render() {
return (
<div className={this.props.className}>
<NavBar>
<Nav>
<NavItem>Item1</NavItem>
<NavItem>Item2</NavItem>
</Nav>
</NavBar>
</div>
);
}
}
export default Header;
Desired Usage:
const StyledHeader = styled.Header`
background: ${props => props.background || 'goldenrod'};
`;
class HomePage extends Component {
render() {
return(
<StyledHeader background={"#d3d9df"}/>
<Content />
);
}
}
export default HomePage;
am I doing the right approach? I just want different background colors for Header every page.
A:
Header.js
class HeaderUnstyled extends Component {
render() {
return (
<div className={this.props.className}>
...
</div>
);
}
}
const Header = styled(HeaderUnstyled)`
background: ${props => props.background || '#aab' };
font-size: large;
font-family: Beirut;
padding: 5px;
`;
export default Header;
HomePage.js
import Header from '..header/Header.js';
class HomePage extends Component {
render() {
return(
<Header />
<Content />
);
}
}
export default HomePage;
AboutPage.js
import Header from '..header/Header.js';
class AboutPage extends Component {
render() {
return(
<Header background={'#fff'}/>
<Content />
);
}
}
export default AboutPage;
this is my chosen approach for now.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++ Loops, scope, and stack (why does this work?)
I'm finding it difficult to find specific answers for questions like this, but I'll explain the way I think think this is supposed to (not) work, and maybe someone can tell me where I'm wrong.
I create an integer array of size 10 in main which lives on the stack. Then I use a for loop to load integers 0-9 into that array. When the for loop ends, the stack pointer returns to where it was after initializing arr1, but those values still exist in memory, and the array is still pointing to them.
Then, I use another for loop to flood the stack, which should overwrite the values created in the first for loop, and now when I go to access my values in arr1, they should be pointing to integers with values of 5000.
When I print the array, it still prints out numbers 0-9. Why does this work? I thought data declared in a loop was popped off the stack when it goes out of scope. Thanks
int main(void)
{
int arr1[10];
for(int i = 0; i < 10; i++)
arr1[i] = i;
for(int i = 0; i < 500; i++)
int a = 5000;
for(int i = 0; i < 10; i++)
cout << arr1[i] << endl;
system("PAUSE");
return 0;
}
A:
You seem to have misunderstood data lifetime in C++. When local data is declared in a scope block (whether in a function, loop, or other control structure), it remains on the stack until that scope block ends.
That means the entirety of arr1 remains allocated and on the stack until main() finishes, no matter what else you do. It will not be overwritten by subsequent local variables in the same function, or variables nested in deeper scope blocks.
In your second loop, variable a is (theoretically) being created and destroyed on every iteration of the loop body. That means you don't have 500 instances of a on the stack during the loop -- you only ever have one. (In practice, the compiler almost certainly optimises that out though, since it's not doing anything useful.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is Negasonic Teenage Warhead so different in the Deadpool film?
Negasonic Teenage Warhead appears in the films to have the powers of Cannonball from the X-Men comics.
Why was the character changed so much? Normally Negasonic Teenage Warhead has telepathic/pre-cognitive powers.
A:
Cannonball was originally intended for the movie because, to quote Tim Miller
"In the original script the action in the third act was great, but it was just Deadpool and a lot of guns
But they were worried about him being perceived as a hick:
"We thought about Cannonball, but he would’ve been a stupid hick character, whereas the guys wrote Negasonic as this deadpan goth teen, which was a great angle.
They choose the character based in the name, and spliced in the powers:
I went through the list of Marvel characters ... And at the end of that list was Negasonic, which I just thought was a freaky, funny name.
Source
A:
"We changed her powers because we thought it was funnier"
In a Q & A podcast the screenwriters Paul Wernick and Rhett Reese admitted that they only wanted to include the character because of her name and that they changed her powers because it was funnier.
Q & A Podcast with Paul Wernick and Rhett Reese
At around 29:30 they answer the question as to the reason for the character being in the movie,
Negasonic was there because Tim [Miller] wanted some good guy super powers in the movie
And at 29:42 they answer the question as to why they wanted her,
Q: Why her? Why did you choose Negasonic?
A: Because of the name.
Then they talk about how they changed her powers, and how she was a mind reader or was able to look into the future, 29:50
In fact we changed her powers, we made her into a literal warhead because we thought that was funnier.
There is a lot of other great stuff in the podcast if you have time to listen to it.
And this on how they had to get permission from the studio,
It was the one thing we needed Marvel’s actual approval on, that they
had to reach out for. Tim [Miller] has a relationship with [Marvel
President] Kevin Feige and I think he went straight to Kevin because
all the lawyers, you know, it gets messy with the lawyers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laravel MAMP Vhosts issue
Have the below config in vhosts. Its always returns 500 error when i run it through MAMP. Not sure what is wrong. Stopped mamp and ran it using valet. laravel website runs successfully. Permissions of bootstrap/cache and storage looks good. Error logs are empty cant debug and debug setting set to true in .env file. Only access log exists with 500 error. Below is the vhosts config that i have for MAMP. Other website in vhosts file work.
<VirtualHost *:80>
ServerName elearn.localhost
ServerAlias elearn.localhost
DocumentRoot "/Users/user1/code/elearn/public"
ErrorLog "/Users/user1/logs/elearn.localhost-error_log"
CustomLog "/Users/user1/logs/elearn.localhost-access_log" common
<Directory "/Users/user1/code/elearn/public">
DirectoryIndex index.php
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Order allow,deny
Allow from all
Require all granted
Satisfy Any
</Directory>
</VirtualHost>
A:
What version of Laravel are you using, if it is 5.6 make sure you're running PHP at at least 7.1 in MAMP - fallen foul of that myself a couple of times?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Exchange 2010 - Send Connectors
I understand in Exchange 2010 in order to send out to the big bad Internet you require to configure a send connector to allow SMTP to *, or to your smart host etc.
My question is how does Exchange 2010 handle mail being delivered interally, i.e. to a another mailbox within Exchange, is there a send connector for this? Separate Queues in Queue Viewer for internal mail etc?
Thanks!
A:
Send connectors are only needed for sending SMTP email to external systems.
For internal email on the same server, or between several servers in your organization, SMTP isn't used - exchange has it's own transfer mechanisms for internal email.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Loop through global substitution
$num = 6;
$str = "1 2 3 4";
while ($str =~ s/\d/$num/g)
{
print $str, "\n";
$num++;
}
Is it possible to do something like the above in perl? I would like the loop to run only 4 times and to finish with $str being 6 7 8 9.
A:
You don't need the loop: the /g modifier causes the substitution to be repeated as many times as it matches. What you want is the /e modifier to compute the substitution. Assuming the effect you were after is to add 5 to each number, the example code is as follows.
$str = "1 2 3 4";
$str =~ s/(\d)/$1+5/eg;
print "$str\n";
If you really wanted to substitute numbers starting with 6, then this works.
$num = 6;
$str = "1 2 3 4";
$str =~ s/\d/$num++/eg;
print "$str\n";
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Duplicate values when populating select dropdown from mysql query
I am trying to populate an html select dropdown with data from multiple columns in a mysql query.
When I retrieve the first column it populates the dropdown without issue. When I add the second or third columns I get issues. Originally I was getting blank fields, this was resolved by adding !empty().
However I am now getting values repeated in place of the blanks
<?php
$base = '';
$base2 = '';
$base3 = '';
while($row = mysqli_fetch_assoc($resultpmb)) {
$code=$row["id"];
$name=$row["gw_name"];
if (!empty(trim($row['vg_name']))){
$vgname=$row["vg_name"];}
if (!empty(trim($row['vm_name']))){
$vmname=$row["vm_name"];}
$base .= "<option value=" .$code.">".$name."</option>";
$base2 .= "<option value=" .$code.">".$vgname."</option>";
$base3 .= "<option value=" .$code.">".$vmname."</option>";
}
?>
<div class="form-group col-4 col-m-12">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon
glyphicon-lock"></span></span>
<select name="base_colour1" class="form-control" id="base_colour1">
<option value="">Base...</option>
<?php
echo "<option value=''>---- GW Golour ----</option></br>";
echo $base;
echo "<option value=''>---- Vallejo Game Golour ----</option>";
echo $base2;
echo "<option value=''>---- Vallejo Model Golour ----</option>";
echo $base3;
?>
</select>
</div>
</div>
A:
It may be easier to add the strings within your test of !empty() otherwise it will always add values in - even when there aren't any...
while($row = mysqli_fetch_assoc($resultpmb)) {
$code=$row["id"];
$name=$row["gw_name"];
if (!empty(trim($row['vg_name']))){
$base2 .= "<option value=" .$code.">".$row["vg_name"]."</option>";
}
if (!empty(trim($row['vm_name']))){
$base3 .= "<option value=" .$code.">".$row["vm_name"]."</option>";
}
$base .= "<option value=" .$code.">".$name."</option>";
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Consulta de Transação PagSeguro
Opa
Estou gerando o pagamento via pagseguro e armazenando seu transaction code para consulta posterior.
Na consulta da transação, pelo transaction code estou fazendo assim:
$email_pagseguro = '[email protected]';
$token_pagseguro = '****************************';
$url = 'https://ws.pagseguro.uol.com.br/v2/transactions/'.$tabela_itens['usuario_checkout_transactionCode'].'?email='.$email_pagseguro.'&token='.$token_pagseguro;
$_h = curl_init();
//curl_setopt($_h, CURLOPT_HEADER, 1);
curl_setopt($_h, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($_h, CURLOPT_HTTPGET, 1);
curl_setopt($_h, CURLOPT_URL, $url );
curl_setopt($_h, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($_h, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($_h, CURLOPT_DNS_USE_GLOBAL_CACHE, false );
curl_setopt($_h, CURLOPT_DNS_CACHE_TIMEOUT, 2 );
$output = curl_exec($_h);
var_dump($output);
//$transaction = simplexml_load_string($output);
O var_dump está retornando um texto com todos os dados da transação, uma string, onde acredito eu deveria ser retornado um xml.
Doc para esta consulta
A:
Solução para Consulta de transação por código.
$email_pagseguro = '[email protected]';
$token_pagseguro = '*******************';
$url = 'https://ws.pagseguro.uol.com.br/v2/transactions/'.$tabela_itens['usuario_transactionCode'].'?email='.$email_pagseguro.'&token='.$token_pagseguro;
$_h = curl_init();
curl_setopt($_h, CURLOPT_HTTPHEADER, Array("Content-Type: application/xml; charset=ISO-8859-1"));
curl_setopt($_h, CURLOPT_RETURNTRANSFER, true);
curl_setopt($_h, CURLOPT_HTTPGET, 1);
curl_setopt($_h, CURLOPT_URL, $url );
curl_setopt($_h, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($_h, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($_h, CURLOPT_DNS_USE_GLOBAL_CACHE, false );
curl_setopt($_h, CURLOPT_DNS_CACHE_TIMEOUT, 2 );
$output = curl_exec($_h);
//var_dump($output);
$transaction = simplexml_load_string($output);
$status_compra = $transaction -> status;
echo '<br><br><Br>'.$status_compra;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Equivalence relation with complex numbers.
In $ \mathbb{C} $ we define the binary relations $ R_{j} $ , $ j=1,2,3,4. $
$ z_{1} R_{1} z_{2} \Leftrightarrow |z_{1}| = |z_{2}| $
$ z_{1} R_{2} z_{2} \Leftrightarrow arg(z_{1}) = arg(z_{2}) $ or $ z_{1} = z_{2} = 0 $
$ z_{1} R_{3} z_{2} \Leftrightarrow \bar{z_{1}} = z_{2} $
$ z_{1} R_{4} z_{2} \Leftrightarrow z_{1} = e^{i\phi}z_{2} $ , $ \phi \in \mathbb{R} $
Let X = { z | |z| = 1 }
Find $ R_{j}(\mathbb{R}), R_{j}(\mathbb{X}), R_{j}(i),R_{j}(\mathbb{R}),R_{j}\circ R_{k},R_{j}^{-1} $
Find which relation is an equivalence relation and in that case determine it's quotient set.
What is the elegant and right way to find those sets ?
They might seem easy to guess but I am not that familiar with the demonstration.
Some answers : $ R_{1}(\mathbb{R}) = \mathbb{C} $ , $ R_{2}(\mathbb{R}) = \mathbb{R} $ , $ R_{3}(\mathbb{R}) = \mathbb{R} $ , $ R_{4}(\mathbb{R}) $ = { $ (a,b) \in \mathbb{R}^2 | b= a\tan\phi $ } , $ R_{1}(X) = X $, $ R_{2}(X) = \mathbb{C}^* $, $ R_{3}(X) = X $, $ R_{4}(X) = X $, $ R_{1}(i) = X $
And the only equivalent relations are the first 2 ( which is pretty obvious because they are Kernels )
A:
You should think of $R_j(S)$ (where $S$ is some subset of $\Bbb{C}$) as the image of the set $S$ under the relation $R_j$. What it means is as follows:
$$R_j(S)=\{z \in \Bbb{C}\, | \, s R_j z \,\,\text{ for some } s \in S\}$$
For example, if $S=\Bbb{R}$ and we are using relation $R_1$, then
\begin{align*}
R_1(\Bbb{R}) & =\{z \in \Bbb{C}\, | \, s R_j z \,\,\text{ for some } s \in \Bbb{R}\}\\
& =\{z \in \Bbb{C}\, | \, |s|=|z| \,\,\text{ for some } s \in \Bbb{R}\}\\
\end{align*}
Since every complex number $z=a+ib$ has magnitude $|z|=\sqrt{a^2+b^2}$, so we can say that the real number $\sqrt{a^2+b^2}$ is related to $z$ via the relation $R_1$. Thus
$$R_1(\Bbb{R})=\Bbb{C}.$$
Hope you can take it from here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change LoadMask text in ExtJS
Is there a way to change Ext.LoadMask.msg on ExtJS 4.1 MVC Application globally?
A:
It should work with
// changing the msg text below will affect the LoadMask
Ext.define("Ext.locale.##.view.AbstractView", {
override: "Ext.view.AbstractView",
msg: "Loading data..."
});
for the most cases. Call this right after/within the onReady() function. Set ## to your locale language
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PDF scraping: how to automate the creation of txt files for each pdf scraped in Python?
Here's what I want to do: A program that will a list of pdf files as its input and return one .txt file for each file of the list.
For example, given a listA = ["file1.pdf", "file2.pdf", "file3.pdf"], I want Python to create three txt files (one for each pdf file), say "file1.txt", "file2.txt" and "file3.txt".
I have the conversion part working smoothly thanks to this guy. The only change I've made is in the maxpages statement, in which I assigned 1 instead of 0 in order to extract only the first page. As I said, this part of my code is working perfectly. here's the code.
def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = file(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
#maxpages = 0
maxpages = 1
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
interpreter.process_page(page)
fp.close()
device.close()
str = retstr.getvalue()
retstr.close()
return str
The thing is I cannot seem to have Python return me is what I stated in the second paragraph. I've tried the following code:
def save(lst):
i = 0
while i < len(lst):
txtfile = "enegep"+str(i)+".txt" #enegep is like the identifier of the files
artigo = convert_pdf_to_txt(lst[0])
with open(txtfile, "w") as textfile:
textfile.write(artigo)
i += 1
I ran that save function with a list of two pdf files as the input, but it generated only one txt file and kept running for several minutes without generating the second txt file. What's a better approach to fulfill my goals?
A:
You don't update i so your code gets stuck in an infinite loop you need to i += 1:
def save(lst):
i = 0 # set to 0 but never changes
while i < len(lst):
txtfile = "enegep"+str(i)+".txt" #enegep is like the identifier of the files
artigo = convert_pdf_to_txt(lista[0])
with open(txtfile, "w") as textfile:
textfile.write(artigo)
i += 1 # you need to increment i
A better option would be to simply use range:
def save(lst):
for i in range(len(lst)):
txtfile = "enegep{}.txt".format(i) #enegep is like the identifier of the files
artigo = convert_pdf_to_txt(lista[0])
with open(txtfile, "w") as textfile:
textfile.write(artigo)
You also only use lista[0] so you may want to also change that code to move accross the list each iteration.
if lst is actually lista you can use enumerate:
def save(lst):
for i, ele in enumerate(lst):
txtfile = "enegep{}.txt".format(i) #enegep is like the identifier of the files
artigo = convert_pdf_to_txt(ele)
with open(txtfile, "w") as textfile:
textfile.write(artigo)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does the food I provide affect which kitties visit?
I've been mostly keeping Frisky Bitz in my bowls because I want to save my gold fish for other things. Will I be able to collect all the kitties with this food, or do some kitties have more expensive tastes and only come for things like Bonito Bitz?
A:
Offering more expensive cat foods, along with specific toys, will attract rare cats to pay a visit. More expensive cat food will also simply attract more cats in general.
The most obvious example of cats who are after food that costs money is Tubbs, who is only interested in food, and will only show up to eat (an entire bowl) of any food that costs money (fish).
Other rare cats are interested in playing with specific toys, and having expensive food around will increase your chances of coaxing them out to play with those toys.
I found information here and here in regards to this topic, and this also seems to be the consensus on Reddit.
A:
Some rare cats will only show up when using specific foods or toys. You can find an incomplete list of which foods attract which cats on the Neko Atsume Wiki.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python MySQL Insert error must be str, not AttributeError
I have a Python function that pulls a JSON file, then reads this and pulls certain key pairs for inserting into a database.
def update_vuln_sets():
try:
logging.info('Getting latest vulnerability sets from Vulners API...')
response = requests.get('https://vulners.com/api/v3/search/stats/')
response.encoding = 'windows-1252'
vuln_set = json.loads(response.text)
vuln_type = vuln_set['data']['type_results']
except Exception as e:
logging.error(e)
try:
logging.info('Processing JSON response')
for k in vuln_type:
vuln_bulletinfamily = vuln_set['data']['type_results'][k]['bulletinFamily']
vuln_name = vuln_set['data']['type_results'][k]['displayName']
vuln_count = vuln_set['data']['type_results'][k]['count']
try:
logging.info('Connecting to the database...')
con = MySQLdb.connect('5.57.62.97', 'vuln_backend', 'aHv5Gz50cNgR', 'vuln_backend')
logging.info('Database connected!')
except FileNotFoundError as fnf:
logging.error(fnf)
except MySQLdb.Error as e:
logging.error(e)
try:
logging.info('Inserting vulnerability type ' + k + ' into DB')
with con:
cur = con.cursor()
con.row_factory = MySQLdb.row
cur.execute("INSERT OR IGNORE INTO vuln_sets (vulntype, displayname, bulletinfamily, vulncount)"
" values (?,?,?,?)", (k, vuln_name, vuln_bulletinfamily, vuln_count))
con.commit()
logging.info('Vulnerability type ' + k + ' inserted successfully!')
except Exception as e:
logging.error('Vulnerability type ' + k + 'not inserted! - Error: ' + e)
logging.info('Vulnerability sets successfully updated!')
except Exception as e:
logging.error(e)
Checking through my logging it is getting held up at the Inserting Record stage but it just gives an error of root ERROR must be str, not AttributeError
A:
You're logging e which is not a str it is an AttributeError. Based on the bit of a stack trace you shared, it looks like 'logging.error()takes astr` argument.
You could either change logging.error() to accept an Exception instead of a string, or you could call take a string portion of the error to log it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Technical term for Internet-like network?
There is a computer network, similar to Internet in architecture but not connected to actual Internet, that is used by the military. What is the term to describe such network?
A:
A private network that is accessible only to the employees of an organisation is called an intranet.
Definition: http://www.dictionary.com/browse/intranet
a computer network with restricted access, as within a company, that uses
software and protocols developed for the Internet.
The same definition would apply in the military context. The difference might be that an elevated level of security precautions is imposed on such a network.
A:
An internet is any TCP/IP network. When used within a single organisation, it is called an intranet. The Internet is simply the public TCP/IP network that hosts the World Wide Web.
A:
Wide area Network or WAN.
From Wikipedia:
A wide area network (WAN) is a telecommunications network or computer network that extends over a large geographical distance. Wide area networks are often established with leased telecommunication circuits.
Business, education and government entities use wide area networks to relay data among staff, students, clients, buyers, and suppliers from various geographical locations. In essence, this mode of telecommunication allows a business to effectively carry out its daily function regardless of location. The Internet may be considered a WAN.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change part of link with jquery
I am using Ransack for sorting. I couldn't find way to change sorting links when search and sorting uses just ajax. So I am developing my own solution to change link and some other stuff.
So far I have this
Ruby
<%= search_form_for @search, :class=>"search",:id=>"search-menio",:remote=>"true", url: advertisements_path, :method => :get do |f| %>
<div class="sort-link-css">
<%= sort_link(@search, :price,"CENA", {},{ :remote => true, :method => :get }) %>
</div>
<%end%>
that generates this :
<div class="sort-link-css">
<a class="sort_link asc" data-method="get" data-remote="true" href="/lv/advertisements?q%5Bs%5D=price+desc">CENA ▲</a>
</div>
My goal:
When user clicks on this link it will change link class that represents sorting order and end of the link that also represents sorting order.
asc -> desc
desc -> asc
And then it submits search form.
Problem:
For first click I see some blinking and changes, but when I try second click nothing happens.
My script:
$('.sort-link-css > a').click(function() {
var className = $(this).attr('class');
if (className = "sort link asc") {
$(this).removeClass('sort link asc');
this.href = this.href.replace('desc', 'asc');
$(this).attr('class', 'sort link desc');
} else if (className = "sort link desc") {
$(this).removeClass('sort link desc');
this.href = this.href.replace('asc', 'desc');
$(this).attr('class', 'sort link asc');
}
$('.search').submit();
})
What I am doing wrong ?
A:
Ideally you would use jQuery.hasClass or jQuery.is to determine if an element has the specified class or classes.
You also need to update the display before navigation or form submit. You can do all this:
$('.sort-link-css > a').click(function(e) {
// cancel the click event on the link
e.preventDefault();
var $this = $(this);
if ($this.is('.asc')) {
this.href = this.href.replace('desc', 'asc');
} else if ($this.is('.desc')) {
this.href = this.href.replace('asc', 'desc');
}
$this.toggleClass('asc desc');
setTimeout(function() {
// I am not sure if you want to load the link href
// or submit the form; use one of the following
window.location = $this.get(0).href;
$('.search').submit();
}, 100);
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Re: tech questions where correct answers change over time - is there a way to show only the votes after a certain date?
Note: In an act of triage, this question was retitled and edited to become a request for technical support instead of a feature request - yet still be a question to match the high quality answer that was given. In case of a quality answer SE urges not deleting the question -
If your question has good answers, though, it's not fair to have those answers removed along with your question: other users put effort into helping you and even if you no longer want the answers, somebody else might. This is why the system prevents you from deleting answered questions most of the time.
A:
I don't think this is going to work, but here is a method to generate such a graph to find out.
I'll illustrate with one of my own examples (anecdotal evidence, but I'm sure it applies to many more situations), Evenly space multiple views within a container view. As of iOS 9 (5 years ago), there's a dedicated solution for this, which I wrote an answer about. I'm obviously biased, but I think that's the best/easiest one :) Of course, old answers still remained valuable for a time since developers had to support older iOS versions, but by 2018 nobody cared about iOS 8 or older anymore. Still, the highest scoring answer (yellow line), not even being the accepted answer, continued to receive more upvotes than mine (green line), perhaps because it already had so many votes that people thought it must be a perfect solution and simply didn't bother to scroll down. There's another answer mentioning the same solution (dark teal, the fifth line from the top) which didn't get many as many upvotes either.
You can run this query to check the situation for other questions / timeframes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to say where I was born
This is Delhi that I was born in.
&
This is Delhi where I was born in.
Are both of these sentences right? If not, what is the right way to say this?
A:
The "in" at the end of both sounds odd and some people (following advice from their grade school English teacher) would say incorrect, as it is a preposition at the end of the sentence.
But more importantly, to make them more standard English I'd rewrite as:
This is Delhi where I was born.
This is Delhi in which I was born. (or "Delhi that I was born in")
In other words, the "where" implies an "in" somewhere. You don't have to say it (though your meaning was clear): it's implied that you were born IN that city.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get the Page Id in my Facebook Application page
I have my application is hosted in FaceBook as a tab and I want to get the page ID when my application is being added to be stored in my logic.
How can I get the page ID, I know it is stored in the URL but when I tried to get it from the page as a server variable, I am not getting it even my application is configured as iFrame ? But this is a standard way to get the parent URL.
C#:
string t= request.serverVariables("HTTP_REFERER");
//doesn't get FB page url even if your app is configured as iframe ?!! @csharpsdk #facebook devs
Any help ?
Thanks a lot.
A:
Here is how I do it:
if (FacebookWebContext.Current.SignedRequest != null)
{
dynamic data = FacebookWebContext.Current.SignedRequest.Data;
if (data.page != null)
{
var pageId = (String)data.page.id;
var isUserAdmin = (Boolean)data.page.admin;
var userLikesPage = (Boolean)data.page.liked;
}
else
{
// not on a page
}
}
A:
The Page ID is not stored in the URL; it is posted to your page within the signed_request form parameter. See this Facebook developer blog post for more details.
You can use the FacebookSignedRequest.Parse method within the Facebook C# SDK to parse the signed request (using your app secret). Once you have done this you can extract the Page ID from the Page JSON object as follows:
string signedRequest = Request.Form["signed_request"];
var DecodedSignedRequest = FacebookSignedRequest.Parse(FacebookContext.Current.AppSecret, SignedRequest);
dynamic SignedRequestData = DecodedSignedRequest.Data;
var RawRequestData = (IDictionary<string, object>)SignedRequestData;
if (RawRequestData.ContainsKey("page") == true)
{
Facebook.JsonObject RawPageData = (Facebook.JsonObject)RawRequestData["page"];
if (RawPageData.ContainsKey("id") == true)
currentFacebookPageID = (string)RawPageData["id"];
}
Hope this helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to export / save a fitted model after cross_validate and use it later on pandas
I am using cross_validate sklearn-function to fit a RandomForest classifier.
I'd like to know if there's a way to export the fitted model(s) to save them and import to predict new data.
I tried to use the return_estimator=True option
[return_estimator : boolean, default False Whether to return the
estimators fitted on each split.]
and then joblib to save the estimators. But when I load the saved model and try to use it to predict, I got an error, (see below).
rfc = RandomForestClassifier(n_estimators=100)
cv_results = cross_validate(rfc, X_train_std ,Y_train, scoring=scoring, cv=5, return_estimator=True)
rfc_fit = cv_results['estimator']
#save estimated model
savedir = ('C://Users//.......//src//US//')
from sklearn.externals import joblib
filename = os.path.join(savedir, 'final_model.joblib')
joblib.dump(rfc_fit,filename)
rfc_model2 = joblib.load(filename)
bla = rfc_model2.predict(X_test_std)
AttributeError: 'tuple' object has no attribute 'predict'
I guess I am confused on what really the return_estimator give back..
it looks like they're not the fitted models. So, is there a way to extrace the model fitted during the cross-validation in order to re-use them?
thanks
A:
return_estimator returns the 'tuple' of ALL the fitted models.
To solve this, you need to select the desired model, save it, load it and then predict.
Example:
from sklearn import datasets, linear_model
from sklearn.model_selection import cross_validate
diabetes = datasets.load_diabetes()
X = diabetes.data[:150]
y = diabetes.target[:150]
lasso = linear_model.Lasso()
cv_results = cross_validate(lasso, X, y, cv=3, return_estimator=True)
rfc_fit = cv_results['estimator']
print(rfc_fit)
The above prints 3 models:
(Lasso(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=1000,
normalize=False, positive=False, precompute=False, random_state=None,
selection='cyclic', tol=0.0001, warm_start=False), Lasso(alpha=1.0,
copy_X=True, fit_intercept=True, max_iter=1000, normalize=False,
positive=False, precompute=False, random_state=None,
selection='cyclic', tol=0.0001, warm_start=False), Lasso(alpha=1.0,
copy_X=True, fit_intercept=True, max_iter=1000, normalize=False,
positive=False, precompute=False, random_state=None,
selection='cyclic', tol=0.0001, warm_start=False))
To see how many models this contains do this:
print(len(rfc_fit))
# 3
Let's say you want to select the first model:
# select the first model
rfc_fit = rfc_fit[0]
# save it
from sklearn.externals import joblib
filename = os.path.join(savedir, 'final_model.joblib')
joblib.dump(rfc_fit,filename)
# load it
rfc_model2 = joblib.load(filename)
Predict works fine now:
predicted = rfc_model2.predict(X)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Detect whether a window was opened from the same website
If I make a link to another part of the site e.g.
<a href="foo.html" target="_blank">Link</a>
I want to be able to tell in the new window if the user has come via that link, or if they have come directly to that url via a different route. Is that possible?
This is because, if they came from the same site, I can use window.close();, but not if they came via a different route.
A:
In this case you can use document.referrer:
if(document.referrer){
// close the window here
console.log('loaded via navigation')
}else{
console.log('no navigation');
}
or you might want to get the domain name from the referrer:
function virtualURL(url) {
var a=document.createElement('a');
a.href=url;
return a.hostname;
}
if(virtualURL(document.referrer) === window.location.hostname){
// close the window here
console.log('loaded via navigation')
}else{
console.log('nope');
}
Here in the above code virtualURL(document.referrer) will return the hostname of the last visited page. So, you can match that with the current application's host name, if they match then you can close the window.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Could not open input file: /Users/me/composer.phar - After running source ~/.bash_profile.save
this is giving me a headache. Simply trying to install laravel 4.
So, installed composer fine and it runs correctly. The issue is that when i tryed to install laravel i was recieving this error:
- laravel/framework v4.2.9 requires php >=5.4.0 -> no matching package found.
So, I checked the PHP version that terminal was using and using:
which php
gave me the usr/local/bin location and then php -v showed that was 5.3 php.
So, following some instructions I edited the .bash_profile.save so that the path was now:
alias composer='php ~/composer.phar'
export PATH=/Applications/MAMP/bin/php/php5.5.14/bin:$PATH
^R
I then ran:
source ~/.bash_profile.save
And then again which php.
This showed the correct path BUT... when trying to use composer i recieved this error:
Could not open input file: /Users/me/composer.phar
So now im stuck. Is it because of the alias composer line? Where should that now be pointed?
Thanks, just want to get on with laravel... :)
A:
You need to have composer in that directory below
mv composer.phar /usr/local/bin/composer
And not in your user account's root
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do PNGs (or JPGs) have a DPI? Or is it irrelevant when building for retina?
A simple question that I have been having great difficulty finding a definitive answer to: do PNG files have a DPI? Or perhaps more importantly, is it even relevant when building retina-enabled sites/apps?
I've just received PSD assets from our designer for a retina iPad app that I must convert into HTML for display within the app. Typically, I receive such files as 2048x1536 @ 72 DPI -- double size but standard screen DPI. I then typically use CSS to tell the browser how to display it.
But this time the designer was instructed to provide his PSDs at 1024x768 @ 144 DPI (standard size but double DPI.) I believe this is incorrect, as the DPI setting within Photoshop is intended for print purposes. Plus, when I save something from a 144 DPI PSD as a PNG or JPG, it is exactly the same as one saved from a 72 DPI (or 30,000 DPI for that matter) PSD. DPI doesn't seem to be reflected in either any setting that I can see in the resultant file nor in a different file size. It seems, at best, metadata.
So, it's my understanding that DPI isn't relevant here, and we should simply be asking for double-sized assets for retina projects, but I would like some confirmation/clarity on the issue before asking for new assets. I work with many designers that are transitioning from print backgrounds so this is a common issue I encounter and I'd like to be able to provide better guidance with our requirements in the future.
A:
DPI is the relationship between an image's pixel dimensions and the physical size it appears (or should appear) when displayed, regardless of how it's displayed (screen, print, whatever). No image format inherently has a DPI, but any actual image that's made of pixels and should appear with a certain physical size has a DPI.
You're correct that DPI is just metadata as far as an image file is concerned. The image itself is a grid of pixels with no inherent physical size, but the DPI value expresses an intended physical size. For example, an image that's 144 pixels wide with a DPI of 144 should appear one inch wide when displayed, but an image that's 144 pixels wide with a DPI of 72 should appear two inches wide when displayed.
The DPI value stored in an image can be used to scale it automatically to the correct physical size when it's displayed on a device whose DPI is also known. For example, a 144dpi image displayed on a 72dpi monitor should be scaled by 50% in each dimension, so that 144 pixels (one inch) of image is mapped to 72 pixels (one inch) of monitor surface. Web browsers, however, typically don't do this; image pixels are simply mapped directly to screen pixels, so you have to manually scale your images to have pixel dimensions that are appropriate for the monitor where they'll be displayed.
You mentioned getting images at 2048x1536 @ 72 DPI and 1024x768 @ 144 DPI, but those are not at all equivalent. A 2048x1536 72DPI image should appear about 28.4 inches wide (2048/72), but a 1024x768 144DPI image should appear about 7.1 inches wide (1024/144). Are you sure you didn't mean 2048x1536 @ 144DPI and 1024x768 @ 72DPI (both of which are 14.2 inches wide)?
BTW, conventional (non-retina) monitors these days are typically 96 to 100 DPI, not 72. For example, my 20-inch Dell 2007WFP has pixel dimensions of 1680x1050. That's about 1981 pixels on the diagonal, which is about 99 pixels per inch. The "px" unit in CSS is actually defined as 1/96th of an inch, which may correspond to more than one physical pixel on a high-DPI screen.
A:
PNG does have the ability to store pixels/meter, separately for the X and Y direction, in the PNG "pHYs" chunk. Unfortunately this does not allow exact conversions (72 dpi is 2834.64566929 pixels per meter which is stored as 2835 pixels/meter and when converted back to DPI becomes 72.009); some people find this disturbing.
JPEG also can store X_density and Y_density, in units pixels/inch or pixels/cm.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Formatting text, Suggestions with how-to?
I'm trying to figure out how to format the code below so that the first two blocks of info display side by side, then display the third one centered underneath it. I tried using a listing style with css to format it so but doesn't seem to really work for me.
Help/Suggestions?
<div class="inauguration-content">
<h3>Inauguration</h3>
Friday, April 17, 2009<br />
3:00 p.m.<br />
Sarkus-Busch Theater<br />
Robert McLaughlin College Center</p>
<h3>Inaugural Gala</h3>
7-11 p.m.<br />
Robert McLaughlin College Center<br />
Featuring hors d'oeuvres, open bar and dinner and dessert stations<br />
Entertainment by Frankie Michaels<br />
Cocktail Attire Recommended<br />
Tickets are $100 per person<br />
Proceeds benefit the Herkimer County College Foundation</p>
<h3>Important Information for Delegates</h3>
<a href="http://www.herkimer.edu/admissions/directions/" target="_blank">Direction to HCCC</a><br />
<a href="http://www.herkimer.edu/pdfs/campusmap.pdf" target="_blank">Campus Map</a><br />
<a href="http://www.herkimer.edu/admissions/hotels/" target="_blank">Lodging Information</a><br />
Delegates marching in the Inaugural Procession should report to the Open Student Area, first floor of the Library Complex at 2:00 p.m. for robing and assembly.<br />
Delegates are expected to furnish their own academic regalia.</p>
</div>
A:
You can create three div's.
The first div (top-left) would have a width set at, say, 50% of the container (e.g. viewport) and float left.
The second div (top-right) would have a width set at, say, 50% of the container (e.g. viewport) and float right.
The third div (bottom-center) would have a witdh set at, say, 100% of the container (e.g. viewport) use the CSS 'clear:both' to position itself immediately below the tallest of the two floats. To center, use a smaller width (e.g. 50% or 20em) and set the CSS margin-left and margin-right to auto (see example below.)
The above will dynamically pack the three divs to accommodate any wrapping and vertical growing (including because of the increase of font size by the user for accessibility purposes) inside any of the three div's.
<html><body>
<div style="width:50%; float:left">
Inauguration<br/>
Friday, April 17, 2009<br/>
3:00 p.m.<br/>
Sarkus-Busch Theater<br/>
Robert McLaughlin College Center
</div>
<div style="width:50%; float:right">
Inaugural Gala<br/>
7-11 p.m.<br/>
Robert McLaughlin College Center<br/>
Featuring hors d'oeuvres, open bar and dinner and dessert stations<br/>
Entertainment by Frankie Michaels<br/>
Cocktail Attire Recommended<br/>
Tickets are $100 per person<br/>
Proceeds benefit the Herkimer County College Foundation
</div>
<div style="width:50%; margin-left:auto; margin-right:auto; clear:both">
Important Information for Delegates<br/>
Direction to HCCC<br/>
Campus Map<br/>
Lodging Information<br/>
Delegates marching in the Inaugural Procession should report to the Open Student Area, first floor of the
Library Complex at 2:00 p.m. for robing and assembly.<br/>
Delegates are expected to furnish their own academic regalia.
</div>
</body></html>
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.