text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
What are the London and Chicago schools of TDD?
I’ve been hearing about the London style vs. Chicago style (sometimes called Detroit style) of Test Driven Development (TDD).
Workshop of Utah Extreme Programming User's Group:
Interaction-style TDD is also called mockist-style, or London-style after London's Extreme Tuesday club where it became popular. It is usually contrasted with Detroit-style or classic
TDD which is more state-based.
Jason Gorman's workshop:
The workshop covers both the Chicago school of TDD (state-based
behaviour testing and triangulation), and the London school, which
focuses more on interaction testing, mocking and end-to-end TDD, with
particular emphasis on Responsibility-Driven Design and the Tell,
Don't Ask approach to OO recently re-popularized by Steve Freeman's
and Nat Pryce's excellent Growing Object-Oriented Software Guided By
Tests book.
The post Classic TDD or "London School"? by Jason Gorman was helpful, but his examples confused me, because he uses two different examples instead of one example with both approaches. What are the differences? When do you use each style?
A:
Suppose you have class called "ledger" a method called "calculate" that uses a "Calculator" to do different types of calculations depending on the arguments passed to "calculate", for example "multiply(x, y)" or "subtract(x, y)".
Now, suppose you want to test what happens when you call ledger.calculate("5 * 7").
The London/Interaction school would have you assert whether Calculator.multiply(5,7) got called. The various mocking frameworks are useful for this, and it can be very useful if, for example, you don't have ownership of the "Calculator" object (suppose it is an external component or service that you cannot test directly, but you do know you have to call in a particular way).
The Chicago/State school would have you assert whether the result is 35. The jUnit/nUnit frameworks are generally geared towards doing this.
Both are valid and important tests.
A:
The article Mocks Aren't Stubs, by Martin Fowler is a good introduction to the topic.
Depending on the design style you choose (and the design principles upon which you build your programs), there are at least two ways of seeing an object:
As a unit that performs computations based on inputs. As a result of this computation the object can return a value or change its state.
As an active element that communicates with other elements in the system by message passing.
In the first case, you are interested in what comes out of the processing or in which state the object is left after that processing. This is where methods such as assertEquals() enter the picture. In this case, it does not matter much what other objects were involved in the processing, which methods were called, etc. This kind of verification is called state-based verification and is the "classical" style.
In the second case, since most objects do not even return any result (e.g. void methods in Java), you are more interested in how the objects communicate with each other and if they pass the right messages under the circumstances imposed by the test. These interactions are usually verified with the aid of mock frameworks. This kind of verification is called behavior-based or interaction-based verification. One of its implications is the technique called Behavior Driven Development, by which you develop a class assuming that its collaborators already exist (even though they might not exist yet), so you can code against their interfaces.
Note that this is not an either/or choice. You can have a design style that mix both approaches to get the best out of each.
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting std::vector<>::iterator to .NET interface in C++/CLI
I am wrapping a native C++ class, which has the following methods:
class Native
{
public:
class Local
{
std::string m_Str;
int m_Int;
};
typedef std::vector<Local> LocalVec;
typedef LocalVec::iterator LocalIter;
LocalIter BeginLocals();
LocalIter EndLocals();
private:
LocalVec m_Locals;
};
1) What is the ".NET way" of representing this same kind of interface? A single method returning an array<>? Does the array<> generic have iterators, so that I could implement BeginLocals() and EndLocals()?
2) Should Local be declared as a value struct in the .NET wrapper?
I'd really like to represent the wrapped class with a .NET flavor, but I'm very new to the managed world - and this type of information is frustrating to google for...
A:
Iterators aren't exactly translatable to "the .net way", but they are roughly replaced by IEnumerable < T > and IEnumerator < T >.
Rather than
vector<int> a_vector;
vector<int>::iterator a_iterator;
for(int i= 0; i < 100; i++)
{
a_vector.push_back(i);
}
int total = 0;
a_iterator = a_vector.begin();
while( a_iterator != a_vector.end() ) {
total += *a_iterator;
a_iterator++;
}
you would see (in c#)
List<int> a_list = new List<int>();
for(int i=0; i < 100; i++)
{
a_list.Add(i);
}
int total = 0;
foreach( int item in a_list)
{
total += item;
}
Or more explicitly (without hiding the IEnumerator behind the foreach syntax sugar):
List<int> a_list = new List<int>();
for (int i = 0; i < 100; i++)
{
a_list.Add(i);
}
int total = 0;
IEnumerator<int> a_enumerator = a_list.GetEnumerator();
while (a_enumerator.MoveNext())
{
total += a_enumerator.Current;
}
As you can see, foreach just hides the .net enumerator for you.
So really, the ".net way" would be to simply allow people to create List< Local > items for themselves. If you do want to control iteration or make the collection a bit more custom, have your collection implement the IEnumerable< T > and/or ICollection< T > interfaces as well.
A near direct translation to c# would be pretty much what you assumed:
public class Native
{
public class Local
{
public string m_str;
public int m_int;
}
private List<Local> m_Locals = new List<Local>();
public List<Local> Locals
{
get{ return m_Locals;}
}
}
Then a user would be able to
foreach( Local item in someNative.Locals)
{
...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Applescript Searcher problem
The AppleScript code:
on dialogBox(theMessage)
display dialog theMessage default answer "" buttons {"Cancel", "Search"} default button 2 with title "Pick a search engine"
end dialogBox
dialogBox("Google, YouTube, Wiki, Dictionary, Apple, Adobe, or Google Images")
if text returned of result = "Google" then
set search to text returned of dialogBox("Enter Google Search")
tell application "Google Chrome"
activate
open location "https://www.google.com/?gfe_rd=cr&ei=4fJgVJ6SM8yD8QfJjYGICA&gws_rd=ssl,cr&fg=1#q=" & search
end tell
else if text returned of result = "YouTube" then
set search to text returned of dialogBox("Enter YouTube Search")
tell application "Google Chrome"
activate
open location "https://www.youtube.com/results?search_query=" & search
end tell
else if text returned of result = "Wiki" then
set search to text returned of dialogBox("Enter Word")
tell application "Google Chrome"
activate
open location "http://en.wikipedia.org/wiki/" & search
end tell
else if text returned of result = "Dictionary" then
set search to text returned of dialogBox("Enter Word")
tell application "Google Chrome"
activate
open location "http://Dictionary.Reference.Com/Browse/" & search
end tell
else if text returned of result = "Apple" then
set search to text returned of dialogBox("Enter Apple Search")
tell application "Google Chrome"
activate
open location "http://www.apple.com/search/?q=" & search
end tell
else if text returned of result = "Adobe" then
set search to text returned of dialogBox("Enter Adobe Search")
tell application "Google Chrome"
activate
open location "http://www.adobe.com/cfusion/search/index.cfm?term=" & search
end tell
else if text returned of result = "Google Images" then
set search to text returned of dialogBox("Enter Image Search")
tell application "Google Chrome"
activate
open location "https://www.google.ca/search?site=imghp&tbm=isch&source=hp&biw=1920&bih=890&q=" & search
end tell
end if
The Problem:
At the top, it says ("Google, YouTube, Wiki, Dictionary, Apple, Adobe, or Google Images")
I want to make it so it puts a question mark at the end, like so: ("Google, YouTube, Wiki, Dictionary, Apple, Adobe, or Google Images?")
The Google Images has a question mark but when I type "Google Images" in the text box,
it closes. Can someone help so I can type Google Images with the question mark and the program doesn't close?
A:
Add "Google Images?" to the acceptable results for the text returned.
else if text returned of result is in {"Google Images", "Google Images?"} then
instead of:
else if text returned of result = "Google Images" then
This will allow for you to enter both as acceptable answers in your dialog.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to write Mule console output in a Text File
How to write a Mule Console Output to a text file. i am not able to see the full console output for big batch runs.
A:
You need to add a log4j properties file into your main/resources directory, this log4j.xml file will do the trick
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="file-appender"
class="org.apache.log4j.FileAppender">
<param name="file" value="path_to_your_log_file_here.log" />
<param name="append" value="true" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<root>
<level value="file-appender" />
<appender-ref ref="file-appender" />
</root>
</log4j:configuration>
| {
"pile_set_name": "StackExchange"
} |
Q:
Inserting dynamic html content
I have a form where one can add multiple questions using the "Add Question" button. If you click on the button, a new accordion-group is created.
<div id="accordion1" class="accordion">
<div id="group1" class="accordion-group">
<input type='text' id='question1' class='textbox-input'/>
</div>
</div>
<input type"button" value="Add Question" id="addQuestion" onclick="javascript:addQuestion();"/>
<script>
function addQuestion(){
var previousContent = document.getElementById("accordion1").innerHTML;
var newContent = "<div id='group2' class='accordion-group'>" +
"<input type='text' id='question2' class='textbox-input'/>" +
"</div>";
document.getElementById("accordion1").innerHTML = previousContent + newContent;
}
</script>
I also have some scripts that give styling to the textboxes, but those styles do not get applied to the new dynamic content added. And also the select boxes places inside each accordion-group gets disabled. Does anyone know how to solve this?
A:
This worked for me. Thanks for all the help :)
function addQuestion(){
var newContent = "<div id='group2' class='accordion-group'>" +
"<input type='text' id='question2' class='textbox-input'/>" +
"</div>";
$("#accordion1").append(newContent);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I include a job I worked at for 4.5 months on my resume?
I left the job as I had some work permit issues and had a period where my new work permit was delayed and I was unable to return to work for a few months. The relationship between my employer and I broke down, and when I got back into the country I decided not to return to work there.
The employer did agree to be a verbal reference, however since then has also accused me of a number of mistakes that have cost the company money. I have not been working there so have no idea if these are my mistakes or if I am being used as a scapegoat.
I had a number of interviews recently and was unsuccessful in the positions after the reference stage. My 2 other references gave glowing reports, so I have a suspicion that this person has given me a bad reference.
I have been freelancing as well so it has been suggested that I remove this company and replace it with my freelance accounts. However I feel it is lying by omission if I completely remove this job from the resume.
I can leave the job on the resume and remove him from my reference list, but it does not stop a potential employer from contacting the company on their own account.
Should I include this previous employer?
A:
You should definitely include this position on your resume - gaps in employment stick out like a sore thumb, and lying about the gap is even worse, because an employer will find out what you were doing in that span of time regardless.
Don't bother including any contact information though - and feel free to mention to your employer, if they ask about that short time at that job, the circumstances of your departure (that they were good, but that your boss has recently soured towards you for reasons unknown). But don't volunteer this information unless it comes up. Most companies just want to know that you've been employed in the past, not the full details of your employment.
A:
I think you should leave them on your resume, and also include the freelancing, as it looks bad if potential employers discover you were hiding a job from them.
However, as you suggested, I would definitely remove them from the reference section. Your references are supposed to be the best people to vouch for you, of if one of your references gives negative feedback, it can suggest that either:
a) You are so short on references that you need to include someone you know has negative things to say, or
b) you are unaware of the negative feedback, which suggests that you might be a bit clueless or uncaring as to how people perceive you.
I would suggest replacing their reference with one from your freelancing experience, but not pretending that you did not work there.
| {
"pile_set_name": "StackExchange"
} |
Q:
auto incrementar con ajax
Tengo un sistema de votación que debería autoincrementarse al presionar sobre unos link, básicamente la estructura es la siguiente:
<ul>
<li>Uno <a href="#">0</a></li>
<li>Dos <a href="#">0</a></li>
<li>Tres <a href="#">0</a></li>
</ul>
Al presionar los enlaces con ceros, estos tienen que incrementar de uno en uno, actualizarse y guardarse en la base de datos, esto último lo hago mediante AJAX.
Tanto los nombres como los enlaces los cargo desde la base de datos. Lo ideal seria que si presionase el enlace 'Dos' se mostrara lo siguiente:
<ul>
<li>Uno <a href="#">0</a></li>
<li>Dos <a href="#">1</a></li>
<li>Tres <a href="#">0</a></li>
</ul>
¿Alguna sugerencia de cómo autoincrementar los valores? Gracias
A:
Te dejo un ejemplo de como realizarlo con jQuery muy simple.
Si tienes alguna duda me dices.
$('li').on('click',function(){
var actual = $(this).find('a').text();
var now = parseInt(actual) + 1;
$(this).find('a').text(now);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Uno <a href="#">0</a></li>
<li>Dos <a href="#">0</a></li>
<li>Tres <a href="#">0</a></li>
</ul>
| {
"pile_set_name": "StackExchange"
} |
Q:
Beego ORM with MySQL
I am new to Beego as well as Go. I read its documentation but it puts every ORM operation in the main package instead of model package. I can't understand how to organize the code. I am really very confused.
A:
You can feel free to follow steps as below, and try to build your first database program.
Build [Models]
According to the table structure of your database.
Initialize the ORM
New an ORM instance
Operate CRUD as your want
Link:
Guidance for Beego/orm configuration
https://beego.me/docs/mvc/model/orm.md
Guidance for operating CRUD on Beego/orm
https://beego.me/docs/mvc/model/object.md
| {
"pile_set_name": "StackExchange"
} |
Q:
safeAreaLayoutGuide guide not working from another viewcontroller
As suggested by some experts like @DonMag , i design the view in a separate controller, while trying to do so , every thing works, but when i use a navigation controller and there is a navigation bar at top, if i try and design in separate controller and then add its view to another controller the safeAreaLayoutGuide does not work and the view is attached to top of screen ignoring the safearea
SOLUTION as per @Mohammad Azam, DonMag solutions works as well , thanks
import UIKit
class NotesDesign: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func commonInit(){
let notesTitle = UITextField()
let notesContent = UITextView()
let font = UIFont(name: "CourierNewPS-ItalicMT", size: 20)
let fontM = UIFontMetrics(forTextStyle: .body)
notesTitle.font = fontM.scaledFont(for: font!)
notesContent.font = fontM.scaledFont(for: font!)
notesTitle.widthAnchor.constraint(greaterThanOrEqualToConstant:250).isActive = true
notesTitle.heightAnchor.constraint(equalToConstant: 30).isActive = true
notesTitle.borderStyle = .line
notesContent.widthAnchor.constraint(greaterThanOrEqualToConstant:250).isActive = true
notesContent.heightAnchor.constraint(greaterThanOrEqualToConstant: 100).isActive = true
notesContent.layer.borderWidth = 1
let notesStack = UIStackView()
notesStack.axis = .vertical
notesStack.spacing = 20
notesStack.alignment = .top
notesStack.distribution = .fill
notesStack.addArrangedSubview(notesTitle)
notesStack.addArrangedSubview(notesContent)
// Do any additional setup after loading the view.
notesStack.translatesAutoresizingMaskIntoConstraints = false
addSubview(notesStack)
notesStack.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
notesStack.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
notesStack.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
notesStack.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -40).isActive = true
}
}
And where i call it
import UIKit
class AddNotesViewController: UIViewController {
var design = NotesDesign()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(design)
design.translatesAutoresizingMaskIntoConstraints = false
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveData))
}
@objc func saveData() {
}
}
And this is what i get
A:
If you are taking a view from its ViewController and adding it as a subview to another view, you need to constrain it just like you would with any other added subview:
class AddNotesViewController: UIViewController {
var design = NotesViewDesign()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(design.view)
// a view loaded from a UIViewController has .translatesAutoresizingMaskIntoConstraints = true
design.view.translatesAutoresizingMaskIntoConstraints = false
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// constrain the loaded view
design.view.topAnchor.constraint(equalTo: g.topAnchor),
design.view.leadingAnchor.constraint(equalTo: g.leadingAnchor),
design.view.trailingAnchor.constraint(equalTo: g.trailingAnchor),
design.view.bottomAnchor.constraint(equalTo: g.bottomAnchor),
])
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveData))
}
@objc func saveData() {
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to open docker-compose services in separate shells
I have a jupyter notebook + elastic docker-compose like so:
version: "3"
services:
jupyter:
build: . #ubuntu
ports:
- 8888:8888
.....
entrypoint: jupyter notebook --ip=0.0.0.0 --allow-root
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:6.2.4
.....
depends_on:
- jupyter
..... (logstash + kibana)
The problem is jupyter spits out a token needed to use it:
The Jupyter Notebook is running at:
jupyter_1 http://0.0.0.0:8888/?token=....
but quickly gets buried from all the elastic output to the shell. It becomes a pain to scroll up and find the token. How can I make the jupyter service open in a new shell separate from from other services so the token is easy to grab?
A:
Run
docker-compose up -d
docker-compose logs jupyter | grep token
If you want to follow logs again you can run
docker-compose logs -f
Or
Just open another terminal and run
docker logs jupyter | grep token
| {
"pile_set_name": "StackExchange"
} |
Q:
Correctness of the integral $\int_a^bf(x)\,dx$ when $f$ is not defined at $a$ and $b$
Knowing that the function
$$\frac{1}{\sqrt{1-x^2}}\
$$ is defined only for $-1 < x <1$, are the limits of integration below allowed?
$$\int_{-1}^1 \frac{1}{\sqrt{1-x^2}} \,dx= \pi$$
PS: As stated above, I can calculate the result as $\pi$, I am just questioning the reasoning behind using $-1$ and $1$ as limits of integration when the function isn't defined at these points.
A:
This is an improper integral. Interpret it as follows:
$$\int_{-1}^1 \frac{1}{\sqrt {1-x^2}} \,dx= \lim_{m \to -1^+} \lim_{n \to 1^-} \int_{m}^n \frac{1}{\sqrt {1-x^2}} \,dx = \lim_{m \to -1^+} \lim_{n \to 1^-} \left[ \arcsin x \right]_{m}^n = \pi.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I center my webpage?
How do I center my webpage?
Something like this, notice the borders on both sides of the text?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Sepia!</title>
<link rel="stylesheet" href="mystyle.css">
<style type="text/css">
body {
padding-top: 14em;
padding-left: 30em;
text-align: center;
font-family: Arial ;
color: #414189;
background-color: #0f0f0f}
ul.navbar {
list-style-type: none;
padding: 0;
margin: 0;
position: absolute;
top: 1em;
left: 10em;
width: 9em }
h1 {
font-family: Arial }
ul.navbar li {
background: #0f0f0f;
padding: 0.4em;
}
ul.navbar a {
text-decoration: none }
a:link {
color: #0f0f0f}
a:visited {
color: #0f0f0f}
address {
margin-top: 1em;
padding-top: 1em }
</style>
</head>
<body>
<!-- Site navigation menu -->
<ul class="navbar">
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo5.png"
alt="Button 1" /></a>
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo4.png"
alt="Button 1" /></a>
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo4.png"
alt="Button 1" /></a>
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo4.png"
alt="Button 1" /></a>
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo4.png"
alt="Button 1" /></a>
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo4.png"
alt="Button 1" /></a>
</ul>
<!-- Main content -->
<p>para 1
<p>para 2
<address>Date<br>
Sepia </address>
</body>
</html>
EDIT:
Tried it and it doesn't seem to be working, what did I do wrong? The text is centered but not the images.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Sepia!</title>
<link rel="stylesheet" href="mystyle.css">
<style type="text/css">
body {
padding-top: 14em;
padding-left: 20em;
font-family: Arial ;
color: #414189;
background-color: white}
wrap {
width: 900px;
margin: 0 auto;
background-color: #0f0f0f}
ul.navbar {
list-style-type: none;
padding: 0;
margin: 0;
position: Absolute;
top: 1em;
left: 1em;
width: 9em }
h1 {
font-family: Arial }
ul.navbar li {
background: #0f0f0f;
padding: 0.4em;
}
ul.navbar a {
text-decoration: none }
a:link {
color: #0f0f0f}
a:visited {
color: #0f0f0f}
address {
margin-top: 1em;
padding-top: 1em }
</style>
</head>
<body>
<div id="wrap">
<!-- Site navigation menu -->
<ul class="navbar">
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo5.png" alt="Button 1" /></a>
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo4.png" alt="Button 1" /></a>
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo4.png" alt="Button 1" /></a>
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo4.png" alt="Button 1" /></a>
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo4.png" alt="Button 1" /></a>
<li><img src="C:\Users\user\Pictures\Style\SepiaWeb\button_demo4.png" alt="Button 1" /></a>
</ul>
<!-- Main content -->
<p>para 1
<p>para 2
<address>Date<br>
Sepia </address>
</div>
</body>
</html>
A:
You can do this by wrapping all your site's content in a wrapping element. You then set the width of this wrap element and center it using the following CSS:
body {
background-color: #ddd; /* the colour on the edges of the screen */
}
#wrap {
width: 700px; /* Set wrapper's width */
margin: 0 auto; /* Center the wrapper in the window */
background-color: #fff; /* the colour of the wrapper */
}
The HTML will look like the following:
<body>
<div id="wrap">
all your site's content
</div>
</body>
| {
"pile_set_name": "StackExchange"
} |
Q:
Lambert W Function values
Do we know of any exact values of the lambert W function like we do for, say, the gamma function at $\frac 12$ ?
A:
Yes , you have for example :
$$ W(e)=1 , W(0)=0 , w(-\frac{\pi}{2})=\pm i\frac{\pi}{2}$$
The last identity comes from the mulitvaluated character of $W$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to programmatically create UIlabel inside a custom uiView swift
how can i create 5 custom uilabel inside a custom UIView. Which will align one after the other. i have tried to create the UILabel inside the custom UIView. but it does not go inside the custom UIView.
//updated with the loop
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var mainView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var getMainViewX = mainView.frame.origin.x
let getMainViewY = mainView.frame.origin.y
for var i = 0; i < 5; i++
{
let label = UILabel(frame: CGRectMake(getMainViewX, getMainViewY, 200, 21))
//label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I'am a test label"
self.mainView.addSubview(label)
getMainViewX+=20
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
A:
If you're using iOS 9, the recently added Stack View has been created for exactly this purpose.
Use a UIStackView for your mainView instead of a default view
You can set the alignment properties of the stack view in Interface Builder
Create the labels in your loop, then add them to the stack view using the addArrangedSubview method of the stack view.
The stack view will take care of the alignment, spacing and layout of it's subviews for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Referencing another function containing a 'this' reference in Javascript
A colleague of mine has written various Javsascript functions which show certain HTML elements dependent on the answers to various inputs. This is an example of one of the functions, which are all very similar.
function addSponsership(sponser) {
if (sponser.value == "N") {
document.getElementById('nameofperson').style.display = "block";
document.getElementById('nameofpersonvalue').style.display = "block";
document.getElementById('address').style.display = "block";
document.getElementById('addressvalue').style.display = "block";
document.getElementById('postcode').style.display = "block";
document.getElementById('postcodevalue').style.display = "block";
document.getElementById('telephone').style.display = "block";
document.getElementById('telephonevalue').style.display = "block";
document.getElementById('fax').style.display = "block";
document.getElementById('faxvalue').style.display = "block";
document.getElementById('emailaddress').style.display = "block";
}
if (sponser.value == "NH") {
document.getElementById('nameofperson').style.display = "none";
document.getElementById('nameofpersonvalue').style.display = "none";
document.getElementById('address').style.display = "none";
document.getElementById('th1').style.display = "none";
document.getElementById('th8').style.display = "table-row";
}
if (sponser.value == "Y") {
document.getElementById('nameofperson').style.display = "none";
document.getElementById('nameofpersonvalue').style.display = "none";
document.getElementById('address').style.display = "none";
}
}
The function is called from the HTML with an onclick event which looks like this:
<input type="radio" name="IPQ_FUND1" id="IPQ_FUND1" value="Y" checked="checked" onclick="addSponsership(this);"/>
I now want to call all of these functions using the onload event on the body element. However, I am unsure how to do this. Example:
function callAllOtherFunctions()
{
addSponsership(sponser)
addSponsership2(sponser)
addSponsership3(sponser)
etc...
}
The problem with this is that I can't find a way to refer to the specific elements whose values need to be checked. Ideally I need to find a solution to this without editing the original functions written by my colleague.
I tried to do it individually by creating another function that looked like this:
function addSponsershipLoad(inputID){
sponser = document.getElementById(inputID);
addSponsership(sponser);
}
and editing the body tag to look like this:
<body onload="addSponserShipLoad('IPQ_FUND1');">
but despite the console not showing any errors, this didn't work.
So, I know I'm probably being quite thick and the solution will be simple, but please help if you can.
A:
You don't have to put everything in variables:
addSponsership(document.getElementById('IPQ_FUND1'));
addSponsership2(document.getElementById('IPQ_FUND2'));
// ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting a global map in Grails
I am building a Grails web app, I created a map in BootStrap and placed it in servletContext in order to make it available to my application from anywhere. On average this map should hold about 1000 entries with String keys and Date value.
I was wondering if that can impact my application performance and there is a better place to keep this map ? I want this map to work as a caching mechanism. I wanna put a unique Key in it and a date, and be able to retrieve that date object from anywhere such as within a controller, or service class by passing the key. I was thinking of using a caching mechanism to do that but haven't find one that can do this form. I appreciate it if anyone can suggest any plugin for Grails that can achieve this.
P.S: Is it possible to do this with Cache Plugin : http://grails-plugins.github.io/grails-cache/docs/manual/guide/usage.html#annotations
A:
You could use a Service for this task. Service is a singleton, so it will be alive all the time. And it's much easier to access from other parts of app. To prepare data on application startup, you can implements InitializingBean.
Foe example:
class MyCacheService implements InitializingBean {
Map cache
void afterPropertiesSet() {
cache = [
a: 1,
b: 2,
// .....
]
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring reading request body twice
In spring I have a controller with an endpoint like so:
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public OutputStuff createStuff(@RequestBody Stuff stuff) {
//my logic here
}
This way if doing a POST on this endpoint, the JSON in request body will be automatically deserialized to my model (Stuff). The problem is, I just got a requirement to log the raw JSON as it is coming in! I tried different approaches.
Inject HttpServletRequest into createStuff, read the body there and log:
Code:
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public OutputStuff createStuff(@RequestBody Stuff stuff, HttpServletRequest req) {
StringBuilder sb = new StringBuilder();
req.getReader().getLines().forEach(line -> {
sb.append(line);
});
//log sb.toString();
//my logic here
}
The problem with this is that by the time I execute this, the reader's InputStream would have already been executed to deserialize JSON into Stuff. So I will get an error because I can't read the same input stream twice.
Use custom HandlerInterceptorAdapter that would log raw JSON before the actual handler is called.
Code (part of it):
public class RawRequestLoggerInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
StringBuilder sb = new StringBuilder();
req.getReader().getLines().forEach(line -> {
sb.append(line);
});
//log sb.toString();
return true;
}
}
The problem with this tho is, that by the time the deserialization to stuff happens, the InputStream from the request would have been read already! So I would get an exception again.
Another option I considered, but not implemented yet, would be somehow forcing Spring to use my custom implementation of HttpServletRequest that would cache the input stream and allow multiple read of it. I have no idea if this is doable tho and I can't find any documentation or examples of that!
Yet another option would be not to read Stuff on my endpoint, but rather read the request body as String, log it and then deserialize it to Stuff using ObjectMapper or something like that. I do not like this idea either tho.
Are there better solutions, that I did not mention and/or am not aware of? I would appreciate help. I am using the latest release of SpringBoot.
A:
To read the request body multiple times, we must cache the initial payload. Because once the original InputStream is consumed we can't read it again.
Firstly, Spring MVC provides the ContentCachingRequestWrapper class which stores the original content. So we can retrieve the body multiple times calling the getContentAsByteArray() method.
So in your case, you can make use of this class in a Filter:
@Component
public class CachingRequestBodyFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest currentRequest = (HttpServletRequest) servletRequest;
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(currentRequest);
// Other details
chain.doFilter(wrappedRequest, servletResponse);
}
}
Alternatively, you can register CommonsRequestLoggingFilter in your application. This filter uses ContentCachingRequestWrapper behind the scenes and is designed for logging the requests.
A:
As referenced in this post: How to Log HttpRequest and HttpResponse in a file?, spring provides the AbstractRequestLoggingFilter you can use to log the request.
AbstractRequestLoggingFilter API Docs, found here
| {
"pile_set_name": "StackExchange"
} |
Q:
mix static and dynamic cell in swift
i have dynamic cells in tableView, but in top of dynamic cells i want add a static cell that contain two label.
i searched but i did not find my solution.
what should i do?
(i am begginer)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dictionary.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : TicketDetailTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TicketDetailTableViewCell
var dict = dictionary[indexPath.row]
cell.lblComment.text = dict["comment"] as? String
cell.lblDate.text = dict["date"] as? String
return cell
}
A:
You have a couple options...
Use a .tableHeaderView - you can use any normal UIView + subviews, labels, images, etc, etc, etc
Create a second prototype cell, and use that cell as your "first row". You can lay it out in Storyboard however you want... just because it is a prototyped cell, doesn't mean you have to change anything when you use it.
Method 2 will end up looking similar to this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// if it's the first row, show the prototype cell with
// identifier "StaticCell"
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticCell", for: indexPath)
return cell
}
// it's not the first row, so show the prototype cell with
// identifier "cell"
//
// Note: you will need to "offset" the array index since the
// "2nd row" is indexPath.row == 1
let cell : TicketDetailTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TicketDetailTableViewCell
var dict = dictionary[indexPath.row - 1]
cell.lblComment.text = dict["comment"] as? String
cell.lblDate.text = dict["date"] as? String
return cell
}
// you will also need to return +1 on the number of rows
// so you can "add" the first, static row
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dictionary.count + 1
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Describe the set of all odd numbers between $100$ and $200$ using set builder notation
I've come across a question in Discrete Mathematics, asking me to use set builder notation to describe the set of all odd numbers between 100 and 200.
The answer I had was:
$$\{ p | p = 2n + 1, n \text{ (all numbers) } [50, 99], 100 < p < 200 \}$$
Although this should technically give the correct answer, the answers in the textbook have:
$$\{x\,|\,100<x<200\text{ and }2\not | x\}$$
I get the first part, however I have no clue what the end means (2 |/ x); what is that symbol called, and does that represent all odd numbers?
A:
The symbol $\mid$ means 'divides'. Drawing a line through it to get $\not \mid$ means 'does not divide'. As for your answer, it is absolutely correct. There are many equally correct ways to write the set of odd numbers with setbuilder notation.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to loop through a nested dictionary or json data in Reactjs
Using Reactjs how do you create a function component that loop through the json data below and display location content.
I want the function to also be able to display something else like members if needed.
I am new to react and most examples online show it using class component (which i am not interested into)
data.json
[{
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"authorization": "Black card",
"location": [
"Next",
"Previous",
"Here"
]
}
]
}]
A:
Of course that I cant make an entire project solution for you but the function that you wanted must have this kind of logic.
const jsonData = [{
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"authorization": "Black card",
"location": [
"Next",
"Previous",
"Here"
]
}
]
}]
jsonData.forEach(item=>{
item.members.map((member)=>{
if(member.location&&member.location[0]){
//Do whatever, maybe you want to use return statement in there
console.log(member.location)
}
else{
//do something else, or add more conditions
console.log("There's no location in it")
}
})
})
you can put it in a variable and add your variable inside your jsx return statement or use it directly in middle of your function's return statement.
Good luck.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the appropriate location for custom systemd service files?
I have many custom service files that I control with systemctl and up until today I have been putting these .service files in /usr/lib/systemd/system/, however today I obtained a new program and it automatically created the .service file in a location I didn't think of - /etc/systemd/system/.
Is this where I should have been putting the service files I have created myself? Both directories appear to work, so ultimately I know it doesn't make a difference, but what does convention dictate? Is there a more correct location to have these custom service files?
A:
The convention is that /usr/lib is for files installed by the system, and /etc is for local configuration.
| {
"pile_set_name": "StackExchange"
} |
Q:
Order of delete, NULL pointer or memory leak
I have the following situation:
Foo1 foo1* = new Foo1(...);
Foo2 foo2* = new Foo2(foo1, ...);
or
Foo1 foo1(...);
Foo2 foo2(foo1, ...);
I need to delete Foo1 and Foo2. If I understand correctly, I should free memory in the reverse order it was allocated. So I should do:
delete(foo2);
delete(foo1);
I can't do this however, because foo1 is being set to NULL in foo2's destructor. So when I try to delete foo2, it's trying to delete a NULL reference and triggering an assert. Is there a way around this? The best solution here would allow me to still allocate the memory to the stack but it's definitely not necessary.
EDIT:
See this thread: Will a shared_ptr automatically free up memory?
Thank you for the responses. I was (clearly) wrong about what the problem was. I need to use a shared_ptr here because I can't change the API.
Foo1 *foo1 = new Foo1(...);
shared_ptr<Foo2> foo2(foo1);
Is the shared_ptr here going to handle freeing the memory used by foo1? If I understand correctly, I shouldn't have to call delete on foo1 correct?
I will ask as a seperate question and link to it.
A:
First, you only need to delete objects created using new. Generally speaking, there is no order dependency for objects created by new. There may be a constructor/destructor dependency, though, such as if foo2 calls functions on foo1 in foo2's destructor. In this case, order of destruction is important.
Second, even if the foo1 pointer in foo2 is set to null, that is just the local copy of the pointer held in foo2. It will not effect other copies of the pointer. Setting foo1 to to null in foo2 is not a bad idea, since it signals the object should no longer be used but this is different to calling its destructor or freeing it.
A:
I should free memory in the reverse order it was allocated.
Uh, not for a general-purpose allocator, like the one powering new and delete.
I can't do this however, because foo1 is being set to NULL in foo2's
destructor.
This is a giant pile of WTF. Why on earth would you have such a scheme? And don't even think about deleteing an object you did not new.
Just use smart pointers like a sane person and forget about all of this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do zeros of uniformly convergent function sequences also converge?
Assume the following:
$f_n{(x)}$ is a sequence of continuous functions, each with a unique zero $x_n^*$
$f_n\to f$ uniformly
$f$ has a unique zero at $x$
Does it then follow that $x_n^*\to x$?
If this claim is false, what are the minimum additional assumptions needed in order to make it true (for example, do we need to assume that all of the $f_n$'s are analytic)?
A:
Consider the functions $f_n(x) = \dfrac{(x^2 + 1/n)(x/n - 1)}{1 + x^4}$ on $\mathbb R$.
EDIT: These, and their limit $f(x) = \dfrac{-x^2}{1+x^4}$, are real-analytic.
On the other hand, if $f_n$ are analytic in a domain $D$ of the complex plane containing $x$ (the unique zero of $f$ in $D$) and converge uniformly to $f$ on compact subsets of $D$, then by the argument principle $f_n$ must have a zero in $D$ for sufficiently large $n$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create and save duplicate item (with custom option) in cart
In fact just copy and save existing cart item.
Programmatically course.
In cart we have item - "A" with custom option, need clone "A" -> to (create) "B"
"B" full double "A" besides id.
A:
Your question is a bit confusing.
What you are saying/asking is how to add the field to 'info_buy_request' options, if it was not filled in by a user.
If the user did not fill it in, what exactly do you want to add? The field with NULL as the value? If the field does not exist in the options, then that explicitly means it was not populated, which should be enough, should it not? Why the need to populate it? (and again, with what?)
also, your way of iterating over the item options is not needed. You can get to the data as follows:
$infoBuyRequest = $item->getOptionByCode('info_buyRequest');
if (is_object($infoBuyRequest)) {
$buyRequest = new Varien_Object(unserialize($infoBuyRequest->getValue()));
}
Now your data is in an object - $buyRequest and can be accessed/manipulated as an object
| {
"pile_set_name": "StackExchange"
} |
Q:
Shannon entropy of a fair dice
The formula for Shannon entropy is as follows,
$$\text{Entropy}(S) = - \sum_i p_i \log_2 p_i
$$
Thus, a fair six sided dice should have the entropy,
$$- \sum_{i=1}^6 \dfrac{1}{6} \log_2 \dfrac{1}{6} = \log_2 (6) = 2.5849...$$
However, the entropy should also correspond to the average number of questions you have to ask in order to know the outcome (as exampled in this guide under the headline Information Theory).
Now, trying to construct a decision tree to describe the average number of questions we have to ask in order to know the outcome of a dice, and this seems to be the optimal one:
Looking at the average number of questions in the image, there are 3 questions in 4/6 cases in 2 questions in 2/6 cases. Thus the entropy should be:
$$\dfrac{4}{6} \times 3 + \dfrac{2}{6} \times 2 = 2.6666...$$
So, obviously the result for the entropy isn't the same in the two calculations. How come?
A:
To recover entropy, you have to consider a sequence of dice throws, and ask how many questions per roll you need in an optimal strategy, in the limit that the number of rolls goes to infinity. Note that each question can cover all the rolls, for example for two rolls, you could ask at some point: “Are the results in $\{16,21,22,23\}$?” (where the first digit denotes the first throw, and the second digit denotes the second throw).
I'm too lazy to do it for 36 possibilities, therefore here a simpler example: Consider a die for which each roll gives only one of three results with equal probability. Then the entropy is about $1.58496$.
For one toss, the optimal strategy is simply to ask “was it $1$?” followed by ”was it $2$?”, which on average gives $5/3 = 1.66$ questions.
For two tosses, an optimal strategy would be to first ask “was it one of $\{11,12,13,21\}$?” (where the first digit gives the result of the first toss, and the second digit the result of the second toss). If the answer is “yes”, then use two questions to single out one of the four results. Otherwise, ask “was the first toss a $2$?”, if yes then it was one of $22$ or $23$, and one question is sufficient to determine that. In the remaining case you know the first toss was $3$ and know nothing about the second, so you employ the one-toss strategy to determine the second toss.
This strategy needs on average $29/9=3.2222$ questions, or $1.61111$ questions per toss. Which is already much better, and indeed only $1.65\,\%$ worse that the value given by the entropy.
Note that the average number of questions of the single-toss optimal strategy can differ dramatically from the entropy. For this, consider the toss of a biased coin. The entropy of this can be made arbitrary low by making the coin sufficiently biased. But obviously there's no way you can get the result of a coin toss with less than one question.
A:
In your setting, the Shannon entropy is "just" a lower bound for an entropy of any decision tree (including optimal ones). These don't have to coincide. To get closer to what the Shannon entropy is, imagine an optimal decision tree identifying outcomes of throwing a dice $N$ times with some large $N$ (assuming independence). The larger $N$ is, the smaller (yet nonnegative) is the difference between the "averaged" (i.e. divided by $N$) entropy of this "compound" decision tree and the Shannon entropy of the dice. (It resembles a background of arithmetic coding).
A:
There is nothing wrong with what you did. In the book "Elements on Information Theory", there is a proof that the average number of questions needed lies between $H(X)$ and $H(X)+1$, which agrees with what you did. So, in terms of "questions", the entropy gives you an accuracy within $1$ question. The following argument is from "Elements on Information Theory":
Proof that $H(X) \leq L < H(X) + 1$
If $L$ is the average number of questions (in the book it is the referred to as the expected description length), it could be written as
$$L = \sum p_i l_i$$
subject to the constraints that each $l_i$ is an integer, because $l_i$ reflects the number of questions asked to arrive at the answer of the $i^{th}$ outcome. Also, you have $$\sum D ^{-l_i} \leq 1$$where $D$ is the size of your alphabets. Furthermore, the optimal number of questions can be found by minimizing the $D-$adic probability distribution closest to the distribution of $X$ in relative entropy, that is, by finding the $D-$adic $r$, where
$$r_i = \frac{D^{-l_i}}{\sum_j D^{-l_j}}$$ that minimizes
$$L - H(X) = D(p \Vert r) - \log(\sum D^{-l_i}) \geq 0$$
The choice of questions $l_i = \log_D \frac{1}{p_i}$ will give $L = H$. Since $\log_D \frac{1}{p_i}$ is not necessarily an integer, you could
$$l_i = \lceil \log_D \frac{1}{p_i} \rceil$$.
Using Kraft-McMillan's inequality, you can say
$$\sum D^{-\lceil \log_D \frac{1}{p_i} \rceil} \leq \sum D^{- \log \frac{1}{p_i}} = \sum p_i = 1$$
Now you'll get that the optimal $l_i$ are bounded between
$$\log_D \frac{1}{p_i} \leq l_i < \log_D \frac{1}{p_i} + 1$$
which gives you
$$H(X) \leq L < H(X) + 1$$
You computed $L \simeq 2.666$ and $H(X) \simeq 2.58$
| {
"pile_set_name": "StackExchange"
} |
Q:
multicast streaming, too much network traffic?
I am thinking of switching our streaming servers to use multicasting instead of registering multiple clients and duplicating the streams manually on the server. It seems to work very well. However, I did notice that on the packet capture, when a server is multicasting the packets show up on every node, even those that have not subscribed to the stream. Is this the way it is supposed to function? Will this cause network problems if I have several of these servers sending out a multicast stream simultaneously(to different addresses obviously)?
thanks!
A:
Multicast, by it's nature, is broadcast based in the sense that the multicast stream is flooded to all switch ports in the same VLAN or broadcast domain. The hosts that have subscribed to and are interested in that stream will then listen to that stream, all other hosts ignoring it. The way to "solve" this "broadcast problem" is to configure IGMP snooping.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I order a list of dictionaries based on another list which has the key?
I have some ids as follows:
req_ids=['964','123','534','645','876','222']
and I get a response from another server like this not in any particular order:
res_result = [{'id':'123', 'name':'Sachin'},
{'id':'534', 'name':'Vipin'},
{'id':'222', 'name':'Ram'},
{'id':'645', 'name':'Anoop'},
{'id':'964', 'name':'Sani'},
{'id':'876', 'name':'John'}]
I need to get res_result in the same request order as req_ids,
[{'id':'964', 'name':'Sani'},
{'id':'123', 'name':'Sachin'},
{'id':'534', 'name':'Vipin'},
{'id':'645', 'name':'Anoop'},
{'id':'876', 'name':'John'},
{'id':'222', 'name':'Ram'}]
How do I do this if possible using an inbuilt python function instead writing our own loop to do this logic?
A:
If you must sort, map the keys to integers, then use that map to sort:
id_to_pos = {key: i for i, key in enumerate(req_ids)}
sorted(res_result, key=lambda d: id_to_pos[d['id']])
Demo:
>>> from pprint import pprint
>>> req_ids = ['964', '123', '534', '645', '876', '222']
>>> res_result = [{'id':'123', 'name':'Sachin'},
... {'id':'534', 'name':'Vipin'},
... {'id':'222', 'name':'Ram'},
... {'id':'645', 'name':'Anoop'},
... {'id':'964', 'name':'Sani'},
... {'id':'876', 'name':'John'}]
>>> id_to_pos = {key: i for i, key in enumerate(req_ids)}
>>> sorted(res_result, key=lambda d: id_to_pos[d['id']])
[{'id': '964', 'name': 'Sani'}, {'id': '123', 'name': 'Sachin'}, {'id': '534', 'name': 'Vipin'}, {'id': '645', 'name': 'Anoop'}, {'id': '876', 'name': 'John'}, {'id': '222', 'name': 'Ram'}]
>>> pprint(_)
[{'id': '964', 'name': 'Sani'},
{'id': '123', 'name': 'Sachin'},
{'id': '534', 'name': 'Vipin'},
{'id': '645', 'name': 'Anoop'},
{'id': '876', 'name': 'John'},
{'id': '222', 'name': 'Ram'}]
However, you can avoid sorting altogether, you already have the right order, you only need to map from id keys to dictionaries (O(N)), then pull out the dictionaries in the right order (still O(N)):
id_to_dict = {d['id']: d for d in res_result}
[id_to_dict[id] for id in req_ids]
Demo:
>>> id_to_dict = {d['id']: d for d in res_result}
>>> [id_to_dict[id] for id in req_ids]
[{'id': '964', 'name': 'Sani'}, {'id': '123', 'name': 'Sachin'}, {'id': '534', 'name': 'Vipin'}, {'id': '645', 'name': 'Anoop'}, {'id': '876', 'name': 'John'}, {'id': '222', 'name': 'Ram'}]
>>> pprint(_)
[{'id': '964', 'name': 'Sani'},
{'id': '123', 'name': 'Sachin'},
{'id': '534', 'name': 'Vipin'},
{'id': '645', 'name': 'Anoop'},
{'id': '876', 'name': 'John'},
{'id': '222', 'name': 'Ram'}]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Browse a particular folder
I have a folderBrowserDialog control and i have a button named click
i did like this way
private void click_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
}
A:
If what you wish to accomplish is to automatically display a folder of your choice whenever the FolderBrowserDialog is shown, then you can use the following code:
private void click_Click(object sender, EventArgs e)
{
FolderBrowserDialog f = new FolderBrowserDialog();
f.Description = "Please browse to, and select a folder";
f.RootFolder = @"C:\Name Of Folder You Want Displayed\";
using(f)
{
if(f.ShowDialog() == DialogResult.OK)
{
// Do something when the user clicks OK or Open.
}
}
}
Or, you could simply add a FolderBrowserDialog to your Form from the Visual Studio ToolBox and click on the Properties tab, and then click the down arrow to the right-hand side of the 'Root Folder' option and select one of the listed folders from the drop-down menu.
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does tuple index out of range mean?
Can anybody shed some light on why:
print('{0} complete (down: {1} kb/s up: {2} kb/s {3} peers: {4} {5}'.format('state.progress * 100', 'state.download_rate / 1000', 'state.upload_rate / 1000', 'state.num_peers', 'state_str[state.state]'))
Results in a tuple index out of range?
A:
You don't have a "fifth" (or rather, index 5) element because the first element has index 0.
Therefore you have to have 6 elements to use index 5.
print('{0} complete (down: {1} kb/s up: {2} kb/s {3} peers: {4} {5}'.format('state.progress * 100', 'state.download_rate / 1000', 'state.upload_rate / 1000', 'state.num_peers', 'state_str[state.state]'))
Here, your elements are:
0: 'state.progress * 100'
1: 'state.download_rate / 1000'
2: 'state.upload_rate / 1000'
3: 'state.num_peers'
4: 'state_str[state.state]'
5: nil
| {
"pile_set_name": "StackExchange"
} |
Q:
old permalinks not found
Looking through Google Webmaster Tools, I have a lot of 404s for posts with permalink structure of /%year%/%month%/%day%/%postname%/
I have since changed permalinks to /%category%/%postname%.html
I thought Wordpress could redirect old post URLs to new post URLS, but the old date based URLs are generating 404s.
My .htaccess file is writable, set to 644.
Why is this occurring? Thanks!
A:
WordPress doesn’t catch all old URLs, you have to help it. Add the following code to your .htaccess above the WordPress rewrite rules:
RedirectMatch permanent /\d+/\d+/\d+/(.+)$ /?pagename=$1
| {
"pile_set_name": "StackExchange"
} |
Q:
Detect collision between SKNode and Particles?
I have this function that creates some lava:
func setupLava() {
let emitter = SKEmitterNode(fileNamed: "Lava.sks")!
emitter.particlePositionRange = CGVector(dx: 200, dy: 0.0)
emitter.advanceSimulationTime(3.0)
emitter.zPosition = 4
emitter.position = CGPoint(x: self.frame.width / 2, y: 300)
lava.addChild(emitter)
}
And I want to detect when the player collides with it. How do I do that?
A:
From the documentation:
Particles are not represented by objects in SpriteKit. This means you
cannot perform node-related tasks on particles, nor can you associate
physics bodies with particles to make them interact with other
content. Although there is no visible class representing particles
added by the emitter node, you can think of a particle as having
properties like any other object.
So you cannot use SpriteKit to detect collisions with the emitted Lava, but you can associate a physics body to the Lava object and collide with it not it individual emitted nodes. Use categoryContactMask, contactBitMask fields of the physicsBody of your nodes to detect contacts.
| {
"pile_set_name": "StackExchange"
} |
Q:
Circuit with two clocks
Most digital circuits can be built in more than one way. However, the easiest way I've seen to build an edge-triggered D flip-flop is with a pair of D latches. One has WRITE connected to CLOCK, the other has WRITE connected to the inverse of CLOCK. This way, one latch is always write-enabled, and which one changes whenever the level of CLOCK changes.
simulate this circuit – Schematic created using CircuitLab
What I ended up doing is to have two separate clock inputs instead. This way I can ensure that they're never both high at the same time; I can put some dead time where both of them are low.
simulate this circuit
Is it common to do something like that? Have I reinvented a common technique that has a name? Or is this a totally off-the-wall crazy way to design circuits?
A:
Multi-phase non-overlapping clocks were (are?) often used in semiconductor logic design. This is due to the possibility of very large worse case skews (max vs. min propagation) in the rise/fall edges of a single clock's distribution, especially in non-symmetric technologies, such as depletion-mode NMOS (no P transistors). So two edges of the same polarity are distributed instead.
Another variation is overlapping quadrature clock systems.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP: echo as condition of if statament?
I need to put echo as condition of if statement. So, for example:
<html>
...
...
<body>
<form onsubmit"<?php $c=false; if(echo "<script>example();</script>";){ $c=true; } echo "\""; if($c){ echo "action=\"./\"";} method="post">
...
</form>
...
...
<script>
function example()
{
alert("This is only an example");
if(..) return true;
return false;
}
</script>
</body>
</html>
So I need to create a function in JavaScript (this top is only an example, but, in realty, it is more complicated) and call it in the if statement.
Update
The code should be execute "action" of the form only if the Javascript function is true.
A:
PHP runs in the server. JavaScript runs in the client. So php can't use a js variable or its function to server side action. What u can do is , u can call JS function from PHP like
echo "<script> myFunction() </script>";
But in the same same case, u can use php values for JS actions,
eg
<script>
var x = <?php echo $myVar ?>
if(x == true){
alert("yahooo");
}
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
IllegalArgumentException while reading a video file from External Stroage
I have a problem that I am getting IllegalArgumentException while reading a video file from sdcard. I don't know why? Please suggest me the right solution for the same.
ErrorStack:
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): FATAL EXCEPTION: main
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.TestCryptoActivity}: java.lang.IllegalArgumentException: File /mnt/sdcard/E0022505.mp4 contains a path separator
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.os.Handler.dispatchMessage(Handler.java:99)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.os.Looper.loop(Looper.java:123)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at java.lang.reflect.Method.invokeNative(Native Method)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at java.lang.reflect.Method.invoke(Method.java:521)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at dalvik.system.NativeStart.main(Native Method)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): Caused by: java.lang.IllegalArgumentException: File /mnt/sdcard/E0022505.mp4 contains a path separator
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.app.ContextImpl.makeFilename(ContextImpl.java:1602)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.app.ContextImpl.openFileInput(ContextImpl.java:399)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.content.ContextWrapper.openFileInput(ContextWrapper.java:152)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at com.example.TestCryptoActivity.onCreate(TestCryptoActivity.java:29)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-03 18:56:18.733: ERROR/AndroidRuntime(24192): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
Code:
try {
is = this.openFileInput(Environment.getExternalStorageDirectory()+"/E0022505.mp4");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[2097152];
try {
while ((bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] bytes = bos.toByteArray();
try {
String byteString = new String(bytes,"UTF-8");
System.out.println("the bytes array of video:"+byteString);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
A:
Context.openFileInput will not allow path separators because it is only to be used for private files in the application's context.
http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
Open a private file associated with this Context's application package for reading.
You could open that file another way (File, FileInputStream, etc), since it is on the sdcard, but you can't use openFileInput for that purpose.
| {
"pile_set_name": "StackExchange"
} |
Q:
php function cannot be called for the second time
This code is self-explanatory. After I call the function and it works fine, other calls would fail:
<?php
function htmlFilter_array(&$html_array)
{
function nested_clean(&$value)
{
$value = htmlentities($value, ENT_QUOTES, "UTF-8");
}
array_walk_recursive($html_array, 'nested_clean');
}
$arr1=array("id"=>"1");
echo "line 1 <br/>";
$arr2=array("id"=>"2");
echo "line 2 <br/>";
$arr3=array("id"=>"3");
echo "line 3 <br/>";
htmlFilter_array($arr1);
echo "line 4 <br/>";
htmlFilter_array($arr2);
echo "line 5 <br/>";
htmlFilter_array($arr3);
echo "line 6 <br/>";
?>
this is the result:
line 1
line 2
line 3
line 4
why line 5 and 6 cannot run?
A:
If you don't want the function to be accessible outside of your other function, you can use an anonymous function. http://php.net/manual/en/functions.anonymous.php (AKA closure)
| {
"pile_set_name": "StackExchange"
} |
Q:
Glassfish 3: cannot set javax.faces.PROJECT_STAGE to "production"
I', trying to set the javax.faces.PROJECT_STAGE to "production" in my web.xml, but in runtime I see, that the value is always "development". Debugging shows very strange things, cannot get to the situation.. Tried both on GF 3.0.1 and GF 3.1 - the same.
Here is the piece of my web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/applicationContext*.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/WEB-INF/rstk-tag.taglib.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>rstk.DOWNLOAD_PATH</param-name>
<param-value>c:\glassfish3.1\downloads</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Production</param-value>
</context-param>
and this
FacesContext.getCurrentInstance().getApplication().getProjectStage()
always returns Development!
Any help appreciated, this is the real stopper for me as JSF 2.1 in GF 3.1 results in frustrating warning in development mode..
A:
Ok, finally I found the real reason for this staff.
It's Jrebel. For some reasons they force the DEVELOPMENT mode for jsf. For more details you can see http://java.net/jira/browse/JAVASERVERFACES-2079?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel - comments block. The other person had the same problem and finally found out the core reason.
Hope this will help everyone.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the largest possible value of $f(4)$?
Q. Assume the function $f : \mathbb R \to \mathbb R$ is continuously differentiable on $\mathbb R$. Assume also that $f(0) = 0$ and $f(x)f^\prime(x) \le 2$ for all $x \in \mathbb R$. What is the largest possible value of $f(4)$? (Hint: in your answer, you need to show that a larger value cannot be obtained; you must also show that the value you give actually is attained by at least one function.)
I think $f(x) = \sqrt2 \sin(x)$ satisfies the above conditions. But, I don't know how to answer the largest possible value of $f(4)$. Do I just sub $4$ in to $x$ (i.e. $f(4) = \sqrt \sin (4)$)?
A:
As Tsemo Aristide's answer already indicates, the key insight in this problem is that $f(x) f'(x) = \frac{1}{2} \frac{d}{dx} [(f(x))^2]$. Therefore, if $f(x) f'(x) \le 2$, then integrating both sides on $[0,4]$, we get:
$$(f(4))^2 = (f(4))^2 - (f(0))^2 = 2 \int_0^4 f(x) f'(x) dx \le 2 \int_0^4 2\, dx = 16.$$
Therefore, $f(4) \le 4$.
Reversing this, we also get an idea of what we would need to happen in order to get a value of 4 to be achieved. Namely, we would need $\frac{d}{dx} (f(x))^2 \equiv 4$ for $x \in [0, 4]$. Therefore, $f(x)^2 = 4x + C$; and since $f(0) = 0$, we get $f(x)^2 = 4x$. In order to get a positive value of $f(4)$, we would select the solution $f(x) = \sqrt{4x}$.
But wait: There's a problem with this function. Namely, it is only defined for $x \in [0, \infty)$, whereas we wanted to have a function defined on all of $\mathbb{R}$. Furthermore, since $\lim_{x \to 0^+} f'(x) = \infty$, there is no hope of extending this function to all of $\mathbb{R}$ in such a way that $f$ becomes continuously differentiable.
In fact, if we look back at the original argument, we can see why 4 cannot be obtained as a value of $f(4)$. Namely, define $g(x) = f(x) f'(x)$. Then $g$ is a continuous function on $\mathbb{R}$; $g(0) = 0$; and $g(x) \le 2$ for all $x \in \mathbb{R}$. It follows that we have a strict inequality $(f(4))^2 = 2 \int_0^4 g(x) dx < \int_0^4 4\,dx = 16$, so $f(4) < 4$.
On the other hand, the analysis above gives an idea for how we might construct functions $f$ which come very close to having $f(4) = 4$: fix $g$ to be a continuous function with $g(0) = 0$, and $g(x) \le 2$ for all $x$, but such that $g(x)$ increases towards 2 very rapidly as $x$ increases from 0. Then define $G(x) = 2 \int_0^x g(t) dt$ and $f(x) = \sqrt{G(x)}$. Then $f'(x) = \frac{G'(x)}{2 \sqrt{G(x)}} = \frac{g(x)}{\sqrt{G(x)}}$, and $f(x) f'(x) = g(x) \le 2$. The only case to watch out for, in checking $f$ is continuously differentiable, is if $G(x) = 0$, in which case you will have to check more closely. Furthermore, $f(0) = \sqrt{G(0)} = \sqrt{0} = 0$; and $G(4) = 2 \int_0^4 g(t)\,dt$ will be very close to $2 \int_0^4 2\,dt = 16$, so $f(4)$ will be very close to 4.
To make some concrete examples, suppose we set $g_n(x) = 2 \left(1 - \frac{1}{(1+nx)^2}\right)$, so that $G_n(x) = 4x + \frac{4}{n(1+nx)} - \frac{4}{n} = 4x - \frac{4x}{1+nx} = \frac{4n x^2}{1+nx}$ and $f_n(x) = \sqrt{G_n(x)} = 2x \sqrt{\frac{n}{1+nx}}$. Then a quick calculation with the definition of derivative shows $f_n'(0) = 2\sqrt{n}$ and the derivative is continuous at $x=0$. Also, $f_n(4) = 8 \sqrt{\frac{n}{1+4n}} \to 4$ as $n \to \infty$.
However, there is one problem: $f_n(x)$ is defined only for $x > -\frac{1}{n}$. To fix this, we will replace the function for negative $x$ by $2x \sqrt{n}$. On this part of the domain, we will have $f(x) < 0$ and $f'(x) > 0$ so $f(x) f'(x) < 0 \le 2$. We also chose the slope to match the value of $f_n'(0)$ from the original function, so the gluing will result in another continuously differentiable function.
To summarize the last paragraph: define
$$ f_n(x) = \begin{cases} 2x \sqrt{\frac{n}{1+nx}}, & x \ge 0; \\
2x \sqrt{n}, & x < 0. \end{cases} $$
Then $f_n$ satisfies the required conditions from the questions. Furthermore, $f_n(4) = 8 \sqrt{\frac{n}{1+4n}}$ gets arbitrarily close to 4.
So, the question as stated is incorrect: there is no maximum value for $f(4)$ that can be achieved. The supremum of possible values for $f(4)$ is 4; however, for any actual function $f$ satisfying the conditions, we have $f(4) < 4$.
| {
"pile_set_name": "StackExchange"
} |
Q:
AngularJS ng-show - 2 Times, 2 different results
I am creating an app with angularjs, cordova and iconic.
I have a trash icon which should be show only when the user is at the main page.
So i will show the icon only wenn the rootScope.Trashicon is true.
It works fine in my sidemenu. But in the side-menu-content area it doesnt work. I dont know why...
<ion-side-menus ng-controller="MainController" ng-init="getListTitle()">
<ion-side-menu side = "left"> <!-- expose-aside-when DELETE IT !!!!!! -->
<header><img src="img/todo_today_logo_small.png"></header>
<div id="sideContent" class="item item-divider">ToDo Liste:
<p>
> <a menu-close href="#/todo">{{sideMenuListTitle}}</a>
</p>
<div ng-show="Trashicon">test</div>
<h3></h3>
</div>
<div>
<ul>
<li><a menu-close href="#/impressum">Impressum</a></li>
<li><a menu-close href="#/datenschutzerklaerung">Datenschutzerklärung</a></li>
</ul>
</div>
</ion-side-menu>
<ion-side-menu-content>
<ion-nav-bar class="custom-dark" align-title="center">
<ion-nav-buttons side="left">
<!-- Toggle left side menu -->
<button menu-toggle="left" class="button button-icon icon ion-navicon light"></button>
</ion-nav-buttons>
<div ng-show="Trashicon">
<ion-nav-buttons side="right">
<button ng-click="deleteProducts()" class="button button-icon ion-ios-trash-outline pull-right light"></button>
</ion-nav-buttons>
</div>
<ion-nav-title></ion-nav-title>
</ion-nav-bar>
<div ng-view="" class="container"></div>
</ion-side-menu-content>
</ion-side-menus>
This is my rootScope Variable
.controller('MainController', function ($scope, $ionicPopup, $rootScope) {
$rootScope.Trashicon = false;
The div with the trash icon is still visible.. and i dont know why... it would be great if someone has an idea for me.
A:
It seams the element ion-nav-buttons has its own styling which overrides all elements above it.
If you move the ng-show closer the button you will have better control.
i.e instead of
<div ng-show="Trashicon">
<ion-nav-buttons side="right">
<button ng-click="deleteProducts()" class="button button-icon ion-ios-trash-outline pull-right light"></button>
</ion-nav-buttons>
</div>
do this
<div>
<ion-nav-buttons side="right">
<button ng-show="Trashicon" ng-click="deleteProducts()" class="button button-icon ion-ios-trash-outline pull-right light"></button>
</ion-nav-buttons>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Matplotlib Table's Font Size
Working with Matplotlib in Python (2.7.9). I have to plot a table in a subplot (in this case subplot name is tab) but I can't seem to find a way to change the font size of the table (http://imgur.com/0Ttvzee - bottom left). Antman is happy about the results, I am not.
This is the code I've been using.
EDIT: Added full code
def stat_chart(self):
DN = self.diff
ij = self.ij_list
mcont = self.mcont
ocont = self.ocont
ucont = self.ucont
dist = self.widths
clon = '%1.2f' %self.mclon
clat = '%1.2f' %self.mclat
clonlat = "{0}/{1}".format(clon,clat)
area = self.area
perim = self.perimeter
mdist = np.array(self.widths)
mdist = mdist[:,0]*10
mdist = np.mean(mdist)
pstat = self.polygon_status
if pstat == 1:
status = "Overestimation"
else:
status = "Underestimation"
# Setting up the plot (2x2) and subplots
fig = plt.figure()
gs = gridspec.GridSpec(2,2,width_ratios=[2,1],height_ratios=[4,1])
main = plt.subplot(gs[0,0])
polyf = plt.subplot(gs[0,1])
tab = plt.subplot(gs[1,0])
leg = plt.subplot(gs[1,1])
tab.set_xticks([])
leg.set_xticks([])
tab.set_yticks([])
leg.set_yticks([])
tab.set_frame_on(False)
leg.set_frame_on(False)
# Main image on the top left
main.imshow(DN[::-1],cmap='winter')
x1,x2,y1,y2 = np.min(ij[:,1])-15,np.max(ij[:,1])+15,np.min(ij[:,0])-15,np.max(ij[:,0])+15
main.axvspan(x1,x2,ymin=1-((y1-320)/float(len(DN)-320)),ymax=1-((y2-320)/float(len(DN)-320)),color='red',alpha=0.3)
main.axis([0,760,0,800])
# Polygon image on the top right
polyf.imshow(DN,cmap='winter')
polyf.axis([x1,x2,y2,y1])
polyf.plot(mcont[:,1],mcont[:,0],'ro',markersize=4)
polyf.plot(ocont[:,1],ocont[:,0],'yo',markersize=4)
polyf.plot(ucont[:,1],ucont[:,0],'go',markersize=4)
for n,en in enumerate(dist):
polyf.plot([en[2],en[4]],[en[1],en[3]],color='grey',alpha=0.3)
# Legend on the bottom right
mc = mlines.Line2D([],[],color='red',marker='o')
oc = mlines.Line2D([],[],color='yellow',marker='o')
uc = mlines.Line2D([],[],color='green',marker='o')
ed = mlines.Line2D([],[],color='black',alpha=0.5)
pos_p = mpatches.Patch(color='lightgreen')
neg_p = mpatches.Patch(color='royalblue')
leg.legend([mc,oc,uc,ed,pos_p,neg_p],("Model Cont.","Osisaf Cont.","Unknown Cont.","Dist. Mdl to Osi", \
'Model Overestimate','Model Underestimate'),loc='center')
# Statistics table on the bottom left
stats = [[clonlat+' degrees' ,'%1.4E km^2' %area,'%1.4E km' %perim,'%1.4f km' %mdist,status]]
columns = ('Center Lon/Lat','Area','Perimeter','Mean Width','Status')
rows = ['TODOpolyname']
cwid = [0.1,0.1,0.1,0.1,0.1,0.1]
the_table = tab.table(cellText=stats,colWidths=cwid,rowLabels=rows,colLabels=columns,loc='center')
table_props = the_table.properties()
table_cells = table_props['child_artists']
for cell in table_cells: cell.set_height(0.5)
plt.show()
return
EDIT2: Eventually (un)solved plotting text instead of table. Good enough.
A:
I had a similar issue in changing the fontsize. Try the following
the_table.auto_set_font_size(False)
the_table.set_fontsize(5.5)
Worked for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ground state of the Jaynes-Cummings hamiltonian
Equation (5) in beautiful paper (link) on Jaynes-Cummings Hamiltonian gives energy levels
$$E_n = n \hbar \omega \pm 2 g \sqrt{n}, \text{ where } n=0, 1, 2, \ldots$$
But eigenstates in Equation (4) are in basis of excited and photon and ground and photon:
$$|e,n\rangle \text{ and } |g, n-1\rangle.$$
So, what is meaning of the state with $n=0$, since eigenstate is $|g, n-1\rangle = |g, -1\rangle$ photon?
A:
The ground state is pretty easy - the ground state of the atom, with no photons. This is pretty trivial to verify directly.
To be a bit more explicit, if you take the paper's hamiltonian,
$$
\mathcal H_\mathrm{sys} = \hbar\omega \sigma^+\sigma^- + (\hbar \omega-\Delta)a^\dagger a + g(\sigma^-a^\dagger+\sigma^+a),
$$
and apply it to the ground state $|g,0\rangle$, then it is easy to check explicitly that
$$
\mathcal H_\mathrm{sys}|g,0\rangle=0=0|g,0\rangle,
$$
since $\sigma^-|g,0\rangle = a|g,0\rangle = 0$. In particular, in no way does $a|g,0\rangle$ invoke states with negative numbers of photons.
The paper makes it clear, when it says
with the exception of $n = 0$ which is unique,
that the ground state is not a part of any doublet of the form $|g,n\rangle \pm|e,n-1\rangle$, and that instead it sits on an invariant subspace of dimension $1$ (as opposed to the layering of the rest of the Hilbert space into the invariant subspaces $\mathrm{span}\mathopen{}\left(\{|g,n\rangle ,|e,n-1\rangle\}\right)$, of dimension $2$, for excitation number $n\geq1$).
The paper is maybe a bit terse when it explains it, which is par for the course because the material is standard and only needs to be laid out to fix the notation; as is, the explanation is sufficient by the normal standards of the literature. If you want an in-depth explanation of the diagonalization of the Jaynes-Cummings model, then the primary literature is not the place to look ─ instead, you should look for a suitable quantum optics textbook such as Gerry & Knight or Scully & Zubairy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sending an image in a faceless email
I am trying to send a faceless email (sending an email without showing the interface), using the code below.
I also want to attach an image to this email.
Is this possible?
- (void) sendEmailTo:(NSString *)toStr withSubject:(NSString *)subjectStr withBody:(NSString *)bodyStr
{
NSString *emailString=[[NSString alloc] initWithFormat:@"mailto:?to=%@&subject=%@&body=%@",
[toStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[subjectStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[bodyStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:emailString]];
[emailString release];
}
A:
You are unable to send faceless emails using the built-in emailer.
However you should be able to roll your own emailer using parts from email frameworks like for instance Pantomime
| {
"pile_set_name": "StackExchange"
} |
Q:
Check the missing value in an excel table
I am working on my assignment of data visualization. Firstly, I have to check dataset I found, and do the data wrangling, if it is necessary. The data consists of several particles index for air quality in Madrid, those data were collected by different stations.
I found some values are missing in the table. How can I check those missing values quickly by tools (python or R or Tableau) and replace those value?
A:
In Python, you can use the pandas module to load the Excel file as a DataFrame. Post this, it is easy to substitute the NaN/missing values.
Let's say your excel is named madrid_air.xlsx
import pandas as pd
df = pd.read_excel('madrid_air.xlsx')
Post this, you will have what they call a DataFrame which consists of the data in the excel file in the same tabular format with column names and index. In the DataFrame the missing values will be loaded as NaN values. So in order to get the rows which contains NaN values,
df_nan = df[df.isna()]
df_nan will have the rows which has NaN values in them.
Now if you want to fill all those NaN values with let's say 0.
df_zerofill = df.fillna(0)
df_zerofill will have the whole DataFrame with all the NaNs substituted with 0.
In order to specifically fill coulmns use the coumn names.
df[['NO','NO_2']] = df[['NO','NO_2']].fillna(0)
This will fill the NO and NO_2 columns' missing values with 0.
To read up more about DataFrame: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html
To read up more about handling missing data in DataFrames : https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does a std::string object passed to a template function not prefer std::string overload?
I'm writing a program and I want to be able to cleanly wrap a string in quotes without having to do something like
std::string firstString = "This is a string";
std::string myString = "\"" + firstString + "\"";
So I wrote a couple of template functions to take their arguments and wrap them in quotes. I've also included my first (naive) attempt at writing a general toString() function (I know about to_string, but I'm doing this for learning too).
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <typeinfo>
template <typename T>
std::string toString(const T &convert)
{
std::string returnString{""};
std::stringstream transfer;
transfer << convert;
transfer >> returnString;
return returnString;
}
template<typename T>
std::string tQuoted(const T &convert)
{
std::cout << "Called template overload" << std::endl;
return ("\"" + toString(convert) + "\"");
}
template<typename T>
std::string tQuoted(const std::string &convert)
{
std::cout << "Called std::string overload" << std::endl;
return ("\"" + convert + "\"");
}
template<typename T>
std::string tQuoted(const char *convert)
{
std::cout << "Called const char overload" << std::endl;
return ("\"" + static_cast<std::string>(convert) + "\"");
}
template<typename T>
std::string tQuoted(std::string convert)
{
std::cout << "Called normal std::string overload" << std::endl;
return ("\"" + convert + "\"");
}
template<typename T>
std::string tQuoted(std::string&& convert)
{
std::cout << "Called rvalue std::string overload" << std::endl;
return ("\"" + convert + "\"");
}
int main()
{
std::vector<std::string> my{"Hello", "30 Days Of Coding", "All Work And No Play"};
std::string myString = "Hello, World!";
std::string *strPtr = &myString;
std::string *mySuperPtr = new std::string{"He's a cockaroach"};
for (std::vector<std::string>::const_iterator iter = my.begin(); iter != my.end(); iter++) {
std::cout << tQuoted(*iter) << std::endl;
}
std::cout << tQuoted(myString) << std::endl;
std::cout << tQuoted(*strPtr) << std::endl;
std::cout << tQuoted(mySuperPtr) << std::endl;
std::cout << tQuoted(std::string{"Another string"}) << std::endl;
delete mySuperPtr;
mySuperPtr = nullptr;
return 0;
}
Every one of those calls the template constructor:
Called template overload
"Hello"
Called template overload
"30"
Called template overload
"All"
Called template overload
"Hello,"
Called template overload
"Hello,"
Called template overload
"0x13cad10"
Called template overload
"Another"
Of course, a much less naive toString() method would do basic checking to see if the parameter was a std::string, and just return that if it was. It seems that a std::stringstream will stop when it encounters the first space in a string (hence the truncated output). However, this isn't the main focus of my confusion.
Sorry for the very basic question, but this one really has me stumped. Thanks for any help you can provide.
A:
You are not specializing the template function correctly. This is how to correctly specialize it:
template<>
std::string tQuoted(const std::string &convert)
{
std::cout << "Called std::string overload" << std::endl;
return ("\"" + convert + "\"");
}
Resulting output becomes:
Called std::string overload
"Hello"
Called std::string overload
"30 Days Of Coding"
Called std::string overload
"All Work And No Play"
Called std::string overload
"Hello, World!"
Called std::string overload
"Hello, World!"
Called template overload
"0x1c27d10"
Called std::string overload
"Another string"
Note that for
tQuoted(mySuperPtr)
mySuperPtr is a pointer to a string, and not a string, hence this doesn't use the specialized template function.
A:
Take a careful look at this function template that you wrote:
template<typename T>
std::string tQuoted(const std::string &convert)
{
std::cout << "Called std::string overload" << std::endl;
return ("\"" + convert + "\"");
}
It's a function template, with template parameter T, but where does T come from? It's nowhere. Specifically, it's a non-deduced context. There's no way for the compiler to tell what T is from tQuoted(myString), you'd have to explicitly call tQuoted<X>(myString).
But in this case, you don't actually want T anyway. You're not trying to write a new function template. You're trying to write an overload specifically for std::string (as the body of your function suggests). So just write an overload:
std::string tQuoted(const std::string &convert)
{
std::cout << "Called std::string overload" << std::endl;
return ("\"" + convert + "\"");
}
No template necessary. The same is true of all your other overloads - they are all accidentally function templates with template parameters that are non-deduced contexts.
Avoid function template specializations unless you really, really need them. Which, in this case, you don't. See Why Not Specialize Function Templates?
| {
"pile_set_name": "StackExchange"
} |
Q:
Samsung Galaxy wont return (Bitmap) data.getExtras().get("data");
String strAvatarPrompt = "Take your picture to store as your avatar!";
Intent pictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
pictureIntent.putExtra( MediaStore.EXTRA_OUTPUT, imageUriToSaveCameraImageTo );
startActivityForResult(Intent.createChooser(pictureIntent, strAvatarPrompt), TAKE_AVATAR_CAMERA_REQUEST);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_AVATAR_CAMERA_REQUEST:
if (resultCode == Activity.RESULT_CANCELED) {
}
else if (resultCode == Activity.RESULT_OK) {
Bitmap cameraPic = (Bitmap) data.getExtras().get("data");
if (cameraPic != null) {
try {
saveAvatar(cameraPic);
}
I have code for users of my app to take pictures. It works fine on the HTC desire. However on the Samsung Galaxy it crashes at the point
Bitmap cameraPic = (Bitmap) data.getExtras().get("data");
I dont know why it is not working?
Stack-
03-31 16:35:15.593: VERBOSE/WindowManager(2497): Delivering toWindow{47fe4340 com.sec.android.app.camera/com.sec.android.app.camera.CropImage paused=false}
03-31 16:35:15.761: VERBOSE/WindowManager(2497): Delivering toWindow{47fe4340 com.sec.android.app.camera/com.sec.android.app.camera.CropImage paused=false}
03-31 16:35:15.761: VERBOSE/CropImage(6885): Crop = no, Return = specified uri
03-31 16:35:15.773: VERBOSE/CropImage(6885): onPause
03-31 16:35:15.780: ERROR/WindowManager(2497): Overwriting rotation value from 1
03-31 16:35:15.780: VERBOSE/WindowManager(2497): Rotation changed to 1 from 0 (forceApp=0, req=0)
03-31 16:35:15.784: INFO/WindowManager(2497): Setting rotation to 1, animFlags=1
03-31 16:35:15.800: ERROR/SurfaceFlinger(2497): Surface Flinger::setOrientation mIsRotationPossible = 0, nBackupOrientationValue = 1
03-31 16:35:15.804: INFO/TvOut-Observer(2497): setTvoutOrientation rotation = 1
03-31 16:35:15.804: ERROR/TvOut-Observer(2497): SetOrientation
03-31 16:35:15.804: INFO/ActivityManager(2497): Config changed: { scale=1.0 imsi=234/10 loc=en_GB touch=3 keys=1/1/2 nav=1/1 orien=2 layout=35 uiMode=17 seq=96 FlipFont=0}
03-31 16:35:15.808: DEBUG/PhoneApp(2588): updateProximitySensorMode: state = IDLE
03-31 16:35:15.855: DEBUG/OPPBaseService(7980): [main/1] onConfigurationChanged()
03-31 16:35:15.870: VERBOSE/Camera(5292): --onActivityResult--requestCode: 2001
03-31 16:35:15.870: VERBOSE/Camera(5292): --onActivityResult--resultCode: -1
03-31 16:35:15.870: VERBOSE/Camera(5292): --onActivityResult--data: Intent { act=inline-data (has extras) }
03-31 16:35:15.882: WARN/ActivityManager(2497): Duplicate finish request for HistoryRecord{481527f8 com.sec.android.app.camera/.Camera}
03-31 16:35:16.038: VERBOSE/CropImage(6885): onDestroy
A:
Some devices don't return the DATA extra; others only return a very small thumbnail in the extra. You're best off reading the file from the SD card location in EXTRA_OUTPUT (which you're already requesting in your original intent) in the callback if it's available, falling back to the data extra only if you can't read the EXTRA_OUTPUT. See this related SO question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Django REST Framework: define fields in nested object?
I got events that happen at locations:
class Event(models.Model):
title = models.CharField(max_length=200)
date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
date_start = models.DateTimeField('start date')
date_end = models.DateTimeField('end date')
def __unicode__(self):
return self.title
description = models.TextField()
price = models.IntegerField(null=True, blank=True)
tags = TaggableManager()
location = models.ForeignKey(Location, blank=False)
class Location(models.Model):
location_title = models.CharField(max_length=200)
location_date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
location_latitude = models.CharField(max_length=200)
location_longitude = models.CharField(max_length=200)
location_address = models.CharField(max_length=200)
location_city = models.CharField(max_length=200)
location_zipcode = models.CharField(max_length=200)
location_state = models.CharField(max_length=200)
location_country = models.CharField(max_length=200)
location_description = models.TextField()
def __unicode__(self):
return u'%s' % (self.location_title)
I can get the results of all via:
class EventSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.Field()
class Meta:
model = Event
depth = 2
fields = ('url','id','title','date_start','date_end','description', 'price', 'location')
Which outputs:
{
"url": "http://localhost:8000/api/event/3/",
"id": 3,
"title": "Testing",
"date_start": "2013-03-10T20:19:00Z",
"date_end": "2013-03-10T20:19:00Z",
"description": "fgdgdfg",
"price": 10,
"location": {
"id": 2,
"location_title": "Mighty",
"location_date_published": "2013-03-10T20:16:00Z",
"location_latitude": "37.767475",
"location_longitude": "-122.406878",
"location_address": "119 Utah St, San Francisco, CA 94103, USA",
"location_city": "San Francisco",
"location_zipcode": "94103",
"location_state": "California",
"location_country": "United States",
"location_description": "Some place"
}
},
However, I don't want it to grab all fields, as I don't need all of them. How can I define what fields should be retrieved from my nested object? Thanks!
A:
Serializers can be nested, so do something like this...
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = (...)
class EventSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.Field()
location = LocationSerializer()
class Meta:
model = Event
fields = ('url','id','title','date_start','date_end','description', 'price', 'location')
A:
I have been to this and did not get a perfect solution, But I did something you may check for it.
This method will not create nested serializers
**class LocationSerializer(serializers.ModelSerializer):**
class Meta:
model = Location
fields = (...) #does not matter
exclude = (...) #does not matter
class EventSerializer(serializers.ModelSerializer):**
loc_field_1 = serializers.CharField(required=False,*source='location.loc_field_1'*)
loc_field_2 = serializers.CharField(required=False,*source='location.loc_field_2'*)
***#ADD YOUR DESIRE FIELD YOU WANT TO ACCESS FROM OTHER SERIALIZERS***
class Meta:
model = Event
fields =('url','id','title','date_start','date_end','description', 'price', 'location')
A:
I found this question when I was trying to figure out how to exclude certain fields from a serializer only when it was being nested. Looks like Tasawer Nawaz had that question as well. You can do that by overriding get_field_names. Here's an example based on Tom Christie's answer:
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = (...)
exclude_when_nested = {'location_title', 'location_date_published'} # not an official DRF meta attribute ...
def get_field_names(self, *args, **kwargs):
field_names = super(LinkUserSerializer, self).get_field_names(*args, **kwargs)
if self.parent:
field_names = [i for i in field_names if i not in self.Meta.exclude_when_nested]
return field_names
class EventSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.Field()
location = LocationSerializer()
class Meta:
model = Event
fields = ('url','id','title','date_start','date_end','description', 'price', 'location')
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use client side code in Visual studio ASP.NET
I am a quite new to web development and I am trying to do some small form updates without causing a postback. For example making a control visible when a drop down list is changed.
I have so far come across some features that achieve this like the RequiredFieldValidator inside an update panels. However, these are specific to a single task.
What are my options to achieve these client side updates in Visual Studio? At the moment I don't know any JavaScript, so I would prefer another solution if it exists.
A:
If you don't know JQuery you should or at least any other Javascript library this will give you an edge and also pump up your resume. The learning curve of these JS frameworks is so short that you'll be creating awesome UI's in no time. I suggest that you take at least two hours to get to know JQuery you won't regret it.
Here's a few great article on using ASP.NET with JQuery:
http://dotnetslackers.com/articles/ajax/using-jquery-with-asp-net.aspx
http://www.dotnetspark.com/kb/1532-gridview-and-jquery-asp-net-tutorial.aspx
http://www.beansoftware.com/ASP.NET-Tutorials/Using-jQuery-ASP.NET.aspx
Here are a few of the best tutorials on JQuery:
http://www.ajaxline.com/best-jquery-tutorials-march-2010
| {
"pile_set_name": "StackExchange"
} |
Q:
Стилизация маркера элемента списка
1) Каким образом задать отображение маркировки элемента списка справа от содержимого?
2) Каким образом задать стиль маркера элемента списка? - background-color, border, border-radius и т.д. ?
A:
можно попробовать подобный вариант, кроссбраузерность разумеется страдает, но судя по тому что Вам нужен border-radius это уже не так важно )
li:after {/*собственно сам маркер*/
background-color: black;
border: 1px solid blue;
border-radius: 3px 3px 3px 3px;
color: red;
content: "$";/*здесь можно в символьном виде задать отображение маркера*/
}
li {
list-style-type: none;/*прятаем родные маркеры*/
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to efficiently apply an operator to the cartesian product of two arrays?
I have a = array([1, 2, 3, 4, 5]) and b = array([10, 20, 30, 40, 50]). I want:
array([[ -9, -19, -29, -39, -49],
[ -8, -18, -28, -38, -48],
[ -7, -17, -27, -37, -47],
[ -6, -16, -26, -36, -46],
[ -5, -15, -25, -35, -45]])
What's the most efficient way to do this? I have
np.transpose([a]) - np.tile(b, (len(a), 1))
However I wonder if there's a more efficient way than this if a is very large, which wouldn't require copying b so much (or vice versa).
A:
Some NumPy functions, like np.subtract, np.add, np.multiply, np.divide, np.logical_and, np.bitwise_and, etc. have an "outer" method which can be used to create the equivalent of "multiplication tables":
In [76]: np.subtract.outer(a, b)
Out[76]:
array([[ -9, -19, -29, -39, -49],
[ -8, -18, -28, -38, -48],
[ -7, -17, -27, -37, -47],
[ -6, -16, -26, -36, -46],
[ -5, -15, -25, -35, -45]])
or, using broadcasting:
In [96]: a[:, None] - b
Out[96]:
array([[ -9, -19, -29, -39, -49],
[ -8, -18, -28, -38, -48],
[ -7, -17, -27, -37, -47],
[ -6, -16, -26, -36, -46],
[ -5, -15, -25, -35, -45]])
The performance of the two is about the same:
In [98]: a = np.tile(a, 1000)
In [99]: b = np.tile(b, 1000)
In [100]: %timeit a[:, None] - b
10 loops, best of 3: 88.3 ms per loop
In [101]: %timeit np.subtract.outer(a, b)
10 loops, best of 3: 87.8 ms per loop
In [102]: %timeit np.transpose([a]) - np.tile(b, (len(a), 1))
10 loops, best of 3: 120 ms per loop
| {
"pile_set_name": "StackExchange"
} |
Q:
Random Access on AudioInputStream java
Is there an example of randomly accessing an AudioInputStream? something like any ordinary audio player does - when you take the bar wherever you want and it plays from wherever you want, how can i access bytes in the audio stream in that manner?
something simple like that : read(byte[] buffer, long startingFrom) where startingFrom can be wherever i want in the audio stream
A:
Using (simulating?) random access in an AudioInputStream is the same as in a normal InputStream. You can create a mark() at the beginning of the file, so before any calls to read() have been done. Then, when you want to do random access, you stop reading from the stream, go to the marker position by calling reset() and then use skip() to go to the location you desire.
Note that the initial 'mark' will default to 0 for an AudioInputStream, so the initial call is not needed. However this behavior is not specified so it might change in the future.
The implementation of AudioInputStream (Oracle Java 8) supports this mechanism if the underlying stream (for instance the InputStream you give to the constructor) supports it. You can find if the AudioInputStream supports it by calling markSupported().
Unfortunately when using the utility functions from AudioSystem to create the AudioInputStream you can't influence the underlying stream. It could even differ per platform. If your stream does not support it (or you want to be absolutely sure it does support it) you could create a new AudioInputStream by wrapping one in a BufferedInputStream. For example like this:
AudioInputStream normalStream = AudioSystem.getAudioInputStream(...);
AudioInputStream bufferedStream = new AudioInputStream(new BufferedInputStream(normalStream),
normalStream.getFormat(), AudioSystem.NOT_SPECIFIED);
Disclaimer: I would qualify this has a 'hack' to create random access. To my surprise I could find little about simulating random access using the mark/reset mechanism in InputStream. This might be because there is a caveat to it. Edit: John Skeet agrees with me on this approach.
| {
"pile_set_name": "StackExchange"
} |
Q:
Tool to create uml models in java - Developing practice
I should clarify my question here, I want to practice my programming skills and I want to develop a simple diagram modeling tool, something where I can move objects with the mouse, drag and drop, but I have no idea where to look to learn this kind of things in Java.
I hope my question is clear, thank you.
A:
Are you looking at a desktop application or a web based application?
For a desktop based application, you should start looking a swing or javafx to get started with the basic ideas and the move along.
For web application, it is a bit more complicated for a beginner. I suggest you to start with spring examples and then implement the front end with the help of some javascript library. Like JQuery, Dojo and Draw2D etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the ASP.NET MVC 4 model to link to an Oracle database
This is my first MVC application so please be patient and kind. I have created an ASP.NET MVC 4 Web Application in Visual Studio 2012. I created the database code first, so all I did was create the model and a data context and a SQL server database was created for me. Every time I changed the model I could just update the database. I also connected to an Oracle database get other data that I needed. These are the connection strings that were used:
<connectionStrings>
<add name="ApplicationDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=something;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="ConnectionString" connectionString="Data Source=something;Persist Security Info=True;" providerName="Oracle.DataAccess.Client" />
</connectionStrings>
However, the database related to the model needs to be in Oracle (and I need a script for it but that is next weeks question) not SQL.
I was hoping that I could just change the data context provider name in the web config like so:
<connectionStrings>
<add name="ApplicationDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=something;Integrated Security=True" providerName="System.Data.OracleClient" />
<add name="ConnectionString" connectionString="Data Source=something;Persist Security Info=True;" providerName="Oracle.DataAccess.Client" />
</connectionStrings>
But that is not working - it gives me errors.
Please note that I am NOT asking about OracleMembershipProvider. This question is unique in that I want the model to relate to an Oracle database. I am not worried about membership and user authentication etc. I have already taken care of that.
It seems like it should be simple enough, but I have googled until every link I find is purple.
I need you to tell me the steps and what to do (hopefully in the web config) to get my model to 'create' an Oracle database. Please.
A:
After reading through a ton of articles I found out that Oracle doesn't support code first (yet) and although there are some work-a-rounds it’s probably best to create scripts to create the db for us.
So as an alternate solution we to created the database in Oracle first and then connected to it from the MVC application.
We added an ADO.NET Entity Data Mode and in the EDM Wizard we said "Generated from database" and added a new connection to the Oracle database. You need Oracle Developer Tools for Visual Studio for this.
Add a new controller and for the data context class, choose Entities. Don't forget to add the connection string to the web config.
<add name="Entities" connectionString="...;provider=Oracle.DataAccess.Client;provider connection string=...;data source=...;" providerName="System.Data.EntityClient" />
This should be done before you start coding because you no longer have a model so I have had to change my code quite a lot. Not more than a day or two's work though.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add line on right and left of text
I have the following HTML and CSS:
body {
text-align: center;
}
div {
border: 1px solid black;
margin: 0 auto;
width: 200px;
}
p {
border: 1px solid red;
line-height: 0.5;
margin: 20px;
text-align: center;
}
span {
display: inline-block;
position: relative;
}
span:before,
span:after {
content: "";
position: absolute;
height: 5px;
border-bottom: 1px solid black;
top: 0;
width: 100%;
}
span:before {
right: 100%;
margin-right: 20px;
}
span:after {
left: 100%;
margin-left: 20px;
}
<div>
<p class="strike"><span>Phrase</span></p>
</div>
I added a line on left and right of text but with 2 problems:
The line gets outside of the P border;
The P does not fill the entire width off the container DIV.
How can I solve these problems?
A:
use left:0; and right:0 to make sure the lines stay within the borders
The margins you have on the p is what's stopping it from filling the entire width of the container.
Also the span is not really needed.
body {
text-align: center;
}
div {
border: 1px solid black;
margin: 0 auto;
width: 200px;
}
p {
border: 1px solid red;
line-height: 0.5;
/* margin: 20px; to span full width*/
text-align: center;
position: relative;
}
p:before,
p:after {
content: "";
position: absolute;
height: 1px;
background:black;
top: 50%;
transform:translateY(-50%);
width: 20%;
}
p:before {
left: 0;
}
p:after {
right: 0;
}
<div>
<p class="strike">Phrase</p>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaFX - How to make ComboBox hgrow?
I have a problem with JavaFX(8), HBox, ComboBox and HGrow.
HGrow does not work in combination with ComboBox.
(INFO: with TextField (instead of ComboBox), it works as expected!)
This is my FXML-Code:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox prefHeight="117.0" prefWidth="285.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.test.TestController">
<children>
<HBox prefHeight="105.0" prefWidth="196.0" VBox.vgrow="ALWAYS">
<children>
<ComboBox fx:id="fxCboTest" prefHeight="25.0" prefWidth="62.0" HBox.hgrow="ALWAYS" />
</children>
</HBox>
</children>
</VBox>
this Code will result in:
i also tried following code (without success, this code does nothing):
HBox.setHgrow(uiController.fxCboTest, Priority.ALWAYS);
Does anyone has an idea how to make an ComboBox HGrow?
A:
This is an answer to my own question.
After some testing, I found out that when setting Max Width to MAX_VALUE, it works:
This will result in following code/xml from SceneBuilder:
...
<children>
<ComboBox maxWidth="1.7976931348623157E308" prefWidth="150.0" HBox.hgrow="ALWAYS" />
</children>
...
where 1.7976931348623157E308 looks like Double.MAX_VALUE.
This will also work with multiple controls in Hbox.
In my opinion, this is not very consequently/consistently.
I still don't unserstand why HGrow does not work for ComboBox.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dropbox api for android returning null for AccessTokenSecret
I am using following code to authenticate with dropbox
AppKeyPair appKeys = new AppKeyPair(Constants.DROPBOX_APPKEY, Constants.DROPBOX_APPSECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
mDBApi.getSession().startOAuth2Authentication(this);
Once done
i call
mDBApi.getSession().finishAuthentication();
Account dropboxAccount = mDBApi.accountInfo();
String name = dropboxAccount.displayName;
AccessTokenPair pair = mDBApi.getSession().getAccessTokenPair();
String accessToken = mDBApi.getSession().getOAuth2AccessToken();
String accessTokenSecret = pair.secret;
However AccessTokenPair is null. How else am i suppose to get accessTokenSecret?
A:
In the Dropbox Android Core SDK, the getAccessTokenPair method returns an OAuth 1 access token, if you have one, as an AccessTokenPair. The getOAuth2AccessToken returns an OAuth 2 access token, if you have one. Note that OAuth 2 access tokens are only one piece (i.e, basically just one string) while OAuth 1 access tokens have two pieces (key and secret).
Since you are using startOAuth2Authentication, you only have an OAuth 2 access token, and getAccessTokenPair won't return anything.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does a '&&x' pattern match cause x to be copied?
In the documentation for std::iter::Iterator::filter() it explains that values are passed to the closure by reference, and since many iterators produce references, in that case the values passed are references to references. It offers some advice to improve ergonomics, by using a &x pattern to remove one level of indirection, or a &&x pattern to remove two levels of indirection.
However, I've found that this second pattern does not compile if the item being iterated does not implement Copy:
#[derive(PartialEq)]
struct Foo(i32);
fn main() {
let a = [Foo(0), Foo(1), Foo(2)];
// This works
let _ = a.iter().filter(|&x| *x != Foo(1));
// This also works
let _ = a.iter().filter(|&x| x != &Foo(1));
// This does not compile
let _ = a.iter().filter(|&&x| x != Foo(1));
}
The error you get is:
error[E0507]: cannot move out of a shared reference
--> src/main.rs:14:30
|
14 | let _ = a.iter().filter(|&&x| x != Foo(1));
| ^^-
| | |
| | data moved here
| | move occurs because `x` has type `Foo`, which does not implement the `Copy` trait
| help: consider removing the `&`: `&x`
Does this mean that if I use the &&x destructuring pattern, and the value is Copy, Rust will silently copy every value I am iterating over? If so, why does that happen?
A:
In Rust, function or closure arguments are irrefutable patterns.
In the Rust reference, it says:
By default, identifier patterns bind a variable to a copy of or move
from the matched value depending on whether the matched value
implements Copy.
So, in this case:
let _ = a.iter().filter(|&x| *x != Foo(1));
the closure is being passed a reference to a reference to the item being iterated; therefore x is bound to a copy of a reference to the item. You can always copy a reference (it is basically a no-op) so this always succeeds.
In this case:
let _ = a.iter().filter(|&&x| x != Foo(1));
x is being bound to a copy of the item itself - which fails if the item is not Copy.
The reference also says:
This can be changed to bind to a reference by using the ref keyword,
or to a mutable reference using ref mut.
That's not so useful in this case though: &&ref x results in x being a reference to the item, the same as if you had used &x.
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting Warnings With Proguard (With External Libraries)
I have enabled Proguard, and i'm trying to build the APK, and i'm getting a lot of warnings and don't know how to solve them .
I'm using Retrofit, Jsoup and other stock libraries, I'm getting the following warnings :
Warning:okio.DeflaterSink: can't find referenced class org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
Warning:okio.Okio: can't find referenced class java.nio.file.Files
Warning:okio.Okio: can't find referenced class java.nio.file.Path
Warning:okio.Okio: can't find referenced class java.nio.file.OpenOption
Warning:okio.Okio: can't find referenced class java.nio.file.Path
Warning:okio.Okio: can't find referenced class java.nio.file.OpenOption
Warning:okio.Okio: can't find referenced class org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
Warning:okio.Okio: can't find referenced class java.nio.file.Path
Warning:okio.Okio: can't find referenced class java.nio.file.OpenOption
Warning:okio.Okio: can't find referenced class java.nio.file.Path
Warning:okio.Okio: can't find referenced class java.nio.file.OpenOption
Warning:okio.Okio: can't find referenced class org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
Warning:retrofit2.Platform$Java8: can't find referenced method 'boolean isDefault()' in library class java.lang.reflect.Method
Warning:retrofit2.Platform$Java8: can't find referenced class java.lang.invoke.MethodHandles$Lookup
Warning:retrofit2.Platform$Java8: can't find referenced class java.lang.invoke.MethodHandle
Warning:retrofit2.Platform$Java8: can't find referenced class java.lang.invoke.MethodHandles
Warning:retrofit2.Platform$Java8: can't find referenced class java.lang.invoke.MethodHandle
Warning:retrofit2.Platform$Java8: can't find referenced class java.lang.invoke.MethodHandles$Lookup
Warning:retrofit2.Platform$Java8: can't find referenced class org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
Note: the configuration keeps the entry point 'android.support.v7.widget.FitWindowsLinearLayout { void setOnFitSystemWindowsListener(android.support.v7.widget.FitWindowsViewGroup$OnFitSystemWindowsListener); }', but not the descriptor class 'android.support.v7.widget.FitWindowsViewGroup$OnFitSystemWindowsListener'
Note: the configuration keeps the entry point 'android.support.v7.widget.RecyclerView { void setAccessibilityDelegateCompat(android.support.v7.widget.RecyclerViewAccessibilityDelegate); }', but not the descriptor class 'android.support.v7.widget.RecyclerViewAccessibilityDelegate'
Note: the configuration keeps the entry point 'android.support.v7.widget.RecyclerView { void setAdapter(android.support.v7.widget.RecyclerView$Adapter); }', but not the descriptor class 'android.support.v7.widget.RecyclerView$Adapter'
Note: the configuration keeps the entry point 'android.support.v7.widget.RecyclerView { void setRecyclerListener(android.support.v7.widget.RecyclerView$RecyclerListener); }', but not the descriptor class 'android.support.v7.widget.RecyclerView$RecyclerListener'
Note: the configuration keeps the entry point 'android.support.v7.widget.RecyclerView { void setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager); }', but not the descriptor class 'android.support.v7.widget.RecyclerView$LayoutManager'
Note: the configuration keeps the entry point 'android.support.v7.widget.RecyclerView { void setRecycledViewPool(android.support.v7.widget.RecyclerView$RecycledViewPool); }', but not the descriptor class 'android.support.v7.widget.RecyclerView$RecycledViewPool'
Note: the configuration keeps the entry point 'android.support.v7.widget.RecyclerView { void setViewCacheExtension(android.support.v7.widget.RecyclerView$ViewCacheExtension); }', but not the descriptor class 'android.support.v7.widget.RecyclerView$ViewCacheExtension'
Warning:there were 22 unresolved references to classes or interfaces.
Warning:there were 1 unresolved references to library class members.
Warning:Exception while processing task java.io.IOException: Please correct the above warnings first.
Here's my proguard :
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
##---------------Begin: proguard configuration for Gson ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature
# Gson specific classes
-keep class com.abohani.tdroms.SharedPreferencesTools { *; }
#-keep class com.google.gson.stream.** { *; }
# Application classes that will be serialized/deserialized over Gson
-keep class com.abohani.tdroms.** { *; }
A:
When you use ProGuard you have to always resolve all warnings.
These warnings tell you that the libraries reference some code and there are no sources for that. That might and might not be ok. It depends if the problematic code ever get called.
In this case warnings for Okio and Retrofit2 can be ignored. Package java.nio.* isn't available on Android and will be never called. You can safely ignore those warnings. Also Java 8 classes won't be used.
Add this to your ProGuard configuration, it should fix your problem:
-dontwarn okio.**
-dontwarn retrofit2.Platform$Java8
| {
"pile_set_name": "StackExchange"
} |
Q:
Timeout function in Python
I want to have a function, in Python (3.x), which force to the script itself to terminate, like :
i_time_value = 10
mytimeout(i_time_value ) # Terminate the script if not in i_time_value seconds
for i in range(10):
print("go")
time.sleep(2)
Where "mytimeout" is the function I need : it terminate the script in "arg" seconds if the script is not terminated.
I have seen good solutions for put a timeout to a function here or here, but I don't want a timeout for a function but for the script.
Also :
I know that I can put my script in a function or using something like subprocess and use it with a
timeout, I tried it and it works, but I want something more simple.
It must be Unix & Windows compatible.
The function must be universal i.e. : it may be add to any script in
one line (except import)
I need a function not a 'how to put a timeout in a script'.
A:
signal is not Windows compatible.
You can send some signals on Windows e.g.:
os.kill(os.getpid(), signal.CTRL_C_EVENT) # send Ctrl+C to itself
You could use threading.Timer to call a function at a later time:
from threading import Timer
def kill_yourself(delay):
t = Timer(delay, kill_yourself_now)
t.daemon = True # no need to kill yourself if we're already dead
t.start()
where kill_yourself_now():
import os
import signal
import sys
def kill_yourself_now():
sig = signal.CTRL_C_EVENT if sys.platform == 'win32' else signal.SIGINT
os.kill(os.getpid(), sig) # raise KeyboardInterrupt in the main thread
If your scripts starts other processes then see: how to kill child process(es) when parent dies? See also, How to terminate a python subprocess launched with shell=True -- it demonstrates how to kill a process tree.
| {
"pile_set_name": "StackExchange"
} |
Q:
setAttribute and removeAttribute doesn't work in chrome and firefox
setAttribute and removeAttribute doesn't work with chrome and firefox works only in IE.
below code is works fine in IE, doesn't work with any other exploerer
<head>
<script type="text/javascript">
function showUser2()
{
buttonpassvalue1.setAttribute("disabled","disabled");
buttonpassvalue.removeAttribute("disabled");
}
</script>
</head>
<button class="button" type="button" name="buttonpassvalue1" value="1" onclick="showUser2(this.value)">This will Disbale</button>
<button class="button" type="button" name="buttonpassvalue" value="-1" onclick="showUser2(this.value)">Press This</button>
its terminates when reach to above code
thanks for your help
A:
It's a bit complicated to explain why your code doesn't work in other browsers. It has something to do with how the "disabled" attribute is treated, as there are different kinds of internal nodes and containers.
However, this doesn't prevent you from achieving what you're doing:
if(val123 > gotnumber){
buttonpassvalue1.disabled='disabled';
buttonpassvalue.disabled='';
} else{
buttonpassvalue.disabled='disabled';
buttonpassvalue1.disabled='';
}
The "checked" attribute in checkboxes, and "readonly" in input fields work the same way.
Edit:
You have to give the elements IDs so you can grab them properly:
var buttonpassvalue=document.getElementById('buttonpassvalue');
var buttonpassvalue2=document.getElementById('buttonpassvalue2');
Edit again, with formatted and corrected code to disable the first button:
<head>
<script type="text/javascript">
function showUser2(v){
var buttonpassvalue1=document.getElementById('buttonpassvalue1');
var buttonpassvalue2=document.getElementById('buttonpassvalue1');
buttonpassvalue1.disabled='disabled';
buttonpassvalue.removeAttribute("disabled");
}
</script>
</head>
<button id="buttonpassvalue1" class="button" type="button" name="buttonpassvalue1" value="1" onclick="showUser2(this.value);">This will Disbale</button>
<button id="buttonpassvalue" class="button" type="button" name="buttonpassvalue" value="-1" onclick="showUser2(this.value)">Press This</button>
| {
"pile_set_name": "StackExchange"
} |
Q:
100% accuracy in classification with LIBSVM- What could be wrong?
I am building a model for classifying malignant breast tumors using LIBSVM. Here is the algorithm I am following:
Use Backward-elimination for feature selection.
Calculate C and gamma for each set of features using grid search.
Derive the most optimal C and gamma using 10-fold cross validation.
Using the above steps, find the best possible subset of features and the maximum accuracy.
The problem is that I am getting a 100% accuracy on a 80:20 dataset using LIBSVM. I've not excluded any feature, and I am NOT training and testing on the same data. Any hints where I could be wrong? Here are some other relevant information:
cost = [2^-10, 2^-8, 2^-6, 2^-4, 2^-2, 0.5, 1,
2, 2^2, 2^3, 2^4, 2^5, 2^6, 2^7, 2^8, 2^9, 2^10];
g = [2^-10, 2^-8, 2^-6, 2^-4, 2^-2, 2^-1, 1,
2, 2^2, 2^3, 2^4, 2^5, 2^6, 2^7, 2^8, 2^9, 2^10];
most optimal C = 1;
most optimal gamma = 9.7656e-04;
Accuracy on 50:50 test:train dataset: 98.5337%
Accuracy on 70:30 test:train dataset: 99.5122%
Dataset used: University of Wisconsin breast cancer dataset (682 entries).
A:
Summary: You didn't complain about the other two data sets; the 100% accuracy is reasonably consistent with those. What makes you think you should have a lower accuracy?
Let's look at the counts of misclassification:
50:50 data set -- 5 / 341 errors
70:30 data set -- 1 / 205 errors
80:20 data set -- 0 / 136 errors
The 80:20 results are sufficiently consistent with your prior results: your accuracy has increased to (apparently) something over 99.8%.
Demanding maximum accuracy from your training suggests that it may well retain all features, with a distinct danger of over-fitting. However, since you apparently find that the first two data sets are acceptable, I intuit that the data set is highly self-consistent. I find that consistency odd from my experience, but you don't describe the data set's properties, or even give us samples or a useful link to check.
| {
"pile_set_name": "StackExchange"
} |
Q:
Number of actions of $\mathbb Z$
Let $X$ be a finite set. Determine the number of actions of $\mathbb Z$ on $X$.
If $X$ is a finite set with $|X|=m$, then $|\{f:X \to X : \text{f is bijective}\}|=m!$.
Finding the number of actions is counting the number of morphisms $\phi:\mathbb Z \to Sym(X)$. By the condition $\phi(1)=Id_{Sym(x)}$ and the fact that $\phi$ is a morphism, we have $\phi(n)=\phi(1+...+1)=Id_{Sym(X)} \circ ... \circ Id_{Sym(X)}=Id_{Sym(X)}$, so there is an only possible action which is the "trivial" action, which is $g.x=x$ for all $g \in \mathbb Z$, $x \in X$.
I would like to verify if my solution is correct.
A:
As said by @anon, your solution is incorrect. In some sense you had a fruitful idea by focussing on $\phi(1)$, but you applied that focus incorrectly by confusing additive and multiplicative notation.
Instead, use the fact that for any group $G$ with group operation denoted $g \cdot h$, a homomorphism $\phi : \mathbb{Z} \to G$ is completely determined by the value of the single element $\phi(1) \in G$, because
$$\phi(n) = \phi(\,\underbrace{1 + \cdots + 1}_{\text{($n$-times)}}\,) = \underbrace{\phi(1) \cdot \ldots \cdot \phi(1)}_{\text{($n$-times)}} = \phi(1)^n
$$
Can you take it from there?
| {
"pile_set_name": "StackExchange"
} |
Q:
Two-way data binding in Android or MonoDroid?
Does Android support XAML-like two-way data binding using Java or C#?
A:
Not natively. Take a look at android-binding though.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to use htaccess redirectmatch with query_string?
im trying to redirect "search.php?q=somethinghere" to "search/somethinghere/" but I can't do it! I'm trying to send form "<form action="search/" method="get" name="search">" like this but url goes to "search/?q=somethinghere"
RedirectMatch 301 ^/search.php?q=(.*)$ http://domain.com/search/$1/ this is also not working. whats the problem?
I don't want "?q=" in URL.
A:
Unless you have a typo above the problem is that you're trying to redirect:
^/search.php?q=(.*)$
but the URL you're receiving is:
search/?q=somethinghere
(the difference is the .php in your redirect rule)
You may want to try using the following redirect rule instead:
RedirectMatch 301 ^/search?q=(.*)$ http://domain.com/search/$1/
| {
"pile_set_name": "StackExchange"
} |
Q:
Maven mojo plugin to load class from hosting project
I have a custom plugin that loads classes, e.g.
Class<?> clazz = Class.forName(NAME_OF_CLASS_FROM_HOST_DEPENDENCIES);
NAME_OF_CLASS_FROM_HOST_DEPENDENCIES - is the class that exists in the dependencies of project, where this plugin is used.
in hosting project pom, I call plugin like this:
<plugin>
<groupId>com.plugins</groupId>
<artifactId>the_plugin</artifactId>
<version>1.0-SNAPSHOT</version>
<executions>
<execution>
<id>do</id>
<phase>process-classes</phase>
<goals>
<goal>do</goal>
</goals>
</execution>
</executions>
</plugin>
Getting ClassNotFoundException
it's important , those dependencies defined in pom as
<scope>provided</scope>
A:
Ended up with following.
List<URL> listUrl = new ArrayList<URL>();
Set<Artifact> deps = project.getDependencyArtifacts();
for (Artifact artifact : deps) {
final URL url = artifact.getFile().toURI().toURL();
listUrl.add(url);
}
newClassLoader = new URLClassLoader(listUrl.toArray(new URL[listUrl.size()]), Thread.currentThread().getContextClassLoader());
| {
"pile_set_name": "StackExchange"
} |
Q:
Comparing pd.Series and getting, what appears to be, unusual results when the series contains None
I am wondering why comparing two identical series with None value returns False:
pd.Series(['x', 'y', None]) == pd.Series(['x', 'y', None])
0 True
1 True
2 False
dtype: bool
I would expect all of results to be True. If I create an array, from the series, and compare I get the expected result:
pd.Series(['x', 'y', None]).values == pd.Series(['x', 'y', None]).values
array([ True, True, True])
Why are the two identical series with None not equal to each other? Am I missing something?
I would expect this behavior with np.nan because np.nan != np.nan; however, None == None
A:
This is by design:
see the warnings box: http://pandas.pydata.org/pandas-docs/stable/missing_data.html
This was done quite a while ago to make the behavior of nulls
consistent, in that they don't compare equal. This puts None and
np.nan on an equal (though not-consistent with python, BUT consistent
with numpy) footing.
So this is not a bug, rather a consequence of stradling 2 conventions.
I suppose the documentation could be slightly enhanced.
For equality of series containing null values, use pd.Series.equals:
pd.Series(['x', 'y', None]).equals(pd.Series(['x', 'y', None])) # True
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Swift Vapor instead of PHP
I need an advise from an experienced Swift developer who have used Vapor framework.
I was planning to use php to create a control panel for an iOS and Android apps, but I was told to use Vapor http://vapor.codes/ instead of it.
Can anyone answer this question I have about Vapor? Searching internet didn't give me much answers and created some confusion.
When Vapor is ready, will we have a front end for it? I mean a user interface. Like I would have if the backend was created using php, and it's frontend using Bootstrap?
A:
In Vapor you could render html pages using Leaf
So yeah, you could build some website and/or admin panel using Vapor.
| {
"pile_set_name": "StackExchange"
} |
Q:
Protecting the SQLite database
In my app I have a database which must be protected with a key to restrict other apps on this device from accessing it.
The problem is that I cannot get the signing key in runtime: whatever I do the CodeSigningKey.get(...) always returns null.
This is my code:
final CodeSigningKey key = CodeSigningKey.get(AbstractDB.class);
if (key != null) {
Log.d("+ GOT SIGNING KEY");
final DatabaseSecurityOptions secopt = new DatabaseSecurityOptions(key);
db = DatabaseFactory.create(name, secopt);
} else {
Log.d("- SIGNING KEY IS NULL");
}
I have downloaded Signing Authority Tool and created a TEST.key using it, and put it in {project_root}/keys/TEST.key in my Eclipse project.
Also, I've doule-clicked TEST.key in Eclipse and selected AbstractDB class to be signed with it.
I run my app on a real device, not in the simulator.
I run it as follows:
start debugging on a device - this initiates packaging and siging the .cod file. (However, in the signing tool window I get a warning about my TEST.key: "Not registered" and "Please contact the signer and register with the Signing Authority.")
with Signing Authority Tool I sign my .cod file obtained on step 1 using my TEST.key
I click debug on device once again, and the signing tool signs the main .cod file again, and then the app starts on the device.
However, the key I get from CodeSigningKey.get(..) is always null.
What do I do wrong?
Solution
After a hint from Michael I was able to resolve this problem.
First of all, indeed I needed an object instance in CodeSigningKey.get(...). However, there is one thing you should aware of: if your object extends some classes and/or implements some interfaces, then ALL of those must be signed with same key in order to work. If any of ancestor classes/interfaces is not signed you will get null.
This can be a problem if your hierarchy is deep enough. Information about which classes are signed with which keys is stored in BlackBerry_App_Descriptor.xml, and copied into parameters of signing tool when you click Debug. It may happen that command line gets too long so the signing tool fails with "Invalid parameter" message in the console.
So I've extracted a class specially for the signing purpose:
final public class SignatureClass {
private static final SignatureClass INSTANCE = new SignatureClass();
private SignatureClass() { }
public static CodeSigningKey getKey() {
return CodeSigningKey.get(INSTANCE);
}
}
I sign only this class with my key and use SignatureClass.getKey() to get the key.
PS: Also, if you move/rename classes or keys check that signing references in the BlackBerry_App_Descriptor.xml are valid. They aren't updated automatically.
Update
How to issue your own signing key properly.
In the process I've described above I had to sign the .cod file with a separate tool because the built-in signing tool gave error "Not registered" for my TEST.key. In order to fix this and have your .cod signed automatically in one go, do following steps.
After you have created your key with Signing Authority Tool, launch the WebAdmin utility included in that app. It offers you to create the keys database and launch the WebSigner service.
Having successfully started the WebAdmin, click menu Record->Add. You'll get a window where you can create a .csi file. Configure: number of requests - infinite; expiry date - never; email notifications - none; email CSI file - no. Click OK and you'll see a dialog with a generated PIN - save it for future use. The .csi file is generated and saved in /data folder in Signing Authority Tool.
Install the .csi file using Eclipse->Window->Preferences->BlackBerry plugin->Signature Tool->Install new keys and register it using the PIN from step 2.
Done. From now on, when signing with RIM keys you'll have your .cod automatically signed also with your key.
A:
I believe you need an object instance from your app, instead of a class object. In this case 'this' ought to work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem with ACM bibliography style
I am writing a paper for an ACM journal. The problem is when I use the following commands:
\bibliographystyle{ACM-Reference-Format}
\bibliography{references}
the references appear without number. And when I replace “ACM-Reference-Format” with “acm” in the “\bibliographystyle” command, the references with URL loose their URLs. I'm wondering if anyone knows how I can solve this problem. My goal is to have a numbered reference list in which URLs do not disappear. I am working in Overleaf environment and use Mendeley to import my references to the Overleaf. Any advice is appreciated.
A:
(too long for a comment, hence posted as an answer)
I'm assuming you use the acmart document class. If that's the case, the ACM-Reference-Format bibliography style should have no problems typesetting the numbers of bibliographic entries or their URL strings -- assuming the URL strings are stored in a field called url.
The much older acm bibliography style does not recognize the url field and hence simply ignores its contents.
\RequirePackage{filecontents}
\begin{filecontents*}{mybib.bib}
@misc{w:19,
author = "Woody",
title = "Problem with {ACM} bibliography style",
year = 2019,
url = "https://tex.stackexchange.com/questions/474684/problem-with-acm-bibliography-style",
}
\end{filecontents*}
\documentclass{acmart}
\bibliographystyle{ACM-Reference-Format}
\begin{document}
\cite{w:19}
\bibliography{mybib}
\end{document}
If you do not use the acmart document class but still wish to use the ACM-Reference-Format bibliography style, be sure to (a) load the natbib package with the option numbers and (b) either the xurl or the url package, the latter preferably with the options hyphens and spaces.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you do a Nested if-else statement in Prolog?
If I have this function:
min(List1, List2, Output) :-
length(List1, N),
length(List2, M),
( N < M ->
Output = 'true'
; Output = 'false'
).
but what if I wanted to also check if N == M? Maybe like this:
min(List1, List2, Output) :-
length(List1, N),
length(List2, M),
( N < M ->
Output = 'true'
; ( N = M ->
Output = 'equal'
; Output = 'other'
)
).
Doesn't seem to work.
A:
In nested if-then-else, it is common to omit redundant parentheses, yielding:
min(List1, List2, Output) :-
length(List1, N),
length(List2, M),
( N < M -> Output = true
; N =:= M -> Output = equal
; Output = other
).
In Prolog, it is good practice to use pattern matching when possible, because this yields more general, more declarative and more readable programs than using if-then-else. For this particular case of conditions, check out the compare/3 library predicate. compare/3 lets you reify the relation of the two lengths into an atom, and you can use that atom to describe the three conditions with pattern matching:
lists_output(List1, List2, Output) :-
length(List1, L1),
length(List2, L2),
compare(Order, L1, L2),
order_output(Order, Output).
order_output(<, true).
order_output(=, equal).
order_output(>, other).
Sample queries and results:
?- lists_output([_,_], [_,_,_], Output).
Output = true.
?- lists_output([_,_,_], [_,_,_], Output).
Output = equal.
?- lists_output([_,_,_,_], [_,_,_], Output).
Output = other.
A:
Your nesting of implication (->) looks correct here. Note that, in your definition, N and M will be integers (assuming the calls to length/2 both succeed), so can be compared with == instead of unification (=). In fact, you could even use arithmetic equals in SWI-PROLOG, namely, =:=:
min(List1, List2, Output) :-
length(List1, N),
length(List2, M),
(N < M ->
Output = 'true'
; (N =:= M ->
Output = 'equal'
; Output = 'other'
)
).
Testing:
1 ?- min([a],[b],O).
O = equal.
2 ?- min([a,c],[b],O).
O = other.
3 ?- min([a,c],[b,d],O).
O = equal.
4 ?- min([a,c],[b,d,e],O).
O = true.
| {
"pile_set_name": "StackExchange"
} |
Q:
SAI - DAI Symbol Not Captured Right Web3.py
trying to capture the symbol of the receipts of transaction using web3.py. I am getting the DAI, DAI and DAI... while this should return SAI, SAI, DAI. Although, I checked that the correct SAI contract is being picked up under the logs of the transaction. Can someone tell me if this is a bug in my code or a bug with how web3.py pick up the symbol from the node?
import json
import urllib.request
from web3 import Web3
import web3
provider = Web3.HTTPProvider('https://mainnet.infura.io/v3/XXXXXXXXXXXXXXXXXXX')
w3 = Web3(provider)
ether_scan_api ='XXXXXXXXXXXXXXXXXXXXXXXX'
tx_hash = '0x52caaf79bf913064a70a6c9d917fd4190cdb099fe79e7d3a9dfe0600e1cfbc81'
receipt= w3.eth.getTransactionReceipt(tx_hash)
transfer_event = "Transfer(address,address,uint256)"
transfer_event_hashed = w3.keccak(text=transfer_event)
transactions = list()
def get_abi(erc_20_address):
requrl = 'https://api.etherscan.io/api?module=contract&action=getabi&address='+erc_20_address+'&apikey='+ ether_scan_api
while True:
with urllib.request.urlopen(requrl) as url:
if url.code != 200:
raise NotImplementedError('I don\'t know how to handle HTTP code {} :('.format(url.code))
else:
result = json.loads(url.read())
if result['status'] == '1':
break
return json.loads(result['result'])
for log in receipt.logs:
if log["topics"][0]==transfer_event_hashed:
contract_address = w3.eth.web3.toChecksumAddress(log["address"])
token_contract = w3.eth.contract(address=contract_address ,abi=get_abi(contract_address))
symbol = str(token_contract.functions.symbol().call()[:3])
print(symbol)
Printing the receipt returns this
AttributeDict({'address': '0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359',
'blockHash': HexBytes('0x9e48b35141e53758171239d618a02a9a0e073506b12a5fecca59240c0e032487'),
'blockNumber': 9560511,
'data': '0x00000000000000000000000000000000000000000000000000d529ae9e860000',
'logIndex': 156,
'removed': False,
'topics': [HexBytes('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'),
HexBytes('0x00000000000000000000000017b11c26f6cb263864610379a6ebec29da49aa2d'),
HexBytes('0x000000000000000000000000c73e0383f3aff3215e6f04b0331d58cecf0ab849')],
'transactionHash': HexBytes('0x52caaf79bf913064a70a6c9d917fd4190cdb099fe79e7d3a9dfe0600e1cfbc81'),
'transactionIndex': 111})
A:
I'm sorry to tell you this, but the symbol value in both contracts is DAI.
The only difference being that the "SAI" contract implements bytes32 public symbol, while the DAI contract implements string public symbol.
The ERC20 standard dictates that the latter should be used.
Unfortunately, some token vendors have failed to fully comply with the standard, in particularly at the early days of the blockchain; I guess they thought it wouldn't matter much.
Unfortunately it does. You are fetching the interface from Etherscan and then use it in order to create a contract object, but most applications assume the interface function function symbol() public pure returns (string memory), and when they call it, they either get a runtime exception or incorrect data.
In any case, as you can see here, the value returned by the symbol function in the "SAI" contract is:
0x4441490000000000000000000000000000000000000000000000000000000000
If you convert it to ASCII, then you get:
0x44 == D
0x41 == A
0x49 == I
| {
"pile_set_name": "StackExchange"
} |
Q:
Dancing images in beamer
When creating a slide using pauses and \only, I am getting cases where the content shifts between slides. I have tried using overlayarea and overprint as described in Avoiding jumping frames in beamer (in every combination I could think of - in one or the other or both columns, around the whole thing, using \only, using \onslide), but I still get dancing images.
Minimal example follows. Note, while debugging I am including the same image 5 times, but in our end document I will be using 5 different images (all the same size). [ Update: The dancing seems to happen on the slide where the visible portion of the itemize environment exceeds the height of the image, so this may depend on the image size ]
\documentclass[t]{beamer}
\usetheme{Singapore}
\usecolortheme{rose}
\begin{document}
\begin{frame}{Riverbend Community Math Center}
\begin{columns}[c]
\begin{column}{0.6\textwidth}
\begin{itemize}[<+->]
\item Founded in Summer of 2006
\item Centered in St.~Joseph County, Indiana
\item Independent, non-profit organization
\item Serves people ages 5 through adult
\item Promotes interest and confidence in mathematics
\end{itemize}
\end{column}
\begin{column}{0.4\textwidth}
\only<1>{\includegraphics[width=\textwidth]{RiverbendCommunityMathCenter}}
\only<2>{\includegraphics[width=\textwidth]{RiverbendCommunityMathCenter}}
\only<3>{\includegraphics[width=\textwidth]{RiverbendCommunityMathCenter}}
\only<4>{\includegraphics[width=\textwidth]{RiverbendCommunityMathCenter}}
\only<5>{\includegraphics[width=\textwidth]{RiverbendCommunityMathCenter}}
\end{column}
\end{columns}
\end{frame}
\end{document}
For complete information, I am using XeLaTeX but see the same dancing when compiling with plain LaTeX.
A:
This seems to be caused by the center alignment of the two columns (because you use {columns}[c]). I would change that to top alignment ([t]) and add \vspace{0cm} on top of the second column to create a narrow top line to which the first line of the first column is aligned to. This is basically the same solution as for Aligning image and text on top, with minipages and Vertical alignment of tikzpicture with text? just for beamer columns.
\documentclass[t]{beamer}
\usetheme{Singapore}
\usecolortheme{rose}
\begin{document}
\begin{frame}{Riverbend Community Math Center}
\begin{columns}[t]
\begin{column}{0.6\textwidth}
\begin{itemize}[<+->]
\item Founded in Summer of 2006
\item Centered in St.~Joseph County, Indiana
\item Independent, non-profit organization
\item Serves people ages 5 through adult
\item Promotes interest and confidence in mathematics
\end{itemize}
\end{column}
\begin{column}{0.4\textwidth}
\vspace{0cm}
\only<1>{\includegraphics[width=\textwidth]{RiverbendCommunityMathCenter}}
\only<2>{\includegraphics[width=\textwidth]{RiverbendCommunityMathCenter}}
\only<3>{\includegraphics[width=\textwidth]{RiverbendCommunityMathCenter}}
\only<4>{\includegraphics[width=\textwidth]{RiverbendCommunityMathCenter}}
\only<5>{\includegraphics[width=\textwidth]{RiverbendCommunityMathCenter}}
\end{column}
\end{columns}
\end{frame}
\end{document}
Note that instead \only<n>{\includegraphics[...]{...}} you can also write \includegraphics<n>[...]{...} which should have the same effect, but is shorter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Compare values of one column in a table based on parent and child relation
I have the following table sample :
+----+-------+-------------+--------------+-----------+-----------+
| ID | value | CommonField | Parentfield | child1 | child2 |
+----+-------+-------------+--------------+-----------+-----------+
| 1 | abc | 123 | | 123child1 | 123child2 |
| 2 | abc | 123child1 | 123 | | |
| 3 | abc | 123child2 | 123 | | |
| 4 | def | 456 | | 456child1 | 456child2 |
| 5 | xyz | 456child1 | 456 | | |
| 6 | def | 456child2 | 456 | | |
+----+-------+-------------+--------------+-----------+-----------+
Now my problem is that I have to compare 'value' field based on the Parent child relation in the table. I need to find when 'value' field is equal for both child1 and child2 and filter records based on that condition. My table has 1000 rows in the similar way.
I did try self joining the table and created a flag field which tells when 'value' is equal in both child rows.
Here is my Query:
Query:
Select p.id,
p.value,
p.CommonField,
p.Parent field,
p.child1,
p.child2,
CASE
When p.child1 IS NULL
THEN p.parentfield
ELSE c1.parentfield
END AS Parent1
CASE
When p.child1 IS NULL
THEN p1.child1
ELSE p.child1
END AS child1p
CASE
When p.child2 IS NULL
THEN p1.child2
ELSE p.child2
END AS child2p
CASE
When c1.value = c2.value
THEN 1
ELSE 0
END AS IS_Childequal
from Table as a
Inner Join Table p ON a.id = p.id
Left Join Table p1 ON p1.commonfield = p.parentfield
Left Join Table c1 ON c1.commonfield = p.child1
Left Join Table c2 ON c2.commonfield = p.child2
Results:
+----+-------+-------------+--------------+-----------+-----------+---------+-----------+-----------+---------------+
| ID | value | CommonField | Parent field | child1 | child2 | parent1 | child1p | child2p | IS_childequal |
+----+-------+-------------+--------------+-----------+-----------+---------+-----------+-----------+---------------+
| 1 | abc | 123 | | 123child1 | 123child2 | 123 | 123child1 | 123child2 | 1 |
| 2 | abc | 123child1 | 123 | | | 123 | 123child1 | 123child2 | 1 |
| 3 | abc | 123child2 | 123 | | | 123 | 123child1 | 123child2 | 1 |
| 4 | def | 456 | | 456child1 | 456child2 | 456 | 456child1 | 456child2 | 1 |
| 5 | xyz | 456child1 | 456 | | | 456 | 456child1 | 456child2 | 1 |
| 6 | def | 456child2 | 456 | | | 456 | 456child1 | 456child2 | 1 |
+----+-------+-------------+--------------+-----------+-----------+---------+-----------+-----------+---------------+
My new Flag field returns 1 always even if 'value' field is not equal.
What am I doing wrong Here?
A:
Your problem must be elsewhere because with the sample data you provided your query works fine:
SQL fiddle with your data and query
Result from your query in SQL fiddle (only first row has IS_Childequal=1 as expected):
| id | value | CommonField | Parentfield | child1 | child2 | Parent1 | child1p | child2p | IS_Childequal |
|----|-------|-------------|-------------|-----------|-----------|---------|-----------|-----------|---------------|
| 1 | abc | 123 | (null) | 123child1 | 123child2 | 123 | 123child1 | 123child2 | 1 |
| 2 | abc | 123child1 | 123 | (null) | (null) | 123 | 123child1 | 123child2 | 0 |
| 3 | abc | 123child2 | 123 | (null) | (null) | 123 | 123child1 | 123child2 | 0 |
| 4 | def | 456 | (null) | 456child1 | 456child2 | 456 | 456child1 | 456child2 | 0 |
| 5 | xyz | 456child1 | 456 | (null) | (null) | 456 | 456child1 | 456child2 | 0 |
| 6 | def | 456child2 | 456 | (null) | (null) | 456 | 456child1 | 456child2 | 0 |
Edit: Since you comment that you need IS_childequal=1 for child rows as well you better use a subquery for getting that value and then join it with the original table using the ID the for parents and ParentField for childs:
select ID, value, CommonField, ParentField, Child1, Child2,
IS_Childequal, Child1Value, Child2Value
from Table1 as p
left join (select p.ID AS ParentID, p.CommonField as Parent,
c1.value as Child1Value, c2.value as Child2Value,
case when c1.value = c2.value then 1 else 0 end as IS_Childequal
from Table1 as p
left join Table1 c1 ON c1.CommonField = p.child1
left join Table1 c2 ON c2.CommonField = p.child2
where p.ParentField is null)
as parents on p.ID=ParentID or ParentField=Parent
Results (SQL fiddle):
| ID | value | CommonField | ParentField | Child1 | Child2 | IS_Childequal | Child1Value | Child2Value |
|----|-------|-------------|-------------|-----------|-----------|---------------|-------------|-------------|
| 1 | abc | 123 | (null) | 123child1 | 123child2 | 1 | abc | abc |
| 2 | abc | 123child1 | 123 | (null) | (null) | 1 | abc | abc |
| 3 | abc | 123child2 | 123 | (null) | (null) | 1 | abc | abc |
| 4 | def | 456 | (null) | 456child1 | 456child2 | 0 | xyz | def |
| 5 | xyz | 456child1 | 456 | (null) | (null) | 0 | xyz | def |
| 6 | def | 456child2 | 456 | (null) | (null) | 0 | xyz | def |
| {
"pile_set_name": "StackExchange"
} |
Q:
Make a folder with an empty file with a specific name in each subfolder
A column in a csv has a couple of numbers in each row:
col
12
14
11
..
I have made a folder for every row with that name with this:
import pandas as pd
import os
path = ..
fn = pd.read_csv(r'C:\Users\user\Desktop\xlfile\asc.csv',header = None)
for i in df["col"].astype(str):
os.mkdir(os.path.join(path, i))
os.mkdir(os.path.join(path, i)) #this has to be make in the last folder
#file from a certain path to be copied
Now I want to make a folder that has a specific file in every one of these folders.
folder name : new_f
and the file is located in a path
path: ...
How do I make a folder named new_f and make a copy of that file in that path to every folder made?
UPDATE:
Further explanation
What the answer below did but its just that these files need to be in one more folder too.
Example:
the folders now are after your code in the answer:
12 // file.shp
14 // file.shp
while they should be
12 // new_folder// file.shp annd file.shx and file.dbf
path = 'this path has the above files scattered so maybe it can read what files are there and copy them to each of the folders as said.
A:
You can use shutil to copy the file into your directories:
import pandas as pd
import os
from shutil import copy
path = ..
file_names = ['text1.txt', 'text2.txt', 'text3.txt'] # replace with your file you want copied
df = pd.read_csv(r'C:\Users\user\Desktop\xlfile\asc.csv',header = None)
for i in df["col"].astype(str):
dest = os.path.join(path, i)
os.mkdir(dest)
dest = os.path.join(path, i, 'new_folder')
os.mkdir(dest)
for file_name in file_names:
source = os.path.join(path, file_name)
copy(source, dest)
This produces 3 folders called 11, 12, and 14, and each contains a copy of the file text.txt.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I prevent overlaying divs from producing a gap at certain resolutions? (google zeitgeist)
Here is my website: http://designobvio.us/portfolio/body.html
Here's my aspiring website: http://www.googlezeitgeist.com/en/top-searches/battlefield_three
I'm getting pretty close to the layout; however, when you shrink the browser vertically too much it produces a gap.
Also I cant even debug resolutions great then mine(1280x800) which I'm sure something else breaks in the other direction.
Update: could it be the general size of the photo? Zeitgeist uses 800x800 (sq) image; while i use a rectangle?
The problem could also be an error in the structure of my HTML? (this is a really tough layout for me)
<section class="bodySection">
<div id="body-wrapper-left" class="class="">
<div id="me"></div>
<div id="pattern"></div>
</div>
<div id="body-wrapper-right"> </div>
<div class="clearfix"></div>
</section>
<!--end of bodySection-->
or my CSS:
html, body, #body-wrapper, .bodySection {
height: 100%;
}
#body-wrapper-left {
position: relative;
width:35%;
height: 100%;
}
#body-wrapper-left #me {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: url('http://designobvio.us/portfolio/img/Me.jpg') repeat-y;
z-index: 1;
-o-background-size:auto 100%;
-webkit-background-size:auto 100%;
-moz-background-size:auto 100%;
background-size:auto 100%;
-webkit-transition: all 0.20s ease-out;
-moz-transition: all 0.20s ease-out;
-o-transition: all 0.20s ease-out;
transition: all 0.20s ease-out;
}
#body-wrapper-left #pattern {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: url('http://designobvio.us/portfolio/img/sliderBG.png') repeat;
z-index: 2;
}
#body-wrapper-right {
position: absolute;
height: 100%;
right:0;
top:0;
min-width:65%;
width:65%;
background:#fff;
z-index:9;
}
To my knowledge it looks like its a set min-height // min-width (perhaps a max in the other direction) value somewhere. Anyone know where and what to select so I can unify widths and heights so the effect is more like Google Zeitgeist?
A:
You could use CSS3's background cover option.
#element {
background: url(http://designobvio.us/portfolio/img/Me.jpg) center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
width: 50%;
height: 100%;
position: absolute;
}
Example: http://jsfiddle.net/B7W2K/20/
Though obviously this won't work in older browsers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Keyboard extension documentContextAfterInput out of sync
We're working on a keyboard extension and I've encountered this weird bug on microsoft office word (we haven't seen it anywhere else yet...) where the the text received from super.textDocumentProxy.documentContextAfterInput simply is out of sync with the current cursor position.
I don't get how that is even possible but the result is pretty consistent.
We write: 'Tom'
Select suggestion 'Tomorrow'
Select next suggestion 'he'
At the start of step 3 the cursor should be at 'Tomorrow |' (Cursor marked with '|') but the documentContextAfterInput will be '\0'. Now I can handle that but if I keep inserting text from suggestions we get 1 random char from the text instead of what it actually should be (nil or empty). The problem is the afterInput is completely inconsistent with the current cursor position. I've even tried moving the cursor to the start of the text and then to the end (same result).
Luckily the BeforeInput method works flawlessly...
Now any suggestions to how I can workaround, fix or explain this will be greatly appreciated.
Edit:
I'm starting to suspect that it is due to character encoding or microsoft carriage return somehow getting broken.
A:
Multiple issues is the cause of this. First: microsoft do use some kind of hidden characters. Second: iOS application have some control about how to handle movecursor which can conflict with how keyboard-extension would expect it to work. This will usually not give any major issues as most keyboard-extension are fairly simple, but if you like us make complex text analyzation and handling you will get some buggy behaviour.
| {
"pile_set_name": "StackExchange"
} |
Q:
Como usar a função 'len' num template em python - Flask
Tenho uma AppWeb em python-Flask que gostaria de mostra a quantidade de jogadores online, só que estou meio perdido nessa parte já tentei {% len(data) %} e {% data|length %} e nenhum dois métodos teve resultado. se alguém poder me ajuda nessa parte.
Observação: a variavel "data" me traz um dicionario json do servido do jogo.
codigo em html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Infinite Fight Brasil</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
{% extends "bootstrap/base.html" %}
{% block content %}
<div id="carregando" class="center" align="center">
<br><br><iframe src='https://www.liveflightapp.com/embed?key=d92f147c-1300-462f-84a0-e198ff0aeb01' width='80%'height='500px' frameborder='0' scrolling='no'></iframe>
<br>
<br>
</div>
<br>
<br>
<div id="quant">
<h2> No momento a xxx online nesse momento.</h2>
</div>
<br>
<div class="container">
<table id="customers">
<tr>
<th>Piloto</th>
<th>Voo</th>
<th>DEP - ARR</th>
<th>Altitude</th>
<th>Velocidade</th>
<th>Online</th>
</tr>
{% for i in range(930) %}
{% if "IFBR" in data[i]["DisplayName"] %}
<tr>
<td>{{data[i]["DisplayName"]}}</td>
<td>{{data[i]["CallSign"]}}</td>
<td>--------</td>
<td>{{"{0:.0f} ft".format (data[i]["Altitude"])}}</td>
<td>{{"{0:.0f} kts".format (data[i]['Speed'])}}</td>
<td>Expert Server</td>
</tr>
{% endif %}
{% endfor %}
</table>
<br>
<br>
<br>
</div>
{% endblock %}
<br>
<br>
</body>
</html>
-->
parte do flask
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from models.database import BancoDados
app = Flask(__name__)
Bootstrap(app)
@app.route('/')
def index():
return render_template('index.html', data=BancoDados.total())
if __name__ == '__main__':
app.run(debug=True)
A:
Simples, basta usar o filtro do próprio jinja2:
<h2> No momento a {{ data|length }} online nesse momento.</h2>
Ou também:
<h2> No momento a {{ data|count }} online nesse momento.</h2>
Mesma coisa para o "for":
{% for i in range(data|length) %}
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing radio button background image
How can I change the background image inside the active radio button
Instead of the default one (I am using redmond) I want to use aristo
.ui-radiobutton-icon {
background-image:????? /images/ui-icons_38667f_256x240.png.jsf)";
}
What is the syntax ?
Thanks
A:
You cannot change the radio button styling purely with CSS.
I would recommend a javascript library that allows you to do this, such as UniformJS for jQuery.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to handle large memory footprint in Python?
I have a scientific application that reads a potentially huge data file from disk and transforms it into various Python data structures such as a map of maps, list of lists etc. NumPy is called in for numerical analysis. The problem is, the memory usage can grow rapidly. As swap space is called in, the system slows down significantly. The general strategy I have seen:
lazy initialization: this doesn't seem to help in the sense that many operations require in memory data anyway.
shelving: this Python standard library seems support writing data object into a datafile (backed by some db) . My understanding is that it dumps data to a file, but if you need it, you still have to load all of them into memory, so it doesn't exactly help. Please correct me if this is a misunderstanding.
The third option is to leverage a database, and offload as much data processing to it
As an example: a scientific experiment runs several days and have generated a huge (tera bytes of data) sequence of:
co-ordinate(x,y) observed event E at time t.
And we need to compute a histogram over t for each (x,y) and output a 3-dimensional array.
Any other suggestions? I guess my ideal case would be the in-memory data structure can be phased to disk based on a soft memory limit and this process should be as transparent as possible. Can any of these caching frameworks help?
Edit:
I appreciate all the suggested points and directions. Among those, I found user488551's comments to be most relevant. As much as I like Map/Reduce, to many scientific apps, the setup and effort for parallelization of code is even a bigger problem to tackle than my original question, IMHO. It is difficult to pick an answer as my question itself is so open ... but Bill's answer is more close to what we can do in real world, hence the choice. Thank you all.
A:
Have you considered divide and conquer? Maybe your problem lends itself to that. One framework you could use for that is Map/Reduce.
Does your problem have multiple phases such that Phase I requires some data as input and generates an output which can be fed to phase II? In that case you can have 1 process do phase I and generate data for phase II. Maybe this will reduce the amount of data you simultaneously need in memory?
Can you divide your problem into many small problems and recombine the solutions? In this case you can spawn multiple processes that each handle a small sub-problem and have one or more processes to combine these results in the end?
If Map-Reduce works for you look at the Hadoop framework.
A:
Well, if you need the whole dataset in RAM, there's not much to do but get more RAM. Sounds like you aren't sure if you really need to, but keeping all the data resident requires the smallest amount of thinking :)
If your data comes in a stream over a long period of time, and all you are doing is creating a histogram, you don't need to keep it all resident. Just create your histogram as you go along, write the raw data out to a file if you want to have it available later, and let Python garbage collect the data as soon as you have bumped your histogram counters. All you have to keep resident is the histogram itself, which should be relatively small.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to return neural network weights (parameters) values of nnetar function?
I am using nnetar of forecast package for a forecasting modelling of a univariate time series.
i fitted a model for example neural network NAR(p,P) on the series data. now i want to know how can i return the weighs or the best weighs that nnetar estimated??
A:
That is explained in ?nnetar: in the output, the model field contains the list of neural networks fitted to your data (there are several of them).
library(forecast)
fit <- nnetar(lynx)
str(fit)
str(fit$model[[1]])
summary( fit$model[[1]] )
# a 8-4-1 network with 41 weights
# options were - linear output units
# b->h1 i1->h1 i2->h1 i3->h1 i4->h1 i5->h1 i6->h1 i7->h1 i8->h1
# 2.99 -7.31 3.90 -2.63 -1.48 4.30 2.57 2.77 -9.40
# b->h2 i1->h2 i2->h2 i3->h2 i4->h2 i5->h2 i6->h2 i7->h2 i8->h2
# -0.23 -1.42 -1.27 0.75 2.48 1.12 0.01 -2.79 -2.35
# b->h3 i1->h3 i2->h3 i3->h3 i4->h3 i5->h3 i6->h3 i7->h3 i8->h3
# 3.30 -1.43 -0.79 7.44 -0.42 1.12 -5.36 15.61 -5.17
# b->h4 i1->h4 i2->h4 i3->h4 i4->h4 i5->h4 i6->h4 i7->h4 i8->h4
# 2.49 6.25 -7.01 7.06 -0.99 1.80 -0.55 5.53 -5.31
# b->o h1->o h2->o h3->o h4->o
# 2.31 -0.47 -0.16 -4.07 2.37
fit$model[[1]]$wts
# [1] 2.98730023 -7.30926809 3.89674784 -2.63077534 -1.48084101 4.30309382
# [7] 2.57150487 2.76947222 -9.40136188 -0.23053466 -1.41876993 -1.26569624
# [13] 0.75035031 2.48057839 1.11969186 0.01107485 -2.79027580 -2.35033702
# [19] 3.29874907 -1.43432740 -0.79437302 7.43590968 -0.42005316 1.12337542
# [25] -5.35698080 15.61077915 -5.16566644 2.49343460 6.25330958 -7.00554826
# [31] 7.05694732 -0.99034344 1.80374167 -0.55078148 5.52887784 -5.31445324
# [37] 2.31407224 -0.46995772 -0.15824823 -4.06939514 2.36781125
| {
"pile_set_name": "StackExchange"
} |
Q:
JAVA Hours to duration
I have an app where i need to check if travel is in duration between 4 hours and 30 hours, I store it as a strings "04:00" and "30:00", then i try to parse it using LocalTime.parse(), "04:00" is parsed successfully but "30:00" gets an error for invalid format, what could be best way to parse duration hours from a string ?
A:
First of all, you're storing it somehow wrong. I suggest to store it in way Duration.parse can handle it, in standard ISO 8601 format.
Examples:
"PT20.345S" -- parses as "20.345 seconds"
"PT15M" -- parses as "15 minutes" (where a minute is 60 seconds)
"PT10H" -- parses as "10 hours" (where an hour is 3600 seconds)
"P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
"P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes"
"P-6H3M" -- parses as "-6 hours and +3 minutes"
"-P6H3M" -- parses as "-6 hours and -3 minutes"
"-P-6H+3M" -- parses as "+6 hours and -3 minutes"
So then you can just do:
Duration dur30H = Duration.parse("PT30H"); // 30h
Duration dur4H = Duration.parse("PT4H"); // 4h
Duration travelTime = Duration.parse("P1D"); // 1D
boolean result = travelTime.compareTo(dur30H) <= 0 && travelTime.compareTo(dur4H) >= 0; // true
| {
"pile_set_name": "StackExchange"
} |
Q:
Update image in php
I want to make an update account page. When I change the image and press update it runs correctly, but when I update any other field than image, the image is deleted from the browser and also from the database table.
This is my code:
<?php
include("includes/db.php");
$user=$_SESSION['customer_email'];
$get_customer="select * from costumers where customer_email='$user'";
$run_customer=mysqli_query($con, $get_customer);
$row_customer=mysqli_fetch_array($run_customer);
$c_id=$row_customer['customer_id'];
$name=$row_customer['customer_name'];
$email=$row_customer['customer_email'];
$pass=$row_customer['customer_pass'];
$img=$row_customer['customer_image'];
?>
<div style="margin-left:15%; margin-top:10%">
<form action="" method="post" enctype="multipart/form-data" />
<table width="500px" align="center" bgcolor="blueskay">
<tr align="center">
<td colspan="2"><h2>Update Your Account</h2></td>
</tr>
<tr>
<td align="right">Customer Name:</td>
<td><input type="text" name="c_name" value="<?php echo $name; ?>" required /></td>
</tr>
<tr>
<td align="right">Customer Image:</td>
<td><input type="file" name="c_image" value="<?php echo $img; ?>" /><img src="customer_images/<?php echo $img; ?>" width="150px" height="100px"></td>
</tr>
<tr>
<td align="right">Customer Email:</td>
<td><input type="text" name="c_email" value="<?php echo $email; ?>"required /></td>
</tr>
<tr>
<td align="right">Customer Password:</td>
<td><input type="password" name="c_pass" value="<?php echo $pass; ?>" required /></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" name="update" value="Update Account"/></td>
<td></td>
</tr>
</table>
</form>
</div>
And this my php code:
<?php
if(isset($_POST['update'])){
$customer_id=$c_id;
$c_name= $_POST['c_name'];
$c_email= $_POST['c_email'];
$c_pass= $_POST['c_pass'];
$c_image= $_FILES['c_image']['name'];
$c_image_temp=$_FILES['c_image']['tmp_name'];
move_uploaded_file($c_image_temp , "customer_images/$c_image");
$c_update="update costumers set customer_name='$c_name', customer_email='$c_email', customer_pass='$c_pass', customer_image= '$c_image'
where customer_id='$customer_id'";
$run_update=mysqli_query($con, $c_update);
if($run_update){
echo"<script>alert('Your Account has been Updated successfully, Thanks')</script>";
echo"<script>window.open('my_account.php','_self')</script>";
}
}
?>
A:
You can try to check whether the image is empty or not and update by condition.
$customer_id=$c_id;
$c_name= $_POST['c_name'];
$c_email= $_POST['c_email'];
$c_pass= $_POST['c_pass'];
$c_image= $_FILES['c_image']['name'];
$c_image_temp=$_FILES['c_image']['tmp_name'];
if($c_image_temp != "")
{
move_uploaded_file($c_image_temp , "customer_images/$c_image");
$c_update="update costumers set customer_name='$c_name', customer_email='$c_email', customer_pass='$c_pass', customer_image= '$c_image'
where customer_id='$customer_id'";
}else
{
$c_update="update costumers set customer_name='$c_name', customer_email='$c_email', customer_pass='$c_pass'
where customer_id='$customer_id'";
}
$run_update=mysqli_query($con, $c_update);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Reset a Standard Auto Number Field?
Autonumber field increments when test class runs and note that in Spring14 salesforce has released an option not to increment when test class runs.
Develop | Apex Test Execution | Options..., selecting Independent Auto-Number Sequence allows one to mostly avoid the gaps in auto-number fields when running tests
But I forgot to check the option and now there is gap in auto number field in existing records. If its a custom field I would have followed the steps from knowledge article but it is Standard Order Number field on Order Object where I don't see an option to Change Field Type to Text when I click on Edit next to Order Number
Below is the screenshot I see when I click on Edit next to Order Number.
A:
From salesforce help link
Modifying Standard Auto-Number Fields
The unique identifiers for solutions, cases, and contracts are standard auto-number fields. Each record is assigned a unique number with a specified format upon creation. You can modify the format and numbering for these auto-number fields.
From Setup, click Customize, select the appropriate tab link, and
then click the Fields link.
Click Edit next to the name of the field
in the Standard Fields list.
Enter a Display Format to control such
formatting details as the minimum number of leading zeros as well as
any prefix or suffix for the number. See Custom Field Attributes.
Format changes do not affect existing records; they are applied only
to new records.
Enter the number to be assigned to the next record
that is created after you save your changes.
Click Save.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is asking a question to validate/verify the real world origins of the practice of being a “Soupeur” appropriate for this site?
First, I hope nobody who is reading this has just eaten…
Okay, I was chatting with some friends and the topic of the “Soupeur” came up. Apparently this is a word used in France to describe the practice of — and I quote:
“…a sexual practice involving attraction to other male secretions, specifically bread soaked in urine, or semen.”
Now, as shocking as that sounds, it also sounds like urban legend nonsense… But for the fact that references to the practice exist in literature dating back to the early 20th century in that Wikipedia article but no real world references.
And all references are strictly connected to French culture with no equivalents found in other cultures which is quite odd from a sociological standpoint: As vile as that practice sounds, there should be other references in other cultures, right?
So my question would be:
Is there any real world evidence to prove that the French sexual practice of being “Soupeur” actually exists or has existed?
So would this question be appropriate for posting here?
A:
To date, we haven't yet identified any taboo topics.
An FAQ answer states
The question should be phrased using respectful language.
While there are no taboo topics here, all claims (and especially potentially offensive claims such as claims about race or porn) must be asked about in respectful manners. It is hard to know what people find offensive, but it's a lot easier for a reader to understand if the language of the question is respectful.
Profanities in answers and questions will be removed. They are not allowed here.
I have put potentially offensive photos behind links tagged "NSFW" or similar to allow people to choose whether they wish to view them.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can the probability of a fumble decrease linearly with more dice?
I'm working on a simplified RPG system that uses only D6s, and I want a mechanic for fumbles/critical fails.
Depending on how good the player character is, they have 1-5 dice to roll and they have to beat a difficulty set by the DM. I thought it would be fun to have players fail if they roll all 1s, but realized it makes it way too hard to fail if you have 5 dice, and a bit too easy if you have 1. Is there a more linear way of defining critical fails?
This is what I get if fumbles are on all dice showing 1s:
\$\begin{array}{|c|c|}
\hline
\textbf{Number of Dice} & \textbf{Probability of Fumble} \\
\hline
\text{1} & \text{16.67%} \\
\text{2} & \text{2.78%} \\
\text{3} & \text{0.46%} \\
\text{4} & \text{0.08%} \\
\text{5} & \text{0.01%} \\
\hline
\end{array}
\$
What I would like (approximately, exact numbers are not that important):
\$\begin{array}{|c|c|}
\hline
\textbf{Number of Dice} & \textbf{Probability of Fumble} \\
\hline
\text{1} & \text{18%} \\
\text{2} & \text{15%} \\
\text{3} & \text{12%} \\
\text{4} & \text{9%} \\
\text{5} & \text{6%} \\
\hline
\end{array}
\$
A:
A close approximation to the percentages you want would use something like this:
\$\begin{array}{|c|c|c|}
\hline
\textbf{Dice} & \textbf{Fumble Range} & \textbf{Probability} \\
\hline
\text{1} & \text{1} & \text{1/6 (16.7%)} \\
\text{2} & \text{2-4} & \text{6/36 (16.7%)} \\
\text{3*} & \text{3-7} & \text{35/216 (16.2%)} \\
& \text{3-6} & \text{20/216 (9.3%)} \\
\text{4} & \text{4-9} & \text{126/1296 (9%)} \\
\text{5} & \text{5-11} & \text{457/7776 (5.9%)} \\
\hline
\end{array}
\$
* (3 dice could go either way)
In terms of gameplay, simpler rules are frequently better than strictly matching the desired probability distribution. I might suggest something like \$N\$ dice fumble on a result \$\le 2\times N\$, with a special case that a single die only fumbles on a 1 (unless you want a 1/3 chance of a fumble in the 1d case). That would give you something like:
\$\begin{array}{|c|c|c|}
\hline
\textbf{Dice} & \textbf{Fumble Range} & \textbf{Probability} \\
\hline
\text{1} & \text{1} & \text{1/6 (16.7%)} \\
\text{2} & \text{2-4} & \text{6/36 (16.7%)} \\
\text{3} & \text{3-6} & \text{20/216 (9.3%)} \\
\text{4} & \text{4-8} & \text{70/1296 (5.4%)} \\
\text{5} & \text{5-10} & \text{252/7776 (3.2%)} \\
\hline
\end{array}
\$
A:
Fumble if the leftmost, unique die is a 1.
(Hear me out.)
N dice are rolled on the table. One of those dice is unique--say it's black with white pips and the rest are numbered dice. If the unique die is both showing a 1 and is farthest left (from the roller's POV)*, that's your fumble. In case of a leftmost-tie, let the closer (to the roller) die win.
It's not linear, but it's a lot closer than the original method (all 1s) while being simple and memorable.
\begin{array}{rl}
N & P(\text{fumble}) \\
\hline
1 & 16.67\% \\
2 & 8.33\% \\
3 & 5.55\% \\
4 & 4.16\% \\
5 & 3.34\% \\
\end{array}
* - at my table I often use the positions of dice, the ordering of dice, and even the orientation of dice as they fall to inform various effects. (I do't like to throw away good information.) I haven't yet had a player complain that it's hard to tell which die is on the left--they generally count/read left-to-right anyway.
A:
Have one unique die (the red die) that players roll in addition to 0–4 other dice. If the red die is a 1, roll it a second time: if this second roll is less than the number of dice the player rolled (to start), then no fumble, but if the second roll is at least the number of dice the player rolled, then fumble.
For example, if the player only got to roll one die (the red one), then a 1 is always a fumble. If the player got to roll five dice, then a 1 is a fumble if the reroll is 5 or 6 but not a fumble if the reroll is 1, 2, 3, or 4. This gives literally a linear sequence of probabilities:
\$\begin{array}{|c|c|}
\hline
\textbf{Number of Dice} & \textbf{Probability of Fumble} \\
\hline
\text{1} & \text{16.67%} \\
\text{2} & \text{13.89%} \\
\text{3} & \text{11.11%} \\
\text{4} & \text{8.33%} \\
\text{5} & \text{5.56%} \\
\hline
\end{array}
\$
| {
"pile_set_name": "StackExchange"
} |
Q:
Restructuring html elements
I have the following HTML element structure:
<span class="parent">
<span class="keyword">belal</span>
<span class="string"> "Belal Mostafa"</span>
</span>
now I want to dynamically select the .parent class and restructure its children it to look like:
<span class="parent">
<span class="keyword">belal</span>
<span class="string"> "Belal </span>
<span class="string"> Mostafa"</span>
</span>
I was thinking of the following but still can't get it done:
unwrap .string class get the text from it
then split it on white spaces
then append each string to a new span element
A:
You can loop on each .parent, after that loop on each string and split all white space and append the result to the parent.
Example
$(".parent .string").each(function(){
if($(this).text().trim().indexOf(" ") != -1)
{
var parent = $(this).parents(".parent");
$.each($(this).text().trim().split(" "),function(index,value){
parent.append("<span class='string'>"+value+"</span>");
});
$(this).remove();
}
});
.string{
border:solid 1px #888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="parent">
<span class="keyword">belal</span>
<span class="string"> "Belal Mostafa Test"</span>
</span>
| {
"pile_set_name": "StackExchange"
} |
Q:
Как узнать имеет ли в себе div id="id" дочерние элементы
На странице изначально записано <div id="id"></div>,
но я могу туда поместить кое-какой контент позже, вот так $id.html(data.id);.
Как проверить внесены ли внутрь дочерние элементы?
A:
$(document).ready(function() {
function isEmpty(el) {
return !$.trim(el.html())
}
if (isEmpty($('#id'))) {
console.log('Пусто!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id"></div>
или вот так
if($.trim($("#id").html())=='')
на самом деле есть чуть проще, но там проблемы с пробелами всякими могут быть
if ($('#id').is(':empty')){
console.log('Пусто!');
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What does django resolve_variable do? (template.Variable)
What does resolve_variable do? And could I use it for accessing the request outside of the view?
Edit
So template.Variable is the correct way to go - but I'm still unsure of its purpose. The documentation doesn't really help.
Cheers guys.
A:
I'm assuming your trying to write a custom template tag here, so here's what you do.
In your compilation function, you bind the variable like so:
@register.tag
def my_tag(parser, token):
# This version uses a regular expression to parse tag contents.
try:
# Splitting by None == splitting by spaces.
tag_name, var_name = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
#this will "bind" the variable in the template to the actual_var object
actual_var = template.Variable(var_name)
return MyNode(template_variable)
class MyNode(template.Node):
def __init__(self, actual_var):
self.actual_var = actual_var
def render(self, context):
actual_var_value = self.actual_var.resolve(context)
#do something with it
return result
If you only want access the request, you bind against the variable directly in the node. Make sure you have the request in the context:
from django.template import RequestContext
def my_view(request):
#request stuff
return render_to_response("mytemplate.html", {'extra context': None,}, context_instance=RequestContext(request))
Then in your template tag code.
@register.tag
def simple_request_aware_tag(parser, token):
return SimpleRequestAwareNode()
class SimpleRequestAwareNode(template.Node):
def render(self, context):
request = template.Variable('request').resolve(context)
#we want to return the current username for example
return request.user.get_full_name()
| {
"pile_set_name": "StackExchange"
} |
Q:
After calling itself, Python function won't return correctly. Why?
I'm making a text adventure game. After the title has printed, the function below prompts the player to begin the game by pressing "y". If they enter "y", the function returns "opening". If not, the function advises them to mind their inputs and calls itself to start over.
The function returns correctly if the player hits "y" the first time. The problem I'm having is that if the player enters the wrong input, subsequent attempts to enter "y" do not return correctly. They skip to the bottom of the function and return my error message "this is wrong".
How can I get the function to return correctly after calling itself?
def prompt():
print "Hit 'Y' to begin."
action = raw_input("> ").lower()
if action == "y":
return "opening"
else:
print "For this game to work, you're going to have to get"
print "the hang of hitting the right key."
print "Let's try that again."
prompt()
return "this is wrong"
ret = prompt()
print ret
A:
you are just calling the function again but not returning the value, it should be
print "Let's try that again."
return prompt()
However, you shouldn't be doing this recursively at all...
def prompt():
print "Hit 'Y' to begin."
action = raw_input("> ").lower()
while action != "y":
print "For this game to work, you're going to have to get"
print "the hang of hitting the right key."
print "Let's try that again."
action = raw_input("> ").lower()
return "opening"
ret = prompt()
print ret
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I use jQuery to convert an HTML table into 's?
How could I go about converting an HTML table (I will provide code below) into <div> elements? Long story short, I am using a PHP script that outputs contents into an HTML table and it has proven very difficult to edit the PHP and convert the table elements into <div>'s. Below is the HTML table code:
<table><tbody><tr data-marker="0"><td class="mapp-marker"><img class="mapp-icon" src="http://www.walmartchicago.com/wp-content/plugins/mappress-google-maps-for-wordpress/icons/walmart-yellow.png"></td><td><b>Walmart Neighborhood Market<br></b><a href="#" class="poi_list_directions">Get Directions</a></td></tr><tr data-marker="1"><td class="mapp-marker"><img class="mapp-icon" src="http://www.walmartchicago.com/wp-content/plugins/mappress-google-maps-for-wordpress/icons/walmart-red.png"></td><td><b>Walmart Express<br></b><a href="#" class="poi_list_directions">Get Directions</a></td></tr><tr data-marker="2"><td class="mapp-marker"><img class="mapp-icon" src="http://www.walmartchicago.com/wp-content/plugins/mappress-google-maps-for-wordpress/icons/walmart-red.png"></td><td><b>Walmart Express<br></b><a href="#" class="poi_list_directions">Get Directions</a></td></tr><tr data-marker="3"><td class="mapp-marker"><img class="mapp-icon" src="http://www.walmartchicago.com/wp-content/plugins/mappress-google-maps-for-wordpress/icons/walmart-blue.png"></td><td><b>Walmart Supercenter<br></b><a href="#" class="poi_list_directions">Get Directions</a></td></tr><tr data-marker="4"><td class="mapp-marker"><img class="mapp-icon" src="http://www.walmartchicago.com/wp-content/plugins/mappress-google-maps-for-wordpress/icons/walmart-blue.png"></td><td><b>Walmart Supercenter<br></b><a href="#" class="poi_list_directions">Get Directions</a></td></tr></tbody></table>
A:
No need to loop through the elements and copy the attributes, just pull the table contents as a string and run a simple string replace ...
$('table').replaceWith( $('table').html()
.replace(/<tbody/gi, "<div id='table'")
.replace(/<tr/gi, "<div")
.replace(/<\/tr>/gi, "</div>")
.replace(/<td/gi, "<span")
.replace(/<\/td>/gi, "</span>")
.replace(/<\/tbody/gi, "<\/div")
);
... or, if you want an unordered list ...
$('table').replaceWith( $('table').html()
.replace(/<tbody/gi, "<ul id='table'")
.replace(/<tr/gi, "<li")
.replace(/<\/tr>/gi, "</li>")
.replace(/<td/gi, "<span")
.replace(/<\/td>/gi, "</span>")
.replace(/<\/tbody/gi, "<\/ul")
);
This will also retain your classes and attributes.
Perhaps the best solution isn't jQuery related, but PHP ... you could use PHP's str_replace() to do the same thing, only before outputting from PHP?
$table_str = //table string here
$UL_str = str_replace('<tbody', '<ul id="table"', $table_str);
$UL_str = str_replace('<tr', '<li', $UL_str);
$UL_str = str_replace('</tr', '</li', $UL_str);
$UL_str = str_replace('<td', '<span', $UL_str);
$UL_str = str_replace('</td', '</span', $UL_str);
$UL_str = str_replace('</tbody', '</ul"', $UL_str);
A:
It does seem like a crazy thing to have to do. I just wrote a jQuery plugin to do this though. Working with an old web app where we don't want to really dig into the backend code and are on a limited budget. So, just taking the data that is dumped out in tables, converting them to divs, so I can float them around, style them up and make the data look better.
The system is rending data that is not really 'tabular' data.
https://github.com/ryandoom/jquery-plugin-table-to-div
If anyone is interested in the future.
| {
"pile_set_name": "StackExchange"
} |
Q:
Staff member has a diamond on a child meta but not on the main site
There is a user Sara Chipps (Engineering Manager at Stack Overflow), who is Moderator in Meta Stack Overflow but not the moderator on the main Stack Overflow site.
Also viewing her network profile (other than Stack Overflow), on all the sites I can see her main site profile only. From the main site profile, there is no link to meta site, also the meta site account does not exist.
This is very new to me. Is this is a bug or expected behaviour?
A:
This was a glitch. While we do make diamonds optional for employees, being a mod only on a child meta site kinda complicates things. After making sure this wasn't intentional in the name of science, I went ahead and fixed it.
Y'all really notice things, I must say.
Update
Wasn't aware of this, but we do now support employees having a diamond on a child meta but not the main site, which is how Sara's was applied. I did speak with her prior to making it the same, thankfully.
So yes, it's now quite possible for employees to have a diamond on meta where they need to speak as employees, but participate normally on main.
Sorry about the confusion!
A:
This makes some sense; she has a diamond on Meta Stack Exchange as well, presumably to give her communications about the Stack Exchange network a more official status.
From the main site profile, there is no link to meta site, also the meta site account is not exist.
That's not uncommon; for a meta profile to exist, you have to visit the meta site. It's not generated automatically if you create an account on the main site. My sockpuppet has quite a few accounts on smaller sites (example) without having a meta profile there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Typescript Code is not returning any output, but is running
I am trying to get a string with a number where, if there is a match between the former and later number add it to a sum total, so 55412 will be 5 and 112332 will be 1 + 3 so 4. This is coded in typescript, the problem is my code doesn't output anything.
function uipath(e, arg)
{
let stringToInt = new StringToInt("5514133");
stringToInt.charCompareAndSum();
stringToInt.stringSplit();
alert (stringToInt.getSumList.toString);
}
class StringToInt
{
private argumentString : string ;
private numberArr : Array<string>;
private sumList : number;
constructor( arg: string)
{
this.argumentString = arg ;
}
stringSplit()
{
this.numberArr = this.argumentString.split(/(?=.)/u);
}
charCompareAndSum()
{
for(var i = 0; i < this.numberArr.length -1; i++ )
{
if (this.numberArr[i] == this.numberArr[i+1])
{
this.sumList = this.sumList + +this.numberArr[i];
}
}
}
get getSumList():number
{
return this.sumList;
}
}
The output should be 8.
A:
Unless I'm missing something, you need to call your functions:
stringToInt.getSumList.toString
Should be
stringToInt.getSumList().toString()
I'm guessing this prints nothing because
stringToInt.getSumList
Evaluates to the getSumList function itself, then
getSumList.toString
Evaluates to undefined since the function doesn't have a toString property.
| {
"pile_set_name": "StackExchange"
} |
Q:
Resize UIButtons from swift once constraints are set
I was looking at this youtube video https://www.youtube.com/watch?v=vzyd33Pv9kg regarding How Priority Constrains works.
I want to do the same but instead of label I am using custom buttons with images. As you can see in the video, the author hardcoded the size of the label to 100wx100h. However regardless of the what iphone you have, the labels always be the same size. I want to accomplish the same thing, but instead I want the size of buttons (or in his case labels) be larger on iphone 5, and even larger in iphone 6 and so on.
My question is how can I accomplish this?
Also is it possible design this with let say 100X100 in 3.5-inch iphone then change the size dynamically change in the code depends what iphone is used?
if iphone4s then use 100X100 size buttons
else if iphone 5 then use 110X110 size buttons and so on?
A:
Yes you can. Just connect your relevant constraints(width and height constraints in your case) to your view controller like usual elements. Than you can change constant property of your NSLayoutConstraints (Probably in your viewDidLoad method).
self.buttonWidthConstraint.constant = 110.;
self.buttonHeightConstraint.constant = 110.;
You also may want to change size classes to provide different constrains for each orientation.
https://developer.apple.com/library/ios/recipes/xcode_help-IB_adaptive_sizes/chapters/AboutAdaptiveSizeDesign.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Undefined offset: 1 error daterange explode array
I get value form date range and use explode to array error line whereBetween
$range = Input::get('daterange') ;
$date = explode('to', $range);
//dd($date);
$temp = Temps::select('temp')
->orderBy('date_temp', 'asc')
->whereBetween('date_temp',[$date[0], $date[1]])
->get()
->pluck('temp');
1/1) ErrorException Undefined offset: 1
A:
you need to change since range is $range='09/11/2017 - 10/10/2017';.you need to split using -
$date = explode('-', $range);
if you print $date
Array
(
[0] => 09/11/2017
[1] => 10/10/2017
)
Also note you can pass data directly.You will get instead of [$date[0], $date[1] since whereBetween accept array and also $date is an array
$temp = Temps::select('temp')
->orderBy('date_temp', 'asc')
->whereBetween('date_temp',$date)
->get()
->pluck('temp');
| {
"pile_set_name": "StackExchange"
} |
Q:
App not compatible with 18 inch tablet because Manifest?
I have uploaded an app to the Google Play Store. It's available for tablets only.
This is in my manifest.xml:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<supports-screens
android:smallScreens="false"
android:normalScreens="false"
android:largeScreens="true"
android:xlargeScreens="true"
android:requiresSmallestWidthDp="600" />
Someone with a Samsung Galaxy View SM-T670 is trying to download my application. This tablet is 18.4 inch but my app is not compatible with this device. Why is it not compatible?
I checked, the device has a camera, so that can't be the problem.
I can't think of anything else because it has everything my manifest wants, but when I look the device up in the Google Developer Console, it says:
This device is not supported in your app's APK-manifest. Therefore, users of this model can not install your app.
Can anyone help me with this?
EDIT: the tablet has a higher SDK then the minimum required SDK.
I don't think it does matter which country the user comes from because when I look in the Google Developer Console, it also shows the message that the app is not compatible with that device. So my guess is that country doesn't matter?
A:
You've specified android:requiresSmallestWidthDp="600" which means you expect the screen to be at least 600dpi. But tablets have a very big screen and bad resolution (generally up to 1920x1080) so you end with something like 122 dpi for a 18 inches tablet. It means most of the tablets will be excluded which is the opposite of what you try to achieve.
So first remove this line.
Then you're using <supports-screens> which:
Lets you specify the screen sizes your application supports and enable screen compatibility mode for screens larger than what your application supports.
(See developer page)
In your case I think it's better to use <compatible-screens>. According to the documentation it
Specifies each screen configuration with which the application is compatible.
It not advised to used it generally because:
This element can dramatically reduce the potential user base for your application, by not allowing users to install your application if they have a device with a screen configuration that you have not listed.
Which is exactly what you want to do. See more info in this answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Grouping of API methods in documentation - is there some custom attribute
I have controller like
public class UserController : ApiController
{
[Route("api/user")]
IHttpActionResult GetUser() { ... }
}
public class ResumeController : ApiController
{
[Route("api/user/resumes")]
IHttpActionResult GetResumes() { ... }
}
Which on swagger generates output like
Is there a way (besides overriding default implementation by rolling out your own ISwaggerProvider or merging two controllers into one) to enforce the group name ? Something like
public class UserController : ApiController
{
[Route("api/user")]
[MagicalAttributeName(Group="User")]
IHttpActionResult GetUser() { ... }
}
public class ResumeController : ApiController
{
[Route("api/user/resumes")]
[MagicalAttributeName(Group="User")]
IHttpActionResult GetResumes() { ... }
}
A:
You could also use SwaggerOperationAttribute:
public class UserController : ApiController
{
[Route("api/user")]
[SwaggerOperation(Tags = new[] { "User" })]
IHttpActionResult GetUser() { ... }
}
public class ResumeController : ApiController
{
[Route("api/user/resumes")]
[SwaggerOperation(Tags = new[] { "User" })]
IHttpActionResult GetResumes() { ... }
}
A:
There is a way - although there is no magic attribute - you can change default rules of grouping in swagger startup configuration in order to introduce your very own custom attribute.
GlobalConfiguration.Configuration
.EnableSwagger(c => {
c.GroupActionsBy(apiDesc => apiDesc
.GetControllerAndActionAttributes<MethodGroupAttribute>().Any() ?
apiDesc.GetControllerAndActionAttributes<MethodGroupAttribute()
.First().GroupName :
apiDesc.ActionDescriptor.ControllerDescriptor.ControllerName);
});
/// <summary>
/// Forces method to be displayed within specified group, regardless of controller
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class MethodGroupAttribute : Attribute
{
/// <summary>
/// Group name
/// </summary>
public string GroupName { get; private set; }
/// <summary>
/// ctor
/// </summary>
/// <param name="groupName"></param>
public MethodGroupAttribute(string groupName)
{
if (string.IsNullOrEmpty(groupName))
{
throw new ArgumentNullException("groupName");
}
GroupName = groupName;
}
}
Usage:
[Route("api/user")]
[MethodGroup("User")]
IHttpActionResult GetUser() { ... }
| {
"pile_set_name": "StackExchange"
} |
Q:
Close button on dialog returns to the wrong page
Here's a very simple fiddle:
http://jsfiddle.net/mmSKj/
If you click the "presets" button in the header bar, it opens a dialog. If you click the "close" button on the dialog, instead of going back to the page it came from, it goes to the last page (excluding the dialog itself) on the page (the one with the content This is another page). How come? Is there a way to fix the automatically inserted back button so it behaves itself properly (like the "home" button I included in the dialog) or, failing that, is there a way to remove the close button.
<div data-role="page" id="index">
<header data-role="header">
<h1>Index</h1>
<a href="#presets" data-icon="star" class="ui-btn-right" data-transition="pop" data-rel="dialog">Presets</a>
</header>
<article data-role="content">
<div>This is the main page</div>
</article>
</div>
<div data-role="page">
This is another page
</div>
<div data-role="page" id="presets">
<header data-role="header">
<h1>Presets</h1>
<a href="#index" data-icon="home" data-iconpos="notext"></a>
</header>
<div data-role="content">
This is a dialog!
</div>
</div>
Update
As Taifun pointed out, the problem is the lack of an id on the page. Adding an id fixes my first fiddle. However, my real situation is a little more complicated, as shown in this fiddle:
http://jsfiddle.net/mmSKj/2/
Here I am actually creating pages dynamically using knockout, and I assign IDs to those pages via data binding, but, it seems, those ids are not recognized by jQuery Mobile for some reason. If you look with Firebug, you can see that the ids are correctly added to the attributes of the pages, but when you close the dialog, you end up on page 3 rather than the original page.
Update 2
Simple fix, I just added a dummy id to the bit of html that knockout is going to use as a template:
<!-- ko foreach: pages -->
<div data-role="page" data-bind="attr: {id: name}" id="dummy">
This is <span data-bind="text:name"></span>
</div>
<!-- /ko -->
See here.
The dummy id is replaced by knockout, so links to that page work correctly and jQuery mobile seems to be happy!
A:
add an id to your other page
<div data-role="page" id="anotherpage">
This is another page
</div>
then it will work, see jsfiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is Facebook using UICollectionView instead of UITableView for their News Feed
If someone doesn't know, Facebook open sourced a new library called componentkit
The documentation says
ComponentKit really shines when used with a UICollectionView.
Facebook developed this lib for their news feed. That means that they are using the UICollectionView for it and not what I thought the UITableView.
Why is Facebook using the UICollectionView instead of the UITableView?
I mean the news feed is actually a table view or not?
Do you have any idea? What do you think about it?
A:
Facebook feed is indeed a UICollectionView and this is mostly for the flexibility it offers moving forward.
With our custom layout, we can move around / animate the cells fairly cleanly. You can attempt to do with a UITableView, but it requires some substantial hacks that we would rather avoid.
When we migrated from UITableView to UICollectionView we also noticed an uptick in scroll performance. Unfortunately I haven't been able to identify the exact call that got faster.
| {
"pile_set_name": "StackExchange"
} |
Q:
List all applications that handle a specified file type
Is it possible to list all the applications on a machine that can open a specific file type, using only the files extension? for example if I have a text file (.txt), I want a list of all applications that can open .txt files.
A:
Check out the HKEY_CLASSES_ROOT hive in your registry. It's all in there.
| {
"pile_set_name": "StackExchange"
} |
Q:
XSL - replace all instances of a tag with another recursively
I have an XML looking like this:
<Viewbox Width="29.513" Height="57.478"
>
<Canvas>
<Canvas>
<!-- Layer 1/<Group>/<Group>/<Compound Path> -->
<Path Fill="#ffffffff" Data="F1... Z"/>
<Path StrokeThickness="0.9" Stroke="#ff59595b" StrokeStartLineCap="Round" StrokeEndLineCap="Round" StrokeLineJoin="Round" Data="F1 ...698"/>
</Canvas>
</Canvas>
</Viewbox>
My XSL looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/" >
<DrawImage>
<xsl:for-each select="//Canvas">
<DrawingGroup><xsl:copy-of select="child::*" /></DrawingGroup>
</xsl:for-each>
<xsl:for-each select="//Path">
<GeometryDrawing>
<xsl:choose>
<xsl:when test="@Fill">
<xsl:attribute name="Brush">
<xsl:value-of select="@Fill"/>
</xsl:attribute>
</xsl:when>
<xsl:when test="@Stroke">
<xsl:attribute name="Brush">
<xsl:value-of select="@Stroke"/>
</xsl:attribute>
</xsl:when>
</xsl:choose>
<xsl:attribute name="Geometry">
<xsl:value-of select="@Data"/>
</xsl:attribute>
<xsl:choose>
<xsl:when test="not(string-length(@StrokeThickness)<1 or string-length(@StrokeStartLineCap)<1 or string-length(@StrokeEndLineCap)<1 or string-length(@StrokeLineJoin)<1)">
<Pen>
<xsl:choose>
<xsl:when test="@StrokeThickness">
<xsl:attribute name="Thickness">
<xsl:value-of select="@StrokeThickness"/>
</xsl:attribute>
</xsl:when>
</xsl:choose>
<xsl:choose>
<xsl:when test="@StrokeStartLineCap">
<xsl:attribute name="StartLineCap">
<xsl:value-of select="@StrokeStartLineCap"/>
</xsl:attribute>
</xsl:when>
</xsl:choose>
<xsl:choose>
<xsl:when test="@StrokeEndLineCap">
<xsl:attribute name="EndLineCap">
<xsl:value-of select="@StrokeEndLineCap"/>
</xsl:attribute>
</xsl:when>
</xsl:choose>
<xsl:choose>
<xsl:when test="@StrokeLineJoin">
<xsl:attribute name="LineJoin">
<xsl:value-of select="@StrokeLineJoin"/>
</xsl:attribute>
</xsl:when>
</xsl:choose>
</Pen>
</xsl:when>
</xsl:choose>
</GeometryDrawing>
</xsl:for-each>
</DrawImage>
</xsl:template>
</xsl:stylesheet>
Something isn't right. My output was supposed to look like shown below, but instead I get the Geometrydrawings outside DrawingGroup and DrawingGroup is not nested like Canvas was.
<?xml version="1.0" encoding="utf-8" ?>
<DrawImage>
<DrawingGroup>
<DrawingGroup>
<GeometryDrawing Brush="#ffffffff" Geometry="F1....478 Z" />
<GeometryDrawing Brush="#ff59595b" Geometry="F1...98">
<Pen Thickness="0.9" StartLineCap="Round" EndLineCap="Round" LineJoin="Round" />
</GeometryDrawing>
</DrawingGroup>
</DrawingGroup>
</DrawImage>
I hope someone can tell me what to put inside my DrawingGroup element in my xsl
A:
Use templates e.g.
<xsl:template match="Canvas">
<DrawingGroup>
<xsl:apply-templates select="@* | node()"/>
</DrawingGroup>
</xsl:template>
then you can easily write modular code that transforms each element as needed, preserving the original document structure.
You simply need to add more templates like
<xsl:template match="@Fill">
<xsl:attribute name="Brush" select="."/><!-- XSLT 2.0 -->
<!-- or XSLT 1.0 <xsl:attribute name="Brush"><xsl:value-of select="."/></xsl:attribute>-->
</xsl:template>
No need for for-each and choose/when.
If there are element or attributes you want to delete then use e.g. <xsl:template match="foo"/> to delete the complete element or <xsl:template match="foo"><xsl:apply-templates/></xsl:template> to process only its child nodes respectively <xsl:template match="@bar"/> to not process bar attributes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finitely generated module with free submodule $S$ and $M/S$ torsion-free implies $M$ is free
Let $R$ be a PID and $M$ a module. Show the following:
(i) If $M$ is finitely generated and $S$ is a free submodule with $M/S$ torsion-free, then $M$ is free.
(ii) If $M$ is torsion-free and $M/S$ is finitely generated of torsion for all submodule $S \neq 0$ of $M$, then $M \cong R$. Deduce that if an infinite abelian group satisfies every non zero subgroup has finite index then $G \cong \mathbb Z$.
I think I could solve (i) but I am not so sure if it is correct so I'll write my solution:
I know that if $R$ is a PID and $M$ is a f.g. torsion-free module, then $M$ is free. So, using this, I've tried to show that $M$ is torsion-free. So suppose there is $r \neq 0, m \in M$ such that $rm=0$. Consider the projection $$\pi: M \to M/S$$ $$ m \to \overline{m}$$
Then $0=\pi(rm)=r\pi(m)$. Since $r \neq 0$ and $M/S$ is torsion-free, it must be $\pi(m)=0 \implies m \in S$. But $S$ is a free submodule which implies $S$ is torsion-free, as $rm=0$ and $r \neq 0$, it follows $m=0$. It follows directly that $M$ is torsion-free.
I have no idea what to do in (ii). As for the last part of (ii), any abelian group is a $\mathbb Z$-module. I don't see why $G/S$ is of torsion (if we have this, then we are under the hypothesis of first part of (ii) and we can apply the proposition).
Any suggestions would be appreciated.
A:
If consider $S$ a non-zero cyclic submodule, from $M/S$ finitely generated you get $M$ finitely generated, so $M$ is free. Now you can use this answer.
For an abelian group $G$ and $S$ a non-zero subgroup, having finite index means that $G/S$ is finite, or a finite abelian group is finitely generated and torsion.
| {
"pile_set_name": "StackExchange"
} |
Q:
Limit Scope to Parent after super() Call
I have something that looks like the following:
class A
def foo
bar
end
def bar
puts "A"
end
end
class B < A
def foo
super
end
def bar
puts "B"
end
end
The desired output is to be able to call B.new.foo #=> "A". Is it possible to limit scope to the parent once super is called? This feels kind of wrong to me, so perhaps this is an indicator of a bad design, but I'm curious if this would be possible regardless.
A:
The problem here is that B defines a new bar method that supplants the one defined in A. If you need to preserve the legacy behaviour you must create an alias for this purpose:
class A
def foo
original_bar
end
def bar
puts "A"
end
alias_method :original_bar, :bar
end
class B < A
def foo
super
end
def bar
puts "B"
end
end
Using alias_method here preserves a "copy" of the original method that the subclass doesn't override.
You're right, though, that this is a bit messy. You may want to declare bar as private so it can't be overruled so easily.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.