text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Questions about C++ iterators
In C++, why can't we use '>' or '<' to compare InputIterators, ForwardIterators and BidirectionalIterators? However, we can compare RandomAccessIterators with '>' or '<', for example std::vector. What is the reason behind this?
Also, why can't we cout iterators' content? such as "cout << itr << endl;" wouldn't work. What is the reason behind this? Iterators are a lot like pointers, but we can cout pointers but not iterators, why?
In general, what is the intrinsic difference between iterators and pointers? I used to think they are similar, but I guess I have to understand this in order to get to the next level of understanding c++.
Question#2: Thank you all for awesome answers. I have one more question in regards to iterators.
Why c++ prints out something like "50397953" when the iterator goes out of bounds? Shouldn't it be printing something like NULL or '\0' ?
A:
std::list<T> has bidirectional iterators and it doesn't make any sense to require them to be comparable. It's not even clear how it would be possible to implement std::list<T> in order to be compliant with such a requirement. However, since random access iterators support subtraction, it is obvious that we can compare them.
Why can't we print the value of an iterator? In general, it's up to the author whether to support such an operation. Many iterators are basically just implemented as pointers or wrappers around pointers---providing operator<< for them wouldn't give the user any benefit they couldn't get by simply printing out the address of the object pointed to.
As for the difference between iterators and pointers, pointers to objects are a specific kind of random access iterator, but iterators can also be of class type so long as they satisfy the iterator requirements.
A:
There's both a rigid, formal explanation, and a practical one.
The rigid, formal explanation
Because that's how it's specified in C++.
The practical explanation
A vector is always stored in contiguous memory, by definition. An iterator is, more or less a pointer. Therefore, by comparing the actual underlying memory addresses it is possible to define which pointer is "less" or "greater" than the other pointer.
On the other hand, each element in a list, or a set, could be stored anywhere. Each element is instantiated independently. An iterator for one particular element in the list could be referencing a numerically lesser memory location than a different iterator for another element in the same list, but the actual element could be after the other element, in the actual list. Given two iterators in a list it cannot be immediately determined which one is closer to the beginning or to the end of the list. Note that inserting and removing elements in a list does not invalidate existing list iterators, because each element in the list is instantiated independently.
The practical reason why you cannot use iterators with operator<< on a std::ostream is because, of course, this overload is not defined. Note that you can always do the following, instead:
cout << &*itr << endl;
This will format the actual memory address of the referenced element. But this is of dubious use anyway. It's mostly meaningless.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to form SPARQL queries that refers to multiple resources
My question is a followup with my first question about SPARQL here.
My SPARQL query results for Mountain objects are here.
From those results I picked a certain object resource.
Now I want to get values of "is dbpedia-owl:highestPlace of" records for this chosen Mountain object.
That is, names of mountain ranges for which this mountain is highest place of.
This is, as I figure, complex. Not only because I do not know the required syntax, but also I get two objects here.
One of them is Mont Blank Massif which is of type "place".
Another one is Western Alps which is of type "mountain range" - my desired record.
I need record # 2 above but not 1. I know 1 is also relevant but sometimes it doesn't follow same pattern. Sometimes the records appear to be of YAGO type, which can be totally misleading. To be safe, I simply want to discard those records whenever there is type mismatch.
How can I form my SPARQL query to get these "is dbpedia-owl:highestPlace of" records and also have the type filtering?
A:
you can use this query, note however that Mont_Blanc_massif in your example is both a dbpedia-owl:Place and a dbpedia-owl:MountainRange
select * where {
?place dbpedia-owl:highestPlace :Mont_Blanc.
?place rdf:type dbpedia-owl:MountainRange.
}
run query
edit after comment: filter
It is not really clear what you want to filter (yago?), technically you can filter for example like this:
select * where {
?place dbpedia-owl:highestPlace :Mont_Blanc.
?place rdf:type dbpedia-owl:MountainRange.
FILTER NOT EXISTS {
?place ?pred ?obj
Filter (regex(?obj, "yago"))
}
}
this filters out results that have any object with 'yago' in its URL.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using a 2D Array in Function: Error
I tried to set values in 2D array and Print it with Function.
but I got trouble to send the Array to the Function.
#include <stdio.h>
void SetArr(int (*arr)[], int n);
void PrintfArr(int (*arr)[], int n);
int main()
{
int arr[100][100];
for(int i=0; i<100; i++)
for(int j=0; i<100; j++)
arr[i][j]=0; //initiallize Array
int size;
printf("input Size : "); scanf("%d", &size);
SetArr(arr, size);
PrintfArr(arr, size);
return 0;
}
void SetArr(int (*arr)[], int n)
{
int i, j;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
arr[i][j]=i+j; // Error! "Subscript of Pointer to imcomplete~
}
}
void PrintArr(int (*arr)[], int n)
{
int i, j;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
printf("%d", arr[i][i]); // Error! "Subscript of Pointer to imcomplete~
}
printf("\n");
}
As you see, both of functions got same problem while using "arr[][]"
A:
In the declaration of the function, array must be mentioned with its size (length). This is what the compiler means when it says "incomplete type": it needs the size to understand how to access its elements.
In order to make size available to the compiler, it should go first in the function's declaration:
void SetArr(int n, int (*arr)[n])
Here arr is technically a "pointer to an array of n elements", but in C it's customary to treat a pointer as an array, so arr can be treated as "an array of arrays of n elements", which is the same as a 2-D array.
You might want to mention both dimensions of the array:
void SetArr(int n, int arr[n][n])
This is equivalent to the first declaration, but seems clearer.
| {
"pile_set_name": "StackExchange"
} |
Q:
FT232R chip and capacitor
The question is basically: why use capacitor in this particular DC circuit? Generally, as I read in the thread below, using a capacitor in DC circuit may have different reasons and purposes. Given my lack on knowledge in the topic I do not know what is the reason for using it here.
What is the role of capacitors in DC circuits like motherboard, graphic card etc?
Here I am talking about the 10nF capacitor right after USB GND. Basically it connects USB GND with USB VCC. Given that USB is DC isn't it just a break in the circuit? Or, if we assume that some significant current can actually flow there, wouldn't we be causing s/c?
I understand that that this partial circuit shown at the bottom of the picture is something we could use instead of this 10nF and ferrite bead setup. So my thinking is that all these capacitors are here only for some EMI filtration. Is that correct? If yes, why is it so important to filter it here on the power terminals rather than maybe data terminals? Will it cause problems if we skip it completely? And why we are doing nothing with the data terminals? Thanks.
The picture comes from
http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf
A:
The data terminals in USB are high speed differential lines, you don't want to put any capacitance on those lines (it would kill your signal basically). You want to use some ESD protection devices on the data terminals though, to protect the data pins from getting destroyed by static discharge.
The 10nF capacitor on the 5V line together with the ferrite bead will filter out some noise picked up from the cable but also coming from the FTDI chip. So it will improve the EMI performance and will not disturb your USB host.
I don't think the bottom part is optional but mandatory as well. The 4.7µF capacitor will store some energy which will acts as a pool the FT232R can take from without the parasitic inductance and resistance of the wire affecting it much. The 100nF capacitor is just your standard value decoupling capacitor to improve the noise performance of the FT232R.
The 10nF capacitor is not a break in the DC circuit. As you can see the GND node is also on the GND pins on the FT232R, so the current will gro from VCC through the FT232 to the GND node and back to the host.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I wrap text within a link tag using JavaScript/Jquery?
Here is my current code:
<a class="mg_label_7" href="/" shape="">Hello</a>
I want to have:
<a class="mg_label_7" href="/" shape=""><div id="hello">Hello</div></a>
So I can manipulate the background of the link text without changing the rest of the link areas text. Is there anyway to pinpoint this piece of text and insert a div or even a span using JavaScript/jQuery?
I've been trying to do this for around 3 hours, the closest I've got to achieving it is using
var elem = document.getElementsByTagName('a')[0];
var html = elem.innerHTML;
elem.innerHTML = '<div class="red">'+ html + '</div>'
which successfully targeted a link in my code and changed it to the span, but if I try to getElementsByTagName then getElementByClassName and use mg_label_7 it won't work. There are duplicates of the tag in the code and I want to target all of them.
I'm trying to manipulate a SharePoint web part so I'm not sure if it's stopping it from being edited.
A:
You can use .wrapInner()
$('.mg_label_7').wrapInner('<div id="hello"></div>')
| {
"pile_set_name": "StackExchange"
} |
Q:
Calling Kotlin from Java -- error: package demo does not exist
I don't understand the documentation:
Package-Level Functions
All the functions and properties declared in a file example.kt inside
a package org.foo.bar, including extension functions, are compiled
into static methods of a Java class named org.foo.bar.ExampleKt.
// example.kt
package demo
class Foo
fun bar() {
}
// Java
new demo.Foo();
demo.ExampleKt.bar();
my code below.
compile error; build failed:
thufir@dur:~/NetBeansProjects/kotlin$
thufir@dur:~/NetBeansProjects/kotlin$ gradle compileJava
> Task :compileJava
/home/thufir/NetBeansProjects/kotlin/src/main/java/net/bounceme/dur/kotlin/App.java:12: error: package demo does not exist
new demo.Foo();
^
/home/thufir/NetBeansProjects/kotlin/src/main/java/net/bounceme/dur/kotlin/App.java:13: error: package demo does not exist
demo.ExampleKt.bar();
^
2 errors
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed; see the compiler error output for details.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
* Get more help at https://help.gradle.org
BUILD FAILED in 0s
1 actionable task: 1 executed
thufir@dur:~/NetBeansProjects/kotlin$
java source:
package net.bounceme.dur.kotlin;
import java.util.logging.Logger;
public class App {
private static final Logger LOG = Logger.getLogger(App.class.getName());
private void run() {
LOG.info("running");
new demo.Foo();
demo.ExampleKt.bar();
}
public static void main(String[] args) {
new App().run();
}
}
kotlin source:
package demo;
class Foo
fun bar() {
}
project:
thufir@dur:~/NetBeansProjects/kotlin$
thufir@dur:~/NetBeansProjects/kotlin$ tree
.
├── build
│ ├── classes
│ │ └── java
│ │ └── main
│ └── tmp
│ └── compileJava
├── build.gradle
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main
│ ├── java
│ │ └── net
│ │ └── bounceme
│ │ └── dur
│ │ └── kotlin
│ │ └── App.java
│ └── kotlin
│ └── example.kt
└── test
└── java
└── AppTest.java
18 directories, 9 files
thufir@dur:~/NetBeansProjects/kotlin$
A:
use this in your build.gradle (module):
apply plugin: 'kotlin-android'
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display answers in index django?
I am trying to display questions and answer count in respective questions, all in the home page. How do I do it?
Models.py
class Question(models.Model):
CATEGORY_CHOICES = (
('Math', 'Math'),
('Geography', 'Geography'),
('Biology', 'Biology'),
('Physics', 'Physics'),
('Chemistry', 'Chemistry'),
('Health', 'Health'),
('Computer Science', 'Computer Science'),
('History', 'History'),
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField(max_length=3000)
slug = models.SlugField(max_length=140, unique=True)
date = models.DateField(null=True, default=datetime.date.today)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=50, default=None, null=True)
satisfied = models.BooleanField(default=False)
def __str__(self):
return self.title
def _get_unique_slug(self):
slug = slugify(self.title)
unique_slug = slug
num = 1
while Question.objects.filter(slug=unique_slug).exists():
unique_slug = '{}-{}'.format(slug, num)
num += 1
return unique_slug
def save(self, *args, **kwargs):
if not self.slug:
self.slug = self._get_unique_slug()
super().save()
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
user = models.ForeignKey(User, default=None)
answer = models.TextField(max_length=3000, null=True)
posted_on = models.DateField(default=datetime.datetime.now().date())
views.py
def home(request):
questions = Question.objects.all().order_by("-date")
numbers = Question.objects.all().count()
numbers2 = Answer.objects.all().count()
total_users = User.objects.all().count()
# PAGINATION ===============================
page = request.GET.get('page', 1)
paginator = Paginator(questions, 10)
try:
questions = paginator.page(page)
except PageNotAnInteger:
questions = paginator.page(1)
except EmptyPage:
questions = paginator.page(paginator.num_pages)
# counting answers on specific questions
empty = []
for a in Answer.objects.raw('SELECT id, question_id FROM main_answer'):
idd = a.id
question_id = (a.question_id)
empty.append(str(question_id))
repeatition = Counter(empty)
i = 0
trend_list = []
for x in range(len(repeatition)):
new = repeatition.most_common()[i][0]
trend_list.append(new)
i += 1
trend = Question.objects.get(id=trend_list[0])
print(trend_list)
print(trend)
# getting the answers to all questions in the front page
# search the questions ============
query= request.GET.get("q")
if query:
results = Question.objects.all()
questions = results.filter(title__icontains=query)
context = {
'questions': questions,
'numbers': numbers,
'numbers2': numbers2,
'total_users': total_users,
'trend': trend,
}
return render(request, 'main/index.html', context)
So what i need is to display questions and the number of answers in specific question.
For Example, in home page, I have all the questions displayed, what I want is to display the number on those questions.
What is Time? Answers: count of answers.
How can I do this? Please help.
A:
You can annotate your queryset with the number of answers:
from django.db.models import Count
results = Question.objects.annotate(num_answers=Count('answer'))
Then you can access question.num_answers as you loop through the queryset:
{% for question in questions %}
{{ question.title }}
{{ question.num_answers }}
{% endfor %}
| {
"pile_set_name": "StackExchange"
} |
Q:
Code Ignitter SQL Model Fatal error: Call to a member function result() on a non-object
Oke guys, i have a little problem about my codeignitter website, the problem display like this.
Fatal error: Call to a member function result() on a non-object in C:\xampp\htdocs\scbdnet\application\models\m_admin.php on line 88
The Code displayed like this :
Model
public function addUser()
{
$userid = $_POST['clientname'];
$userpassword = md5(12345);
$usernama = $_POST['completename'];
$useremail = $_POST['email'];
$usertelpon = $_POST['phone'];
$usernodesktop = $_POST['desktop'];
$usertypedesktop = $_POST['type'];
$usercompany = $_POST['company'];
$privilegeid = $_POST['level'];
$query=$this->db->query("INSERT INTO table_user (userId, userPassword, userName, userEmail, userTelp, userNoDesktop, userTypeDesktop, userCompany, fkPrivilegeId, userStatus)
VALUES ('$userid','$userpassword','$usernama','$useremail','$usertelpon','$usernodesktop','$usertypedesktop','$usercompany','$privilegeid','1');");
return $query->result(); //LINE 88
}
Controller
public function adduser_to_db(){
$this->load->model('m_admin');
$this->m_admin->addUser();
redirect('admin/user');
}
Views
<form action="<?php echo base_url();?>admin/adduser_to_db" method="POST" name="adduser" id="adduser">
<div class="row form-row">
<div class="col-md-12">
<input type="text" class="form-control" placeholder="New Username" name="clientname">
<input type="text" class="form-control" placeholder="Complete Name" name="completename">
<input type="text" class="form-control" placeholder="Email" name="email">
<input type="text" class="form-control" placeholder="Phone Ext." name="phone">
<input type="text" class="form-control" placeholder="Desktop no." name="desktop">
<input type="text" class="form-control" placeholder="Desktop type" name="type">
<input type="text" class="form-control" placeholder="Company" name="company">
<select id="level" style="width:100%" name="level">
<?php foreach($priv_list as $list){ ?>
<option value="<?php echo $list->privilegeId?>"><?php echo $list->privilegeStatus?></option><?php }?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="adduser" id="adduser" value="adduser">Save changes</button>
</div>
</form>
Any idea guys?
A:
$query->result(); does not work here
try like this
public function addUser()
{
$userid = $_POST['clientname'];
$userpassword = md5(12345);
$usernama = $_POST['completename'];
$useremail = $_POST['email'];
$usertelpon = $_POST['phone'];
$usernodesktop = $_POST['desktop'];
$usertypedesktop = $_POST['type'];
$usercompany = $_POST['company'];
$privilegeid = $_POST['level'];
$query=$this->db->query("INSERT INTO table_user (userId, userPassword, userName, userEmail, userTelp, userNoDesktop, userTypeDesktop, userCompany, fkPrivilegeId, userStatus)
VALUES ('$userid','$userpassword','$usernama','$useremail','$usertelpon','$usernodesktop','$usertypedesktop','$usercompany','$privilegeid','1');");
if($query){
return true;
}else{
return flase;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Using ResponseEntity Spring MVC
I want to use the ResponseEntity without returning a body, only set status code and headers. The ResponseEntity is a generic class, do I need to specify the type in this case, and if, what should it be?
A:
No you don't, just do something like this
ResponseEntity responseEntity = new ResponseEntity(HttpStatus.BAD_REQUEST);
A:
You can use return ResponseEntity<Void>
| {
"pile_set_name": "StackExchange"
} |
Q:
Eval MongoDB Query with NodeJS
I have a querying interface for MongoDB and am sending queries from a browser to NodeJS through a HTTP request. The query is is sent as a string and can be something like this:
var query = '{_id: ObjectId(\'536b07935c89be214c000009\'), "date": ISODate("2012-12-19T06:01:17.171Z"), mail: /test/i}'
My question, how can I safely evaluate this string in order to send it to the MongoDB NodeJS client?
eval is not an option (both on MongoDB and NodeJS) as this is part of a consumer faced application.
I'm open to other safe solutions for passing a query through HTTP and properly execute them on the server.
A:
The string you are presenting is a mongodb shell query.
This string contains mongodb shell specific datatypes, and as such is only usable inside the mongodb shell.
You can not parse or evaluate these queries in a different (javascript) enviroment, because they are not valid JSON. Hence, eval, or JSON.parse wouldn't even work, because of the specific datatypes.
If you want to serialize mongodb queries for usage in different enviroments, you could use MongoDB Extended JSON.
https://docs.mongodb.org/v3.0/reference/mongodb-extended-json/
This is standard JSON which can contain mongodb datatypes.
Your query would like this in MongoDB extended JSON.
{
"_id": {
"$oid": "536b07935c89be214c000009"
},
"date": {
"$date": "2012-12-19T06:01:17.171Z"
},
"mail": {
"$regex": "test",
"$options": "i"
}
}
If you want to parse or evaluate a string like this to pass it along to the node.js mongodb driver, you would need to use a library to deserialize this to a proper Node.js MongoDB Driver object.
You could use this library to do that:
https://www.npmjs.com/package/mongodb-extended-json
You can also use this library in your browser to build the queries. Or you could build the mongodb queries by hand.
I'm not aware of plugin / npm package that would allow you to convert mongodb shell queries to MongoDB Extended JSON automatically. You could try to convert them automatically by implementing some of the types your self ( ISODate, ObjectId ). However you will never have a full compatibility between the mongodb shell and the mongodb nodejs driver, many methods have different signatures and return types, cursors work differently, etc...
There also is this project, an alternative to the officially supported mongodb nodejs driver, which tries to mimic the shell a bit more if you really value that, but it won't help you with your specific query, you'll still need to convert it.
https://docs.mongodb.org/ecosystem/drivers/node-js/
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is this variable is listed as unassigned local variable in C# through Mono
I am unable to determine why the code here will not compile in MonoDevelop 2.8.2 on Win32 using Mono 2.10.6. Monodevelop indicates that found_image_paths is an unassigned local variable?
Am I missing something here? I am new to C#
string path = this.DirectoryChooser.CurrentFolder;
Console.WriteLine ("Selected Path: " + path);
//Iterate over all DAE files in this folder
string[] model_paths = Directory.GetFiles(path,"*.dae");
HashSet<string> found_image_paths;
foreach (string dae_path in model_paths)
{
XmlDocument xmlDoc= new XmlDocument(); //* create an xml document object.
xmlDoc.Load(dae_path); //* load the XML document from the specified file.
//* Get elements.
XmlNodeList library_images = xmlDoc.GetElementsByTagName("library_images");
System.Console.WriteLine(dae_path);
foreach (XmlNode image_node in library_images[0].ChildNodes) {
string image_path = image_node.FirstChild.InnerText;
found_image_paths.Add(image_path);
Console.WriteLine(image_path);
}
}
//The next line returns the error "Use of unassigned local variable 'found_image_paths'
foreach (var item in found_image_paths) {
A:
Because it is unassigned; you need to instantiate a hashset and assign it to your variable or at least assign it null.
| {
"pile_set_name": "StackExchange"
} |
Q:
Declaring a var instead of using .find multiple times?
I have been reading on best practices and I have come across this one:
Dont do this:
$("#element .child").hide()
Do this:
$("#element").find('.child').hide()
Now my question is what if i want to hide/show the .child element multiple times, should I declare it like this:
var spinner = $("#element").find('.child');
spinner.hide();
or do I just keep calling $("#element").find('.child').hide()
A:
Should I declare it like this:
var spinner = $("#element").find('.child');
spinner.hide();
Yes. You should do exactly that since it will obviate the need for multiple dom queries.
One common best practice though, so you can easily keep track of which variables are jQuery objects and which are not, is to prefix your variable with $
var $spinner = $("#element").find('.child');
$spinner.hide();
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery and labels
Further to my previous question, I have a jQuery event that I want to fire when the checkbox and the label itself is clicked.
jsFiddle example here.
My problem is that when I click the label, it doesn't fire the function. The checkbox works fine, as you can see.
Is there anything more I can add? Or is this it?
Thanks :)
EDIT: code from jsFiddle link
HTML
<div id="scrollwrap">
<div>
<input value="1" type="checkbox" name="salgsvilkar" id="checkbox2" style="float:left;"/>
<label for="checkbox2" class="akslabel">Salgs og leveringsvilkår er lest og akseptert</label>
</div>
</div>
jQuery
$(function() {
//checkbox
$("#checkbox2, .akslabel").click(function() {
$("#scrollwrap").toggleClass('highlight');
});
});
A:
You can change it a bit like this to be safe:
$(function() {
$("#checkbox2").change(function(){
$("#scrollwrap").toggleClass('highlight', this.checked);
});
});
You can test it out here. The advantage here is you can add a .change() on the end to make the state match if it's initially checked, like this:
$(function() {
$("#checkbox2").change(function(){
$("#scrollwrap").toggleClass('highlight', this.checked);
}).change();
});
You can test that version here. You can also make this much more generic, like this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android ImageView not displayed and is null
An ImageView inside a ListView item is not being displayed, however if I just replace ImageView with Button or something it's displayed fine.
Layout file of the list item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="18dp"
android:gravity="center"
android:orientation="horizontal"
android:weightSum="1">
<ImageView
android:id="@+id/image"
android:layout_width="48dp"
android:layout_height="48dp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.AppCompat.Medium" />
<TextView
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.AppCompat.Small" />
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray" />
Looked fine in Android Studio:
While it's not displayed at runtime:
Replace "ImageView" by "Button" and run:
Code that inflate this layout:
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View root = getLayoutInflater().inflate(R.layout.entry_pickblock_list, viewGroup, false);
Block blk = getItem(i);
TextView tv = root.findViewById(R.id.text);
tv.setText(blk.locale_name);
tv = root.findViewById(R.id.text2);
tv.setText(getString(R.string.pickblock_entry_detail, blk.id, blk.name));
ImageView iv = findViewById(R.id.image);//iv is null.
//iv.setImageDrawable(BlockIcons.get(blk.id));
return root;
}
Yes the ImageView is empty but it should have a border box shown by my debug tool. And more importantly, findViewById returns null for the ImageView but returns a valid Button reference when it's replaced by a Button.
That's to say, only ImageViews are removed in this ListView.
ImageViews in other lists are displayed and have border box shown even they're empty; Things else are shown in this ListView with same properties set.
I didn't write code to remove them, and I'm not able to do so at all since I can't even get it from view tree. I don't have Adblock or other Xposed modules installed that manipulates views. Vendor of my system or phone seems not doing so. So who did this?
A:
I think the problem is here
iv = findViewById(R.id.image);//iv is null
Shouldn't it be
iv = root.findViewById(R.id.image);
| {
"pile_set_name": "StackExchange"
} |
Q:
Dojo Build using Proj4 External JS File
I'm working on learning how to build an application into a single js file (or close to) using the Dojo Build System. I have followed the instructions to the best of my knowledge and have it working with a basic example. I am now trying to add additional js resources and widgets.
One of my widgets requires the Proj4js projection library to convert between coordinates. Unfortunately this is causing issues when I try to build the app.
error(311) Missing dependency.
module: app/widgets/MapInfo; dependency: proj4/proj4
I have my dojo config for that package set up as follows:
packages: [
// Using a string as a package is shorthand for `{ name: 'app', location: 'app' }`
'app',
'dgrid',
'dijit',
'dojo',
'dojox', {
name: 'put-selector',
location: 'put-selector',
main: 'put'
},
'xstyle',
'esri',
{
name: 'proj4',
location: '//cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.6/'
}
],
Here is the top of the widget:
define([
'dojo/_base/declare',
'dijit/_WidgetBase',
'dijit/_TemplatedMixin',
'dojo/_base/lang',
'dojo/html',
'dojo/dom-style',
'dojo/number',
'dojo/topic',
'proj4/proj4',
'xstyle/css!./MapInfo/css/MapInfo.css'
], function (
declare,
WidgetBase,
TemplatedMixin,
lang,
html,
style,
number,
topic,
proj4
) {
Option 1: ignore it
I had thought first to try and tell dojo to ignore it, however, after reading some posts this isn't really an option.
Option 2: Use a plugin?
My next thought is to try and use a dojo plugin like dojo/text! to include the file, however, I haven't been able to get this to work either.
Option 3: Embed script in page
Finally, as a last resort I could simply embed the script using a script tag and reference proj4 via window.proj4 in the widget, but this isn't very portable so I am looking for better solutions.
Thanks!
A:
I ended up getting this working by using a local copy of the proj4 library. Then I used the dojo's map property to map proj4 to its correct location:
map: {
'*': {
'viewer': 'cmv/viewer/js/viewer',
'gis': 'cmv/viewer/js/gis',
'proj4js': 'app/vendor'
}
},
proj4 can now be used by widgets using the path 'proj4js/proj4'.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does SagePay work with PayPal Express Checkout?
A client would like to integrate PayPal Express Checkout with SagePay. My understanding is that this is possible but I haven't been able to find any documentation online anywhere. I believe PayPal Express works by directing the user to PayPal to login, then retrieving user details from PayPal, and then confirming the order on site. However, when added with SagePay, does this work the same way, only then confirmation happens on SagePay? Can I just redirect to SagePay normally and it will register that someone has logged in using PayPal Express and automatically process the payment, bypassing the card selection screen?
I am writing in PHP and am intending to use Omnipay to handle this.
Thanks
A:
After contacting SagePay about this, it would appear that their integration of what they call 'Express Checkout' doesn't actually include the ability to take addresses from the PayPal account, they still need to come from your site
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get log4j to log my firms classes only
Below is a code of the log4j.xml file we are using at my firm. We been trying to change it to log only output from classes with made that is in org.xxxx. can someone let me know if this can be done and how to do it
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<appender name="logfile" class="org.apache.log4j.FileAppender">
<param name="File" value="logs/disater_relief.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<appender name="rollinglogfile" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="logs/ennrollment.log" />
<param name="immediateFlush" value="true" />
<param name="append" value="true" />
<param name="maxFileSize" value="1MB" />
<param name="maxBackupIndex" value="3" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<appender name="dailyrollinglogfile" class="org.apache.log4j.DailyRollingFileAppender">
<param name="file" value="logs/ennrollment.log" />
<param name="immediateFlush" value="true" />
<param name="append" value="true" />
<param name="datePattern" value=" '.' yyyy-MM-dd "/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<root>
<priority value="debug" />
<appender-ref ref="console" />
<appender-ref ref="dailyrollinglogfile" />
</root>
</log4j:configuration>
A:
Your root looger defines debug logging for all components. You should change it to warn (so you still see warnings) and add an extra logger for your own components:
<logger name="com.xxx.mycomponent">
<level value="trace"/>
<!-- appenders ... -->
</logger>
<root>
<priority value="warn" />
<appender-ref ref="console" />
<appender-ref ref="dailyrollinglogfile" />
</root>
| {
"pile_set_name": "StackExchange"
} |
Q:
Not a file, not a folder, but a hard link(?) to /bin from another partition - scared to delete
I have a not-quite-folder not-quite-file on my file system. It is an AWS EC2 instance running Ubuntu 18.04.4 LTS.
I have a script that runs nightly that picks up a file (/ebsvol/dead-drop/sync) and moves it to (/ebsvol/dead-drop/sync) using Robo, which in turn is using Symfony's Filesystem rename() method (https://symfony.com/doc/current/components/filesystem.html#rename).
const CANARY_PATH = '/ebsvol/dead-drop/sync';
const CANARY_WORKING_PATH = '/ebsvol/dead-drop/~sync';
...
$this->taskFilesystemStack()
->rename(self::CANARY_PATH, self::CANARY_WORKING_PATH)
->run();
Something is going awry in the script or with this code, though that's not really why I'm here. The result and cleanup is why I'm here. :)
The result is that the ~sync "file" is created, however it is actually... a hard link to /bin? This is where things get fishy. My ls -ial looks like this:
3276803 -rw-rw-r-- 1 configbot configbot 125 Jul 4 00:30 '~sync'
So it's just a text file, so let's try cat...
$ cat ~sync
cat: /bin: Is a directory
Uhh, OK.
$ cd ~sync
...changes my prompt to /bin, and doing an ls, it's surely bin. Incidentally, ls -ial on my root volume shows that /bin is iNode 12.
This has happened to me once in the past, and I just did rm -rf ~sync which hosed my entire server and I had to rebuild. So I'm trying to avoid that.
How do I get rid of this weird ~sync file/folder/symlink/hardlink without trashing /bin?
Some additional info:
/ebsvol is a separate EBS volume than / (i.e. separate hard drives/partitions!)
I think if it's a hard link in some weird way, rm ~sync might work. But wouldn't it show identical iNode numbers?
I will take a snapshot of both volumes before I attempt anything. :)
A:
It's a very bad idea to name a file beginning with a tilde if you intend to access it with a shell like bash. The reason being that it interprets the tilde as meaning that you want to access a user's home directory.
Thus, bash (and other shells) expand ~ to the current user's home directory, and expand ~sync to the home directory of the user named sync.
It turns out that your Ubuntu system has a system user named sync whose home directory is /bin. Thus when you try to access ~sync from the shell, it expands this to the user's home directory, and you start getting odd messages. And when you ran rm -rf ~sync the effect was rm -rf /bin, which pretty much trashes the system.
If you want to access the file itself, either quote it, or prefix it with something, such as its path:
$ cat ./~sync
You should also rework your code so that it does not create filenames that start with a tilde. This will save you and future you a lot of headaches later.
| {
"pile_set_name": "StackExchange"
} |
Q:
How cross browser is backbone.js?
We are working with several browser types - on web, mobile, tablet and smart-tv. We are looking into backbone.js for our mvc.
Is there any known cross browser limitations of backbone.js?
A:
I think this has less to do with Backbone then it has to do with the HTML and CSS you use. You can see a list of mobile uses of Backbone here: http://backbonejs.org/#examples. jQuery is commonly used together with Backbone and has a great track record of browser compatiblity. Check that out here: http://docs.jquery.com/Browser_Compatibility.
See also the backbone test suite mentioned by lwburk
A:
I'm just starting to learn backbone.js but we had a browser related issue regarding the history.
This:
Backbone.history.start({pushState: true})
Has some trouble with older browsers.
That's all we've run into so far, but the project is still pretty new.
Here's a related link on backbone's github:
https://github.com/documentcloud/backbone/issues/173
A:
c4urself's answer is good, but bringing things up to date with more recent evidence:
According to this comment by braddunbar in their github issues list, they don't have an official support document, but "to my knowledge Backbone supports IE6+, and the latest version of Chrome, Safari, Firefox, and Opera"
They have a test suite here which you can run in whatever browser you want in order to test support.
See also the support information for their dependencies:
jQuery: http://docs.jquery.com/Browser_Compatibility
Underscore: Can't find anything official either, but this comment on issue "Cut support for IE6-8 and other older browsers" by library author (of both underscore and backbone) jashkenas says "Underscore should always be a simple, single script that supports all of the environments you're likely to encounter as a JavaScript developer out of the box. Code that is written to work against one version of Underscore should just work, cross-platform."
JSON-js: can't find anything explicit, but since the point of the library "are for applications
that are expected to run in obsolete web browsers" that don't have the JSON object, I'd say that's not going to be an issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
User defined function can only have select statements
One of the main differences between UDF and SP is that UDF can only have select statements inside it and not insert/update/delete statements. Can someone please explain the reason behind this? The below function:
create function test(..)
...
BEGIN
insert into EMPLOYEE('22',12000,'john');
return 0;
END
is not valid. But why is this so?
A:
This is not about function (UDF) vs procedure. It is the context where you use them.
You can have DML operations in a function:
SQL> create table t1 (c1 number);
Table created.
SQL> create or replace function f1 return number as
2 begin
3 insert into t1 values (1);
4 commit;
5 return 0;
6 end;
7 /
Function created.
SQL> declare
2 i number;
3 begin
4 i := f1;
5 end;
6 /
PL/SQL procedure successfully completed.
SQL> select * from t1;
C1
----------
1
But if you use your function as and UDF in a query:
SQL> select f1 from dual;
select f1 from dual
*
ERROR at line 1:
ORA-14551: cannot perform a DML operation inside a query
ORA-06512: at "BP.F1", line 3
You can still work around this with an autonomous transaction:
SQL> create or replace function f2 return number as
2 pragma autonomous_transaction;
3 begin
4 insert into t1 values (1);
5 commit;
6 return 0;
7 end;
8 /
Function created.
SQL> select f2 from dual;
F2
----------
0
SQL> select * from t1;
C1
----------
1
1
But should you do this? I do not think so.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are my chances of getting a tourist visa to Croatia after 3 successive rejections?
First, I applied for a tourist visa for 16 days, showing a reservation for a hotel as I thought that visiting places nearby could be done in a single day. Also I showed my interest to meet friends I met online but didn't provide their details.
Result: visa refusal saying "Justification of purpose and conditions of the intended stay was not provided."
I required to reschedule my flight and changed the itinerary because of less time.
The second time, I applied right away for a tourist visa again for 9 days, showing a proper itinerary with different locations and different accommodation reservations. I added a letter to tell them about changes in the plan. I told them I wouldn't meet friends because my main purpose is tourism and I wouldn't have time to meet them.
Result: refusal with 3 points:
"proof of sufficient means of subsistence...".
"There are reasonable doubts as to the authenticity of the supporting documents or the veracity of their contents or the reliability of the statements made".
"There are reasonable doubts as to your intention to leave the territory of the republic of Croatia before the expiry of the visa applied for".
The third time, I applied again for a tourist visa with the same planning. And as I found that I didn't have movements in my savings account so may be it caused the issue. I added my salary account statements and other saving account statements. But I didn't have anything to prove my intention to leave the country other than my confirmed return flight, booking of final day accommodation. I thought the bank statement was issue for doubts on supporting document. So my new evidence will clear it.
Result: visa refusal with 2 points:
"There are reasonable doubts as to the authenticity of the supporting documents or the veracity of their contents or the reliability of the statements made".
"There are reasonable doubts as to your intention to leave the territory of the republic of Croatia before the expiry of the visa applied for".
After the third rejection I rescheduled my flights to next year. But still I am unable to find what the exact reason behind the refusal was. Recently I found that the company where I'm currently working was registered in February but I joined in January. So is it possible that they checked the company registration?
Can it be the reason of refusal of the visa application?
This year I am planning to go to a nearby country for my first international trip. Will it be helpful for my next application? Can buying a car be evidence of property? Can having a fixed deposit of 4,000 USD be evidence of property?
How can I improve my circumstance before applying again?
I tried to contact several consultants but they even didn't answer after listening to my query.
Any help would be appreciated. Thank you.
A:
You've applied three times in quick succession, with three rejections. You're seeing
There are reasonable doubts as to the authenticity of the supporting
documents or the veracity of their contents or the reliability of the
statements made".
and
"There are reasonable doubts as to your intention to leave the
territory of the republic of Croatia before the expiry of the visa
applied for".
The visa officer is saying that he no longer believes your explanations or your intentions.
You appear desperate, and the suspicion is that there is something going on that you're not being honest about. A fourth application now will serve only to reinforce that idea and will almost certainly result in another rejection. The consultants you have approached appear to have decided that you are a lost cause, at least for now.
Give up on Croatia for now. Cancel your flights - you're unlikely to have any success in the foreseeable future. You need to establish credible ties to your home country (an established job, own your own home or long term rental, family and friends) and a history of international travel before applying again. This could take years.
And when you do apply again consider consulting a lawyer with appropriate experience to help you draft your application.
| {
"pile_set_name": "StackExchange"
} |
Q:
Display Alert Dialog after WakefulIntentService completes?
I am using commansware example for wakefulIntentService. I am stuck at a point where I am not able to create alert dialog for the user after my doWakefulWork() gets the updated response from the backend?
I am starting this service and closing as soon as i get the favorable response. I have my polling interval as 2 mins and max this service can poll for 3 attempts that is 6 min. I donot want to display notifications and toast message as I want to capture other event on button click of this alert dialog.
Any help on how to alert the user of this update?
A:
You cannot raise a Dialog from a Service. This has nothing to do with WakefulIntentService.
You are welcome to start an activity from your service, perhaps an activity that uses a theme that makes it look like a dialog.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove that any linear functional on $\mathbb{R^{n}}$ with the Euclidean norm is bounded
I'm not sure how to prove this without just using the fact that is equivalent to say that a linear functional is continous.
A:
For
$\vec v \in \Bbb R^n, \tag 1$
we may write
$\vec v = \displaystyle \sum_1^n v_i \vec e_i, \tag 2$
where $\vec e_i$, $1 \le i \le n$ is a basis of $\Bbb R^n$, orthonormal in the Euclidean inner product $\langle \cdot, \cdot \rangle_2$ on $\Bbb R^n$, which defines the Euclidean norm norm $\Vert \cdot \Vert_2 = \langle \cdot, \cdot \rangle^{1/2}$ on $\Bbb R^n$ (see note below); then with
$\phi: \Bbb R^n \to \Bbb R \tag 3$
linear, we have
$\phi(\vec v) = \phi \left (\displaystyle \sum_1^n v_i \vec e_i \right ) = \displaystyle \sum_1^n v_i \phi(\vec e_i); \tag 4$
thus
$\vert \phi(\vec v) \vert = \left \vert \displaystyle \sum_1^n v_i \phi(\vec e_i) \right \vert \le \displaystyle \sum_1^n \vert v_i \phi(\vec e_i) \vert = \sum_1^n \vert v_i \vert \vert \phi(\vec e_i) \vert; \tag 5$
let
$M = \max \{\vert \phi(\vec e_i) \vert, \; 1 \le i \le n \}; \tag 6$
then
$\vert \phi(\vec v) \vert \le \displaystyle \sum_1^n \vert v_i \vert \vert \phi(\vec e_i) \vert \le M \sum_1^n \vert v_i \vert; \tag 7$
also,
$\vert v_i \vert \le \sqrt { \displaystyle \sum_1^n v_i^2 }, \ 1 \le i \le n; \tag 8$
whence
$\displaystyle \sum_1^n \vert v_i \vert \le n \sqrt { \displaystyle \sum_1^n v_i^2 }, \tag 9$
so that (7) becomes
$\vert \phi(\vec v) \vert \le M n \sqrt { \displaystyle \sum_1^n v_i^2 } = Mn\Vert \vec v \Vert_2, \tag {10}$
which shows that $\phi$ is bounded in the Euclidean norm $\Vert \cdot \Vert_2$ on $\Bbb R^n$, with bound $Mn$.
Nota Bene: The definition of Euclidean norm $\Vert \cdot \Vert_2$ on $\Bbb R^n$ used here is the usual one defined in terms of the Euclidean inner product $\langle \cdot, \cdot \rangle_2$, where if
$\vec w = \displaystyle \sum_1^n w_i \vec e_i, \tag{11}$
we have
$\langle \vec v, \vec w \rangle_2 = \displaystyle \sum_1^n v_i w_i, \tag{12}$
from which
$\Vert \vec v \Vert_2 = \sqrt{\langle \vec v, \vec v \rangle_2} = \sqrt {\displaystyle \sum_1^n v_i^2}; \tag{13}$
the vectors $\vec e_i$ are chosen orthonormal with respect to this basis:
$\langle \vec e_i, \vec e_j \rangle = \delta_{ij}, \; 1 \le i, j \le n. \tag{14}$
End of Note.
| {
"pile_set_name": "StackExchange"
} |
Q:
CesiumJS Running without 3D
We are planning on replacing OpenLayers with CesiumJS, however, we cannot be 100% sure our clients are going to have robust-enough video cards to support WebGL. We are only planning on using CesiumJS's 2D mapping features, is there a way to get around having a video card with WebGL (or OpenGL) capabilities?
A:
Core Cesium is based solely on WebGL, and requires it. But there's a fork called TerriaJS that uses Leaflet as its 2D fallback for non-WebGL systems. TerriaJS was built for Australia's National Map, and can be installed via npm.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best way to update a users email address in meteor?
So the built in meteor auth system stores user emails under the user like so:
emails: [ { address: [email protected], verified: true} ]
Is there a 'meteoric' way to set a primary email, and update an email address (or add/remove emails)?
It seems to me if would be a great deal simpler if they were stored like so:
emails: { '[email protected]': { verified: true } }
A:
Your suggested object format makes no sense, because then how do I request that object? Normally I'd say obj.emails[i].address, now I have to say... what? for (var key in obj.emails) { var email = obj.emails[key]; }? That's much more complicated.
To update an email address, you should change the email address in the user record, mark it unverified, and initiate the verification process with Account.sendVerificationEmail.
| {
"pile_set_name": "StackExchange"
} |
Q:
Algebra word problem but done without system of equations
I have this word problem, its well known mixture type of problem, I can solve this using a system of equations, so that is not the issue.
But is it possible to solve this just using numerical ways, such as
ratio-proportion method.
Here is the problem:
An 18% brine solution is a salt water mixture which has 18% salt. Bobby mixed some 18% brine solution with some 35% brine solution to make 85 L of 19% brine solution. What is the volume in liters of the 35% brine solution.
I have found another similar like problem here on stackoverflow:
solve ratio word problem without algebra
SO just to give an idea of the approach.
A:
$85\; L$ of a $19\%$ brine solution has $0.19 \times 85 = 16.15\; L$ of salt.
If Bobby just used the $18\%$ solution he would have $0.18 \times 85 = 15.30\; L$ of salt.
So he needed an additional $16.15 - 15.30 = 0.85\; L$ of salt. If you replace $1\; L$ of $18\%$ solution with $1\; L$ of $35\%$ solution you get an additional $0.35 - 0.18 = 0.17\; L$ of salt. So we have to do that $0.85/0.17 = 5$ times. Thus Bobby must have used $80\; L$ of $18\%$ and $5\; L$ of $35\%$ solution.
| {
"pile_set_name": "StackExchange"
} |
Q:
Image path is not displaying into textbox
<script type="text/javascript">
function myFunction() {
//var query = '?';
var str = $("form").serialize();
str = str.replace(/\=/g, "='").replace(/\&/g, "'&");
$( "#results" ).text(str+"'" );
var x = $("#results").text();
return x;
}
$('#myButton').on('click',function(){
var jsonString = JSON.stringify(myFunction());
console.log(jsonString);
$.ajax({
url: 'insert_value.php',
data: jsonString,
contentType: 'application/json; charset=utf-8',
type: 'POST',
}).done(function(resp) {
$('#result').html(resp)
});
});
</script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<?php
include("con_gen.php");
error_reporting(E_ALL);
// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "idcard";
$db_user = "root";
$db_word = "";
// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);
// DID THE CONNECT/SELECT WORK OR FAIL?
if ($mysqli->connect_errno)
{
$err
= "CONNECT FAIL: "
. $mysqli->connect_errno
. ' '
. $mysqli->connect_error
;
trigger_error($err, E_USER_ERROR);
}
// RUN A QUERY
$result = mysqli_query($mysqli,"SELECT value FROM combo1");
$num_rows = mysqli_num_rows($result);
//echo "$num_rows Rows\n";
if ($result->num_rows > 0) {
// output data of each row
$array = Array();
$array1 = Array();
while($row = $result->fetch_assoc()) {
//echo "<br> value: ". $row['value']. "<br>";
$array[] = $row['value'];
}
//print_r($array);
$sql = "SELECT static_name FROM static_values";
$result = mysqli_query($mysqli, $sql);
if ($result && mysqli_num_rows($result) > 0)
while($row = mysqli_fetch_array($result)){
//echo "<option>" . $row['static_name'] . "</option>";
$array1[]=$row['static_name'];
//echo $source;
}
// print_r($array1);
foreach ($array as $row)
{
if(in_array($row, $array1))
{
$sql = "SELECT source_table,Alias_name FROM static_values where static_name='$row'";
$res = $mysqli->query($sql);
// DID THE QUERY WORK OR FAIL?
if (!$res)
{
$err
= 'QUERY FAILURE:'
. ' ERRNO: '
. $mysqli->errno
. ' ERROR: '
. $mysqli->error
. ' QUERY: '
. $sql
;
trigger_error($err, E_USER_ERROR);
}
// ARE THERE ANY ROWS IN THE RESULTS SET
if ($res->num_rows == 0)
{
trigger_error("ERROR: NO DATA FOUND BY $sql", E_USER_ERROR);
}
// RETRIEVE THE ROWS INTO AN ARRAY OF HTML STATEMENTS
//$html = "";
echo '<form method="POST" action="" id="myform">';
while ($row = $res->fetch_object())
{
//$html =$html.'
echo'
<tr>
<td>
<div class="row-fluid">
<div class="span3 bgcolor">
<label>'.$row->Alias_name.'</label>
<select id='.$row->source_table.' name='.$row->source_table.' data-live-search="true" class="selectpicker form-control" type="sel">';
/*foreach ( $Data->{$row->source_table} as $key =>$item) {
echo "<option value=".$key.">".$item."</option>" ;
}*/
foreach ( $Data->{$row->source_table} as $key =>$item) {
echo "<option value=".$key.">".$item."</option>";
}
echo '
</select>
</div>
</div>
</td>
</tr>';
}
}
else if($row=="Image")
{
echo '
<tr>
<td>
<div class="row-fluid">
<div class="span3 bgcolor">
<label>'.$row.'</label>
<label>'.$row.'</label>
<input type="file" name="'.$row.'" id="'.$row.'" onchange="document.getElementById(\''.$row.'\').value = this.value">
<input type="text" name="'.$row.'" id="'.$row.'" value="'.$imagepath.'">
</div>
</div>
</td>
</tr>';
}
else
{
//$html =$html.'
echo '
<tr>
<td>
<div class="row-fluid">
<div class="span3 bgcolor">
<label>'.$row.'</label>
<input id='.$row.' type="text" placeholder=" Enter Value " name='.$row.' style="width:100%" class="form-control" required="" />
</select>
</div>
</div>
</td>
</tr>';
}
}
echo'<input id="myButton" type="button" value="SUBMIT" class="btn btn-success" name="submit" onclick="myFunction();"/>';
echo '<p id="results"> </p>';
echo '<pre id="result"></pre></form> ';
//echo '<p><tt id="results"></tt></p>';
}
?>
</body>
</html>
<?php else if($row=="Image")
{
echo '<tr>
<td>
<div class="row-fluid">
<div class="span3 bgcolor">
<label>'.$row.'</label>
<input type="file" name='.$row.' id='.$row.' onchange="document.getElementById('.$row.').value = this.value">
<input type="text" name='.$row.' id='.$row.'>
</div>
</div>
</td>
</tr>';
?>
Here I'm reading image full path within textbox and inserting into database but here image path is not coming into textbox please tell me solution
I posted my whole code please let me know the solution how to get image path into text box
A:
you need value attribute and every attribute value should be enclosed by single quotes or double quotes like this
<?php
echo '<tr>
<td>
<div class="row-fluid">
<div class="span3 bgcolor">
<label>'.$row.'</label>
<input type="file" name="'.$row.'" id="'.$row.'" onchange="document.getElementById(\''.$row.'\').value = this.value">
<input type="text" name="'.$row.'" id="'.$row.'" value="'.$imagepath.'">
</div>
</div>
</td>
</tr>';
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use C++ Boost's regex_iterator()
I am using Boost to match substrings in a string. Io iterate over the results, I need to use regex_iterator().
That is the only usage example I have found, but I do not understand the callback. Could someone give me an example uage of the function?
Let us assume that my input text is:
"Hello everybody this is a sentense
Bla bla 14 .. yes
date 04/15/1986
"
I want to get:
"Hello" "everybody" "this" "is" "a" "sentense" "bla" "yes" "date"
A:
If the only part of the example you don't understand is the callback, consider that:
std::for_each(m1, m2, ®ex_callback);
is roughly equivalent to:
for (; m1 != m2; ++m1){
class_index[(*m1)[5].str() + (*m1)[6].str()] = (*m1).position(5);
}
Assuming that, in your case, you want to store all the matches in a vector, you would write something like:
//Warning, untested:
boost::sregex_iterator m1(text.begin(), text.end(), expression);
boost::sregex_iterator m2;
std::vector<std::string> tokens;
for (; m1 != m2; ++m1){
tokens.push_back(m1->str()).
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Disable Grid of Buttons
I have a grid with lots of buttons in it, is it possible to disable the grid which would lead to all the buttons to being disabled?.
The reason why is after the use clicks a button to answer the question, the answer is checked and scores etc calculated, but if i keep pressing a button while this is happening it keeps answering the next question and so on even when i use a handler to wait. The disable is only temporary they are enabled again after everything is calculated.
How do i stop this? without having to disable every single button manually.
Thanks in advance.
Edit:
GridLayout numgrid = (GridLayout) findViewById(R.id.numbersGrid);
GridLayout lettergrid = (GridLayout) findViewById(R.id.lettersGrid);
numgrid.setEnabled(false);
lettergrid.setEnabled(false);
I tried the above code doesn't work as i need it too.
A:
Apparently there does not seem to be an "easy" way to solve this. What you can do is grab all buttons in your layout as an array, then loop through them. Something like the following method which disables all buttons in a GridLayout:
private void disableButtons(GridLayout layout) {
// Get all touchable views
ArrayList<View> layoutButtons = layout.getTouchables();
// loop through them, if they are an instance of Button, disable it.
for(View v : layoutButtons){
if( v instanceof Button ) {
((Button)v).setEnabled(false);
}
}
}
Then simply pass in your grid layouts:
GridLayout numGrid = (GridLayout) findViewById(R.id.numbersGrid);
GridLayout letterGrid = (GridLayout) findViewById(R.id.lettersGrid);
disableButtons(numGrid);
disableButtons(letterGrid);
| {
"pile_set_name": "StackExchange"
} |
Q:
Handling Android dynamic text string in res/values
Let's say I have this string:
Your player has a good keeper skill and a decent people skill
Now the part not in bold of the string is always the same, what is known at runtime is the part in bold.
So how could I do something like:
Your player has a {var1} keeper skill and a {var2} people skill
and then fill those vars at runtime with right values?
I do not want to concatenate strings like:
"You player has a" + var1 + "keeper skill and a" + var2 + "people skill"
A:
You need to see Android string resource guide. There is a way to provide static string which can be later formatted with variables.
http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
You will define string like
<resources>
<string name="welcome_messages">Hello, %1$s! You have <b>%2$d new messages</b>.</string>
</resources>
And later in code you can replace
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);
A:
in Strings.xml
You player has a %1$d keeper skill and a %2$d people skill
in java
getString(R.string.article_stats, var1, var2);
A:
Yes, see the following from android devguide
If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguements from your application like this:
Resources res = getResources();
String text = String.format(
res.getString(R.string.welcome_messages),
username, mailCount);
| {
"pile_set_name": "StackExchange"
} |
Q:
Android. Не меняется активити по нажатию кнопки
Добрый день!
Портирую свой клиент-серверный чат под Android.
У меня есть два активити с настройками либо клиента,
либо сервера, где по нажатию кнопки должны задаваться
параметры и активити меняется на другой. Но проблема в
том, что активити не меняется. Я закомментировал большую
часть кода всех трех активити, но не помогло.
Вот часть кода(только клиентская часть, ибо в
инициализации они схожи):
ClientSetting:
public class ClientSettings extends AppCompatActivity {
private EditText edit_nickname;
private EditText edit_serverIP;
private String nickname;
private String serverIP;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_settings);
edit_nickname = (EditText) findViewById(R.id.edit_nickname);
edit_serverIP = (EditText) findViewById(R.id.edit_serverIP);
Button btn_connect = (Button) findViewById(R.id.btn_connect);
View.OnClickListener listenerConnect = new View.OnClickListener() {
@Override
public void onClick(View view) {
nickname = edit_nickname.getText().toString();
serverIP = edit_serverIP.getText().toString();
setContentView(R.layout.activity_functional);
}
};
btn_connect.setOnClickListener(listenerConnect);
}
}
FunctionalActivity:
public class FunctionalActivity extends AppCompatActivity {
static private EditText edit_msg;
static private Button btn_send;
static private TextView msgBox;
static private String msg;
private Client client;
private Server server;
static private String nickname;
static private String serverIP;
static private String serverName;
static private String maxConnections;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_functional);
View.OnClickListener listenerSend = new View.OnClickListener() {
@Override
public void onClick(View view) {
msg = edit_msg.getText().toString();
}
};
}
static String waitAndGetMsg() {
while (true) {
if (btn_send.callOnClick()) {
if (!msg.isEmpty()) {
return msg;
}
}
}
}
public static void msgBoxSetText(String str) {
msgBox.setText(str);
}
static void msgBoxAddText(String str) {
msgBox.append(str);
}
}
UPD: Экспериментируя, я узнал, что оказывается из ClientSettings и ServerSettings ВООБЩЕ не меняется активити
A:
В классе ClientSettings, при обработке OnClickListener удалите setContentView(R.layout.activity_functional); и добавьте вызов activity
Пример:
View.OnClickListener listenerConnect = new View.OnClickListener() {
@Override
public void onClick(View view) {
nickname = edit_nickname.getText().toString();
serverIP = edit_serverIP.getText().toString();
Intent intent = new Intent(this, FunctionalActivity.class);
startActivity(intent); // вызов другой activity
}
};
Изучите
| {
"pile_set_name": "StackExchange"
} |
Q:
Highcharts - gap between series in stacked area chart
I've created a stacked area chart in Highcharts, which you can see in the image below and in the following jsfiddle: http://jsfiddle.net/m3dLtmoz/
I have a workaround for the gaps you see, which is to group the data for each series by month so that each series looks something like this instead:
series: [{
data: [
[1464739200000,2471],
[1467331200000,6275],
[1470009600000,2574],
[1472688000000,7221],
[1475280000000,3228]
]}
]
While the above isn't exactly what I'm going for, the way the series above is structured does give me what I ultimately want, which is this:
I'm really dying to know why the original setup isn't working appropriately, however. I've tested other instances where datetimes group and aggregate properly based on a single datetime x axis value. I'm stumped as to why this particular data set isn't working. I've tried using the dataGrouping option in the Highstock library, but wasn't able to integrate that effectively. I've messed with options as far as tickInterval goes to no avail. I tried setting the "stacking: 'normal' option in each series instead of in the plotOptions, but that made no difference. I've seen issues on github dealing with the stacked area charts, but nothing seems to exactly match up with what I'm seeing. Any help is appreciated - thank you much!
A:
You receive the error in the console. Most of the series require data to be sorted in ascending order. Stacking has nothing do to it, see example.
Series which do not require data to be sorted are scatter or polygon. No error in scatter
You should sort and group the points on your own. If you want to group them by months you have to prepare the data before you put them in a chart. The example below takes averages from the same datetime.
function groupData(unsortedData) {
var data = unsortedData.slice();
data.sort(function (a, b) {
return a[0] - b[0]
});
var i = 1,
len = data.length,
den = 1,
sum = data[0][1],
groupedData = [[data[0][0], sum]],
groupedData = [];
for (; i < len; i++) {
if (data[i - 1][0] === data[i][0]) {
sum += data[i][1];
den++;
} else {
groupedData.push([data[i - 1][0], sum / den]);
den = 1;
sum = data[i][1];
}
}
groupedData.push([data[i-1][0], sum / den]);
return groupedData;
}
example: http://jsfiddle.net/e4enhw9a/1/
| {
"pile_set_name": "StackExchange"
} |
Q:
binding validation controls in a datagrid
I have the following datagrid:
<asp:DataGrid runat="server" ID="gastosReembolsables" ShowFooter="True" AutoGenerateColumns="False">
<AlternatingItemStyle CssClass="DATAitem2"></AlternatingItemStyle>
<ItemStyle CssClass="DATAitem1"></ItemStyle>
<HeaderStyle CssClass="DATAheader"></HeaderStyle>
<FooterStyle CssClass="DATAitem1"></FooterStyle>
<Columns>
<asp:TemplateColumn runat="server" HeaderText="Item">
<ItemTemplate>
<asp:Label ID="Item" runat="server" Text='<%# Eval("item") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="Item" Width="40px" />
</FooterTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn runat="server" HeaderText="Precio">
<ItemTemplate>
<asp:Label runat="server" ID="precio" Width="40px" Text='<%# Eval("precio") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" Width="40px" ID="precio"></asp:TextBox>
</FooterTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn runat="server" HeaderText="Cantidad">
<ItemTemplate>
<asp:TextBox ID="cantidad" Width="40px" runat="server" Text='<%# Eval("cantidad") %>' />
<asp:DropDownList runat="server" ID="unidadMedida" DataValueField='id' DataTextField="nombre"></asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="cantidad" Width="40px" runat="server"></asp:TextBox>
<asp:DropDownList runat="server" ID="unidadMedida" DataValueField='id' DataTextField="nombre"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateColumn>
<asp:BoundColumn runat="server" HeaderText="Total" DataField="total" />
<asp:BoundColumn runat="server" Visible="False" DataField="id" />
<asp:TemplateColumn runat="server">
<ItemTemplate>
<asp:ImageButton ID="actualizarGasto" runat="server" CommandName="Update" ImageUrl="../../imagenes/btn_guardar.gif"
CausesValidation="True" ValidationGroup="item" />
<asp:ImageButton ID="eliminarGasto" runat="server" CommandName="Delete" ImageUrl="../../imagenes/btn_eliminar.gif"
CausesValidation="False" ValidationGroup="item" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="agregarGasto" runat="server" CommandName="New" ImageUrl="../../imagenes/agregar.png"
CausesValidation="True" ValidationGroup="footer" />
</FooterTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn runat="server" Visible="True">
<ItemTemplate>
<asp:RequiredFieldValidator ID="validaCantidad" runat="server"
ControlToValidate="cantidad" ValidationGroup='item<%# Eval("id") %>' ErrorMessage="Ingrese una Cantidad" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="validaCantidadNumerico" Display="Dynamic" runat="server"
ControlToValidate="cantidad" ValidationGroup='item<%# Eval("id") %>' ErrorMessage="La cantidad debe ser numérica"
Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>
<asp:CompareValidator ID="validaUnidadMedida" runat="server"
ControlToValidate="unidadMedida" ValidationGroup='item<%# Eval("id") %>' ErrorMessage="Seleccione una unidad de medida" Display="Dynamic" Operator="NotEqual" ValueToCompare="0"></asp:CompareValidator>
<asp:ValidationSummary ID="resumenGastosReembolsablesItem" runat="server" ShowMessageBox="True" ShowSummary="false" ValidationGroup='item<%# Eval("id") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:RequiredFieldValidator ID="validaCantidad" runat="server"
ControlToValidate="cantidad" ErrorMessage="Ingrese una Cantidad" Display="None" ValidationGroup="footer"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="validaCantidadNumerico" runat="server"
ControlToValidate="cantidad" Display="Dynamic" ErrorMessage="La cantidad debe ser numérica"
Operator="DataTypeCheck" Type="Integer" ValidationGroup="footer"></asp:CompareValidator>
<asp:CompareValidator ID="validaUnidadMedida" runat="server"
ControlToValidate="unidadMedida" ErrorMessage="Seleccione una unidad de medida" Display="Dynamic" ValidationGroup="footer" Operator="NotEqual" ValueToCompare="0"></asp:CompareValidator>
<asp:RequiredFieldValidator ID="validaItem" runat="server"
ControlToValidate="Item" ErrorMessage="Ingrese un Item" Display="Dynamic" ValidationGroup="footer"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="validaPrecio" runat="server"
ControlToValidate="precio" ErrorMessage="Ingrese un precio" Display="Dynamic" ValidationGroup="footer"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="validaPrecioNumerico" runat="server"
ControlToValidate="precio" ErrorMessage="El precio debe ser numérico"
Operator="DataTypeCheck" Type="Double" Display="Dynamic" ValidationGroup="footer"></asp:CompareValidator>
<asp:ValidationSummary ID="resumenGastosReembolsablesFooter" runat="server" ShowMessageBox="True" ShowSummary="False" ValidationGroup="footer" />
</FooterTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
all bindings work except the ones in the validation controls for the itemtemplate of the last column (they are passed as text to the web page).
Why is this happening? is it even possible to do what I'm trying to do?
A:
You can only use the <%# ... %> syntax to specify the entire value of a property, not a partial value.
Change
ValidationGroup='item<%# Eval("id") %>'
to
ValidationGroup='<%# "item" & Eval("id") %>'
| {
"pile_set_name": "StackExchange"
} |
Q:
Determine number of connected components
You are given a graph represented through an adjacency list. For example, the input
1-2 2-3 3-4 4-1
would correspond to the graph with nodes 1, 2, 3 and 4, where 1 is connected to 2, 2 is connected to 3, 3 is connected to 4, and 4 is connected to 1 (forming a square).
The task is to determine the number of of connected components of the graph represented by an inputted adjacency list. A "connected component" is a set of nodes from which there is no path to any other node that is not in the set.
Example:
Intput: 1-2 2-3 4-5
Output: 2
Language of your choice - shortest code possible.
A:
Ruby, 77 characters
gets;0while$_.sub!(/\b(\d+)\b(.*) (\1-\d+|\d+-\1)\b/,'\3\2');p$_.count(" ")+1
A first plain attempt in Ruby. It collects the sub-graphs using a regular expression until no more connections can be made.
Examples:
> 1-2 2-3 3-4 4-1
1
> 1-2 2-3 4-5
2
> 1-2 3-4 8-9 1-6 5-7 7-4 10-9
3
| {
"pile_set_name": "StackExchange"
} |
Q:
Double GOTO Command - DOS-Based Clock
I'm making a DOS-Based clock with blinking black/white background every seconds but goto command can't use like the code below the first goto makes the command runs only in the :CLOCK label
can anyone help me about this?
@echo off
title DOS-Based Clock
color a
cls
goto CLOCK
goto 0a
:CLOCK
cls
echo The current time is: %time%
goto CLOCK
:0a
color 0a
ping -n 2 127.0.0.1>nul
goto 7a
:7a
color 7a
ping -n 2 127.0.0.1>nul
goto 0a
A:
@echo off
title DOS-Based Clock
set "color=0a"
:clock
cls
color %color%
echo the current time is: %time%
ping -n 2 127.0.0.1 > nul
goto %color%
:0a
set "color=7a"
goto clock
:7a
set "color=0a"
goto clock
Use a variable to store the color and use it both to change the color and to jump to the same label as the color, then change the value of the color and repeat the process
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check if string has format arguments in Python?
I am formatting strings using named arguments with .format(). How can I obtain a list of arguments?
For example:
>>> my_string = 'I live in {city}, {state}, {country}.'
>>> get_format_args(my_string)
# ['city', 'state', 'country']
Note that order does not matter. I have dug a fair amount into the string.Formatter documentation to no avail. I am sure you could write regex to do this, but there must bet a more elegant way.
A:
It looks like you can get field names using the Formatter.parse method:
>>> import string
>>> my_string = 'I live in {city}, {state}, {country}.'
>>> [tup[1] for tup in string.Formatter().parse(my_string) if tup[1] is not None]
['city', 'state', 'country']
This will also return non-named arguments. Example: "{foo}{1}{}" will return ['foo', '1', '']. But if necessary you can filter out the latter two by using str.isdigit() and comparing against the empty string respectively.
A:
Regex can solve your problem.
>>> import re
>>> re.findall(r'{(.*?)}', 'I live in {city}, {state}, {country}.')
['city', 'state', 'country']
Edit:
To avoid matching escaped placeholders like '{{city}}' you should change your pattern to something like:
(?<=(?<!\{)\{)[^{}]*(?=\}(?!\}))
Explanation:
(?<= # Assert that the following can be matched before the current position
(?<!\{) # (only if the preceding character isn't a {)
\{ # a {
) # End of lookbehind
[^{}]* # Match any number of characters except braces
(?= # Assert that it's possible to match...
\} # a }
(?!\}) # (only if there is not another } that follows)
) # End of lookahead
| {
"pile_set_name": "StackExchange"
} |
Q:
Password hashing alogirthm simple enough to implement myself?
I'm doing a password manager for a school project and I need to hash the master password for verification but I also need to write the hashing algorithm myself. However, most the algorithms I've come across are very complicated (except for MD5 but that's overly insecure).
Are there any slightly simpler hashing alogorithms which won't take too long to write and implement without libraries? (I'm using c#).
A:
The PBKDF2 construction is simple to implement, and can be implemented with any underlying hash function.
Unlike modern password hash functions, the end result will be computationally intensive, but won't have any resistance against parallelization. Not requiring much memory means that ASICs can efficiently brute-force passwords hashed that way.
| {
"pile_set_name": "StackExchange"
} |
Q:
Change query sql
I have the following query to obtain an average of a data of the 52 weeks of the year as follows:
$dates = array();
$firstDate = date("Y-m-d", strtotime('first day of January 2016'));
$lastDate = date("Y-m-d", strtotime('last day of December 2016'));
for($i=strtotime($firstDate); $i<=strtotime($lastDate); $i+=86400 *7){
array_push($dates, date("Y-m-d", strtotime('monday this week', $i)));
}
for($i = 0; $i < count($dates); $i++){
$sql = "SELECT pr_products.product,
CONCAT(YEAR('".$dates[$i]."'),'-',LPAD(WEEK('".$dates[$i]."'),2,'0')) AS Week,
SUM(IF(sw_sowing.type = 'SW', sw_sowing.quantity,0)) AS PlantSowing,
SUM(IF(ROUND(DATEDIFF(TIMESTAMPADD(DAY,(6 WEEKDAY('".$dates[$i]."')),'".$dates[$i]."'), sw_sowing.date)/7) >= pr_products.week_production AND sw_sowing.type = 'SW',sw_sowing.quantity,0)) AS production
FROM (
SELECT max(sw_sowing.id) AS id
FROM sw_sowing
WHERE sw_sowing.status != 0
AND sw_sowing.id_tenant = :id_tenant
AND sw_sowing.status = 100
AND sw_sowing.date <= TIMESTAMPADD(DAY,(6-WEEKDAY('".$dates[$i]."')),'".$dates[$i]."')
GROUP BY sw_sowing.id_production_unit_detail
) AS sw
INNER JOIN sw_sowing ON sw_sowing.id = sw.id
INNER JOIN pr_products ON pr_products.id = sw_sowing.id_product
INNER JOIN pr_varieties ON sw_sowing.id_variety = pr_varieties.id
INNER JOIN pr_lands ON pr_lands.id = sw_sowing.id_land
WHERE pr_varieties.code != 1
AND sw_sowing.id_product = 1
AND sw_sowing.status = 100
GROUP BY pr_products.product
HAVING plantSowing > 0
ORDER BY pr_products.product";
}
I declare two variables initially that are $firstdate what is the start date and $lastDate which is the end date.
Then I make a for to go through the two dates and keep in an array the dates of Monday of each week.
Then I go through that new array to get the data I need from week to week.
Note: Within the query the variables $dates[$i] are the Monday dates of each week.
Anyway, the query works perfectly because it brings me the data I need from the 52 weeks of the year. The problem is that it takes a while.
I already indexed the tables in mysql, I improve a little but not enough, the query is not actually heavy it takes an average of 0.60 seconds per cycle.
I would like to know if there is a possibility of deleting the for what I am doing and within the query add I do not know, a WHERE that compares the two dates and brings me the data, or if there is any way to improve the query.
I already updated the query with the suggestions of the answer:
$data = array();
$start = new DateTime('first monday of January 2016');
$end = new DateTime('last day of December 2016');
$datePeriod = new DatePeriod($start , new DateInterval('P7D') , $end);
$sql = "SELECT product AS product,
Week AS label,
ROUND(SUM(harvest)/SUM(production),2) AS value
FROM (
(
SELECT pr_products.product,
CONCAT(YEAR(:dates),'-', LPAD(WEEK(:dates1),2,'0')) AS Week,
SUM(IF(sw_sowing.type = 'SW', sw_sowing.quantity,0)) AS PlantSowing,
SUM(IF(ROUND(DATEDIFF(TIMESTAMPADD(DAY,(6-WEEKDAY(:dates2)),:dates3), sw_sowing.date)/7) >= pr_products.week_production AND sw_sowing.type = 'SW',sw_sowing.quantity,0)) AS production,
0 AS Harvest
FROM (
SELECT max(sw_sowing.id) AS id
FROM sw_sowing
WHERE sw_sowing.status != 0
AND sw_sowing.date <= TIMESTAMPADD(DAY,(6-WEEKDAY(:dates4)),:dates5)
GROUP BY sw_sowing.id_production_unit_detail
) AS sw
INNER JOIN sw_sowing ON sw_sowing.id = sw.id
INNER JOIN pr_products ON pr_products.id = sw_sowing.id_product
INNER JOIN pr_varieties ON sw_sowing.id_variety = pr_varieties.id
WHERE pr_varieties.code != 1
AND sw_sowing.id_product = 1
AND sw_sowing.status = 100
AND sw_sowing.id_tenant = :id_tenant
GROUP BY pr_products.product
HAVING plantSowing > 0
ORDER BY pr_products.product
)
UNION ALL
(
SELECT pr_products.product,
CONCAT(YEAR(:dates6),'-', LPAD(WEEK(:dates7),2,'0')) AS Week,
0 AS plantSowing,
0 AS Production,
SUM(pf_harvest.quantity) AS Harvest
FROM pf_harvest
INNER JOIN pr_products ON pr_products.id = pf_harvest.id_product
INNER JOIN pr_varieties ON pr_varieties.id = pf_harvest.id_variety
INNER JOIN pf_performance ON pf_performance.id = pf_harvest.id_performance
WHERE pf_harvest.date BETWEEN TIMESTAMPADD(DAY,(0-WEEKDAY(:dates8)),:dates9)
AND TIMESTAMPADD(DAY,(6-WEEKDAY(:dates10)),:dates11)
AND pr_varieties.code != 1
AND pf_harvest.id_product = 1
AND pf_performance.status = 100
AND pf_harvest.id_tenant = :id_tenant1
GROUP BY pr_products.product
ORDER BY pr_products.product
)
) AS sc
GROUP BY product, label
ORDER BY label";
$statement = $this->db->prepare($sql);
$id_tenant = $this->getIdTenant();
foreach($datePeriod AS $dates){
$values = [
':dates' => $dates->format('Y-m-d'),
':dates1' => $dates->format('Y-m-d'),
':dates2' => $dates->format('Y-m-d'),
':dates3' => $dates->format('Y-m-d'),
':dates4' => $dates->format('Y-m-d'),
':dates5' => $dates->format('Y-m-d'),
':dates6' => $dates->format('Y-m-d'),
':dates7' => $dates->format('Y-m-d'),
':dates8' => $dates->format('Y-m-d'),
':dates9' => $dates->format('Y-m-d'),
':dates10' => $dates->format('Y-m-d'),
':dates11' => $dates->format('Y-m-d'),
':id_tenant' => $id_tenant,
':id_tenant1' => $id_tenant
];
$result = $this->db->executePrepared($statement , $values);
$data[] = $result->fetchAll();
}
$this -> jsonReturnSuccess($data);
A:
You have to consider that your entire code needs to be improved. First of all, use the resources from PHP to get some improvement.
DatePeriod
To create the period between the first and the last monday of the year. Use DatePeriod:
$start = new \DateTime('first monday of this year');
$end = new \DateTime('first day of next year');//The last date is never reached, so if the year ends in a monday, you won't have any problem
$datePeriod = new \DatePeriod($start , new \DateInterval('P7D') , $end);
foreach($datePeriod as $date)
{
echo $period->format('Y-m-d');
}
It's very fast compared to your for loop.
array_push
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
As manual says, if it's to add an element into the array, use $array[].
Prepared Statement
Other common problem which I found, use prepared statement. It can be used to your query get a "pre-compiled" state (simple example):
$query = 'SELECT * FROM table WHERE id = :id';
$statement = $pdo->prepare($query);
$idArray = [1 , 2 , 3 , 4 , 5 , /** very long array, as your date list **/ ];
foreach($idArray as $id)
{
$statement->execute(array(':id' => $id));
$result = $statement->fetchAll();
}
The N+1 problem
Another way is about the N+1 problem. If the others hints aren't enough to gain some speed, you can use native functions (array_map, array_walk, array_filter, etc...) to gather the values and do a single request.
Take a look at:
What is SELECT N+1?
https://secure.phabricator.com/book/phabcontrib/article/n_plus_one/
The Query
At last, I need more information about your query. You're using many mysql functions. It's the last plausible hint which I have. But, as you said, the query execution is fast. Try to take out those functions and check if the execution of script has been improved.
UPDATE
First of all, I think you're using so much PHP variable inside MySQL functions. If you have to take just the year and month (yyyy-mm), use DateTime::format().
$date->format('Y-m');//2017-02
There's a lot of example on manual.
As I said before, prepared statement is a kind of "pre-compiled" query. You have to write your query using placeholders (named or positional) instead of variables. The query above will be my example:
$query = "SELECT *
FROM
mytable
INNER JOIN mysecondtable ON (mytable.id = mysecondtable.id_mytable)
WHERE
mytable.date BETWEEN :start AND :end
AND mytable.value >= :value;";
You already have the foreach:
$data = array();
$start = new DateTime('first monday of January 2016');
$end = new DateTime('last day of December 2016');
$datePeriod = new DatePeriod($start , new DateInterval('P7D') , $end);
foreach($datePeriod AS $dates) {
//your code
}
Now, you have to "prepare" your query outside of your foreach loop:
$statement = $this->db->prepare($query);
foreach($datePeriod AS $dates) {
//your code
}
And inside your foreach, just have to use the placeholders.
foreach($datePeriod AS $dates) {
$values = [
'start' => $dates->format('Y-m-d'),
'end' => $dates->add(new DateInterval('P7D'))->format('Y-m-d'),//add 7 to reach a week
'value' => 10
];
$types = [
'start' => Column::BIND_PARAM_STR,
'end' => Column::BIND_PARAM_STR,
'value' => Column::BIND_PARAM_INT
]
//Phalcon PDO Adapter method
$result = $connection->executePrepared($statement , $values , $types);//The result is a PDOStatement object
$data[] = $result->fetchAll();
}
With these tips, you can improve a lot the execution time of your script.
| {
"pile_set_name": "StackExchange"
} |
Q:
visualization of correlation between replicates
To test the quality of the biological replicates by calculating Pearson correlation coefficient for the pairs of biological replicates for each cell-line.
A<-data.frame(A1=rnorm(100), A2=rnorm(100),
A3=rnorm(100), B1=rnorm(100),
B2=rnorm(100))
Some cases of the data have two replicates and others are three and contain no missing values. How to obtain such a plot to compare the replicates?
A:
Here's one possible way. There's probably a more concise way to do this, though.
First thing, figure out which columns are replicates of which.
fullnames<-colnames(A)
basenames<-substr(fullnames,1,nchar(fullnames)-1)
repnum<-as.integer(substr(fullnames,nchar(fullnames),nchar(fullnames)))
Now compute the correlation matrix, and extract the data you need:
ca<-cor(A)
corMask<-upper.tri(ca) & basenames[col(ca)]==basenames[row(ca)]
corSub<-ca[corMask]
nameSub<-basenames[row(ca)[corMask]]
repnumSub<-apply(cbind(repnum[row(ca[corMask]],repnum[col(ca[corMask]]),1,paste,collapse="-")
Then draw the plot:
require(ggplot2)
plotdata<-data.frame(name=nameSub,cor=corSub,replicas=repnumSub)
ggplot(plotdata,aes(x=name,y=cor,pch=replicas))+geom_point()
Here's what it looks like, with the following sample data set:
set.seed(123)
A<-data.frame(A1=rnorm(100), A2=rnorm(100),A3=rnorm(100),
B1=rnorm(100),B2=rnorm(100),
C1=rnorm(100),C2=rnorm(100),C3=rnorm(100))
You can then add color or change the plot limits etc. to make it look the way you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
understanding vptr in multiple inheritance?
I am trying to make sense of the statement in book effective c++. Following is the inheritance diagram for multiple inheritance.
Now the book says separate memory in each class is required for vptr. Also it makes following statement
An oddity in the above diagram is that there are only three vptrs even though four classes are involved. Implementations are free to generate four vptrs if they like, but three suffice (it turns out that B and D can share a vptr), and most implementations take advantage of this opportunity to reduce the compiler-generated overhead.
I could not see any reason why there is requirement of separate memory in each class for vptr. I had an understanding that vptr is inherited from base class whatever may be the inheritance type. If we assume that it shown resultant memory structure with inherited vptr how can they make the statement that
B and D can share a vptr
Can somebody please clarify a bit about vptr in multiple inheritance?
Do we need separate vptr in each class ?
Also if above is true why B and D can share vptr ?
A:
Your question is interesting, however I fear that you are aiming too big as a first question, so I will answer in several steps, if you don't mind :)
Disclaimer: I am no compiler writer, and though I have certainly studied the subject, my word should be taken with caution. There will me inaccuracies. And I am not that well versed in RTTI. Also, since this is not standard, what I describe are possibilities.
1. How to implement inheritance ?
Note: I will leave out alignment issues, they just mean that some padding could be included between the blocks
Let's leave it out virtual methods, for now, and concentrate on how inheritance is implemented, down below.
The truth is that inheritance and composition share a lot:
struct B { int t; int u; };
struct C { B b; int v; int w; };
struct D: B { int v; int w; };
Are going to look like:
B:
+-----+-----+
| t | u |
+-----+-----+
C:
+-----+-----+-----+-----+
| B | v | w |
+-----+-----+-----+-----+
D:
+-----+-----+-----+-----+
| B | v | w |
+-----+-----+-----+-----+
Shocking isn't it :) ?
This means, however, than multiple inheritance is quite simple to figure out:
struct A { int r; int s; };
struct M: A, B { int v; int w; };
M:
+-----+-----+-----+-----+-----+-----+
| A | B | v | w |
+-----+-----+-----+-----+-----+-----+
Using these diagrams, let's see what happens when casting a derived pointer to a base pointer:
M* pm = new M();
A* pa = pm; // points to the A subpart of M
B* pb = pm; // points to the B subpart of M
Using our previous diagram:
M:
+-----+-----+-----+-----+-----+-----+
| A | B | v | w |
+-----+-----+-----+-----+-----+-----+
^ ^
pm pb
pa
The fact that the address of pb is slightly different from that of pm is handled through pointer arithmetic automatically for you by the compiler.
2. How to implement virtual inheritance ?
Virtual inheritance is tricky: you need to ensure that a single V (for virtual) object will be shared by all the other subobjects. Let's define a simple diamond inheritance.
struct V { int t; };
struct B: virtual V { int u; };
struct C: virtual V { int v; };
struct D: B, C { int w; };
I'll leave out the representation, and concentrate on ensuring that in a D object, both the B and C subparts share the same subobject. How can it be done ?
Remember that a class size should be constant
Remember that when designed, neither B nor C can foresee whether they will be used together or not
The solution that has been found is therefore simple: B and C only reserve space for a pointer to V, and:
if you build a stand-alone B, the constructor will allocate a V on the heap, which will be handled automatically
if you build B as part of a D, the B subpart will expect the D constructor to pass the pointer to the location of V
And idem for C, obviously.
In D, an optimization allow the constructor to reserve space for V right in the object, because D does not inherit virtually from either B or C, giving the diagram you have shown (though we don't have yet virtual methods).
B: (and C is similar)
+-----+-----+
| V* | u |
+-----+-----+
D:
+-----+-----+-----+-----+-----+-----+
| B | C | w | A |
+-----+-----+-----+-----+-----+-----+
Remark now that casting from B to A is slightly trickier than simple pointer arithmetic: you need follow the pointer in B rather than simple pointer arithmetic.
There is a worse case though, up-casting. If I give you a pointer to A how do you know how to get back to B ?
In this case, the magic is performed by dynamic_cast, but this require some support (ie, information) stored somewhere. This is the so called RTTI (Run-Time Type Information). dynamic_cast will first determine that A is part of a D through some magic, then query D's runtime information to know where within D the B subobject is stored.
If we were in case where there is no B subobject, it would either return 0 (pointer form) or throw a bad_cast exception (reference form).
3. How to implement virtual methods ?
In general virtual methods are implemented through a v-table (ie, a table of pointer to functions) per class, and v-ptr to this table per-object. This is not the sole possible implementation, and it has been demonstrated that others could be faster, however it is both simple and with a predictable overhead (both in term of memory and dispatch speed).
If we take a simple base class object, with a virtual method:
struct B { virtual foo(); };
For the computer, there is no such things as member methods, so in fact you have:
struct B { VTable* vptr; };
void Bfoo(B* b);
struct BVTable { RTTI* rtti; void (*foo)(B*); };
When you derive from B:
struct D: B { virtual foo(); virtual bar(); };
You now have two virtual methods, one overrides B::foo, the other is brand new. The computer representation is akin to:
struct D { VTable* vptr; }; // single table, even for two methods
void Dfoo(D* d); void Dbar(D* d);
struct DVTable { RTTI* rtti; void (*foo)(D*); void (*foo)(B*); };
Note how BVTable and DVTable are so similar (since we put foo before bar) ? It's important!
D* d = /**/;
B* b = d; // noop, no needfor arithmetic
b->foo();
Let's translate the call to foo in machine language (somewhat):
// 1. get the vptr
void* vptr = b; // noop, it's stored at the first byte of B
// 2. get the pointer to foo function
void (*foo)(B*) = vptr[1]; // 0 is for RTTI
// 3. apply foo
(*foo)(b);
Those vptrs are initialized by the constructors of the objects, when executing the constructor of D, here is what happened:
D::D() calls B::B() first and foremost, to initiliaze its subparts
B::B() initialize vptr to point to its vtable, then returns
D::D() initialize vptr to point to its vtable, overriding B's
Therefore, vptr here pointed to D's vtable, and thus the foo applied was D's. For B it was completely transparent.
Here B and D share the same vptr!
4. Virtual tables in multi-inheritance
Unfortunately this sharing is not always possible.
First, as we have seen, in the case of virtual inheritance, the "shared" item is positionned oddly in the final complete object. It therefore has its own vptr. That's 1.
Second, in case of multi-inheritance, the first base is aligned with the complete object, but the second base cannot be (they both need space for their data), therefore it cannot share its vptr. That's 2.
Third, the first base is aligned with the complete object, thus offering us the same layout that in the case of simple inheritance (the same optimization opportunity). That's 3.
Quite simple, no ?
| {
"pile_set_name": "StackExchange"
} |
Q:
How to copy and paste a sheet in vba?
I'm searching how i can copy the activesheet in vba , i'm wanting to paste it in another workbook ( which is closed ).
Normaly i tried this but it fails :
Workbooks.Open Filename:=ThisWorkbook.Path & "\target.xlsx"
ThisWorkbook.ActiveSheet.Copy After:=Workbooks("target.xlsx").Sheets(Workbooks("target.xlsx").Worksheets.Count)
A:
Workbooks.Open is a function. It returns a Workbook object reference, pointing to the Workbook object that was just opened.
Workbooks.Open Filename:=ThisWorkbook.Path & "\target.xlsx"
You are discarding that reference.
Capture it!
Dim targetBook As Workbook
Set targetBook = Workbooks.Open(ThisWorkbook.Path & "\target.xlsx")
Now instead of dereferencing that workbook from the Workbooks collection everytime you need it...
ThisWorkbook.ActiveSheet.Copy After:=Workbooks("target.xlsx").Sheets(Workbooks("target.xlsx").Worksheets.Count)
Simply use the object you've got:
ThisWorkbook.ActiveSheet.Copy After:=targetBook.Sheets(targetBook.Worksheets.Count)
And when you're done, invoke it's Close method to close it:
targetBook.Close SaveChanges:=True
| {
"pile_set_name": "StackExchange"
} |
Q:
Problems with view controllers going into the background of UITabBarController
I have a UITabBarController with 3 view controllers connected to it. Everything works fine apart from when you switch from one view to another, the new view takes a moment to reload what it was doing. I know this isn't such a big deal but it just makes the app look a bit sloppy. Does anyone know how I can keep the app running in the background, or something so that it doesn't have to reload each time.
As you might have noticed I'm very new to Objective-C so I can understand if I'm being unclear but any help is really appreciated!
EDIT: FOR DAVID
This is the code for the stopwatch in the .m file:
@implementation StopwatchViewController
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
isCounting = false;
}
- (IBAction)startOrStop:(id)sender
{
if (self->isCounting == false) {
self->isCounting = true;
[self startStopwatch];
} else {
self->isCounting = false;
[self stopStopwatch];
}
}
- (void)startStopwatch
{
[startStopButton setTitle:@"STOP" forState:UIControlStateNormal];
[self performSelector:@selector(stopwatch) withObject:self afterDelay:1.0];
}
- (IBAction)resetStopwatch:(id)sender
{
[self reset];
}
- (void)stopwatch
{
if (self->isCounting == false) {
return;
} else {
NSInteger hourInt = [hourLabel.text intValue];
NSInteger minuteInt = [minuteLabel.text intValue];
NSInteger secondInt = [secondLabel.text intValue];
if (secondInt == 59) {
secondInt = 0;
if (minuteInt == 59) {
minuteInt = 0;
if (hourInt == 23) {
hourInt = 0;
} else {
hourInt += 1;
}
} else {
minuteInt += 1;
}
} else {
secondInt += 1;
}
NSString *hourString = [NSString stringWithFormat:@"%02d", hourInt];
NSString *minuteString = [NSString stringWithFormat:@"%02d", minuteInt];
NSString *secondString = [NSString stringWithFormat:@"%02d", secondInt];
hourLabel.text = hourString;
minuteLabel.text = minuteString;
secondLabel.text = secondString;
CGRect hourFrame = self->hourBar.frame;
CGRect minuteFrame = self->minuteBar.frame;
CGRect secondFrame = self->secondBar.frame;
if ((NSInteger)hourFrame.size.height != hourInt) { // check if we need to modify
hourFrame.origin.y -= ((hourInt * 10.0) - hourFrame.size.height);
hourFrame.size.height = (hourInt * 10.0);
self->hourBar.frame = hourFrame;
}
if ((NSInteger)minuteFrame.size.height != minuteInt) { // check if we need to modify
minuteFrame.origin.y -= ((minuteInt * 4.0) - minuteFrame.size.height);
minuteFrame.size.height = (minuteInt * 4.0);
self->minuteBar.frame = minuteFrame;
}
if ((NSInteger)secondFrame.size.height != secondInt) { // check if we need to modify
secondFrame.origin.y -= ((secondInt * 4.0) - secondFrame.size.height);
secondFrame.size.height = (secondInt * 4.0);
self->secondBar.frame = secondFrame;
}
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:NO];
}
}
- (void)stopStopwatch
{
[startStopButton setTitle:@"START" forState:UIControlStateNormal];
}
- (void)reset
{
[startStopButton setTitle:@"START" forState:UIControlStateNormal];
self->isCounting = false;
hourLabel.text = @"00";
minuteLabel.text = @"00";
secondLabel.text = @"00";
CGRect hourFrame = self->hourBar.frame;
CGRect minuteFrame = self->minuteBar.frame;
CGRect secondFrame = self->secondBar.frame;
hourFrame.size.height = 0;
minuteFrame.size.height = 0;
secondFrame.size.height = 0;
hourFrame.origin.y = 321.0;
minuteFrame.origin.y = 321.0;
secondFrame.origin.y = 321.0;
self->hourBar.frame = hourFrame;
self->minuteBar.frame = minuteFrame;
self->secondBar.frame = secondFrame;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
SECOND EDIT FOR DAVID:
Changed the main parts of the code to look like this:
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:YES];
[self swapFrames];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
[self updateBars];
}
- (void)stopwatch
{
if (self->isCounting == false) {
return;
} else {
hourInt = [hourLabel.text intValue];
minuteInt = [minuteLabel.text intValue];
secondInt = [secondLabel.text intValue];
if (secondInt == 59) {
secondInt = 0;
if (minuteInt == 59) {
minuteInt = 0;
if (hourInt == 23) {
hourInt = 0;
} else {
hourInt += 1;
}
} else {
minuteInt += 1;
}
} else {
secondInt += 1;
}
NSString *hourString = [NSString stringWithFormat:@"%02d", hourInt];
NSString *minuteString = [NSString stringWithFormat:@"%02d", minuteInt];
NSString *secondString = [NSString stringWithFormat:@"%02d", secondInt];
hourLabel.text = hourString;
minuteLabel.text = minuteString;
secondLabel.text = secondString;
[self swapFrames];
[self updateBars];
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:NO];
}
}
- (void)updateBars
{
if ((NSInteger)hourFrame.size.height != hourInt) { // check if we need to modify
hourFrame.origin.y -= ((hourInt * 10.0) - hourFrame.size.height);
hourFrame.size.height = (hourInt * 10.0);
self->hourBar.frame = hourFrame;
}
if ((NSInteger)minuteFrame.size.height != minuteInt) { // check if we need to modify
minuteFrame.origin.y -= ((minuteInt * 4.0) - minuteFrame.size.height);
minuteFrame.size.height = (minuteInt * 4.0);
self->minuteBar.frame = minuteFrame;
}
if ((NSInteger)secondFrame.size.height != (secondInt * 4.0)) { // check if we need to modify
secondFrame.origin.y -= ((secondInt * 4.0) - secondFrame.size.height);
secondFrame.size.height = (secondInt * 4.0);
self->secondBar.frame = secondFrame;
}
}
- (void)swapFrames
{
hourFrame = self->hourBar.frame;
minuteFrame = self->minuteBar.frame;
secondFrame = self->secondBar.frame;
}
I separated the code so that just before the view appear it should update the bars. However, it did not work. I did some investigating by printing out the values of some of the variables at certain points. It appears that in viewWillAppear, secondBar.frame (and minuteBar, etc.) has updated to the correct height. However, in viewDidAppear, that value is reset to 0. This does not happen to secondInt, or secondFrame. Somewhere between those two methods the frame is reset but I cannot figure it out.
A:
From what I understand, the frames for your properties self.hourBar, self.minuteBar and self.secondBar are set to 0 when you switch between tabs, and only update them every second.
If this is indeed the case, just set them to their correct values in your viewControllers viewWillAppear: method (assign them to some property in viewWillDisappear:).
As a sidenote, you seem to be coming from C++. The "->" notation is very uncommon for Objective-C, since properties are accessed with ".", and their corresponding instance variable with "->". Using the arrow notation will not call the auto-synthesised getter/setter methods of properties!
Also, is there a specific reason why you always create new NSTimer objects instead of setting repeats: to yes? Creating a timer and adding it to a runloop (which scheduledTimerWith:... does) is a relatively costly operation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento 1.7 Checkout Page Not Working Properly
Hello everyone I have a issue that I can not pin point at this time.
I am running magento at http://mytempsite.net/gotie and then have a wholesale store setup on the same installation at http://mytempsite.net/gotie/wholesale.
The issue is when I go to checkout on mytempsite.net/gotie when I click proceed to check out it goes to the next page but I am not able to move past the "Checkout as Guest, Register or Login Page" If i try loggin using an existing test account it loads the next step but under billing information there is absolutely nothing (Test Login: [email protected] pass: hayden927 )
But when I go to the wholesale site mytempsite.net/gotie/wholesale and add a product to cart I am able to go through all the steps just fine. You will need to login to see the catalog using the following information (Test Login: [email protected] pass: hayden927 )
What I have Tried
I have tried disabling all 3rd party plugins and modules.
List of 3rd Party Modules That Came with Theme?
Amasty Improved Navigation
Itoris Registration Fields (Wholesale Site)
Netzarbeiter Customer Activation (Wholesale Site)
Netzarbeiter Login Catalog (Wholesale Site)
List of 3rd Party Modules I installed
Phoenix Money Bookers
Webdziner Ajax Search
Webdziner All
Webdziner Bgsetting
Webdziner New Product
A:
I think there is an issue with your billing.phtml file. For some reason the content of the billing address container is empty.
It looks like this:
<div id="checkout-step-billing" class="step a-item" style="display:none;">
</div>
There should be some content inside the div. Actually a lot of content. Make sure there are no errors in app/design/frontend/{interface}/{theme}/checkout/onepage/billing.phtml. or if the file even exists. You can enable the logging and check the var/log folder for errors.
| {
"pile_set_name": "StackExchange"
} |
Q:
P812 "forgot" RAID6 - can't see disks at boot time in ORCA
We have an MSA60 with 12x4TB non-HP issue Seagate Constellation ES.3 drives connected to a P812/FBWC, on which I created a RAID6 over all of those disks with hpacucli and started to copy data on them.
Also, I pulled one of the drives during the early part of the copying procedure and replaced it, just to see how badly a RAID6 rebuild would affect write (and later read) performance for our production scenario. (It wasn't too bad, and it would've taken ~5 days to rebuild). This drive was at 75% rebuild.
Now I rebooted the DL385G7 with Debian Squeeze on it, to which the P812 is attached, and on reboot, no more array on the P812. The internal P410i array was intact. Hpacucli does see the drives, but lists them as unassigned. I googled a bit, and got the suggestion that re-creating the array the same would bring it back. I did do that. vgscan did not find the LVM volume.
I rebooted and went into ORCA. ORCA says that there are no volumes and no drives.
Now I'm a bit taken aback - what could be the problem? ORCA doesn't see the drives but hpacucli does? Could this be the problem why the LD that I created with hpacucli and already used doesn't pop up?
I have a replacement minisas cable and a replacement MSA60 I can play around with. A replacement P812 will take a while.
How do I debug this? What chance do I have getting the data back without the use of an external forensics company?
edit: Ok, now hpacucli doesn't see the drives either anymore. I think I'll go with replacing the MSA60 enclosure first.
edit2: Ok, ignoring all the "you're only a professional if you have the money for HP-disk-tax" snobbery, the following has transpired:
I did not check for the MSA actually being there:
=> ctrl slot=1 enclosure all show
Error: The specified device does not have any storage enclosures.
could've told me all I needed.
After swapping the cable and the port on the P812, I swapped the MSA60 (cold) and lo and behold, there was my array.
The previously rebuilding disk at 70-something% is now marked "OK", prompting me to run filesystem checks. I suspect that the controller will continue the rebuild after the initial rescan.
Please not that I did not pull a disk "just for fun". I pulled it to be able to judge if RAID6 was sufficient for our needs in production. Which I would encourage everybody to do for a new configuration - doesn't matter if in storage, a piece of software or network equipment.
A:
So let me summarise, correct me if I've missed something out;
You're running unsupported disks
You're running an unsupported OS
You pulled a disk for fun
You've lost your array
Is that right?
If so then you want to know how to debug this right? This site is for professional sysadmins, not amateurs, it says so in the top line of our FAQ (which you read right, and definitely didn't skip yeah?), but you're running an unsupportable disk setup and are surprised that causing an unnecessary fault has knock-on effects - and you did this on a server that had actual data on it, not test data of zero value.
I think you probably could get your data back using an external company, but it'll be pretty spendy, hopefully enough to teach you to use supported configurations and never to cause a fault for the fun of it.
By the way I have LOTS of PXXX cards, including probably being the largest P8xx-series buyer in the world and we've NEVER lost an array every in literally millions of disk/hours over more than half a decade of use.
A:
Your array is probably gone. I suspect that you probably ran into a firmware issue. Chances are that your P812 controller wasn't at a good revision level. Also, the MSA60 went end-of-life back in 2008-2009.
Did you run any updates prior to configuring this array?
What version firmware is the Smart Array P812 controller running?
Is the MSA60 at a good level?
Were these SAS or SATA drives?
What link speed did the drive negotiate? 1.5Gbps? 3Gbps?
Can you boot the Array Configuration Utility and run an HP ADU diagnostic report?
Finally, pull the power on everything. Let the drives and enclosure spin down. Try again.
Failures on the MSA60 and Smart Array controllers are very rare. I think you ran into a bug. Using RAID6 (which is sub-optimal in most situations) and unsupported disks could be an issue. Especially with SATA. If anything, I'd run them RAID 1+0 to reduce the chance of controller issues.
Potential problems fixed by recent firmware (over the last year)...
Protection has been added to prevent potential Smart Array controller hangs under rare conditions when hot-adding hard drives.
On rare occasions, the Smart Array controller would reset the same SATA drive several times when a PHY is stuck longer than four seconds.
The Smart Array controller would not connect to hard drives within 20ms under heavy stress.
Fixed an issue with the HP P812 controller in which a rare lockup (code 0xD4) could occur upon reboot.
Fixed an issue where after hot-adding a SATA disk to an MSA-60, MSA-70, or HP DL180-G6 12-drive backplane, the storage controller could become unresponsive. Reference Customer Advisory c03011608.
Fixed an issue where simultaneous handling of many Unrecoverable Read Errors on SATA disks supporting Native Command Queuing could result in a lockup (code 0x15).
RAID 6/60 surface analysis could result in background parity scans that stop responding while doing excessive fault tolerance calculations.
A Smart Array P812 controller attached to multiple MSA 60 storage systems may encounter a lockup condition (lockup code 0XAB) during heavy I/O workload.
After hot-replacement of an HP Smart Array HDD, all drives, which were attached to the expander where the HDD was replaced, report as being in Bay 0. Issue occurs on the HP StorageWorks MSA60, HP StorageWorks MSA70, and HP ProLiant DL180 G6 with 12 bay and 25 bay backplanes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way I can give 20% width to a div and the remainder of width to another div with CSS
I have the following simple HTML:
<article id="root-view">
<div id="menu-view">
x
</div>
<div id="content-view">
y
</div>
</div>
I set the style of menu-view to width: 20% and content-view to width: 80%
I would like to now give the menu-view: width: 40rem and have the remainder allocated to the content-view.
Is there a way that I can do this with CSS? I've not seen a setting that I could use for content-view's width? Note that we are using browsers IE9 and above.
A:
You could use calc() to set #content-view's width to 100% subtracted by 40rem.
jsFiddle example - Full screen example might work better.
#content-view {
width:calc(100% - 40rem);
}
This is equivalent to the remaining space.
Alternatively, you could use CSS tables:
jsFiddle example - Full screen example
#root-view {
display:table;
width:100%;
}
#menu-view {
display:table-cell;
width:40rem;
}
#content-view {
display:table-cell;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
get highest attribute number in jquery and ecmascript6
trying to get the max value for all selects with the same data attribute. but receiving the error
{ "message": "Uncaught TypeError: undefined is not a function",
"filename": "https://stacksnippets.net/js", "lineno": 37, "colno":
34 }
please run snippet below I would like it to console out 3 as that is the highest responsegroupnumber with a question.id of 1
$(document).ready(function() {
let question = {
Id: 1
};
let responseGroupNumber = Math.max(...$(`select[data-questionid = ${question.Id}]`)
.map(x => $(x)
.attr('data-responsegroupnumber')));
console.log(responseGroupNumber);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select data-questionid="1" data-responsegroupnumber="1">
<option>one</option>
<option>two</option>
<option>three</option>
</select>
<select data-questionid="1" data-responsegroupnumber="2">
<option>one</option>
<option>two</option>
<option>three</option>
</select>
<select data-questionid="1" data-responsegroupnumber="3">
<option>one</option>
<option>two</option>
<option>three</option>
</select>
A:
You need to use the jQuery .get() function before mapping :
If you don't, you'll be using jQuery .map() method instead of Array#map
$(document).ready(function() {
let question = {
Id: 1
};
let responseGroupNumber = Math.max(...$(`select[data-questionid = ${question.Id}]`).get().map(x => $(x).attr('data-responsegroupnumber')));
console.log(responseGroupNumber);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select data-questionid="1" data-responsegroupnumber="1">
<option>one</option>
<option>two</option>
<option>three</option>
</select>
<select data-questionid="1" data-responsegroupnumber="2">
<option>one</option>
<option>two</option>
<option>three</option>
</select>
<select data-questionid="1" data-responsegroupnumber="3">
<option>one</option>
<option>two</option>
<option>three</option>
</select>
| {
"pile_set_name": "StackExchange"
} |
Q:
Casting exception during form validation of nested:select (Struts 1.3.10)
I am now trying to dig into struts framework and now, I am testing nested-tags. I encounter problem when I retrieve data. My code is as following :
<nested:select property="formatDisponible">
<logic:iterate id="listFormat" property="formatList" name="videoGameForm">
<html:option value="${listFormat}" />
</logic:iterate>
</nested:select>
When I perform validation action (by that I mean retrieving data from my form) I got the following exception:
GRAVE: Method invocation failed.
java.lang.IllegalArgumentException: java.lang.ClassCastException@110e3b5
at sun.reflect.GeneratedMethodAccessor80.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
Thank you for your help (I will update you about any change).
I finally found what was going wrong in my previous code. If somehow, other people are facing the same problem, I am going to put the correct code below.
<nested:nest property="formatDisponible">
<nested:select property="id">
<html:options collection="formatList" property="id" labelProperty="nom" labelName="id"></html:options>
</nested:select>
</nested:nest>
I corrected my first test and ended up with that solution. The only thing I am trying to figure out right now is how to set selected value (because I am using this form to update my object). If I can resolve it, I will update my post.
A:
All my problem related to this question was solved (at least for now). I accidentally overloaded the value of the select property.
| {
"pile_set_name": "StackExchange"
} |
Q:
Split and join back a binary file in java
I am trying to divide a binary file (like video/audio/image) into chunks of 100kb each and then join those chunks back to get back the original file.
My code seems to be working, in the sense that it divides the file and joins the chunks, the file I get back is of the same size as original. However, the problem is that the contents get truncated - that is, if it's a video file it stops after 2 seconds, if it is image file then only the upper part looks correct.
Here is the code I am using (I can post the entire code if you like):
For dividing:
File ifile = new File(fname);
FileInputStream fis;
String newName;
FileOutputStream chunk;
int fileSize = (int) ifile.length();
int nChunks = 0, read = 0, readLength = Chunk_Size;
byte[] byteChunk;
try {
fis = new FileInputStream(ifile);
StupidTest.size = (int)ifile.length();
while (fileSize > 0) {
if (fileSize <= Chunk_Size) {
readLength = fileSize;
}
byteChunk = new byte[readLength];
read = fis.read(byteChunk, 0, readLength);
fileSize -= read;
assert(read==byteChunk.length);
nChunks++;
newName = fname + ".part" + Integer.toString(nChunks - 1);
chunk = new FileOutputStream(new File(newName));
chunk.write(byteChunk);
chunk.flush();
chunk.close();
byteChunk = null;
chunk = null;
}
fis.close();
fis = null;
And for joining file, I put the names of all chunks in a List, then sort it by name and then run the following code:
File ofile = new File(fname);
FileOutputStream fos;
FileInputStream fis;
byte[] fileBytes;
int bytesRead = 0;
try {
fos = new FileOutputStream(ofile,true);
for (File file : files) {
fis = new FileInputStream(file);
fileBytes = new byte[(int) file.length()];
bytesRead = fis.read(fileBytes, 0,(int) file.length());
assert(bytesRead == fileBytes.length);
assert(bytesRead == (int) file.length());
fos.write(fileBytes);
fos.flush();
fileBytes = null;
fis.close();
fis = null;
}
fos.close();
fos = null;
A:
I can spot only 2 potential mistakes in the code:
int fileSize = (int) ifile.length();
The above fails when the file is over 2GB since an int cannot hold more.
newName = fname + ".part" + Integer.toString(nChunks - 1);
A filename which is constructed like that should be sorted on a very specific manner. When using default string sorting, name.part10 will namely come before name.part2. You'd like to supply a custom Comparator which extracts and parses the part number as an int and then compare by that instead.
A:
And for joining file, I put the names of all chunks in a List, then sort it by name and then run the following code:
But your names are of the following form:
newName = fname + ".part" + Integer.toString(nChunks - 1);
Think carefully about what happens if you have 11 or more parts. Which string comes first in alphabetical order: ".part10" or ".part2"? (Answer: ".part10", since '1' comes before '2' in the character encoding.)
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the official reasoning behind "stepped-up basis" when selling inherited property?
Note: "official" here means "on-paper". Meaning: I'm not asking what's the true reason this stepped-up basis calculation exists, but rather how it's justified on paper. This is to prevent this from getting political.
I'm a non-American and was recently made aware of the "stepped-up basis" calculation when selling inherited property.
This quote (source) should explain for non-Americans:
Plus, your inheritance receives a "stepped-up basis" to the date of the decedent's death as well.
For example, you might inherit a house that's valued at $250,000 on the decedent's date of death. You then sell the property for $275,000 a few years later. You would owe long-term capital gains tax on $25,000.
Even if the decedent purchased the property decades ago for $100,000, your gain isn't calculated using this number.
Playing the advocate for this rule for the sake of trying to understand it, I couldn't come up with a convincing argument.
A:
I don't think you'll find "official reasoning" from the IRS. The most reasonable explanation in my view is that it prevents double-taxation of estate assets and applies a consistent methodology for taxation of inherited property. The estate tax is based on inherited value, not the basis.
Say you inherited a $50M estate that had a $1M basis. Upon inheritance almost $38M ($50M - $11.2M exemption, and some disparity caused by progressive tax rates) would be subject to the 40% estate tax rate. If the basis wasn't stepped up and you sold it immediately for $50M you'd pay 20% of almost $49M in capital gains tax.
The exemption amount was much lower in the past, so this double-taxation issue was more relevant. In 2010 people actually had a choice between carryover basis and stepped up basis, if they chose carryover basis they paid no estate tax. That odd year highlights the link between estate tax and stepped up basis.
It is also logistically challenging to try to track basis over generations, while determining current value is relatively easy for most assets.
Of course, the high exemption amount and trust-based loopholes allow many to avoid estate tax, which erodes the impact of stepped up basis, but that's the nature of our complex tax code.
A:
One intent is to reduce double-taxation. If several people inherit a property with a low cost basis (say a house that was bought decades ago), then the most practical thing is usually for some or all of them to sell it and take the proceeds. With a very low cost basis, the total value of the property is effectively what is inherited.
But in the US, there is also an estate tax that is levied on estates upon inheritance (with a very large exemption). If the value of the property were effectively inherited (via a low cost basis), AND the estate tax were to apply, then the property would be effectively taxed twice.
Now, the estate tax only kicks in in very large estates, so this particular benefit only applies to the very wealthy, but it also benefits those that inherit, say, a family farm that don't then have to pay a large tax bill upon inheriting the land.
| {
"pile_set_name": "StackExchange"
} |
Q:
HTTP Post returns the whole website html instead of a JSON response
So im trying to get a JSON response from a server using this api
The problem is that it returns the html code of the homepage of the website. If you look at the api page it says that it should return some json.
I think there's something wrong with my code.
Any suggestions?
The image im using:
My code:
static void Main(string[] args)
{
Image img = Image.FromFile("image.jpg");
String base64 = ImageToBase64(img, System.Drawing.Imaging.ImageFormat.Jpeg);
var request = (HttpWebRequest)WebRequest.Create("http://www.whatanime.ga/api/search?token=<token>");
var postData = base64;
var data = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine("data:" + responseString);
Console.ReadLine();
}
public static string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
A:
Okay after some messing with other options I've found a working (for me) solution
I'm posting this to help people in the future with the same problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using System.Drawing;
using System.Net;
using System.Collections.Specialized;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Image img = Image.FromFile("image.jpg");
String base64 = ImageToBase64(img, System.Drawing.Imaging.ImageFormat.Jpeg);
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["image"] = base64;
var response = client.UploadValues("https://whatanime.ga/api/search?token=<token>", values);
var responseString = Encoding.Default.GetString(response);
Console.WriteLine("data: " + responseString);
Console.ReadLine();
}
}
public static string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to restore a GIT repository to a server from a client
I have a Synology DS212j NAS that I was running gitolite and git on it. The DS212j was corrupted with a virus and through the process of cleaning it, my NAS was lost and formatted. I have a up-to-date GIT repo on a laptop and I want to start over on the DS212j and push everything including all of my checkins and history into a repo on the DS212j. Is there a way to accomplish this task?
A:
As long as you have your local copy you can simply set up an empty GIT repository on the server (in your example your gitolite instance on your NAS), update your remote-url in your local copy and then simply push to the remote.
So in single steps:
Set up gitolite
Set up your project in your gitolite instance
(if required) Change the remote URL (see git remote set-url) in your local copy
Do a git push to the newly created remote (maybe with multiple branches)
After this you will have an exact copy of your local on the remote (your NAS).
| {
"pile_set_name": "StackExchange"
} |
Q:
Has Facebook sharer.php changed to no longer accept detailed parameters?
We have been opening a sharing popup (via window.open) with the URL like
https://www.facebook.com/sharer/sharer.php?s=100&p[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE
and until some unknown point in the last month or so everything was fine.
What is happening now is; the popup dialog appears and correctly includes the Title, Description, Image and URL provided by the query string parameters, but when the post is submitted, the resulting wall post on Facebook is missing the Title, Description and Image, though it still links to the correct URL.
Does anyone know if there have been recent changes which could have suddenly stopped this from working?
Pre-empting some common responses:
"sharer.php URL was deprecated" - usage seemed to continue and it
seemed the consensus was that it was largely considered to be
sticking around - I haven't seen any specific indication that it
should have suddenly ceased working - might have missed something
"Use JavaScript SDK/these OG meta tags" - not possible in my specific
situation - just trust me ... I can explain if you REALLY want but
it's really not relevant.
"Use the feed dialog" - not suitable due to lack of support for
posting with attachments on FB pages
A:
Facebook no longer supports custom parameters in sharer.php
The sharer will no longer accept custom parameters and facebook will
pull the information that is being displayed in the preview the same
way that it would appear on facebook as a post from the url OG meta
tags.
Use dialog/feeds instead of sharer.php
https://www.facebook.com/dialog/feed?
app_id=145634995501895
&display=popup&caption=An%20example%20caption
&link=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fdialogs%2F
&redirect_uri=https://developers.facebook.com/tools/explorer
Official answer from fb team
A:
Starting from July 18, 2017 Facebook has decided to disregard custom parameters set by users. This choice blocks many of the possibilities offered by this answer and it also breaks buttons used on several websites.
The quote and hashtag parameters work as of Dec 2018.
Does anyone know if there have been recent changes which could have suddenly stopped this from working?
The parameters have changed. The currently accepted answer states:
Facebook no longer supports custom parameters in sharer.php
But this is not entirely correct. Well, maybe they do not support or endorse them, but custom parameters can be used if you know the correct names. These include:
URL (of course) → u
custom image → picture
custom title → title
custom quote → quote
custom description → description
caption (aka website name) → caption
For instance, you can share this very question with the following URL:
https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fstackoverflow.com%2Fq%2F20956229%2F1101509&picture=http%3A%2F%2Fwww.applezein.net%2Fwordpress%2Fwp-content%2Fuploads%2F2015%2F03%2Ffacebook-logo.jpg&title=A+nice+question+about+Facebook"e=Does+anyone+know+if+there+have+been+recent+changes+which+could+have+suddenly+stopped+this+from+working%3F&description=Apparently%2C+the+accepted+answer+is+not+correct.
Try it!
I've built a tool which makes it easier to share URLs on Facebook with custom parameters. You can use it to generate your sharer.php link, just press the button and copy the URL from the tab that opens.
A:
Your problem is caused by the lack of markers OpenGraph, as you say it is not possible that you implement for some reason.
For you, the only solution is to use the PHP Facebook API.
First you must create the application in your facebook account.
When creating the application you will have two key data for your code:
YOUR_APP_ID
YOUR_APP_SECRET
Download the Facebook PHP SDK from here.
You can start with this code for share content from your site:
<?php
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?php
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
// Give the user a logout link
echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please <a href="' . $login_url . '">login.</a>';
}
?>
</body>
</html>
You can find more examples in the Facebook Developers site:
https://developers.facebook.com/docs/reference/php
| {
"pile_set_name": "StackExchange"
} |
Q:
Questions regarding simulating Central Limit Theorem from Book Data Science from Scratch
I was reading the book Data Science From scratch by Joel Grus. My question is specifically concerning Chapter 6, where the author was using binomial random variable to simulate the theorem.
The result would be a chart with the probability distribution of the binomial trials and an approximation plot using normal distribution. The two plots should be very similar to each other. The book shows a chart like this:
Author's Chart
The codes he provided are:
import random
from matplotlib import pyplot as plt
from collections import Counter
def bernoulli_trial(p):
return 1 if random.random() < p else 0
def binomial(n, p):
return sum(bernoulli_trial(p) for _ in range(n))
def make_hist(p, n, num_points):
data = [binomial(n, p) for _ in range(num_points)]
histogram = Counter(data)
plt.bar([x-0.4 for x in histogram.keys()],
[v / num_points for v in histogram.values()],
0.8,
color='0.75')
mu = p * n
sigma = math.sqrt(n * p * (1-p))
# use a line chart to show the normal approximation
xs = range(min(data), max(data) + 1)
ys = [normal_cdf(i+0.5, mu, sigma) - normal_cdf(i-0.5, mu, sigma) for i in xs]
plt.plot(xs, ys)
plt.title('Binomial Distribution vs. Normal Approximation')
plt.show()
make_hist(0.75, 100, 10000)
My question is, in this line:
[normal_cdf(i+0.5, mu, sigma) - normal_cdf(i-0.5, mu, sigma) for i in xs]
why did the author use +0.5 and -0.5? Is there a specific reason for that?
Not sure if anyone has encountered this question.
Thank you in advance!
A:
In xs variable you have a list of X coordinates with step 1, e.g. [5,6,7,8,9,10]. In ys variable you need to get corresponding Y coordinates and normal_cdf(i+0.5, mu, sigma) - normal_cdf(i-0.5, mu, sigma) in your code is an integral from i-0.5 to i+0.5, i.e. with the width of (i+0.5) - (i-0.5) = 1, the same step.
More understandable code would look like this:
step = 1.0
xs = range(min(data), max(data) + 1, step)
ys = [normal_cdf(i + step / 2, mu, sigma) - normal_cdf(i - step / 2, mu, sigma) for i in xs]
| {
"pile_set_name": "StackExchange"
} |
Q:
What is $\int f$ if $f$ is not Riemann integrable in the reverse direction of this theorem
Consider following theorem:
I wanted to prove the $\Longleftarrow$ direction when I run into trouble. I do not understand the expression $|R(f,P)-A|$. Here $R(f,P)$ is a Riemann sum with respect to a tagged partition $P$. But at this point we do not know that $f$ is Riemann integrable, it is what we want to show. But $A=\int_a^b f$ is the Riemann integral of $f$. (It is defined to be the sup of the upper sums (or inf of the lower sums, they are equal if $f$ is Riemann integrable)).
How to interpret $A=\int_a^b f$ if $f$ is not know to be Riemann integrable?
A:
The author means "...iff there exists a number $A$ with the following property: ...". If such number exists, we denote $A=\displaystyle\int_a^b f$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Stack Overflow, Google, or Wikipedia?
Possible Duplicate:
Is it appropriate to ask questions on Stack Overflow without prior research?
I've asked a questions on stackoverflow that are closed almost immediately and instead referred to either a Wikipedia article or told to search Google, neither of which answered my question.
Are the higher-ups at stack overflow trying to reduce traffic?
It seems to me like even if the answer could be found on Wikipedia, it would still make sense to keep it open here, since they are separate sites. I rather post something here, which gets seen by more programmers in-the-know, than on Wikipedia, which seems to have been becoming more of a joke.
Regardless, I'd like to get my answer from one place. So which do you recommend as the best source for programming/hardware-related questions? Google, Wikipedia, or here?
A:
I looked at your previous questions, and one was closed because there was a previous question covering it, and the other was migrated to superuser, where you got several answers.
The "higher-ups" at stackoverflow are just users who have been around long enough to have enough rep points to do some actions, like voting to close/migrate questions. They are not trying to reduce traffic, but actually the opposite. By closing duplicate questions and moving off-topic questions the signal to noise ratio is kept up, making it easier to find actual information on the site.
If you want answers to both programming and hardware questions, you can't use only stackoverflow, as that is intended for programming related questions. Google itself doesn't contain any information, so of your three choises, only Wikipedia is left.
As Wikipedia covers pretty much everything, you will not find any in-depth answers to very specific questions. For programming related questions you will find definitions for various concepts, but no answers to specific programming problems, like the ones stackoverflow is full of.
So, don't try to find a single source for all answers, you will not get good answers that way.
A:
Are the higher-ups at stack overflow trying to reduce traffic?
Were your questions closed by higher-ups, or were they closed - as almost every closed question on SO is - by five normal users who felt your questions were off-topic?
So which do you recommend as the best source for programming/hardware-related questions? Google, Wikipedia, or here?
For your two questions on SO - essentially "what is a quantum computer" and "what is HTML5" - I'd go to Google or Wikipedia, because the answers are available there, instantly and with references. Those questions have been answered here already, and having people repeat those straight-forward answers ad nauseum wastes everyone's time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Form validation not running onsubmit
I am trying to run a form validation on an HTML form to make sure the person has filled out the two fields. I put together a JSFiddle here:
http://jsfiddle.net/yCqqj/
It has worked previously for me and I don't know what's going on now. I made a JSFiddle to pull it out of my site to make sure nothing else was conflicting with it but I'm realizing now that it's something in the code. The two fields are name "emailaddress" and "Name" respectively and it looks like I'm checking their values correctly. Basically, I'm looking for an alert (and NOT a submittal of the form) if they've left either field blank. Thanks for helping me track down the problem. I appreciate it.
function ValidateForm(){
var emailID=document.MailingList.emailaddress
var nameID=document.MailingList.Name
if ((nameID.value==null)||(nameID.value=="")){
alert("Please Enter your Name");
nameID.focus();
return false;
}
if ((emailID.value==null)||(emailID.value=="")){
alert("Please Enter your Email ID");
emailID.focus();
return false;
}
}
Even though there is not return true, the form still submits.
A:
the problem is that you haven't defined ValidateForm in the Head section.
i have edited the jsfiddle.check demo.
| {
"pile_set_name": "StackExchange"
} |
Q:
Facing trouble with viewing push notification in iOS 10 Swift 3
My app has 2 types of initial state.
Login
After Login which contains Dashboard & other stuff.
My app working fine when switching view from Appdelegate like that
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let userDataExist = CommonUserFunction.isUserDataExist() as Bool
if userDataExist == true {
let homeViewController = self.window?.rootViewController?.storyboard?.instantiateViewController(withIdentifier: "HomeView") as? HomeViewController
let navigationController = UINavigationController()
navigationController.viewControllers = [homeViewController!]
self.window!.rootViewController = navigationController
}
else{
let loginController = self.window?.rootViewController?.storyboard?.instantiateViewController(withIdentifier: "LoginView") as? LoginController
let navigationController = UINavigationController()
navigationController.viewControllers = [loginController!]
self.window!.rootViewController = navigationController
}
self.window?.makeKeyAndVisible()
return true
}
I am facing problem when i have to handle push notification. I received push notification in iOS 10 in these methods
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
print("Handle push from foreground")
// custom code to handle push while app is in the foreground
print(notification.request.content.userInfo)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// custom code to handle push while app is in the foreground
print(response.notification.request.content.userInfo)
}
When i tapped notification from notification tray these two methods are fired whereas app is foreground or background. After tapping the notification i must show a details page. I tried to set the details page like that which i did before in didFinishLaunchingWithOptions method
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let pushResponse = response.notification.request.content.userInfo as NSDictionary
let rtype = pushResponse.object(forKey: "rtype") as? String
let rid = pushResponse.object(forKey: "rid") as? String
if rtype != nil {
if rtype == "5" {
if rid != nil {
let noticeDetailsViewController = self.storyboard?.instantiateViewController(withIdentifier: "NoticeDetailsView") as? NoticeDetailsController
noticeDetailsViewController!.id = rtype!
noticeDetailsViewController?.fromPush = true
let navigationController = UINavigationController()
navigationController.viewControllers = [noticeDetailsViewController!]
self.window!.rootViewController = navigationController
}
}
}
}
Every time i do that app crashes. How to overcome this. Please help. Thanks in advance.
A:
Finally solved this using Observer design pattern.
When app is in Background & tapped the the notification in notification tray then post the notification from here like that
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let pushResponse = response.notification.request.content.userInfo as NSDictionary
let rtype = pushResponse.object(forKey: "rtype") as? String
let rid = pushResponse.object(forKey: "rid") as? String
if rtype != nil {
if rtype == "5" {
if rid != nil {
NotificationCenter.default.post(name: Notification.Name(rawValue: "getPush"), object: pushResponse)
}
}
}
}
To receive this notification init below code to your viewController
NotificationCenter.default.addObserver(self, selector: #selector(self.getPushResponse), name: NSNotification.Name(rawValue: "getPush"), object: nil)
Get response from the below code
func getPushResponse(_ notification: Notification){
if let info = notification.object as? NSDictionary {
let rid = info.object(forKey: "rid") as? String
let noticeDetailsViewController = self.storyboard?.instantiateViewController(withIdentifier: "NoticeDetailsView") as? NoticeDetailsController
noticeDetailsViewController?.id = rid!
noticeDetailsViewController?.fromPush = true
self.navigationController?.pushViewController(noticeDetailsViewController!, animated: true)
}
}
Don't forget to Remove Observer from the viewController like that
deinit {
NotificationCenter.default.removeObserver(self)
}
If app has no instance in background & tapped the notification in tray then how to show the notification which has no instance. This can be handle like that in AppDelegate
let prefs: UserDefaults = UserDefaults.standard
if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
prefs.set(remoteNotification as! [AnyHashable: Any], forKey: "startUpPush")
prefs.synchronize()
}
Check your initial viewController is this key exist or not like that
let prefs:UserDefaults = UserDefaults.standard
if prefs.value(forKey: "startUpPush") != nil {
let pushResponse = prefs.object(forKey: "startUpPush") as! NSDictionary
NotificationCenter.default.post(name: Notification.Name(rawValue: "getPush"), object: pushResponse)
}
Don't forget to remove this key after showing the detailsController like that
if fromPush == true {
let prefs: UserDefaults = UserDefaults.standard
if prefs.value(forKey: "startUpPush") != nil {
prefs.removeObject(forKey: "startUpPush")
prefs.synchronize()
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
element.setCustomValidity( num message )
In Darts API, the method
element.setCustomValidity(num message)
has a number as the argument. I was expecting the type of the message to be a String. Is this an error?
A:
I created an issue https://github.com/Polymer/core-input/issues/41
The Dart element uses information from JS comments to generate type annotations and the comment in the JavaScript element contains the wrong type information.
As a workaround you can call the JS function directly:
void setCustomValidity(CoreInput inp, String message) {
inp.jsElement.callMethod('setCustomValidity', ["Give me more!"]);
}
see also Taking total control of PaperInput validation
| {
"pile_set_name": "StackExchange"
} |
Q:
Use of OGNL expression to access request headers in Tiles 2
I'm using Tiles 2.2.2 in my application (Struts 2.2.3). I want to use expressions in order to modify my screen composition depending on some attribute in the request. Basically, I would like to change the extends of a screen depending if there is a header in the request with name "x-requested-with" and the value is "XMLHttpRequest". Is it possible to do that? I've tried to do a simple example with an attribute:
<put-attribute name="test" expression="OGNL:requestScope" cascade="true"/>
I've tried different expressions like OGNL:%{#request.headers.referer}, OGNL:#request.headers.referer, OGNL:requestScope.headers.referer , etc. But it always returns null. I haven't found any documentation on how the OGNL expressions works on Tiles, so I'm working based on how I would do it with Struts. But it doesn't seem to work.
Any ideas?
A:
How are you initializing Tiles? If you're using the StrutsTilesListener, OGNL expressions in tiles.xml won't be evaluated.
In my Struts2 app, I am using the org.apache.tiles.extras.complete.CompleteAutoloadTilesListener in web.xml and OGNL evaluation is working:
<listener>
<listener-class>org.apache.tiles.extras.complete.CompleteAutoloadTilesListener</listener-class>
</listener>
In my case, I have a custom TilesResult with a property called 'content':
<put-attribute name="content" expression="OGNL:content" />
| {
"pile_set_name": "StackExchange"
} |
Q:
Growth rate of signed sum of divisor function
Let $d(n)$ be the number of divisors function, i.e., $d(n)=\sum_{k|n} 1$ of the positive integer $n$. I know about some of the "gross" averages for this function, such as the estimate
$$
\sum_{n\leq x} d(n)=x \log x + (2 \gamma -1) x +{\cal O}(\sqrt{x})
$$
as well as its variability, e.g., the lim sup of the fraction
$$
\frac{\log d(n)}{\log n/\log \log n}
$$
is $\log 2$ while the lim inf of $d(n)$ is $2$, achieved whenever $n$ is prime.
How much is known about the statistics of $d(n)$? In particular, if we let $N$ grow to infinity, is there any way
to bound a sum of the form
$$
\left| \sum_{n=1}^N \varepsilon_n d(n) \right|
$$
from below for all or almost all $(\varepsilon_1,\cdots,\varepsilon_N)\in \{\pm 1\}^N$?
A:
Studying your sum
$$
X(\varepsilon) = \sum_{n=1}^N \varepsilon_n d(n)
$$
for almost all $\varepsilon = (\varepsilon_1,\dots,\varepsilon_N) \in \{\pm1\}^N$ is basically equivalent to a probability problem: assign each such $\varepsilon$ a probability of $2^{-N}$. Then $X(\varepsilon)$ is a random variable with expectation $0$ and variance
$$
\sigma^2(X(\varepsilon)) = \sum_{n=1}^N d(n)^2 \sim \frac{N(\log N)^3}{\pi^2}.
$$
Therefore for the vast majority of $\varepsilon$, your sum will have order of magnitude $\sqrt N (\log N)^{3/2}$.
As for bounding from below, I claim that for sufficiently large $N$ the sum can always be made to be at most $2$ in absolute value. Choose $\varepsilon$ at random; then almost surely your sum $X(\varepsilon)$ will be less than say $N^{2/3}$ in absolute value. Without loss of generality, let's say the sum is positive. Also, almost surely at least a third of the primes $p$ will have $\varepsilon_p = 1$. Since "a third of the primes" has order of magnitude $N/\log N$, much larger than $N^{2/3}$, we can choose $X(\varepsilon)/4$ (rounded) primes $p$ for which $\varepsilon_p = 1$ and change them to $\varepsilon_p = -1$. The resulting $X(\varepsilon)$ will then have absolute value at most 2.
Note that the perfect squares are the only integers for which $d(n)$ is odd. A similar argument shows that almost surely there are perfect squares with $\varepsilon_{m^2} = 1$ and $\varepsilon_{n^2} = -1$. These can be used to adjust the sum so that it equals either 0 or 1, depending on the parity of the integer $X(1) = \sum_{n=1}^N d(n)$. (And note, by the same characterization of the integers with $d(n)$ odd, that the parity of $X(1)$ is exactly the parity of $\lfloor \sqrt N \rfloor$ !)
A:
An answer to Greg's comment. It's true about the parity. However the sum can take on any value between $-\sum_{n=1}^N d(n)$ to $\sum_{n=1}^N d(n)$ if it has the right parity. It's because if $k$ is any number between $0$ and $D(N)=\sum_{n=1}^N d(n),$ then there exists some subset $A_{k,N}$ of $\{1,\dots, N\}$ such that $\sum_{n\in A_{k,N}} d(n)=k.$
It follows from the relatively easy fact that $2D(N)+1 \geq D(N+1)$ or equivalently $D(N)+1 \geq d(n+1).$ Then the result follows by induction.
It's true for $N=1$ since $A_{0,1}$ the empty set and $A_{1,1}={1}.$
Suppose it's true for $N$, then if $0\le k \le D(N)$, let $A_{k,N+1}=A_{k,N}$
If $D(N+1)-D(N) \le k \le D(N+1),$ then let $A_{k,N+1}=A_{K,N} \cup N+1,$ where $K=D(N+1)-k.$
$2D(N)+1 \geq D(N+1),$ this covers all $k$ between $0$ and $D(N+1)$ finishing the induction.
Note that this idea shows the same can be done for any arithmetic function $f: \mathbb{N} \to \mathbb{N}$ with the same inequality $2F(N)+1 \geq F(N+1).$ Examples include the Euler totient function $\phi,$ the Carmichael lambda function $\lambda$ and many others.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using JSONP over SSL
If I want to send information to a server using SSL, presumably that's sensitive information. If I use JSONP to send it to a different domain, that sensitive information must go in the querystring. At a minimum, it seems that this information would be logged by the web server, thus exposing sensitive information. Does using JSONP over SSL make any sense?
A:
For returning data, sure it can make sense, for requesting data though...yes you're going to expose data in the query string that can be logged at several places along the way.
Using SSL to POST the data through your own domain(and you proxying to the other) seems like a better option, if it's possible, so you're not providing data using GET at any point.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access to list of all ansible extra-vars, passed from the cli? (Variable of variable)
I have a problem with accessing to extra-vars from my playbook with variable-of-variable way.
For example, I created a group_vars/mygroup.yml file with content:
MYVAR=AAAA
Then I call command and pass extra-vars:
ansible-playbook -i test playbook.yml --extra-vars "MYVAR=BBB"
I need to get actual value of MYVAR from list of exists variables. I tried to do this:
- debug: var=hostvars[inventory_hostname]['MYVAR']
...I getting
TASK: [test | debug var=AAA] *******************************
ok: [192.168.1.21] => {
"var": {
"AAA": "BBB"
}
}
TASK: [test | debug var=hostvars[inventory_hostname]['AAA']] ***
ok: [192.168.1.21] => {
"var": {
"hostvars[inventory_hostname]['AAA']": "AAA" // ← THIS IS THE PROBLEM
}
}
How I can get actual value of AAA, that passed from cli?
Please, don't say to me to just use AAA directly by name, because this is a part of more complex logic, when I have a list of registered variables and I can't use their names.
hostvars[inventory_hostname][**item**] ← variable of variable
Thank you in advance.
Update: OR maybe Ansible already supports something like this?:
VARNAME: APP_ENV
APP_ENV: blabla
debug: var=${VARNAME} // blabla expected
Update 2: The github gist with problem explanation.
A:
Now, after ansible 2.0 was released, the problem from gist example is gone:
ansible-playbook -i localhost.ini test.yml --extra-vars="AAA=BBB"
TASK [debug] *****************
ok: [localhost] => (item=AAA) => {
"item": "AAA",
"msg": "BBB"
}
So, like @chrism said, it was a bug.
| {
"pile_set_name": "StackExchange"
} |
Q:
Change logback output
I'm trying to change logback output from my code.
I develop a web service and I would like to log some header information the service receive from the request.
I have this config :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE XML>
<configuration debug="true" scan="true" scanPeriod="1 hour">
<!-- sends logs to logback-beagle -->
<consolePlugin />
<timestamp key="freqLogFile" datePattern="yyyyMMdd" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d [%thread] %level %class\(%method\) %line - %m%n</Pattern>
</layout>
</appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d [%thread] %level %class\(%method\) %line - %m%n</Pattern>
</layout>
<file>logs/webservice.logs_${freqLogFile}.log</file>
</appender>
</configuration>
Is there a way to change the pattern to include these header information ?
A:
You can put those headers into the MDC, then use them in the pattern.
In your service:
MDC.put("header1", header1);
MDC.put("header2", header2);
In your logback config:
<Pattern>%d [%thread] %level %class\(%method\) %line - %X{header1} %X{header2} %m%n</Pattern>
More info on the MDC and how to use it can be found in the documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
GNOME: supend on laptop lid close no longer works since 19.10 upgrade
I'm quite positive that this used to work flawlessly in 19.04 (and past releases) but no longer does after a release-upgrade to 19.10 (kernel 5.3.0-24, ThinkPad X1 Carbon gen 5 in case this matters).
I have the corresponding switch set in GNOME-Tweaks and have also attempted to manually edit /etc/systemd/logind.conf as suggested here, namely uncomment and adjust the following lines, followed by a reboot:
$ grep -v '^#' /etc/systemd/logind.conf
[Login]
HandleLidSwitch=suspend
HandleLidSwitchExternalPower=suspend
HandleLidSwitchDocked=suspend
LidSwitchIgnoreInhibited=yes
(strictly speaking, only the first one ought to be required but, just in case, I also added lines 2 & 3, as well as #4 for good measure...
Looking at the output of systemctl status systemd-logind, I see the following:
Dec 17 17:56:50 x1c5 systemd-logind[8959]: Lid closed.
Dec 17 17:57:03 x1c5 systemd-logind[8959]: Lid opened.
So the lid events are correctly detected. To rule out any issue with the suspend process itself, I have also set my power button to suspend in Settings->Power->Suspend & Power Button, for testing purposes. Pressing the power button now results in this in the output of systemctl status systemd-logind (after a successful suspend-resume cycle):
Dec 17 18:13:58 x1c5 systemd-logind[8959]: Power key pressed.
Dec 17 18:14:28 x1c5 systemd-logind[8959]: Delay lock is active (UID 121/gdm, PID 9215/gsd-power) but inhibitor timeout is reached.
Dec 17 18:14:39 x1c5 systemd-logind[8959]: Operation 'sleep' finished.
Bottom line: lid events are detected correctly and suspend works flawlessly - but not on lid close...
Any idea how I can get the suspend on lid-close feature back to life? I can of course use the workaround with the power button but it's a little too easy to forget and result in laptop overheating in bag etc...
--- edited to add ---
Got a little further courtesy of this ticket, although the issue isn't the exactly as described. Here's a smoking gun:
$ systemd-inhibit --list --mode=block
WHO UID USER PID COMM WHAT WHY MODE
gdm 121 gdm 2231 gsd-power handle-lid-switch External monitor attached or configuration changed recently block
gdm 121 gdm 2252 gsd-media-keys handle-power-key:handle-suspend-key:handle-hibernate-key GNOME handling keypresses block
user 1000 user 3017 gsd-media-keys handle-power-key:handle-suspend-key:handle-hibernate-key GNOME handling keypresses block
This suggests that the lid close action is being blocked because "External monitor attached or configuration changed recently". I do connect my laptop to a monitor using a USB-C cable but as I write this, it's been undocked and running on batteries for nearly 3 hours (GNOME settings only shows my laptop display as available). However it looks like systemd or whichever component is responsible for this still incorrectly believes the external display is attached and - per the ticket - suspend isn't supported by GNOME in such scenarios...
Interestingly the gsd-power process (PID 2231) is owned by gdm rather than my UID. Killing it restores the suspend-on-lid-close functionality. Need to figure out why this process exists... When actually connected to external display, systemd-inhibit --list --mode=block reports a 2nd gsd-power process owned by the interactive user; which appears correct and sufficient.
A:
Per investigations at the end of the question, the issue appears to be caused by GDM running a redundant gsd-power process. This can simply be killed as soon as you log in. Here's how I've done it:
Create a kill script as follows:
script=~/bin/kill_gdm_gsd-power.sh
cat > $script << EOF
#!/bin/sh
sudo pkill -u gdm gsd-power
EOF
chmod 755 $script
Your account will need to be allowed to run sudo pkill without a password prompt (make sure you're comfortable with this). Run sudo visudo -f /etc/sudoers.d/NOPASSWD and enter the following
Cmnd_Alias PKILL = /usr/bin/pkill
user ALL=(ALL) NOPASSWD: PKILL
(replace user above with your own user id)
Open the GNOME startup apps applet (gnome-session-properties) and add an entry with your script, so it runs as soon as you log on.
Ideally we'd find a way to prevent gsd-power from starting up altogether but I found this non-trivial... Please chip in if you find a better way.
A slightly cleaner solution might be to cook a custom handle-lid-switch script per this solution but the script would primarily have to be installed for the gdm user and this may also not be trivial...
There might be some side-effects to killing gdm's gsd-power process, eg: if you log out and leave the laptop to the GDM greeting screen but I think this isn't a scenario many of us will run into.
| {
"pile_set_name": "StackExchange"
} |
Q:
limes of martingale given quadratic variation
Given a martingale $M_t$ with $M_0=0$ and $E[M_t^2]<\infty$. Let the
quadratic variation of $M_t$ be $[M]_t:=ln(1+t)$. Calculate $\limsup_{t\to\infty} \dfrac{M_t}{\sqrt{t}}$.
Does anyone have an approach for that? I thought of using Itô's formula but this didn't help.
A:
Let $\epsilon>0$, we define $$A_n=\{\max_{2^n\leq t\leq 2^{n+1}}\frac{|M_t|}{\sqrt{t}}>\epsilon\}$$
We have
$$A_n\subseteq{\{\exists t \in[2^{n},2^{n+1}] , |M_t|>\epsilon\sqrt{2^n} \}}$$,
Thus,
$$P(A_n) \leq P({\{\exists t \in[2^{n},2^{n+1}] , |M_t|>\epsilon\sqrt{2^n} \}})$$
or equivalently ,
$$P(A_n) \leq P({\max_{2^n\leq t\leq 2^{n+1}} |M_t|>\epsilon\sqrt{2^n} })$$
A that stage, you can apply the Doob inequality :
$$ P({\max_{2^n\leq t\leq 2^{n+1}} |M_t|>\epsilon\sqrt{2^n} })\leq\frac{E(M_{2^{n+1}}^2)}{\epsilon^22^n}$$
We have that $$M_t^2=U_t+log(1+t)$$ where $U_t$ is a martingale,
therefore
$$ P(A_n)\leq\frac{log(1+2^{n+1})}{\epsilon^22^n}$$
The Borel-Cantelli lemma concludes that
$$P(\limsup_{t \to \infty}\frac{|M_t|}{\sqrt{t}} \leq \epsilon)=1 $$
Moreover,
$$\{\frac{|M_t|}{\sqrt{t}}=0\}=\cap_{k\geq1}\{\limsup_{t \to \infty}\frac{|M_t|}{\sqrt{t}}\leq\frac{1}{k}\}$$
You can conclude
| {
"pile_set_name": "StackExchange"
} |
Q:
How to de-noise raw sound data
What techniques/algorithms can I use to remove noise from a raw recording of sound (voice)?
The purpose is to get a smoother graph (removing the "jaggedness"). What I have tried was to average-out small deviations by using the surrounding two values to either side, but ended up with distorted sound. What better way is there to "smooth-out" the graph?
A:
For what you intend to do, a low-pass filter is the way to go. Your statement about filtering frequencies vs filtering amplitudes is incorrect. Your signal contains many components at many frequencies, the amplitude of which varies in time, and the high frequency components are those causing the "jaggedness" and you want to get rid of them. Not sure why you say your signal is "constant frequency" - maybe you are getting confused by the sample rate?
What you have tried (averaging) is indeed a special case of low-pass filtering, but one with a frequency response far from being ideal. You should try a properly designed IIR or FIR filter. In particular, the FIR filter is not very different from what you tried - this is just a weighted combination of the samples neighboring each sample. But the choice of the coefficients is important and ensures that only unwanted components are eliminated. Note that an FFT is not the way to go. This question crops up here quite frequently under different forms, but in short - FFT, messing with coefficients, IFFT - is a bad idea.
By design, the output of a moving average filter (what you implemented) has less energy than the input. It is thus impossible for a moving average filter to cause distortion. If the input signal is in the [-1, 1] range, there is no way for an averaging filter to yield values outside this range. The "distorted sound" you observed was probably due to an implementation error on your side (overflow / clipping of integer values, signed values treated as unsigned value, or maybe incorrect in-place processing)...
EDIT: one thing worth mentioning is that there are situations in which a speech signal actually has high frequency components (appears "jagged", is noisy) - for example during a sss or shhh ; and removing those with a low-pass filter will affect its brilliance. Ideally, you'll want your low-pass filter to be active only when you detect that your speech signal is voiced - and inhibit it when you detect an unvoiced, noisy consonant.
A:
Another interesting audio denoising technique exploits the fact that many sound recordings contain silent time intervals that contain only noise. Such sections can be chopped out of the recording to obtain a noise spectrum and then spectral gating can be applied to suppress noise. Take a look at the following links for detailed discussion on this technique:
Noise gate: http://en.wikipedia.org/wiki/Noise_gate
Noise removal in Audacity (an open source audio editing tool): http://wiki.audacityteam.org/wiki/Noise_Removal
Of course, this method rests on the assumption that the ``same noise source'' persists throughout the duration of the audio.
| {
"pile_set_name": "StackExchange"
} |
Q:
able to create thumbnails with PIL but my multiprocessing code does not create PIL thumbnails
I am trying to learn how to use multiprocessing with PIL using python 2.7 on a 64 bit windows 7 pc.
I can successfully create (and save) the thumbnails using PIL to the desired location on my pc. When I try to implement multiprocessing, my code does not create any thumbnails and it loops through the files about twice as fast. I have about 9,000 image files in multiple directories and sub directories (I have no control over the file names not directory structure)
here is the basis of the code that works.
from multiprocessing import Pool, freeze_support
import os
from fnmatch import fnmatch
from timeit import default_timer as timer
from PIL import Image, ImageFile
starttime = timer()
SIZE = (125, 125)
SAVE_DIRECTORY = r'c:\path\to\thumbs'
PATH = r'c:\path\to\directories\with\photos
def enumeratepaths(path):
""" returns the path of all files in a directory recursively"""
def create_thumbnail(_filename):
try:
ImageFile.LOAD_TRUNCATED_IMAGES = True
im = Image.open(_filename)
im.thumbnail(SIZE, Image.ANTIALIAS)
base, fname = os.path.split(_filename)
outfile = os.path.split(_filename)[1] + ".thumb.jpg"
save_path = os.path.join(SAVE_DIRECTORY, outfile)
im.save(save_path, "jpeg")
except IOError:
print " cannot create thumbnail for ... ",_filename
if __name__ == '__main__':
freeze_support() # need this in windows; no effect in *nix
for _path in enumeratepaths(PATH):
if fnmatch(_path, "*.jpg"):
create_thumbnail(_path)
# pool = Pool()
# pool.map(create_thumbnail, _path)
# pool.close()
# pool.join()
The code works and creates the 9,000 thumbnails in the desired location. When I comment out create_thumbnail(_path) and un-comment the multiprocessing code, the code iterates thru the directory structure twice as fast but does not create any thumbnails. How would I adjust the multiprocessing code to make it work?
A:
the code "pool.map(create_thumbnail, _path)" needs to be pool.map(create_thumbnail(_path), _path) to create the thumbnails
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Web Fonts in Custom SharePoint MasterPage HTML
I have to use a web font that from another website and the URL of that is at the below.
<a href="http://fast.fonts.com/cssapi/b0549848-32a3-4c8e-a13e-810394960364.css">http://fast.fonts.com/cssapi/b0549848-32a3-4c8e-a13e-810394960364.css</a>
To add this web font I have used the following statement in my MasterPage's HTML file.
<link href="http://fast.fonts.com/cssapi/b0549848-32a3-4c8e-a13e-810394960364.css" type="text/css" rel="stylesheet" />
My MasterPage is a custom one. I tried the following statement but it didnot work because when I tried to save the MasterPages's HTML file an error occurs saying the file should have the .aspx extension.
<SharePoint:CssRegistration Name="<%$SPrl:~sitecollection/Style Library/MyCustomTheme/mycss.css%>" runat="server" After="corev15.css"/>
The problem I think the custom web font will be replaced by the default font in the default CSS file in the SharePoint Site.
So what can I do for to obstruct this problem? Please could someone help me solve this?
Thanks and regards,
Chiranthaka
A:
Actually SharePoint requires secure connections for external resources. So the URLmust start with https:// instead of http://.
I changed the URL from `
to
<link href="https://fast.fonts.com/cssapi/b0549848-32a3-4c8e-a13e-810394960364.css" type="text/css" rel="stylesheet" />
Thanks guys however you have replied me ASAP.
Regards,
Chiranthaka
| {
"pile_set_name": "StackExchange"
} |
Q:
Which ways exist to do the UI in Vaadin for two or more Entitys in the same view?
I have the following excel table printed on paper which represents an attendance list for one month which I should bring online.
In first column are all participant names.
The others columns will be will be checked if the person was present on the day or empty if not.
As column header will be the day of the month.
Backend is made with Spring Data/JPA
What options exist to do the UI in Vaadin?
The first impulse was for me the Vaadin grid, but if you look exactly is not possible because in grid is posible only one entity per grid.
As second possibility would be Polymer 3 with TemplateModel
Do you have other idea in which way to do that?
Thank you very much.
A:
You can just create a Grid of type person/user, and add columns for each event, example code below. Your classes probably differ, but hopefully you get the idea. Note that the code for actually creating the grid is only 8 lines.
You could also encapsulate all the data in a view mode class as Simon Martinelli suggested, e.g. EventGridModel that contains attendees, events, persons, and maybe some utility functions.
@Route
public class MainView extends VerticalLayout {
public MainView() {
Person[] persons = new Person[]{
new Person(0, "Foo", "Bar"),
new Person(1, "John", "Doe"),
new Person(2, "Scala", "JVM"),
new Person(3, "Jeht-Phuel", "Steelbeam"),
new Person(4, "Ilike", "Turtles")
};
Event[] events = new Event[] {
new Event(0, Arrays.asList(persons[0], persons[1], persons[2], persons[4]), LocalDate.of(2019, 9, 5)),
new Event(0, Arrays.asList(persons[0], persons[1], persons[2], persons[3]), LocalDate.of(2019, 9, 5)),
new Event(0, Arrays.asList(persons[1], persons[2], persons[3]), LocalDate.of(2019, 9, 5)),
new Event(0, Arrays.asList(persons[0], persons[2], persons[3]), LocalDate.of(2019, 9, 5)),
new Event(0, Arrays.asList(persons[1], persons[2], persons[3], persons[4]), LocalDate.of(2019, 9, 5)),
};
Grid<Person> grid = new Grid<>();
grid.addColumn(person -> person.getFirstName() + " " + person.getLastName()).setHeader("Name");
for (Event event: events) {
grid.addColumn(person -> event.getAttendees().contains(person) ? "X" : "")
.setHeader(event.getDate().toString());
}
grid.setItems(persons);
add(grid);
}
class Person {
private final Integer id;
private final String firstName;
private final String lastName;
Person(Integer id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public Integer getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public boolean equals(Object other) {
return other instanceof Person && Objects.equals(((Person) other).getId(), id);
}
}
class Event {
private final Integer id;
private final List<Person> attendees;
private final LocalDate date;
Event(Integer id, List<Person> attendees, LocalDate date) {
this.id = id;
this.attendees = attendees;
this.date = date;
}
public Integer getId() {
return id;
}
public List<Person> getAttendees() {
return attendees;
}
public LocalDate getDate() {
return date;
}
@Override
public boolean equals(Object other) {
return other instanceof Event && Objects.equals(((Event) other).getId(), id);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Get words and values Between Parentheses in Scala-Spark
here is my data :
doc1: (Does,1) (just,-1) (what,0) (was,1) (needed,1) (to,0) (charge,1) (the,0) (Macbook,1)
doc2: (Pro,1) (G4,-1) (13inch,0) (laptop,1)
doc3: (Only,1) (beef,0) (was,1) (it,0) (no,-1) (longer,0) (lights,-1) (up,0) (the,-1)
etc...
and i want to extract words and values and then store them in two separated matrices , matrix_1 is (docID words) and matrix_2 is (docID values) ;
A:
input.txt
=========
doc1: (Does,1) (just,-1) (what,0) (was,1) (needed,1) (to,0) (charge,1) (the,0) (Macbook,1)
doc2: (Pro,1) (G4,-1) (13inch,0) (laptop,1)
doc3: (Only,1) (beef,0) (was,1) (it,0) (no,-1) (longer,0) (lights,-1) (up,0) (the,-1)
val inputText = sc.textFile("input.txt")
var digested = input.map(line => line.split(":"))
.map(row => row(0) -> row(1).trim.split(" "))
.map(row => row._1 -> row._2.map(_.stripPrefix("(").stripSuffix(")").trim.split(",")))
var matrix_1 = digested.map(row => row._1 -> row._2.map( a => a(0)))
var matrix_2 = digested.map(row => row._1 -> row._2.map( a => a(1)))
gives:
List(
(doc1 -> Does,just,what,was,needed,to,charge,the,Macbook),
(doc2 -> Pro,G4,13inch,laptop),
(doc3 -> Only,beef,was,it,no,longer,lights,up,the)
)
List(
(doc1 -> 1,-1,0,1,1,0,1,0,1),
(doc2 -> 1,-1,0,1),
(doc3 -> 1,0,1,0,-1,0,-1,0,-1)
)
| {
"pile_set_name": "StackExchange"
} |
Q:
File ReadAllLines turns foreign language into gibberish (�)
I am creating a tool that replaces some text in a text file. My problem is that File ReadAllLines turns the Hebrew characters into Gibberish (weird question marks �)
Does anyone know why this is happening? Note that I do have a problem with Hebrew in games and such.. And in Notepad, I can't save Hebrew documents. I can write Hebrew letters but when I save it tells me there's a problem with that.
EDIT - Tried this, but it only turned the Hebrew into regular question marks and not "special" ones-
string[] lines = File.ReadAllLines(fullFilenameDir);
byte[] htmlBytes = Encoding.Convert(Encoding.ASCII, Encoding.Unicode, Encoding.ASCII.GetBytes(String.Join("\r\n", lines)));
char[] htmlChars = new char[Encoding.Unicode.GetCharCount(htmlBytes)];
Encoding.Unicode.GetChars(htmlBytes, 0, htmlBytes.Length, htmlChars, 0);
A:
Try using the Windows-1255 code page to get the encoder.
var myLines = File.ReadAllLines(@"C:\MyFile.txt", Encoding.GetEncoding("Windows-1255"));
| {
"pile_set_name": "StackExchange"
} |
Q:
How to capture n groups in regex so i can substitute them in js
I have following string:
[{par1}, {par2}, ..., {parN}]
And I am capturing this with following regex:
(\{\S*\})
This works fine, and captures in groups my params: $1 = par1, $2 = par2... etc
My question is, I want to do some operation in javascript with all those groups.
I know how to do it for 1 group.
str.replace(new RegExp((\{\S*\}),g),'whatever'+$1) //Probably need to add more escape characters
My question is how to replace $1 to 'whatever+'$1, $2 to 'whatever'+$2... etc
i.e
[{par1},{par2}] ==> [mypar1,mypar2]
EDIT
To explain what i want to do more detailed with parameters:
From [{par1},{par2}] I need to extract par1 and par2, so i can call a function with them, which will return different values:
function translate(par) {
//return different things for every parameter
}
//so finally will be like:
str.replace(new RegExp((\{\S*\}),g),translate($1))
A:
Use callback function as a second argument of String.replace function:
var str = '[{par1}, {par2}, ..., {parN}]',
prefix = 'whatever',
replaced = str.replace(/\{(\S+)\}/g, function (p0, p1) {
// ... some other logic
return prefix + p1;
});
console.log(replaced); // "[whateverpar1, whateverpar2, ..., whateverparN]"
| {
"pile_set_name": "StackExchange"
} |
Q:
regex for non alphabets or nothing
I want to identify "how" from python strings.
string1
how to find
it is a show
okay how to
Used:
df[df['string1'].str.contains("how",case=False)]
Output coming:
string1
how to find
it is a show
okay how to
As 'show' contains 'how'
output needed:
string1
how to find
okay how to
after that i used
df[df['string1'].str.contains(r"\Whow",case=False)]
but output i got is:
string1
okay how to
which is again worng.
regex '\W' is not including nothing. how to achieve this?
A:
You need boundaries (\b) for the pattern, otherwise it will also match substrings contained in words:
df[df['string1'].str.contains(r"\bhow\b",case=False)]
string1
1 how to find
3 okay how to
dtype: object
| {
"pile_set_name": "StackExchange"
} |
Q:
Dúvidas Propriedades Popover Bootstrap
Estou criando um popover com bootstrap, ele aparece assim que eu passo o mouse na tag html, mas quando vou tentar clicar em cima do popover ele some, tem alguma propriedade que quando passo o mouse em cima deixar ele aberto para conseguir click em um link no popover por exemplo?
var criarPopoverCompra = function (cupomFiscal) {
$('#cupom' + cupomFiscal).popover({
html: true,
placement: "bottom",
trigger: "hover",
title: '',
content: 'Clique no registro para voltar'
});
}
A:
Certo, isso ocorre porque você esta utilizando trigger como hover.
De uma olhada na documentação do popover https://getbootstrap.com/docs/4.0/components/popovers
Eu fiz um workaround aqui bem simples, caso queira seguir ele, de uma melhorada no código, abstraia para uma função e etc.
$(() => {
const popover = $('#myPopover');
popover.popover({
html: true,
placement: "bottom",
trigger: "manual",
title: '',
content: 'Clique <a href="#" data-popover="myPopover" class="close-popover">aqui</a> para voltar'
});
popover.on('mouseover', () => popover.popover('show') );
popover.on('shown.bs.popover', (event) => {
const id = popover.attr('id');
$(`[data-popover=${id}].close-popover`).on('click', () => {
popover.popover('hide');
});
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<div class="container">
<button
id="myPopover"
type="button"
class="btn btn-secondary">
Popover
</button>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Jetty websocket class loading issue
I have implemented a basic websocket server in Jetty(Standalone mode).
MyWebSocketServlet.java
public class MyWebSocketServlet extends WebSocketServlet {
@Override
public void configure(WebSocketServletFactory webSocketServletFactory){
webSocketServletFactory.getPolicy().setIdleTimeout(1000 * 10 * 60);
webSocketServletFactory.setCreator(new MyWebSocketFactory());
}
}
MyWebSocketFactory.java
public class MyWebSocketFactory implements WebSocketCreator {
public Object createWebSocket(
ServletUpgradeRequest servletUpgradeRequest
, ServletUpgradeResponse servletUpgradeResponse) {
return new MyWebSocketListener();
}
}
MyWebSocketListener.java
public class MyWebSocketListener implements WebSocketListener {
private Session sessionInstance;
public void onWebSocketBinary(byte[] bytes, int i, int i1) {
ByteBuffer data = ByteBuffer.wrap(bytes, i, i1);
try {
sessionInstance.getRemote().sendBytes(data);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onWebSocketClose(int i, String s) {
}
public void onWebSocketConnect(Session session) {
sessionInstance = session;
}
public void onWebSocketError(Throwable throwable) {
throwable.printStackTrace(System.err);
}
public void onWebSocketText(String s) {
try {
sessionInstance.getRemote().sendString(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
metadata-complete="false"
version="3.1">
<servlet>
<servlet-name>WsEcho</servlet-name>
<servlet-class>org.test.sanket.MyWebSocketServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WsEcho</servlet-name>
<url-pattern>/echo/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>HttpEcho</servlet-name>
<servlet-class>org.test.sanket.MyHttpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HttpEcho</servlet-name>
<url-pattern>/httpecho/*</url-pattern>
</servlet-mapping>
</web-app>
Instead of using a Standalone Jetty if I use embedded jetty and programatically configure the server and add the Servlets then this sample runs fine.
But if I am packaging the same as a war, and then deploying the same in a standalone jetty instance I am having the following observation:
I am able to hit the HttpServlet , i.e. MyHttpServlet and receive a response
But when I try to hit the websocket servlet, i.e. MyWebSocketServlet, I am seeing the following error:
exception
java.lang.ClassCastException: org.eclipse.jetty.server.HttpConnection cannot be cast to org.eclipse.jetty.server.HttpConnection
at org.eclipse.jetty.websocket.server.WebSocketServerFactory.acceptWebSocket(WebSocketServerFactory.java:175)
at org.eclipse.jetty.websocket.server.WebSocketServerFactory.acceptWebSocket(WebSocketServerFactory.java:148)
at org.eclipse.jetty.websocket.servlet.WebSocketServlet.service(WebSocketServlet.java:151)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:751)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:566)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:578)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:221)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1111)
I did come across the following link:
Jetty - stand alone WebSocket server
From the above link it seems to be a class loading issue, because jetty websocket package is treated as system class package and shouldn't be loaded by the WebApp if already loaded by the system.
So as referenced in the above link, I looked into the details suggested at:
http://www.eclipse.org/jetty/documentation/9.2.10.v20150310/jetty-classloading.html
From this link, one of the ways to get around this issue is to call the org.eclipse.jetty.webapp.WebAppContext.setSystemClasses(String Array) or org.eclipse.jetty.webapp.WebAppContext.addSystemClass(String) to allow fine control over which classes are considered System classes.
So for being able to do that, I should be able to get an Instance of WebAppContext, when Jetty is initializing and add the WebSocket classes as system classes.
I tried searching for how one would be able to achieve the same but no luck so far ? Can anybody kindly point me to a reference implementation as to how this can be achieved ?
Java Version: OpenJDK 7(latest)
Jetty: 9.2.10.v20150310
Operating System: Ubuntu 14.04
Thanks in advance!
A:
If you have followed this link to setup the Jetty Standalone Instance, then you might have run the following command:
[/opt/web/mybase]# java -jar /opt/jetty/jetty-distribution-9.2.10.v20150310/start.jar --add-to-start=deploy,http,logging
If so, then when you try to hit the websocket servlet you will see the exception that you are noticing.
All you need to do is, instead of that command, you as well need to initialize the websocket module as shown below:
[/opt/web/mybase]# java -jar /opt/jetty/jetty-distribution-9.2.10.v20150310/start.jar --add-to-start=deploy,http,logging,websocket
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Redefining logging root logger
At my current project there are thousand of code lines which looks like this:
logging.info("bla-bla-bla")
I don't want to change all these lines, but I would change log behavior. My idea is changing root logger to other Experimental logger, which is configured by ini-file:
[loggers]
keys = Experimental
[formatter_detailed]
format = %(asctime)s:%(name)s:%(levelname)s %(module)s:%(lineno)d: %(message)s
[handler_logfile]
class = FileHandler
args = ('experimental.log', 'a')
formatter = detailed
[logger_Experimental]
level = DEBUG
qualname = Experimental
handlers = logfile
propagate = 0
Now setting the new root logger is done by this piece of code:
logging.config.fileConfig(path_to_logger_config)
logging.root = logging.getLogger('Experimental')
Is redefining of root logger safe? Maybe there is more convenient way?
I've tried to use google and looked through stackoverflow questions, but I didn't find the answer.
A:
You're advised not to redefine the root logger in the way you describe. In general you should only use the root logger directly for small scripts - for larger applications, best practice is to use
logger = logging.getLogger(__name__)
in each module where you use logging, and then make calls to logger.info() etc.
If all you want to do is to log to a file, why not just add a file handler to the root logger? You can do using e.g.
if __name__ == '__main__':
logging.basicConfig(filename='experimental.log', filemode='w')
main() # or whatever your main entry point is called
or via a configuration file.
Update: When I say "you're advised", I mean by me, here in this answer ;-) While you may not run into any problems in your scenario, it's not good practice to overwrite a module attribute which hasn't been designed to be overwritten. For example, the root logger is an instance of a different class (which is not part of the public API), and there are other references to it in the logging machinery which would still point to the old value. Either of these facts could lead to hard-to-debug problems. Since the logging package allows a number of ways of achieving what you seem to want (seemingly, logging to a file rather than the console), then you should use those mechanisms that have been provided.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can mobilesubstrate hook this?
I want to hook a function called png_handle_IHDR declared locally in the ImageIO framework. I used MobileSafari as the filter. But while calling the original function, mobilesafari crashes. Upon inspection of the NSLog, i get this:
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: dlopen ImageIO success!
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: Zeroing of nlist success!
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: method name successfully assigned!
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: nlist SUCCESS! nlsetting..
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: nlset success! Hooking..
Jun 5 17:21:09 unknown MobileSafari[553] <Warning>: Png IHDR handle hooking!
Jun 5 17:21:09 unknown UIKitApplication:com.apple.mobilesafari[0x819][553] <Notice>: libpng error: Invalid IHDR chunk
Jun 5 17:21:09 unknown ReportCrash[554] <Notice>: Formulating crash report for process MobileSafari[553]
Jun 5 17:21:09 unknown com.apple.launchd[1] <Warning>: (UIKitApplication:com.apple.mobilesafari[0x819]) Job appears to have crashed: Abort trap: 6
Jun 5 17:21:09 unknown SpringBoard[530] <Warning>: Application 'Safari' exited abnormally with signal 6: Abort trap: 6
I immediately gathered that its very likely that I got the function prototype of the png_handle_IHDR wrong. The following is my code in the tweak:
#import <CoreFoundation/CoreFoundation.h>
#include <substrate.h>
#define ImageIO "/System/Library/Frameworks/ImageIO.framework/ImageIO"
void (*png_handle_IHDR)();
MSHook(void, png_handle_IHDR){
NSLog(@"Png IHDR handle hooking!\n");
_png_handle_IHDR(); //crashed here!!
NSLog(@"Png IHDR handle hooking finished!\n");
}
template <typename Type_>
static void nlset(Type_ &function, struct nlist *nl, size_t index) {
struct nlist &name(nl[index]);
uintptr_t value(name.n_value);
if ((name.n_desc & N_ARM_THUMB_DEF) != 0)
value |= 0x00000001;
function = reinterpret_cast<Type_>(value);
}
MSInitialize {
if (dlopen(ImageIO, RTLD_LAZY | RTLD_NOLOAD)!=NULL)
{
NSLog(@"dlopen ImageIO success!\n");
struct nlist nl[2];
bzero(&nl, sizeof(nl));
NSLog(@"Zeroing of nlist success!\n");
nl[0].n_un.n_name = (char*) "_png_handle_IHDR";
NSLog(@"method name successfully assigned!\n");
nlist(ImageIO,nl);
NSLog(@"nlist SUCCESS! nlsetting..\n");
nlset(png_handle_IHDR, nl, 0);
NSLog(@"nlset success! Hooking..\n");
MSHookFunction(png_handle_IHDR,MSHake(png_handle_IHDR));
}
}
My makefile is as such:
include theos/makefiles/common.mk
TWEAK_NAME = privateFunctionTest
privateFunctionTest_FILES = Tweak.xm
include $(THEOS_MAKE_PATH)/tweak.mk
privateFunctionTest_FRAMEWORKS = UIKit ImageIO CoreGraphics Foundation CoreFoundation
Edit: The question is, is knowing the original function arguments necessary for a successful hook? If yes, is getting the function prototype from the disassembly the only way? There is no definition of this in any of the SDK headers. Thanks.
A:
Ok, I decompiled the function and get the function prototype guessed by the decompiler. As long as the parameters and return type broadly matched e.g. bool : int, unsigned int : int, it still works without killing the execution. So this works:
int *png_handle_IHDR(int a1, int a2, int a3);
MSHook(int, png_handle_IHDR, int a1, int a2, int a3){
NSLog(@"png_handle_IHDR(%d,%d,%d)", a1,a2,a3);
int val = _png_handle_IHDR(a1,a2,a3);
NSLog(@"Png IHDR handle hooking finished, returning %d as result!", val);
return val;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring security with hibernate and mysql login
my project is based on Spring and Hibernate and now I have to implement authentication and profiling both from database and LDAP.
Given that I am new in spring I thought to start with implementation of authentication from database and then I'll think to profile and LDAP.
I followed this guide spring security annotation but when I call my web page it works like before, no authentication is called.
These are my configuration classes:
SpringSecurityInitializer
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
SpringMvcInitializer
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
SecurityConfig
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**")
.access("hasRole('ROLE_ADMIN')").and().formLogin()
.loginPage("/login").permitAll();//.failureUrl("/login?error")
//.usernameParameter("username")
//.passwordParameter("password")
//.and().logout().logoutSuccessUrl("/login?logout")
//.and().csrf()
//.and().exceptionHandling().accessDeniedPage("/403");
}
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
AppConfig
@EnableWebMvc
@Configuration
@PropertySource(value = { "classpath:application.properties" })
@ComponentScan({ "com.*" })
@EnableTransactionManagement
@Import({ SecurityConfig.class, SpringMvcInitializer.class})
@EnableJpaRepositories("com.repository")
public class AppConfig extends WebMvcConfigurerAdapter{
@Autowired
private Environment env;
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
// private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
/**
* This and the next methods are used to avoid exception while jackson mapping the entity, so fields are setted with null value
* unless use Hibernate.initialize
* @return
*/
public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
//Registering Hibernate4Module to support lazy objects
mapper.registerModule(new Hibernate4Module());
messageConverter.setObjectMapper(mapper);
return messageConverter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//Here we add our custom-configured HttpMessageConverter
converters.add(jacksonMessageConverter());
super.configureMessageConverters(converters);
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
// properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
properties.put("hibernate.enable_lazy_load_no_trans",true);
return properties;
}
@Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
ds.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
ds.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
ds.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return ds;
}
@Bean
public ServletContextTemplateResolver TemplateResolver(){
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/templates/pages/");
resolver.setSuffix(".html");
resolver.setTemplateMode("LEGACYHTML5");
resolver.setCacheable(false);
return resolver;
/*ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
return resolver;*/
}
@Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(TemplateResolver());
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setOrder(1);
resolver.setViewNames(new String[]{"*", "js/*", "template/*"});
return resolver;
}
/**
* Register multipartResolver for file upload
* @return
*/
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver=new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
return resolver;
}
/**
* Allow use of bootstrap
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("/static/");
}
/**
* Allow use of JPA
*/
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(env.
getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
entityManagerFactoryBean.setJpaProperties(getHibernateProperties());
return entityManagerFactoryBean;
}
}
MyUserDetailsServices
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.domain.UserRole;
import com.services.dbservices.tables.UserServices;
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserServices userServices;
@Transactional(readOnly=true)
@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
com.domain.User user = userServices.findById(username);
List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());
return buildUserForAuthentication(user, authorities);
}
// Converts com.users.model.User user to
// org.springframework.security.core.userdetails.User
private User buildUserForAuthentication(com.domain.User user, List<GrantedAuthority> authorities) {
return new User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities);
}
private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
// Build user's authorities
for (UserRole userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getUserRoleKeys().getRole()));
}
List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
return Result;
}
}
MainController
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class MainControllerImpl implements MainController{
@Override
@RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
public String mainPage(){
return "index";
}
@Override
@RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public String loginPage(){
return "login";
}
}
How you can see, I am only using annotations without any xml configuration file.
Where is the problem? If someone has a good guide for spring security with hibernate , Ldap with annotation I thank him.
at the moment, only to for testing, login.html
<div class="login-box-body">
<p class="login-box-msg">Sign in to start your session</p>
<form th:action="@{/login}" method="post">
<div th:if="${param.error}">
<script>
notifyMessage("Invalid username and password!", 'error');
</script>
</div>
<div th:if="${param.logout}">
<script>
notifyMessage("You have been logged out!", 'error');
</script>
</div>
<div class="form-group has-feedback">
<input id="username" name="username" type="text"
class="form-control" placeholder="Username"> <span
class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input id="password" name="password" type="password"
class="form-control" placeholder="Password"> <span
class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
<label> <input type="checkbox"> Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button id="signinButton" type="submit"
class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
<div class="social-auth-links text-center">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-social btn-facebook btn-flat"><i
class="fa fa-facebook"></i> Sign in using Facebook</a> <a href="#"
class="btn btn-block btn-social btn-google btn-flat"><i
class="fa fa-google-plus"></i> Sign in using Google+</a>
</div>
<!-- /.social-auth-links -->
<a href="#">I forgot my password</a><br> <a href="register.html"
class="text-center">Register a new membership</a>
</div>
A:
I had to add in AppConfig
@Bean
public SpringSecurityDialect springSecurityDialect() {
SpringSecurityDialect dialect = new SpringSecurityDialect();
return dialect;
}
and in SecurityConfig
@Override
public void configure(WebSecurity web) throws Exception {
web
//Spring Security ignores request to static resources such as CSS or JS files.
.ignoring()
.antMatchers("/static/**");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Как избавиться черной области при изменении размеров окна wpf
Я программно регулирую изменение размеров окна. И при уменьшении размеров появляется черная область, которая исчезает при нажатии на окно.
Получается, что окно фризиться при изменении размеров и за счет этого появляется черная область.
Вот код в котором изменяются размеры:
this.MinWidth = 510;
this.MaxWidth = 510;
this.MaxHeight = 315;
this.ResizeMode = ResizeMode.NoResize;
this.contentControl.Content = this.logInControl;
Я пробовала добавлять метод UpdateLayout() и InvalidateVisual(), но они не помогли. Подскажите, пожалуйста, как избавиться от этой черной области при смене размеров окна.
[Edit] Код разметки
<Window x:Class="LoginWindowForAras.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LoginWindowForAras"
xmlns:gif="http://wpfanimatedgif.codeplex.com"
mc:Ignorable="d"
Title="Log In" Height="315" Width="510" FontFamily="Time New Roman" FontSize="16"
MinWidth="510" MinHeight="315" Background="#FFD7D7D7" Icon="images/aras.png" KeyDown="MainWindow_KeyDown" ResizeMode="NoResize">
<Grid x:Name="mainGrid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="30"></ColumnDefinition>
</Grid.ColumnDefinitions>
<ContentControl x:Name="contentControl" Margin="0,0,0,0" Grid.Column="0"/>
<StackPanel Orientation="Vertical" Background="#FF646464" HorizontalAlignment="Right" Grid.Column="1">
</StackPanel>
</Grid>
</Window>
Содержание окна регултруется с помощью юзер контролов. Добавляю еще код изменения размеров для контрола с которого пользователь может перейти на контрол логина.
this.ResizeMode = ResizeMode.CanResize;
this.MinWidth = 575;
this.MaxWidth = Double.PositiveInfinity;
this.MaxHeight = Double.PositiveInfinity;
this.contentControl.Content = checkInControl;
Ситуация с черной областью возникает тогда, когда сделать ресайз - окно на весь экран, а затем перейти на контрол логина, нажав соответствующую кнопку на сайд баре.
[Edit] Скрины отображения ситуации:
Сначала пользователь логинится, окно имеет фиксированные размеры.
После успешной авторизации в окне меняется юзер контрол на Check in. Сначала оно имеет размеры, которые задаются в коде при переходе на этот контрол.
Но его размеры можна менять. И в случаии когда размеры окна сделать на весь экран и после этого нажать на кнопку Log out на сайт баре визникает ситуация з черной областью как на самом первом скрине в вопросе. Но если я растягиваю окно з контролом Check in'а просто стрелочками - проблем нету, окно при переходе на контрол логина появляется в центре и с такими размерами как нужно, без черных участков.
A:
this.SizeToContent = SizeToContent.WidthAndHeight;
- для Log in
this.SizeToContent = SizeToContent.Manual;
- для Check in
Но тогда есть проблема с тем, что окно появляется в левом углу, а не в центре экрана.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Shield of Faith stack?
Could shield of faith cast by multiple casters stack on one creature?
A:
No
Spells don't stack with themselves.
Combining Magical Effects:
The effects of different spells add together while the durations of those spells overlap. The effects of the same spell cast multiple times don't combine, however. Instead, the most potent effect — such as the highest bonus — from those castings applies while their durations overlap. (PHB 205)
A:
Short answer:
No.
Long Answer:
As long as an effect is active on the player, you can't stack it, casting it again would just extend the duration.
| {
"pile_set_name": "StackExchange"
} |
Q:
Что нужно дописать в js, чтобы зум получился как у амазона?
Необходимо реализовать зум изображения как у Амазона, когда по клику на картинку она открывается во весь размер и картинка скользит вверх/вниз за курсором, дополнительно, скролл "фокусируется" на месте клика, приближая конкретное место. Вот ссылка для примера. Кликните по большой картинке, затем еще раз, чтобы вызвать зум. Я знаю, что мне нужно реализовать коллизию, как у них, посредством вычитания высоты оригинального изображения из высоты контейнера использовать получившееся число как предел... но я не понимаю, как это необходимо применить? Вот моя реализация:
const imgUrl =
"https://images-na.ssl-images-amazon.com/images/I/71RxjEEZwkL._AC_SL1500_.jpg";
const trigger = document.getElementById("showImage");
trigger.addEventListener('click', () => {
buildModal()
})
/**
* Строим модал
*
*/
function buildModal() {
const modalBackdrop = document.createElement("div");
modalBackdrop.classList.add("media-viewer-backdrop");
const modal = document.createElement("div");
modal.classList.add("media-viewer");
modalBackdrop.appendChild(modal);
const modalMain = document.createElement("div");
modalMain.classList.add("media-viewer-main");
const modalContent = document.createElement("div");
modalContent.classList.add("media-viewer-main-content");
modalContent.appendChild(setActiveContent());
modalMain.appendChild(modalContent);
modal.appendChild(modalMain);
document.body.appendChild(modalBackdrop);
}
/**
* Установить контент
*
*/
function setActiveContent() {
const tabContent = document.createElement("div");
tabContent.classList.add("media-viewer-main-content-tab");
tabContent.appendChild(show());
return tabContent;
}
/**
* Показать модал
*
*/
function show() {
const images = document.createElement("div");
images.classList.add("media-viewer-main-content-viewer");
const bigImage = new Image();
bigImage.src = imgUrl;
bigImage.classList.add("media-viewer-main-content-viewer-image");
images.appendChild(bigImage);
toggleZoom(images);
return images;
}
/**
* Включить/выключить зум
*
*/
function toggleZoom(images) {
images.addEventListener("click", (e) => {
const target = e.target;
if ("IMG" !== target.tagName) {
return;
}
const zoomClass = "media-viewer-main-content-viewer-image__zoomed";
target.classList.toggle(zoomClass);
if (target.classList.contains(zoomClass)) {
const limit = images.offsetHeight - target.offsetHeight;
target.onmousemove = (event) => {
if (event.clientY !== limit && event.clientY !== 0) {
target.style.top = event.clientY + 1 + `px`;
}
};
}
});
}
.show-image {
font-size: 21px;
}
.media-viewer {
width: 100%;
height: 100%;
margin: 0 auto;
}
.media-viewer-backdrop {
bottom: 0;
left: 0;
position: fixed;
right: 0;
top: 0;
z-index: 1600;
overflow-y: scroll;
display: flex;
justify-content: center;
align-content: stretch;
align-items: center;
background: rgba(0, 0, 0, 0.5);
}
.media-viewer-main {
position: relative;
box-shadow: rgba(0, 0, 0, 0.32) 0 16px 24px 0;
max-width: 100%;
min-width: 200px;
background: white;
margin: auto 0;
width: 100%;
height: 100%;
}
.media-viewer-main-header {
z-index: 1000;
position: relative;
border-radius: 8px 8px 0 0;
background: #F9F9F9;
}
.media-viewer-main-header-text {
font-size: 20px;
line-height: 22px;
padding: 15px;
margin: 0;
}
.media-viewer-main-header__close {
position: absolute;
right: 20px;
top: 15px;
}
.media-viewer-main-content {
z-index: 1000;
position: relative;
border-radius: 8px 8px 0 0;
}
.media-viewer-main-content-viewer {
text-align: center;
overflow: hidden;
width: 100%;
height: 764px;
position: relative;
}
.media-viewer-main-content-viewer-image {
height: calc(100vh - 174px);
max-width: 100%;
cursor: zoom-in;
}
.media-viewer-main-content-viewer-image__zoomed {
cursor: zoom-out;
height: auto;
position: relative;
transform: translate(0%, -50%);
z-index: 1;
margin: 0 auto;
}
<div class="show-image" id="showImage">
show image
</div>
A:
Я решил задачу, все, что нужно было сделать, переписать функцию toggleZoom вот так:
/**
* Toggling zoom
*
*/
function toggleZoom(images) {
images.addEventListener("click", (e) => {
const target = e.target;
if ("IMG" !== target.tagName) {
return;
}
const zoomClass = "media-viewer-main-content-viewer-image__zoomed";
target.classList.toggle(zoomClass);
if (target.classList.contains(zoomClass)) {
target.addEventListener("mousemove", (event) => {
const x = event.offsetX;
const y = event.offsetY;
const w = target.offsetWidth;
const h = target.offsetHeight;
const originX = (x / w) * 100;
const originY = (y / h) * 100;
target.style.transformOrigin = originX + "% " + originY + "%";
});
}
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
mocha and nested objects
Excuse if this is a silly question, I am new to mocking.
I am able to use mocha to do things like:
person.expects(:first_name).returns('David')
How can I mock a nested object?
Say I have a Product that belongs to a Person and I want to get the first name of that person.
In my app I might do it like this:
product.person.first_name
How would I get the same result using a mock?
A:
as an alternative to shingara's answer, you could use mocha's any_instance method "which will detect calls to any instance of a class".
Person.any_instance.expects(:first_name).returns('david')
it's documented at:
http://mocha.rubyforge.org/classes/Mocha/ClassMethods.html#M000001
| {
"pile_set_name": "StackExchange"
} |
Q:
How to play video in Rio play 2.0
Hello can any buddy help me how do i play video lectures in Rio player i am facing issue,while playing lecture it showing that Rio player application has stopeed working.Please help me to out this.
Thanks*
A:
You can try reinstalling app from RecordShield.Net
| {
"pile_set_name": "StackExchange"
} |
Q:
Working with merged column headers in Excel
Possible Duplicate:
Read csv with two headers into a data.frame
I am new to R and working to use R to analyse some data. The data happens to be in Excel format and right now I'm struggling to find a way to convert it into a format that is R-friendly.
The issue is that the column headers have merged cells, so in effect the headers have two rows. I'd like to convert it into a normal set of 1-D vectors, add an extra column and a row. Let me explain with an example:
Currently the excel format looks thus:
| H | J |
Y |M |F |M |F |
== == == == ==
Y1|V1|V2|V3|V4|
H,J are merged column headers and each of them span columns M and F.
The = indicate that the rows above are header rows
Given that H,J both are elements under, say R, I would like to convert this into a columnar format with a normal header and two rows, like this
Y |R |M |F |
== == == ==
Y1|H |V1|V2|
Y1|J |V3|V4|
Does anyone have an idea how to do this?
A:
First, some assumptions:
The merged headings are on the first line of the CSV
The merged headings start in the second column of the CSV
The variable names in the second line of the CSV repeat (except for the variable in the first column)
Second, your data.
temp = c(",\"H\",,\"J\",",
"\"Y\",\"M\",\"F\",\"M\",\"F\"",
"\"Y1\",\"V1\",\"V2\",\"V3\",\"V4\"")
Third, a slightly modified version of this answer.
# check.names is set to FALSE to allow variable names to be repeated
ONE = read.csv(textConnection(temp), skip=1, check.names=FALSE,
stringsAsFactors=FALSE)
GROUPS = read.csv(textConnection(temp), header=FALSE,
nrows=1, stringsAsFactors=FALSE)
GROUPS = GROUPS[!is.na(GROUPS)]
# This can be shortened, but I've written it this way to show how
# it can be generalized. For instance, if 3 columns were repeated
# instead of 2, the rep statement could be changed to reflect that
names(ONE)[-1] = paste0(names(ONE)[-1], ".",
rep(GROUPS, each=(length(names(ONE)[-1])/2)))
Fourth, the actual reshaping of the data.
TWO = reshape(ONE, direction="long", ids=1, varying=2:ncol(ONE))
# And, here's the output.
TWO
# Y time M F id
# 1.H Y1 H V1 V2 1
# 1.J Y1 J V3 V4 1
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Groovy have support for something like Ruby Modules?
Ruby modules make things like passing a database connection or other dependencies to various objects much easier while allowing for separation of concerns. Does Groovy support a similar functionality? And if so what is it called?
A:
In ruby modules are used either as mixins or to namespace a class (e.g. Net::HTTP).
To mixin the behavior you can use @mixin annotation. like examples here http://groovy.codehaus.org/Category+and+Mixin+transformations.
To namespace, groovy uses same mechanism as java i.e. using packages (e.g. groovy.sql.Sql).
I am not sure if that answered your question or not. But for dependency injection, while its common to do it mixin way in ruby (or even in scala/play), I have not seen it done a lot using @mixin in groovy. Usually a DI container like spring is used.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wann darf bzw. muss man „solch“ nicht beugen?
Wiktionary sagt nichts zu dessen ungebeugter Nutzung. Laut canoo könne es als gewisse ungebeugte Adjektive (z. B. absolut, enorm) als Gradpartikel vor einem Adjektiv stehen. Und da findet man Folgendes:
ein solch großer Hund
mit solch kleinen Summen
Darüber hinaus soll laut dem Duden das Demonstrativpronomen solch – falls ungebeugt – gehoben wirken.
Ist das alles, was ich zum ungebeugten solch wissen soll? D. h., wann darf man solch nicht beugen? Wann muss man?
A:
Vor solch kann ein unbestimmter Artikel stehen. Und das Adjektiv wird dekliniert. Zum Beispiel:
Das ist eine solch interessante Frage.
Im Plural wird es auch wie ein Adjektiv dekliniert. Zum Beispiel:
Das sind solch interessante Fragen.
| {
"pile_set_name": "StackExchange"
} |
Q:
run a standlone .cs file within a asp.net application in vs2010
I am using the vs2010 to build a asp.net web application,sometime I want to do some test,so I have to create a new .cs file,but when I click the debug button,the vs will start the whole web application rather than the standlone .cs file.
In java,I use eclipse as my IDE,if I want to do some test in my web applicatio,I just create a new .java which own the "main" method,then I can run this file by "run as java appliation",so this .java will start.
I wonder if I can do the samething in vs2010?
BTW,how to do some output in the console within vs2010?
In java,within a servlet,I can use the System.out.println("xxx") within the method,when a request comes from the client,the "xxx" will be printed in the console of the eclipse,but in vs when I try "Console.WriteLine("xxx"),there is no output in the vs console, why?
A:
You need to create a new C# project within your solution alongside your ASP.NET project, and if you want console-based output in that C# program, you need to make sure it's a C# Console Application.
To add a new project to your solution, right-click the solution header in the Solution View, and select "Add Project...". You should definitely not just insert a .cs file into your ASP.NET project.
| {
"pile_set_name": "StackExchange"
} |
Q:
mongomapper and rails view for array
i have a rails controller grabbing some data from mongodb. the field i'm interested in is actually an array and i would like to expose this in an erb view.
my current hack is to just set the javascript variable in the view directly (where item.array = [ "one", "two" ]):
var array = <%= item.array %>;
however, i see that the code is coming out escaped such that the html is coming out like
var array = ["one", "two"];
is there a helper function i can use so that i can set the array directly in the javascript?
(long term is to move this into a json call, but i just want to get something working for now)
A:
Please use as per below:
var array = <%= item.to_s.html_safe %>;
| {
"pile_set_name": "StackExchange"
} |
Q:
In what method should I recreate resources after didReceiveMemoryWarning?
I have a view controller that has a private NSArray variable. The variable is initialised in the viewDidLoad method. A few questions arise for the case when the didReceiveMemoryWarning is called:
Should I set the private variable to nil?
If I set it to nil in what method must it be recreated? Does the view controller call the viewDidLoad method to recreate it?
I'm asking because other methods of the view need this variable and won't work if it's nil.
Thank you!
A:
Typically you unload a private property by assigning nil via the setter (e.g. self.propertyName = nil). Or you could set the ivar to nil after calling release, e.g. [_propertyName release]; _propertyName = nil;, but the former is preferable.
The didReceiveMemoryWarning method is called when there is a low memory situation. It is called on every view controller, including the one(s) responsible for the currently visible UI!
Therefore, you can't just unload data arbitrarily when you get a call to didReceiveMemoryWarning -- the view controller might need that data if it is currently visible on the display.
The general principle is that didReceiveMemoryWarning can get rid of any resources it can to assist freeing up memory, but only those that aren't immediately needed. For example, in an OpenGL game you wouldn't unload textures that are currently visible on the display. However, see my last paragraph.
Typically you reload the resources by checking they are loaded when you need them, and if not, loading them.
It's not worth niling/releasing tiny resources such as a single normally sized string. You should concentrate on items taking up significant amounts of memory.
Recent advances in behind the scenes memory management mean you're less likely to need to actually unload data these days - the operating system can unload and reload uncompressed image data and the like behind the scenes.
As Hot Licks mentions, the simulator has an option for simulating a memory warning. It's worth triggering this memory warning at various points in your app to see how it behaves.
A:
Its better to set your variable to nil. I mean release the memory it is holding in didReceiveMemoryWarning and set a dirty flag.
You can always check the dirty flag in array's getter(you can write your own) and repopulate it. It is probably not the best way. It entirely depends on the array's usage.
| {
"pile_set_name": "StackExchange"
} |
Q:
shell script to find the combination of the array elements
I have a shell script in which I have defined an array. The array contains more than 2 elements. I need to find the combination of all the elements in my array. Suppose, if my array has the elements, {12345, 56789, 98765}, I am trying to get the output as,
12345, 56789
12345, 98765
56789, 98765
I tried the php code from here.
<?php
function pc_permute($items, $perms = array( )) {
if (empty($items)) {
print join(' ', $perms) . "\n";
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
pc_permute($newitems, $newperms);
}
}
}
pc_permute(split(' ', '12345 56789 98765'));
?>
I get the output as,
12345 56789 98765
56789 12345 98765
12345 98765 56789
98765 12345 56789
56789 98765 12345
98765 56789 12345
Is it possible to get the combination in 2 elements sized output? I am not concerned with the order and so if A B is got as a combination, I do not need the reverse (B A).
A:
All you need is printf. It's the print function - that's its job.
printf '%s\t%s\n' ${array[@]}
You do it like this:
( set -- 12345 56789 98765; for i ; do
eval set -- $(printf '"$%s" ' `seq 2 $#` 1)
echo "$*"
done )
OUTPUT
56789 98765 12345
98765 12345 56789
12345 56789 98765
I didn't need eval - that was dumb. Here's a better one:
( set -- 12345 56789 98765 ;
until [ $((i=i+1)) -gt $# ] ; do
set -- $(s=$1 ; shift ; printf '%s\n' "$@" "$s")
printf '%s ' "$@" ; echo
done)
OUTPUT
56789 98765 12345
98765 12345 56789
12345 56789 98765
And then if you want only two elements you just change it a little bit - one more line:
( set -- 12345 56789 98765 ;
until [ $((i=i+1)) -ge $# ] ; do
set -- $(s=$1 ; shift ; printf '%s\n' "$@" "$s")
v="${v}$(printf '%s ' "$@")"
done ; printf "%s\t%s\n" $v
)
OUTPUT
56789 98765
12345 98765
12345 56789
I do this all of the time, but never the bashisms. I always work with the real shell array so it took a few minutes to get hold of it.
Here's a little script I wrote for another answer:
abc="a b c d e f g h i j k l m n o p q r s t u v w x y z"
for l in $abc ; do {
h= c= ; [ $((i=i+1)) -gt 26 ] && n=$((n+26)) i=
xyz=$(x=${xyz:-$abc} ;\
printf %s\\n ${x#?} $l)
mid=$(set -- $xyz ; eval echo \$$((${#}/4))) ;\
echo "$mid $l" >&2 ;
[ $(((i+n)%${mod=3})) -eq 0 ] && c="$mid" h="${xyz%"$mid"*}"
line="$(printf '%s ' $h $c ${xyz#"$h"})"
printf "%s$(printf %s ${xyz#?}${mid})\n" \
${line} >|/tmp/file$((i+n))
} ; done
This writes to 26 files. They look like this only they increment per file:
bcdefghijklmnopqrstuvwxyzag
ccdefghijklmnopqrstuvwxyzag
dcdefghijklmnopqrstuvwxyzag
ecdefghijklmnopqrstuvwxyzag
fcdefghijklmnopqrstuvwxyzag
gcdefghijklmnopqrstuvwxyzag
hcdefghijklmnopqrstuvwxyzag
icdefghijklmnopqrstuvwxyzag
jcdefghijklmnopqrstuvwxyzag
kcdefghijklmnopqrstuvwxyzag
lcdefghijklmnopqrstuvwxyzag
mcdefghijklmnopqrstuvwxyzag
ncdefghijklmnopqrstuvwxyzag
ocdefghijklmnopqrstuvwxyzag
pcdefghijklmnopqrstuvwxyzag
qcdefghijklmnopqrstuvwxyzag
rcdefghijklmnopqrstuvwxyzag
scdefghijklmnopqrstuvwxyzag
tcdefghijklmnopqrstuvwxyzag
ucdefghijklmnopqrstuvwxyzag
vcdefghijklmnopqrstuvwxyzag
wcdefghijklmnopqrstuvwxyzag
xcdefghijklmnopqrstuvwxyzag
ycdefghijklmnopqrstuvwxyzag
zcdefghijklmnopqrstuvwxyzag
acdefghijklmnopqrstuvwxyzag
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between StudlyCaps and CamelCase?
PSR suggests, method names MUST be declared in camelCase and class names MUST be declared in StudlyCaps.
A:
StudlyCaps, also known as PascalCase, implies that the first capital of each subword is capitalized. camelCase implies, like a camel, that the humps are in the middle, therefore the first letter is not capitalized.
Compare Microsoft's standards for .NET.
Other well known capitalization styles are snake_case, where all words are concatenated in lowercase with underscores, and kebab-case, which is identical but uses a hyphen.
A:
CamelCase is where the first letter of each sub-word in a name is capitalised. The first letter of the whole name can be upper or lower case, and is generally (always?) lower case in programming.
StudlyCaps is a little weird. There are capital letters, but they can be at any letter according to some rule, not just the beginning of a sub-word. The classic example is (was) HoTMaiL.
My understanding of the PSRs is that their intention is that each sub-word should be capitalised in both instances, with classes having an initial upper-case letter and methods an initial lower-case letter.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to avoid UICollectionView repeating cells?
Hello I have a UICollectionView. I load data from a NSMutableArray and it has 4 objects. But my problem is its repeating the same cells again.
`
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return mutArrayArtists.count;
}
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
return 2;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
artist = [mutArrayArtists objectAtIndex:indexPath.row];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = artist.artistImage;
UILabel *lblArtistname=(UILabel *)[cell viewWithTag:102];
lblArtistname.text=artist.artistName;
UILabel *lblSongCount=(UILabel *)[cell viewWithTag:101];
lblSongCount.text=artist.numberofSongs;
return cell;
}
`
But the result is like this
How can I avoid this? Please help me
Thanks
A:
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
return 1; //instead of 2
}
The section here does not mean the number of columns. It means that the collection view will contain 2 sections vertically above each others
| {
"pile_set_name": "StackExchange"
} |
Q:
How to extract specific fields in BATCH using Mailchimp API v3 for GET method?
I am trying to GET information(specific fields from email-activity), how should I do it in Batch GET requests in Mailchimp api v3?
This is my code -
{
"operations": [
{
"method": "GET",
"path": "/reports/campaign_id/email-activity",
"operation_id" : "123"
}
]
}
With the above code, the entire email-activity is extracted, I only need few fields from email-activity like "email_address" and "campaign_id". How do I do it using BATCH GET request using Mailchimp API v3?
A:
You've had this question answered for you multiple times now in various comments, but for the sake of anyone else who might find this on google later, the answer is found in the Getting Started Guide.
Partial responses
Use field parameters to cut down on data transfers by limiting which
fields the MailChimp API returns. For example, you may not need the
full details of a resource, and can instead pass a comma-separated
list of specific fields you want to include.
The parameters fields and exclude_fields are mutually exclusive and
will throw an error if a field isn’t valid in your request. For example,
the following URL uses the fields query string parameter to only include
the list name and list id fields in the response:
https://usX.api.mailchimp.com/3.0/lists?fields=lists.name,lists.id
Now, you might be wondering, "How do I add parameters to a batch request?" Fortunately, the MailChimp documentation is here for you. Refer to the How to use Batch Operations guide, which tells you to include an field called params in your operation object.
In the example above, you would do the following:
{
"operations": [{
"method": "GET",
"path": "/reports/campaign_id/email-activity",
"params": {
"fields": "campaign_id,emails.email_address"
},
"operation_id" : "123"
}]
}
Note: You say you'd like to retrieve the campaign_id field. Please note that the "path" portion of the request already needs to contain the campaign_id, so you have to have it before you can make this request at all. That said, you might find it valuable to be included in the response so that your processor doesn't have to have information about the request that generated the response.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display average per grading period in html? using django
I have this filter that compute the final average per Grading Categories
gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True))\
.filter(grading_Period__in=period.values_list('id', flat=True)).values('Grading_Categories').annotate(average_grade=Avg('Grade'))
when i print it, the result is like this:
<QuerySet [{'Grading_Categories': 1, 'average_grade': 88.3333333333333}, {'Grading_Categories': 2, 'average_grade': 90.0}]>
I just want to display in my html the actual average per grading period in html but the result i got in html is like this
<QuerySet [{'Grading_Categories': 1, 'average_grade': 88.3333333333333}, {'Grading_Categories': 2, 'average_grade': 90.0}]>
A:
It depends how you want it displayed in the template, but for example, in a table:
<table>
<thead>
<tr>
<th>Categories</th>
<th>Avgerage Grade</th>
</tr>
</thead>
<tbody>
{% for result in gradepercategory %}
<tr>
<td>{{ result.Grading_Categories }}</td>
<td>{{ result.average_grade }}</td>
</tr>
{% endfor %}
</tbody>
</table>
| {
"pile_set_name": "StackExchange"
} |
Q:
Java Calendar: Why are UTC offsets being reversed?
I'm trying to grok time-handling, and I've stumbled upon something in Java that has me somewhat baffled. Take this sample code:
public static void main(String[] args)
{
//Calendar set to 12:00 AM of the current day (Eastern Daylight Time)
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-4"));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
/////
//Calendar set to 12:00 AM of the current day (UTC time)
Calendar utcCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
utcCal.set(Calendar.HOUR_OF_DAY, 0);
utcCal.set(Calendar.MINUTE, 0);
utcCal.set(Calendar.SECOND, 0);
utcCal.set(Calendar.MILLISECOND, 0);
/////
long oneHourMilliseconds = 3600000;
System.out.println((cal.getTimeInMillis() - utcCal.getTimeInMillis()) / oneHourMilliseconds);
}
I visualize the algorithm for calculating the time represented by cal taking 1 of 2 forms:
Calculate the number of milliseconds from the Epoch, add offset (add -4)
Calculate the number of milliseconds from (Epoch + offset). So # of milliseconds from (Epoch - 4 * oneHourMilliseconds).
Both of these algorithms should yield a result that is 4 hours behind that of utcCal, however running the code returns 4 .
Can someone explain to me why cal, despite being set to a time zone 4 hours behind that of utcCal, ends up having a millisecond value 4 hours after that of utcCal? Shouldn't the code be returning -4?
A:
It's an unfortunate piece of history. A time zone with an ID of "GMT-4" is what you'd expect to be "UTC+4", i.e. it's 4 hours ahead of UTC.
From the etcetera file from tzdb:
# We use POSIX-style signs in the Zone names and the output abbreviations,
# even though this is the opposite of what many people expect.
# POSIX has positive signs west of Greenwich, but many people expect
# positive signs east of Greenwich. For example, TZ='Etc/GMT+4' uses
# the abbreviation "GMT+4" and corresponds to 4 hours behind UTC
# (i.e. west of Greenwich) even though many people would expect it to
# mean 4 hours ahead of UTC (i.e. east of Greenwich).
And from this similar explanation:
If you can at all manage it, avoid definitions and use of the GMT timezones...
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I find out how much a currency is traded?
I am interested to find out which currencies are the highest traded. For instance, if someone travels from the UK to the US (as a tourist) and converts pounds to dollars, or a company that deals with companies or provides services to people in different markets. So far searching on Google has only produced hits for companies that offer a conversion service. I imagine there would be three or four different ways currency trade could occur: personal, business, stock market and maybe countries.
How can I find a list of which currencies are traded the most (in terms of value), preferably broken down into categories?
EDIT
I am looking for information exactly like this that was provided in the answer.
A:
This is actually a fairly hard question to answer well as much of the currency trading that is done in financial markets is actually done directly with banks and other financial institutions instead of on a centralized market and the banks are understandably not always excited to part with information on how exactly they do their business. Other methods of currency exchange have much, much less volume though so it is important to understand the trading through markets as best as possible.
Some banks do give information on how much is traded so surveys can give a reasonable indication of relative volume by currency. Note the U.S. Dollar is by far the largest volume of currency traded partially because people often covert one currency to another in the markets by trading "through" the Dollar. Wikipedia has a good explanation and a nicely formatted table of information as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to tell if code cannot be optimized any further
I have written a function to calculate a formula in C# that uses nested for loops. It runs slower than I would like and I have been trying to speed it up. Is there a good way to determine if my code can optimized further in C# or if I need to move to a language that is machine compiled such as C++?
I know each case will be different but is there a general process/checklist that could be used to determine if more optimization is possible?
A:
No, there is no general rule that works for any algorithm saying "This algorithm cannot be optimized further". If such a tool existed, it would be applied to, well, any existing program.
However a profiler can show you hot spots in your code that should be optimized : it is usually a good idea to run a profiler on time-sensitive parts of the program showing inefficiencies.
Compiling with .NET native could give you results closer to what one would expect to the equivalent C++ program.
| {
"pile_set_name": "StackExchange"
} |
Q:
parsing line capture value in the ttoken
My goal is to find the line that has id on the plain text file then get the value of the token behind that id. On my file has 100s of lines similar to this: (the 5th column is always the id that i search for and the 6th column is the token i need to grab/store the number between two alphabet.
For example if I am looking for id Q9C0F0, i want to get/store value 1136( which is between 2 alphabet-K and N). Then i want to use that number to print on the outputfile. Thanks in advance
COAAD ASXL3 Missense_Mutation KFGM-AA-3672 Q9C0F0 K1136N
COAAD ASXL3 Missense_Mutation KFGM-AA-3693 Q9C0F0 A1544E
COAAD ASXL3 Missense_Mutation KFGM-AA-A010 Q9C0F0 F353S
COAAD ASXL3 Missense_Mutation KFGM-AA-A010 Q9C0F0 L157I
COAAD ASXL3 Missense_Mutation KFGM-AG-3890 Q9C0F0 L1324Q
COAAD ASXL3 Missense_Mutation KFGM-AG-A002 Q9C0F0 H552N
COAAD ASXL3 Missense_Mutation KFGM-AG-A002 Q9C0F0 K471N
COAAD ASXL3 Missense_Mutation TKFGM-AG-A002 Q9C0F0 L804M
A:
This is a simple way how to do it, maybe it will help you, corectness of the "algorithm" depends on the input condition, so maybe you will need to change parsing of the integers and change some conditions
with open('file') as f:
for line in f.readlines():
l = line.split()
if l and l[4] == 'Q9C0F0':
print l[5][1:-1] # or parse int in a more inteligent way
| {
"pile_set_name": "StackExchange"
} |
Q:
Shell script - SSH
I am using shell script to add some file to server. Is there any way to write a shell script that will execute one part on local computer and the other part when you're logged into that server?
For example, I want to log in, do something, add some file, and then I want to list everything on that server.
ssh something@something
I enter password
Then list files from server.
A:
You can just add a command to end of the ssh command; for example:
ssh username@host ls
will run ls on the server, instead of giving you a login shell.
| {
"pile_set_name": "StackExchange"
} |
Q:
Responsive design image aligning
I am a novice html/CSS programmer who needs to satisfy a very specific set of circumstances.
I have 2 images, both must be aligned vertically by the center of the image. One image must be left aligned and the other must be right aligned. They will be in a max width div but I don't think that should be an issue. As the webpage is shrunk down below the width of the two pictures together, the images then need to be horizontally centered with one image on top of the other. I have added pictures to clarfiy (sorry I would have added as pictures but I have zero rep). The div container and images will all be variable so positioning based upon pixels is out of the question.
So I researched this a ton, but all answers I've found have been partial; not able to do everything I'm looking for. Any ideas?
(http://imageshack.us/a/img819/9515/3zt.gif)
(http://imageshack.us/a/img14/853/qp8.gif)
Research:
I notice my question was -1'd. I guess not providing my research was the fault? Here's some of the methods I tried to fix this issue:
Vertical alignment of elements in a div
How to vertically align an image inside div
How to vertically middle-align floating elements of unknown heights?
Wrap long HTML tables to next line
A:
Edit #2
Another version, I think this is the cleanest I can think of
live view
edit view
Use a css table and vertical-align:middle for the wide screen view, then collapse the table for narrow viewports. The code is clean and it's completely independant of image heights.
================
Edit
As @user2748350 correctly pointed out, my original suggestion below didn't align images vertically on a wide screen if they were different heights.
Here's a variation which is an improvement using vertical-align: middle and inline images. The only requirement is that you set a line height larger than the tallest image:
live view
edit view
===============================================
Original
See if this helps you:
live view
edit view
HTML
<div class="container">
<img src="http://placehold.it/300x150" class="left">
<img src="http://placehold.it/250x150" class="right">
</div>
CSS
.container{
margin: 0 auto;
max-width:1000px;
}
img.left{
display:block;
float:left;
}
img.right{
display:block;
float:right;
}
@media (max-width: 570px) {
img.left{
float:none;
margin: 0 auto;
}
img.right{
display:block;
float:none;
margin: 0 auto;
}
}
In the head of your page, you also want to add
<meta name="viewport" content="width=device-width, initial-scale=1.0">
for good display on mobile devices.
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.