text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
What is the best way to migrate from InstallScript to WiX Toolset?
We use InstallShield InstallScript projects to create our installers and are looking for a good way to migrate to the WiX Toolset. As far as I know there is no UpgradeCode (as for MSI) to update from an Installshield InstallScript project to a WiX project.
The only solution I found so far is:
manually save configurations
uninstall the InstallScript installation completely
install the WiX installation
apply the saved configurations
Is there a better way?
A:
Ok after all those comments I think I understand why this is such an issue. Unfortunately I don't think there is a very simple way to do waht you want to do.
I think your method will be the only real way to migrate from this isntallscript setup based installation. There should be some registry entry in HKLM/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall that relates to your product. In here there may be a uninstall command which you could read into a Variable from your burn package and pass that value as a property to your msi.
In you MSI you can have 3 custom actions specifically related to upgrading from the installshield product installation. All these tasks should be deferred custom actions so that they can run with administrator elevation. The first task should copy all the configuration settings to a safe place (generally %temp%\ProductConfig\ would be fine). The second part after saving the configuration would run that uninstall command to remove the product, you may need to append /q or something to make it run passively/quietly. Then at the end of the installation you can copy back the configuration files from temp.
Each of the custom actions should run conditionally on whether or not the property you passed in is set to something. I would schedule the copy cofig after InstallInitialize, the uninstall after the copy and the restore before InstallFinalize just to ensure that everything is copied over after the installer puts all the files on the system.
Ideally you would like to get everything to upgrade without the user needing to interact except in a minimal way by clicking next and Install.
I've only dealt with InstallShield enough to know I really don't like it so if someone else knows more and knows of a better way to do it they'll hopefully chime in.
| {
"pile_set_name": "StackExchange"
} |
Q:
Kafka Streams - How does it save the state internally
There are a lot of articles across the internet about the usage of the Kafka Streams, but almost nothing about how it's done internally.
Does it use any features inside Kafka outside the standard set (let's call "standard" the librdkafka implementation)?
If it saves the state inside RocksDB (or any custom StateStore), how it guarantees that the state saving and the commit are in one transaction?
The same question in the case when the state is saved in the compacted log (the commit and the log updated should be in one transaction).
Thank you.
A:
I found the answers by combining information from several threads here.
It uses transactions (see https://stackoverflow.com/a/54593467/414016) which are unsupported (yet) by librdkafka.
It doesn't really rely on RocksDB, instead it saves the state changes into the commit log (see https://stackoverflow.com/a/50264900/414016).
It does it using the transactions as mentioned above.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Text-Based Baseball Game - Flipping Booleans
My friend and I are making a Text-Based Baseball game in Python. We are trying to figure out how to manage the runners on base. We were thinking if the best way would be to have a list of booleans and flip them based on if the play was a single, double, etc. Any help would be appreciated!
Ex.
bases = [False,False,False]
if hit == single:
bases = [True,False,False]
We are finding it difficult considering all the possible combinations of runners on base
A:
from collections import deque
bases = [False, False, True]
playing_field = deque(bases)
print(playing_field) #deque([False, False, True])
playing_field.rotate(-1)
print(playing_field) #deque([False, True, False])
#can use it like a list:
print(playing_field[0]) #False
deque from collections is perfect for what you want to do. You can basically shift the list and add a member to first base.
rotate() takes an integer, positive or negative, and shifts the list that many times left or right.
If I were you, make it include a home plate, so you can pop it off and score or what not. IF you need deque has popleft() and popright() methods to literally take the left or right most item off the list.
| {
"pile_set_name": "StackExchange"
} |
Q:
flex transition effects works on 2nd and after transition, but not on very first transition
i have a flex app that transitions between 2 states with the toggle of a button. my issue is that the effect of fading only seems to work on the 2nd transition and after. However, for my first transition... going from State1 to studyState... there is no fade effect whatsoever, in fact the components in state1 disappear completely (the footer fills the empty gap where the "body" use to be) and then the flex recreates the studyState (without any fade refilling the "body" with components only in studyState).
After this first transition however, going between studyState and State1 working COMPLETELY fine.. why does this happen and how can i make it so that crossfade works STARTING FROM THE VERY FIRST TRANSITION? please help!
<s:transitions>
<s:Transition id="t1" autoReverse="true">
<s:CrossFade
target="{holder}"
duration="1500" />
</s:Transition>
</s:transitions>
<s:states>
<s:State name="State1" />
<s:State name="studyState" />
</s:states>
<s:VGroup id="globalGroup" includeIn="State1" width="100%">stuff</Vgroup>
<s:VGroup id="studyGroup" includeIn="studyState" width="100%">stuff</Vgroup>
A:
What is wrong about the state transition? Can you provide a full code sample?
This code segment, basically, works as I would have expected:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<s:transitions>
<s:Transition id="t1" autoReverse="true">
<s:CrossFade
target="{this}"
duration="1500" />
</s:Transition>
</s:transitions>
<s:states>
<s:State name="State1" />
<s:State name="studyState" />
</s:states>
<s:VGroup id="globalGroup" includeIn="State1" width="100%">
<s:Button label="State1 to studyState" click="this.currentState = 'studyState'" />
</s:VGroup>
<s:VGroup id="studyGroup" includeIn="studyState" width="100%">
<s:Button label="studyState to State1" click="this.currentState = 'State1'" />
</s:VGroup>
</s:Application>
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I use tmutil to figure out which files just got deleted?
I'm on Lion and until ten minutes ago I didn't know that the nifty new tmutil existed. But now I'm a little uncertain with all its options and sub-commands which to use to try and figure out what went wrong and how to fix it.
A program ran amuck and started deleting files from ~. It made only a little progress before I stopped it, but doubtless I lost some files. I just can't tell out of a drive with hundreds of thousands of files, which ones went away. I know there were some configuration files (for example .bash_profile) because those were right there in that folder, but doubtless it went off in some depth first rampage so no telling what got deleted and from where.
I can't just do a restore of /Users/John (the Mac OS prevents it), I can't restore all the files inside of /Users/John using the GUI (the Finder ignores all the .something files and folders, some of which I know were deleted), so my current hope is to figure out from the command line exactly which files got the axe and somehow restore only those from my Time Machine backup.
In other words... help.
A:
Run
tmutil listbackups
to get the list of snapshots available. Pick the one before the problem occured and run
tmutil compare YOUR-SNAPSHOT-HERE | cut -c33- | grep /Users/YOUR-USERNAME
to get a list of differences between then and now. If you leave out the cut part you may also get some indication concerning the actual difference (but it's more difficult to use the result afterwards).
| {
"pile_set_name": "StackExchange"
} |
Q:
Puzzled by ror Mechanize
I'm trying to use mechanize to perform a simple search on my college's class schedule db. The following code returns nil, however it works logging into facebook and searching google (with diff url/params). What am I doing wrong?
I'm following the latest (great) railscast here. Mechanize documentation has been useful but I'm still puzzled. Thanks in advance for your suggestions!
ruby script/console
require 'mechanize'
agent = WWW::Mechanize.new
agent.get("https://www.owens.edu/cgi-bin/class.pl/")
agent.page.forms
form = agent.page.forms.last
form.occ_subject = "chm"
form.submit.search
=> []
A:
Remove search from form.submit.search i.e. form.submit I'm guessing you're appending search to submit thinking that it has something to do with the value of the submit button i.e. search.
What you're code is doing IS successfully submitting the form. However you are calling the search method of the resulting page object with a nil argument. The search method expects a selector e.g. 'body div#nav_bar ul.links li' as an argument for it to return an array of elements that match that selector. Of course no elements will match a nil selector, hence the empty array.
Edit per your response:
Your code:
ruby script/console
require 'mechanize'
agent = WWW::Mechanize.new
agent.get("https://www.owens.edu/cgi-bin/class.pl/")
agent.page.forms
form = agent.page.forms.last
form.occ_subject = "chm"
form.submit.search
=> []
What I tried and got to work:
ruby script/console
require 'mechanize'
agent = WWW::Mechanize.new
agent.get("https://www.owens.edu/cgi-bin/class.pl")
agent.page.forms
form = agent.page.forms.last
form.occ_subject = "chm"
form.submit # <- No search method.
=> Insanely long array of HTML elements
The same code will not work with Google either:
require 'mechanize'
require 'nokogiri'
agent = WWW::Mechanize.new
agent.get("http://www.google.com")
form = agent.page.forms.last
form.q = "stackoverflow"
a = form.submit.search
b = form.submit
puts a
=> [] # <--- EMPTY!
puts b
#<WWW::Mechanize::Page
{url
#<URI::HTTP:0x1020ea878 URL:http://www.google.co.uk/search?hl=en&source=hp&ie=ISO-8859-1&q=stackoverflow&meta=>}
{meta}
{title "stackoverflow - Google Search"}
{iframes}
{frames}
{links
#<WWW::Mechanize::Page::Link
"Images"
"http://images.google.co.uk/images?hl=en&source=hp&q=stackoverflow&um=1&ie=UTF-8&sa=N&tab=wi">
#<WWW::Mechanize::Page::Link
"Videos"
…
The search method of a page object behaves like the search method of Nokogiri, in that it accepts a sequence of CSS selectors and/or XPath queries and returns an enumerable object of matching elements. e.g.
page.search('h3.r a.l', '//h3/a[@class="l"]')
| {
"pile_set_name": "StackExchange"
} |
Q:
Maze generation vector segmentation fault
The code creates a maze using a depth-first search algorithm. The code compiles completely fine, but when running it, it produces a segmentation fault.
This is the code:
#include "stdafx.h"
#include <cctype>
#include <ctime>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include "maze2.h"
enum mDirection { UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3 };
//the alrogrithm used for maze generation is the depth first search algorithm
//i followed this as a guide http://www.migapro.com/depth-first-search/
//the link uses arrays but i've tried to use vectors as i believe using arrays was one cause of an issue in the last maze generation code
bool Maze::randDirection(bool firstMove) {
int randAdjSquare;
std::vector<std::vector<int>> unvisAdjSquare; //unvisited adjacent squares
for (int direction = 0; direction < 4; direction++) { //i is the direction
int possible_pmd[2] = { 0, 0 };
if (direction == UP) {
possible_pmd[1] = -1;
}
else if (direction == DOWN) {
possible_pmd[1] = 1;
}
else if (direction == LEFT) {
possible_pmd[0] = -1;
}
else {
possible_pmd[0] = 1;
}
if (algoPath.back()[0] + possible_pmd[0] * 2 >0 && algoPath.back()[0] + possible_pmd[0] * 2 <mazeSize[0] - 1 && algoPath.back()[1] + possible_pmd[1] * 2 > 0 && algoPath.back()[1] + possible_pmd[1] * 2 < mazeSize[1] - 1) {
if (!maze[algoPath.back()[1] + possible_pmd[1] * 2]
[algoPath.back()[0] + possible_pmd[0] * 2][1]) {
std::vector<int> possMove = { possible_pmd[0], possible_pmd[1] };
unvisAdjSquare.push_back(possMove);
}
}
if (unvisAdjSquare.size() > 0) {
randAdjSquare = rand() % unvisAdjSquare.size();
for (int i = 0; i< !firstMove + 1; i++) {
std::vector<int> nextPlace;
nextPlace.push_back(algoPath.back()[0] + unvisAdjSquare[randAdjSquare][0]);
nextPlace.push_back(algoPath.back()[1] + unvisAdjSquare[randAdjSquare][1]);
algoPath.push_back(nextPlace);
maze[algoPath.back()[1]][algoPath.back()[0]][0] = false;
maze[algoPath.back()[1]][algoPath.back()[0]][1] = true;
}
return true;
}
else {
return false;
}
}
return true;
}
void Maze::generateMaze() {
bool firstMove = true;
bool worked = true;
while ((int)algoPath.size() > 1 - firstMove) {
if (!worked) {
algoPath.pop_back();
if (!firstMove && algoPath.size() > 2) {
algoPath.pop_back();
}
else {
break;
}
worked = true;
}
while (worked) {
worked = randDirection(firstMove);
if (firstMove) {
firstMove = false;
}
}
}
}
void Maze::initMaze() { //this function sets up the vector as a grid of the size defined before in the mazeSize variable
for (int i = 0; i < mazeSize[1]; i++) {
for (int j = 0; j <mazeSize[0]; j++) {
bool isEdge; // this bool checks to see if the next square is the edge of the vector, if it is, keep going back until the algorithm is able to move in a new direction
if (i == 0 || i == mazeSize[1] - 1 || j == 0 || j == mazeSize[0] - 1) {
isEdge = true;
}
else {
isEdge = false;
}
std::vector<bool> newCell = { true, isEdge };
if ((int)i + 1 > maze.size()) {
std::vector<std::vector<bool>> newRow = { newCell };
maze.push_back(newRow);
}
else {
maze[i].push_back(newCell);
}
}
}
}
void Maze::printMaze() {
for (int i = 0; i < maze.size(); i++) {
for (int j = 0; j < maze[i].size(); j++) {
if (maze[i][j][0]) {
std::cout << "##";
}
else {
std::cout << " ";
}
}
std::cout << std::endl;
}
}
void Maze::setStartandEnd(bool jeff) {
int axis;
int side;
if (!jeff) {
axis = rand() % 2;
side = rand() % 2;
Maze::startSide = side;
Maze::startAxis = axis;
}
else {
bool done = false;
while (!done) {
axis = rand() % 2;
side = rand() % 2;
if (axis != startAxis || side != startSide) {
done = true;
}
}
}
std::vector<int> place = { 0, 0 };
if (!side) {
place[!axis] = 0;
}
else {
place[!axis] = mazeSize[!axis] - 1;
}
place[axis] = 2 * (rand() % ((mazeSize[axis] + 1) / 2 - 2)) + 1;
if (!jeff) {
algoPath.push_back(place);
}
Maze::maze[place[1]][place[0]][0] = false;
Maze::maze[place[1]][place[0]][1] = true;
}
int main() {
srand(time(NULL));
Maze maze;
maze.initMaze();
maze.setStartandEnd(false);
maze.setStartandEnd(true);
maze.generateMaze();
maze.printMaze();
return 0;
}
This is the header file "maze2.h" that is included in the code:
#pragma once
class Maze {
private:
int mazeSize[2];
int startAxis;
int startSide;
std::vector<std::vector<int>> algoPath;
std::vector<std::vector<std::vector<bool>>> maze;
std::vector<int> place;
public:
bool randDirection(bool);
bool validInt(char*);
void generateMaze();
void initMaze();
void printMaze();
void setStartandEnd(bool);
};
I have run it through the debugging tool, and it runs up until this line:
Maze::maze[place[1]][place[0]][0] = false;
I commented this out to see if the same issue occurs on the next line, and it does.
The debugger gives me this error when the line tries to run:
Unhandled exception at 0x1008CAB6 (ucrtbased.dll) in maze2.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.
I believe this, as well as the segmentation fault, shows that the code is trying to assign memory that hasn't been allocated yet, but I can't figure out why. I have declared everything, so it should be in memory, but I just can't figure out why this is happening.
A:
As the comment points out, this code does not initialize the value of mazeSize explicitly, so its value will be default initialized to {0, 0}
When you run
maze.initMaze();
in main, Maze::maze will not be init properly (the for loop will not run). That will cause the program to throw an "out of range" exception to be thrown when
maze.setStartandEnd(false);
trys to access the first element inside the Maze::maze because Maze::maze is still empty(has a size of 0).
| {
"pile_set_name": "StackExchange"
} |
Q:
Given a ring $R$ and a ring extension $R'$, if $r=r's$ where $r'\in R'\setminus R$, does that mean that $s\not\mid r$ in $R$?
Given a ring $R$ and a ring extension $R'$, if $r=r's$ where $r'\in R'\setminus R$ and $r,s\in R\setminus\{0\}$, does that mean that $s\not\mid r$ in $R$?
I was thinking for example in $\Bbb{Z}$, since $\frac{2}{3} \not\in \Bbb{Z}$ then $3\not\mid 2$ in $\Bbb{Z}$. Or equivalently $2=\frac23 3$, since $\frac23 \in \Bbb{Q}\setminus \Bbb{Z}$ we know $3\not\mid 2$.
So in general I conjecture if "$\frac{r}{s}$" exists only in some larger ring, then $s\not\mid r$. Is this true? Or is there some extreme example where $r=r's$ for some $r'$ in a larger ring and also $r=ts$ for $t$ in the original ring?
Note there are trivial cases where $r$ and $s$ are $0$.
I think this would be a good characterization of divisibility.
A:
If $s$ is not a right zero divisor in $R'$, a counterexample is obviously impossible, since then $as=bs$ implies $a=b$ so $r'$ is the only element of $R'$ such that $r's=r$. Without this assumption, there are counterexamples. For instance, take $R=\mathbb{Z}$ and $R'=\mathbb{Z}[x]/(2x)$ and let $r=6$, $s=2$, and $r'=3+x$.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best way of converting List object to long[] array in java?
Is there any utility method to convert a list of Numerical types to array of primitive type?
In other words I am looking for a better solution than this.
private long[] toArray(List<Long> values) {
long[] result = new long[values.size()];
int i = 0;
for (Long l : values)
result[i++] = l;
return result;
}
A:
Since Java 8, you can do the following:
long[] result = values.stream().mapToLong(l -> l).toArray();
What's happening here?
We convert the List<Long> into a Stream<Long>.
We call mapToLong on it to get a LongStream
The argument to mapToLong is a ToLongFunction, which has a long as the result type.
Because Java automatically unboxes a Long to a long, writing l -> l as the lambda expression works. The Long is converted to a long there. We could also be more explicit and use Long::longValue instead.
We call toArray, which returns a long[]
A:
Google Guava : Longs.toArray(Collection)
long[] result = Longs.toArray(values);
A:
Use ArrayUtils.toPrimitive(Long[] array) from Apache Commons.
Long[] l = values.toArray(new Long[values.size()]);
long[] l = ArrayUtils.toPrimitive(l);
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL is 8 hours behind timezone set by PHP
I have a PHP script that is setting the timezone for the MySQL session. I have checked the output and it is sending the offset correctly, +1:00 (Europe/London in DST). However, when I read the timestamp that has been placed in the database, it is eight hours behind. Why is this happening?
The MySQL server is setting the timestamp as the default value.
A:
Update your database parameters:
SET GLOBAL time_zone = 'Europe/London';
// OR: SET time_zone = 'Europe/London';
// OR: SET @@session.time_zone = 'Europe/London';
Update timezone directly in the request:
SELECT ..., CONVERT_TZ(field, 'GMT', 'Europe/London') FROM ...
Define in the entry file (like index.php) the proper timezone:
date_default_timezone_set('Europe/London');
Additionally it can be done on server (sample, Ubuntu):
sudo timedatectl set-timezone Europe/London
# do not forget to restart all services: nginx|Apache, mysql, ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex to block pattern except in certain situations
I am working with the following regex:
[\s.,_-]*[wW][\s.,_-]*[wW][\s.,_-]*[wW]
It blocks all instances of www in a chat window for me ... there in lies the issue.
I want it to keep looking for spaces and special chars before the first w and still block, but I also want it to leave words like awwwwwww and ewwwwwwww alone completely.
I feel like I'm not far off but I have exhausted my regex know how.
A:
To answer your question, you could use
\b[wW](?:[\s.,_-]*[wW]){2}\b
\b is a word boundary, (?:...) is a non capturing parenthesis.
But indeed, without more context it's hard to tell if your URL filter won't break on strange output.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I take a sensitive result for this equation?
Is there any sensitive equation solver which will not show the result as approximately 0 for this equation:
$cosx=e^{-\frac{x}{10^{45}}}$
being x is variable, or how can I calculate it?
A:
Using the same idea as Alan Turing, using Taylor expansion to $O\left(x^3\right)$ we have $$\cos (x)-e^{-\frac{x}{a}}=\frac{x}{a}-\left(\frac{1}{2 a^2}+\frac{1}{2}\right) x^2+O\left(x^3\right) $$ and solving the quadratic, beside the trivial solution $x=0$, there is $$x_0=\frac{2 a}{1+a^2}$$
Coding Newton method in a double precision Fortran program for $a=10^{45}$, only one iteration can be performed and the first and last iterate is $$x_1= 1.99999999999999996830000\times 10^{-45}$$ The calculations stop because the derivative is computed to be $0$.
I suppose that using extended precision will allow more significant figures.
Edit
Consider the equation $$f(x)=\cos(x)-e^{-\frac{x}{a}}$$ and perform one iteration of Newton (or halley or Householder) method starting at $x_0=\frac{2 a}{1+a^2}$ Comuting the first iterate $x_1$, write it as $$x_1=x_0\left(1-\frac{f(x_0)}{x_0\,f'(x_0)}\right)$$ and call $\epsilon$ the machine accuracy. Developing the term in bracket as Taylor series around $a=0$, it is sure that we shall start to be in trouble as soon as $$\frac1{3a^2} <\epsilon\implies a >\frac 1{\sqrt{3\epsilon}}$$ Using $\epsilon=10^{-19}$ as in the Fortran environment I used, this means that problem will start as soon as $a >2 \times 10^{9}$. So, the result given above does not mean anyhing except that is is an inacurrate estimate of the starting value itself.
| {
"pile_set_name": "StackExchange"
} |
Q:
When a function which has one parameter receives np.array
Suppose there is a function:
def test(x):
return x**2
When I give a list of ints to the function, an error is raised:
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
But an array of ints instead, the function returns an array of outputs.
How is this possible?
A:
It's important to understand that operators are functions too:
Writing a**b is like writing pow(a, b)
Functions can't guess what the expected behavior is when you give them different inputs, so behind the scenes, pow(a, b) has different implementations for different inputs (i.e. for two integers, return the first in the power of the second. For an array of integers, return an array where each cell has the corresponding cell in the input array in the power of the second integer)
whoever implemented the numpy array created a ** implementation for it, but an ordinary list doesn't have a ** implementation.
If you want to raise a list to a power, use list comprehension:
[xi ** 2 for xi in x]
You can also write your own class and implement ** for it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if NSFont is bold in Swift
I am writting unit test checking the format of a generated NSAttributedString.
I can extract the font like this:
if let font = attributedString.attributesAtIndex(0, effectiveRange: nil) as? NSFont {
...
}
Given this NSFont instance, how can I check if it is bold or not?
A:
You can check your font traits like this:
let descriptor = font.fontDescriptor
let symTraits = descriptor.symbolicTraits
let traitSet = NSFontTraitMask(rawValue: UInt(symTraits))
let isBold = traitSet.contains(.BoldFontMask))
But I'm not sure if isBold would be true for all seemingly-bold fonts.
| {
"pile_set_name": "StackExchange"
} |
Q:
A fantasy book about runes where the hero learns to chop wood
I read this many years ago (around 1990-92) and I don't remember a lot of details about the story.
There was a young man who was being raised by his uncle and aunt I believe. I really forget what the point of his journey is supposed to be - maybe finding his father or mother who disappeared. It was part of a trilogy, I think, and my library only had the first in the series and soon they didn't have that one either.
I remember there was a tinker that visited the cottage and repaired pots and pans. There was also some training given to the teenage hero that involved him chopping wood and it went into detail about the weight of the axe doing the work. There was also a horse and runes in the story.
The horse may have been magical or even talking. I think it was black and had a star or moon on its brow.
I think - but am not sure - that "Runes" was in the title.
I don't have any more details to give and realize this isn't a lot to go on. The writing seemed to be teen orientated but the only classification it had at my library was fantasy.
A:
Is this the Tales of Gom in the Legends of Ulm by Grace Chetwin?
About the first book, Gom on Windy Mountain, GoodReads has the following description:
Plot: Gom is born, the tenth child of Stig, simple woodcutter on Windy Mountain, and a mysterious woman who turns up one day and whom he calls, Wife. As Gom grows, he finds he has gifts others do not possess, neither does he age as fast as his siblings do. He also learns the dangers of his hasty tongue, running afoul of a wily pedlar, Dismas Skeller. Finding gold beneath the mountain, Gom almost dies for it, then is shunned by townsfolk below who do not recognize the true worth of the metal.
About the second book, The Riddle and the Rune, GoodReads offers the following:
Plot: Gom no sooner sets out to find his wizard mother, Harga, when strange things begin to happen. A bear appears, and the sparrow atop his staff comes to life and utters a riddle. Solve it, and his mother would appear, it says. Easy, thinks Gom, but he soon learns that it is not the regular word conundrum but a life riddle which can be solved only through experience. Plodding on, he is attacked by a vicious skull bird which almost kills him, and so the adventure begins.
The Riddle and the Rune description at Google books, says:
Gom sets forth to seek his destiny, discovering that he has new powers and a gift for making friends such as the magnificent horse, Stormfleet, who accompanies him through many adventures.
It seems to have many elements of what you describe: young man looking for mother, chopping wood (a woodcutter), an innate ability to communicate with animals and nature including a prominent horse, a tinker, the second book contains the word Rune and rune(s) play some (important?) role, and the original trilogy was published before 1990.
You can find sample chapters of the above (or other Grace Chetwin works) at the Feral Press Inc site.
I haven't read these myself, so I can't directly speak to the story elements. This is the closest I've found though.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do declare methods that return a Sequence of custom Structs in Swift
What is the proper way to declare a function that return a Sequence in Swift 4. I tried the following but receive a error stating:
error: Models.playground:29:13: error: cannot convert return expression of type 'Cars' to return type 'S'
return Cars(cars)
^~~~~~~~~~
as! S
Here is the code I used:
import Foundation
struct Car {
let make:String
let model:String
}
class Cars: Sequence, IteratorProtocol {
typealias Element = Car
var current = 0
let cars:[Element]
init(_ cars:[Element]) {
self.cars = cars;
}
func makeIterator() -> Iterator {
current = 0
return self
}
func next() -> Element? {
if current < cars.count {
defer { current += 1 }
return cars[current]
} else {
return nil
}
}
}
let cars = Cars([Car(make:"Buick", model:"Century"), Car(make:"Buick", model:"LaSabre")])
func getCars<S:Sequence>(cars:[Car]) -> S where S.Iterator.Element == Car {
return Cars(cars)
}
A:
The return value cannot be a specialization of the Sequence protocol.
You can either return Cars itself, as Daniel suggested, or –
if you want to hide the implementation of the sequence – a
“type-erased” sequence:
func getCars(cars:[Car]) -> AnySequence<Car> {
return AnySequence(Cars(cars))
}
or even
func getCars(cars:[Car]) -> AnySequence<Car> {
return AnySequence(cars)
}
AnySequence is a
generic struct conforming to the Sequence protocol which forwards
to the underlying sequence or iterator from which it was created.
See also A Little Respect for AnySequence
for more examples.
Remark: Similarly, it is possible to make Cars a Sequence
by returning a type-erased iterator which forwards to the array
iterator:
class Cars: Sequence {
typealias Element = Car
let cars: [Element]
init(_ cars: [Element]) {
self.cars = cars;
}
func makeIterator() -> AnyIterator<Element> {
return AnyIterator(cars.makeIterator())
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: How to create a csv string (no file) from a list of dictionaries?
In Python I have a list of dictionaries like this:
[
{
"col2": "2",
"id": "1",
"col3": "3",
"col1": "1"
},
{
"col2": "4",
"id": "2",
"col3": "6",
"col1": "2"
},
{
"col1": "1",
"col2": "4",
"id": "3",
"col3": "7"
}
]
and I need to convert this to a string in csv format including a header row. (For starters let's not care about column and row delimiters...)
So, ideally the result would be:
id,col1,col2,col3
1,1,2,3
2,2,4,6
3,1,4,7
("ideally" because the column order does not really matter; having the "id" column first would be nice though...)
I have searched SOF and there are a number of similar questions but the answers always involve creating a csv file using csv.DictWriter. I don't want to create a file, I just want that string!
Of course, I could loop over the list and inside this loop loop over the dictionary keys and in this way create the csv string using string operations. But surely there must be some more elegant and efficient way of doing this?
Also, I'm aware of the Pandas library but I am trying to do this in a very limited environment where I would prefer to use only built-in modules.
A:
The easiest way would be to use pandas:
import pandas as pd
df = pd.DataFrame.from_dict(your_list_of_dicts)
print(df.to_csv(index=False))
Result:
col1,col2,col3,id
1,2,3,1
2,4,6,2
1,4,7,3
If you want to reorder columns, nothing easier:
col_order = ['id', 'col1', 'col2', 'col3']
df[col_order].to_csv(index=False)
or, to just ensure the id column is first:
df.set_index('id', inplace=True) # the index is always printed first
df.to_csv() # leave the index to True this time
A:
You can use io.StringIO to write to a 'string' instead of a file. Using the example of csv.DictWriter we get the following code:
import csv
import io
data = [...] # your list of dicts
with io.StringIO() as csvfile:
fieldnames = ['id', 'col1', 'col2', 'col3']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for row in data:
writer.writerow(row)
print(csvfile.getvalue())
| {
"pile_set_name": "StackExchange"
} |
Q:
How to place NULLs last in ascending order
I need to sort a table and I need to display the rows that include Nulls at the bottom. Whenever I run the below query
select * from t1
order by status, date;
Nulls show up in the first row which I don't want:
+--------+------------+--+
| Status | Date | |
+--------+------------+--+
| 1 | NULL | |
| 1 | 2011-12-01 | |
| 1 | 2011-12-21 | |
| 2 | NULL | |
| 2 | 2005-09-02 | |
| 3 | 2000-08-07 | |
| | | |
+--------+------------+--+
This is what I need:
+--------+------------+--+
| Status | Date | |
+--------+------------+--+
| 1 | 2011-12-01 | |
| 1 | 2011-12-21 | |
| 1 | NULL | |
| 2 | 2005-09-02 | |
| 2 | NULL | |
| 3 | 2000-08-07 | |
| | | |
+--------+------------+--+
How can I do it?
A:
select * from t1
order by status,
date,
CASE WHEN date is NULL
THEN 1
ELSE 0
END;
| {
"pile_set_name": "StackExchange"
} |
Q:
PhpStorm incorrectly showing files as unversioned in Git
In a project I have that is under Git PhpStorm is showing a bunch of files that it states are "unversioned", however Git disagrees.
Running:
git ls-files . --exclude-standard --others
...from the Terminal shows nothing.
PhpStorm version 2018.1.6
Did PhpStorm get confused somehow or what is the problem here?
A:
Ok, it seems I had previously set this project to using the SubVersion VCS.
I fixed this by:
Pressing ctrl + alt + s (Windows) to bring up Settings
Navigating to Version Control
On the right I saw my project and changed the and changed the selection under the VCS header to "Git"
After I had done this it started working correctly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Drop down menu doesnt work
My Drop down menu to choose a date does not work unless I hold down left click on my mouse.
Only the year drop down works correctly but the month and days only work if you hold your mouse button down.
Here is the website it is on: www.cipslimoshuttle.com/tickets
Here is the code:
<label>
Date of travel:
<select name="ticketYear">
<?php
$i = date('Y');
while($i <= date('Y')+5){
?>
<option <?php if(date('Y') == $i) echo 'selected' ?> value="<?php echo $i ?>"><?php echo $i ?></option>
<?php
$i++;
}
?>
</select>
<select name="ticketDay">
<?php
$i = 1;
while($i <= 31){
?>
<option <?php if(date('j') == $i) echo 'selected' ?> value="<?php echo $i ?>"><?php echo $i ?></option>
<?php
$i++;
}
?>
</select>
<select name="ticketMonth">
<?php
$months = array(
'01-January',
'02-February',
'03-March',
'04-April',
'05-May',
'06-June',
'07-July',
'08-August',
'09-September',
'10-October',
'11-November',
'12-December'
);
foreach($months as $month) {
$month = explode('-',$month);
?>
<option <?php if(date('m') == $month[0]) echo 'selected' ?> value="<?php echo $month[0] ?>"><?php echo $month[1] ?></option>
<?php
}
?>
</select>
</label>
A:
The problem is with your label tag You need to end before the select box.Check this it will work
<label>
Date of travel: </label>
<select name="ticketYear">
<?php
$i = date('Y');
while($i <= date('Y')+5){
?>
<option <?php if(date('Y') == $i) echo 'selected' ?> value="<?php echo $i ?>"><?php echo $i ?></option>
<?php
$i++;
}
?>
</select>
<select name="ticketDay">
<?php
$i = 1;
while($i <= 31){
?>
<option <?php if(date('j') == $i) echo 'selected' ?> value="<?php echo $i ?>"><?php echo $i ?></option>
<?php
$i++;
}
?>
</select>
<select name="ticketMonth">
<?php
$months = array(
'01-January',
'02-February',
'03-March',
'04-April',
'05-May',
'06-June',
'07-July',
'08-August',
'09-September',
'10-October',
'11-November',
'12-December'
);
foreach($months as $month) {
$month = explode('-',$month);
?>
<option <?php if(date('m') == $month[0]) echo 'selected' ?> value="<?php echo $month[0] ?>"><?php echo $month[1] ?></option>
<?php
}
?>
</select>
| {
"pile_set_name": "StackExchange"
} |
Q:
Where do I put my environment variables for API credentials?
I'm trying to work with the Spotify API and it needs client credentials. I've integrated spotipy and it works fine when I don't need to request user info (i.e. just downloading track names from an artist) but I wish to access audio features.
In what file/script and how do I include credentials?
This is what they say in the oauth2.py file:
You can either provid a client_id and client_secret to the
constructor or set SPOTIPY_CLIENT_ID and SPOTIPY_CLIENT_SECRET
environment variables
https://github.com/plamere/spotipy/blob/master/examples/audio_features.py
A:
I would start here - Authorized Requests. Then you can simply use this example:
token = util.prompt_for_user_token(username)
if token:
sp = spotipy.Spotify(auth=token)
To get things started and then grab what you need.
See this page for full documentation. And here for details using the SpotifyClientCredentials.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reading a file, getting the current position and reading backwards
I'm using the BufferedReader class to search an occurrence in a large file by reading it line by line.
How can I get the current position when the occurrence is found ?
Then, how can I read in reverse the file starting at that position ?
I really searched on the net for a consistent solution but haven't found.
A:
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("sample.txt");
BufferedReader reader = new BufferedReader(fr);
String line = "";
ArrayList<String> linee = new ArrayList<String>();
while ((line = reader.readLine()) != null) {
if (line.equals("bb"))
break;
linee.add(line);
}
reader.close();
for (int i = linee.size() - 1; i >= 0; i--)
System.out.println(linee.get(i));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot loop through list A(icollection) of generic type B where A and B both implement same interface
The intro is a bit tedious, but is just for clearity! Some might even learn something from it or get some handy insights. My question is found at the bottom. I really hope someone can help me!
I have this interface
public interface IEFEntity
{
object GetPKValue();
bool PKHasNoValue();
}
All my automatic genereted EF classes implement this interface and implement the 2 methods. This is done via a separate file using partial classes so the implementation is not gone when regenerating the EF classes. This is not important for the question but I have put an example of the setup of two EF classes, debiteur and schakeling below. All are in the same namespace offcourse:
public partial class debiteur
{
public debiteur()
{
this.schakeling = new HashSet<schakeling>();
}
public int id { get; set; }
public string naam { get; set; }
public virtual ICollection<schakeling> schakeling { get; set; }
}
public partial class schakeling
{
public schakeling()
{
this.debiteur = new HashSet<debiteur>();
}
public int id { get; set; }
public string omschrijving { get; set; }
public virtual ICollection<debiteur> debiteur { get; set; }
}
And I have this 2 extra partials that implement the interface. Nothing special here.
public partial class debiteur : IEFEntity
{
public object GetPKValue() {
return this.id;
}
public bool PKHasNoValue() {
return this.id == 0;
}
}
public partial class schakeling : IEFEntity
{
public object GetPKValue() {
return this.id;
}
public bool PKHasNoValue() {
return this.id == 0;
}
}
(Just to clearify: Other EF generated classes might have a PK property who's name is not 'id' or even have a PK of type string and a name of username, but this is not important for the question! And also not the only reason I use these methods, keep reading...)
I have a GenManager class which uses two generic type parameters. Here's the class definition without implementation. (And I know, this only works for entities/tables with a single PK not with composite keys, as debated here)
public class GenManager<Entity, EntityKey> where Entity : class, IEFEntity {}
This means that the Entity type parameter must be a class which implement interface IEFEntity. So anywhere in my application, lets say a controller I can now create an instance by using:
private GenManager<debiteur, int> DebiteurManager;
private GenManager<schakeling, int> SchakelingManager;
But for example:
private GenManager<anotherClass, int> AnotherClassManager;
will fail because anotherClass does not implement IEFEntity. But back to the GenManager class. Here's the first outlining without all the implementation
public class GenManager<Entity, EntityKey> where Entity : class, IEFEntity
{
public IQueryable<Entity> Items { get { return repo.Items; } }
private IGenRepo<Entity, EntityKey> repo;
public GenManager(IGenRepo<Entity, EntityKey> repo) { this.repo = repo; }
public Entity find(EntityKey pk) { return repo.find(pk); }
public RepoResult delete(EntityKey pk) { return repo.delete(pk); }
public RepoResult create(Entity item) { return repo.create(item); }
public RepoResult update(Entity item) { return repo.update(item); }
public bool isInFKEntity<FKEntity, FKEntityKey>(EntityKey pk, FKEntityKey fk) where FKEntity : class, IEFEntity { }
public List<FKEntity> GetFKEntities<FKEntity, FKEntityKey>(EntityKey pk) where FKEntity : IEFEntity { }
public RepoResult removeFKEntities<FKEntity, FKEntityKey>(EntityKey pk, FKEntityKey[] fkList) where FKEntity : IEFEntity { }
public RepoResult addFKEntities<FKEntity, FKEntityKey>(EntityKey pk, FKEntityKey[] fkList) where FKEntity : IEFEntity { }
public RepoResult resetFKEntities<FKEntity, FKEntityKey>(EntityKey pk, FKEntityKey[] fkList) where FKEntity : IEFEntity { }
public RepoResult resetFKEntities2<FKEntity, FKEntityKey>(EntityKey pk, FKEntityKey[] fkList) where FKEntity : IEFEntity { }
public RepoResult resetFKEntities3<FKEntity, FKEntityKey>(EntityKey pk, FKEntityKey[] fkList) where FKEntity : IEFEntity { }
public RepoResult clearFKEntities<FKEntity>(EntityKey pk) where FKEntity : IEFEntity { }
}
Take a second to look at this. Just as the first generic type Entity of the GenManager class must be a class that implements IEFEntity, this must also be the case with generic type FKEntity used in the methods. So in my controller for example I can now use this statement:
bool b = DebiteurManager.isInFKEntity<schakeling, int>(debiteur_id, schakeling_id);
But again an example:
bool b = DebiteurManager.isInFKEntity<anotherEntity, int>(debiteur_id, anotherEntity_id);
will fail because anotherEntity does not implement IEFEntity.
And it is in these methods where the magic must happen using c# reflection and I face a problem. I give you the implementation of the unfinished method isInFKEntity with some test code statements including comments:
public bool isInFKEntity<FKEntity, FKEntityKey>(EntityKey pk, FKEntityKey fk) where FKEntity : class, IEFEntity
{
Entity dbEntry = find(pk);
if (dbEntry == null) throw new InvalidOperationException(RepoMessages.dbEntryIsNull(new List<object> { pk }));
//----------Not important for question! Just to clearify things----------\\
var v1 = typeof(Entity).GetProperty("naam").GetValue(dbEntry);//Sets v1 to a string value
var v1Copy = new debiteur().GetType().GetProperty("naam").GetValue(dbEntry);//Just to test and clearify what the above statement does, vars have the same value!
//----------End----------\\
var FKEntityList = typeof(Entity).GetProperty(typeof(FKEntity).Name).GetValue(dbEntry);//Gives a list back at runtime, but I can't loop through them
var FKEntityListCopy = new debiteur().GetType().GetProperty("schakeling").GetValue(dbEntry);//Just to test and clearify what the above statement does, vars have the same value!
var FKEntityListWithCast = typeof(Entity).GetProperty(typeof(FKEntity).Name).GetValue(dbEntry) as List<FKEntity>;//Gives a NULL value back at runtime, but intellisense!
var FKEntityListWithCastCopy = new debiteur().GetType().GetProperty("schakeling").GetValue(dbEntry) as List<FKEntity>;//Just to test and clearify what the above statement does, vars have the same value!(also NULL)
return false;
}
I want to loop through FKEntityList but if I try to do that using a foreach I get a message: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'. Also, using intellisense only shows the 4 standard methods Equals(object obj), GetHashCode(), GetType() and ToString(). See image
So I try to cast it succesfully using as List<FKEntity> and assign the result to FKEntityListWithCast and now I get no error message using a foreach.
So I thought, very nice I just use this return statement and it works:
return FKEntityListWithCast.Any(item => item.GetPKValue().ToString() == fk.ToString());
The above return statment doesn't give an error and everything compiles, but the problem is that at runtime the FKEntityListWithCast doesn't get a value. It stays NULL. So the problem is:
GETS VALUE at runtime but CANNOT loop through:
var FKEntityList = typeof(Entity).GetProperty(typeof(FKEntity).Name).GetValue(dbEntry);
GETS NO VALUE(NULL) at runtime but CAN loop through:
var FKEntityListWithCast = typeof(Entity).GetProperty(typeof(FKEntity).Name).GetValue(dbEntry) as List<FKEntity>;
Any help would be greatly appiciated!
A:
ICollection<FKEntity> FKEntityList = typeof(Entity).GetProperty(typeof(FKEntity).Name).GetValue(dbEntry) as ICollection<FKEntity>;
Still a bummer nobody could answer this
| {
"pile_set_name": "StackExchange"
} |
Q:
ArgumentNullException by IpcClientChannel - Parameter name: URI
When I try to run any method or read a parameter of an object, I'm get ArgumentNullException. This object has a single instance, from IpcServerChannel. How do I handle this?
Client
IDictionary prop = new Hashtable();
prop["name"] = "remote";
prop["portName"] = "connector";
prop["tokenImpersonationLevel"] = TokenImpersonationLevel.Impersonation;
prop["secure"] = true;
IpcClientChannel clientChannel = new IpcClientChannel(prop, null);
ChannelServices.RegisterChannel(clientChannel, true);
RemotingConfiguration.RegisterWellKnownClientType(typeof(Connector), "ipc://connector");
Connector c = new Connector();
c.Connect(); /* ArgumentNullException - Value cannot be null. Parameter name: URI */
Server
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
IDictionary prop = new Hashtable();
prop["name"] = "remote";
prop["portName"] = "connector";
prop["tokenImpersonationLevel"] = TokenImpersonationLevel.Impersonation;
prop["secure"] = true;
prop["authorizedGroup"] = new SecurityIdentifier("S-1-1-0").Translate(typeof(NTAccount)).ToString(); /* Everyone or Todos =p */
// Create and register an IPC channel
IpcServerChannel serverChannel = new IpcServerChannel(prop, serverProvider);
ChannelServices.RegisterChannel(serverChannel, true);
// Expose an object
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Connector), "connector", WellKnownObjectMode.Singleton);
Call Stack
Test.exe!Test.Program.Main() Line 39 C#
[External Code]
System.ArgumentNullException was unhandled
Message=Value cannot be null.
Parameter name: URI
Source=mscorlib
ParamName=URI
StackTrace:
Server stack trace:
at System.Runtime.Remoting.IdentityHolder.ResolveIdentity(String URI)
at System.Runtime.Remoting.Messaging.InternalSink.GetServerIdentity(IMessage reqMsg)
at System.Runtime.Remoting.Channels.ChannelServices.CheckDisconnectedOrCreateWellKnownObject(IMessage msg)
at System.Runtime.Remoting.Channels.ChannelServices.DispatchMessage(IServerChannelSinkStack sinkStack, IMessage msg, IMessage& replyMsg)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Vex_Connector_Service.Connector.Connect()
at Vex_Connector_Client.Program.Main() in C:\Users\Vex\Desktop\Final Vex Connector\Vex Connector\Vex Connector Client\Program.cs:line 39
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
A:
Duh! The problem is a bad URL, missing the URI.
RemotingConfiguration.RegisterWellKnownClientType(typeof(Connector), "ipc://connector/connector");
| {
"pile_set_name": "StackExchange"
} |
Q:
Git Diff Shows Reversed Colors/Indicators
I am looking at my git diff and the lines are exactly reversed. New lines show with "-"s and red colors, and the removed lines show with "+"s and green colors.
+ deleted line [green]
- newline [red]
Nothing in my .gitconfig seems to indicate anything amiss.
Anyone ever seen this happen before? What did you do to fix? Thanks!
A:
The direction of the diff is important:
git diff A B will provide different output than git diff B A and the difference will be in reversing what was deleted and what was added.
A:
In git diff A B, A is the one in red and B is the one in green (as Eugene said, the order matters)
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove parameter from url not working
I'm attempting to remove a url parameter status from the url but in the following alert, the parameter is still there.
var addressurl = location.href.replace(separator + "status=([^&]$|[^&]*)/i", "");
alert(addressurl);
location.href= addressurl;
How do i solve?
A:
You are confusing regex with strings.
It should be:
var addressurl = location.href.replace(separator, '').replace(/status=([^&]$|[^&]*)/i", "");
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ : automatic const?
When I compile this code:
class DecoratedString
{
private:
std::string m_String;
public:
// ... constructs, destructors, etc
std::string& ToString() const
{
return m_String;
}
}
I get the following error from g++: invalid initialization of reference of type 'std::string&" from expression of type 'const std::string'.
Why is m_String being treated as const? Shouldn't the compiler simply create a reference here?
EDIT:
Further, what should I do to get this function to act as a conversion to a string that will work in most cases? I made the function const, as it doesn't modify the internal string... maybe I just need to make it return a copy...
EDIT: Okay... making it return a copy worked.
A:
m_String is treated as const because it is accessed as
this->m_String
and this is const because the member function, ToString() is const-qualified.
A:
m_String is const at that point because you've chosen to declare the method as const (which of course makes all data instance members const, too) -- if you need to bypass that for that specific data member, you could choose to explicitly make it mutable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Haskell : multiple declarations of "" ...?
Hey guys so here is my code on which I get the weird error of "Multiple Declarations of mirror". I have other functions before that but none of them are named mirror... Any ideas?
mirror :: BinTree a -> BinTree a
mirror = undefined
mirror (Node tL x tR) = Node x mirror tR mirror tL
A:
Multiple definitions of a function must have the same number of arguments left of the equals sign. This is not required from a theory standpoint (note: one of the definitons could certainly be a lambda or return another function) but people seem to like it as such definitions typically indicate a bug.
Specifically, you have one definition with zero arguments:
mirror = undefined
And one definition with one argument:
mirror (Node tL x tR) = Node x mirror tR mirror tL
you probably want:
mirror _ = undefined
mirror (Node tL x tR) = Node x mirror tR mirror tL
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple Sockets/Reuse/Close Sockets in Python? _socketobject error
so I've been trying to make this bot in python that uses sockets to get some information to and from a chat on a website. This requires a login, which gets keys, then using the keys from the first connection, you can connect to the chat (different socket/ip)
I tried doing this with socket.close() and whatnot, but alas I keep getting errors :(
This is what i'm currently using:
def send_packet(socket, packet):
socket.send(packet+chr(0))
def socket_make(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
return s
socket = socket_make(get_ip('8'), get_port('8'))
send_packet(socket, '<y r="8" />')
socket.recv(1024)
send_packet(socket, '<v n="'+username+'" p="'+password+'" />')
tmp = socket.recv(1024)
socket.close()
socket = socket_make("174.36.242.40",10032)
send_packet(socket, '<y r="'+infos['c']+'" />')
token = socket.recv(1024)
token = token[token.find('i="')+3:token.find('" c="')]
It gives this Attribute error, presumably because .socket doesn't mean anything, but it normally does? I'm not quite sure
AttributeError: '_socketobject' object has no attribute 'socket'
A:
You had imported the socket module before. Then you create a global variable with the same name ("socket"), which now takes the place of the module. The module disappeared, and is now a socket object. Then when you try to call socket_make a second time, the global socket is no longer the module, but the socket instance.
Use a different name, or better yet encapsulate your whole client into another class.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between good quality chocolate and cheap chocolate?
There are many types of chocolate out there, some higher quality than others. What are the main differences between good quality chocolate and cheap chocolate? And in practical applications in baking and confections, what "benefits" do higher quality chocolate offer?
A:
The short answer is that good quality chocolate has a high proportion of cocoa constituents with little or no substitution.
What to look for:
High cocoa solids content. Chocolate with less than 50% cocoa solids will have little real chocolate taste and those with more than 70% will have a much more complex and fine chocolate taste.
Cocoa butter content. Chocolate makers tend to substitute vegetable oil in place of cocoa butter to reduce costs. Cocoa butter prices have increased in recent years due to demand in the cosmetics industry.
Smooth texture. This comes from the cocoa spending a longer period being crushed in the concher.
Conversely, these are indications of a poor quality chocolate:
Low proportion of cocoa solids
Use of vegetable oil instead of cocoa butter
Chocolates with low cocoa solids content, such as milk chocolate, are usually inappropriate for baking due to their proportionally low chocolate flavor. Baking cocoa powder itself is in fact just another word for cocoa solids, and this is why it is favored when baking: it is the pure chocolate flavor.
The milk constituents of milk chocolate may also go rancid, giving the chocolate a'bad olive oil' taste as described here.
In this image the cocoa solids go up from 0% in white chocolate to a maximum of 100% in the highest of quality chocolates.
As white chocolate contains no cocoa solids, look instead for cocoa butter and vanilla in place of vegetable oils and vanilla extract.
A:
I'd really suggest you read the wikipedia on chocolate processing as a starting point. http://en.wikipedia.org/wiki/Chocolate#Processing
There are many steps involved, and each one is important.
A summary of things that can go wrong:
Under-ripe beans
Improper fermentation. (many factors can contribute to this)
over/under roasting
Improper cleaning (foreign particles)
Poor conching (smoothing and grinding of particles)
Poor tempering (crystal structure)
5 and 6 go more to texture. You may find mass market Easter chocolate has a grainy texture -- That's poor conching.
Then the recipe has to be taken into account as well. Cocoa butter has value outside of chocolate making, and it may be replaced with cheaper oils (Hydrogenated coconut or palm oils for example.)
The cocoa solids themselves may be adulterated with cheaper ingredients to stretch the yield. And the mass producer's favorite weapon is more sugar. If you make it sweet enough, a lot of people won't notice the low quality product.
I'd recommend that you go out and buy a Lindt 70% cocoa bar and give it a taste. While not necessarily the best chocolate out there, it is readily available, and of a decent quality.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android - TextView not changing text
I'm currently learning some android for a school project and I can't figure out the way to set text dynamically to a TextView.
Here is the full activity:
package com.avilyne.android.gcmclient;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.content.DialogInterface;
public class EnviarMensaje extends Activity {
ListView l;
EditText t;
TextView err;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enviar_mensaje);
l = (ListView)findViewById(R.id.listaVista);
t = (EditText)findViewById(R.id.editText1);
err = (TextView)findViewById(R.id.textoss);
err.setText("Escriba su mensaje y luego seleccione el canal.");
l.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String m= t.getText().toString();
if(m.equals("")){
err.setText("Escriba su mensaje y luego seleccione el canal.");
return;
}
else{
showAlert();
(new Funciones()).EnviarMensaje(l.getItemAtPosition(arg2).toString(), m);
//mostrar mensaje Su mensaje ha sido enviado
Intent activityChangeIntent = new Intent(EnviarMensaje.this, FirstActivity.class);
EnviarMensaje.this.startActivity(activityChangeIntent);
}
}
});
ListView lv;
setContentView(R.layout.activity_enviar_mensaje);
lv = (ListView)findViewById(R.id.listaVista);
ArrayList<String> your_array_list = (new Funciones()).listarCanales();
// This is the array adapter, it takes the context of the activity as a first // parameter, the type of list view as a second parameter and your array as a third parameter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, your_array_list);
lv.setAdapter(arrayAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.enviar_mensaje, menu);
return true;
}
private void showAlert(){
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Confirmación.");
alertDialog.setMessage("Su mensaje ha sido enviado correctamente.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Add your code for the button here.
}
});
// Set the Icon for the Dialog
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
}
}
Below is my activity_enviar_mensaje:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".EnviarMensaje" >
<TextView
android:id="@+id/instrucciones"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Escriba el mensaje y luego clickee el canal a ser enviado"
android:textSize="20sp" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/instrucciones"
android:layout_alignRight="@+id/instrucciones"
android:layout_below="@+id/instrucciones"
android:ems="10"
android:inputType="text" />
<TextView
android:id="@+id/textoss"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/listaVista"
android:layout_alignParentBottom="true"
android:text="TextView" />
<ListView
android:id="@+id/listaVista"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textoss"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText1" >
</ListView>
</RelativeLayout>
Any help will be much appreciated... Thank you for the time, José.
A:
ListView lv;
setContentView(R.layout.activity_enviar_mensaje);
lv = (ListView)findViewById(R.id.listaVista);
You have set the content to activity TWICE , That is why your text is not changing because activity is again setting the original layout. Remove the above three lines from the bottom and it will work just fine.
Also after removing the above three lines set the adapter as l.setAdapter(arrayAdapter);
Below is your updated onCreate() Method
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = (ListView)findViewById(R.id.listaVista);
t = (EditText)findViewById(R.id.editText1);
err = (TextView)findViewById(R.id.textoss);
err.setText("Escriba su mensaje y luego seleccione el canal.");
l.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String m= t.getText().toString();
if(m.equals("")){
err.setText("Escriba su mensaje y luego seleccione el canal.");
return;
}
else{
showAlert();
(new Funciones()).EnviarMensaje(l.getItemAtPosition(arg2).toString(), m);
//mostrar mensaje Su mensaje ha sido enviado
Intent activityChangeIntent = new Intent(EnviarMensaje.this, FirstActivity.class);
EnviarMensaje.this.startActivity(activityChangeIntent);
}
}
});
ArrayList<String> your_array_list = (new Funciones()).listarCanales();
// This is the array adapter, it takes the context of the activity as a first // parameter, the type of list view as a second parameter and your array as a third parameter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, your_array_list);
l.setAdapter(arrayAdapter);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Nested comments in Xcode
When I write a method that is a bit complicated I prefer to add a little comment block above it as
/*--------------------------------------------------------------+
| When I wrote this, only God and I understood what I was doing
| Now, God only knows
+-------------------------------------------------------------*/
- (void) overlyDifficultMethodToGrasp { ... }
Is it really so that the only way to comment out this method from my code would be to hit cmd + /? Which would result in
///*--------------------------------------------------------------+
// | When I wrote this, only God and I understood what I was doing
// | Now, God only knows
// +-------------------------------------------------------------*/
//- (void) overlyDifficultMethodToGrasp { ... }
//
What I would like to do is
/*
/*--------------------------------------------------------------+
| When I wrote this, only God and I understood what I was doing
| Now, God only knows
+-------------------------------------------------------------*/
- (void) overlyDifficultMethodToGrasp { ... }
*/
Which, as you can see, doesn't work...
Why? Well I think large chunks of // are ugly!
A:
This has not much to do with Xcode, but with the language (and compiler) you're using. You can't have nested comment blocks like that in C or Objective-C.
A:
As DrummerB pointed out, you can't nest comments.
Use // for the fancy comments instead of /*
here:
/*
//--------------------------------------------------------------+
// When I wrote this, only God and I understood what I was doing
// Now, God only knows
//+-------------------------------------------------------------+
- (void) overlyDifficultMethodToGrasp { ... }
*/
| {
"pile_set_name": "StackExchange"
} |
Q:
Updating text in component drawn in drawRect in UIView subclass
I have a UIView with it's subclass set in interface builder to a UIView subclass I created. I want to update labels within the UIView class holding them. I cannot seem to update the text of any labels drawn in drawRect. What are my options for drawing elements I need to change within a UIView subclass?
// Using UILabel subclass (FontLabel)
- (void)drawRect:(CGRect)rect {
scoreLabel = [[FontLabel alloc] initWithFrame:CGRectMake(0,0, 400, 50) fontName:@"Intellect" pointSize:80.0f];
scoreLabel.textColor = [[UIColor alloc] initWithRed:0.8157 green:0.8000 blue:0.0706 alpha:1.0f];
[scoreLabel sizeToFit];
[scoreLabel setText:@"Initial text"];
[self addSubview:scoreLabel];
[self setNeedsDisplay];
//Also tried [self setNeedsLayout];
}
- (void)updateScoreLabel:(int)val
{
[scoreLabel setText:[NSString stringWithFormat:@"%d", val]];
}
// Using CATextLayer
- (void)drawRect:(CGRect)rect {
scoreLabel = [CATextLayer layer];
[scoreLabel setForegroundColor:[UIColor whiteColor].CGColor];
[scoreLabel setFrame:CGRectMake(0,0, 200, 20)];
[scoreLabel setAlignmentMode:kCAAlignmentCenter];
[[self layer] addSublayer:scoreLabel];
[scoreLabel setString:@"Initial text"];
[self setNeedsDisplay];
//Also tried [self setNeedsLayout];
}
- (void)updateScoreLabel:(int)val
{
[scoreLabel setString:[NSString stringWithFormat:@"%d", val]];
}
A:
In order to change the text of labels programmatically, you need to do the following:
In your .h file:
Define them as UILabels in your @interface section
Add IBOutlets to them in your @property declarations
In your .m file:
Put in @synthesize lines for them in your .m file.
After that, you can refer to them as any other self. variable, and set their text property to change how they appear in your display.
In general, trying to subclass UIView can be a bit tricky (as you're finding), but hopefully the above will help you at least a bit.
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieving firebase topics data for app instance - 401 error
I'm trying to retrieve a list of subscribed FCM topics for an app instance.
The documentation states that I should make a GET request at https://iid.googleapis.com/iid/info/<IID_TOKEN>?details=true, passing in Authorization:key=<WEB_API_KEY> as a header.
Here's how the request looks inside my client:
const getTopics = (token) => {
fetch('https://iid.googleapis.com/iid/info/${token}?details=true', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'key=AIzaSy...dQ80g'
}
})
.then(res => console.log(res))
.catch(err => console.log(err))
}
const messaging = firebase.messaging()
messaging
.requestPermission()
.then(() => messaging.getToken())
.then(getTopics)
.catch(err => console.log(err))
And this is the response I'm getting:
Any ideas what I'm doing wrong here? Clearly one of my tokens is invalid, but according the documentation this should be correct.
A:
In case anyone finds this question and needs an answer, I found the issue: the documentation is wrong, the Authorization header requires the cloud messaging project SERVER KEY. This is NOT the same as the general API key.
Here's where you can find the correct key as of Oct 2019:
Google, please keep your documentation up to date, I wasted hours trying to figure this out!
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove that the eigenvectors are independent.
Given two vectors $\boldsymbol\alpha=\left(\alpha_1,...,\alpha_N\right)^{T}$ and $\boldsymbol\beta=\left(\beta_1,...,\beta_N\right)^{T}$, let $M$ be the $N\times N$ matrix whose entries are expressed as
$$
M_{k,q}=\frac{\alpha_q}{\beta_k},\quad k=1,...,N,\quad q=1,...,N\quad ?
$$
It's easy to see that $\boldsymbol\beta=\left(1/\beta_1,...,1/\beta_N\right)^{T}$ is eigenvector relative to the eigenvalue $\sum_{p=1}^{N}M_{p,p}$. Moreover it is easy to see that the $N$ vectors
$$
\mathbf{v}^{(p)} = \left(\begin{array}{c}
\frac{\alpha_p}{(N-1)\,\alpha_1}\\
\vdots\\
\frac{\alpha_p}{(N-1)\,\alpha_{p-1}}\\
-1\\
\frac{\alpha_p}{(N-1)\,\alpha_{p+1}}\\
\vdots\\
\frac{\alpha_p}{(N-1)\,\alpha_N}
\end{array}\right)\begin{array}{c}
\\
\\
\\
\leftarrow p\textrm{-th entry}\\
\\
\\
\\
\end{array},\quad p=1,...,N
$$
are all eigenvectors with eigenvalue zero. My guess is that only $N-1$ of them are independent, how can I prove it?
A:
If your $N\times N$ matrix is not entirely zero (which is the case here unless all $\alpha_i$ are zero) then it cannot have $N$ independent eigenvectors with eigenvalue$~0$. The kernel (eigenspace for $\lambda=0$) is of dimension at most $N-1$, and here in fact of dimension $N-1$ exactly (assuming $M\neq0$) since by the way it is constructed $M$ has rank$~1$. Note that this is even true if the trace of $M$ (the "other" eigenvalue $\sum_pM_{p,p}$) happens to be$~0$ too (if all its eigenvalues are zero then $M$ is nilpotent, but not necessarily zero).
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Jquery Cycle2 can I define a different slide effect for mobile?
I have a very nice responsive slideshow going, using the very nice jQuery Cycle2 plugin.
http://jquery.malsup.com/cycle2/
Now, in case of desktop use, I would like to use a subtle fade effect. I do this by setting these attributes on the container div:
<div class="cycle-slideshow" data-cycle-slides=".slide" data-cycle-swipe="true" data-cycle-pause-on-hover="true" data-cycle-auto-height="container" data-cycle-fx="fade">
But then on mobile devices, since my slider is swipe-enabled, I would like to use scrollHorz (horizontally scrolling), since this makes much better sense when swiping.
Is this possible? Here's the link to the API reference:
http://jquery.malsup.com/cycle2/api/
Thanks in advance.
A:
Since the HTML tag data-cycle-fx should be set before initializing jQuery Cycle, and I am using PHP, I looked into determining the user device server side.
I've found $_SERVER['HTTP_USER_AGENT'] to be fairly reliable (I've heard it's not 100% foolproof, but in my case that's not a problem).
I created a function, from the example here:
Using Modernizr to test for tablet and mobile - Opinions wanted (hopefully, this is not too resource intensive).
function is_mobile() {
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$_SERVER['HTTP_USER_AGENT'])||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($_SERVER['HTTP_USER_AGENT'],0,4))){
return 1;
} else {
return 0;
}
}
Then, in my slider HTML, I do the following construction:
echo '<div class="cycle-slideshow" data-cycle-slides=".slide" data-cycle-fx="'.( is_mobile() ? 'scrollHorz' : 'fade' ).'">';
It seems to work for me. I am interested to see other examples or better practices.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get the sum of 2 array with the same id in a collection
i have an array of collections with some same occurrences like below :
array:6 [▼
0 => Collection {#926 ▶}
1 => Collection {#926 ▶}
2 => Collection {#1045 ▶}
3 => Collection {#1045 ▶}
4 => Collection {#1156 ▶}
5 => Collection {#1156 ▶}
]
now what i want to do is to is to get the sum of those who repeated like 926 so i would have 2 prices to sum because 926 occurred 2 times . how can i achieve that thanks !
A:
Use this approach:
// sum same keys in an array
$sum = array_sum(array_column($yourarray, 'your key/index'));
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any systematic way for transforming differential equation into Clairaut form?
I have a few differential equations with their substitution to form Clairaut form, but is there any standard method to get the intuition of the substitution?
examples:
$y = 2xp + y^2 p^3$, for transforming , put $y^2 = Y$
$y + px = x^4 p^2$, for transforming , put $1/x = X$
$y = 3px + 6 y^2 p^2$, for transforming , put $y^3 = Y$
and few other transformation cases.
Note : $p = \frac{dy}{dx}$
I understand that reducing to Clairaut's form involves suitable substitution so as to bring it in the form of $Y = P X + f(P)$ but i am unable to form any intuition about what such substitutions might be , as the above equations seem complicated with more than one combination of variables and $p$.
Help appreciated.
A:
There is a structure that all equations that are equivalent to a Clairaut form have to satisfy. Taking the derivative of the equation modulo the original equation has to factor into one term containing the second derivative and one without it.
Take the second equation, $y+xy'=x^4y'^2$. Its derivative is
$$
2y'+xy''=4x^3y'^2+2x^4y'y''\iff (xy''+2y')(1-2x^3y')=0
$$
so that we get a direct factorization. The first term gives the family $y'=-Cx^{-2}$, $y=Cx^{-1}+D$ which tells us that the transformation $X=x^{-1}$ produces the solution family as family of lines.
In the third equation $y = 3xy' + 6 y^2 y'^2$ the derivative is
$$
y'=3y'+3xy''+12yy'^3+12y^2y'y''\iff0=3y''(x+4y^2y')+2y'(1+6yy'^2)
$$
Now the original equation can be rearranged as $y(1+6yy'^2)=3y'(x+4y^2y')$ so that the derivative gets the factorized form
$$
0=3(y''y+2y'^2)(x+4y^2y').
$$
The first factor implies $y'y^2=C$ so that $y^3=3Cx+D$ and thus one obtains a linear family with $Y=y^3$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android option menu: change size of icon
I am using option menu, i want to increase the size of my icon...
means icon are too small... how can increase their width or height ....
or how remove space around icon.. i.e padding, margin etc...
i want a menu with icon at bottom...
what i should do???
<activity
android:name="com.example.parentengagementtracking.BaseActivity"
android:label="@string/title_activity_base"
android:theme="@style/MenuTheme" >
<!-- android:theme="@style/Theme.FixedSize"> -->
</activity>
<style name="MenuTheme" parent="android:Theme">
<item name="android:panelFullBackground">@drawable/back11</item>
<item name="android:padding">1dip</item>
<item name="android:drawablePadding">1dip</item>
</style>
public class BaseActivity extends Activity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_parent_home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
Bundle objBundle;
Intent objIntent;
switch (item.getItemId())
{
case R.id.menu_about_us:
objIntent=null;
objIntent = new Intent(BaseActivity.this,InfoActivity.class);
objBundle=new Bundle();
objBundle.putString("source","BaseActivity");
objIntent.putExtras(objBundle);
finish();
startActivity(objIntent);
return true;
case R.id.menu_profile:
objIntent=null;
objIntent = new Intent(BaseActivity.this,UserProfile.class);
finish();
startActivity(objIntent);
return true;
case R.id.menu_activity:
objIntent=null;
objIntent = new Intent(BaseActivity.this,ViewActivity.class);
finish();
startActivity(objIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
<!-- android:icon="@drawable/homen" -->
<item
android:id="@+id/menu_profile"
android:orderInCategory="2"
android:showAsAction="always"
android:icon="@drawable/profile1"
android:title="Profile"/>
<item
android:id="@+id/menu_activity"
android:orderInCategory="3"
android:showAsAction="always"
android:icon="@drawable/reports"
android:title="Reports"/>
<item
android:id="@+id/menu_about_us"
android:icon="@drawable/aboutusn"
android:orderInCategory="4"
android:showAsAction="always"
android:title="Aboutus"/>
how can i set padding, margin, width and height etc of icon..??
A:
You can solve this problem by using "app:actionLayout".
<item
android:id="@+id/menu1"
app:actionLayout="@layout/custom_action_bar" //this line will change icon
android:visible="true"
android:title="Menu 1"
app:showAsAction="always" />
Refer this docs Custom menu icons to add listeners to custom menu.
A:
Your image should be 24*24 or 36*36.
| {
"pile_set_name": "StackExchange"
} |
Q:
Hirb doesn't work at all in rails console
I followed the tutorial on hirb rdoc but unfortunately, my rails console is not working at all.
I've already done sudo gem install hirb
and added hirb to my Gemfile:
gem 'hirb', '~>0.7.0'
Then I launched bundle install
And I get this result :
rails c
Loading development environment (Rails 3.2.11)
> require 'hirb'
=> false
> Hirb.enable
=> true
> Municipality.all
Municipality Load (0.8ms) SELECT "municipalities".* FROM "municipalities" ORDER BY name asc
=> [#<Municipality id: 1, district_id: 6, name: "Ambalamanasy II", created_at: "2013-01-16 12:11:45", updated_at: "2013-01-16 12:11:45">,
...
# doesn't work
Could anyone help?
A:
If your using pry as your rails console... add this in your .pryrc file
require 'hirb'
Hirb.enable
old_print = Pry.config.print
Pry.config.print = proc do |output, value|
Hirb::View.view_or_page_output(value) || old_print.call(output, value)
end
| {
"pile_set_name": "StackExchange"
} |
Q:
How to optimize UPDATE statement?
I have a table with almost 1 million records and another table with a few hundred records. I would like to update the large table with values from the small table with the following
UPDATE tableA ta, tableB tb
SET price=tb.price
WHERE ta.id=tb.id
Using the above SQL statement, the query is taking a really long time (more than 1 hour). Is there a method that I can use to make this operation faster?
Here is the schema for both tables.
Table A
id name descrip region price
0 a abc def 1.7
1 b abc def 2.2
3 c abc def 3.4
4 d abc def 5.3
.... . ... ... ...
999999 e abc def 4.5
1000000 f abc def 7.9
Table B
id price
0 0.7
1 2.5
3 1.9
4 7.9
Result
Table A
Table A
id name descrip region price
0 a abc def 0.7
1 b abc def 2.5
3 c abc def 1.9
4 d abc def 7.9
.... . ... ... ...
999999 e abc def 4.5
1000000 f abc def 7.9
A:
If your tableB has index, that covers id (obviously it is) - then you have no other ways to speed it up. Since the slowest thing here is physical changing of the value.
Probably you can change your where to:
WHERE ta.id=tb.id and ta.price <> tb.price
to avoid of updating the price to the same value
| {
"pile_set_name": "StackExchange"
} |
Q:
Sound recording program using Nano
I want to make a sound recording program such as this on my RPI machine with several modifications. The problem is that I get the fatal error message "alsa/asoundlib.h : No such file or directory". I have Debian on my RPI
/*
This example reads from the default PCM device
and writes to standard output for 5 seconds of data.
*/
/* Use the newer ALSA API */
#define ALSA_PCM_NEW_HW_PARAMS_API
#include <alsa/asoundlib.h>
int main() {
long loops;
int rc;
int size;
snd_pcm_t *handle;
snd_pcm_hw_params_t *params;
unsigned int val;
int dir;
snd_pcm_uframes_t frames;
char *buffer;
/* Open PCM device for recording (capture). */
rc = snd_pcm_open(&handle, "default",
SND_PCM_STREAM_CAPTURE, 0);
if (rc < 0) {
fprintf(stderr,
"unable to open pcm device: %s\n",
snd_strerror(rc));
exit(1);
}
/* Allocate a hardware parameters object. */
snd_pcm_hw_params_alloca(¶ms);
/* Fill it in with default values. */
snd_pcm_hw_params_any(handle, params);
/* Set the desired hardware parameters. */
/* Interleaved mode */
snd_pcm_hw_params_set_access(handle, params,
SND_PCM_ACCESS_RW_INTERLEAVED);
/* Signed 16-bit little-endian format */
snd_pcm_hw_params_set_format(handle, params,
SND_PCM_FORMAT_S16_LE);
/* Two channels (stereo) */
snd_pcm_hw_params_set_channels(handle, params, 2);
/* 44100 bits/second sampling rate (CD quality) */
val = 44100;
snd_pcm_hw_params_set_rate_near(handle, params,
&val, &dir);
/* Set period size to 32 frames. */
frames = 32;
snd_pcm_hw_params_set_period_size_near(handle,
params, &frames, &dir);
/* Write the parameters to the driver */
rc = snd_pcm_hw_params(handle, params);
if (rc < 0) {
fprintf(stderr,
"unable to set hw parameters: %s\n",
snd_strerror(rc));
exit(1);
}
/* Use a buffer large enough to hold one period */
snd_pcm_hw_params_get_period_size(params,
&frames, &dir);
size = frames * 4; /* 2 bytes/sample, 2 channels */
buffer = (char *) malloc(size);
/* We want to loop for 5 seconds */
snd_pcm_hw_params_get_period_time(params,
&val, &dir);
loops = 5000000 / val;
while (loops > 0) {
loops--;
rc = snd_pcm_readi(handle, buffer, frames);
if (rc == -EPIPE) {
/* EPIPE means overrun */
fprintf(stderr, "overrun occurred\n");
snd_pcm_prepare(handle);
} else if (rc < 0) {
fprintf(stderr,
"error from read: %s\n",
snd_strerror(rc));
} else if (rc != (int)frames) {
fprintf(stderr, "short read, read %d frames\n", rc);
}
rc = write(1, buffer, size);
if (rc != size)
fprintf(stderr,
"short write: wrote %d bytes\n", rc);
}
snd_pcm_drain(handle);
snd_pcm_close(handle);
free(buffer);
return 0;
}
A:
You can easily solve it by installing libasound2-dev. to do so just use the following code:
apt-get install libasound2-dev
Now you should be able to use alsa/asoundlib.h.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create a data structure with object at index 0 of an array
I want to add an object to an array at specific index: this is my existing structure:
let a = {
"tt" : ["test"],
"tt4": [
"the test44",
"the test55"
]
}
and this is what I want to achieve:
let a = {
"tt" : ["test"],
"tt4": [ {key: "the test44", gptest: "e732iry"}, "the test55" ]
}
However its giving me an "Unexpected identifier" at the "the test44"? Ho can I create an object with the above structure?
A:
Assuming your desired output is an array as follow:
[ {key: "the test44", gptest: "e732iry"}, "the test55" ]
You can use the function map.
This approach will find a specific target, even if this is repeated multiple times within the current array.
let a = {"tt": ["test"],"tt4": ["the test44","the test55"]},
target = "the test44";
a.tt4 = a.tt4.map((t) => t === target ? {[t]: t, gptest: "e732iry"} : t);
console.log(a);
.as-console-wrapper { max-height: 100% !important; top: 0; }
| {
"pile_set_name": "StackExchange"
} |
Q:
How to interpret a t-sql deadlock trace
I'm trying to sort out a deadlock by looking at the t-sql trace but I'm struggling to understand the information. I have a summary of the info here and then the full deadlock trace at the end of the post:
The first lock is on a table called dbo.RetailVoucher
The second lock is on a table called ooc.PlannedUniversalVoucher
The 1st stored procedure reads the following tables:
dbo.RetailVoucher, ooc.PlannedOrderItem and ooc.PlannedOrder.
The 2nd stored procedure reads the following tables:
ooc.PlannedBatch & ooc.PlannedUniversalVoucher
Now, for the procedures to be waiting for each other, I thought they would both have to be reading the same table at some point. I obviously don't understand how to interpret the trace. Do I need to hunt down the source of the locks on dbo.RetailerVoucher and ooc.PlannedUniversalVoucher in other procedures?
Thanks.
Here's the full trace:
<deadlock-list>
<deadlock victim="process894748">
<process-list>
<process id="process894748" taskpriority="0" logused="3064" waitresource="KEY: 8:72057594084655104 (845afc30a382)" waittime="944" ownerId="12987790066" transactionname="user_transaction" lasttranstarted="2014-04-10T19:07:02.250" XDES="0x803d53c0" lockMode="S" schedulerid="3" kpid="14356" status="suspended" spid="67" sbid="0" ecid="0" priority="0" trancount="3" lastbatchstarted="2014-04-10T19:07:02.287" lastbatchcompleted="2014-04-10T19:07:02.287" clientapp=".Net SqlClient Data Provider" hostname="ID13115" hostpid="4872" loginname="UVUser" isolationlevel="read committed (2)" xactid="12987790066" currentdb="8" lockTimeout="4294967295" clientoption1="673185824" clientoption2="128056">
<executionStack>
<frame procname="UVSystem.ooc.PlannedPacketPreserveEVouchers" line="144" stmtstart="12286" stmtend="13618" sqlhandle="0x0300080039a18c7fa2ed9800dda200000100000000000000">
update dbo.RetailVoucher
set QuantityInStock -= rvsum.QuantitySum
from dbo.RetailVoucher urv
join (
select oib.id, SUM(oib.Quantity) as QuantitySum
from (
select coalesce(rv.RelatedVoucherId, rv.Id) id, oi.Quantity
from
ooc.PlannedOrderItem oi
join ooc.PlannedOrder po on oi.PlannedOrderId = po.Id
join RetailVoucher rv on oi.RetailVoucherId = rv.Id
where po.PlannedPacketId = @PlannedPacketId
and oi.PartnerId is null
and oi.OnDmenadServiceId is null
and rv.VoucherTypeId = 1
) oib
group by oib.Id
) rvsum
on urv.Id = rvsum.id;
</frame>
</executionStack>
<inputbuf>
Proc [Database Id = 8 Object Id = 2139922745] </inputbuf>
</process>
<process id="processd0db8088" taskpriority="0" logused="10716" waitresource="PAGE: 8:1:778990" waittime="1078" ownerId="12987783115" transactionname="user_transaction" lasttranstarted="2014-04-10T19:07:01.473" XDES="0x144975950" lockMode="S" schedulerid="7" kpid="11172" status="suspended" spid="61" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2014-04-10T19:07:01.473" lastbatchcompleted="2014-04-10T19:07:01.473" clientapp=".Net SqlClient Data Provider" hostname="ID13115" hostpid="12168" loginname="UVUser" isolationlevel="read committed (2)" xactid="12987783115" currentdb="8" lockTimeout="4294967295" clientoption1="673185824" clientoption2="128056">
<executionStack>
<frame procname="UVSystem.ooc.OfflineOrdersImportPacket" line="294" stmtstart="23548" stmtend="24026" sqlhandle="0x030008006d6796551b829700dda200000100000000000000">
update ooc.PlannedBatch
set
IsCompleted = @True
from ooc.PlannedBatch pb
join ooc.PlannedUniversalVoucher puv on puv.PlannedBatchId = pb.Id
left outer join @DuplicatedVouchers dv on dv.Id = puv.Id
where dv.Id is null; </frame>
</executionStack>
<inputbuf>
Proc [Database Id = 8 Object Id = 1435920237] </inputbuf>
</process>
</process-list>
<resource-list>
<keylock hobtid="72057594084655104" dbid="8" objectname="UVSystem.dbo.RetailVoucher" indexname="PK_RetailVoucher" id="lock10ccbd180" mode="X" associatedObjectId="72057594084655104">
<owner-list>
<owner id="processd0db8088" mode="X"/>
</owner-list>
<waiter-list>
<waiter id="process894748" mode="S" requestType="wait"/>
</waiter-list>
</keylock>
<pagelock fileid="1" pageid="778990" dbid="8" objectname="UVSystem.ooc.PlannedUniversalVoucher" id="lock15ba81480" mode="IX" associatedObjectId="72057594113425408">
<owner-list>
<owner id="process894748" mode="IX"/>
</owner-list>
<waiter-list>
<waiter id="processd0db8088" mode="S" requestType="wait"/>
</waiter-list>
</pagelock>
</resource-list>
</deadlock>
</deadlock-list>
A:
Let me try.
You have tho processes, processd0db8088 and process894748. From the execution stack you can see that the process894748 was executing PlannedPacketPreserveEVouchers, and processd0db8088 is executing OfflineOrdersImportPacket. You can see the queries in question for both processes there as well.
From resource list you can find out the resorces on which these two processes were deadlocked. First one is a particular index row in PK_RetailVoucher index on RetailVoucher table: processd0db8088 locked it exclusively and the process process894748 is waiting to gain shared lock on it. The other resource is a data page 778990 which belongs to PlannedUniversalVoucher table, held by process process894748 while processd0db8088 is waiting to gain read access to it.
The locks could have been taken anywhere from start of transaction. The queries shown here in the execution stack are the queries that were waiting on the resources, not the ones that taken the locks. Inspect the whole execution trace to find out where the locks were actually taken.
The standard advices apply: shorten transactions, access the tables in order, index appropriatelly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Two dimensional array bug (can't find it)
I am doing this homework project that produces the pascals triangle but I'm getting an error and I can't find it. I looked it over many times but to me it seems okay, Can someone help me find the bug?
public class PascalsTriangle {
public static void main(String[] args) {
int[][] triangle = new int[11][];
fillIn(triangle);
print(triangle);
}
public static void fillIn(int[][] triangle) {
for (int i = 0; i < triangle.size(); i++) {
triangle[i] = new int[i++];
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
}
}
public static void print(int[][] triangle) {
for (int i = 0; i < triangle.length; i++) {
for (int j = 0; j < triangle[i].length; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
A:
I assume you have already changed your code to use length instead of size as the other answer mentions.
When you call this method:
public static void fillIn(int[][] triangle) {
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i++]; // this line
triangle[i][0] = 1;
The line pointed out above should be:
triangle[i] = new int[i + 1];
When you call i++ the int array will be initialized with length i and then i will be incremented. You are already incrementing i in the declaration of your for loop. So, we take away the ++.
But then we have another problem. You start the loop at i = 0. Then you initialize an array with length 0. Then you add an element to that array. Something doesn't make sense. What you meant to do was to initialize the array as int[i + 1].
Finally the program displays some lines from Pascal's Triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP and AJAX: How can I display json_encode data in PHP while loop?
I am very new to using AJAX and passing data with json_encode. I have this "aht" button when clicked it will send an AJAX request to my show_aht.php script, which will run a query. I want to save the results and display it to my map.php.
Problem:
In my map.php I have a while loop that outputs square(desk) DIVs with another DIV(station) when clicked that displays content inside of it. Here is the fiddle so you may understand. I want the results of show_aht.php "TIME" to be displayed in the DIVs being produced by my WHILE LOOP in map.php.
How is it possible to do this? I know that AJAX and PHP cannot interact with eachother and thats why I need help. If this can't be done, how else can I display the TIME from show_aht.php to their corresponding usernames on each DIV being output? I have around 200 of them being displayed.
Thanks in advance.
map.php (only showing the last line of the while loop, outputs all DIVs)
//desk DIV
while(somequery){
....
echo '<div class="' . $class . '" data-rel="' . $id . '" style="left:' . $x_pos . 'px;top:' . $y_pos.'px;">' . $sta_num . '</div>' . "\n";
}//end while
//station DIV
while(some query){
.....
echo '<div class="station_info_" id="station_info_' . $id . '" style="left:' . $x_pos . 'px;top:' .$y_pos . 'px;"><p class="numb">User:' . $user .'<br>Station:' . $hostname . '<br>Pod:' . $sta_num . '<br>Section:' . $sec_name . '<br>State:' . $state .'<br></p></div>' . "\n";
}//end while
map.php (AJAX part)
<div id="aht"><!--aht button-->
<button id="aht_button">AHT</button>
</div><!--aht button-->
<script type="text/javascript">
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: , // pass data here
dataType: 'json',
success : function(data){
}//end success
});//end ajax
});//end click
});//end rdy
</script>
show_aht.php (showing the loop and part I where I want the data to be returned)
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
echo " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
echo "User: " . $m . " Time: N/A <br>";
}
}
}
A:
Don't output anything except one valid json string. In your case you do that by replacing the echo's with building an array (or object...) and output that at the very end:
For example:
$data = array();
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
$data[] = " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
$data[] = "User: " . $m . " Time: N/A <br>";
}
}
}
// Output your json string
echo json_encode($data);
Note that I have simply replaced your echos with an assignment but you could also add arrays in your array to return just the data parts and process that afterwards in javascript.
For example (this would depend a bit on your exact data structure...):
...
$data[] = array($m, $v['avg_handle_time']);
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Wrapping a function call into a closure when using goroutines
Wrapping a function call into a closure leads to an unexpected behaviour when using goroutines.
Consider the following example:
package main
import (
"log"
"sync"
"time"
)
var workerNum = 5
var wg sync.WaitGroup
func block() {
dur := 300 * time.Millisecond
//time.Sleep()
select {
case <- time.After(dur): {}
}
}
func startWorker(worker int) {
for i:=0; i < 3; i++{
log.Printf("Worker %d woke up! \n", worker)
block()
}
wg.Done()
}
func main() {
for i:=0; i < workerNum; i++ {
//go func() { startWorker(i) }()
go startWorker(i)
}
wg.Add(workerNum)
wg.Wait()
}
Test it here: http://play.golang.org/p/nMlnTkbwVf
One can see that wrapping startWorker(i) into func() { startWorker(i) }() results in calling only the 5-th worker.
It looks like there is something wrong in the way how closures capture variables from the outer scope. Why is this happening? Do closures use pass-by-reference way for passing outer variables instead of pass-by-value?
A:
That's how closures in all languages work, if you want to do it that way, you have to isolate the variable.
go func(i int) { startWorker(i) }(i)
| {
"pile_set_name": "StackExchange"
} |
Q:
loop through two muti-dimensional array at same time using foreach loop
i am trying to loop through two multi-dimensional array with a foreach loop
[array1] => Array (
[0] => Array ( 1,2,3 )
[1] => Array ( 4,5,6 )
[2] => Array ( 7,8,9 )
)
[array2] => Array (
[0] => Array ( 1,2,3 )
[1] => Array ( 4,5,6 )
[2] => Array ( 7,8,9 ) )
)
both has same keys,
i want to access 1st array of both arrays at same time,
i want to do something like this
foreach($array1 as $key1=>$value1 && $array2 as $key2=>$value2)
echo $value1[1]." ".$value2[2]
its not correct, but that's what i want to do !!
A:
If the keys are identical between the two arrays in both dimensions :
foreach (array_keys($array1) as $key1) {
foreach (array_keys($array1[$key1]) as $key2) {
echo $array1[$key1][$key2].' '.$array2[$key1][$key2];
}
}
Worst case scenario, some keys in one dimension or the other are missing in one or both arrays and you have to merge them prior to reading (and ensure the existence of the key's value in each loop & array).
UPDATE: used the same solution twice for two-dimensional array structure.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does CVXPY have a way to constrain a variable to be even?
I am trying to write a search for clock frequencies and divisors to generate a target frequency.
However one constraint is the divisors need to be even (due to hardware limitations) and I can't find a way to model this.
There is no modulo operator support I get
"TypeError: unsupported operand type(s) for %: 'Variable' and 'int'"
and the following hack attempt using divide and multiply didn't work:
wantipp = cp.Parameter(name = 'wantedipp') # Desired IPP
div = cp.Variable(integer = True, name = 'div') # Divisor must be integral
ipp = cp.Variable(pos = True, name = 'ipp') # nsec
constraints = [
ipp == 1e9 / 6e6 * div, # Constrain IPP to divisor
div >= 2, div <= 65536, # Divisor must be 2-65536
div / 2 * 2 == div, # Divisor must be even (doesn't actually work)
]
objective = cp.Minimize(cp.abs(ipp - wantipp)) # Find closest possible IPP
prob = cp.Problem(objective, constraints);
for i in (1e3, 2e3, 1e6, 2e6, 123123, 5412341, 1233, 12541):
wantipp.value = i
prob.solve()
print('IPP %.3f nsec (%.3f Hz) -> Divisor %d %.3f nsec (%.3f Hz)' % (
i, 1e9 / i, div.value, ipp.value, 1e9 / ipp.value
))
IPP 1000.000 nsec (1000000.000 Hz) -> Divisor 6 1000.000 nsec (1000000.000 Hz)
IPP 2000.000 nsec (500000.000 Hz) -> Divisor 12 2000.000 nsec (500000.000 Hz)
IPP 1000000.000 nsec (1000.000 Hz) -> Divisor 6000 1000000.000 nsec (1000.000 Hz)
IPP 2000000.000 nsec (500.000 Hz) -> Divisor 12000 2000000.000 nsec (500.000 Hz)
IPP 123123.000 nsec (8121.959 Hz) -> Divisor 739 123166.667 nsec (8119.080 Hz)
IPP 5412341.000 nsec (184.763 Hz) -> Divisor 32474 5412333.333 nsec (184.763 Hz)
IPP 1233.000 nsec (811030.008 Hz) -> Divisor 7 1166.667 nsec (857142.857 Hz)
IPP 12541.000 nsec (79738.458 Hz) -> Divisor 75 12500.000 nsec (80000.000 Hz)
i.e. it ended up with a divisor of 739 etc.
(Note that I am starting with a fixed clock, later it will change)
I'm using CVXPY 1.0.25, Python 3.7.5 on MacOSX 10.14.6.
A:
To answer the question in your tile, no there is no way to create such a constraint natively. If you could impose such a constraint directly, you would no longer have a convex hull as your solution space.
The fundamental issue here is that you can't create a constraint that makes the sampling of your range non-consecutive. This manifests itself in the interface in two ways that you have seen: you also can't have a constraint on a variable that depends on an expression containing that variable, and the operators // and % aren't defined for expressions.
The workaround for your particular case is to create a 1-to-1 mapping between the variable you solve for and the value you want to get from it. Even numbers are just integers multiplied by 2, so you can remove the explicit evenness constraint and do
constraints = [
ipp == 1e9 / 3e6 * div, # Constrain IPP to divisor
div >= 1, div <= 32768, # Divisor must be 2-65536
]
objective = cp.Minimize(cp.abs(ipp - wantipp)) # Find closest possible IPP
When you print the solution, show twice the solved value:
print('IPP %.3f nsec (%.3f Hz) -> Divisor %d %.3f nsec (%.3f Hz)' % (
i, 1e9 / i, 2 * div.value, ipp.value, 1e9 / ipp.value
))
Better yet, use a more modern f-string in place of the old-style interpolation:
print(f'IPP {i:.3f} nsec ({1e9 / i:.3f} Hz) -> Divisor {2 * div.value} {ipp.value:.3f} nsec ({1e9 / ipp.value:.3f} Hz)')
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery appending value to textarea not working until ajax submitted a 2nd time
I have a jquery jhtml WYSIWYG editor in a form and I need to append its output to a textarea manually. The form is being submitted via ajax. The updateText function is called to grab whats in the wysiwyg div and place it in a textarea to enable ajax to send it. I am using the ajaxForm “beforeSubmit” callback to fire off this function.
//For Ajax Form
$('#addFaci').ajaxForm({
beforeSubmit: updateText,
success: function(response) {
eval(response);
}
});
function updateText(formData, jqForm, options){
var save = '#detail';
$(save).val($(save).htmlarea("toHtmlString"));
return true;
};
This is not working on the first submit... you have to click submit twice before updateText actually fires. Does anyone have any ideas?
Thanks,
A:
When you hit submit this is what happens:
Form data is being collected
beforeSubmit fires, and the collected form data is being passed as the first parameter
You're changing the value of textarea, but it's too late, because data has been already collected
Instead of changing textarea's value you should modify formData object.
UPD. Try this:
for (var i in formData) {
if (formData[i].name == '...name of your textarea here...') {
formData[i].value = ...wysiwyg's html...
}
}
Even easier, remove the hidden textarea and use this:
function updateText(formData, jqForm, options) {
formData.push({name: 'textarea_name', value: .... })
return true;
};
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best modern replacement type for a metalized paper capacitor?
I have a couple of old power supplies in which Rifa brand metalized paper line filter capacitors (for 240V mains power) have failed - or may fail - like in this question here.
30+ years sounds pretty good for a capacitor, but researching replacements turns up lots of opinions about brands and references to different types and materials.
Similar metalized paper capacitors are still available (Evox Rifa is now Kemet), which though a bit pricey have the appeal of looking like the original part. One downside is their failure is messy!
Alternatively there are cheaper metalized film capacitors with polypropylene or polyester.
Is there evidence for a best replacement type considering performance and reliability?
A:
As user EM Fields already suggested, I have already half-answered your question in the linked EE.SE post. Short answer is: get an X2 or Y2 capacitor (see below), these are almost always MKP (metallized polypropylene) film capacitors. Make sure you use a value close or equal to the capacitor it's replacing. Note that both paper and film resistors have very large tolerances (20% is fairly standard over operating conditions), so it doesn't matter if the value is exactly spot-on.
Your application is mains filtering, which is not a precision or high-linearity application. You do not need to worry about the exact type of capacitor. All mains-rated capacitors have similar performance, and performance is basically only dependent on their capacitance value.
What you do need to worry about is that the capacitor is safe to use. If the capacitor is connected between live and neutral, you need to use an X rated capacitor, I recommend X2 to be compliant with 99% of countries' electrical safety regulations. If the capacitor is connected between protective earth (PE) and live or neutral, use Y rated capacitors.
DO NOT use ceramic capacitors. They have very unfavourable failure modes that can cause fire or electric shock hazard.
A:
X and Y capacitors are subject to line spikes, and most will endure multiple small breakdowns over the years as a result of this stress. They fail open because local heating caused by a microscopic dielectric breakdown results in polypropylene melting, which seals off the "edge" of the breakdown.
The practical lifetime is determined more by the number of HV line spikes they absorb rather than by any aging phenomenon.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to print a list of dates asp.net
I'm trying to print a list of dates using a for loop. I'm getting an error saying 'AddDays' is not a member of 'System.Array'.
Dim payDates(10) as Date
For index As Integer = 1 to 10
Redim Preserve payDates(index)
payDates(index) = payDates.AddDays(1)
index +=1
NEXT
Response.Write(payDates)
A:
I'm no vb expert, but you need to access the index of the array, not the array itself:
Dim payDates(10) as Date
For index As Integer = 1 to 10
Redim Preserve payDates(index)
payDates(index) = payDates(index).AddDays(1)
index +=1
NEXT
Response.Write(payDates)
Also you migzht want to write every date. In this case change you code to this:
Dim payDates(10) as Date
For index As Integer = 1 to 10
Redim Preserve payDates(index)
payDates(index) = payDates(index).AddDays(1)
Response.Write(payDates(index))
index +=1
NEXT
In essence:
payDates is of type System.Array
payDates(index) contains a DateTime variable at the position index, where index is of type int
| {
"pile_set_name": "StackExchange"
} |
Q:
MonoDroid 4.0.6+ on GoogleTV?
I've been trying to find out if MonoDroid can run on the GoogleTV as it uses an Intel Atom x86 CPU instead of a ARM CPU.
I came across:: http://docs.xamarin.com/android/Releases/Mono_For_Android_4/Mono_For_Android_4.0.6
The release notes quote:: "It also includes x86 support for full versions of Mono for Android (not trial)".
Does this statement mean MonoDroid will now support GoogleTV??
If so i'm buying the software...
NOTE: It's not an issue if it runs in the emulator, only if MonoDroid can run on the native hardware.
A:
It should in theory, but it haven't been tested yet. An upcoming release will add x86 emulator support to the trial version. Or you can purchase, try it, and if it doesn't work, take advantage of the full refund.
| {
"pile_set_name": "StackExchange"
} |
Q:
Displaying and hiding a specific row in the table
Goal:
When you click the text "info" in the column "comments", a row should be displayed below with text information that is related to the "comments". Need also to click the text "Info" again to hide the text information of comments.
Problem:
I don't know how to display the row when you click one of the comments with the text "info". When clicking one of the link the remaining rows with the text "info" should not be affected. In order words, the part should be independent
Need also some help hiding the text information of comments.
There are some things that you also need to take account to:
The amount of data that will be displayed in the table will be
changed from day to day. The data is taken from a xml file.
Would like the sourcode to be written in jQuery.
Only html, css and javascript is allowed in this context.
html code in tr and td will be generated by javscript code.
Please remember that the text hide and show is only for temporary.
// Fullmetalboy
$(document).ready(init);
function init()
{
startPoint();
}
var mittXHRobjekt = null;
function skapaXHRobjekt() {
try {
mittXHRobjekt = new XMLHttpRequest(); // Firefox, Opera, ...
} catch (err1) {
try { // Någon IE version
mittXHRobjekt = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err2) {
try { // Någon IE version
mittXHRobjekt = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err3) {
mittXHRobjekt = false;
}
}
}
if (mittXHRobjekt == null) {
alert('Error creating request object!');
}
return mittXHRobjekt;
}
function startPoint() {
var xmlAdress = "data.xml";
mittXHRobjekt = skapaXHRobjekt();
if (mittXHRobjekt) {
mittXHRobjekt.onreadystatechange = function () {
if (mittXHRobjekt.readyState == 4) {
testt();
} //if
} //slut på anonym funktion som utförs när tillståndet i XHR ändras
mittXHRobjekt.open("GET", xmlAdress);
mittXHRobjekt.send(null);
}
} //slut på funktionen visaKurs
function testt()
{
var data = retrieveDataFromXML();
var data2 = briefAllProject(data);
AddRow(data2);
}
function retrieveDataFromXML() {
//Hämtar alla taggar av typen kurs
var projektnamn = mittXHRobjekt.responseXML.getElementsByTagName("projektnamn");
var kommentar = mittXHRobjekt.responseXML.getElementsByTagName("kommentar");
var datum = mittXHRobjekt.responseXML.getElementsByTagName("datum");
var timmar = mittXHRobjekt.responseXML.getElementsByTagName("timmar");
var minuter = mittXHRobjekt.responseXML.getElementsByTagName("minuter");
var araay = new Array();
var nummer = 0;
//Har nu en matris/array av <kurs> noder. Kan loopa genom matrisen
for (a = 0; a < projektnamn.length; a++)
{
for (b = 0; b < 5; b++)
{
if(b == 0)
{
araay[nummer] = projektnamn[a].firstChild.data;
}
else if(b == 1)
{
araay[nummer] = kommentar[a].firstChild.data;
}
else if(b == 2)
{
araay[nummer] = datum[a].firstChild.data;
}
else if(b == 3)
{
araay[nummer] = timmar[a].firstChild.data;
}
else if(b == 4)
{
araay[nummer] = minuter[a].firstChild.data;
}
nummer++;
}
}
return araay;
} //slut på fyllElementMedDataFranServern
function AddRow(pArray)
{
var b=0;
var tabell = document.getElementById("tblProjekt");
var tabell2 = document.getElementById("tblProjekt");
var newRow;
var c = 1;
var test = 0;
for(a=0; a < pArray.length/4; a++)
{
newRow = tabell.insertRow(tabell.rows.length);
for(b=1; b <= 4; b++)
{
var newCell;
if(b == 1)
{
newCell = newRow.insertCell(0);
newCell.innerHTML = pArray[test + 0];
}
else if(b == 2)
{
newCell = newRow.insertCell(1);
newCell.innerHTML = pArray[test + 1];
}
else if(b == 3)
{
newCell = newRow.insertCell(2);
newCell.innerHTML = pArray[test + 2];
}
else if(b == 4)
{
newCell = newRow.insertCell(3);
newCell.innerHTML = "Info";
//newCell.innerHTML = pArray[test + 3];
newRow = tabell2.insertRow(tabell2.rows.length);
//newCell = newRow.insertCell(0);
var newAttrColspan = document.createAttribute("colspan");
newAttrColspan.nodeValue = 4;
newRow.className = "firstDataRow";
//newRow.id = "firstDataRow";
var newCell = newRow.insertCell(0);
newCell.setAttributeNode(newAttrColspan);
newCell.innerHTML = "asdf";
//$("#firstDataRow").hide();
//$(".aaa").hide();
}
}
test = 4 + test;
}
}
$(document).ready(function()
{
$('.submit').click(function()
{
$(".firstDataRow").hide();
}); // saveForm
$('.submitt').click(function()
{
$(".firstDataRow").show();
}); // saveForm
}); // ready
function briefAllProject(pArray)
{
var araay = new Array();
var nummer5 = 0;
var nummer3 = 3;
var projectNameArray = new Array();
var newArray=new Array();
for (a = 0; a < pArray.length/5; a++)
{
newArray[a] = pArray[nummer5];
nummer5 = 5 + nummer5;
}
projectNameArray = removeDuplicates(newArray);
nummer5 = 0;
nummer3 = 0;
var sanning = true;
var dontAddValue = true;
for (var a = 0; a < projectNameArray.length; a++)
{
for (var b = 0; b < pArray.length/5; b++)
{
if( (projectNameArray[a] == pArray[nummer5]) && (pArray[nummer5] != null) && (a < projectNameArray.length) )
{
if(sanning == true)
{
araay[0 + nummer3] = pArray[0 + nummer5]; // namn
araay[1 + nummer3] = mergAllTimeOfSpecificProject(pArray , pArray[0 + nummer5]);
araay[2 + nummer3] = "Info"; // info
araay[3 + nummer3] = pArray[1 + nummer5]; // kommentar
nummer3 = nummer3 + 4;
sanning = false;
}
}
nummer5 = nummer5 + 5;
}
nummer5 = 0;
sanning = true;
}
return araay;
}
function mergAllTimeOfSpecificProject(pArray , pProjectName)
{
var aa = 0;
var nummer5 = 0;
for(a = 0; a < pArray.length/5; a++)
{
if(pArray[nummer5] == pProjectName)
{
aa += parseInt(pArray[3 + nummer5]);
}
nummer5 = 5 + nummer5;
}
return aa;
}
function removeDuplicates(arr)
{
//get sorted array as input and returns the same array without duplicates.
var result=new Array();
var lastValue="";
result[0] = arr[0];
var kth = 0;
var sanning = true;
for (var a=0; a < arr.length; a++)
{
for(var b=0; b < arr.length; b++)
{
if (result[kth] != arr[b])
{
for(var aa = 0; aa < result.length; aa++)
{
if(result[aa] == arr[b])
{
sanning = false;
}
}
if(sanning == true)
{
result[result.length] = arr[b];
kth++;
}
else
{
sanning = true;
}
}
}
}
return result;
}
<table border="1" SUMMARY="aaa" id="tblProject">
<thead>
<tr>
<th>Projekt name</th>
<th>Total time</th>
<th>Task</th>
<th>comments</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<a href="#" class="submit">hide</a>
<a href="#" class="submitt">show</a>
<?xml version="1.0" encoding="UTF-8" ?>
<projektarbeten>
<projekt>
<projektnamn>aaaa</projektnamn>
<kommentar>kommentar</kommentar>
<datum>2011-3-3</datum>
<timmar>6</timmar>
<minuter>0</minuter>
</projekt>
<projekt>
<projektnamn>bbbb</projektnamn>
<kommentar>kommentar</kommentar>
<datum>2011-3-3</datum>
<timmar>2</timmar>
<minuter>0</minuter>
</projekt>
<projekt>
<projektnamn>aaaa</projektnamn>
<kommentar>kommentar</kommentar>
<datum>2011-3-3</datum>
<timmar>6</timmar>
<minuter>0</minuter>
</projekt>
<projekt>
<projektnamn>cccc</projektnamn>
<kommentar>kommentar</kommentar>
<datum>2011-3-3</datum>
<timmar>10</timmar>
<minuter>0</minuter>
</projekt>
<projekt>
<projektnamn>cccc</projektnamn>
<kommentar>kommentar</kommentar>
<datum>2011-3-3</datum>
<timmar>10</timmar>
<minuter>0</minuter>
</projekt>
<projekt>
<projektnamn>cccc</projektnamn>
<kommentar>kommentar</kommentar>
<datum>2011-3-3</datum>
<timmar>10</timmar>
<minuter>0</minuter>
</projekt>
<projekt>
<projektnamn>kth ss</projektnamn>
<kommentar>kommentar</kommentar>
<datum>2011-3-3</datum>
<timmar>14</timmar>
<minuter>0</minuter>
</projekt>
<projekt>
<projektnamn>kth ss</projektnamn>
<kommentar>kommentar</kommentar>
<datum>2011-3-3</datum>
<timmar>50</timmar>
<minuter>0</minuter>
</projekt>
</projektarbeten>
A:
I'd suggest you to use a table plugin for jquery. I've been using datatables for two years and i find it particulary useful. Look at this example that perfectly suits your case io think:
http://datatables.net/release-datatables/examples/api/row_details.html
Look at this fiddle for an example: http://jsfiddle.net/nicolapeluchetti/5QhNx/3/
| {
"pile_set_name": "StackExchange"
} |
Q:
li marker character color not updating in chrome
I have a <ul> with a handful of <li>s. I'm adding classes to the <li>s with a very basic bit of js. (This is an example for illustrating the possible bug, not my actual use case).
In FF, IE, Safari, the class .good or .bad is added, and the <li> and <a> colors are updated.
However, in Chrome the class is added, the <a> color is updated, but the <li> color stays the same. Browser Inspector shows the li character color is the color specified in the class, however the actual window shows the old color. Toggling any class attribute with the browser inspector causes the window to re-render, with the correct colors. Likewise with resizing the codepen results window.
View a CodePen here: http://codepen.io/fontophilic/pen/EVmbWd
setTimeout(function(){
document.getElementById("bar").classList.add("bad");
document.getElementById("test").classList.add("good");
document.getElementById("foo").classList.add("good");
document.getElementById("whatevs").classList.add("good");
}, 3000);
ul li {
color: black;
}
ul li a {
color: black;
}
ul li.good {
color: green;
}
ul li.good a {
color: green;
}
ul li.bad {
color: red;
}
ul li.bad a {
color: red;
}
<ul>
<li> <a href="#" class="">First</a></li>
<li id="test"> <a href="#" class="">Two</a></li>
<li id="foo"> <a href="#" class="">The Third</a></li>
<li> <a href="#" class="">Quatro</a></li>
<li id="bar"> <a href="#" class="">Fiver</a></li>
<li> <a href="#" class="">Six</a></li>
<li id="whatevs"> <a href="#" class="">Seven</a></li>
</ul>
Important to note, if the <li>s have the classes applied on page load, display is as expected: http://codepen.io/fontophilic/pen/XmRqqJ
Any ideas on how to get Chrome to re-render the li color? Is this a known bug?
A:
I still believe this to be a chromium/webkit bug, but for now I've found an acceptable solution. I force Chrome to re-render the element by modifying the box by adding and removing a 1px transparent border.
setTimeout(function(){
document.getElementById("bar").classList.add("bad");
document.getElementById("test").classList.add("good");
document.getElementById("foo").classList.add("good");
document.getElementById("whatevs").classList.add("good");
}, 3000);
ul {
width: 150px;
}
ul li {
list-style: disc;
color: transparent;
}
ul li a {
color: black;
display: block;
border-top: 1px solid transparent;
}
ul li.good {
background-image: none;
color: green;
border-top: 1px solid transparent;
}
ul li.good a {
color: green;
border-top: 0px solid transparent;
}
ul li.bad {
color: red;
border-top: 1px solid transparent;
}
ul li.bad a {
color: red;
border-top: 0px solid transparent;
}
<ul>
<li> <a href="#" class="">First</a></li>
<li id="test"> <a href="#" class="">Two</a></li>
<li id="foo"> <a href="#" class="">The Third</a></li>
<li> <a href="#" class="">Quatro</a></li>
<li id="bar"> <a href="#" class="">Fiver</a></li>
<li> <a href="#" class="">Six</a></li>
<li id="whatevs"> <a href="#" class="">Seven</a></li>
</ul>
Update
Based on this stackoverflow question, I've improved my solution and eliminated the crufty css. hiding and showing the parent element will force a redraw of its children. For whatever reason, using jQuery's show/hide worked, and vanilla js show/hide did not. This is confusing, but seemingly true.
setTimeout(function(){
document.getElementById("bar").classList.add("bad");
document.getElementById("test").classList.add("good");
document.getElementById("foo").classList.add("good");
document.getElementById("whatevs").classList.add("good");
$("#woot").hide().show(0);
}, 3000);
ul li {
color: black;
}
ul li a {
color: black;
}
ul li.good {
color: green;
}
ul li.good a {
color: green;
}
ul li.bad {
color: red;
}
ul li.bad a {
color: red;
}
<ul id="woot">
<li> <a href="#" class="">First</a></li>
<li id="test"> <a href="#" class="">Two</a></li>
<li id="foo"> <a href="#" class="">The Third</a></li>
<li> <a href="#" class="">Quatro</a></li>
<li id="bar"> <a href="#" class="">Fiver</a></li>
<li> <a href="#" class="">Six</a></li>
<li id="whatevs"> <a href="#" class="">Seven</a></li>
</ul>
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting data from my join table
I have a join table which takes the id from my respondents table respondant_id and the id from my teams table table_id.
The output is fine when I SELECT from that table so I get back the respondants ID married up with the teams ID.
I am wanting to show the respondents name from respondant_data and the team name from teams by using the values output from the join table.
I have attempted this here but I keep getting 0 results.
$sql = "
SELECT
respondant_data.respondant_id, teams.team_id
FROM
respondant_data
INNER JOIN
teams
ON
respondant_data.respondant_id = teams.team_id
WHERE
respondant_teams.team_id= 5";
$result = $conn->query($sql);
$i = 1;
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo $i++ . ' ';
echo 'user_id: ' . $row["respondant_id"] . ', ';
echo 'team_id: ' . $row["team_id"];
echo '<br>';
}
} else{
echo 'no results';
}
So I want my output to be like 'John Smith', 'Central Team'
A:
Try this query.
SELECT
resp_data.respondant_id, teams.team_id
FROM
respondant_data resp_data,
teams,
respondant_teams resp_teams
WHERE
resp_data.respondant_id = teams.team_id
and resp_teams.team_id = teams.team_id
and resp_teams.team_id = 5
| {
"pile_set_name": "StackExchange"
} |
Q:
storing a string with '#' in it in rails
I tried storing a string in rails like
string = 'abc#$123'
but the string stores "abc\ #$123". I tried removing "\" by using string.delete("\",'') but didn't work
Is there any way to solve this problem ?
A:
This is correct, Ruby interpreter is just escaping the character #$ by using backslash (\) character.
It is not exactly changing your string and adding the unwanted (\) character. You can verify this by doing puts string and it should print abc#$123
| {
"pile_set_name": "StackExchange"
} |
Q:
80s era Sci-Fi/Horror film featuring several unrelated stories (not Creepshow)
Plot Details/Summary
As stated in the prompt, this particular film was made up of a number of short stories with science fiction and/or horror elements. It's not one of the Creepshow films or the Tales From The Darkside movie. I do not recall exactly how many stories there were, but I do recall two of the stories fairly well.
The first story is about a rebellious teenager who is obsessed with a particular video game at the local arcade. He's the best player in town on the particular game, but he always seems to be defeated before cracking the final level. It sticks in my mind his family and friends are worried about his obsession.
The sci-fi elements come into play when the teen sneaks into the arcade late one night and finally cracks the secret level. To his horror, it turns out that the bad guy in the video game is released and the game becomes "real life". I recall the video game monster being a very blocky animation in the style of early 80s video games. I think it represented a face or the like.
The creature chases the teen, unleashing energy bolts, etc. The teen is eventually cornered, and we see the monster floating towards him in a first-person view. The twist comes the next morning, when worried friends and family come down to the arcade to look for him. The scene closes with his horrified friend looking at the game screen and realizing his friend is now a character trapped inside the game itself.
*
The second story involves a priest getting caught up in a car chase with what is probably The Devil. The priest has just left his parish, disenchanted and in a crisis of faith. He resists all attempts to change his mind, and the only thing he is willing to take with him is a vial of holy water that (IIRC) another priest insists he take with him for luck. The church is probably somewhere in the southwestern US, as I think the story takes place mostly in the desert
While on the road to wherever he's headed, the priest encounters a black truck or SUV-type vehicle. I don't recall exactly how it happens. What follows is a deadly game of chase very reminiscent of the Steven Spielberg tv movie Duel. We never see the antagonist, though we do get a glimpse from behind the wheel, which reveals an inverted cross hanging from the rear view mirror (thus the suspicion this is Old Nick we're dealing with here.)
The climax to the story comes when the priest, now on foot, is about to be run down by the SUV. The priest desperately throws the vial of holy water, which strikes the vehicle and causes it to vanish or explode (can't remember which). As best as I can remember, the story closes with the priest returning to the parish, his faith in God renewed.
Date of Release
I'm sure it's 1980s, probably early 80s, based on the video game story. The film is in English, and most likely a U.S.-made film.
A:
This is Nightmares from 1983. The first story is Bishop of Battle:
Young Jerry "J.J." Cooney (Estevez) is a video game wizard and arcade game hustler with help from his bespectacled friend Zock (Billy Jayne).
After an argument about Jerry's obsession with video games, they split up for the day, and Jerry goes into his local arcade to try again to beat The Bishop of Battle, a maddeningly difficult video game that features thirteen levels; no one he knows has made it to the thirteenth, and many believe it is just a myth. He repeatedly tries and fails to make it to the thirteenth level until the owner forces him to leave at closing time.
Jerry's parents, concerned about his performance in school, ground him until his grades improve. That night, he sneaks out and breaks into the arcade to finally finish the game. However, when he reaches the thirteenth level, the arcade cabinet collapses and the enemies fly out (Estevez went through a two-week gun training session with the NYPD to realistically perform his gun maneuvers for these scenes). Jerry flees to the parking lot, but the Bishop of Battle appears, drawing closer and closer to a terrified Jerry. The scene cuts to the next morning, where his friends and family see Jerry's image on the screen of the arcade machine for a few seconds before it turns into the player and the short ends.
The second story is The Benediction
Lance Henriksen plays a priest serving at a small parish and is facing a crisis of faith brought on by the violent death of a young boy. He explains to his bishop (Plana) that he has lost his belief in the concepts of good and evil. He finally leaves the ministry with some blessed water which he now deems as purely tap water, and takes off across the desert in his car.
Out of nowhere he encounters a black Chevrolet C-20 Fleetside. At first, it just cuts him off and takes off. However, it keeps reappearing, forcing him off the road and damaging his car. The truck's driver is Satan because of the upside down cross hanging on the rear-view mirror of the truck. Satan blows up the priest's car with the pickup truck by hitting it. With nowhere left to run, the former priest hurls the blessed water at the pickup truck, which is vaporized at the impact. The short ends as the police arrive later on the scene and the ambulance crew takes the injured priest back to the church.
The other stories are Terror in Topanga, about a woman on a late-night cigarette run and the killer who is stalking the area, and Night of the Rat, which is about a family terrorized by an infestation of rats.
I found it by searching Google for film priest car chase devil.
Official Trailer
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert std::vector to QImage
I am trying to create QImage from std::vector. I tried;
void FaceCutThread::convertImage(std::vector<uint8_t> &buf)
{
QImage img(&buf[0], 300, 300, QImage::Format_ARGB32);
emit isFinisedFaceCut(img);
}
and
void FaceCutThread::convertImage(std::vector<uint8_t> &buf)
{
QImage img(buf.data(), 300, 300, QImage::Format_ARGB32);
emit isFinisedFaceCut(img);
}
both two type of convertion didn't give any error;however, when I tried to show it in QLabel like;
void MainWindow::handleFaceResults(QImage& buf)
{
QImage myImage(buf);
ui->lblRawImage->setPixmap(QPixmap::fromImage(myImage));
}
my app always unexpectedly finishing. Could you please help how I can convert to QImage correctly?
EDIT:
I can write image into file without any problem like;
bool save_file (const string &path, const vector<uint8_t> &data)
{
std::ofstream os;
os.open(path.c_str(), std::ios::out | std::ios::binary);
if (!os.is_open())
return false;
os.write((const char*)data.data(), data.size());
return true;
}
A:
I solved a similar problem with QImageReader and QBuffer
QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(buf.data()), buf.size());
QBuffer buffer(data);
QImageReader reader(&buffer);
QImage img = reader.read();
| {
"pile_set_name": "StackExchange"
} |
Q:
CodeIgniter Controller- How do I pass status back to calling function
I am posting some data to an action on a controller using the CI framework. The post completed successfully but I would like to return a status to the calling jQuery.post().
Using firebug I can see that the post is completed successfully (200) but I don't see the json that I am returning. How come I am not getting the json returned?
public function sendMail()
{
$senderName = trim($_POST['senderName']);
$returnEmail = trim($_POST['returnEmail']);
$message = trim($_POST['message']);
if (valid_email($returnEmail))
{
send_email('[email protected]','Website Email From: '.$senderName, $message);
$success = array('success'=>'Mail Sent');
echo json_encode($success);
}
else
{
$errorMessage = array('error'=>'Invalid Email Address');
echo json_encode($errorMessage);
}
}
Ajax post
$.post("http://example.com/index.php/mail/sendmail",{senderName: senderName, returnEmail: senderAddr, message: message }, function(data){
if(data.status == "success")
{
alert("mail sent.");
}
else
{
alert("mail failure");
}
});
A:
The problem was with the url. I think trying to post to 'http://mysite.com' from my local host was causing cross site scripting security issues.
I changed the url property to something relative and it works great.
$.ajax({
type: 'POST',
url: "index.php/mail/sendmail",
data: {senderName: senderName, returnEmail: senderAddr, message: message},
dataType: "JSON",
success: function(data){
if(typeof data.error == "undefined"){
alert("Mail failure");
}
else{
alert("Mail sent");
}
},
error: function(data){
alert("Something went wrong"); // possible that JSON wasn't returned
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Detecting the locked table or row in SQL Server
I'm trying to understand/learn how to track down the details of a blocked session.
So I created the following setup:
create table foo (id integer not null primary key, some_data varchar(20));
insert into foo values (1, 'foo');
commit;
Now I connect to the database twice from two different clients.
The first session issues:
begin transaction
update foo set some_data = 'update'
where id = 1;
I explicitly do not commit there in order to keep the locks.
In the second session I issue the same statement and of course that one waits due to locking. Now I'm trying to use the different queries floating around in order to see that session 2 is waiting for the foo table.
sp_who2 shows the following (I removed some columns to only show the important information):
SPID | Status | BlkBy | DBName | Command | SPID | REQUESTID
-----+--------------+-------+----------+------------------+------+----------
52 | sleeping | . | foodb | AWAITING COMMAND | 52 | 0
53 | sleeping | . | foodb | AWAITING COMMAND | 53 | 0
54 | SUSPENDED | 52 | foodb | UPDATE | 54 | 0
56 | RUNNABLE | . | foodb | SELECT INTO | 56 | 0
This is expected, session 54 is blocked by the un-committed changes from session 52.
Querying sys.dm_os_waiting_tasks also shows this. The statement:
select session_id, wait_type, resource_address, resource_description
from sys.dm_os_waiting_tasks
where blocking_session_id is not null;
returns:
session_id | wait_type | resource_address | resource_description
-----------+-----------+--------------------+---------------------------------------------------------------------------------
54 | LCK_M_X | 0x000000002a35cd40 | keylock hobtid=72057594046054400 dbid=6 id=lock4ed1dd780 mode=X associatedObjectId=72057594046054400
Again this is expected.
My problem is, that I can't figure out how to find the actual object name that session 54 is waiting for.
I have found several queries that are joining sys.dm_tran_locks and sys.dm_os_waiting_tasks like this:
SELECT ....
FROM sys.dm_tran_locks AS l
JOIN sys.dm_os_waiting_tasks AS wt ON wt.resource_address = l.lock_owner_address
But in my above test scenario this join does not return anything. So either that join is wrong or dm_tran_locks doesn't actually contain the information I'm looking for.
So what I am looking for is a query that returns something like:
"session 54 is waiting for a lock in table foo".
Some background info:
The real life problem I'm trying to solve is a bit more complicated, but boils down to the question "on which table is session 54 waiting for". The problem in question involves a largish stored procedure that updates several tables and a select from a view that accesses some of those tables. The select statement is blocked even though we have snapshot isolation and read committed snapshot enabled. Figuring out why the select is blocked (which I thought would not be possible if snapshot isolation is enabled) will be the next step.
As a first step I'd like to find out on what that session is waiting.
A:
I think this does what you need.
USE 'yourDB'
GO
SELECT
OBJECT_NAME(p.[object_id]) BlockedObject
FROM sys.dm_exec_connections AS blocking
INNER JOIN sys.dm_exec_requests blocked
ON blocking.session_id = blocked.blocking_session_id
INNER JOIN sys.dm_os_waiting_tasks waitstats
ON waitstats.session_id = blocked.session_id
INNER JOIN sys.partitions p ON SUBSTRING(resource_description,
PATINDEX('%associatedObjectId%', resource_description) + 19,
LEN(resource_description)) = p.partition_id
A:
You can try it :
SELECT
db_name(rsc_dbid) AS 'DATABASE_NAME',
case rsc_type when 1 then 'null'
when 2 then 'DATABASE'
WHEN 3 THEN 'FILE'
WHEN 4 THEN 'INDEX'
WHEN 5 THEN 'TABLE'
WHEN 6 THEN 'PAGE'
WHEN 7 THEN 'KEY'
WHEN 8 THEN 'EXTEND'
WHEN 9 THEN 'RID ( ROW ID)'
WHEN 10 THEN 'APPLICATION' end AS 'REQUEST_TYPE',
CASE req_ownertype WHEN 1 THEN 'TRANSACTION'
WHEN 2 THEN 'CURSOR'
WHEN 3 THEN 'SESSION'
WHEN 4 THEN 'ExSESSION' END AS 'REQUEST_OWNERTYPE',
OBJECT_NAME(rsc_objid ,rsc_dbid) AS 'OBJECT_NAME',
PROCESS.HOSTNAME ,
PROCESS.program_name ,
PROCESS.nt_domain ,
PROCESS.nt_username ,
PROCESS.program_name ,
SQLTEXT.text
FROM sys.syslockinfo LOCK JOIN
sys.sysprocesses PROCESS
ON LOCK.req_spid = PROCESS.spid
CROSS APPLY sys.dm_exec_sql_text(PROCESS.SQL_HANDLE) SQLTEXT
| {
"pile_set_name": "StackExchange"
} |
Q:
pdo connection in php file executed in terminal does not work
I have a php file that if executed in the browser works just fine but when I execute it in the terminal,
php
/opt/lampp/htdocs/xampp/site_name/update_db.php
the pdo include and connection do not seem to work because I get the error
could not find driverPHP Fatal error:
Call to a member function prepare() on
a non-object in
/opt/lampp/htdocs/xampp/site_name/update_db.php
on line 8
update_db.php
include("roc/include/connection.php");
$db = new PDOConnectionFactory();
$conn = $db->getConnection();
//prepare for utf8 characters
$sql = 'SET NAMES utf8';
$stmt = $conn->prepare($sql);
$result=$stmt->execute();
$sql = 'SET CHARACTER SET utf8';
$stmt = $conn->prepare($sql);
$result=$stmt->execute();
//**************************
$sql = 'update video SET
status=? WHERE file_name=?';
$stmt6 = $conn->prepare($sql);
$result=$stmt6->execute(array('1','5cca985383047644f51c4f31d906c8f8'));
Anyone have any ideas?
A:
This topic has been Solved. Read Comments.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to use Pageable Interface to avoid printing range 1-9999
I am trying to print a JPanel called print_p.It contains a Table and some labels.
The error is in print dialog its range 1-9999
How can I fix this issue?
private void printCard(){
PrinterJob printjob = PrinterJob.getPrinterJob();
printjob.setJobName(" Test Report ");
printjob.setPrintable (new Printable() {
@Override
public int print(Graphics pg, PageFormat pf, int pageNum){
pf.setOrientation(PageFormat.LANDSCAPE);
if (pageNum > 0){
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.translate(0f, 0f);
print_p.paint(g2);
return Printable.PAGE_EXISTS;
}
});
if (printjob.printDialog() == false)
return;
try {
printjob.print();
} catch (PrinterException ex) {
System.out.println("NO PAGE FOUND."+ex);
}
}
A:
When using Printable, this is expected behaviour, as the dialog has no idea of how many pages might be printed, as nothing about the print job has been processed.
You need to use a Pagable interface. This allows you to collect a series of Printables, each which represents a single page within the virtual book.
For a ready made implementation, you can take a look at java.awt.print.Book
Updated with example
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PrintTest {
public static void main(String[] args) {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName("Book 'em Danno");
PageFormat pf = pj.defaultPage();
pf.setOrientation(PageFormat.LANDSCAPE);
Book book = new Book();
for (int index = 0; index < 10; index++) {
book.append(new Page(index + 1), pf);
}
pj.setPageable(book);
if (pj.printDialog()) {
try {
pj.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
}
public static class Page implements Printable {
private int page;
public Page(int page) {
this.page = page;
}
@Override
public int print(Graphics graphics, PageFormat pf, int pageIndex) throws PrinterException {
Graphics2D g2 = (Graphics2D) graphics;
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.translate(0f, 0f);
FontMetrics fm = g2.getFontMetrics();
String text = Integer.toString(page);
double y = (pf.getImageableHeight() - fm.getHeight()) + fm.getAscent();
double x = (pf.getImageableWidth() - fm.stringWidth(text)) / 2d;
g2.drawString(text, (float)x, (float)y);
System.out.println(pageIndex);
return PAGE_EXISTS;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
iMac Will not Recognize its HDD
I have been using a late-2009 iMac (21.5") (it was running the latest pre-Sierra update, I do not remember the exact OS version) for somewhere in the area of six months now and have, overall, had no issues with it. However, two weeks ago, it failed. The story surrounding this apparently sudden failure is that I was running an update of Safari that involved needing to do a restart. Immediately after doing the restart, the electricity for our home went out, it was only out for around a minute. Luckily the computer was plugged into a surge protector... Or not.
Later that day, when I tried to turn it on, it turned on but wouldn't boot passed the Apple Screen with the small, gray progress bar.
It is still basically in that same state. However, after some reading on the internet and trying a variety of things booting to "Command+S" as well as "Command+R". What happened when I ran "Command+R" was somewhat depressing. The Mac is completely unaware of the fact that it has a 500GB Western Digital HDD in it (which I can hear turning) and if I run Disk Utility, it will spend hours looking for that drive.
What I tried today was reinstalling the OS (failed), booting it with SpinRite and booting it from a 64GB external drive (worked). Once I booted to the external drive, I ran disk utility which I started at around 1400 hours, it is now 1500 hours and it just now found its hard drive. A warning popped up and indicated that the drive could not be repaired. I am now running First Aid on it, just curious to see what if anything it can do there.
I do not totally know what my question here is. Other than, if what I am trying right now doesn't work, what should I do? Should I just give up and drag the thing to an Apple Store? I have data on it that I must recover (sadly I had nothing backed up).
To Summarize: If what I am doing right now doesn't work, what - if anything - can I do next? Are there any other at-home fixes I can try before taking it to an Apple Store?
Note: I own one other Mac that is exactly the same as the one that is not working, I also own portions of 38 other older Macs and part of a broken one that is also this computer's twin. (I added this in case anyone recommends any form of testing, or needing certain parts).
A:
I just had a hdd fail in my imac last week. So I know this method works:
Get all important files off of the hdd with Lazesoft Mac Data Recovery. You'll have to copy the files to another disk. If you have enough space, the one you used to boot with might be enough. It takes a LONG time to copy files off of a disk that will not mount in the OS! Be patient.
From there it's up to you. Personally I'd replace the failed drive. If it failed once, it will fail again. But if you have the luxury of time and patience, you can try to erase/reformat it yourself then copy the files back... hope for the best.
Otherwise, take it to Apple. They'll replace the drive and copy the data for you (if possible). They'll also break your bank =) They won't even give you a price over the phone!
I went with UBreakIFix. $100 got the replacement done. But I had to copy the files myself as described above. Also they didn't do the jumpers right so the fans come on at 100% until I put in a software solution to fix that. A lackluster experience for sure. But if you go in there with the knowledge of the SMC/fan situation, they'll probably set it up correctly for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Universal Windows 10 App Using Visual Studio 2015
I started learning Windows app development using Visual Studio 2015 following this article: https://code.msdn.microsoft.com/windowsapps/Windows-Phone-Login-17725566
In my solution I created two directories, one for Views (xaml) and another for Models (xaml.cs). Up to the creation of my xaml files everything went smoothly. When it comes to xaml.cs (assume now I'm in a login page), when I click the login button, it should go to the signup page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
namespace LoginApp.Model
{
class LoginPage
{
public void Login_Click(object sender, RoutedEventArgs e) {
}
public void SiguUp_Click(object sender, RoutedEventArgs e) {
NavigationService.Navigate(new Uri("/Views/SignUpPage.xaml", UriKind.Relative));
}
}
}
I have an issue with NavigationService (It is saying "the name NavigationService does not exist in current context").
The second point where I'm stuck is in the signup Page.xaml.cs. I have a textbox with the name txtusername. I'm trying to add some text to the textbox and use a message box:
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.UI.Xaml;
namespace LoginApp.Model
{
class SignUpPage
{
IsolatedStorageFile ISOFile = IsolatedStorageFile.GetUserStoreForApplication();
public void Submit_Click(object sender, RoutedEventArgs e) {
if (!Regex.IsMatch(TxtUserName.Text.Trim(), @"^[A-Za-z_][a-zA-Z0-9_\s]*$")) {
MessageBox.Show("Invalid UserName");
}
}
}
}
<Page
x:Class="LoginApp.SignUpPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:LoginApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid x:Name="LayoutRoot" Background="White">
<Grid Margin="10,10,-5,-10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Text="User Registration :" Grid.Row="0" FontSize="40" Foreground="Black"/>
<TextBlock Text="UserName" Grid.Row="1" Foreground="Black" Margin="0,25,0,0"/>
<TextBox Name="TxtUserName" BorderBrush="LightGray" Grid.Row="1" Margin="100,0,0,0" GotFocus="Txt_GotFocus"/>
<TextBlock Text="Password:" Grid.Row="2" Margin="0,25,0,0" Foreground="Black"/>
<PasswordBox Name="TxtPwd" BorderBrush="LightGray" Grid.Row="2" Margin="100,0,0,0" GotFocus="pwd_GotFocus"/>
<TextBlock Text="Address:" Grid.Row="3" Margin="0,25,0,0" Foreground="Black"/>
<TextBox Name="TxtAddr" BorderBrush="LightGray" Margin="100,0,0,0" GotFocus="Txt_GotFocus"/>
<TextBlock Text="Gender:" Grid.Row="4" Margin="0,25,0,0" Foreground="Black"/>
<RadioButton Name="GenMale" Background="LightGray" Grid.Row="4" Margin="100,0,0,0" Content="Male" Foreground="Black"/>
<RadioButton Name="GenFemale" Background="LightGray" Grid.Row="4" Margin="200,0,0,0" Content="Female" Foreground="Black"/>
<TextBlock Text="Phone No:" Grid.Row="5" Margin="0,25,0,0" Foreground="Black"/>
<TextBox Name="TxtPhNo" Grid.Row="5" Margin="100,0,0,0" Foreground="LightGray" MaxLength="10" InputScope="Digits" GotFocus="Txt_GotFocus"/>
<TextBlock Text="EmailID:" Grid.Row="6" Margin="0,25,0,0" Foreground="Black"/>
<TextBox Name="TxtEmail" Grid.Row="6" Margin="100,0,0,0" GotFocus="TxtGotFocus"/>
<Button BorderBrush="Transparent" Background="#FF30DABB" Content="Submit" Name="BtnSubmit" Click="Submit_Click" Grid.Row="7" Margin="0,25.667,0,-41.667" Width="345"/>
</Grid>
</Grid>
</Page>
With this code the red line points to the TxtUserName and MessageBox saying that "The name does not exist in current context".
I found one article in the it is saying "use correct reference Add Reference to PresentationFramework.dll". I added a reference and clicked Select Assemblies > Framework > Check the PresentationFramework component box and clicked ok.
When I reach this point, it is showing "No Framework assemblies were found on the machine".
I have .NET Framework 4.5 installed on my computer.
A:
This is weird, I pasted your code and launched the app, its working fine and I am able to display Text and Textbox is visible:
private void Submit_Click(object sender, RoutedEventArgs e)
{
TxtUserName.Text = "Sample text!";
}
Maybe there is some other problem with your project?
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't link Tkinter scrollbar to Listbox
I am trying to create a part manager using Tkinter and Sqlite3, but the scrollbar doesn't seem to work. It shows up on the screen, but it isn't usable and doesn't seem to be linked to the listbox.
OBS: I have to use .grid() due to organization.
from tkinter import *
root = Tk()
#Define and Grid Listbox / Scrollbar
parts_list = Listbox(root, height=12, width=86, borderwidth=3)
parts_list.grid(row=0, column=0, pady=10, padx=10)
scrollbar = Scrollbar(root)
scrollbar.grid(row=0, column=1)
#Set Scroll to Listbox
parts_list.configure(yscrollcommand=scrollbar.set)
scrollbar.configure(command=parts_list.yview)
#Populate Listbox
for x in range(20):
parts_list.insert(END, 'Lorem Ipsum' + str(x))
root.mainloop()
A:
Apply sticky=NS to the scrollbar widget, Try this:
from tkinter import *
root = Tk()
#Define and Grid Listbox / Scrollbar
parts_list = Listbox(root, height=12, width=86, borderwidth=3)
parts_list.grid(row=0, column=0, columnspan=1)
scrollbar = Scrollbar(root)
scrollbar.grid(row=0,column=1,sticky=NS)
#Set Scroll to Listbox
scrollbar.configure(command=parts_list.yview)
parts_list.configure(yscrollcommand=scrollbar.set)
#Populate Scrollbar
for x in range(20):
parts_list.insert(END, 'Lorem Ipsum' + str(x))
root.mainloop()
| {
"pile_set_name": "StackExchange"
} |
Q:
Reflective and Constant Flux Boundary Conditions
Can anyone tell me how I can use NDSolveValue to model reflective and constant heat flux boundary conditions. I am solving the heat equation. Essentially I have a PDE that is dependent on time, radius, and axial length. I want to solve it such that the spatial derivative of the temperature is equal to 0 on one boundary and equal to a constant on another boundary. Can anyone explain how I can set up NDSolveValue with these types of boundary conditions? I don't think it can be achieved using NeumannValue because that just sets the entire differential equation to a value. I have tried a lot of different approaches but nothing seems to be working for me. Can anyone please recommend a way to achieve this?
Edit: Here is some code
tf = 50; Ti = 100;
Ls = 250; Lito = 5; Lsl = 230;
Ltot = Ls + Lito + Lsl;
R = 1500; k = 1;
eqn = r*\!\(
\*SubscriptBox[\(∂\), \(t\)]\(T[t, r, z]\)\) - r*k*\!\(
\*SubscriptBox[\(∂\), \(z, z\)]\(T[t, r, z]\)\) - k*\!\(
\*SubscriptBox[\(∂\), \(r\)]\(T[t, r, z]\)\) - k*r*\!\(
\*SubscriptBox[\(∂\), \(r, r\)]\(T[t, r, z]\)\);
Subscript[Γ, D] = {DirichletCondition[T[t, r, z] == Ti, z == Ltot],
DirichletCondition[T[t, r, z] == Ti, r == R]};
BCr = NDSolveValue[{eqn == 0, Subscript[Γ, D], \!\(
\*SubscriptBox[\(∂\), \(r\)]\(T[t, 0, z]\)\) == 0, \!\(
\*SubscriptBox[\(∂\), \(z\)]\(T[t, r, 0]\)\) == -100,
T[0, r, z] == Ti}, T, {t, 0, tf}, {r, 0, R}, {z, 0, Ltot}];
A:
With v[x, t] the dependent variable, and x the spatial independent variable ranging from x1 to x2, the requested boundary conditions are,
v[x1, t] == 0
(D[v[x, t], x] /. x -> x2) == 0
In answer to the OP's comment below, these and any other boundary and initial conditions are included in the first argument of NDSolveValue, as illustrated by several of the Basic Examples in the documentation.
Edit
As noted in my comment below, the question's recently added code can be made to work with the change,
r0 = .1;
BCr = NDSolveValue[{eqn == 0, Subscript[Γ, D], (D[T[t, r, z], z] /. z -> 0) == 0,
(D[T[t, r, z], r] /. r -> r0) == 0, T[0, r, z] == Ti}, T, {t, 0, tf},
{r, r0, R}, {z, 0, Ltot}]
For the parameters chosen in the question, BCr is equal to Ti everywhere.
| {
"pile_set_name": "StackExchange"
} |
Q:
select a 'virtual' column computed from other existing columns
Is it possible in sql/sqlite3 to perform a select where the column doesnt exist but is the computed result of other columns?
e.g. Given a table with columns max and current, I would like to perform a select on the diffrence of between the two so if I had:
table_data:
max|current
10|3
12|8
select ???? from table_data order by ????? asc;
desired result:
4
7
sqlite3 grammar here http://www.sqlite.org/lang_expr.html but cant make sense of it
A:
select `max` - `current` as `result` from table_data order by `result` asc
| {
"pile_set_name": "StackExchange"
} |
Q:
How to transparent remove image shadow
I have a html code with css
<style>
#lightbox {
position:fixed; /* keeps the lightbox window in the current viewport */
top:0;
left:0;
width:100%;
height:100%;
background:url(overlay.png) repeat;
text-align:center;
}
#lightbox p {
text-align:right;
color:#fff;
margin-right:20px;
font-size:12px;
}
#lightbox img {
box-shadow:0 0 25px #111;
-webkit-box-shadow:0 0 25px #111;
-moz-box-shadow:0 0 25px #111;
max-width:940px;
}
</style>
and in my html I have a .png logo image which is transparent the logo image is showing showed to it, and I want to remove that showed.
Please suggest me a solution.
A:
You should remove these lines from your css:
#lightbox img {
box-shadow: 0 0 25px rgb(17, 17, 17);
-webkit-box-shadow: 0 0 25px rgb(17, 17, 17);
-moz-box-shadow: 0 0 25px #111;
}
Or add these lines after that
#lightbox img {
box-shadow: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculate total data from several tables and groups by date
i've 3 tables
equipment1
+-------------+-------------+-------------+
| id_skt1 | status_kt1 | tgl_skt1 |
+-------------+-------------+-------------+
| 1 | ON | 2019-07-23 |
+-------------+-------------+-------------+
| 2 | ON | 2019-07-23 |
+-------------+-------------+-------------+
| 3 | ON | 2019-07-24 |
+-------------+-------------+-------------+
equipment2
+-------------+-------------+-------------+
| id_skt2 | status_kt2 | tgl_skt2 |
+-------------+-------------+-------------+
| 1 | ON | 2019-07-23 |
+-------------+-------------+-------------+
| 2 | OFF | 2019-07-23 |
+-------------+-------------+-------------+
| 3 | ON | 2019-07-25 |
+-------------+-------------+-------------+
equipment3
+-------------+-------------+-------------+
| id_skt3 | status_kt3 | tgl_skt3 |
+-------------+-------------+-------------+
| 1 | OFF | 2019-07-25 |
+-------------+-------------+-------------+
| 2 | ON | 2019-07-26 |
+-------------+-------------+-------------+
| 3 | ON | 2019-07-26 |
+-------------+-------------+-------------+
| 4 | ON | 2019-07-27 |
+-------------+-------------+-------------+
| 5 | ON | 2019-07-27 |
+-------------+-------------+-------------+
| 6 | ON | 2019-07-27 |
+-------------+-------------+-------------+
how to count all status "ON" on these tables and group by date?
I have searched the website SO but i haven't found a similar problem
i've tried using this code:
SELECT (SELECT COUNT(*) FROM status_kt1 WHERE status_kt1="ON") as T1, (SELECT COUNT(*) FROM status_kt2 WHERE status_kt2="ON") as T2, (SELECT COUNT(*) FROM status_kt3 WHERE status_kt3="ON") as T3
I have searched the website so but did not find a similar problem
I want the results like this:
+-------------+-------------+
| tgl_all |totalStatusOn|
+-------------+-------------+
| 2019-07-23 | 3 |
+-------------+-------------+
| 2019-07-24 | 1 |
+-------------+-------------+
| 2019-07-25 | 1 |
+-------------+-------------+
| 2019-07-26 | 2 |
+-------------+-------------+
| 2019-07-27 | 3 |
+-------------+-------------+
regards :)
A:
Concatenate all tables and select from the resulting one:
select tgl_all, count(tgl_all) as totalStatusOn from (
select status_kt1 as status, tgl_skt1 as tgl_all from equipment1
union all select status_kt2 as status, tgl_skt2 as tgl_all from equipment2
union all select status_kt3 as status, tgl_skt3 as tgl_all from equipment3) t
where status='ON' group by tgl_all;
tgl_all totalStatusOn
2019-07-23 3
2019-07-24 1
2019-07-25 1
2019-07-26 2
2019-07-27 3
Btw, it seems like a bad design, it would be better if you had only one table with additional field for equipment kind.
| {
"pile_set_name": "StackExchange"
} |
Q:
Plot a 3D-plane in Matlab?
How can I plot a 3D-plane at specific point in Matlab?
Consider the plane equation
Z=(-a * X - b * Y)/c
with following coefficients:
a=0.01; b=0.03; c= 1; d=0.
I want to plot this plane around point (100,100) not at origin (0,0). How it possible to do that?
The code I used:
[X,Y] = meshgrid(x);
a=0.1;
b=0.2;
c=1;
d=0;
Z=(-a * X - b * Y)/c;
surf(X,Y,Z)
shading flat
xlabel('x')
ylabel('y')
zlabel('z')
A:
surf() just plots whatever set of points you give it. To generate those points, you're evaluating the equation at a specific set of coordinates given by X and Y. Therefore you want those points to be centred around the region of interest:
[X, Y] = meshgrid(95:0.1:105); % e.g. +/-5 at resolution of 0.1
or, say, for arbitrary view coordinates m,n:
[X, Y] = meshgrid(m-20:m+20, n-20:n+20); % e.g. +/-20 at resolution of 1
That gives you the view around 100,100 of a plane centred at the origin, which I think is what you're asking for.
Alternatively if you want the plane itself centred at 100,100, then you need that offset in the equation:
Z=(-a * (X - 100) - b * (Y - 100))/c;
so then a view centred on the origin will be equivalent to viewing the original plane around -100,-100.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the canonical way to make a function accept any permutation of its argument list?
Suppose I have
class A,B,C;
const A a_def;
const B b_def;
const C c_def;
void f(A a=a_def, B b=b_def, C c=c_def);
This does, if I want to use the default parameters, only allow me to omit either just c, or b and c, or all three of them – but not just a or b alone. However, as the argument types cannot be mixed up, it would be completely unabiguous to call f(A(), C()), (or in fact f(B(), C(), A()): the order of arguments is arbitrary and actually meaningless).
To enable these alternative ways of calling the function, I now tend to overload every permutation manually
void f(A a, C c, B b=b_def) { f(a,b,c); }
void f(B b, A a=a_def, C c=c_def) { f(a,b,c); }
void f(B b, C c, A a=a_def) { f(a,b,c); }
void f(C c, A a=a_def, B b=b_def) { f(a,b,c); }
void f(C c, B b, A a=a_def) { f(a,b,c); }
which is acceptable for just three parameters (3!=6 permutations) but gets tedious at four (4!=24 permutations) and out of bounds at five parameters (5!=120 permutations).
Is there any way to get this functionality automatically, without actually having to do all the overloads, for instance by means of variable argument lists or some kind of template metaprogramming?
A:
Look into the Boost.Parameters Library. It uses some template heavy lifting to get it to work. http://www.boost.org/doc/libs/1_37_0/libs/parameter/doc/html/index.html
It works basically by making your 'named' parameters into types that can be created, and assigned.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to bypass model_save_before observers?
I have a strange issue which I think I narrowed down to observers occasionally not being triggered.
Situation:
An Observer for sales_order_invoice_save_before (in the global node), serializes some custom attributes. In most cases, this works fine, but in ~5% of the cases I get the string Array in sales_flat_order_invoice, as if the observer was not triggered.
I did not find out yet, what these orders/invoices have in common, but I want to be sure that I am on the right track and the issue isnt't somewhere else.
Question:
In which cases is it possible that models are saved without dispatching their {$eventPrefix}_save_before event? I can only imagine raw SQL queries but maybe I am missing something?
A:
It looks like this is actually not possible. The observed behavior might have been a side effect of another observer that was registered for the same event.
| {
"pile_set_name": "StackExchange"
} |
Q:
Saving Image From DataGridViewImage to the Database
I'm trying to save my images located in my datagrid with ColumnType of "DataGridViewImageColumn" passing thru class and to the class query that I have.
Here's my code.
// Class name
public byte[] Image;
// Getting the value image from datagridview
int i;
for(...){
byte[] image = (byte[])dgv.Rows[i].Cells[7].Value;
MemoryStream ms = new MemoryStream(image);
belsalesquote.Image = Image.FromStream(ms);
}
Error List says "Cannot Implicitly convert type 'System.Drawing.Image' to 'byte[]'
My column type inside my database is equal to 'image'.
A:
You cant direct convert image to byte
//byte[] image = (byte[])dgv.Rows[i].Cells[7].Value;
Image image = (Image)dgv.Rows[i].Cells[7].Value;
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
}
So you can save [base64String] to your db
| {
"pile_set_name": "StackExchange"
} |
Q:
boost asio async_connect success after close
Single-threaded application.
It happens not every time, only after 1.5 hours of high load.
tcp::socket::async_connect
tcp::socket::close (by deadline_timer)
async_connect_handler gives success error_code (one of a million times), but socket is closed by(2). 99.999% of time it gives errno=125 (ECANCELED).
Is it possible that socket implementation or boost asio somehow do this:
async_connect
async success posted to io_service
close by timer
async success handled by me, not affected by close
Right now solved by saving state in my variables, ignoring accept success.
Linux 2.6 (fedora).
Boost 1.46.0
PS: ofcouse possible bug on my part... But runs smoothly for days if not this.
A:
As Igor mentions in the comments, the completion handler is already queued.
This scenario is the result of a separation in time between when an operation executes and when a handler is invoked. The documentation for io_service::run(), io_service::run_one(), io_service::poll(), and io_service::poll_one() is specific to mention handlers, and not operations. In the scenario, the socket::async_connect() operation and deadline_timer::async_wait() operation complete in the same event loop iteration. This results in both handlers being added to the io_service for deferred invocation, in an unspecified order.
Consider the following snippet that accentuates the scenario:
void handle_wait(const boost::system::error_code& error)
{
if (error) return;
socket_.close();
}
timer_.expires_from_now(boost::posix_time::seconds(30));
timer_.async_wait(&handle_wait);
socket_.async_connect(endpoint_, handle_connect);
boost::this_thread::sleep(boost::posix_time::seconds(60));
io_service_.run_one();
When io_service_.run_one() is invoked, both socket::async_connect() and deadline_timer::async_wait() operations may have completed, causing handle_wait and handle_connect to be ready for invocation from within the io_service in an unspecified order. To properly handle this unspecified order, additional logic need to occur from within handle_wait() and handle_connect() to query the current state, and determine if the other handler has been invoked, rather than depending solely on the status (error_code) of the operation.
The easiest way to determine if the other handler has invoked is:
In handle_connect(), check if the socket is still open via is_open(). If the socket is still open, then handle_timer() has not been invoked. A clean way to indicate to handle_timer() that handle_connect() has ran is to update the expiry time.
In handle_timer(), check if the expiry time has passed. If this is true, then handle_connect() has not ran, so close the socket.
The resulting handlers could look like the following:
void handle_wait(const boost::system::error_code& error)
{
// On error, return early.
if (error) return;
// If the timer expires in the future, then connect handler must have
// first.
if (timer_.expires_at() > deadline_timer::traits_type::now()) return;
// Timeout has occurred, so close the socket.
socket_.close();
}
void handle_connect(const boost::system::error_code& error)
{
// The async_connect() function automatically opens the socket at the start
// of the asynchronous operation. If the socket is closed at this time then
// the timeout handler must have run first.
if (!socket_.is_open()) return;
// On error, return early.
if (error) return;
// Otherwise, a connection has been established. Update the timer state
// so that the timeout handler does not close the socket.
timer_.expires_at(boost::posix_time::pos_infin);
}
Boost.Asio provides some examples for handling timeouts.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I skip an eunit test?
I wonder how to mark a specific test in eunit in a way that will force it to be ignored (ie compiled, but not executed) on the next test run. I'm asking this question in a TDD context, ie I'd like to refactor in the green, but still have some test cases that I'll get to later.
I'd rather not comment-out the test, that is a good way of forgetting about it. eunit's test summary line does have a skipped line, but I could not find any docs about that functionality.
A:
You can temporarily remove '_test' suffix from test's name (or add any other, e.g. '_ignore'). It will compile, but won't show up in the summary (as it will be treated like a regular function and thus will be ignored by eunit).
This is a workaround of course, eunit should support such functionality, but I'm afraid it doesn't.
EUnit's notion of "skipped" means that something prevented the test from running, such as a compilation failure, the node that was in charge of the test crashing, or the setup failing.
This concept is pretty deeply embedded in the code, so there's no simple way to get user-skipped tests.
| {
"pile_set_name": "StackExchange"
} |
Q:
Chaining functions of type IO (Maybe a )
I am writing a small library for interacting with a few external APIs. One set of functions will construct a valid request to the yahoo api and parse the result to a data type. Another set of functions will look up the users current location based on IP and return a data type representing the current location. While the code works, it seems having to explicitly pattern match to sequence multiple functions of type IO (Maybe a).
-- Yahoo API
constructQuery :: T.Text -> T.Text -> T.Text
constructQuery city state = "select astronomy, item.condition from weather.forecast" <>
" where woeid in (select woeid from geo.places(1)" <>
" where text=\"" <> city <> "," <> state <> "\")"
buildRequest :: T.Text -> IO ByteString
buildRequest yql = do
let root = "https://query.yahooapis.com/v1/public/yql"
datatable = "store://datatables.org/alltableswithkeys"
opts = defaults & param "q" .~ [yql]
& param "env" .~ [datatable]
& param "format" .~ ["json"]
r <- getWith opts root
return $ r ^. responseBody
run :: T.Text -> IO (Maybe Weather)
run yql = buildRequest yql >>= (\r -> return $ decode r :: IO (Maybe Weather))
-- IP Lookup
getLocation:: IO (Maybe IpResponse)
getLocation = do
r <- get "http://ipinfo.io/json"
let body = r ^. responseBody
return (decode body :: Maybe IpResponse)
-- Combinator
runMyLocation:: IO (Maybe Weather)
runMyLocation = do
r <- getLocation
case r of
Just ip -> getWeather ip
_ -> return Nothing
where getWeather = (run . (uncurry constructQuery) . (city &&& region))
Is it possible to thread getLocation and run together without resorting to explicit pattern matching to "get out" of the Maybe Monad?
A:
You can happily nest do blocks that correspond to different monads, so it's just fine to have a block of type Maybe Weather in the middle of your IO (Maybe Weather) block.
For example,
runMyLocation :: IO (Maybe Weather)
runMyLocation = do
r <- getLocation
return $ do ip <- r; return (getWeather ip)
where
getWeather = run . (uncurry constructQuery) . (city &&& region)
This simple pattern do a <- r; return f a indicates that you don't need the monad instance for Maybe at all though - a simple fmap is enough
runMyLocation :: IO (Maybe Weather)
runMyLocation = do
r <- getLocation
return (fmap getWeather r)
where
getWeather = run . (uncurry constructQuery) . (city &&& region)
and now you see that the same pattern appears again, so you can write
runMyLocation :: IO (Maybe Weather)
runMyLocation = fmap (fmap getWeather) getLocation
where
getWeather = run . (uncurry constructQuery) . (city &&& region)
where the outer fmap is mapping over your IO action, and the inner fmap is mapping over your Maybe value.
I misinterpreted the type of getWeather (see comment below) such that you will end up with IO (Maybe (IO (Maybe Weather))) rather than IO (Maybe Weather).
What you need is a "join" through a two layer monad stack. This is essentially what a monad transformer provides for you (see @dfeuer's answer) but it is possible to write this combinator manually in the case of Maybe -
import Data.Maybe (maybe)
flatten :: (Monad m) => m (Maybe (m (Maybe a))) -> m (Maybe a)
flatten m = m >>= fromMaybe (return Nothing)
in which case you can write
runMyLocation :: IO (Maybe Weather)
runMyLocation = flatten $ fmap (fmap getWeather) getLocation
where
getWeather = run . (uncurry constructQuery) . (city &&& region)
which should have the correct type. If you are going to chain multiple functions like this, you will need multiple calls to flatten, in which case it maybe be easier to build a monad transformer stack instead (with the caveat's in @dfeuer's answer).
There is probably a canonical name for the function I've called "flatten" in the transformers or mtl libraries, but I can't find it at the moment.
Note that the function fromMaybe from Data.Maybe essentially does the case analysis for you, but abstracts it into a function.
A:
Some consider this an anti-pattern, but you could use MaybeT IO a instead of IO (Maybe a). The problem is that you only deal with one of the ways getLocation can fail—it could also throw an IO exception. From that perspective, you might as well drop the Maybe and just throw your own exception if decoding fails, catching it wherever you like.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you do a power in Matlab
How do I do this question in Matlab:
4^3^2
Should the answer be 4069
A:
Sounds like you are doing homework. Let's walk through the way to do this.
What does 4^3^2 mean, exactly?
Well, 4^3 means 4 raised to the 3rd power, or 4*4*4.
Then we need to raise that to the 2nd power (^2).
4^3 = 4 x 4 x 4 = 16 x 4 = 64
4^3^2 = 64^2 = 64 x 64 = 4096
The simplest way to do this in MATLAB would be to type exactly 4^3^2 in the command line.
To check the answer MATLAB gives you, you should perform the calculation in a different way using a calculator. This allows you to ensure that not only is your answer correct, but that you understand the arithmetic behind it.
| {
"pile_set_name": "StackExchange"
} |
Q:
PostgreSQL collapse multiple rows as one custom named
I'm trying to collapse multiple rows in PostgreSQL.
I'm counting the 'page views' of specific pages in a web application over the last month.
SELECT DISTINCT page_urlpath AS "URL",
COUNT(DISTINCT (domain_userid)) AS "Unique views"
FROM "atomic".events
WHERE derived_tstamp > current_date - integer '31'
GROUP BY 1
ORDER BY 2 DESC
Output would look something like this:
/title/342fer243r
/title/1rf3f134r4
/title/141f14r1tr
And I would like to end up with:
/title/subtitle
I'm unsure how to perfect my query to collapse all rows with
/title/*
into just one custom named row.
** UPDATE **
I was thinking something like:
SELECT DISTINCT Regexp_replace( page_urlpath, 'title/(*)', 'title/subtitle' ) AS "URL",
Count(DISTINCT (domain_userid)) AS "Unique views"
FROM "atomic".events
WHERE derived_tstamp > CURRENT_DATE - integer '31'
GROUP BY 1
ORDER BY 2 DESC ;
But I know that the "all" part doesn't work. 'title/(*)',. Any good ideas?
A:
One thing you can do is have a mapping table that maps url patterns to the page you want to report on. This can be a CTE if you don't want to create an actual database table.
For example:
CREATE TABLE events (
page_url varchar,
derived_tstamp timestamp,
domain_userid int);
insert into events values
('/title/item1',current_timestamp,1),
('/title/item1',current_timestamp,2),
('/title/item2',current_timestamp,3),
('/title/item3',current_timestamp,1),
('/home/user1',current_timestamp,1),
('/home/user2',current_timestamp,2),
('/home/user3',current_timestamp,3),
('/order/order1',current_timestamp,1),
('/order/order2',current_timestamp,1);
WITH pages (prefix,page) AS (
VALUES ('/title/','/title/subtitle'),
('/home/','Home Page'),
('/order/','/order/*')
)
SELECT
pages.page as "Page",
count(distinct (domain_userid)) as "Unique Views"
FROM
events e
INNER JOIN pages ON LEFT(page_url, LENGTH(pages.prefix)) = pages.prefix
WHERE
derived_tstamp > current_date - 31
GROUP BY pages.page
ORDER BY 2 DESC
Here the pages CTE maps prefixes '/title/','/home/' etc, to a page name that we're going to show in the results.
It does a simple string comparison to check if the url matches the prefix, and if so uses that name instead of the url.
This does have the side effect that any URL that doesn't match any pattern won't show up though.
Fiddle at: http://sqlfiddle.com/#!15/d6279/3
| {
"pile_set_name": "StackExchange"
} |
Q:
$e^{i\theta}$ $=$ $\cos \theta + i \sin \theta$, a definition or theorem?
My question is simply whether the well-known formula $e^{i \theta}$ $=$ $\cos \theta$ $+$ $i \sin \theta$ a definition or there is some proof of the result.
It seems to me that the formula is a definition (as is the case with the definition of $e$ from which the definition of $e^x$ can easily be derived). But if I try to form the definition in the same manner I have to us the definition from Complex Analysis. Is there any way to prove the result without using any ideas from Complex Analysis?
A:
It's a theorem.
Assuming that $e^z$ is defined as $\sum\limits_{n=0}^{\infty}\frac{z^n}{n!}$ (remember that there are a few ways of defining $e$), we have:
$$e^{i\theta}:=1+i\theta+\frac{\theta^2i^2}{2!}+\frac{\theta^3i^3}{3!}+\frac{\theta^4i^4}{4!}+\frac{\theta^5i^5}{5!}+\cdots=$$
Simplifying this, we find that $$\boxed{e^{i\theta}\equiv1+i\theta-\frac{\theta^2}{2!}-\frac{i\theta^3}{3!}+\frac{\theta^4}{4!}+\frac{i\theta^5}{5!}-\cdots}$$
Now, $\color{blue}{\underbrace{\cos(\theta)=1-\frac{\theta^2}{2!}+\frac{\theta^4}{4!}-\frac{\theta^6}{6!}+\cdots}_{\text{Taylor expansion of} \cos(\theta)}}$.
Also, $\underbrace{\sin(\theta)=\theta-\frac{\theta^3}{3!}+\frac{\theta^5}{5!}-\frac{\theta^7}{7!}+\cdots}_{\text{Taylor expansion of} \sin(\theta)}\iff \color{green}{i\sin(\theta)=i\theta-\frac{i\theta^3}{3!}+\frac{i\theta^5}{5!}-\frac{i\theta^7}{7!}+\cdots}$.
Now, $\color{blue}{\cos(\theta)}\color{\green}{+i\sin(\theta)}=\color{blue}{1}\color{green}{+i\theta}\color{blue}{-\frac{\theta^2}{2!}}\color{green}{-\frac{i\theta^3}{3!}}\color{blue}{+\frac{\theta^4}{4!}}\color{green}{+\frac{i\theta^5}{5!}}\color{blue}{-}\cdots=e^{i\theta}$.
A:
It depends on how you define $e$, $\cos$, and $\sin$!
You can define
$$ e^{i\theta} = \cos(\theta) + i\sin(\theta).$$
In that case, you need to go on and show that your other definition of the exponential for real numbers gives you an equivalent result when extended to the entire complex plane.
Alternatively, you can define
$$ e^z = \sum_{n=0}^\infty \frac{z^n}{n!}.$$
In this case, you need to prove (or define!) the infinite series expansions of $\cos$ and $\sin$, show that everything always converges, then show that when restricted to a purely imaginary argument, $e^{i\theta} = \cos(\theta) + i\sin(\theta).$
A:
I think if one sets up analysis for aiming at economy of definition (rather than pedagogy), it would be natural to introduce the exponential function first (through the differential equation $f'=f$, or by its series) and then define cosine and sine by
$$
\cos(z)=\frac{\exp(z)+\exp(-z)}2
\qquad\text{and}\qquad
\sin(z)=\frac{\exp(z)-\exp(-z)}{2\mathbf i}.
$$
Now your result is a theorem, but a pretty obvious one proved by elementary algebra from the definitions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Json strings to Json array
Good day!
I have an array of json objects like this :
[{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
},
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}]
For some reasons I need to split then to each element and save to storage. In the end I have many objects like
{ "senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
}
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}
After some time I need to combine some of them back into json array.
As I can see - I can get objects from storage, convert them with Gson to objects, out objects to a list, like this:
String first = "..."; //{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":0}
String second = "...";//{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":4}
BaseMessage msg1 = new Gson().fromJson(first, BaseMessage.class);
BaseMessage msg2 = new Gson().fromJson(second, BaseMessage.class);
List<BaseMessage> bmlist = new ArrayList<>();
bmlist.add(msg1);
bmlist.add(msg2);
//and then Serialize to json
But I guess this is not the best way. Is there any way to combine many json-strings to json array? I rtyed to do this:
JsonElement elementTm = new JsonPrimitive(first);
JsonElement elementAck = new JsonPrimitive(second);
JsonArray arr = new JsonArray();
arr.add(elementAck);
arr.add(elementTm);
But JsonArray gives me escaped string with json - like this -
["{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":4
}","
{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":0
}"]
How can I do this?
Thank you.
A:
At the risk of making things too simple:
String first = "...";
String second = "...";
String result = "[" + String.join(",", first, second) + "]";
Saves you a deserialization/serialization cycle.
| {
"pile_set_name": "StackExchange"
} |
Q:
xcode 7 beta stuck at "Running xxxxx WatchKit App on iPhone 6"
I recently tried to build new watch os 2 watch app. However, my Xcode 7 beta is not working. I tried reinstalled already. It still doesn't work. It basically stuck at "Running xxxxx WatchKit App on iPhone 6" every time I tried to run it on the watch and iPhone simulators.
A:
I turned off the watch app in the iPhone setting
| {
"pile_set_name": "StackExchange"
} |
Q:
Select partial ID name in javascript
I have an asp.net webform where I include the following script (on a separate .js file):
function pageLoad() {
var mpe = $find("mpeEmpresa");
mpe.add_shown(onShown);
$addHandler(document, "keydown", onKeyDown);
}
function onShown() {
var background = $find("mpeEmpresa")._backgroundElement;
background.onclick = function() {
$find("mpeEmpresa").hide();
}
}
Unfortunately, it won't work because asp.net 3.5 changes the elements id's. The only way I could get it to work is to use ctl00_ContentPlaceHolder1_empresaFilha_mpeEmpresa as the ID.
Sure I could use <%= mpeEmpresa.ClientID %> from the asp.net side, it would work but I'll have to pass that as a var to my external .js file and it's not exactly what I'm trying to accomplish.
I have searched on a few ways to select the element by it's ID name partially, but couldn't get any of them to work... Is there a guaranteed way?
A:
I can see the JQuery tag on your question, so you can easily use this:
$('div[id*="mpeEmpresa"]')
As i know the ContentPlaceHolders are rendered as div.
Update:
If you need to select empresaFilha too so you can't use the above selector.
because $('div[id*="mpeEmpresa"]') select both of ctl00_ContentPlaceHolder1_empresaFilha and ctl00_ContentPlaceHolder1_empresaFilha_mpeEmpresa.
so you need to use this:
Select only mpeEmpresa:
$('div[id*="mpeEmpresa"]').css("background-color","blue");
Select only empresaFilha:
$('div[id*="mpeEmpresa"]').parent('div[id*="empresaFilha"]').css("background-color","red");
Or something like this, maybe this code isn't so optimized because i don't see your ASP code or rendered HTML so have to provide a general solution.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fixtures to popualte ManyToOne field from csv data
The entity category has a ManyToOne relation with type so each category has one type, and each type can relate to many categories.
I loaded the type form a csv as follows :
$types = fopen(__DIR__.'/types.csv','r');
while (!feof($types)){
$line = fgetcsv($types);
$data = str_getcsv($line[0],';');
$t[$i] = new Type();
$t[$i]->setIdType($data[0]);
$t[$i]->setDescription($data[1]);
$manager->persist($t[$i]);
$manager->flush();
$i++;
}
fclose($agregatnational);
Now I have to load the categories the same way : reading from a csv and inserting the values to a relation field without breaking the relation (read the id from the csv then search for the type object that has this id, map that object to the current category).
Keep in mind that I can't generate random id's.
Can someone help please ?
A:
I don't know how your classes look like, but it seem like you save the original Id of the type in a field called idType. If that's the case you can use ist to get the persisted entity:
$categories = fopen(__DIR__.'/categories.csv','r');
while (!feof($categories)){
$line = fgetcsv($categories);
$data = str_getcsv($line[0],';');
$type = $manager->getRepository('Type::class')->findOneBy(['idType' => data[1]);
$new = new Category();
$new->setType($type);
$new->setName($data[0);
$manager->persist($new);
$manager->flush();
$i++;
}
I hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Distance from great circle to North pole
Suppose a great circle passes through a plane with normal $[a,2a,3a]$, so by converting it to a unit vector, the normal of the plane is $\frac{1}{\sqrt{14a^2}}[a,2a,3a]$.
My teacher explained that the distance between the great circle (that passes through the above mentioned plane) and the North Pole $(0,0,1)$ is the latitutde of the unitary normal vector of the plane. (We are only considering the unit sphere)
Hence, the distance is $arcssin(\frac{3a}{\sqrt{14a^2}})$. Why is this so? Did she write something wrong?
A:
Your teacher is correct.
Let $\mathbf{n}$ is your normal. If $\mathbf{n}\cdot\mathbf{N}=1$ then the circle is the equator and $\mathbf{n}=\mathbf{N}$ has latitude $\pi/2$.
So assume $\mathbf{n}\cdot\mathbf{N}\in[0,1)$. There is a unique closet point $\mathbf{P}$ to $\mathbf{N}$ which is the rotation of $\mathbf{n}$ by an angle of $\pi/2$ in the plane containing $\mathbf{N}$ and $\mathbf{n}$ (orientation chosen so that the course of rotation by $\theta\in[0,\frac\pi2]$ passes through $\mathbf{N}$).
Then
$$
d(\mathbf{N},\mathbf{P})+d(\mathbf{N},\mathbf{n})=\frac\pi2
$$
and you know $d(\mathbf{N},\mathbf{n})=\arccos(\mathbf{N}\cdot\mathbf{n})=\arccos n_z$.
Hence $d(\mathbf{N},\mathbf{P})=\arcsin n_z$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Securing outgoing emails with logs of a web server
On the web server I am going to run rkhunter, tripwire, OSSEC, fail2ban and psad. All of those applications need to be able to send emails to notify the sysadmin.
Therefore, I've:
sudo apt-get install -y mailutils postifx
Then I configured postfix to catch mails sent to root@localhost and send those mails to [email protected] :
sudo nano /etc/aliases
and I have added this alias (after postmaster: root):
root: [email protected]
I have allowed outgoing traffic on port 25/tcp (since my default UFW policy is DROP on both INPUT, OUPUT and FORWARD)
sudo ufw allow out 25/tcp
I am now able to send-only emails, and I am going to use postifx/mail only for those applications listed aboIve, while I will use PHPMailer for the web application itself (login notifications, email verification, password change notification, etc, etc).
At this point, I wonder:
Is postfix/mail, as I set it above, a safe way to send logs in terms of security? Assuming that an attacker wants to get my logs, how hard will be for him with my current configuration?
Does anyone know a good link where to learn something that can help me in this stuff?
My postfix TLS configuration lines:
smtp_enforce_tls=yes
smtp_use_tls=yes
smtp_tls_security_level=encrypt
smtp_tls_mandatory_ciphers = high
smtp_tls_loglevel = 1
smtp_tls_session_cache_timeout = 3600s
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
tls_random_source = dev:/dev/urandom
smtpd_tls_received_header = yes
smtpd_tls_loglevel = 1
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
A:
The security of your current setup against interception, and consequently possible disclosure and modification, of your mails on their way from your server to the destination mailbox, depends on the security of your server's DNS resolution. If an attacker is able to forge DNS replies to your server she can divert your mails to her own TLS-enabled SMTP server. Your Postfix daemon will log a certificate verification failure but deliver the mail anyway. To protect against that sort of attack you need to use one of the higher smtp_tls_security_level values (dane-only, fingerprint, verify, secure) and/or use DNSSEC.
Security against blocking your mails depends mainly on the reliability and security of your Internet connection, but also of your DNS resolution, and of course on the destination mail server hosting the [email protected] mailbox. For example, if the destination server has an overly strict antispam policy it may be possible to block your mails by falsely reporting your server as a spam source.
Last but not least, once the mails are delivered to the [email protected] mailbox their security depends of course entirely on the security of that mailbox. For example, if an attacker gets hold of the access credentials for that mailbox (through phishing) she can read, delete or replace any mail in it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way with Git to make future merges ignore version number difference in a pom file between branches?
My team is planning to switch from Perforce to Git and I am trying to find a way to make Git ignore pom version differences between branches. This works well in Perforce and I'm not having any luck reproducing the behavior with Git.
Here are my steps:
Checkout parent branch
ndeckard@ws /c/dev/proj/testgit (master)
$ git checkout release/1.0
Switched to branch 'release/1.0'
Your branch is up-to-date with 'origin/release/1.0'.
Create child branch from it
ndeckard@ws /c/dev/proj/testgit (release/1.0)
$ git branch branch/FEA-650
Switch over to new branch
ndeckard@ws /c/dev/proj/testgit (release/1.0)
$ git checkout branch/FEA-650
Switched to branch 'branch/FEA-650'
Update child branch pom version
<version>1.0.0-FEA-650-SNAPSHOT</version>
Add it and commit
ndeckard@ws /c/dev/proj/testgit (branch/FEA-650)
$ git status
On branch branch/FEA-650
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: pom.xml
no changes added to commit (use "git add" and/or "git commit -a")
ndeckard@ws /c/dev/proj/testgit (branch/FEA-650)
$ git add pom.xml
ndeckard@ws /c/dev/proj/testgit (branch/FEA-650)
$ git commit -m "set feature branch pom version"
[branch/FEA-650 59e156e] set feature branch pom version
1 file changed, 1 insertion(+), 1 deletion(-)
Switch back to parent branch
ndeckard@ws /c/dev/proj/testgit (branch/FEA-650)
$ git checkout release/1.0
Switched to branch 'release/1.0'
Your branch is up-to-date with 'origin/release/1.0'.
Merge child branch into parent auto-accepting parent branch version (using the “ours” merge strategy)
ndeckard@ws /c/dev/proj/testgit (release/1.0)
$ git merge branch/FEA-650 -s ours
Merge made by the 'ours' strategy.
Attempt 2nd merge of child into parent (Already up-to-date.) Good. This is what I want
ndeckard@ws /c/dev/proj/testgit (release/1.0)
$ git merge branch/FEA-650
Already up-to-date.
Checkout child and merge parent into child (it fast forwards and sticks the parent branches pom version on the child). Not good. I need it to say "already up-to-date" like above and keep the child branch pom version as it already is on the child branch
ndeckard@ws /c/dev/proj/testgit (release/1.0)
$ git checkout branch/FEA-650
Switched to branch 'branch/FEA-650'
ndeckard@ws /c/dev/proj/testgit (branch/FEA-650)
$ git merge release/1.0
Updating 59e156e..2f3a2a0
Fast-forward
pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
After step 7, I would like merges in either direction between parent and child to say (Already up-to-date.)
Is there a way with Git to make future merges ignore the version number difference in the pom file between branches?
A:
My initial thought is to automate your POM version numbers by partly externalizing the POM <version> computation, see further down in the answer. If you don't want to do that, then you need to re-evaluate your Git workflow.
Merging two-ways, into master and then back into the feature branch causes problems. Your git merge branch/FEA-650 -s ours using the ours strategy tells Git that you have integrated all commits and changes from the feature branch into master, including your pom.xml version change, which is lost, with master retaining its version. The master branch now considers the feature branch's HEAD to be a common ancestor (it's a parent commit on the merge), so when you merge it back into the feature branch, Git says "everything was resolved when you merged to master, there are no changes ... fast-forward".
The simple answer is that you should re-branch to a new feature branch after merging to master, giving your feature branch a new/later youngest common ancestor, then you need to somehow replay your POM <version> change. You should not continue to work on the original feature branch, since it has been merged. To pick up new changes from master you should re-branch. There seems to be some implication that you may have left changes on the feature-branch unmerged with master, otherwise you wouldn't need it anymore and could re-branch, or it might just be the <version> change commit you are interested in.
There's any number of ways to simplify/speed-up/automate the version-number management on re-branching, from externalizing (see below) to cherry-picking it from a placeholder branch, using a Maven plugin e.g. Versions Maven Plugin .
Original answer
Another approach would be to externally calculate the final/effective <version> outside your POM file, based on branch metadata or other input from your CI. This is slightly tricky to do in Maven without pre-munging pom.xml yourself after checkout, but take a look at the Maven External Version Plugin.
It hooks into the Maven lifecycle and will build a pom.xml.new-version file on the fly (which you can .gitignore), dynamically-replacing all or part of the version number, based on whatever you supply - a feature-branch name, git commit hash etc.
Build/deploy the plugin and add it to your POM:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-external-version-plugin</artifactId>
<version>0.1.0-SNAPSHOT</version>
<extensions>true</extensions>
<configuration>
<strategy hint="sysprop"/>
</configuration>
</plugin>
... then get creative with replacing the version-string, for example you can:
mvn install -Dexternal.version-qualifier=$(git symbolic-ref --short HEAD| sed s_^master\$__)
... which will change 1.2.3-SNAPSHOT to 1.2.3-FEA-650-SNAPSHOT if the current checked-out Git branch is FEA-650. You might need to consider replacing / with - in your branch-naming strategy, depending on what Maven thinks of it (I find the /s confusing, but that's just me), or modify the sed accordingly.
At worst this would allow you to remove your version-number from of your POM, so other POM changes can be safely merged and known to be non-version-number related - if necessary you can keep version numbers in another file, using a Maven Properties Plugin to load them and replace the entire version number if required.
| {
"pile_set_name": "StackExchange"
} |
Q:
Firebird 2.1 database is missing the monitor tables can they be added?
I found some Firebird 2.1 databases which are missing the monitor tables ie(MON$ATTACHMENTS).
Is there anyway of adding them?
I tried to insert them, but they appeared as normal tables.
A:
Features like monitoring tables depend on the On-Disk-Structure (ODS) version of the Firebird database. Your database is likely still an old ODS version (11.0 or older, eg Firebird 2.0 or older). You need to backup and restore the database to upgrade it to the ODS of Firebird 2.1 (ODS 11.1). This will add the monitoring tables.
This is also documented in the 2.1.7 release notes, section Monitoring tables:
Virtual monitoring tables exist only in ODS 11.1 (and higher) databases, so a migration via backup/restore is required in order to use this feature.
If you are upgrading, consider upgrading to Firebird 2.5 instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java How do you declare a generic parameter to be any interface
I'm trying to learn some reflection in Java and I've run into a snag. Essentially I'm trying to create a really generic event system. Yes I know there are already many out there but this is more of an exercise in learning than anything practical. Anyway, I keep getting the following error when I declare an Instance of EventSource<PersonnameChangeListener, PersonNameChangeEvent>
error: type argument PersonNameChangeListener is not within bounds of type-variable ListenerT
private EventSource<PersonNameChangeListener,
where ListenerT is a type-variable:
ListenerT extends Class declared in class EventSource
So My question is, "How do I declare that I want a generic parameter to be any interface?"
Thank you in advance,
Jec
public interface PersonNameChangeListener extends EventListener
{
public void nameChangeOccured(PersonNameChangeEvent event);
}
public class PersonNameChangeEvent extends EventObject
{
private String m_OldName;
private String m_NewName;
public PersonNameChangeEvent(Object source,
String oldName,
String newName)
{
super(source);
m_OldName = oldName;
m_NewName = newName;
}
public String getOldName()
{
return m_OldName;
}
public String getNewName()
{
return m_NewName;
}
}
public class EventSource<ListenerT extends Class, EventT>
{
List<ListenerT> m_ListenerList;
public EventSource()
{
m_ListenerList = new ArrayList<>();
}
public void addNameChangeListener(ListenerT listener)
{
m_ListenerList.add(listener);
}
public void removeNameChangeListener(ListenerT listener)
{
m_ListenerList.remove(listener);
}
private void fireNameChangedEvent(EventT event) throws IllegalAccessException,
InvocationTargetException
{
for (ListenerT listener : m_ListenerList)
{
Method[] methods = listener.getDeclaredMethods();
for (Method method : methods)
{
Class<?>[] parameterTypes = method.getParameterTypes();
final int parameterCount = method.getParameterCount();
if (parameterCount == 1
&& parameterTypes[1].getTypeName().compareTo(event.getClass().getTypeName()) == 0)
{
try
{
method.invoke(this, event);
}
catch (IllegalAccessException | InvocationTargetException e)
{
throw e;
}
break;
}
}
}
}
}
A:
There's really no value in declaring ListenerT to be a generic type parameter if you're going to have to reflect on it anyway to get the methods you need. I would remove the type parameter entirely and just use Object.
Important note: Doing it this way only makes sense for learning the reflection API, not for doing this in production. I realize you said that, but I wanted to reemphasize the point.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wating for all finished request in a loop with node request
I use the node request ajax package. So, i have an loop, in every iteration it makes an request to my server.
// realItems needs the complete value of items assigned
var realItems;
var items = [];
_.forEach(JSON.parse(body), (value, key) => {
request('myurl/' + id, (error, response, body) => {
items = JSON.parse(body)
});
});
How can i bundle all my requests from request package, so I can assign the value of items variable to the realItems at the end?
// edit:
I use react js, so in this case realItems is an state, and i can't trigger it in every loop iteration, because render triggers on every setState
A:
There are a number of ways to approach this. Here's a brute force method that does not preserve the order of the results:
var items = [];
var cnt = 0;
_.forEach(JSON.parse(body), (value, key) => {
++cnt;
request('myurl/' + value.id, (error, response, body) => {
items.push(JSON.parse(body));
// if all requesets are done
if (--cnt === 0) {
// process items here as all results are done now
}
});
});
Here's a version that uses Bluebird promises:
var Promise = require('bluebird');
var request = Promise.promisify(require("request"));
Promise.promisifyAll(request);
var promises = [];
_.forEach(JSON.parse(body), (value, key) => {
promises.push(request('myurl/' + value.id));
});
Promise.all(promises).then(function(results) {
// all requests are done, data from all requests is in the results array
// and are in the order that the requests were originally made
});
And, here's a little bit simpler Bluebird promises method that uses a Bluebird iterator:
var Promise = require('bluebird');
var request = Promise.promisify(require("request"));
Promise.promisifyAll(request);
Promise.map(JSON.parse(body), function(value) {
return request('myurl/' + value.id);
}).then(function(results) {
// all requests are done, data is in the results array
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to stream a PDF file as binary to the browser using .NET 2.0
I'm looking for a way to stream a PDF file from my server to the browser using .NET 2.0 (in binary).
I'm trying to grab an existing PDF file from a server path and push that up as binary to the browser.
A:
Here you go: How To Write Binary Files to the Browser Using ASP.NET and Visual C# .NET
A:
Set Content-Type: Response.ContentType = "application/pdf"
Set ContentDisposition, if you want to give a new name for the file: Response.Headers.Add("Content-Disposition", "attachment: filename=file.pdf");
Write the content, using Response.OutputStream as Mr. Kopp said.
Step 2 is not strictly necessary, but it's probably a good idea if you don't want the browser to try to save the PDF with the same name as your ASPX file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can I use conservation of momentum to understand a bag getting dropped on a moving truck, if the ground provides an external force?
Please help me with this sat question from released test
A toy truck with a mass of $0.6$ kg initially coasts horizontally at a speed of $2$ meters per second. A child drops a beanbag with a mass of $0.2$ kg straight down onto the truck. What is the speed of the truck after it?
Attempt:
My teacher told me to use conservation of momentum in the horizontal direction. However, when the beanbag is dropped, isn’t the ground pushing the truck up so that an external force is acting on the system? If not what does an external force mean in momentum conservation as momentum is conserved if and only if no external forces act.
Also, I tried to use the fact that energy is conserved so that $(0.5) (0.6 )2^2 = 0.5 (0.6+0.2) v^2 $ but this doesn’t work. As the correct answer is $1.5$. Why is the kinetic energy not conserved during this collision?
Thank you in advance
A:
isn’t the ground pushing the truck up so that an external force is acting on the system?
Yes, but it is exclusively acting in the vertical direction. (And, indeed, vertical momentum is not conserved, since the vertical momentum of the bag is lost during the collision.) However, there are no external forces with any horizontal components acting on the system, so the horizontal component of momentum is conserved.
Why is the kinetic energy not conserved during this collision?
The collision is quite clearly inelastic, so there is no requirement for kinetic energy conservation.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a library in NetBeans
I have a class Utilities.java that I'd like to turn into a library that I can include in subsequent projects.
I did New project, Java class library and named the class Utilities and put it into the C:\Users\Dov\Google Drive\NetBeansProjects\Utilities folder.
In a new project, I tried to add the library via Libraries, Add jar/folder and gave the name C:\Users\Dov\Google Drive\NetBeansProjects\Utilities\dist\Utilities.jar, so under Libraries I then had JDK 1.8 and Utilities.jar.
But I got errors (cannot find symbol) on all attempts to use methods in Utilities.jar.
What should I have done?
A:
OK. I deleted Utilities.jar from the Libraries folder, then right-clicked Libraries and this time selected Add library..., which opened dialog in which I clicked Create library.
I gave the new library the name Utilties and clicked Add jar/folder,then gave path to jar file: C:\Users\Dov\Google Drive\NetBeansProjects\Utilities\dist\Utilities.jar. Now I have in the Libraries folder a library named Utilities - Utilities.jar and all is well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Objective C & iOS: running a timer? NSTimer/Threads/NSDate/etc
I am working on my first iOS app, and have run in the first snag I have not been able to find a good answer for.
The problem: I have a custom UIGestureRecognizer and have it all wired up correctly, and I can run code for each touch in the @selector after recognition. This has been fine for most things, but it's a little too much input for others.
My goal: To make a timer that triggers at a specified interval to run the logic, and to be able to cancel this at the moment touches are cancelled.
Why I am asking here: There are a lot of possibilities for solutions, but none has stood out as the best to implement. So far it seems like
performSelector (and some variations on this)
NSThread
NSTimer
NSDate
Operation Queues
I think I found some others as well...
From all the research, some form of making a thread seems the route to go, but I am at a loss at which would work best for this situation.
An example of an implementation: an NSPoint is taken every 0.10 seconds, and the distance between the previous and current point is taken. [Taking the distance between every point was yielding very messy results].
The relevant code:
- (void)viewDidLoad {
CUIVerticalSwipeHold *vSwipe =
[[CUIVerticalSwipeHold alloc]
initWithTarget:self
action:@selector(touchHoldMove:)];
[self.view addGestureRecognizer:vSwipe];
[vSwipe requireGestureRecognizerToFail:doubleTap];
}
...
- (IBAction)touchHoldMove:(UIGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
}
if (sender.state == UIGestureRecognizerStateBegan) {
}
//other stuff to do goes here
}
A:
Use an NSTimer
Set it up like this:
theTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(yourMethodThatYouWantRunEachTimeTheTimerFires) userInfo:nil repeats:YES];
Then when you want to cancel it, do something like this:
if ([theTimer isValid])
{
[theTimer invalidate];
}
Note that in the above example you would need to declare the "theTimer" instance of NSTimer where it will be available to both methods. In the above example the "0.5" means that the timer will fire twice a second. Adjust as needed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Synchronizing an Oracle database using "last modified" timestamps in the face of transactions
We've got an enterprise Oracle 12c database that we'd like to synchronize with an analytical database using a Java program (which will be doing a lot of aggregating during the sync), using a per-row "last modified" timestamp in the Oracle database to determine which rows need to be synced. The general algorithm is
void run() {
Timestamp lastRead = loadLastRead(); // load last logged timestamp
while(true) {
rows = select * from Oracle database where last_modified >= lastRead;
lastRead = rows.max(last_modified); // max timestamp from the retrieved rows
saveLastRead(lastRead); // log the timestamp in case the program crashes
sleep(five minutes or whatever);
}
}
My concern is that I might run into the following situation:
Transaction starts on row R1, calculates timestamp of T1
last_modified timestamp T2 written to row R2
Sync using lastRead of T0
Sync ends, lastRead updated to T2
Transaction commits with timestamp T1 < T2 on row R1
And now I'll never sync row R1 (until new data is written to it, assuming I'm not foiled by a transaction again). I can try to minimize the timestamp skew, but I don't see a way to eliminate it.
One solution would be to do something like
lastRead = rows.max(last_modified) - C;
where C is five seconds or some other time span that we don't think that many transactions will exceed - the problem is that with too large a C we'll be re-syncing too much data, and with too small a C we might get some outlier transactions exceeding C
Another solution would be to use a per-row version number, which would require a lot of bookkeeping and would almost certainly hurt the performance of select * from Oracle database
A:
It's true, trying to use a query based on a timestamp column is not a reliable method for picking up changes, unless you introduce a significant delay or system downtime (e.g. running an overnight batch process when concurrent changes are unlikely to be made).
Another method that some have used is to use a monotonically increasing numeric ID column based on an ORDERed Oracle sequence. One problem with this approach may be how ordered sequences perform in a RAC system.
A Materialized View (as suggested by Lalit) would be one option.
Some other options depending on your budget and the complexity of your requirements include:
Change Data Capture
Oracle GoldenGate
Oracle Data Integrator (ODI)
Note: GoldenGate and ODI are complementary products and can work well together.
| {
"pile_set_name": "StackExchange"
} |
Q:
New to SQL - Need help with a query
Table 1: Food
id name
-------
1 Hot-dog
2 Sandwich
3 Apple
Table 2: Report
id food_id date
----------------
1 1 2010-01-01
2 1 2010-02-01
3 2 2011-02-01
How can I devise a query to select all the food in the food table with a variable called numReports which is a total count of all reports that food item has in reports?
What I've been trying:
SELECT
food.id AS foodId,
food.name AS foodName,
count(
SELECT * FROM reports WHERE reports.food_id=food.id
) AS numReports
FROM
food
Output:
id name numReports
-------------------
1 Hot-dog 2
2 Sandwich 1
3 Apple 0
A:
SELECT food.name,
COUNT(*) as food_count
FROM reports
INNER JOIN food ON reports.food_id = food.id
GROUP BY food.name;
| {
"pile_set_name": "StackExchange"
} |
Q:
The verb "dope" here
I am currently read this article, and could someone help me in what sense the verb "dope" is used here?
"This suggests that there's been a massive increase in domestic use of coal and minerals. This is such a crucial export commodity and now that very little of it is being sold abroad, as compared to normal years, domestic industry is probably getting financially doped by cheap energy at the moment given how much of production is still going on," he said.
So would it mean North Korea is administered drugs (cheap energy) like a drug addict?
FYI the definition of the Merriam Unabridged. (Googling didn't help).
1
a : to smear or lubricate with dope
b : to apply dope to (as the fabric of an airplane or balloon)
2
a : to introduce an adulterant into (a food) or an additive into (a fluid)
b : to treat or impregnate with a foreign substance to impart a desired appearance or property : doctor
3
a : to give a stupefying or exhilarating drug to : drug
b : to put a stupefying drug into
c : to administer a drug to (a horse) to increase or decrease speed in a race
d : to induce inaction, apathy, or submissiveness in by a mental diet designed to produce such qualities or attitudes
4
slang : to work out from one's interpretation of available information a forecast about the outcome of (a competition) or the performance or placing of (competitors)
Thank you for your support.
A:
I think the choice of words in the article are rather bad but here is my answer. You should link two words in the part sentence "domestic industry is probably getting financially doped by cheap energy at the moment".
Then taking the definition of the Merriam Unabridged 3b : to put a stupefying drug into.
We can assume the writer is trying to say that the domestic industry is financially insensitive and slow to react because of the cheap energy available.
stupefy (ˈstjuːpɪˌfaɪ)
vb (tr) , -fies, -fying or -fied
1. to render insensitive or lethargic
| {
"pile_set_name": "StackExchange"
} |
Q:
Entries in Tkinter
I'd like to make a program which takes an integer from user and makes as many entries in a Tkinkter window. Then It'll make a graph base on them but for now I do not know how to make as many entries in my window. I tried something like this below but It does not work. Please help.. edit: oh and It's PyDev for Eclipse python 2.75
# -*- coding: utf-8 -*-
#import matplotlib.pyplot as mp
import Tkinter as T, sys
def end():
sys.exit()
def check():
z = e.get()
try:
z = int(z)
e.config(bg = 'green')
e.after(1000, lambda: e.config(bg = 'white'))
x = []
for i in (0,z):
x.append(e = T.Entry(main, justify = 'center'))
x[i].pack()
except:
e.config(bg = 'red')
e.after(1000, lambda: e.config(bg = 'white'))
z = 0
main = T.Tk()
main.title('something')
main.geometry('600x600')
main.config(bg = "#3366ff")
e = T.Entry(main,justify = 'center')
l = T.Label(main,text = 'Give me an N =',bg = '#3366ff')
b1 = T.Button(main, text = 'OK', command = check)
b = T.Button(main,text = 'Zakończ', command = end)
l.pack()
e.pack()
b1.pack()
b.pack()
main.mainloop()
A:
Make youre for-loop look like this:
for i in range(0,z):
x.append( T.Entry(main, justify = 'center'))
x[i].pack()
you need to use range because when you dont it is only iterating through twice because it thinks its iterationg through a 2 item tuple instead of a list of numbers
also get rid of the e = so that it is just appending a new entry each time
| {
"pile_set_name": "StackExchange"
} |
Q:
Direct2d ID2D1HwndRenderTarget->GetSize() returns zero
I've noticed that calling GetSize() on ID2D1HwndRenderTarget returns 0,0 if this call is made after a BeginDraw() call. It returns the correct value otherwise.
Is this "normal" behaviour? I haven't seen it documented in any examples. I did spend a few hours scratching my head over this.
A:
This is a normal behaviour.
In your case, the method returns its const defined return value.
virtual D2D1_SIZE_F GetSize() const = 0;
Most probably, the method fails inside, because the render target could not be "acquired" inside a BeginDraw/EndDraw loop.
BeginDraw and EndDraw are used to indicate that a render target is in
use by the Direct2D system. Different implementations of
ID2D1RenderTarget might behave differently when BeginDraw is called.
An ID2D1BitmapRenderTarget may be locked between BeginDraw/EndDraw
calls, a DXGI surface render target might be acquired on BeginDraw and
released on EndDraw, while an ID2D1HwndRenderTarget may begin batching
at BeginDraw and may present on EndDraw, for example.
Remarks section:
ID2D1RenderTarget::BeginDraw method
| {
"pile_set_name": "StackExchange"
} |
Q:
Tool for request/response visualization
I'm designing some client-server web project with a lot of requests and responses.
So my question is what tool can I use to visualize my request/response map (like UML editors for code designing).
A:
If you want to do it in UML, Enterprise Architect from Sparx Systems has facilities for "Web Modeling", where you model things like pages, servers, forms, etc.
It also supports WSDL 1.1, with forward and reverse engineering, although I haven't tested this myself.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.