text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
open a new webpage on click of tab
here is my code .. i want to open facebook when i click on second tab ie tab2
<html>
<head>
<link rel="stylesheet" media="screen" type="text/css" href="style.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".tab_content").hide();
$("ul.tabs li:first").addClass("active").show();
$(".tab_content:first").show();
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active");
$(this).addClass("active");
$(".tab_content").hide();
var activeTab = $(this).find("a").attr("href");
$(activeTab).fadeIn();
return false;
});
});
</script>
</head>
<body>
<div class="container">
<ul class="tabs">
<li><a href="#tab1">tab1</a></li>
<li><a href="#tab2">tab2</a></li>
<li><a href="#tab3">tab3</a></li>
<li><a href="#tab4">tab4</a></li>
</ul>
<div class="tab_container">
<div id="tab1" class="tab_content">
<p>No Data Available</p>
</div>
<div id="tab2" class="tab_content" >
</div>
<div id="tab3" class="tab_content">
</div>
<div id="tab4" class="tab_content">
</div>
</div>
</div>
</body>
</html>
A:
How about:
<li><a href="http://facebook.com">tab2</a></li>
Though I will say making a tab a link is highly unintuitive and not good UI practice.
| {
"pile_set_name": "StackExchange"
} |
Q:
FFMPEG vstack and loop
I would like to stack 4 videos as in the code below and add a loop for top_left.mp4 that is shorter for example.
I can't find a way to add the loop option without getting errors.
Could you help me please?
ffmpeg -i top_left.mp4 -i top_right.mp4 -i bottom_left.mp4 -i bottom_right.mp4 \
-lavfi "[0:v][1:v]hstack[top];[2:v][3:v]hstack[bottom];[top][bottom]vstack" \
2by2grid.mp4
A:
Use -stream_loop -1 and add shortest=1 to the first hstack:
ffmpeg -stream_loop -1 -i top_left.mp4 -i top_right.mp4 -i bottom_left.mp4 -i bottom_right.mp4 -lavfi "[0:v][1:v]hstack=shortest=1[top];[2:v][3:v]hstack[bottom];[top][bottom]vstack" 2by2grid.mp4
xstack version:
ffmpeg -stream_loop -1 -i top_left.mp4 -i top_right.mp4 -i bottom_left.mp4 -i bottom_right.mp4 -lavfi "[0][1][2][3]xstack=inputs=4:layout=0_0|w0_0|0_h0|w0_h0:shortest=1" 2by2grid.mp4
| {
"pile_set_name": "StackExchange"
} |
Q:
Classification report in scikit learn
I want to classify faults and no-fault conditions for a device. Label A for fault and label B for no-fault.
scikit-learn gives me a report for classification matrix as :
precision recall f1-score support
A 0.82 0.18 0.30 2565
B 0.96 1.00 0.98 45100
Now which of A or B results should I use to specify the model operation?
A:
Introduction
There's no single score that can universally describe the model, all depends on what's your objective. In your case, you're dealing with fault detection, so you're interested in finding faults among much greater number of non-fault cases. Same logic applies to e.g. population and finding individuals carrying a pathogen.
In such cases, it's typically very important to have high recall (also known as sensitivity) for "fault" cases (or that e.g. you might be ill). In such screening it's typically fine to diagnose as "fault", something that actually works fine - that is your false positive. Why? Because the cost of missing a faulty part in an engine or a tumor is much greater than asking engineer or doctor to verify the case.
Solution
Assuming that this assumption (recall for faults is most important metric) holds in your case, then you should be looking at recall for Label A (faults). By these standards, your model is doing rather poorly: it finds only 18% of faults. Likely much stems from the fact that number of faults is ~20x smaller than non-faults, introducing heavy bias (that needs to be tackled).
I can think of number of scenarios where this score would not be actually bad. If you can detect 18% of all faults in engine (on top of other systems) and not introduce false alarms, then it can be really useful - you don't want too often fire alarm to the driver while everything's fine. At the same time, likely you don't want to use the same logic for e.g. cancer detection and tell patient "everything's OK", while there's a very high risk that the diagnosis is wrong.
Metrics
For the sake of completeness, I will explain the terms. Consider these definitions:
tp - true positive (real fault)
tn - true negative (it's not a fault)
fp - false positive (detected fault, while it's OK)
fn - false negative (detected OK, while it's a fault)
Here is one article that attempts to nicely explain what's precision, recall and F1.
| {
"pile_set_name": "StackExchange"
} |
Q:
Составить запрос Mysql
Нужно составить вот такой запрос.
DB::table('work')
->select(DB::raw('FROM_UNIXTIME(date, \'%Y %D %M %h:%i\') AS unique_date'))
->where('moderator', $moderator)
->whereNotIn('unique_date', $data)->get();
Он генерируется в
select from_unixtime(date, '%Y %D %M %h:%i') as unique_date from `work` where `moderator` = 1 and `unique_date` not in (2015 27th August 08:25, 2015 27th August 08:34)
В данном случае выходит ошибка:
Unknown column 'unique_date' in 'where clause'
Кто-нибудь сталкивался с подобным? Нужно делать выборку по ассоциации столбца. Можно пример запроса на чистом sql, это не критично.
A:
Мой ответ из комментариев В условии запроса вместо имени генерируемого самим запросом поля используйте формулу на основе которого формируется это поле. То есть вместо
->whereNotIn('unique_date', $data)->get();
используйте
->whereRaw(DB::raw('FROM_UNIXTIME(date, \'%Y %D %M %h:%i\') not in (\'' . implode('\',\'', $data) . '\')'))
->get();
| {
"pile_set_name": "StackExchange"
} |
Q:
Change names of appended table row fields jQuery
I have a table in an html form containing a table that a row is added to every time a button is clicked. When each row is added, I want the name and id of each field in the new row (there are four) to be updated from "Id.0" in the first row to "Id.1" in the second row and then "Id.2" in the third, etc. I can accomplish this with the id no problem using
var next=$("#QualificationRequirements tr:last").clone();
fixIds(next,nexdex);
nexdex++;
$("#QualificationRequirements").append(next);
function fixIds(element, counter) {
$(element).find("[id]").add(element).each(function() {
this.id = this.id.replace(/\d+$/, "")+counter;
}
}
However I have found that the same logic does not apply to the name attribute, and
$(element).find("[name]").add(element).each(function() {
this.name = this.name.replace(/\d+$/, "")+counter;
});
causes an error that says I can't call "replace" on a null object, so it appears the name attribute is not being found.
Can anyone see what I'm doing wrong? Thanks!
A:
The issue comes from this part of your statement: add(element)
See, element refers to the complete row, and rows don't have a name attribute. You just want to act upon the inputs inside the row that have the name attribute so you should remove that part from your code:
$(element).find("[name]").each(function() {
this.name = this.name.replace(/\d+$/, "")+counter;
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to write value of one div into another div
I have the following HTML and I want to pull the value from one div into another and if possible to put a : between them.
It is about to add the value of div class="ITSv" to the value of div class="ITSn"
Source HTML:
<div id="HTML_SPEC"
class="ITSs">
<div class="ITSg">Specifications</div>
<div class="ITSr0">
<div class="ITSn">Battery form</div>
<div class="ITSv">Cylinder</div>
</div>
<div class="ITSg">Batterie</div>
<div class="ITSr0">
<div class="ITSn">battery voltage</div>
<div class="ITSv">1,5 V</div>
</div>
<div class="ITSr1">
<div class="ITSn">Capacity</div>
<div class="ITSv">7800 mAh</div>
</div>
Target format:
<div id="HTML_SPEC"
class="ITSs">
<div class="ITSg">Specifications</div>
<div class="ITSr0">
<div class="ITSn">Batteryform: Cylinder</div>
</div>
<div class="ITSg">Batterie</div>
<div class="ITSr0">
<div class="ITSn">battery voltage: 1,5 V</div>
</div>
<div class="ITSr1">
<div class="ITSn">Capacity: 7800 mAh</div>
</div>
A:
You can do the following
Array.from(document.getElementsByClassName('ITSn')).forEach(element => {
element.innerText += ': ' + element.nextElementSibling.innerText;
element.nextElementSibling.remove();
});
<div id="HTML_SPEC"
class="ITSs">
<div class="ITSg">Specifications</div>
<div class="ITSr0">
<div class="ITSn">Battery form</div>
<div class="ITSv">Cylinder</div>
</div>
<div class="ITSg">Batterie</div>
<div class="ITSr0">
<div class="ITSn">battery voltage</div>
<div class="ITSv">1,5 V</div>
</div>
<div class="ITSr1">
<div class="ITSn">Capacity</div>
<div class="ITSv">7800 mAh</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I reset X
My computer seems to have issues suspending and resuming properly. Most recently, it resumed from hibernate, was working fine until I started logging in, and then X froze completely. I can log in via SSH (and it works flawlessly when I do), and I'd love to reset it without restarting the whole computer, and preferably without crashing all my open applications.
Is this doable? If I have to crash the open apps, that's OK too, I suppose, but not preferred.
A:
I know hibernation still has a lot of issues with a wide variety of hardware in Ubuntu. You can restart X I believe with service gdm restart (or /etc/init.d/gdm restart) you should be able to get X reset. If you use Kubuntu or KDE you'll want to use service kdm restart (or /etc/init.d/kdm restart)
A:
Since the computer is not locked up, Alt+SysRq+k should kill/restart your X server. Type it on the X VT not on a console VT.
| {
"pile_set_name": "StackExchange"
} |
Q:
Layout UIView without adding it to subview
I'm creating a Grid view that reuses Cells, supports header and footer and also supports constraints.
But I'm getting a bad time with the layout of the constraints, because I add everything to a ScrollView, the constraints doesn't want to work. I already try
sizeThatFits
setNeedsUpdateConstraints
updateConstraintsIfNeeded
setNeedsLayout
layoutIfNeeded
I'm doing this because I didn't find any grid View that supports everything that was developed in swift or obj-c
Any idea on how I can force that the UI calculate the Constraints before adding it to the Scroll view?
A:
Any idea on how I can force that the UI calculate the Constraints
before adding it to the Scroll view?
You can try calling -layoutIfNeeded, but it may not work. The OS is probably optimized not to layout views that are not part of the view hierarchy. Even if it works, it will get laid out again when it's added as a subview to another view.
But I'm getting a bad time with the layout of the constraints, because
I add everything to a ScrollView, the constraints doesn't want to
work.
To get auto layout working with a scroll view, you'll want to add all of your objects to a single view, then add that one view to the scroll view.
Using scroll views with auto layout is tricky. I still cringe every time I have to do it.
| {
"pile_set_name": "StackExchange"
} |
Q:
abstract static member initialization
I want derived classes to have their own loggers, but it looks like I cannot:
abstract class C {
final protected static Logger l;
C (...) {
l.emit("C");
}
}
class C1 extends C {
final protected static Logger l = new Logger("C1");
C1 (...) {
super(...);
l.emit("C1");
}
}
I want a Logger in C1 but not in C, so that new C1() produces this output:
C1: C
C1: C1
(the first line comes from the C constructor and the second line from the C1 constructor). Instead I get a nullPointerException in C because l there is null.
I cannot make l into abstract in C, and I do not want to init it there either because then the output would be
C: C
C1: C1
What are my options?
Thanks!
A:
Solution 1 (the classic)
A possible approach would be to have an abstract getLogger() method in your abstract class, so that derived classes are forced to provide their own logger.
public class AbstractClass {
abstract Logger getLogger();
public void someMethodInAbstractClass() {
getLogger().debug("something"); // will output using provided child logger
}
}
public class ConcreteClass extends AbstractClass {
private static final Logger LOGGER = Logger.getLogger(ConcreteClass.class);
@Override
Logger getLogger() {
return (LOGGER);
}
public void someMethod() {
getLogger().debug("something"); // will output using local logger
}
}
You could also provide a default implementation in the abstract class to not force the child to implement an override. You make it easier on the consumers of your abstract class (developing concrete classes), but you won't enforce the fine graining of the method.
Solution 2 (long-winded...)
Another, more violent solution would be to have a getMagicLogger() method in the abstract class, that will determine at runtime the concrete type of the current instance to return a new logger instance, either every time or by lazy loading it and storing it in a field.
This way the abstract class handles it all and it's very easy for consumers, but it's kind of a crazy thing to do. AND, that means the Logger won't be a static field, obviously.
A:
There's no attribute overriding for static members, the l logger in C is the one declared in C (which is null) and not the one from the C1 subclass.
| {
"pile_set_name": "StackExchange"
} |
Q:
Interleaving serialized data
With the following input file:
rohit
mohit
sohit
34
45
67
I have to create a new file with following:
rohit 34
mohit 45
sohit 67
by only using paste & sed. Any ideas on how this could be done?
A:
$ paste -d' ' <(sed '3q' input.txt) <(sed -n '4,$p' input.txt)
rohit 34
mohit 45
sohit 67
| {
"pile_set_name": "StackExchange"
} |
Q:
Parcelize complains "Parcelable should be a class" on objects and enums
When I try to annotate an enum class or object with @Parcelize, it results in the error 'Parcelable' should be a class, both as an editor hint and as a compile failure. I can @Parcelize classes just fine, but I can't do things like
@Parcelize object MySingletion : Parcelable
@Parcelize enum class Direction : Parcelable { N, E, W, S }
This happens even though the Kotlin website explicitly states that objects and enums are supported. Is there a way to fix this so that I can @Parcelize these types of classes? And ideally, is there a solution that doesn't involve manually coding the parceler logic?
A:
Since Kotlin 1.2.60, the CHANGELOG states that Parcelize works with object and enum types.
A:
The documented support means, that objects and enums are properly handled when used as properties on the class being parcelized. More importantly both types are implicitly excluded from the usage, as the fields have to be properties defined within the primary constructor:
@Parcelize requires all serialized properties to be declared in the primary constructor. Android Extensions will issue a warning on each property with a backing field declared in the class body. Also, @Parcelize can't be applied if some of the primary constructor parameters are not properties.
If you need to use your objects or enums as a property only, there's no issue with it. If you want to use it as a Parcelable, you can't get around implementing the interface by yourself, since both types are a kind of a singleton implementation and @Parcelize only supports types with accessible constructors with properties.
| {
"pile_set_name": "StackExchange"
} |
Q:
retrieve LocalResource key and pass to Html.ActionLink linkText
i want retrieve LocalResource key and pass to Html.ActionLink linkText.but i dont know.
A:
You could try using the strongly generated class by visual studio:
<%= Html.ActionLink(Resources.SomeKey, "Home", "Index") %>
Or for a more general solution take a look at this post.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change the default terminal emulator on Windows (cmd)?
Is it possible to change the default terminal emulator on Windows (7 and 8 in particular) from Console to, for example, Console2 or ConEmu? In essence, I want all command line tools, whether launched by double clicking, from "Run" or by other processes to use the custom terminal.
This is a trivial matter on Linux, is it even possible on Windows?
It would be especially helpful if this could be done via a script.
A:
Default terminal
You may set up ConEmu as default terminal for cmd.exe, tcc.exe, powershell.exe or any other console application. In fact, you choose from what application you need to run any console application, even from Visual Studio for debugging your console applications.
Just turn on checkbox, point applications from you like to start console tools (for example explorer.exe|totalcmd.exe|wdexpress.exe) and voila. You may press Win+R type ipconfig /all and press Enter. You may even start your console application in Visual Studio debugger. New console will starts attached to the new ConEmu tab. You may also doubleclick on some executable in the Explorer window.
You may find more information about the feature in the project wiki: DefaultTerminal.
Alternative
Also, there is an alternative less preferable way to auto run ConEmu on cmd.exe and tcc.exe startup. Just press "Register ConEmu autorun" in Settings -> ComSpec.
| {
"pile_set_name": "StackExchange"
} |
Q:
Factory Method Pattern Example in Java troubles
I'm trying to create a really simple Factory Method design pattern example in Java. I don't really know Java, I am new to programming in general but I need to come up with a a basic FactoryMethod example implemented in java. The following is what I came up with. There are quite a few errors I'm sure, I'm missing some constructors apparently and I get confused with abstract classes and interfaces. Could you point out my mistakes and correct my code along with an explanation please? Thank you in advance for your time and help.
public abstract class Person
{
public void createPerson(){ }
}
public class Male extends Person
{
@Override
public void createPerson()
{
System.out.print("a man has been created");
}
}
public class Female extends Person
{
@Override
public void createPerson()
{
System.out.print("a woman has been created");
}
}
public class PersonFactory
{
public static Person makePerson(String x) // I have no Person constructor in
{ // the actual abstract person class so
if(x=="male") // is this valid here?
{
Male man=new Male();
return man;
}
else
{
Female woman=new Female();
return woman;
}
}
}
public class Test
{
public static void main(String[] args)
{
Person y= new Person(makePerson("male")); // definitely doing smth wrong here
Person z= new Person(makePerson("female")); // yup, here as well
}
}
A:
In brief there are several issues in your version that were corrected below:
createPerson method is useless.
The way you invoke the factory method is wrong.
You use == instead of .equals in your factory method.
I've enhanced your Person class to add a member field that is shared by the Male and Female class, to demonstrate how sharing a common abstract constructor could be used.
public abstract class Person {
protected final String name;
public Person(String name) {
this.name = name;
}
}
public class Male extends Person {
public Male(String name) {
super(name);
}
}
public class Female extends Person {
public Female(String name) {
super(name);
}
}
public class PersonFactory
{
public static Person makePerson(String gender, String name)
{
if(gender.equals("male"))
{
Male man=new Male(name);
return man;
}
else
{
Female woman=new Female(name);
return woman;
}
}
}
public class Test
{
public static void main(String[] args)
{
Person y= PersonFactory.makePerson("male", "bob"));
Person z= new PersonFactory.makePerson("female", "janet"));
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
URLs design for filtering Model's attributes in Django
Need you advice.
In my Django app I have a model for some Users. Users have some attributes: name, age, phone etc. This is not the API site. Just my intranet user's catalog.
I can get users using the following URLs:
/users/ # All users
/users/12 # User with ID 12
But how should I design URLs to get only the users which meet certain criteria? Is it a good practice to use query string for that purpose? Like this:
/users/ # All users
/users/?name=John # Filter by name
/users/?name=Peter&age=25 # Filter by name AND age
A:
If the point is to display the same object list just filtered / sorted on a specific criteria (or set of) then yes, that's one of the purpose of query strings.
| {
"pile_set_name": "StackExchange"
} |
Q:
After updating Joomla version "Media Manager" in Administrator panel not working
"My site is still on the old legacy Joomla platform but I did an update last week, which I probably shouldn't have done since everything was working fine. After the update I checked several features and all appeared to be operating properly. Then a week or so later I went back to add a photo to the Media Manager and now it times out and I get an error message." - (Unknown)
Its diverting me to the following page: http://www.my-site.xxx/administrator/index.php?option=com_media
and on this page the following error is coming: "Fatal error: Maximum execution time of 30 seconds exceeded in /home/theaarc/public_html/libraries/joomla/filesystem/folder.php on line 506"
Here is the Image:
A:
If you don't have a backup of your previous site before the upgrade, Im afraid reverting won't be possible else extremely hard and time consuming. Take a backup of the current website you have and try upgrading to Joomla 2.5, using jUpgrade.
I explained on this Stackoverflow post, why it is important to ensure your Joomla version is up to date.
Why should I keep my Joomla version up to date?
Once done, check if the Media Manager is working.
Hope this helps
| {
"pile_set_name": "StackExchange"
} |
Q:
Count unique values in Python list
I have the following code I've been working on, but I can't seem to find a way to count the number of unique values in the anagram list. If I just print out: print len(anagram) I get the total value of the list, but it includes duplicates.
I have tried to convert the list to a set and back to get rid of the duplicates, but have not had any luck.
Thanks!
#import libraries
import urllib, itertools
#import dictionary
scrabble = urllib.urlopen('http://www.puzzlers.org/pub/wordlists/ospd.txt').read().split()
#print the length of the dictionary
print len(scrabble)
#make anagrams from scrabble list
anagrams = [list(g) for k,g in itertools.groupby(sorted(scrabble, key=sorted), key=sorted)]
#print the largest anagram
print "Largest number of anagrams for a word : ", len(max(anagrams, key=len))
print "Largest anagram word and values ", max(anagrams, key=len)
A:
Use a set. sets hold only unique values:
print len(set(anagram))
| {
"pile_set_name": "StackExchange"
} |
Q:
One try/catch for each error, or one global try catch and switch error?
I have multiple methods that could fail, let's say :
readFile()
parseFile()
compute()
Each of them could fail (e.g file not found, wrong file type, wrong data), should I put each of them in their own try/catch block or should I create one try/catch block then switch the error and log/display text depending on the error?
e.g:
try {
readfile()
}
catch (err) {
log.error(err);
throw 'Could not read file';
}
try {
parsefile()
}
catch (err) {
log.error(err);
throw 'File corrupted or wrong type';
}
try {
compute()
}
catch (err) {
log.error(err);
throw 'Data is wrong';
}
or :
try {
readfile()
parsefile()
compute()
}
catch (err) {
switch(err) {
case 'NOENT': throw...
case 'CORRUPTED': throw...
}
}
A:
I am a believer that the best reason to catch an exception is to be able to log and then recover so as to continue running the program, for example, informing the user of the failure so they can take an alternate action.
What you're discussing here is alternative constructs/patterns for catching that all re-throw.
This implies that you necessarily have another try/catch higher up in the call chain that is doing this recovery.
This higher in the call-stack try/catch can do the logging, which makes the local try/catch (close to the point of throw, where corrective action cannot be taken) seem redundant to me, and I would seek to eliminate these seemingly unnecessary constructs.
try {
parsefile()
}
catch (err) {
log.error(err);
throw 'File corrupted or wrong type';
}
For example, the above try/catch could be removed by (1) relying on the outer try/catch to log the error and recover the program, and (2) throwing the proper exception in parsefile() in the first place.
(It could also be the case that the the parsefile() is already throwing a more useful and specific exception that is then being obscured by re-throwing a different more general exception. Let's recall that exceptions in most languages can participate in hierarchy to simplify some issues here.)
(Of course, there are times when this is impractical, but the question is posed rather generally, so this is a general answer)
A:
In most situations, I would say "neither". Instead, you should probably go with one try followed by multiple catch parts.
try {
readFile();
parseFile();
compute();
} catch (ReadFileException err) {
log.error(err);
throw new SomeException("Cannot read file", err);
} catch (ParseFileException err) {
log.error(err);
throw new SomeException("Cannot parse file", err);
} catch (ComputeException err) {
log.error(err);
throw new SomeException("Cannot compute results of file", err);
}
This keeps your "happy flow" code bundled together, while making it easy to handle different cases.
Your second option has these same advantages, but seems to match on some error message, which is rather brittle. Using different exception types gives your IDE the option to help you.
One note: If there is actually a lot of stuff going on between readFile(), parseFile() and compute(), I would go with 3 try..catch blocks instead - what "a lot of stuff" means in that case is very much a matter of personal taste, I think, and something you need to get a feel for.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rake db:migrate error "don't know how to build task"
I've got a table where I used integer on a field which needs decimal places, so I'm trying to create a migration which changes the field type from integer to float/real. My database is sqllite3 and I'm using rails3.
I ran
rails generate migration ChangeMeasureColumnOnIngredients
to create the initial migration files, then updated the class to
class ChangeMeasureColumnOnIngredients < ActiveRecord::Migration
def self.up
change_column :ingredients, :measure, :real
end
I ran rake db:migrate and it returned fine.
When I inserted a value via my rails app, it didn't return the decimal place. I started to think that many rails doesn't know what 'real' is as a datatype, so I changed the migration to change_column :ingredients, :measure, :float
I then ran rake db:migrate change_measure_column_on_ingredients
and now I get the following errorc:\Ruby192\rails3rc>rake db:migrate change_measure_column_on_ingredients
(in c:/Ruby192/rails3rc)
rake aborted!
Don't know how to build task 'change_measure_column_on_ingredients'
C:/Ruby192/lib/ruby/1.9.1/rake.rb:1720:in []'
C:/Ruby192/lib/ruby/1.9.1/rake.rb:2040:ininvoke_task'
C:/Ruby192/lib/ruby/1.9.1/rake.rb:2019:in block (2 levels) in top_level'
C:/Ruby192/lib/ruby/1.9.1/rake.rb:2019:ineach'
C:/Ruby192/lib/ruby/1.9.1/rake.rb:2019:in block in top_level'
C:/Ruby192/lib/ruby/1.9.1/rake.rb:2058:instandard_exception_handling'
C:/Ruby192/lib/ruby/1.9.1/rake.rb:2013:in top_level'
C:/Ruby192/lib/ruby/1.9.1/rake.rb:1992:inrun'
C:/Ruby192/bin/rake:31:in `'
I tried changing the :float back to :real, but I still get that error.
can somebody tell me what I'm doing wrong?
I'm new to rails and still learning.
A:
Your rake call has instructed rake to build the task db:migrate followed by the task change_measure_column_on_ingredients which clearly isn't want you want as the latter is not a rake task.
To run a specific migration you need to provide the VERSION of the migration. This is the number in the file name which comes before your name for the migration. You can migrate it up or down like this:
rake db:migrate:down VERSION=123456789
rake db:migrate:up VERSION=123456789
Alternatively you can take the last migration down then up by doing the following (you can also specify a VERSION for this):
rake db:migrate:redo
There are other options though. If you run rake --describe db:migrate you'll get some more information.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bevel corners, background not rounded
I have a figure with bevel corners, but the background is not rounded:
How to have it rounded?
.test-block {
height: 480px;
padding: 4px;
color: #ffffff;
background-color: transparent;
background-image:
-webkit-linear-gradient(top, #ffdc00, #ffdc00),
-webkit-linear-gradient(225deg, #ffdc00, #ffdc00),
-webkit-linear-gradient(bottom, #ffdc00, #ffdc00),
-webkit-linear-gradient(left, #ffdc00, #ffdc00),
-webkit-linear-gradient(315deg, transparent 9px, #ffdc00 10px, #ffdc00 12px, red 12px);
background-image:
linear-gradient(180deg, #1698d9, #1698d9),
linear-gradient(225deg, #1698d9, #1698d9),
linear-gradient(0deg, #1698d9, #1698d9),
linear-gradient(90deg, #1698d9, #1698d9),
linear-gradient(135deg, transparent 28px, #1698d9 28px, #1698d9 32px, #ffffff 10px);
background-position: top right, top right, bottom left, bottom left, top left;
background-size: -webkit-calc(100% - 15px) 2px, 2px 100%, 100% 2px, 2px -webkit-calc(100% - 15px), 100% 100%;
background-size: calc(100% - 40px) 4px, 4px 100%, 100% 4px, 4px calc(100% - 40px), 100% 100%;
background-repeat: no-repeat;
border-radius: 10px;
width: 320px;
}
.test-block__div {
background-image: url(http://css-snippets.com/blogfile/wp-content/uploads/2011/03/square.jpg);
background-repeat: no-repeat;
background-position: -24px 208px;
height: 100%;
}
<div class="test-block">
<div class="test-block__div"></div>
</div>
A:
Since you are using multiple background you can add more using radial-gradiant to create the corner (I removed the vendor prefixes to simplify the code)
.test-block {
height: 480px;
padding: 4px;
color: #ffffff;
background-color: transparent;
background-image:
radial-gradient(circle at top left, transparent 40%, #1698d9 0%),
radial-gradient(circle at bottom left, transparent 40%, #1698d9 0%),
radial-gradient(circle at top right, transparent 40%, #1698d9 0%),
linear-gradient(180deg, #1698d9, #1698d9),
linear-gradient(225deg, #1698d9, #1698d9),
linear-gradient(0deg, #1698d9, #1698d9),
linear-gradient(90deg, #1698d9, #1698d9),
linear-gradient(135deg, transparent 28px, #1698d9 28px, #1698d9 32px, transparent 10px);
background-position:
bottom right,
top right,
bottom left,
top right,
top right,
bottom left,
bottom left,
top left;
background-size:
10px 10px, 10px 10px, 10px 10px,
calc(100% - 40px) 4px,
4px 100%,
100% 4px,
4px calc(100% - 40px),
100% 100%;
background-repeat: no-repeat;
border-radius: 10px;
width: 320px;
}
body {
background-image:linear-gradient(30deg, pink, yellow);
}
<div class="test-block">
</div>
By the way you can achieve the same layout using pseudo-element and without multiples background. It can be easier to handle:
.test-block {
height: 440px;
padding: 4px;
margin-top: 60px;
color: #ffffff;
border-right: 4px solid #1698d9;
border-left: 4px solid #1698d9;
border-bottom: 4px solid #1698d9;
border-radius: 0 0 10px 10px;
width: 320px;
position: relative;
}
.test-block:before {
content: "";
position: absolute;
left: -4px;
width: 50%;
height: 40px;
top: -44px;
border-left: 4px solid #1698d9;
border-top: 4px solid #1698d9;
transform: skewX(-40deg);
transform-origin: bottom left;
}
.test-block:after {
content: "";
position: absolute;
right: -4px;
height: 40px;
width: 50%;
top: -44px;
border-right: 4px solid #1698d9;
border-top: 4px solid #1698d9;
border-radius: 0 10px 0 0;
}
body {
background-image: linear-gradient(30deg, pink, yellow);
}
<div class="test-block">
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
How could the ideal gas law be discovered from experiments on real gases?
The gas laws, namely Boyle's Law, Charles' Law, Avogadro's Law and Gay-Lussac's Law, are all experimental laws. Combining these laws, we get the ideal gas law $pV=nRT$. Also, "real life" gases do not exactly follow this law, so there are more laws for "real life" gases: van der Waals' law, Dieterici equation, etc., which approximately describe these laws within certain boundaries of the gas parameters: pressure $p$, volume $V$ and temperature $T$.
But there seems to be an apparent logical flaw: the ideal gas law $pV=nRT$ was found by experimenting on "real life" gases, but these "real life" gases do not follow the ideal gas law. How could this be the case?
A:
The ideal gas law is a very good approximation of how gases behave most of the time
There is no logical flaw in the laws. Most gases most of the time behave in a way that is close to the ideal gas equation. And, as long as you recognise the times they don't, the equation is good description of the way they behave.
The ideal gas equations assume that the molecules making up the gas occupy no volume; they have no attractive forces between them and their interactions consists entirely of elastic collisions.
These rules can't explain, for example, why gases ever liquefy (this requires attractive forces). But most of the common gases that were used to develop the laws in the first place (normal atmospheric gases like oxygen or nitrogen) are usually observed far from the point where they do liquefy.
As for the volume taken up by the molecules of the gas, consider this. A mole of liquid nitrogen occupies about 35mL and this is a fair approximation of the volume occupied by the molecules. at STP that same mole of gas occupies a volume of about 22,701mL or about 650 times as much. So, at least to a couple of decimal places, the volume occupied by the nitrogen molecules is negligible.
The point is that for gases not close to the point where they liquefy (and few components of the atmosphere are), the ideal gas laws are a very good approximation for how gases behave and that is what we observe in experiments on them. The fancy and more sophisticated equations describing them are only really required when the gas gets close to liquefaction.
A:
You must consider this:
The question whether a physical system follows a particular law is not a "yes or no" question. There is always an error when you compare what you measure with what the law predicts. The error can be at the 17th digit, but it's still there. Let me quote a very insightful passage by H. Jeffreys about this:
It is not true that observed results agree exactly with the predictions made by the laws actually used. The most that the laws do is to predict a variation that accounts for the greater part of the observed variation; it never accounts
for the whole. The balance is called 'error' and usually quickly forgotten or altogether disregarded in physical writings, but its existence compels us to say that the laws of applied mathematics do not express the whole of the variation. Their justification cannot be exact mathematical agreement, but only a partial one depending on what fraction of the observed variation in one quantity is accounted for by the variations of the others. [...] A physical law, for practical use, cannot be merely a statement of exact predictions; if it was it would invariably be wrong and would be rejected at the next trial. Quantitative prediction must always be prediction within a margin of uncertainty; the amount of this margin will be different in different cases[...]
The existence of errors of observation seems to have escaped the attention of many philosophers that have discussed the uncertainty principle; this is perhaps because they tend to get their notions of physics from popular writings, and not from works on the combination of observations.
(Theory of Probability, 3rd ed. 1983, §I.1.1, pp. 13–14).
The error can be different in different ranges of the quantities you're measuring.
When trying to guess a physical law, scientists often consider the simplest mathematical expression that's not too far from the data.
The "ideal gas law" is very accurate in the range where the temperature $T$ is high, the pressure $p$ is low, and the mass density $1/V$ (inverse volume) is low. In these ranges the law is very realistic. If you 3D-plot various measurements of $(p,V,T)$ for a fixed amount of a real gas, you'll see that a curved surface given by $pV/T=\text{const}$ fits the points having large $T$, low $p$, low $1/V$ very accurately. "Real" gases are very "ideal" in those ranges.
Moreover, the law involves simple multiplication and division: $pV/T$, so it's one of the first a scientist would try to fit the points.
Finally, the law wasn't just suggested by fitting, but also by more general physical and philosophical principles and beliefs. Take a look at
S. G. Brush: The Kind of Motion We Call Heat (2 volumes, North-Holland 1986)
for a very insightful presentation of the history of this and other laws.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the rules used by a reasoner
In OWL.
I know that if
ObjectProperty AB
and
AB domain A
and
AB range B
and
A subClassOf AB something
then the reasoner can infer that
A subClassOf B
1- What is the notion behind this inference?
2- Is there any references that explains the whole set of rules for how does the reasoner works, i.e. what are the rules that a reasoner applies to turn implicit knowledge into explicit one? like this one presented in the example above?
A:
The reasoning behind these inferences follows the rules outlined here:
http://www.w3.org/TR/owl2-direct-semantics/#Object_Property_Expression_Axioms
| {
"pile_set_name": "StackExchange"
} |
Q:
A horizontal line with the same space-filling behaviour as /hfill?
Is there a command or package which would allow me to draw a line in the largest available space in the way that \hfill fills up the remaining space in a line?
i.e., a command to draw a line from the end of the text, wherever it happens to fall, to the right edge of the textwidth (leaving space for any additional text indented to be at the end of the line)?
A:
You can use ordinary \hrulefill. There is also \dotfill for dots. For advanced control xhfill may be used.
\documentclass{article}
\usepackage{showframe} %% just to show the frame
\usepackage{xhfill}
\setlength{\parindent}{0pt}
\begin{document}
%% Usage
%% \xhrulefill{<color>}{<height>}
%% \xrfill[raise]{ruleheight}[color]
%% \xhrectanglefill{<height>}{<linewidth>}
%% \xhrectanglefill{1cm}{1pt}
First \verb|\xrfill|\xrfill{1pt}
This is \verb|\xrfill|\xrfill[0pt]{3pt}[blue]
A take with \verb|\xhrulefill|\xhrulefill{cyan}{1cm}
With \verb|\xhrectanglefill|\xhrectanglefill{0.5cm}{1pt}
%% Ordinary \hrulefill
With \verb|Ordinary \hrulefill|\hrulefill
With \verb|Ordinary \dotfill|\dotfill
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Detect hardware on client from a java web application
I am creating a web application using java. I'm wondering if there is a way to detect external memory like an SD card on a client's device. Also, is Java a good language to use for an application with this functionality? Or is there something better?
A:
Java works on the server side (your server) and won't run on the client unless you send a Java application to the client like an Applet or a JavaFX app. If using the web application only, you're unable to accomplish this with Java, if you're using the Applet/JavaFX approach, you're able to get that info but maybe you cannot send it to the server.
IMO it would be very insecure to have such features in a web application. Imagine a web application where everyone who access to it and the web application can access to your SD card, retrieve all the contents and send them through the net to the server side, thus having access to all your info and the info of every user who access to it.
| {
"pile_set_name": "StackExchange"
} |
Q:
getting place name from Json using google API
When I run this code I get a blank screen and nothing gets displayed.What changes I have to make in order to get this right and where am I going wrong?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$.getJSON("https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AIzaSyC1BIAzM34uk6SLY40s-nmXMivPJDfWgTc",
function(data, textStatus){
alert(data);
$.each(data.results,function(i, name) {;
$("#placenames").append(i+':'+name.vicinity+'<br/>');
});
});
});
</script>
</head>
<body>
<div id="placenames"></div>
</body>
</html>
A:
Have you tried using Google Maps Javascript API? It does all the JSONP stuff for you.
Here is a demo with your coordinates: http://jsfiddle.net/ThinkingStiff/CjfcX/
Script:
var places = new google.maps.places.PlacesService( document.createElement( 'div' ) ),
searchRequest = {
name: 'harbour',
location: new google.maps.LatLng( -33.8670522, 151.1957362 ),
radius: 500,
types: ['food']
};
places.search( searchRequest, function ( results, status ) {
var html = '';
for ( var index = 0; index < results.length; index++ ) {
html +=
'<li '
+ 'data-location-id="' + results[index].id + '" '
+ 'data-address="' + results[index].vicinity + '" '
+ 'data-latitude="' + results[index].geometry.location.lat() + '" '
+ 'data-longitude="' + results[index].geometry.location.lng() + '" '
+ 'data-name="' + results[index].name + '">'
+ '<div>' + results[index].name + '</div>'
+ '<div>' + results[index].vicinity + '</div>'
+ '</li>';
};
document.getElementById( 'results' ).innerHTML = html;
} );
HTML:
<script src="http://maps.googleapis.com/maps/api/js?libraries=places,geometry&sensor=true"></script>
<ul id="results"></ul>
Output:
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you use std::distance to find the array index of a pointer to an std::array element?
Let's say I have a std::array of some object and create a pointer to one of the objects.
std::array<Object, 100> my_array;
Object* ptr_object = &my_array[50];
So assuming I don't know the index referred to by ptr_object, how would I go about and back-track to find this index in C++11?
I've come across some readings that suggest std::distance might help, however, my attempt of
std::distance(my_array, ptr_object);
throws an error stating that "no matching overloaded function found".
A:
The easiest way to get the index is to use pointer arithmetic. Simply subtract a pointer to the desired element from a pointer to the first element, eg:
size_t index = (ptr_object - my_array.data()/*&my_array[0]*/);
std::distance() takes iterators as input, and raw pointers can be used as iterators. So, you can use a pointer to the first element as the starting iterator, and a pointer to the desired element as the ending iterator, eg:
size_t index = std::distance(my_array.data()/*&my_array[0]*/, ptr_object);
Note how this differs from your code, where you try to pass the std::array itself to std::distance(). That does not work.
Both of the above have constant complexity, since they are simple arithmetic operations (std::distance() is optimized for random-access iterators, like raw pointers and std::array iterators).
Alternatively, you can use actual iterators instead, but that requires iterating through the array to get an iterator to the desired element without knowing its index beforehand, eg:
auto iter = std::find_if(std::begin(my_array), std::end(my_array), [=](Object &o) { return (&o == ptr_object); });
size_t index = std::distance(my_array.begin(), iter);
A:
I would advise against gratuitous use of std::distance, unless it is a requirement in your case.
std::distance is an interface-unifying function, whose purpose is to allow one to calculate distances between various kinds of iterators: random-access, bidirectional, forward etc. This function is intended to conceal the inefficiency of directly calculating the distance for non-random-access iterators, in situations where you really know what you are doing and really want to accept that inefficiency. It is intended to stand out in your code (like a cast), signalling the fact that in general case the code might be inefficient, but you are willing to accept that at least for now, like in temporary "sketch" code. (The same applies to std::advance).
If you do not intend to "hide" the inefficiency, i.e. you intend your code to work with random-access iterators only, don't use std::distance. Just subtract the iterators
std::ptrdiff_t i = ptr_object - my_array.data();
| {
"pile_set_name": "StackExchange"
} |
Q:
How to render Markdown using Node.js Express, Mongo and Markdown-it?
I am entirely new to the world of markdown and trying to get my head around it.
I hacked together a basic node Express app. It is reading some sample markdown text from a mongodb database, then using markdown-it middleware to process the markdown.
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var fs = require('fs');
var path = require('path');
var md = require('markdown-it')({
html: true,
linkify: true,
typographer: true
});
var app = express();
app.set('views', path.resolve(__dirname, 'views'));
app.set('view engine','ejs');
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/mdtest1", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
app.use('/2',function(req,res){
MongoClient.connect("mongodb://localhost:27017/mdtest1", function(err, db) {
var collection2 = db.collection('mdcol');
var ObjectId = require('mongodb').ObjectId;
var o_id = new ObjectId('58f273ae624c4d435c632fa0');
collection2.findOne({}, function(err, document) {
//console.log(document.body);
console.log('--------------------------------------------------')
var result = md.render(document.body);
console.log(result);
res.render('md', {
'main': result
});
});
});
});
app.listen(3000);
My question is: how do I render this in a template? I am using ejs templating where the following variable is displayed:
<%= main %>
Bu this displays HTML as text on the page.
What am I doing wrong? Thanks!
A:
<%= main %> would escape the html.
Using <%- main %> would also parse the html in your variable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Indexing every WHERE column?
I tried to turn on MYSQLI_REPORT_ALL | MYSQLI_REPORT_STRICT and now MySQL tells me:
No index used in query/prepared statement...
in some of my app's queries.
Is it really best practice to index every WHERE column I'll possibly use so that MySQL will not complain? Seems a bit overkill to me as there are probably some columns where I'll only use the WHEREclause occasionally.
A:
Turn on those flags only for initial development. They are too noisy with false alarms otherwise.
There are valid cases for queries that do not use indexes.
There are cases (such as EAV) where it is impractical to have indexes for every possible query.
I prefer to turn on the slowlog with a low value for long_query_time, and later gather what queries are the "worst". This is a much better list of queries to work on improving. It may include some slow queries with the best possible index, and exclude some very fast queries that don't involve any index.
Do not blindly index every column. Learn about "composite" indexes.
See my Cookbook on creating optimal indexes for basic queries.
| {
"pile_set_name": "StackExchange"
} |
Q:
Barcodescanner cordova with led light
I used plugin com.phonegap.plugins.barcodescanner to create app scan qr code
but i can't turn on led light in device when Scan
how to solve the problem
Thanks all you help!
A:
I found a solution.
When you scan, if you want the LED light on, just increase the volume. If want the LED light off, decrease the volume
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic validation based on conditions
Scenario: I have 4 form fields.
Description (Optional)
Select Type (Required)
Phone (Required only if Select Type is set to 'Phone')
Email (Required only if Select Type is set to 'Email')
When I change anything is Select Type field, based on the selection, Phone field or Email field will be visible. I need to validate these fields.
Problem:
When the form loads, it'll have only description, select type dropdown and save button.
Step 1: Click save button without entering any input, should throw an alert saying Select Type is required and select type will be red.
Step 2: Select a type, the next input becomes visible with red border. This should not happen since the user didn't touched the field. How can I solve this?
Code:
Stackblitz code
html
<div class="example-container">
<form [formGroup]="groupForm" (ngSubmit)="onSubmit()">
<section>
<section class="input-row">
<mat-form-field>
<input matInput type="test" placeholder="Description" id="description" formControlName="description"/>
</mat-form-field>
</section>
<section class="input-row">
<mat-form-field>
<mat-select id="sourceType" formControlName="sourceType" placeholder="Select Type*">
<mat-option value="phone">Phone</mat-option>
<mat-option value="email">Email</mat-option>
</mat-select>
</mat-form-field>
</section>
<section *ngIf="typeIsPhone" class="input-row">
<mat-form-field>
<input matInput type="number" placeholder="Phone" id="phoneValue" formControlName="phoneValue"/>
</mat-form-field>
</section>
<section *ngIf="typeIsEmail" class="input-row">
<mat-form-field>
<input matInput type="email" placeholder="Email" id="emailValue" formControlName="emailValue"/>
</mat-form-field>
</section>
</section>
<button mat-raised-button color="primary" type="submit" class="save">
Save
</button>
</form>
</div>
component:
export class FormFieldOverviewExample implements OnInit {
typeIsPhone = false;
typeIsEmail = false;
public groupForm: FormGroup = new FormGroup({
description: new FormControl(""),
sourceType: new FormControl("", [Validators.required]),
phoneValue: new FormControl("", [Validators.required]),
emailValue: new FormControl("", [Validators.required])
});
constructor() {}
ngOnInit(): void {
this.groupForm
.get("sourceType")
.valueChanges.subscribe(this.setSourceType.bind(this));
}
setSourceType(SourceType: string) {
this.typeIsPhone = SourceType === "phone";
this.typeIsEmail = SourceType === "email";
}
onSubmit() {
const sourceTypeFormControl = this.groupForm.get("sourceType");
const phoneEnteredFormControl = this.groupForm.get("phoneValue");
const emailEnteredFormControl = this.groupForm.get("emailValue");
if (sourceTypeFormControl.errors.required) {
alert("Source Type is required!");
return;
} else {
if (phoneEnteredFormControl.errors.required) {
alert("Phone is required!");
return;
}
if (emailEnteredFormControl.errors.required) {
alert("email is required!");
return;
}
}
}
}
A:
As if a FormControl is disabled don't has errors I suggest another aproach using disable and enable that you can see in this stackblitz
ngOnInit(): void {
const control=this.groupForm.get("sourceType")
if (control)
control.valueChanges.pipe( //Use startWith to execute at first
startWith(control.value)
).subscribe(res=>this.setSourceType(res)); //<--see how pass the value
}
setSourceType(SourceType: string) {
this.typeIsPhone = SourceType === "phone";
this.typeIsEmail = SourceType === "email";
const phoneControl=this.groupForm.get('phoneValue')
const emailControl=this.groupForm.get('emailValue')
if (phoneControl)
phoneControl[SourceType==='phone'?'enable':'disable']() //(*)
if (emailControl)
emailControl[SourceType==='email'?'enable':'disable']()
}
//(*) is a abreviated way to say
// if (SourceType=='phone')
// phoneControl.enable()
// else
// phoneControl.disable()
NOTE:
//You can not use
if (phoneEnteredFormControl.errors.required) //WRONG
//use
if (phoneEnteredFormControl.errors && phoneEnteredFormControl.errors.required) //OK
| {
"pile_set_name": "StackExchange"
} |
Q:
JS files not referenced in the application
I have jsp page inside which am calling my xhtml page. Am mapping xhtml to facesServlet and have all resource servlet active so it maps all js and css file fine, if i hit xhtml page.
If I hit jsp page then those files are not referenced firebug pops out all sorts of js errors.
To work around, i added js and css files to web folder and am including and tried them including in xhtml as well as jsp page but those are not referenced and as of now, if i directly hit xhmtl page then file upload works fine but if i go and hit jsp page then end up getting js errors, is there any other way of getting js file included.
Here is how am referencing my js files
<%@ include file="/common/taglibs.inc" %>
<html>
<head>
<link rel="stylesheet" href="/css/Main.css" type="text/css">
<link rel="stylesheet" href="/css/Admin.css" type="text/css">
<link rel="stylesheet" href="/css/Home.css" type="text/css">
<script type="text/javascript" src="/js/icefaces/ace-jquery.js"/>
<script type="text/javascript" src="/js/icefaces/ace-components.js"/>
<script type="text/javascript" src="/js/icefaces/icepush.js"/>
<script type="text/javascript" src="/js/icefaces/bridge.js"/>
<script type="text/javascript" src="/js/icefaces/compat.js"/>
<script type="text/javascript" src="/js/icefaces/fileEntry.js"/>
<script type="text/javascript" src="/js/icefaces/jsf.js"/>
<script type="text/javascript" src="/js/icefaces/icefaces-compat.js"/>
<!-- BEGIN SCRIPT TO OPEN RIGHT NOW HELP POPUP, THIS SCRIPT INCLUDES THE FUNCTION OPENRN-->
<
%@ include file="/js/popupRightNow.inc" %>
<!-- END SCRIPT TO OPEN RIGHT NOW HELP POPUP, THIS SCRIPT INCLUDES THE FUNCTION OPENRN-->
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<jsp:include page="/navigation/TopNav.jsp" flush="true"/>
<jsp:include page="/trade_entry/UploadBlotter.xhtml"/>
<!--BEGIN BOTTOM NAV -->
<jsp:include page="/navigation/BottomNav.jsp" flush="true"/>
<!--END BOTTOM NAV -->
</body>
</html>
Any thoughts, suggestions?
Update:
I have requirement of creating new pages using jsf2 and i have created xhtml page but i want to get my application header and footer themes and those are defined in jsp now I tried looking for integrating jsp into xhtml but it was rightly suggested that one must not do it.
Tried How to include a JSP page in a Facelets page? but that didn't work either as my tags were not recognized and so finally tried creating jsp page and included xhtml page inside it and that seemed to work but not 100%.
So as it stands right now if i hit xhtml page directly then it works but if i hit jsp page with header/footer information then icefaces or say jsf stuffs doesn't work 100%, hope am able to clarify what am trying to achieve.
Update 2
js file from javax.faces.resources are referenced fine on xhtml page but are not referenced on jsp page.
A:
It's the webbrowser who has got to download those JS/CSS files. It's not the server who has got to load/include those JS/CSS files.
So, the path which you specified in src and href attributes are resolved relative to the current request URL as you see in browser's address bar. They are not resolved relative to the location of the JSP file in the public webcontent.
So, if you happen to have a context path in the request URL like so
http://localhost:8080/somecontextpath/page.jsp
then for example your <link href="/css/Main.css"> would be downloaded by the webbrowser from the following URL
http://localhost:8080/css/Main.css
while it should actually have been
http://localhost:8080/somecontextpath/css/Main.css
Fix it accordingly.
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/Main.css" type="text/css">
Or if you're using Facelets
<link rel="stylesheet" href="#{request.contextPath}/css/Main.css" type="text/css">
Or if you're using JSF 2 <h:outputStylesheet> (and <h:outputScript> components)
<h:outputStylesheet name="css/Main.css" />
(and put the /css and /js folders in /resources subfolder of public webcontent)
By the way, the following line makes absolutely no sense:
<jsp:include page="/trade_entry/UploadBlotter.xhtml"/>
You're mixing view technologies here. You can't include the one in the other. Facelets is the successor of JSP. Use the one or the other. You can mix them in 1 webapp, but not in 1 view.
| {
"pile_set_name": "StackExchange"
} |
Q:
SELECT between dynamically queried rows
Let's say I have a book table:
CREATE TABLE book (
-- NOTE: the app guarantees that content is ordered by id
id INTEGER PRIMARY KEY,
section TEXT NOT NULL,
verse INTEGER NOT NULL,
content TEXT NOT NULL
);
INSERT INTO book (id, section, verse, content) VALUES
(0, "Prelude", 0, "A long long time ago"),
(1, "Prelude", 1, "I can still remember"),
(2, "Chap", 0, "Something happened"),
(3, "Chap", 1, "Something else happened"),
(4, "Chap", 2, "A weighty climax"),
(5, "End", 0, "The end")
;
I want to be able to query for all verses with within a starting verse and chapter with only one SQL query. I can do that with the following SQL:
SELECT id, content
FROM book
WHERE
id BETWEEN
(SELECT id FROM book WHERE section == "Prelude" AND verse == 1 LIMIT 1)
AND
(SELECT id FROM book WHERE section == "Chap" AND verse == 2 LIMIT 1)
λ sqlite3 :memory: < tmp.sql
id content
---------- --------------------
1 I can still remember
2 Something happened
3 Something else happe
4 A weighty climax
That involves 2 subqueries, and I'm not sure it's the best way. Can I improve this query to not have the subqueries (with the idea that fewer subqueries are more efficient)?
A:
The code after the BETWEEN clause is scanning twice the table to return the 2 ids. But also there is another problem:
do you know in advance which id is the smallest and which is the highest?
If not (probably) then you can't safely set each of the returned ids before or after AND.
For example if you do this:
id BETWEEN
(SELECT id FROM book WHERE section == "Chap" AND verse == 2 LIMIT 1)
AND
(SELECT id FROM book WHERE section == "Prelude" AND verse == 1 LIMIT 1)
nothing will be returned.
So you must set the min id as the lower bound and the max id as the upper bound.
Use a CTE so the table will be scanned only once to get the starting and ending ids:
WITH cte AS (
SELECT MIN(id) AS fromId, MAX(id) AS toId FROM book
WHERE (section = "Prelude" AND verse = 1) OR (section = "Chap" AND verse = 2)
)
SELECT id, content
FROM book
WHERE id BETWEEN (SELECT fromId FROM cte) AND (SELECT toId FROM cte)
See the demo.
Or with a CROSS JOIN with the CTE:
WITH cte AS (
SELECT MIN(id) AS fromId, MAX(id) AS toId FROM book
WHERE (section = "Prelude" AND verse = 1) OR (section = "Chap" AND verse = 2)
)
SELECT b.id, b.content
FROM book AS b CROSS JOIN cte AS c
WHERE b.id BETWEEN c.fromId AND c.toId
See the demo.
Results:
| id | content |
| --- | ----------------------- |
| 1 | I can still remember |
| 2 | Something happened |
| 3 | Something else happened |
| 4 | A weighty climax |
| {
"pile_set_name": "StackExchange"
} |
Q:
Как сгрупировать одно поле многомерного массива?
Есть массив вида:
array:4 [▼
0 => array:7 [▼
"answer_schema_id" => "1"
"content" => "odpowiedz 1"
"locale" => "pl"
"points" => "3"
"answerKey" => "1"
"answerElementOrder" => "1"
"image" => "5cd143beba821203428009.jpg"
]
1 => array:7 [▼
"answer_schema_id" => "1"
"content" => "answer 1"
"locale" => "en"
"points" => "3"
"answerKey" => "1"
"answerElementOrder" => "1"
"image" => "5cd143beba821203428009.jpg"
]
2 => array:7 [▼
"answer_schema_id" => "2"
"content" => "answer 2"
"locale" => "en"
"points" => "2"
"answerKey" => "2"
"answerElementOrder" => "2"
"image" => "5cd143bebcdfc405126844.jpg"
]
3 => array:7 [▼
"answer_schema_id" => "2"
"content" => "odpowiedz 2"
"locale" => "pl"
"points" => "2"
"answerKey" => "2"
"answerElementOrder" => "2"
"image" => "5cd143bebcdfc405126844.jpg"
]
]
Нужно получить следующий массив:
array:4 [▼
0 => array:7 [▼
"answer_schema_id" => "1"
"content" => [
"pl" => 'odpowiedz 1',
"en" => 'answer 1'
]
"points" => "3"
"answerKey" => "1"
"answerElementOrder" => "1"
"image" => "5cd143beba821203428009.jpg"
],
1 => array:7 [▼
"answer_schema_id" => "2"
"content" => [
"pl" => 'odpowiedz 2',
"en" => 'answer 2'
]
"points" => "2"
"answerKey" => "2"
"answerElementOrder" => "2"
"image" => "5cd143bebcdfc405126844.jpg"
]
]
Но так у меня получается массив только с 1м ключом.
Вот мой код:
$new = [];
foreach ($data as $key => $datum){
if(empty($new)){
$new[] = $datum;
unset($new[0]['content']);
}
foreach ($new as $keyz => $item){
if($item['answer_schema_id'] == $datum['answer_schema_id']){
$new[$keyz]['content'][$datum['locale']] = $datum['content'];
}
}
}
Прошу помощи в решении данной проблемы
A:
Вроде бы можно как-то вот так:
// Исходный массив
$srcArray = [
0 => [
"answer_schema_id" => "1",
"content" => "odpowiedz 1",
"locale" => "pl",
"points" => "3",
"answerKey" => "1",
"answerElementOrder" => "1",
"image" => "5cd143beba821203428009.jpg",
],
1 => [
"answer_schema_id" => "1",
"content" => "answer 1",
"locale" => "en",
"points" => "3",
"answerKey" => "1",
"answerElementOrder" => "1",
"image" => "5cd143beba821203428009.jpg",
],
2 => [
"answer_schema_id" => "2",
"content" => "answer 2",
"locale" => "en",
"points" => "2",
"answerKey" => "2",
"answerElementOrder" => "2",
"image" => "5cd143bebcdfc405126844.jpg",
],
3 => [
"answer_schema_id" => "2",
"content" => "odpowiedz 2",
"locale" => "pl",
"points" => "2",
"answerKey" => "2",
"answerElementOrder" => "2",
"image" => "5cd143bebcdfc405126844.jpg",
]
];
// Результат
$result = [];
// Группировка
foreach ($srcArray as $item)
{
if(empty($result[$item['answer_schema_id']]))
{
$result[$item['answer_schema_id']] = [
"answer_schema_id" => $item['answer_schema_id'],
"content" => [
$item['locale'] => $item['content'],
],
"points" => $item['points'],
"answerKey" => $item['answerKey'],
"answerElementOrder" => $item['answerElementOrder'],
"image" => $item['image'],
];
}else{
$result[$item['answer_schema_id']]['content'][$item['locale']] = $item['content'];
}
}
$result = array_values($result);
| {
"pile_set_name": "StackExchange"
} |
Q:
Reader read the right words from the wrong day of Chanukah. Must he repeat?
Is the Torah reader required to read the correct portion on Chanukah in the following or similar circumstance?
It is the second day of Chanukah.
The reader correctly reads the Cohen's portion starting with
יח) בַּיּוֹם, הַשֵּׁנִי, הִקְרִיב, נְתַנְאֵל בֶּן-צוּעָר--נְשִׂיא, יִשָּׂשכָר)
When he comes to read the Levi's portion, instead of reading
כא) פַּר אֶחָד בֶּן-בָּקָר, אַיִל אֶחָד כֶּבֶשׂ-אֶחָד בֶּן-שְׁנָתוֹ--לְעֹלָה).
and on to the end of the parsha, he starts reading the equivalent possukim for the next day,
כז) פַּר אֶחָד בֶּן-בָּקָר, אַיִל אֶחָד כֶּבֶשׂ-אֶחָד בֶּן-שְׁנָתוֹ--לְעֹלָה)
and then corrects himself before the end and ends up with the correct nosi.
He has read one or two wrong pessukim, but the words were right. Does he have to repeat by reading the right words or is this a case of טרחה דצבורה - inconvenience to the community and it is not necessary to repeat?
A:
The mishna berura deals with this issue in סימן תרפד סעיף קטן ג at the end. If someone read the nasi for the third day on the second day (or the like) then he is still yotzai (עלתה להם) because we are not makpid on the day. אין קפידה ליום. The magid shiur added on this that since he is yotzei reading the complete wrong day (even kohen) then just reading the wrong Levi would be OK.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to prove with induction
So far I have learned how to write proofs by induction and it went fine until I got this recursive problem, which I'm not quite sure how to begin and how to prove that with induction.
P(2·a,⌊b/2⌋) : b>1 and b is even number
P(a,b):= P(2·a,⌊b/2⌋)+a : b>1 and b is odd number
a :b=1
to prove is for all a,b ∈ N+ -> P(a,b)=a·b
Please don't show me the proof but how to deal with this kind of question.
Thank you
A:
The first step is the basis step (or base case). For this problem, that is when $b = 1$. We identify that as the base case because $P(a, b)$ is a piece-wise function, and the non-recursive case is the base case. So prove that $P(a,b) = ab$ when $b=1$.
The inductive step will be a proof by cases because there are two recursive cases in the piecewise function: $b$ is even and $b$ is odd. Prove each separately.
The induction hypothesis is that $P(a,b_0) = ab_0$. You want to prove that $P(a,b_0+1)=a(b_0+1)$.
For the even case, assume $b_0 > 1$ and $b_0$ is even. Then show that $P(a,b_0+1)=P(2·a,⌊(b_0+1)/2⌋)=a(b_0+1)$. Prove this with a substitution based on the induction hypothesis.
After you complete the proof for the even case, do the same for the odd case.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to handle a syntactically valid but logically invalid argument passed to the constructor?
I need to make a class Expr having public interface like this:
class Expr{
//...
public:
Expr(const char*);
int eval(); //Evaluates the expression and gives the result
void print();
};
In the design, if user enters an invalid string to construct an Expr object like "123++233+23/45", would it be right to construct the Object initially and notify the error when eval() is called on that object.
Or the error should be checked at that point itself and en exception be thrown, though that would lead to serious increase in runtime. And the user may write code furthur with assumption that Object is created and will discover the error at runtime only..
Such problems arise always in creating a class, is there a rather standard way to handle such errors made at user's part????
A:
The only standard part about how you do this is thorough documentation.
I prefer throwing the errors as early as possible, or using a factory for objects of this type - objects that require specific arguments to be initialized. If you use a factory, you can return a NULL or a nullptr or whatever.
I don't see the point in constructing the object and returning an error only when eval() is called. What's the point? The object is invalid anyway, why wait until you use it?
and an exception be thrown, though that would lead to serious increase
in runtime.
Have you profiled this? Don't not use exceptions because you assume increase in runtime.
A:
class illogical_expression_exception : public virtual exception {};
class Expr{
//...
int result; // store evaluated result.
public:
explicit Expr(const char*);
int getResult(); // Evaluate & Parse in the Constructor.
void print();
};
/* in constructor */
if ( ! checkExpression(expr) ) throw illogical_expression_exception();
/* in main() */
try{ Expr my_expr("2+2*2"); }
catch(const illogical_expression_exception& e){
cout << "Illogical Expression." << endl;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How display Yii2 pagination in GridView widget on and top and bottom part of table?
How display Yii2 pagination in GridView widget on and top and bottom part of table
A:
Add this in GridView widget configuration:
'layout' => "{summary}\n{pager}\n{items}\n{pager}",
| {
"pile_set_name": "StackExchange"
} |
Q:
About $e^{i z} = \cos z + i \sin z$ in Michael Spivak "Calculus 3rd Edition".
I am reading "Calculus 3rd Edition" by Michael Spivak.
The author wrote as follows (p. 555):
Moreover, if we replace $z$ by $i z$ in the series for $e^z$, and make a rearrangement of the terms (justified by absolute convergence), something particularly interesting happens:
$$e^{i z} = 1 + i z + \frac{(iz)^2}{2!} + \frac{(iz)^3}{3!} + \frac{(iz)^4}{4!} + \frac{(iz)^5}{5!} + \cdots \\
=1 + iz - \frac{z^2}{2!} - \frac{i z^3}{3!} + \frac{z^4}{4!} + \frac{i z^5}{5!} + \cdots \\
= (1 - \frac{z^2}{2!} + \frac{z^4}{4!} - \cdots) + i (z - \frac{z^3}{3!} + \frac{z^5}{5!} + \cdots),$$
so $$e^{i z} = \cos z + i \sin z.$$
But I think the author didn't use a rearrangement of the terms at all.
Am I right?
Let
$$c_n := 1 - \frac{z^2}{2!} + \frac{z^4}{4!} - \cdots + (-1)^n \frac{z^{2 n}}{(2 n)!},$$
$$s_n := z - \frac{z^3}{3!} + \frac{z^5}{5!} - \cdots + (-1)^n \frac{z^{2 n + 1}}{(2 n + 1)!},$$
$$e_n := 1 + i z + \frac{(iz)^2}{2!} + \frac{(iz)^3}{3!} + \frac{(iz)^4}{4!} + \frac{(iz)^5}{5!} + \cdots + \frac{(iz)^n}{n!}.$$
Then, $$e_{2 n + 1} = c_n + i s_n,$$
$$\lim_{n \to \infty} e_{2 n + 1} = e^{i z},$$
$$\lim_{n \to \infty} c_n + i s_n = \lim_{n \to \infty} c_n + i \lim_{n \to \infty} s_n = \cos z + i \sin z,$$
so $$e^{i z} = \cos z + i \sin z.$$
A:
Your statement:
But I think the author didn't use a rearrangement of the terms at all.
He did re-arrange the terms as said...See:
| {
"pile_set_name": "StackExchange"
} |
Q:
Maximizing entropy inside integers array
I have an array as follow 44477125, and I would like to maximize the entropy so that the maximum of n-tuple be scattered.
A result example would be 74574214.
This problem seems to be NP-Complete and I don't really have a function to measure the "entropy" of my array. (It could be the sum of distance between same numbers entropy(44477125)=3, entropy(74574214)=9)
What I'm looking for is an heuristic which could give me an acceptable result in a polynomial time.
A:
Algorithm
Using entropy measured as sum of distance between same numbers, there exists very simple polynomial-time algorithm:
Count number of occurrences of each number.
Sort pairs < number,ocurrences > descending by occurrences.
Create empty table of the same size as input.
For each pair< number, ocurrences >:
a) get maximum_possible_distance = array_size/occurrences
b) insert all occurrences of number in following indexes: 0*maximum_possible_distance, 1*maximum_possible_distance, 2*maximum_possible_distance, etc. If index is already taken, use the nearest empty index.
Example
Input array: 44477125
1.Counting occurrences:
<4 - 3>, <7 - 2>, <1 - 1>, <2 - 1>, <5 - 1>
2.Sorting pairs < number - occurrences >
It is already sorted.
3.Create empty table:
. . . . . . . .
4.Insert occurrences:
a) 1st pair <4 - 3> : maximum_possible_distance=8/3=2
b) insert occurrences: we have: 4..4..4.
c) 2nd pair <7 - 2> : maximum_possible_distance=8/2=4
d) insert occurrences: we have: 47.4.74.
e) 3rd pair <1 - 1> : maximum_possible_distance=8/1=8
f) insert occurrences: we have: 4714.74.
g) 4th pair <2 - 1> : maximum_possible_distance=8/1=8
h) insert occurrences: we have: 4714274.
i) 5th pair <5 - 1> : maximum_possible_distance=8/1=8
j) insert occurrences: we have: 47142745
| {
"pile_set_name": "StackExchange"
} |
Q:
lambda arguments unpack error
In Python 2 this code is OK:
f = lambda (m, k): m + k
m = [1,2,3,4]
k = [5,6,7,8]
print(map(f, zip(m, k)))
but in Python 3 the following error occurred:
f = lambda (m, k): m + k
^
SyntaxError: invalid syntax
If I remove parentheses in lambda expression then another error occurred:
TypeError: <lambda>() missing 1 required positional argument: 'k'
Also approach with tuple as single lambda argument works in Python 3, but it's not clear (hard for reading):
f = lambda args: args[0] + args[1]
How can I unpack values in the right way in Python 3?
A:
The removal of tuple unpacking is discussed in PEP 3113. Basically, you can't do this in Python 3. Under the headline Transition plan, you see that the "suggested" way of doing this is as your final code block:
lambda x_y: x_y[0] + x_y[1]
A:
You can use the same syntax in both Python 2 and Python 3 if you use itertools.starmap instead of map which unpacks the tuple items for us:
>>> from itertools import starmap
>>> f = lambda m, k: m + k
>>> list(starmap(f, zip(m, k)))
[6, 8, 10, 12]
A:
You cannot use parentheses in Python3 to unpack arguments in lambda functions (PEP 3113), Try:
f = lambda m, k: m + k
To make it work with your code, you should use:
lambda mk: mk[0] + mk[1]
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery File Upload - configuring and running
I'm using this plugin: jQuery File Upload
My HTML:
<input id="fileupload" type="file" name="files[]" data-url="upload.php" multiple>
<script src="/js/vendor/jquery.ui.widget.js"></script>
<script src="/js/jquery.iframe-transport.js"></script>
<script src="/js/jquery.fileupload.js"></script>
<script src="http://blueimp.github.com/JavaScript-Load-Image/load-image.min.js"></script>
<script src="http://blueimp.github.com/JavaScript-Canvas-to-Blob/canvas-to-blob.min.js"></script>
<script src="/js/jquery.fileupload-fp.js"></script>
<div id="dropzone" class="fade well">Drop files here</div>
My JS:
$(document).ready(function() {
$('#fileupload').fileupload({
dataType: 'json',
dropZone: $('#dropzone'),
singleFileUploads: false,
add: function (e, data) {
$(this).fileupload('process', data).done(function () {
data.submit();
});
},
done: function (e, data) {
$.each(data.result, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
},
process: [
{
action: 'load',
fileTypes: /^image\/(gif|jpeg|png)$/,
maxFileSize: 20000000 // 20MB
},
{
action: 'resize',
maxWidth: 1920,
maxHeight: 1080
},
{
action: 'save'
}
]
});
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
// The example input, doesn't have to be part of the upload form:
var GAL = $('#galleryId');
data.formData = {
galleryId: GAL.val(),
type: 'gallery',
entityId: 1
}
return true;
});
$(document).bind('dragover', function (e) {
var dropZone = $('#dropzone'),
timeout = window.dropZoneTimeout;
if (!timeout) {
dropZone.addClass('in');
} else {
clearTimeout(timeout);
}
if (e.target === dropZone[0]) {
dropZone.addClass('hover');
} else {
dropZone.removeClass('hover');
}
window.dropZoneTimeout = setTimeout(function () {
window.dropZoneTimeout = null;
dropZone.removeClass('in hover');
}, 100);
});
$(document).bind('drop dragover', function (e) {
e.preventDefault();
});
});
Things I'd love to achieve:
Resizing images at client side
Then send images with additional form data (data are not comming to server side script) to upload.php
Thanks a lot in advance.
A:
Jquery File upload is not the right choice for my request. I'm now successfully using Plupload.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dart Map Key Type Safety
I've implemented enums as keys for my maps, but I'm finding that Dart doesn't provide type safety when retrieving values.
For example, the following code does not cause compilations errors:
enum Animal {Bird, Cat, Dog, Horse}
Map<Animal, String> petNames = {
Animal.Bird: 'Lucky',
Animal.Cat: 'Cleo',
Animal.Dog: 'Spot',
Animal.Horse: 'Sleven',
};
String birdName = petNames[Animal.Bird]; // Positive test
String catName = petNames[1]; // What I want to test
String dogName = petNames['two']; // My control, I expected a compilation error
print(birdName); // Output as expected: Lucky
print(catName); // Output is null
print(dogName); // Output is null
Is this a defect in Dart?
A:
No, its not a bug. Here you can check what are you calling when you execute something like petNames[1] or petNames['two']. Internally, Dart takes the value inside square brackets as an Object because you are using the [] operator.
When you check the Map definition, you can see that is defined as a Generic Type (with parameters K and V). For example when you assign some value to some key on that map:
petNames[Animal.Bird] = 'New Bird Name'
You are using the operator []= and that operator call a function isValidKey() to check if the key (Animal.Bird in the example) is of type K (Animal) and the value ('New Bird Name' in the example) is of type V (String).
But isValidKey() function is not called when you use the [] operator.
So, as in Dart all is an Object, and the [] operator get as input an Object, when you call petNames['two'], Dart will try to find that key, even if it is not of type K.
For more information please check the links above and this issue on Dart Lang SDK.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the three marks of existence?
What are the three marks of existence and where are they found in the canon? Is there any fundamental differences in interpretation among the different traditions?
A:
The Three characteristics of existence are part of the core teaching of the Buddha and found throughout his teachings. In essence every single compound (i.e. made of the 5 aggregates and/or the four elements) thing has these characteristics inherent in their very existence.
When one realizes with their own experiential knowledge that all things we have attachments and aversions to have at their core these three characteristics, then there is nothing to cling to, nothing to run from, there is just peace.
We understand that everything, from the universe itself down to ourselves and our loved ones are subject to change and decay(impermanence). We understand that every compound thing is subject to and can be part of the cause of Dukkha(unsatisfactoriness/suffering). Because of our attachments and aversions, nothing created can bring lasting happiness. And Thirdly we understand that there can be found nothing that we can truly identify as "self". What we take to be self is not-self. There is no inherent permanent self/identity in anything created, the "self" we take to be us is merely a coming together of the 5 aggregates (form, feeling, perception, mental formations, consciousness), processes that come into being, and eventually decay.
As far as I know( and I'd love to be proven wrong on this if anyone can link it) there is no one grand sutta solely on this specific topic, but it is inherently at the core of all of the teachings and therefore pervades the whole cannon. I agree with what Catpnosis said about there being no fundamental differences, but differences in interpretation and usage as part of the various paths.
Here are a few Suttas regarding the three characteristics:
Dhamma-niyama Sutta: The Discourse on the Orderliness of the Dhamma
"Monks, whether or not there is the arising of Tathagatas, this property stands — this steadfastness of the Dhamma, this orderliness of the Dhamma: All processes are inconstant.
"Whether or not there is the arising of Tathagatas, this property stands — this steadfastness of the Dhamma, this orderliness of the Dhamma: All processes are stressful.
"Whether or not there is the arising of Tathagatas, this property stands — this steadfastness of the Dhamma, this orderliness of the Dhamma: All phenomena are not-self.
And from the Dhammapada:
Maggavagga: The Path
"All conditioned things are impermanent" — when one sees this with wisdom, one turns away from suffering. This is the path to purification.
"All conditioned things are unsatisfactory" — when one sees this with wisdom, one turns away from suffering. This is the path to purification.
"All things are not-self" — when one sees this with wisdom, one turns away from suffering. This is the path to purification.
I think this passage from the Maha-parinibbana Sutta speaks volumes about understanding impermanence:
Then, when the Blessed One had passed away, some bhikkhus, not yet freed from passion, lifted up their arms and wept; and some, flinging themselves on the ground, rolled from side to side and wept, lamenting: "Too soon has the Blessed One come to his Parinibbana! Too soon has the Happy One come to his Parinibbana! Too soon has the Eye of the World vanished from sight!"
But the bhikkhus who were freed from passion, mindful and clearly comprehending, reflected in this way: "Impermanent are all compounded things. How could this be otherwise?"
Of course Dukkha is all over the teachings.. heck it's the first noble truth:
"Now this, monks, is the Noble Truth of dukkha: Birth is dukkha, aging is dukkha, death is dukkha; sorrow, lamentation, pain, grief, & despair are dukkha; association with the unbeloved is dukkha; separation from the loved is dukkha; not getting what is wanted is dukkha. In short, the five clinging-aggregates are dukkha."
And about not-self:
Anatta-lakkhana Sutta: The Discourse on the Not-self Characteristic
"Bhikkhus, form is not-self. Were form self, then this form would not lead to affliction, and one could have it of form: 'Let my form be thus, let my form be not thus.' And since form is not-self, so it leads to affliction, and none can have it of form: 'Let my form be thus, let my form be not thus.'
"Bhikkhus, feeling is not-self...
"Bhikkhus, perception is not-self...
"Bhikkhus, determinations are not-self...
"Bhikkhus, consciousness is not self. Were consciousness self, then this consciousness would not lead to affliction, and one could have it of consciousness: 'Let my consciousness be thus, let my consciousness be not thus.' And since consciousness is not-self, so it leads to affliction, and none can have it of consciousness: 'Let my consciousness be thus, let my consciousness be not thus.'
A:
According to one hypothesis, the Three Marks of Existence are Buddha's sarcastic response to Hinduism's Sat-Cit-Ananda, the three characteristics of Brahman experienced by an awakened yogi:
Sat -- true and timeless, not subject to change.
Chit -- self-aware.
Ananda -- blissful or happy.
Supposedly, when yogi becomes one with Brahman, he perceives Himself as infinite and timeless self-aware Universe. From this moment on, all of yogi's experiences are marked with perpetual bliss.
When Buddha awakened to the way things are, he realized that the above description was rather misleading, because it made the practitioner seek permanent bliss, something impossible in principle. Out of compassion for future seekers, he offered a more realistic description of the same Universal vision:
Whatever is compound (consists of multiple pieces coming together), will fall apart. Same way, whatever is conditional (depends on multiple factors coinciding together), is impermanent.
Nothing is solid, everything is made of pieces or depends on conditions. This includes "I" which cannot possibly be a solid/independent entity. Since "I" is really just a compound phenomena, it is not independent and too is subject to conditions. What we call "consciousness" is too an interplay of conditions and not a substance or entity.
Because of the above, there is no (and there can't be!) such thing as permanent Sukha ("ease", "comfort"). Dukkha ("wrongness", "trouble") is an inevitable part of existence at large. ("At large" is the key word here. As to personal liberation from suffering, Buddha addressed this question in his Four Truths of The Nobles.)
Buddha criticized simple naive non-dualism of Brahmins, as returning to the same limiting concept of "I" they supposedly wanted to escape. He compared "I" to a stick their mind was tied to, going around but never completely departing. This said, Buddha still held "the state of Brahma" (experience of non-dual unity with the world) as a useful intermediate realization (AN 4.190).
In an interesting twist, my present teacher, who comes from a Taoism-influenced non-sectarian tradition, speaks of Three Gates To Enlightenment, the experiential realizations one must go through on one's way to Completion:
Pain or Suffering. One must realize that life is painful and accept pain as necessary condition for one's growth. This involves dropping resistance that comes from seeing pain as important factor of one's decisions.
Impermanence or Transience. One must fully accept that nothing is permanent in one's life, and admit the inevitability of death. This involves dropping attachments to what one holds as dear.
Nothingness or Voidness. One must go through the realization that life is pointless and has no meaning in the absolute sense. This involves dropping fundamental preconceptions or imperatives about the purpose of one's life.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to toggle a hidden ul by clicking a link with jquery
I have following code created dynamically with php.
What I want to do is when I click class='toggle' with href of desc76, I want to show ul with id desc76.
also I want to change arrowdown16.png to arrowup16.png.
Then when I click it, ul will fadeOut or hidden again.
class, secondul has CSS display:hidden;.
I tried this, but it does not work.
$(".toggle").click(function () {
event.preventDefault();
var id = "#"+$(this).attr('href')
$("id").show("slow");
});
HTML:
<ul>
...
...
<li class='toggledetail'>
Show Details
<div>
<a href='desc76' class='toggle' >
<img src="http://blablabla.com/assets/icons/arrowdown16.png" alt="arrowdown16" title="Show Details" /></a>
</div>
</li>
</ul>
<ul class='secondul' id='desc76'>
<li class='listdetail'>Spec Details<div>0</div>
</li>
</ul>
<li class='toggledetail'>
Show Details<div>
<a href='desc75' class='toggle' >
<img src="blablabla.com/assets/icons/arrowdown16.png" alt="arrowdown16" title="Show Details" /></a>
</div>
</li>
</ul>
<ul class='secondul' id='desc75'>
<li class='listdetail'>Spec Details<div>0</div>
</li>
</ul>
... Here comes more ul
...
A:
Updated for image:
$(".toggle").live('click', function () {
event.preventDefault();
var id = "#"+$(this).attr('href');
// change image of the next element
$(this).next('img').attr('src', 'path here');
$("id").show("slow");
});
Note if you want to show/hide the element with click on the same element, you need to use slideToggle instead of show. Or you can use the animate method with opacity:'toggle' for fadding toggle effect.
You need to use live() method for dynamically generated elements:
$(".toggle").live('click', function () {
event.preventDefault();
var id = "#"+$(this).attr('href');
$("id").show("slow");
});
| {
"pile_set_name": "StackExchange"
} |
Q:
In PivotItem, ListBox Binding dont show value
Im create collection for show in ListBoxTransactions and binding as Description. But in result i have only name collection in ListBoxTransactions.ItemsSource, but not value. adn a cant use ListBox.ItemTemplate
XAML
<phone:PivotItem Header="Journal">
<Grid>
<ListBox Name="ListBoxTransactions">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Description}" FontSize="35"/>
</StackPanel>
</ListBox>
</Grid>
</phone:PivotItem>
C#
public class TransactHelper
{
public string Description { get; set; }
}
public void ShowTransactions()
{
ListBoxTransactions.Items.Clear();
var transactFulls = _workerDb.GeTransactFull();
var list = new List<TransactHelper>();
foreach (var t in transactFulls)
{
list.Add(new TransactHelper { Description = t.Description });
}
this.ListBoxTransactions.ItemsSource = list; // dont view collection. only name collection
A:
You should implement ItemContainerStyle for your items.
<ListBox Name="ListBoxTransactions" ItemContainerStyle="{DynamicResource MyItemStyle}">
<ListBox.Resources>
<Style x:Key="MyItemStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Description}" FontSize="35"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
And once note:
Don't use this pair
ListBoxTransactions.Items.Clear();
this.ListBoxTransactions.ItemsSource = list;
You need
ListBoxTransactions.ItemsSource = null;
this.ListBoxTransactions.ItemsSource = list;
Or Implement your collection as ObservableCollection
| {
"pile_set_name": "StackExchange"
} |
Q:
Are finitely generated virtually abelian groups space $\times$ finite?
A finitely generated virtually abelian group $G$ must have $\mathbb Z^n$ as a normal subgroup with $G/\mathbb Z^n$ finite. For each $n$ there are a finite number of examples of such groups arising as space or crystallographic groups, represented by isometries on $\mathbb R^n$, where the action of the finite group on $\mathbb Z^n$ is faithful, but of course there are many more finitely generated virtually abelian groups than there are space groups, most obviously by taking a direct product of a space group and a finite group.
It would be very convenient for me if any finitely generated virtually abelian group with $n=2$ was of this form, i.e. a direct product of one of the 17 wallpaper groups and some finite group, but I think perhaps that's a bit too much to hope for. Could anybody point me to a proof or a counterexample? I only need $n=2$ but I'm curious about general $n$.
I found the claim
If $G$ is finitely generated virtually abelian then there is a projection with finite kernel to a crystallographic group.
in https://core.ac.uk/download/pdf/82725144.pdf but I can't work out what projection means there. I don't see how it helps to just mod out by the kernel of the map from the finite group to $\operatorname{Aut}(\mathbb Z^n)$, and I think perhaps that's what is considered there.
A:
I think projection just means surjective homomorphism.
A counterexample to your conjecture is the group $\langle x,y \mid y^4=1, y^{-1}xy=x^{-1} \rangle$. It has the infinite cyclic group $\langle x \rangle$ as a subgroup of index $4$. It projects onto the infinite dihedral group (which is a space group) with kernel of order $2$, but it is not a direct product.
| {
"pile_set_name": "StackExchange"
} |
Q:
Apple Push Notification Hebrew
I am using Apns-PHP for sending push notification to IOS devices, below is the link of open source code which I have applied.
http://code.google.com/p/apns-php
It is working fine for English text messages however, for Hebrew text message sometimes its send null as text message.
To overcome with it, I have applied solution suggested by the following link.
https://stackoverflow.com/a/10936493/1928421
As per the above link I have replaced my payload function with the given method, now I some text message is coming in push message but it seems like they are formatted with UTF8.
Here is the actual Hebrew text that I am passing to Apns.
"האילנית לזון זקוק לעזרה כדי לקחת מ גבעה ל ת"
And this the dictionary which is getting created by the script.
[aps] => Array (
[alert] => Array (
[body] => "\u05d4\u05d0\u05d9\u05dc\u05e0\u05d9\u05ea \u05dc\u05d6\u05d5\u05df \u05d6\u05e7\u05d5\u05e7 \u05dc\u05e2\u05d6\u05e8\u05d4 \u05db\u05d3\u05d9 "
)
[badge] => 3
)
on device hand for the alert key I am receiving following text only.
"\u05d4\u05d0\u05d9\u05dc\u05e0\u05d9\u05ea \u05dc\u05d6\u05d5\u05df \u05d6\u05e7\u05d5\u05e7 \u05dc\u05e2\u05d6\u05e8\u05d4 \u05db\u05d3\u05d9 "
Any comment or suggestion is highly appreciated.
A:
I have just downloaded the latest code from ** https://github.com/duccio/ApnsPHP/ ** and its works absolutely fine
| {
"pile_set_name": "StackExchange"
} |
Q:
Zurb Foundation change top-bar colour
I am having trouble changing the top-bar section of a Foundation site to a different colour.
I have created a custom style.css for this.
I can change most of the top-bar color but NOT the right hand drop down list side (I don't have a list on the left). Clicking a link on the drop down changes colour of the nav bar but the nav bar component at the top does not change other than this (hope this makes sense?)...
This is the basic HTML:
<section class="top-bar-section">
<!-- Right Nav Section -->
<ul class="right">
<li class="divider"></li>
<li class="has-dropdown">
<a href="#">Sections</a>
<ul class="dropdown">
<li><a href="about.html">####</a></li>
<li class="divider"></li>
<li><a href="philosophy.html">####</a></li>
<li class="divider"></li>
<li><a href="beginning.html">####</a></li>
<li class="divider"></li>
<li><a href="#">#####</a></li>
<li class="divider"></li>
</ul>
</li>
<li class="has-dropdown">
<a href="#">Links</a>
<ul class="dropdown">
<li><a href="#" target="new">####</a></li>
<li class="divider"></li>
<li><a href="#" target="new">####</a></li>
<li class="divider"></li>
<li><a href="#" target="new">####</a></li>
<li class="divider"></li>
</ul>
</li>
</ul>
</section>
This is my attempt at changing it using style.css:
@charset "UTF-8";
.top-bar {
background-color: #2D4DC7;
}
.top-bar-section ul {
background-color: #2D4DC7;
}
.top-bar-section ul.right {
background-color: #2D4DC7;
}
.top-bar-section li a:not(.button) {
background-color: #2D4DC7;
}
.top-bar-section ul li.active > a {
background-color: #2D4DC7;
/** Changes the hover state of non active menu items **/
.top-bar-section li:hover a {
background-color: #2D4DC7;
}
.top-bar-section ul li > a {
background-color: #2D4DC7;
}
.top-bar-section ul.dropdown li a:hover:not(.button) {
background-color: #2D4DC7;
}
.top-bar-section ul.dropdown {
background-color: #2D4DC7;
}
.top-bar-section .has-dropdown > a:after {
background-color: #2D4DC7;
}
I am pretty sure it is just syntax that I am having issues with. Something to do with the 'right' class I think???
Any help please?
Many Thanks
A:
I strongly suggest you use a browser such as Firefox with Firebug installed.
Load any page, hit Tools > Web Developer > Inspector (or its hot key equivalent), then click on your object, the HTML code inspector will reference the exact line of the css file that is governing the style being generated (either the style directly, or the computed style).
Time and sanity saver.
| {
"pile_set_name": "StackExchange"
} |
Q:
Best way to document anonymous objects and functions with jsdoc
Edit: This is technically a 2 part question. I've chosen the best answer that covers the question in general and linked to the answer that handles the specific question.
What is the best way to document anonymous objects and functions with jsdoc?
/**
* @class {Page} Page Class specification
*/
var Page = function() {
/**
* Get a page from the server
* @param {PageRequest} pageRequest Info on the page you want to request
* @param {function} callback Function executed when page is retrieved
*/
this.getPage = function(pageRequest, callback) {
};
};
Neither the PageRequest object or the callback exist in code. They will be provided to getPage() at runtime. But I would like to be able to define what the object and function are.
I can get away with creating the PageRequest object to document that:
/**
* @namespace {PageRequest} Object specification
* @property {String} pageId ID of the page you want.
* @property {String} pageName Name of the page you want.
*/
var PageRequest = {
pageId : null,
pageName : null
};
And that's fine (though I'm open to better ways to do this).
What is the best way to document the callback function? I want to make it know in the document that, for example, the callback function is in the form of:
callback: function({PageResponse} pageResponse, {PageRequestStatus} pageRequestStatus)
Any ideas how to do this?
A:
You can document stuff that doesnt exist in the code by using the @name tag.
/**
* Description of the function
* @name IDontReallyExist
* @function
* @param {String} someParameter Description
*/
/**
* The CallAgain method calls the provided function twice
* @param {IDontReallyExist} func The function to call twice
*/
exports.CallAgain = function(func) { func(); func(); }
Here is the @name tag documentation. You might find name paths useful too.
A:
You can use @callback or @typedef.
/**
* @callback arrayCallback
* @param {object} element - Value of array element
* @param {number} index - Index of array element
* @param {Array} array - Array itself
*/
/**
* @param {arrayCallback} callback - function applied against elements
* @return {Array} with elements transformed by callback
*/
Array.prototype.map = function(callback) { ... }
A:
To compliment studgeek's answer, I've provided an example that shows what JsDoc with Google Closure Compiler lets you do.
Note that the documented anonymous types get removed from the generated minified file and the compiler ensures valid objects are passed in (when possible). However, even if you don't use the compiler, it can help the next developer and tools like WebStorm (IntelliJ) understand it and give you code completion.
// This defines an named type that you don't need much besides its name in the code
// Look at the definition of Page#getPage which illustrates defining a type inline
/** @typedef { pageId : string, pageName : string, contents: string} */
var PageResponse;
/**
* @class {Page} Page Class specification
*/
var Page = function() {
/**
* Get a page from the server
* @param {PageRequest} pageRequest Info on the page you want to request
*
* The type for the second parameter for the function below is defined inline
*
* @param {function(PageResponse, {statusCode: number, statusMsg: string})} callback
* Function executed when page is retrieved
*/
this.getPage = function(pageRequest, callback) {
};
};
| {
"pile_set_name": "StackExchange"
} |
Q:
By letting $m=\frac{1}{n}$ find $\lim_{n\rightarrow\infty} n \tan \left(\frac{1}{n}\right)$
By letting $m=\dfrac{1}{n}$ find
$$\lim\limits_{n\rightarrow\infty} n \tan \left(\dfrac{1}{n}\right)$$
I've played around with the algebra, but can't see how m fits in, apart from abbreviation. Is my working correct?
$\dfrac{\tan{\frac{1}{n}}}{\frac{1}{n}}=\frac{0}{0}$
L'Hopital's rule:
$\dfrac{\sec^2m}{(-1/n^2 )}=\dfrac{-n^2}{\cos^2\frac{1}{n}}$
Divide by $-n^2$ to get $\dfrac{1}{\cos^2\frac{1}{n}}$ which is 1 as n tends to infinity because $\cos0=1$. I don't really get limits yet, but is this right?
A:
Here are the steps
$$ \lim\limits_{n\to\infty} n\tan\left(\frac{1}{n}\right)$$
Let $m=\frac{1}{n}$. Since $n\to\infty$, then $m=\frac{1}{\infty}=0$. So now we have
$$ \lim\limits_{m\to 0} \frac{\tan\left(m\right)}{m}= \lim\limits_{m\to 0} \frac{\frac{d}{dm}\tan\left(m\right)}{\frac{d}{dm}m} = \lim\limits_{m\to 0} \sec^2\left(m\right) = \lim\limits_{m\to 0} \frac{1}{\cos^2\left(m\right)}=1$$
Looks to me like you do get limits. Keep it up.
| {
"pile_set_name": "StackExchange"
} |
Q:
Lock-free SPSC queue implementation on ARM
I'm trying to write a single producer single consumer queue for ARM and I think I'm close to wrapping my head around DMB, but need some checking (I'm more familiar with std::atomic.)
Here's where I'm at:
bool push(const_reference value)
{
// Check for room
const size_type currentTail = tail;
const size_type nextTail = increment(currentTail);
if (nextTail == head)
return false;
// Write the value
valueArr[currentTail] = value;
// Prevent the consumer from seeing the incremented tail before the
// value is written.
__DMB();
// Increment tail
tail = nextTail;
return true;
}
bool pop(reference valueLocation)
{
// Check for data
const size_type currentHead = head;
if (currentHead == tail)
return false;
// Write the value.
valueLocation = valueArr[currentHead];
// Prevent the producer from seeing the incremented head before the
// value is written.
__DMB();
// Increment the head
head = increment(head);
return true;
}
My question is: is my DMB placement and justification accurate? Or is there still understanding that I'm missing? I'm particularly uncertain about whether the conditionals need some guard when dealing with the variable that's updated by the other thread (or interrupt).
A:
A barrier there is necessary but not sufficient, you also need "acquire" semantics for loading the var modified by the other thread. (Or at least consume, but getting that without a barrier would require asm to create a data dependency. A compiler wouldn't do that after already having a control dependency.)
A single-core system can use just a compiler barrier like GNU C asm("":::"memory") or std::atomic_signal_fence(std::memory_order_release), not dmb. Make a macro so you can choose between SMP-safe barriers or UP (uniprocessor) barriers.
head = increment(head); is a pointless reload of head, use the local copy.
use std::atomic to get the necessary code-gen portably.
You normally don't need to roll your own atomics; modern compilers for ARM do implement std::atomic<T>. But AFAIK, no std::atomic<> implementations are aware of single-core systems to avoid actual barriers and just be safe wrt. interrupts that can cause a context switch.
On a single-core system, you don't need dsb, just a compiler barrier. The CPU will preserve the illusion of asm instructions executing sequentially, in program order. You just need to make sure the compiler generates asm that does things in the right order. You can do that by using std::atomic with std::memory_order_relaxed, and manual atomic_signal_fence(memory_order_acquire) or release barriers. (Not atomic_thread_fence; that would emit asm instructions, typically dsb).
Each thread reads a variable that the other thread modifies. You're correctly making the modifications release-stores by making sure they're visible only after access to the array.
But those reads also need to be acquire-loads to sync with those release stores. E.g. to make sure push isn't writing valueArr[currentTail] = value; before pop finishes reading that same element. Or reading an entry before it's fully written.
Without any barrier, the failure mode would be that if (currentHead == tail) return false; doesn't actually check the value of tail from memory until after
valueLocation = valueArr[currentHead]; happens. Runtime load reordering can easily do that on weakly-ordered ARM. If the load address had a data dependency on tail, that could avoid needing a barrier there on an SMP system (ARM guarantees dependency ordering in asm; the feature that mo_consume was supposed to expose). But if the compiler just emits a branch, that's only a control dependency, not data. If you were writing by hand in asm, a predicated load like ldrne r0, [r1, r2] on flags set by the compare would I think create a data dependency.
Compile-time reordering is less plausible, but a compiler-only barrier is free if it's only stopping the compiler from doing something it wasn't going to do anyway.
untested implementation, compiles to asm that looks ok but no other testing
Do something similar for push. I included wrapper functions for load acquire / store release, and fullbarrier(). (Equivalent of Linux kernel's smp_mb() macro, defined as a compile time or compile+runtime barrier.)
#include <atomic>
#define UNIPROCESSOR
#ifdef UNIPROCESSOR
#define fullbarrier() asm("":::"memory") // GNU C compiler barrier
// atomic_signal_fence(std::memory_order_seq_cst)
#else
#define fullbarrier() __DMB() // or atomic_thread_fence(std::memory_order_seq_cst)
#endif
template <class T>
T load_acquire(std::atomic<T> &x) {
#ifdef UNIPROCESSOR
T tmp = x.load(std::memory_order_relaxed);
std::atomic_signal_fence(std::memory_order_acquire);
// or fullbarrier(); if you want to use that macro
return tmp;
#else
return x.load(std::memory_order_acquire);
// fullbarrier() / __DMB();
#endif
}
template <class T>
void store_release(std::atomic<T> &x, T val) {
#ifdef UNIPROCESSOR
std::atomic_signal_fence(std::memory_order_release);
// or fullbarrier();
x.store(val, std::memory_order_relaxed);
#else
// fullbarrier() / __DMB(); before plain store
return x.store(val, std::memory_order_release);
#endif
}
template <class T>
struct SPSC_queue {
using size_type = unsigned;
using value_type = T;
static const size_type size = 1024;
std::atomic<size_type> head;
value_type valueArr[size];
std::atomic<size_type> tail; // in a separate cache-line from head to reduce contention
bool push(const value_type &value)
{
// Check for room
const size_type currentTail = tail.load(std::memory_order_relaxed); // no other writers to tail, no ordering needed
const size_type nextTail = currentTail + 1; // modulo separately so empty and full are distinguishable.
if (nextTail == load_acquire(head))
return false;
valueArr[currentTail % size] = value;
store_release(tail, nextTail);
return true;
}
};
// instantiate the template for int so we can look at the asm
template bool SPSC_queue<int>::push(const value_type &value);
Compiles cleanly on the Godbolt compiler explorer with zero barriers if you use -DUNIPROCESSOR, with g++9.2 -O3 -mcpu=cortex-a15 (just to pick a random modern-ish ARM core so GCC can inline std::atomic load/store function and barriers for the non-uniprocessor case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Effectivly creating a tabbed website with RadTabStrip
I have an ASP.NET web application that I am making and I am thinking of making it a tabbed interface using Telerik's RadTabStrip. I am trying to figure out the best way to approach this though. I would need about 10 tabs because I have about 10 different main areas of my application. My question is how is the best way to integrate the content into the tabs. All of the simple examples I've seen create RadViews with imbedded HTML/ASP.NET content. The problem with this approach is that, with 10 tabs, it would make my main ASPX file really really big and it would be kind of clumsy to work with, having to integrate all 10 pages into one page. Is there a better or more accepted way to accomplish this?
A:
I think, you have several possibilities:
Use one RadTabStrip and several RadView controls. Put the content for each tab into a separate user control (*.ascx). Then you only have to include the user controls in your main aspx page.
Use a master page and put the RadTabStrip on it. Create a separate page for each area of your application (each using the same master page). Use the RadTab's NavigateUrl property to navigate to the corresponding page (as shown in this demo).
there are certainly other possibilities...
| {
"pile_set_name": "StackExchange"
} |
Q:
Symfony2 error when trying to create entity field in form
$tip->setGame($em->getRepository('XXXBundle:Game')->find($id));
$form = $this->createFormBuilder($tip)->add('player', 'entity', array(
'class' => 'XXXBundle::FootballPlayer',
/*'query_builder' => function(\XXX\XXXBundle\Entity\FootballPlayerRepository $er)
{
$er->findByCurteam($team->getName());
},*/
))->getForm();
(not really using 'XXX' in my code)
error:
Warning: class_parents(): Class XXX\XXXBundle\Entity\ does not exist
and could not be loaded in
D:\www\xxx\xxx\vendor\doctrine\lib\Doctrine\ORM\Mapping\ClassMetadataFactory.php
line 223
seems the Entity class is not found - strange
A:
Something is strange in your code: 'class' => 'XXXBundle::FootballPlayer', are you sure :: exist? Never seen it, seems like a mistake (maybe can provoke the error).
After testing, yes, it's because of the double :: replace by :: 'class' => 'XXXBundle:FootballPlayer',.
| {
"pile_set_name": "StackExchange"
} |
Q:
Veshameru in Chabad siddur
Why do Chabad siddurim always print Veshameru before the Shabbat Ma'ariv Amida, even while also noting that the Chabad custom is not to say it? Are there any groups that use the Chabad Nusach Ari siddur, and include Veshameru?
A:
Two stories explaining why the Alter Rebbe included V'shomru in his siddur:
R' Avraham Chaim Na'ah, in his sefer Piskei Hasidur (paragraph 128), brings a story Chassidim would tell.
Levi Yitzchok of Berditchev once asked the Alter Rebbe why his custom is not to say V'shomru, if it makes such a "יריד" (usually translated as fair, or parade) in heaven. The Alter Rebbe answered that juxtaposing Redemption to the Amidah also makes a fair in heaven, and you can't be at every fair.
But out of respect for R' Levi Yitzchok of Berditchev, the Alter Rebbe included it in the siddur, with a preface saying our custom is not to say it.
Rabbi Abraham J. Twerski, in his book "The Zeide Reb Motele", tells a different story that was a tradition in his family. He says when his ancestor, the grandson of R' Menachem Nochum of Chernobyl (Yaakov Yisroel of Hornsteipl) married the granddaughter of the Alter Rebbe, The Alter Rebbe asked R' Yaakov Yisroel to start saying "Ki Vanu Vachartah" in Kiddush on Friday night. R' Yaakov Yisroel answered that he would if the Alter Rebbe would start saying V'shomru. The Alter Rebbe answered that he was too old to change his ways, but as a compromise he would include it in the Siddur. (see here)
--- Dayan Raskin quotes a Gilyon HaBeSH"T that wants to disprove this story on the grounds that the dates don't match up. (If someone could provide a link to that Gilyon HaBesh"T that would be great)
| {
"pile_set_name": "StackExchange"
} |
Q:
document must have an _id before saving mongoose error
I am trying to create a schema.
I keep getting the document does not have an _id error, besides the code below I did try to initialize it explicitly, but nothing works.
var UserSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
username: String,
password: String
});
var User = mongoose.model('user', UserSchema);
A:
http://mongoosejs.com/docs/guide.html#_id reads:
Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor.
If you explicitly define _id type in the schema, it's your responsibility to set it:
User._id = mongoose.Types.ObjectId('000000000000000000000001');
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I check the next line without eating the next integer?
I'm grappling with a specific problem, but seeing as this is technically homework and I want to learn what I'm doing wrong, I would love a more general solution. Some caveats: I have to use the scanner class, and my data is not in an array or anything. I know from reading around on the site that BufferedReading is preferred. From what I've read of it, I think I would prefer it too. But that's not what I'm allowed to work with here.
I'm trying to read from a data file and then do some stuff with that file. The data goes like this:
1234 55 64 75
1235 44 32 12
...
nnnn xx yy zz
0
2234 47 57 67
2235 67 67 67
...
nnnn xx yy zz
0
Each line is an ID followed by three grades. Each class is terminated by a zero line and then the while loop starts from the top:
while (classContinues == true) {
//get the student's data and assign it in the program
studentID = inputFile.nextInt();
programGrade = inputFile.nextInt();
midtermGrade = inputFile.nextInt();
finalGrade = inputFile.nextInt();
// in here I'm doing other stuff but I don't need help with that
// check if the class has more students
if (inputFile.nextInt() == 0) {
classContinues = false;
} else {
classContinues = true;
inputFile.nextLine(); // eat the rest of the line
}
}
Now, when you run the code like this, it manages to print the output I want, but it skips every other row of data. Remove the inputFile.nextLine(); and it skips the second student ID and then messes up all the other output. So I guess what I'd like to know is what I'm doing wrong--how should I be checking for the next integer to be zero without eating the next student ID?
A:
Store every line into a String variable, parse integers from that line and then assign them by reading it from that string, not from the line itself. So:
String nextLine;
while (classContinues)
{
nextLine = inputFile.nextLine();
String[] tokens = nextLine.split(" ");
if(tokens.length == 1) //this means line has '0' character
classContinues = false;
else
{
classContinues = true;
studentID = tokens[0];
programGrade = tokens[1];
midtermGrade = tokens[2];
finalGrade = tokens[3];
// your stuff
}
}
If there will be any kind of error that will show misleading results with this code, it is probably my bad because I don't know the rest of the project. So I posted a code similar to yours.
Also you have to do a null check to that String that you got from nextLine method.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add a new folder to Ruby in Rails assets pipeline
I'm utilizing a bootstrap template and it requires a plugin for a revolution slider. I'm used to check the source code of the template and remove individual JS and CSS files it requires and place them in the asset pipeline. Is there any way to import into the asset pipeline the entire plugin folder with all of its files?
Here is a picture of what the folder contains:
UPDATE
I've added the rs-plugin to the assets portion of my app:
In application.rb I've added the following:
config.assets.paths << Rails.root.join("assets", "rs-plugin-5")
In assets/javascripts/application.js I've added the following:
//= require rs-plugin-5/js/jquery.themepunch.tools.min
//= require rs-plugin-5/js/jquery.themepunch.revolution.min
I am getting the following error:
A:
Yes, you can do it by adding next line to config/application.rb:
config.assets.paths << Rails.root.join('/path/to/folder')
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the pros and cons of using a flags enum?
I'm receiving several bit fields from hardware.
My code was originally:
public readonly byte LowByte;
public bool Timer { get { return (LowByte & 1) == 1; } }
Then I remembered the flags enum and am considering changing it to:
[Flags]
public enum LowByteReasonValues : byte
{
Timer = 1,
DistanceTravelledExceeded = 2,
Polled = 4,
GeofenceEvent = 8,
PanicSwitchActivated = 16,
ExternalInputEvent = 32,
JourneyStart = 64,
JourneyStop = 128
}
public readonly LowByteReasonValues LowByte;
public bool Timer { get { return (LowByte & LowByteReasonValues.Timer) == LowByteReasonValues.Timer; } }
and so on.
Which is best practice and what if any are the pros and cons of each approach?
EDIT: I'm interested to know if there are any practical differences between the two approaches, particularly in regards to performance. I'm not wishing to solicit opinion on coding styles (unless it comes from Microsoft guidelines) as that would see the question closed as unconstructive. Thanks.
A:
The later is best practice since it makes your code more readable
A:
If you are using .NET 4.0, you can now use the HasFlag method to check whether an enum contains a specific bit. This makes it even more readable than the previous method of checking.
[Flags]
public enum LowByteReasonValues : byte
{
Timer = 1,
DistanceTravelledExceeded = 2,
Polled = 4,
GeofenceEvent = 8,
PanicSwitchActivated = 16,
ExternalInputEvent = 32,
JourneyStart = 64,
JourneyStop = 128
}
public readonly LowByteReasonValues LowByte;
public bool Timer
{
get
{
return (LowByte.HasFlag(LowByte.Timer));
}
}
More information on MSDN.
A:
At the very least, your second example has better semantics and indicates the meaning of the bits within the code. There is some documentation within the code of what the bit is used for.
Otherwise, based on your first example, you will need to add comments since you are basically twiddling magic (bit) numbers, which makes the code much more difficult to read, especially by another person not familiar with it. Even if you yourself will be maintaining this code six months down the road, you may find it difficult to remember what bit 5 was used for.
| {
"pile_set_name": "StackExchange"
} |
Q:
uwp directx and c# development
I'm working on a UWP C# Bluetooth application with 3d representation view.
(of the hand and fingers will receive sensors ST microelectronic WESU)
For the moment, I used windows phone 8 application (desktop and Windows phone) for Bluetooth with the ti sensor tag and DirectX example.
Now I arrived to read computed quaternion from the stmicro wesu sensor with a custom UWP BLE example (originally present in the Windows SDK).
But now that it works fine with ble /sharpdx /uwp and Windows 10. But when I tried now to execute the application on Lumia 640, I have an exception.
The issue is that it uses DirectX 9 and it is not supported in UWP by sharp dx.
The sharp dx team confirmed me that UWP doesn't work with DirectX 9 (core.net if I remember correctly).
I tried to downgrade the version used for the pixel shader and vertax shader as below but it doesn't do the job.
so my question is how can I arrive to run DirectX 9 Under UWP on the Lumia 640?
//
using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("vertexShader.hlsl", "main", "vs_4_0_level_9_1", ShaderFlags.None))
{
vertexShader = new D3D11.VertexShader(this.device,vertexShaderByteCode);
inputSignature = new ShaderSignature(vertexShaderByteCode);
}
//
using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("pixelShader.hlsl", "main", "ps_4_0_level_9_1", ShaderFlags.None))
{
pixelShader = new D3D11.PixelShader(this.device , pixelShaderByteCode);
}
A:
ok i agreee with you, it's just about de shader
vs_4_0_level_9_1
ps_4_0_level_9_1
and
using (D3D11.Device defaultDevice = new D3D11.Device(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.None))
enter image description here
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual Studio 2015 Extensions Manager Index was out of range error
Env: Visual Studio 2015 Community Edition on Windows 8
Trying to open Tools --> Extensions and Updates results in the following error in a message box:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Tried running as Admin, same result.
I've tried looking at the log but nothing mentions that error.
In the log there are 3 error entries related to extensions which could be related, they say the following:
Error loading extension: Could not find a part of the path 'C:\path\to\APPDATA\LOCAL\MICROSOFT\VISUALSTUDIO\14.0\EXTENSIONS\ZW2UF5JV.JVN\extension.vsixmanifest'.
The other 2 are identical except the odd string at the end is HQ1Y5EQD.TMG and 3KWE1LJF.Z1W.
Interestingly, just before those errors in the log appear, there is a line for each saying the extension was loaded successfully but if I try to go to the path it's got listed, it doesn't exist.
I can't find any reference to those strings on my machine. I've also searched the registry but can't find any reference in there either.
I can get into the Extensions manager if I click on one of the update notifications but the original error message just displays in the main pane and I can't do anything else. I can get to the online window but as soon as I click an extension, I am prompted with the original message.
I haven't installed any extensions or VS updates for a while but my Web Compiler extension extension has stopped auto compiling JSX files which is why I started trying to look at the Extension manager. I'm guessing the issues are related.
I can still work, compiling can be done manually which is inconvenient but not the end of the world. My worry is some other extensions are also misbehaving and I just haven't noticed yet.
Don't really want to re-install VS as a) it took ages last time and b) it might not fix the issue. Is there any good advice on troubleshooting the error or anything else I can try before I re-install?
A:
I refreshed the GitHub extension on VS 2015 and got this error. Deleting the two cache files:
extensions.en-US.cache
extensionSdks.en-US.cache
from the AppData\Local\Microsoft\VisualStudio\14.0\Extensions causes them to be rebuilt and eliminates the error.
No reinstall needed.
A:
Problem got worse, I started getting the error message when starting Visual Studio and things like the package manager wouldn't load. Each restart seemed to yield a different combination of windows not loading, sometimes Solution Explorer, sometimes Team Explorer etc. Not good.
A repair to VS 2015 via the Control Panel took a while but didn't help, same problems.
I ended up completely uninstalling and trying to re-install. However the installer threw an index was out of range error but weirdly VS 2015 was now listed as an installed application again.
So I'm guessing the original uninstall left some problematic files lying around which messed up the next install. So I uninstalled again, renamed Microsoft Visual Studio 14.0 folder, cleared all files from AppData\Local\Microsoft\VisualStudio\14.0\Extensions and re-installed.
It installed and ran fine.
The problem I now had was that I couldn't find the SQL Server Object Explorer window anywhere. I tried repairing SQL Server Data Tools but still no luck. So I uninstalled SSDT and then re-installed. This seemed to fix it.
Now I realised I also couldn't connect to Azure through the Server Explorer window, the option was simply not appearing in the list like it used to. This time a repair to Azure Tools for Microsoft Visual Studio 2015 - v2.9 and a repair to Azure App Service Tools v2.9 - Visual Studio 2015 fixed that problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Deep copy of array with elements containing an array?
I'm trying to make a deep copy of a list of the following objects:
struct Book {
var title: String
var author: String
var pages: Int
}
struct BookShelf {
var number: Int
}
class BookShelfViewModel {
var bookShelf: BookShelf
var number: Int
var books: [BookViewModel]?
init(bookShelf: BookShelf) {
self.bookShelf = bookShelf
self.number = bookShelf.number
}
required init(original: BookShelfViewModel) {
self.bookShelf = original.bookShelf
self.number = original.number
}
}
class BookViewModel {
var book: Book
var title: String
var author: String
var pages: Int
init(book: Book) {
self.book = book
self.title = book.title
self.author = book.author
self.pages = book.pages
}
required init(original: BookViewModel) {
self.book = original.book
self.title = original.title
self.author = original.author
self.pages = original.pages
}
}
Books for BookShelf is fetched in the BookShelfViewModel.
If I go like:
var copiedArray = originalArray
for bs in copiedArray {
bs.books = bs.books.filter { $0.title == "SampleTitle" }
}
The above filter both the copiedArray and the originalArray, and I obviously just want the copiedArray altered.
When I clone the array like this:
var originalArray = [BookShelfViewModel]()
... // Fill the array
var clonedArray = originalArray.clone()
clonedArray is cloned, but clonedArray.books is empty.
I've created the extension and followed this gist. How do I clone the array in the objects in the array?
I've done a quick playground to visualize the problem, hopefully it helps understand what I'm talking about.
A:
In your copying initialiser in BookShelfViewModel you don't actually clone the books array. You need to add self.books = original.books?.clone() to required init(original: BookShelfViewModel)
class BookShelfViewModel: Copying {
var bookShelf: BookShelf
var number: Int
var books: [BookViewModel]?
init(bookShelf: BookShelf) {
self.bookShelf = bookShelf
self.number = bookShelf.number
}
required init(original: BookShelfViewModel) {
self.bookShelf = original.bookShelf
self.books = original.books?.clone()
self.number = original.number
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Removing all the columns of the data frame that have same values across all the rows
I have a data frame like this :
1 NA 0.2 NA 1 2
2 NA 0.5 NA 1 6
3 NA 0.7 NA 1 4
4 NA 0.3 NA 1 4
I want to remove the columns that have same values across all the rows.i.e my data frame should look like this:
1 0.2 2
2 0.5 6
3 0.7 4
4 0.3 4
Is there an easiest way to do this?
A:
dataf[sapply(dataf, function(x) length(unique(x))>1)]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to calculate Volume Weighted Average Price (VWAP) using a pandas dataframe with ask and bid price?
How do i create another column called vwap which calculates the vwap if my table is as shown below?
time bid_size bid ask ask_size trade trade_size phase
0 2019-01-07 07:45:01.064515 495 152.52 152.54 19 NaN NaN OPEN
1 2019-01-07 07:45:01.110072 31 152.53 152.54 19 NaN NaN OPEN
2 2019-01-07 07:45:01.116596 32 152.53 152.54 19 NaN NaN OPEN
3 2019-01-07 07:45:01.116860 32 152.53 152.54 21 NaN NaN OPEN
4 2019-01-07 07:45:01.116905 34 152.53 152.54 21 NaN NaN OPEN
5 2019-01-07 07:45:01.116982 34 152.53 152.54 31 NaN NaN OPEN
6 2019-01-07 07:45:01.147901 38 152.53 152.54 31 NaN NaN OPEN
7 2019-01-07 07:45:01.189971 38 152.53 152.54 31 ask 15.0 OPEN
8 2019-01-07 07:45:01.189971 38 152.53 152.54 16 NaN NaN OPEN
9 2019-01-07 07:45:01.190766 37 152.53 152.54 16 NaN NaN OPEN
10 2019-01-07 07:45:01.190856 37 152.53 152.54 15 NaN NaN OPEN
11 2019-01-07 07:45:01.190856 37 152.53 152.54 16 ask 1.0 OPEN
12 2019-01-07 07:45:01.193938 37 152.53 152.55 108 NaN NaN OPEN
13 2019-01-07 07:45:01.193938 37 152.53 152.54 15 ask 15.0 OPEN
14 2019-01-07 07:45:01.194326 2 152.54 152.55 108 NaN NaN OPEN
15 2019-01-07 07:45:01.194453 2 152.54 152.55 97 NaN NaN OPEN
16 2019-01-07 07:45:01.194479 6 152.54 152.55 97 NaN NaN OPEN
17 2019-01-07 07:45:01.194507 19 152.54 152.55 97 NaN NaN OPEN
18 2019-01-07 07:45:01.194532 19 152.54 152.55 77 NaN NaN OPEN
19 2019-01-07 07:45:01.194598 19 152.54 152.55 79 NaN NaN OPEN
Sorry, the table is not clear, but the second most right column is trade_size, on its left is trade, which shows the side of the trade( bid or ask). if both trade_size and trade are NaN, it indicates that no trade occur at that timestamp.
If df['trade'] == "ask", trade price will be the price in column 'ask' and if df['trade] == "bid", the trade price will be the price in column 'bid'. Since there are 2 prices, may I ask how can i calculate the vwap, df['vwap']?
My idea is to use np.cumsum(). Thank you!
A:
You can use np.where to give you the price from the correct column (bid or ask) depending on the value in the trade column. Note that this gives you the bid price when no trade occurs, but because this is then multiplied by a NaN trade size it won't matter. I also forward filled the VWAP.
volume = df['trade_size']
price = np.where(df['trade'].eq('ask'), df['ask'], df['bid'])
df = df.assign(VWAP=((volume * price).cumsum() / vol.cumsum()).ffill())
>>> df
time bid_size bid ask ask_size trade trade_size phase VWAP
0 2019-01-07 07:45:01.064515 495 152.52 152.54 19 NaN NaN OPEN NaN
1 2019-01-07 07:45:01.110072 31 152.53 152.54 19 NaN NaN OPEN NaN
2 2019-01-07 07:45:01.116596 32 152.53 152.54 19 NaN NaN OPEN NaN
3 2019-01-07 07:45:01.116860 32 152.53 152.54 21 NaN NaN OPEN NaN
4 2019-01-07 07:45:01.116905 34 152.53 152.54 21 NaN NaN OPEN NaN
5 2019-01-07 07:45:01.116982 34 152.53 152.54 31 NaN NaN OPEN NaN
6 2019-01-07 07:45:01.147901 38 152.53 152.54 31 NaN NaN OPEN NaN
7 2019-01-07 07:45:01.189971 38 152.53 152.54 31 ask 15.0 OPEN 152.54
8 2019-01-07 07:45:01.189971 38 152.53 152.54 16 NaN NaN OPEN 152.54
9 2019-01-07 07:45:01.190766 37 152.53 152.54 16 NaN NaN OPEN 152.54
10 2019-01-07 07:45:01.190856 37 152.53 152.54 15 NaN NaN OPEN 152.54
11 2019-01-07 07:45:01.190856 37 152.53 152.54 16 ask 1.0 OPEN 152.54
12 2019-01-07 07:45:01.193938 37 152.53 152.55 108 NaN NaN OPEN 152.54
13 2019-01-07 07:45:01.193938 37 152.53 152.54 15 ask 15.0 OPEN 152.54
14 2019-01-07 07:45:01.194326 2 152.54 152.55 108 NaN NaN OPEN 152.54
15 2019-01-07 07:45:01.194453 2 152.54 152.55 97 NaN NaN OPEN 152.54
16 2019-01-07 07:45:01.194479 6 152.54 152.55 97 NaN NaN OPEN 152.54
17 2019-01-07 07:45:01.194507 19 152.54 152.55 97 NaN NaN OPEN 152.54
18 2019-01-07 07:45:01.194532 19 152.54 152.55 77 NaN NaN OPEN 152.54
19 2019-01-07 07:45:01.194598 19 152.54 152.55 79 NaN NaN OPEN 152.54
| {
"pile_set_name": "StackExchange"
} |
Q:
TRP Spyre SLC brakes compatible with other vendors' rotors?
Does anyone know whether TRP Spyre (SLC) mechanical disc brakes can be used with other vendors' 160mm rotors, i.e. the ones for SRAM's HRD brakes?
A:
Yes, they are compatible. As long as you are using a 160mm caliper mount, and a 160m rotor they will work together. There are industry-wide standards for rotor position for front and rear brakes.
Like @Carel says above though: make sure your pads are a type that are correct for the rotor (this shouldn't be a problem with HRD rotors, you can use metallic or organic pads on them) and also compatible for the type of riding you are doing. For example, if you are doing tons of downhill with organic pads, you'll wear through them really quickly.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do $i$ and $\pi$ show up in this result from a Google search?
I am just curious and play a bit here. I googled (-1e-10)^(-1e-10) and got
(-1e-10)^(-1e-10) =
$1 - 3.14159266 × 10^{-10} i$
I guess this is some form of approximation to $x^x$ when $x$ approaches $0$. But what does $i$ stand for and how does $\pi$ show up in this?
Note that googling 1e-10^1e-10 simply returns 0.99999999769.
A:
If $r$ is a small positive real, one branch of exponentiation gives$$(-r)^{-r}=(re^{i\pi})^{-r}=\underbrace{r^{-r}}_{\approx1}\underbrace{e^{-ir\pi}}_{\approx1-ir\pi}\approx1-ir\pi.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Android-Studio: No build.gradle in my project, why?
I am developing my android application on Android-Studio. My project was checked out project from Git version control. Everything works fine. Except that I cannot see build.gradle file. Hence I am unable to add modules or libraries.
Why doesn't my project has a build.gradle file ?!
Did I do anything wrong to import my project from Git ?
What should I do to be able to add libraries without having build.gradle ?
Here is what I did to import my project:
Check out project from Version Control -> Git,
after cloning, the following box appears:
I click `Yes. The follwoing box appears:
I accept the default options and click Ok, then the following box appear:
Again, I accept the default options and click Ok
Then my projec loads on Android-Studio. It shows me the following message:
Before I click on add root, the following box appears:
I click on dont' remind me again for this project. After that I can continue programming (Git and Version Control is working). But build.gradle is nowhere to be found !!
UPDATE 1:
The following image is the project view:
what am I doing wrong ?
UPDATE 2:
Here is the Android view:
A:
Choose Android View instead of Project View.. enjoy
see image1
see image2
A:
With huge help from Stack Overflow community, I figure out how to solve it. Here is what I did:
I totally removed Android-Studio following this guidance, then ...
I installed Gradle from this link, then ...
I re-installed Android-Studio following this link:
I am gussing the main problem was that I didn't installed Gradle manually and hence Android-Studio was using some sort of Gradle-Wrapper to allow the application to run.
Now, finally I can edit build.gradle.
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS: How can I change the orientation of a UICollectionViewCell?
I have a UICollectionViewController that I load when a user turns their iPad so as to put it into landscape orientation. The problem I’m having is that my UICollectionViewCells are still loading as if it were in portrait orientation. I set the UICollectionViewController to landscape inside Interface Builder, and I’m using a custom cell class that I’ve called CollectionViewCell. Each cell contains just an image and a label.
Is there something that I should be doing either in Interface Builder or in my code? I tried using CGAffineTransformationMakeRotation, but that was no help. If anyone else has encountered this before, I would be extremely grateful! Thanks very much!
Here’s a bit of the code for reference:
-(void)viewDidLoad
{
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
}
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
return listArray.count;
}
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"devices" forIndexPath:indexPath];
cell.statusImage.image=[UIImage imageNamed:@"Default.png"];
cell.name.text=@"HEY !!!!!";
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(320, 420);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(50, 20, 50, 20);
}
A:
In case anyone else has had this problem, here is how I solved it.
I was initially not allowing autorotation, and instead was just registering for orientationChanged notifications using NSNotificationCenter. This worked great except that it was preventing my second view from realizing that it needed to load in landscape mode.
So instead of that, I’ve created a class for the tabBar that my main view is embedded in, and I return NO for the shouldAutoRotate method in that class and in every other view except for the one which I want to load in landscape mode. I’m still using the orientationChanged notifications in my main view’S controller, since it is embedded in the tabBar. But I’m just using autorotation when returning to the main view.
If anyone has any questions, let me know. Hope it helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Split table according to string in a column
This should be an easy one, but I found no solution which worked and was at the same time elegant...
I have a table which has in one column a string. Some strings start with letter "E" and others start with letter "B". How do I generate two tables where the first one contains only the rows with strings starting with "E" and the second one rows where strings start with "B"?
EDIT:
Example:
Col1 Col2 StringCol Col4
1 1 Bacteria 3.2
2 3 Eukaryote 1.0
4 1 Bacteria 1.5
0 2 Bacteria 1.2
2 0 Eukaryote 0.9
Now the data frame should be split into two frames, one with all the rows "Bacteria" and the other with all the rows "Eukaryote".
A:
You can always use grepl for string matching. Thus, one option would
# Some sampledata:
yourdata <- data.frame(id=1:5, stringcol=c("bus", "easter", "Bunny", "nothing", "End"))
subset(yourdata, grepl("^B", stringcol))
# ^ marks the beginning of a string, then followed by "B"
# For E:
subset(yourdata, grepl("^E", stringcol))
If you want the matching to be case insensitive, you could do
subset(yourdata, grepl("^[Bb]", stringcol))
A totally different approach would be to use
subset(yourdata, substring(stringcol, 1, 1) == 'B')
# substring(..., 1, 1) extracts just the first letter from your string.
Edit:
If you know the whole string, you could always do the most elegant version:
subset(yourdata, stringcol == 'Bacteria')
| {
"pile_set_name": "StackExchange"
} |
Q:
How to avoid Spike Arrest Limits when making API calls from APEX
I'm running into a problem where my APEX code is firing too many API calls in the span of 100ms, so simply, is there a way to delay the code from firing for 101ms.
As I understand there may be a few 'Bad Code' workarounds such as home brew sleep methods and running for loops until certain conditions have been met, but I would rather avoid these for obvious reasons.
Thanks for any advice!
A:
Given your comments, use JavaScript to make the API calls. You can call a wire method, precisely wait at least 101 ms (or any other value), then continue. As a practical example:
createPrimaryAccountAndContact({data:data})
.then(result => new Promise((resolve, reject) => setTimeout(resolve, 101)))
.then(result => createContact({data:data2}));
You'll need a second method to chain together the calls for creating contacts, but this should help get you started, I think.
| {
"pile_set_name": "StackExchange"
} |
Q:
Activating Compression (esp. Dynamic Compression) with IIS-Express
Is it somehow possible to enable dynamic compression (for WCF-Services) on an IIS-Express?
It's a development environment issue so I cannot use the full version: but I need to figure out how it would behave with compression.
A:
Go to IIS Express installation folder (%programfiles%\IIS Express) and run the following command to enable dynamic compression.
appcmd set config -section:urlCompression /doDynamicCompression:true
Then add mime-types. Run following commands to add wildcard entries or take a look at http://www.iis.net/ConfigReference/system.webServer/httpCompression to add specific mime-types
appcmd set config /section:httpCompression /staticTypes.[mimeType='*/*'].enabled:"true" /commit:apphost
appcmd set config /section:httpCompression /dynamicTypes.[mimeType='*/*'].enabled:"true" /commit:apphost
A:
I found the configfile in Documents/IISExpress/config/applicationhost.config: here in the httpCompression-Section you can define the mime-types to use for dynamic compression.
| {
"pile_set_name": "StackExchange"
} |
Q:
SelectedIndexChanged() event of a dropdownlist on a checkbobx checking
I have a checkbox to indicate that communication address is same as the permanent address. There are 4 dropdownlists -
DRP_Comm_Country1
DRP_Comm_State1
DRP_Per_Country2
DRP_Per_State2
When i check the checkbox, the items of permanent address dropdownlists should be same as that of communication address dropdownlists.How to make it possible?
My code is
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
DRP_Per_Country2.SelectedIndex = DRP_Comm_Country1.SelectedIndex;
}
But the SelectedIndexChanged() Event of DRP_Per_Country2 is not get fired.Is it a wrong method? If so ,how to work it?
A:
First of all, you have to set the
AutoPostBack = true
property for all the DropDownList. If this wont work then call the SelectedIndexChanged Event manually
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
DRP_Per_Country2.SelectedIndex = DRP_Comm_Country1.SelectedIndex;
DRP_Per_Country2_SelectedIndexChanged(sender,e);
}
This will surely fire the event.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to connect to different HTTP port on server
I am new to WCF Services, I have developed a WCF service library hosted within a Windows Service. The service end point is http://servername:9980/ApplicationServer/ServiceName.
When I run this service on local system and try to connect using my application, everything works fine.
The problem starts when I deploy this service on server system, none of my application can use this service, even the browser says page not found. Though, if I remove the specific port number from the endpoint all works well.
I have already opened all the ports in Windows Firewall including Client and Server. Also proper exceptions are made to the router firewall, still I am not able to host the service on specific port. I have even tried by switching firewall off on both client and server system.
Thank you in advance.
-Ashish Sharma
A:
When you remove the specific port number it defaults to port 80.
So there is something that is blocking the other port.
Try using the Telnet command to check if the port is open (you may have to enable telnet)
As you have allready checked the firewalls, it could be urlscan or a network device.
| {
"pile_set_name": "StackExchange"
} |
Q:
Kotlin customer interface declaration
I'm having some issues converting my existing Java code to Kotlin, specifically with a custom click listener that I used with a recycle view. Here's what I got so far.
//this is the click listener interface (in Kotlin)
interface RecyclerClickListener {
fun onClick(view: View, position: Int)
}
In Java this is how I would create and use the interface
RecyclerClickListener clickListener = (view1, position) -> {
setSelectedDate(dateCards.get(position).getDateTime());
DateCardAdapter adapter = (DateCardAdapter) date_recycler_view.getAdapter();
adapter.setSelected(position);
};
DateCardAdapter cardAdapter = new DateCardAdapter(dateCards, getActivity(), clickListener, true );
Now this is how I'm trying to do it in Kotlin (most of this was auto-converted in Android Studio)
val listener: RecyclerClickListener = { view1: View, position: Int ->
setSelectedDate(dateCards[position].dateTime)
val adapter = sun_date_recycler_view.adapter as DateCardAdapter
adapter.setSelected(position)
} as RecyclerClickListener
val cardAdapter = DateCardAdapter(dateCards, activity!!, listener, true)
But when I launch my app I keep getting a ClassException when trying to create the listener
Caused by: java.lang.ClassCastException: .fragments.SunFragment$onViewCreated$listener$1 cannot be cast to .interfaces.RecyclerClickListener
A:
If you use IntelliJ to convert a Java class defining such a listener defined as an anonymous inner class to Kotlin, it will generate the following, correct code:
val listener = object : RecyclerClickListener {
override fun onClick(view: View, position: Int) {
// ...
}
}
The syntax is, BTW, described in the Kotlin documentation: https://kotlinlang.org/docs/reference/nested-classes.html#anonymous-inner-classes
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery-ajax parse xml and set radiobutton
I've a form with some radio button like this:
<input type="radio" name="leva" value="a"><input type="radio" name="leva" value="b">
with ajax post method I receive value of the radio.
The question is how can I set correct radio value to checked?
thanks in advance
ciao
h.
A:
You just need to find the right button using an attribute equals selector for the value, then set checked attribute using .attr(), like this:
$("input:radio[name='leva'][value='"+ returnedValue +"']").attr('checked', true);
The browser will handle un-selecting the other options since it's a radio button, and if no button is found with the value...well, like all jQuery selectors, it just won't have any effect, which is usually what's desired.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fetch all rows that meet criteria and display in new sheet
I am trying to automate excel so that it allows me to show all records from another tab where a certain condition is met.
my source table is(Analysis tab):
I have name all my ranges according to the column name. so for example named range Vehicle is
=Analysis!$A$2:$A$3000
all ranges go to row 3000.
dropdown is cell C1, the name of the vehicle and the filter to use.
My destination worksheet is as follows:
In Cell B3, I have the following array formula that I have tried to adapt unsuccessfully.
=IF(COUNTIF(vehicle,DropDown)<ROWS($A$1:$A1),"",INDEX(DataTable,LARGE(IF(DropDown=Litres,ROW(INDIRECT("1:"&ROWS(vehicle)))),ROW(Analysis!$A1)),MATCH(Analysis!A$3,Analysis!$A$3:$E$3,0)))
This does not work correctly. Any help is appreciated.
to summarize, I want to return all rows from Tab analysis where vehicle is equal to cell C1. I need to automate this as data changes each day.
UPDATE
A:
You will need to use VBA. A good way to do this is by adding a custom function and then using it in another cell. For instance in cell D1 put =MyFunction(C1). Then create a module in VBA and add the following (May contain some bugs cause I didn't test it):
Function MyFunction(parVal As String) As String
'Clear what is there now
ActiveSheet.Range("A3", "I3000").ClearContents
'Add new rows
varRange = Sheets("Analysis").UsedRange
varCount = 2
For varRow = 1 To varRange.Rows.Count
If varRange(varRow, 1) = parVal Then
varRange(varRow, 1).EntireRow.Copy
varCount = varCount + 1
ActiveSheet.Cells(varCount, 1).EntireRow.Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End If
Next varRow
MyFunction = "Found " & (varCount - 2) & " rows"
End Function
| {
"pile_set_name": "StackExchange"
} |
Q:
Solve quadratic equation using only 3 variables and arithmetic
Write function which solves equation of degree less than or equal to 2 (ax^2 + bx + c = 0).
Input
Function should get 3 parameters - floating point numbers which are coefficients of this equation. Coefficients may be zero (that means function must able to solve bx + c = 0 and c = 0 too).
Coefficients are between -1000 and 1000 with 3 significant decimal digits but maximum 3 digits after comma, for example, 999. or 3.14 or 0.233 but not 1001 or 0.0123.
Rules
You may use only + - * / % & | xor ~ && || ! < > >= <= == != << >> operators
No built-in functions (that means no square root or power or similar functions)
No variables except 3 function parameters
You can't use complicated expressions - only statements of the form a = b @ c or a = @ b are allowed (@ - any allowed operator and a, b, c - any variables, may be same or constants)
No loops, recursion, goto's, custom types
Casts and type conversion between integral data types are allowed
Using features of dynamic typing (changing floating point number to array/object/something else that is not number) is not allowed
If's are allowed with one or none operators in condition (if (a) {...} else {...} or if (a==b) {...} else {...}). Note that if itself and its condition scores separately
You may use try{}catch{}
Output
Output should be passed by reference to input variables, if your language doesn't have such feature, you anyway should put result to input variables and print their values
In variable a - number of real roots - 0, 1, 2, 3 (value greater than 2 stands for infinitely many roots)
In variables b and c - 1st and 2nd roots (if none or infinitely many roots than any values, if one root then c - any value)
Note that 2 equal roots is not the same as 1 root
Precision should be at least 3 significant decimal digits
Score
Score is [number of operators] + [number of if's]. Assignment operators have score 0.
Answer with lowest score wins.
In case of same score answer with greater precision wins. If precision is same then first answer wins.
if(a != 0) and if(a == 0) has score 1 (instead of 2) because if(a) or if(a)else{} can be used, however not all languages support it.
For each catch{} +2 to score
Use of 1 temporary variable of numeric type is +20 to score.
A:
C, 60
I happen to use the same square root algorithm (Newton) as Peter. However, I think we need to use two different starting values in order to get away with even 8 iterations. The maximum value of b²/4-c (the normalised discriminant) is for b = -c = 1000. The minimum value is for b = 0.001; c = 0 (in fact, there are smaller values but these would be beyond the significant digits of b and c). If we split the range of values at 20, we can use 0.1 as the starting guess for the lower range and 100 as the starting guess for the upper range and always converge in 8 steps. If I could be bothered to keep searching I think I could get this down to 7, and with a few more subdivisions probably even below 6 while still saving operations (but I can't be bothered right now).
void qe(&float a, &float b, &float c)
{
float t; // 20
if (a) // 21
{
b = b / a; // 22
c = c / a; // 23
b = b / -2; // 24
t = b * b; // 25
c = t - c; // 26
if (c<0) // 28
{
a = 0;
}
else
{
if (c<20) // 30
a = .1
else
a = 100
t = c / a; // 31
a = a + t; // 32
a = a / 2; // 33
t = c / a; // 34
a = a + t;
a = a / 2;
t = c / a; // 37
a = a + t;
a = a / 2;
t = c / a; // 40
a = a + t;
a = a / 2;
t = c / a; // 43
a = a + t;
a = a / 2;
t = c / a; // 46
t = a + t;
t = t / 2;
t = c / a; // 49
t = a + t;
t = t / 2;
t = c / a; // 52
t = a + t;
t = t / 2;
a = 2;
c = b + t; // 55
b = b - t; // 56
}
}
else if (b) // 57
{
a = 1;
b = b / c; // 58
b = -b; // 59
}
else if (c) // 60
{
a = 0;
}
else
{
a = 3;
}
}
A:
Hybrid of iterative approaches; score: 62
I originally posted an answer which purely used Newton-Raphson; however, in the cases of large b and c this requires a lot of iterations. Consider only the most interesting quadratics: those which have two solutions. If we normalise them to the form x^2 + bx + c = 0 then we can plot the number of iterations required for various approaches as a function of b and c. For example, we can modify the continued fraction route to get the direct approach:
c = -c;
a = b * 0.5;
while (loopCount-- > 0) { // This loop would be unrolled in the final solution
a = a + b;
a = c / a;
}
// Roots are a and -c/a
That gives a loop count diagram of
2236...................6322
2224n.................n4222
22236.................63222
22224n...............n42222
222236...............632222
222224m.............m422222
2222236.............6322222
2222224j...........j4222222
22222234P.........P43222222
22222223d.........d32222222
222222222t.......t222222222
2222222225Z.....Z5222222222
22222222219/////91222222222
/////////////./////////////
222222222*********222222222
222222222*********222222222
22222222***********22222222
22222223***********32222222
2222223*************3222222
2222224*************4222222
222223***************322222
222224***************422222
22223*****************32222
22224*****************42222
2223*******************3222
2224*******************4222
223*********************322
where c is negative in the first row and increases downwards, b increases from left to right, * means negative discriminant, / means only one root was within tolerance in 62 iterations, . means no root was within tolerance in 62 iterations, and numbers are in base-62 with digits 0-9a-zA-Z. This is pretty decent for a certain range, but fails completely for another range.
bmarks' original implementation is similar to (but not the same; this is a reimplementation from the continued fraction):
a = b;
while (loopCount-- > 0) {
a = c / a;
a = b - a;
}
// Roots are -a, -c/a (which is better than a-b)
with loop count diagram
1117...................7111
1112n.................n2111
11117.................71111
11112n...............n21111
111117...............711111
111112m.............m211111
1111117.............7111111
1111112j...........j2111111
11111115Q.........Q51111111
11111111d.........d11111111
111111113u.......u311111111
1111111116/...../6111111111
1111111111a/////a1111111111
1111111111111.1111111111111
111111111*********111111111
111111111*********111111111
11111111***********11111111
11111112***********21111111
1111111*************1111111
1111112*************2111111
111111***************111111
111113***************311111
11111*****************11111
11113*****************31111
1111*******************1111
1113*******************3111
111*********************111
My naïve N-R was quite bad, but the really interesting thing to note about it is where the worst areas are:
njfdcccccccccccccccccccdfjn
njgcbbbbbbbbbbbbbbbbbbbcgjn
njgc9999999999999999999cgjn
njgc9777777777777777779cgjn
njgc9666666666666666669cgjn
njgc9544444444444444459cgjn
njgc9521111111111111259cgjn
njgc9534444444444444359cgjn
njgc9535555555555555359cgjn
njgc9536777777777776359cgjn
njgc9536888888888886359cgjn
njgc9536899999999986359cgjn
njgc95368aaaaaaaaa86359cgjn
njgc95368aaaaaaaaa86359cgjn
njgc95368*********86359cgjn
njgc95369*********96359cgjn
njgc9536***********6359cgjn
njgc9536***********6359cgjn
njgc953*************359cgjn
njgc954*************459cgjn
njgc95***************59cgjn
njgc94***************49cgjn
njgc9*****************9cgjn
njgc8*****************8cgjn
njgc*******************cgjn
njgb*******************bgjn
njf*********************fjn
So the thing to do is to hybridise. For the areas where it's good, I use the continued fraction; for the rest, I use N-R, but I've done some optimisation: I've experimentally found two cutoffs and three initial values which converge in 5 iterations to a worst-case mixed error abs(value - correct_value) / (1 + abs(correct_value) of 0.000052. (Thanks to Martin Büttner for the idea of doing a case split). The final loop count (mixing the two cases into one diagram) is:
111555555555555555555555111
111233333333333333333332111
111133333333333333333331111
111125555555555555555521111
111115555555555555555511111
111112333333333333333211111
111111333333333333333111111
111111255555555555552111111
111111144444444444441111111
111111112111111111111111111
111111113222222222211111111
111111111333333333111111111
111111111444444444111111111
111111111111111111111111111
111111111*********111111111
111111111*********111111111
11111111***********11111111
11111112***********21111111
1111111*************1111111
1111112*************2111111
111111***************111111
111113***************311111
11111*****************11111
11113*****************31111
1111*******************1111
1113*******************3111
111*********************111
and the code is
solve_quad(&float a, &float b, &float c) {
float t; // 20 points
if (a != 0) { // 21
if (c == 0) {
// x(x+b) = 0
b = -b; // 22
a = 2;
}
else {
// Normalise so that we're solving x^2 + bx + c = 0 and have `a` free to use
// Hereon, mentions of b and c in comments refer to these normalised values.
b = b / a; // 22
c = c / a; // 23
// Three cases:
// b^2 < 4c: negative determinant, no solutions
// b^2 < -4c: use Newton-Raphson
// Otherwise: use the continued fraction method that bmarks was the first to post
a = b / 2; // 24
a = a * a; // 25
if (a < c) { // 26
a = 0;
}
else {
t = a + c; // 27
if (t < 0) { // 28
c = a - c; // 29, c holds the determinant
// Carefully optimised case split:
if (c < 0.05) // 30
a = 0.025;
else if (c < 250) // 31
a = 2;
else a = 193;
t = c / a; a = a + t; a = a / 2; // 34
t = c / a; a = a + t; a = a / 2; // 37
t = c / a; a = a + t; a = a / 2; // 40
t = c / a; a = a + t; a = a / 2; // 43
t = c / a; a = a + t; a = a / 2; // 46
// At this point a ~= sqrt(determinant)
t = b / 2; // 47
a = a + t; // 48
t = t * t; // 49
c = t - c; // 50
// At this point a ~= b/2 + sqrt(determinant) and c holds its original value
}
else {
a = b;
a = c / a; a = b - a; // 52
a = c / a; a = b - a; // 54
a = c / a; a = b - a; // 56
// At this point a ~= b/2 + sqrt(determinant)
}
b = -a; // 57
c = c / b; // 58
a = 2;
}
}
}
else {
// bx + c = 0
if (b != 0) { // 59
a = 1;
c = -c; // 60
b = c / b; // 61
}
else {
// c = 0
if (c != 0) a = 0; // 62
else a = 3;
}
}
}
A:
C# (46)
Used a different way of computing sqrt(x) (continued fractions http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Generalized_continued_fraction)
It fails for b=0 due to large rounding errors. I'm not sure how to fix that, but I hope I can help fellow contestants with a new way of doing the square roots.
Edit: Thanks to @Peter Taylor for the suggestion on how to handle b=0.
Edit 2: Thanks to @steveverrill for pointing out that there are only >2 solutions if c is also 0, thus requiring an extra if check.
public static void doStuff(ref double a, ref double b, ref double c)
{
if (a == 0) //1
{
if (b == 0) //2
{
if (c == 0){ //3
a = 3;
}
else {
a = 0;
}
}
else
{
b = -1 / b;//4
b = c * b;//5
a = 1;
}
}
else
{
b = b / a;//6
c = c / a;//7
if (b == 0) //8
{
b = 1 + 1E-7;// still just one constant; since 0.001/1000>1E-7, b can never equal this value normally
c = c + 0.25; //9
}
a = 2 * c;//10
a = a / b;//11
a = b - a;//12
a = c / a; a = b - a;//14
a = c / a; a = b - a;//16
a = c / a; a = b - a;//18
a = c / a; a = b - a;//20
a = c / a; a = b - a;//22
a = c / a; a = b - a;//24
a = c / a; a = b - a;//26
a = c / a; a = b - a;//28
a = c / a; a = b - a;//30
a = c / a; a = b - a;//32
a = c / a; a = b - a;//34
a = 2 / a;//35
a = c * a;//36
a = b - a;//37
if (b == 1 + 1E-7) //38
{
b = 0;
c = c - 0.25;//39
}
if (a == 0) //40
{
b = -1.0 / 2 * b;//41
c = b;
a = 2;
}
else
{
if (a < 0) //42
{
a = 0;
}
else
{
b = -1.0 / 2 * b;//43
a = a / 2;//44
c = b - a;//45
b = b + a;//46
a = 2;
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting data once and use it in all activities
I have a question about getting data from server.
I get general data in mainActivity of my app and I want to use it across all activities. I was thinking about using database to get my data once, save it in database and get it where I want from database. But now I'm thinking about using a Singleton class that I can use it to save data once amd get that data in every activity. Is it possible and is it a good idea?
Update :
Data Type is list of objects, So SharedPrefrences is not a good choice
and I want to save them temporally until application is running.
A:
You can save the data in any of the following sources
Shared Preferences
SqlLite Database
Android Room or any other ORM
Files (specially for images)
Based on your data type, you can decide one among these
| {
"pile_set_name": "StackExchange"
} |
Q:
select query inside in select query php mysql
<?php
$query = "select * from comments t1
inner join users t2 on t1.user_id = t2.UserId
where usercomplain_id='$id'";
$run =mysqli_query($mysqli,$query);
while($row=mysqli_fetch_array($run))
{
$commentid = $row['comment_id'];
$comment = $row['comment'];
$username = $row['UserName'];
$userid1 = $row['UserId'];
$date = $row['CDate'];
$ageDate = time_elapsed_string($date);
?>
<div class="jumbotron" style="border:3px solid #2FAB9B; background-color:#68C8C6;">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<?php echo $ageDate; ?>
</div>
</div>
<br>
<label>Comment by <a href="profile.php?id=<?php echo $userid1; ?>"><?php echo $username; ?></a></span></label><br>
<h5><b>Reply on this post</b></h5>
<?php
$query = "select * from Reply";
$run = mysqli_query($mysqli,$query);
?>
<a class="reply" data-role="<?php echo $commentid; ?>">Reply</a>
<br>
<br>
<div style="width:63%; display:none;" class="replyForm" data-role="<?php echo $commentid; ?>">
<form method="post">
<textarea name="comment[<?php echo $commentid; ?>]" cols="100" rows="4"></textarea><br>
<br>
<input type="submit" name="reply" class="btn btn-primary" style="float:right" value="reply">
</form>
</div>
</div>
<script>
It is a simple comment system in which after each comment I want to display replies on that particular comment using select inside a select query is returning only first record is there is any method to display those reply
A:
Your second query, which in inside the while loop, is over writing the result set of the first as both use the handle $run
This one
<?php
$query = "select * from Reply";
$run = mysqli_query($mysqli,$query);
?>
Not quite sure if you even use the result of this query actually
But if you do change $run to say... $run1 and at least it will not destroy $run while still inside the while loop that is using $run.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does XmlSerializer serialize an object to a file containing zeros instead of XML?
I have a strange case - it happens at a few customers that a config file saved during runtime using the XmlSerializer is saved as a sequence of zeros (bytes with value 0). The file length is what the expected file size for the given XML output would be (around 350 bytes).
This is the code used for serializing the file:
XmlSerializer s = new XmlSerializer(this.GetType());
using (StreamWriter sw = new StreamWriter(File.Create(path), Encoding.Default))
{
s.Serialize(sw, this, new XmlSerializerNamespaces());
}
The config file model is simple - a class with automatic properties of type string, bool, DateTime and one property of enum type.
I am sure File.Create with some subsequent failure is not causing this - if I do File.Create on an existing file, it just sets its length to zero.
I tried adding a throw new Exception() statement before the s.Serialize call - also not the culprit - file is trimmed to zero length
What could be causing XmlSerializer to output zeros instead of the actual XML?
A:
I found a similar question with a perfect answer matching my symptoms:
From Malcolm:
We've encountered this problem several times at $WORK, with the
symptom being an empty file of the correct size but filled with zero
bytes.
The solution we found was to set the WriteThrough value on the
FileStream:
using (Stream file = new FileStream(settingTemp, FileMode.Create,
FileAccess.Write, FileShare.None,
0x1000, FileOptions.WriteThrough))
{
using (StreamWriter sw = new StreamWriter(file))
{
...
}
}
Original answer at https://stackoverflow.com/a/8858975/163393
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert active to passive
Need help converting this sentence to passive voice:-
The students will assemble in the hall.
I think it should be:-
The hall will be assembled by the students.
But it sounds like students are building the hall by putting together some pieces.
Should I change it to assembled in by the students? Or something else?
A:
I in comments wrote to John Lawler:
What, you don’t like “The students will go downtown for lunch” becoming “Downtown will be gone to by the students for lunch” much, eh? :-) Because such abominations do crop up from not-native speakers from time to time, I suspect nobody ever let them in on the joke in the first place.
And then to the asker:
You can't ever do passive inversion on intransitive verbs, including both yours and mine. If what I wrote sounds right to you, somebody has trained you wrong because it’s completely ungrammatical in English. You must have a transitive verb with a direct object to use passive inversion on so that you can invert subject and object. Intransitive verbs lack an object to use for the subject.
Also, homework is a mass noun not a count noun, so you can never say *a homework.
| {
"pile_set_name": "StackExchange"
} |
Q:
Determine values for differential equation system asymptotic stable
I have this differential equation system where $k \in \mathbb{R}$ is a number.
How can I determine which values of $\textit{k}$ is the differential system asymptotic stable?
And does anybody have an easy setup for these cases (stability)
Thanks a lot!
A:
Using Mathematica's function RSolve you can solve the system of difference, and not differential, equations:
system = {x[t + 1] == 1/2 x[t] + k y[t] - 1/2 (-1)^t k^t,
y[t + 1] == k x[t] + 1/2 y[t] + 1/2 (-1)^t k^t}
RSolve[Join[system,{x[0] == x0, y[0] == y0}], {x[t], y[t]},t][[1]]//FullSimplify
$$x_t=\frac{1}{2} \left(2 (-1)^{t} k^t+\left(\frac{1}{2}-k\right)^t (-2+\text{x0}-\text{y0})+\left(\frac{1}{2}+k\right)^t (\text{x0}+\text{y0})\right),\\
y_t=\frac{1}{2} \left(-2 (-1)^{t} k^t+\left(\frac{1}{2}-k\right)^t (2-\text{x0}+\text{y0})+\left(\frac{1}{2}+k\right)^t (\text{x0}+\text{y0})\right)
$$
to check the stability now you have to check where the terms $k^t, \left(\frac{1}{2}-k\right)^t, \left(\frac{1}{2}+k\right)^t$ converge. All those terms converge for $\lvert k\rvert<\frac{1}{2}$. And they converge to the attractor $y=-x$.
Visually:
data = Table[#, {t, 0, 100}]&/@Flatten[
Table[{1/2 (2 (-k)^t + (1/2 - k)^t (-2 + x0 - y0) +
(1/2 + k)^t (x0 + y0)),
1/2 (-2 (-k)^t + (1/2 - k)^t (2 - x0 + y0) +
(1/2 + k)^t (x0 + y0))},
{x0, -2, 2, 0.5}, {y0, -2, 2, 0.5}], 1];
(* unstable case*)
ListPlot[data/.k -> 1/8, PlotRange -> All, Joined -> True,
InterpolationOrder -> 2]
(* unstable case*)
ListPlot[data /. k -> 3/4, Joined -> True, InterpolationOrder -> 2,
PlotRange -> {{-10, 10}, {-10, 10}}]
Observe that the orbits go to infinity along the diagonal $y=x$. The bigger the value of $k$ the bigger the "fluctuation":
ListPlot[data /. k -> 2, Joined -> True, InterpolationOrder -> 2,
PlotRange -> {{-100, 100}, {-100, 100}}]
Its a mystery to me why they redirected here from the Mathematica.SE :/
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML/Javascript for Chrome Extension not quite working
So I'm trying to make a chrome extension. My code works fine when I run it as a normal html page, but when I use browser action, my enable/disable button doesn't work. It doesn't do anything when I press enable (Which it should switch to disable). Was wondering if there is something I don't know about like permissions or something. I haven't set any permissions in my json page but I didn't think it was the problem. Was wondering if you guys can take a look and see what I'm missing. Here's my code.
<html>
<head>
<link rel="stylesheet" type="text/css" href="nosidebar.css">
<script type="text/javascript">
function enableBtn(){
document.getElementById("btn1").style.display = "none";
document.getElementById("btn2").style.display = "";
return false;
}
function disableBtn(){
document.getElementById("btn2").style.display = "none";
document.getElementById("btn1").style.display = "";
return false;
}
</script>
</head>
<body>
<div id="button">
<a href="javascript:void(0)" class="myButton1" title="Click to disable" id="btn1" style="display:;" onclick="enableBtn(); return false;">Enabled</a>
<a href="javascript:void(0)" class="myButton2" title="Click to enable" id="btn2" style="display:none;" onclick="disableBtn(); return false;">Disabled</a>
</div>
<div id="text">
You must refresh the page for the change to take effect.
</div>
</body>
</html>
Thanks to @duskwuff I have fixed my problem. I created a separate js file and used the following code.
function enableBtn(){
document.getElementById("btn1").style.display = "none";
document.getElementById("btn2").style.display = "";
return false;
}
function disableBtn(){
document.getElementById("btn2").style.display = "none";
document.getElementById("btn1").style.display = "";
return false;
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("btn1").addEventListener("click", enableBtn);
document.getElementById("btn2").addEventListener("click", disableBtn);
});
A:
HTML pages used as part of Google Chrome extensions always have a Content Security Policy set which prohibits inline scripts, both in attributes (e.g. onclick) and inline <script> tags. You will need to define these scripts in a separate Javascript file and bind event handlers in that script, e.g.
<script src="nosidebar.js"></script>
and in that file:
function enableBtn() { ... }
function disableBtn() { ... }
document.getElementById("btn1").addEventListener("click", enableBtn);
document.getElementById("btn2").addEventListener("click", disableBtn);
For more information on Content Security Policy and how it relates to Chrome extensions, please refer to:
https://developer.chrome.com/extensions/contentSecurityPolicy
| {
"pile_set_name": "StackExchange"
} |
Q:
In-App-Billing Remove Ads Works after payment but after destroying the app not
I am trying to use the in-app-billing API for the first time.
I have tested the app with a different account and the payment went through and the ads were removed from the app. However, when I destroyed the app and they launching it again the ads were present again. I dont understand what I am doing wrong. Please does anybody has a suggestion?
This is my code in main acticity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private RecyclerView mRecyclerView;
private ArrayList<String> shoppingListItems;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private TextView mEmptyTextView;
private ShoppingListAdapter adapter;
private ActionButton actionButton;
private MaterialDialog addItemdialog = null;
private AdView mAdView;
private IabHelper mHelper;
private String SKU_REMOVE_ADDS = "remove_adds_sku";
private boolean mIsRemoveAdds = false;
private IabHelper.OnIabPurchaseFinishedListener mPurchasedFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
@Override
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_REMOVE_ADDS)) {
// consume the gas and update the UI
mIsRemoveAdds = true;
mAdView.setVisibility(View.GONE);
Toast.makeText(MainActivity.this,"Purchase successful",Toast.LENGTH_LONG).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEmptyTextView = (TextView)findViewById(R.id.list_empty);
mEmptyTextView.setVisibility(View.INVISIBLE);
mSharedPreferences = getPreferences(MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
queryPurchasedItems();
//load ads
if(!mIsRemoveAdds) {
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}else{
mAdView.setVisibility(View.GONE);
}
String publicKey = s1+s2+s3+s4+s5;
mHelper = new IabHelper(this,publicKey);
if(mHelper != null) {
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
@Override
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
//error
Log.d(TAG, "Proglem setting up in-app Billing: " + result);
}
//Horay, IAB is fully set up!
Log.d(TAG, "Horay, IAB is fully set up!");
}
});
}
}
private void queryPurchasedItems() {
//check if user has bought "remove adds"
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
@Override
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (result.isFailure()) {
// handle error here
Toast.makeText(MainActivity.this,"error",Toast.LENGTH_LONG).show();
}
else{
// does the user have the premium upgrade?
mIsRemoveAdds = inventory.hasPurchase(SKU_REMOVE_ADDS);
if(!mIsRemoveAdds){
Toast.makeText(MainActivity.this,"no premium",Toast.LENGTH_LONG).show();
}
// update UI accordingly
Toast.makeText(MainActivity.this,"premium",Toast.LENGTH_LONG).show();
}
}
};
}
@Override
protected void onResume() {
super.onResume();
queryPurchasedItems();
//Toast.makeText(MainActivity.this,"On Resume",Toast.LENGTH_LONG).show();
//read isRemoveAdds from shared preferences
//mIsRemoveAdds = mSharedPreferences.getBoolean(Constants.IS_REMOVE_ADDS,false);
if(!mIsRemoveAdds) {
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}else{
mAdView.setVisibility(View.GONE);
}
isListEmpty();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
mAdView.destroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(id == R.id.action_remove_adds){
mHelper.launchPurchaseFlow(this,SKU_REMOVE_ADDS,1,mPurchasedFinishedListener,"");
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
// Pass on the activity result to the helper for handling
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
// not handled, so handle it ourselves (here's where you'd
// perform any handling of activity results not related to in-app
// billing...
//setContentView(R.layout.activity_main_adds);
super.onActivityResult(requestCode, resultCode, data);
}
else {
Log.d(TAG, "onActivityResult handled by IABUtil.");
//setContentView(R.layout.activity_main_adds);
}
}
A:
You need to move your if statement
if(!mIsRemoveAdds) {
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}else{
mAdView.setVisibility(View.GONE);
}
to onQueryInventoryFinished. This is because you're displaying ads before the app has a chance to check if the user has purchased the upgrade, and then after the check is complete, you never hide the ads again.
So, remove the above if statement from your onCreate and onResume method and format your onQueryInventoryFinished method like so:
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (result.isFailure()) {
// handle error here
Toast.makeText(MainActivity.this,"error",Toast.LENGTH_LONG).show();
}
else{
// does the user have the premium upgrade?
mIsRemoveAdds = inventory.hasPurchase(SKU_REMOVE_ADDS);
if(!mIsRemoveAdds){
Toast.makeText(MainActivity.this,"no premium",Toast.LENGTH_LONG).show();
// user does not have premium, load ads
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
} else {
Toast.makeText(MainActivity.this,"premium",Toast.LENGTH_LONG).show();
// user has premium, hide ads
mAdView.setVisibility(View.GONE);
}
}
}
Disclaimer I've never worked with the purchases api before, so this exact code may not work, but the general idea that you're not hiding the ads after checking for the purchase is right.
| {
"pile_set_name": "StackExchange"
} |
Q:
Webservice php sem usar o soap?
Não tenho familiaridade com Webservice e queria saber como fazer um, sem a necessidade de usar Soap (para pegar dados do banco e consumir no Android Studio).
A:
Usa JSON como retorno...
Aí no Android você recebe com auxílio de alguma biblioteca e cria os objetos usando Gson
Exemplo simples no php que retorna um JSON array:
$result = $this->con->query("SELECT * FROM usuario");
if ($result->num_rows > 0) {
while ($obj = mysqli_fetch_object($result)) {
$lista[] = $obj;
}
}
return $lista;
| {
"pile_set_name": "StackExchange"
} |
Q:
Highlight selected header in preference-headers
I'm using the new preference-headers to show the settings in my application.
While the standard settings activity on my Motorola Xoom shows the selected item in the header list with a blue background, my settingsactivity that extend PreferenceActivity does not highlight the selected item in any way.
Is there a way to do it?
A:
I fixed it. It was enough to use:
<uses-sdk android:minSdkVersion="11"/>
in the AndroidManifest: it used to be ="9" previously.
If you switch to 11 you will we see many changes: the menu is on the top and not on the bottom, the application icon is shown on the top-left and the title font is bigger
To customize the highlight etc I used:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.SettingsActivity" parent="@android:style/Theme">
<item name="android:listSelector">@color/green</item>
</style>
</resources>
In the AndroidManifest for the SettingsActivity I used:
android:theme="@style/Theme.SettingsActivity"
After switching to minsdk=11 it works
| {
"pile_set_name": "StackExchange"
} |
Q:
OpenGL program isn't rendering on Ubuntu with VirtualBox
I'm starting to learn OpenGL and I decided to use Ubuntu 15.10 on a VirtualBox to do this. I installed the packages mesa-common-dev (gl.h), libglew-dev (glew.h) and libglfw3-dev (glfw3.h) and following this tutorial I came up with this code:
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
using namespace std;
const GLchar* vertexSource =
"#version 130\n"
"in vec2 position;"
"void main() {"
" gl_Position = vec4(position, 0.0, 1.0);"
"}";
const GLchar* fragmentSource =
"#version 130\n"
"out vec4 outColor;"
"uniform vec3 triangleColor;"
"void main() {"
" outColor = vec4(triangleColor, 1.0);"
"}";
int main(int argc, char *argv[]) {
// GLFW initialization
if (!glfwInit()) {
cout << "Failed to initialize GLFW." << endl;
return -1;
}
cout << "GLFW initialized." << endl;
GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL", nullptr, nullptr);
glfwMakeContextCurrent(window);
cout << "Window and context created." << endl;
// GLEW initialization
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
cout << "Failed to initialize GLEW." << endl;
return -1;
}
cout << "GLEW initialized." << endl;
GLfloat vertices[] = {
0.0f, 0.5f,
0.5f, -0.5f,
-0.5f, -0.5f
};
// Create Vertex Array Object
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
cout << "VAO created and binded." << endl;
//Vertex Buffer Object
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
cout << "VBO created and binded." << endl;
// Create and compile the vertex shader
GLint status;
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexSource, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
if (!status) {
// Vertex shader error handling
char errorLog[512];
glGetShaderInfoLog(vertexShader, 512, NULL, errorLog);
cout << errorLog << endl;
glfwTerminate();
return -1;
}
cout << "Vertex shader created and compiled." << endl;
// Create and compile the fragment shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);
if (!status) {
// Fragment shader error handling
char errorLog[512];
glGetShaderInfoLog(fragmentShader, 512, NULL, errorLog);
cout << errorLog << endl;
glfwTerminate();
return -1;
}
cout << "Fragment shader created and compiled." << endl;
// Link the vertex and fragment shader into a shader program
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glBindFragDataLocation(shaderProgram, 0, "outColor");
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
cout << "Shaders linked." << endl;
// Specify the layout of the vertex data
GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
cout << "Layout of the vertex data specified." << endl;
while( !glfwWindowShouldClose(window) ) {
glDrawArrays(GL_TRIANGLES, 0, 3);
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
glfwSwapBuffers(window);
glfwPollEvents();
}
// Prepare to close the application
glDeleteProgram(shaderProgram);
glDeleteShader(fragmentShader);
glDeleteShader(vertexShader);
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &vao);
glfwTerminate();
return 0;
}
I'm compiling it as g++ test.cpp -o test -lglfw -lGLEW -lGL with no errors.
But, when I execute the program, it opens the window with a black screen without rendering the triangle. I tried to execute this code that someone posted on the comments of the tutorial but I got the same black screen and no polygons rendered. Is the problem on the code? Did I miss something when setting OpenGL up? Are the compiling parameters correct?
A:
Since I didn't declare colors neither for the background nor for the triangle, both of them were black by default. Thus, the triangle was not visible althought it was being rendered. Setting up colors for both of them solved the problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are RavenDB bundles still published via NuGet?
I have a unit test project with references to Raven.Client.Embedded and Raven.Database v2.0.3, which were added via NuGet. I was looking to add the RavenDB Versioning bundle, also via NuGet, but the current Versioning package references Raven.Database v1.0.992.
Is there a new way to include bundles into an embedded document store, or is NuGet still the right way to go? And if it's still NuGet, can I help in some way to get the published package updated in the NuGet Gallery?
A:
The versioning bundle is now part of the RavenDB core, and doesn't require a separate bundle.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to access suspend Dao function from a CoroutineScope launch
i have a simple Dao interface of Room database in which I have suspend functions to insert and get data from the table.
in my DBHelper class I am trying to insert data using launch - CoroutineScope but does not seem to go within the launch and the functions within the launch are not executed.
any suggestions on what I might be doing wrong please
OfflineDataDao
@Dao
interface OfflineDataDao {
@Query("SELECT * FROM offlineDatax")
suspend fun getOfflineData(): List<OfflineDatax>
@Insert
suspend fun insertOfflineData(offlineData: OfflineDatax): Long
}
Entity
@Entity
data class OfflineDatax (
@PrimaryKey val uid: Int,
@ColumnInfo(name = "requestJSON") val requestJSON: String?,
@ColumnInfo(name = "requestCode") val requestCode: String?
)
DBHelper
class where I am accessing the dao suspend methods
class DBHelper @Inject constructor(
private val userDao: UserDao,
private val offlineDataDao: OfflineDataDao
) : CoroutineScope {
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
fun accessDBFunction() {
var offlineDatax = OfflineDatax(1, "rjson", "rCode")
addOfflineData(offlineDatax)
getOfflineData()
}
fun addOfflineData(offlineDatax: OfflineDatax): Long {
var lng: Long = 0L
launch {
lng = offlineDataDao.insertOfflineData(offlineDatax) // IS NOT CALLED, DOES NOT GET INTO LAUNCH
}
return lng
}
fun getOfflineData (): List<OfflineDatax> {
var offlineData = emptyList<OfflineDatax>()
launch {
offlineData = offlineDataDao.getOfflineData(); // IS NOT CALLED, DOES NOT GET INTO LAUNCH
}
Timber.d("offlinedata " + offlineData.toString())
return offlineData
}
}
A:
Just make the function suspend, via suspend modifier and return from them directly they will suspend themselves into their own dispatcher defined in the Room library.
suspend fun addOfflineData(offlineDatax: OfflineDatax): Long =
offlineDataDao.insertOfflineData(offlineDatax)
suspend fun getOfflineData (): List<OfflineDatax> =
offlineDataDao.getOfflineData().also { Timber.d("offlinedata " + it.toString()) }
And call the function from any coroutine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Gluon iOS audio Player
I've been following various answers to various questions on the subject and I've come to a result and some code which looks like it works. I'm getting stuck with the NSURL part of it. I've got 2 mp3 tracks in the assets folder of my iOS gluon project. I've made the IOSAudioService Class to handle the playback. and I'm passing an argument from the play button in the view to the Play() method. Everything other than the actual file is registering as working. I'm getting an NSError, which from looking at the code is a nil value, so either the argument isn't passing correctly or it can't find the file. Code below.
public AVAudioPlayer backgroundMusic;
private double currentPosition;
NSURL songURL = null;
@Override
public void Play(String filename){
songURL = new NSURL(filename);
try {
if (backgroundMusic != null) {
Resume();
}
else {
//Start the audio at the beginning.
currentPosition = 0;
backgroundMusic = new AVAudioPlayer(songURL);
//create the mendia player and assign it to the audio
backgroundMusic.prepareToPlay();
backgroundMusic.play();}
//catch the audio error
} catch(NSErrorException e) {
System.out.println("error: " + e);
}
}
@Override
public void Stop() {
backgroundMusic.stop();
backgroundMusic = null;
}
@Override
public void Pause() {
currentPosition = backgroundMusic.getCurrentTime();
backgroundMusic.pause();
}
@Override
public void Resume() {
backgroundMusic.setCurrentTime(currentPosition);
backgroundMusic.play();
}
try {
services = (AudioService) Class.forName("com.gluonhq.charm.down.plugins.ios.IOSAudioService").newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
System.out.println("Error " + ex);
}
I'm getting the error at the catch block for NSExceptionError e.
if (services != null) {
final HBox hBox = new HBox(10,
MaterialDesignIcon.PLAY_ARROW.button(e -> services.Play("/audio.mp3")),
MaterialDesignIcon.PAUSE.button(e -> {
if (!pause) {
services.Pause();
pause = true;
} else {
services.Resume();
pause = false;
}
}),
MaterialDesignIcon.STOP.button(e -> services.Stop()));
//set the HBox alignment
hBox.setAlignment(Pos.CENTER);
hBox.getStyleClass().add("hbox");
//create and set up a vbox to include the image, audio controls and the text then set the alignment
final VBox vBox = new VBox(5, Image(), hBox, text1);
vBox.setAlignment(Pos.CENTER);
setCenter(new StackPane(vBox));
} else {
//start an error if service is null
setCenter(new StackPane(new Label("Only for Android")));
}
Services.get(LifecycleService.class).ifPresent(s -> s.addListener(LifecycleEvent.PAUSE, () -> services.Stop()));
}
I've also follow the advice on creating the service factory class and the interface from Audio performance with Javafx for Android (MediaPlayer and NativeAudioService) taking out the add audio element and I'm intending to do this on a view by view basis if possible.
A:
Problem solved after must fiddling and looking in the Javadocs.Solved by adding/replacing some code with the below.
songURL = new NSURL("file:///" + NSBundle.getMainBundle().findResourcePath(filename, "mp3"));
try {
songURL.checkResourceIsReachable();}
catch(NSErrorException d) {
System.out.println("Song not found!" + d);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Using summarise with weighted mean from dplyr in R
I'm trying to tidy a dataset, using dplyr. My variables contain percentages and straightforward values (in this case, page views and bounce rates). I've tried to summarize them this way:
require(dplyr)
df<-df%>%
group_by(pagename)%>%
summarise(pageviews=sum(pageviews), bounceRate= weighted.mean(bounceRate,pageviews))
But this returns:
Error: 'x' and 'w' must have the same length
My dataset does not have any NA's in the both the page views and the bounce rates.
I'm not sure what I'm doing wrong, maybe summarise() doesn't work with weighted.mean()?
EDIT
I've added some data:
### Source: local data frame [4 x 3]
### pagename bounceRate pageviews
(chr) (dbl) (dbl)
###1 url1 72.22222 1176
###2 url2 46.42857 733
###3 url2 76.92308 457
###4 url3 62.06897 601
A:
The summarize() command replaces variables in the order they appear in the command, so because you are changing the value of pageviews, that new value is being used in the weighted.mean. It's safer to use different names
df %>%
group_by(pagename)%>%
summarise(pageviews_sum = sum(pageviews),
bounceRate_mean = weighted.mean(bounceRate,pageviews))
And if you really want, you can rename afterward
df %>%
group_by(pagename) %>%
summarise(pageviews_sum = sum(pageviews),
bounceRate_mean = weighted.mean(bounceRate,pageviews)) %>%
rename(pageviews = pageviews_sum, bounceRate = bounceRate_mean)
A:
I've found the solution.
Since summarise(pageviews=sum(pageviews) is evaluated before bounceRate= weighted.mean(bounceRate,pageviews), the length of pageviewsis reduced and therefore shorter than bounceRate, which triggers the error.
The solution is simple, just switch them:
require(dplyr)
df<-df%>%
group_by(pagename)%>%
summarise(bounceRate= weighted.mean(bounceRate,pageviews),pageviews=sum(pageviews))
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between plugins and dependencies in the Vue.js UI?
When using the ui you have the option of installing dependencies and plugins.
I am confused about the difference between both of these.
For instance, I can install axios as a dependency and a plugin.
Do I need to do both? Why do one over the other?
My current understanding is that dependency is just that, it adds a package to your project while a plugin will add configuration as well.
Am I correct in thinking that?
A:
A plugin is exactly what you described. It 'plugs into' another piece of software and adds functionality. A dependency on the other hand means that your software simply depends on something to function correctly - usually code.
In your axios example:
The axios plugin installs another prototype property on your Vue instance (this.$axios.. or whatever it is called) so it definitely adds a feature to Vue.
You could also only use Axios by itself and import it in the files you need
import axios from 'axios'. You don't add any feature to Vue itself - you just use another software within your app. Axios here is a dependency.
A:
I will probably not be completely correct, but my understanding is
Plugins vs Dependencies
Command line
dependencies are installed via the command line as npm install <name> or npm install --save <name> to add the dependency to package.json
plugins are installed via the command line as vue add @scope/vue-cli-plugin-<name> or with the shorthand vue add @scope/<name>
Installation
dependencies are placed into your projects node_modules folder
plugins will invoke the generator.js script of the plugin being installed. This generator.js may add dependencies to package.json, add import statements to files in your project, add/alter existing components, or any of the various things listed under the generator api docs
Usage
dependencies will need to be imported into any file you use them in, or imported globally, before they are able to be used
plugins often will have already set up global imports, making them available in every file. Plugins will also often add additional scripts to package.json (which show up as tasks in the vue ui)
| {
"pile_set_name": "StackExchange"
} |
Q:
AppExchange Partner Program Models
What are the AppExchange Partner Program Models ? What is 15% and 25% net revenue in the models ?
I got this values stated on http://www.salesforce.com/partners/isv/program-models/ this link.
Thank you in advance.
A:
When you create an ISV app (to publish on the appexchange) and you want to sell and use it as a standalone app, meaning when someone logs in your app the only thing they can see, do and use, are the objects, tabs, logic, and everything else you created yourself to be in your app (for example a software suite to manage a car-park)
This way you can market and sell your app to anyone interested (your customers don't need to already have a Salesforce license)
This means that besides the revenue you get for your app, salesforce doesn't get anything else (no license fees), meaning you'll have to give salesforce 25% of your revenue, for use of the platform.
When however you create an app that works more like a plug-in to existing salesforce logic (for example an invoicing module that works based on the data in Opportunities). Your client already has a salesforce license, and salesforce gets revenue from those licenses already, and salesforce is so kind to lower the cost for the use of the platform down to 15% of the revenue you generate only with your app.
| {
"pile_set_name": "StackExchange"
} |
Q:
Array returning all zeros
I have been playing with it and the problem is in my array resultArray(i).
When instead of the line resultArray(i) = Sheets("DeSL_CP").Range("P" & j).Value, I use .Range("M" & i).Value = Sheets("DeSL_CP").Range("P" & j).Value, it works, but takes longer.
Why is resultarray(i) returning all zeros?
Original post:
I have two sheets: Summary has a productid in col A and a field that marks the product as unlicensed or licensed in AK. DeSL_CP has multiple lines for each productId (in col B).
I need to find the line with activity code (Col K) AA0001 for unlicensed product and return the date for baseline end (col P). Then I need to find the code A0003 for the remaining products and return that lines baseline end. Baseline N should be in col M of the summary sheet.
My code is not throwing errors. It populates all of column M with 1/0/1900.
Sheets("Summary").Select
Dim lastRow As Long, lastRow1 As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row
lastRow1 = Sheets("DeSL_CP").Range("A" & Rows.Count).End(xlUp).Row
lastRow1 = lastRow1 - 1
Dim BaselineEnd As Variant, ActivityCode As Variant, ProductIDDeSL As Variant, _
Licensed As Variant, ProductIDSumm As Variant
BaselineEnd = ThisWorkbook.Worksheets("DeSL_CP").Range("P2:P" & lastRow1).Value
ActivityCode = ThisWorkbook.Worksheets("DeSL_CP").Range("K2:K" & lastRow1).Value
ProductIDDeSL = ThisWorkbook.Worksheets("DeSL_CP").Range("B2:B" & lastRow1).Value
Licensed = ThisWorkbook.Worksheets("Summary").Range("AK7:AK" & lastRow).Value
ProductIDSumm = ThisWorkbook.Worksheets("Summary").Range("A7:A" & lastRow).Value
Dim resultArray() As Date
ReDim resultArray(7 To lastRow)
Dim i As Long, j As Long
With ThisWorkbook.Worksheets("Summary")
For i = 7 To UBound(ProductIDSumm)
For j = 2 To UBound(ProductIDDeSL)
If ProductIDSumm(i, 1) = ProductIDDeSL(j, 1) Then
If Licensed(i, 1) = "Unlicensed" Then
If ActivityCode(j, 1) = "AA0001" Then
resultArray(i) = Sheets("DeSL_CP").Range("P" & j).Value
Exit For
End If
Else
If ActivityCode(j, 1) = "A0003" Then
resultArray(i) = Sheets("DeSL_CP").Range("P" & j).Value
Exit For
End If
End If
End If
Next j
Next i
.Range("M7").Resize(lastRow - 7 + 1, 1).Value = resultArray
End With
There are times it is blank, but many times not. I hid a lot of data to focus on the columns that matter. It is in century month - does that matter?
A:
In the code some issues found like lastRow1 = Sheets("DeSL_CP").Range("A" & Rows.Count).End(xlUp).Row preferred to be based on Col B. also think starting value for the For loops should be 1 instead of 7 and 2 (depending on Option Base). ResultArray could be populated directly from BaselineEnd(j, 1). Finally ResultArray was solved with Range("M7").Resize(UBound(resultArray), 1).Value = resultArray. The Consolidated final code:
Option Base 1
Sub test()
Sheets("Summary").Select
Dim lastRow As Long, lastRow1 As Long
lastRow = Sheets("Summary").Range("A" & Rows.Count).End(xlUp).Row
lastRow1 = Sheets("DeSL_CP").Range("B" & Rows.Count).End(xlUp).Row
lastRow1 = lastRow1 - 1
Dim BaselineEnd As Variant, ActivityCode As Variant, ProductIDDeSL As Variant, Licensed As Variant, ProductIDSumm As Variant
BaselineEnd = ThisWorkbook.Worksheets("DeSL_CP").Range("P2:P" & lastRow1).Value
ActivityCode = ThisWorkbook.Worksheets("DeSL_CP").Range("K2:K" & lastRow1).Value
ProductIDDeSL = ThisWorkbook.Worksheets("DeSL_CP").Range("B2:B" & lastRow1).Value
Licensed = ThisWorkbook.Worksheets("Summary").Range("AK7:AK" & lastRow).Value
ProductIDSumm = ThisWorkbook.Worksheets("Summary").Range("A7:A" & lastRow).Value
Dim resultArray() As Date
ReDim resultArray(lastRow - 7 + 1, 1)
Dim i As Long, j As Long
With ThisWorkbook.Worksheets("Summary")
For i = 1 To UBound(ProductIDSumm)
For j = 1 To UBound(ProductIDDeSL)
'If Not Sheets("DeSL_CP").Rows(j).Hidden Then
If ProductIDSumm(i, 1) = ProductIDDeSL(j, 1) Then
If Licensed(i, 1) = "Unlicensed" Then
If ActivityCode(j, 1) = "AA0001" Then
resultArray(i, 1) = BaselineEnd(j, 1)
Exit For
End If
Else
If ActivityCode(j, 1) = "A0003" Then
resultArray(i, 1) = BaselineEnd(j, 1)
Exit For
End If
End If
End If
'End If
Next j
Next i
Range("M7").Resize(UBound(resultArray), 1).Value = resultArray
End With
End Sub
I tried simply with out any array and found working correctly
Sub test2()
Sheets("Summary").Select
Dim lastRow As Long, lastRow1 As Long
Dim i, j As Long, Found As Boolean
lastRow = Range("A" & Rows.Count).End(xlUp).Row
lastRow1 = Sheets("DeSL_CP").Range("B" & Rows.Count).End(xlUp).Row
lastRow1 = lastRow1
Dim BaselineEnd As Variant, ActivityCode As Variant, ProductIDDeSL As Variant, Licensed As Variant, ProductIDSumm As Variant
For i = 7 To lastRow
Found = False
ProductIDSumm = ThisWorkbook.Worksheets("Summary").Cells(i, 1).Value
Licensed = ThisWorkbook.Worksheets("Summary").Cells(i, 37).Value
If ProductIDSumm <> "" Then
For j = 2 To lastRow1
ProductIDDeSL = ThisWorkbook.Worksheets("DeSL_CP").Cells(j, 2).Value 'Col B
ActivityCode = ThisWorkbook.Worksheets("DeSL_CP").Cells(j, 11).Value 'Col K
BaselineEnd = ThisWorkbook.Worksheets("DeSL_CP").Cells(j, 16).Value ' Col P
If ProductIDDeSL <> "" Then ' to skip blank rows
If ProductIDSumm = ProductIDDeSL Then
If Licensed = "Unlicensed" Then
If ActivityCode = "AA0001" Then
Found = True
Exit For
End If
Else
If ActivityCode = "A0003" Then
Found = True
Exit For
End If
End If
End If
End If
Next j
ThisWorkbook.Worksheets("Summary").Cells(i, 13).Value = IIf(Found, BaselineEnd, "Not Found")
End If
Next i
Edit: Since You are supposedly in possession of a large data and having processing time problem. merely on curiosity I am adding the find method solution as third option
Sub test3()
Sheets("Summary").Select
Dim lastRow As Long, lastRow1 As Long
Dim i, j As Long, Found As Boolean
lastRow = Sheets("Summary").Range("A" & Rows.Count).End(xlUp).Row
lastRow1 = Sheets("DeSL_CP").Range("B" & Rows.Count).End(xlUp).Row
lastRow1 = lastRow1
Dim RngIDsm, RngIDde, Cl, Cl2 As Range
Set RngIDsm = Sheets("Summary").Range("A7:A" & lastRow)
Set RngIDde = Sheets("DeSL_CP").Range("B2:B" & lastRow1)
Dim BaselineEnd As Variant, ActivityCode As Variant, ProductIDDeSL As Variant, Licensed As Variant, ProductIDSumm As Variant
For Each Cl In RngIDsm
Found = False
ProductIDSumm = Cl.Value
Licensed = Cl.Offset(, 36).Value
With RngIDde
Set Cl2 = .Find(ProductIDSumm, LookIn:=xlValues)
If Not Cl2 Is Nothing Then
firstAddress = Cl2.Address
Do
ActivityCode = Cl2.Offset(, 9).Value 'Col K
If Licensed = "Unlicensed" Then
If ActivityCode = "AA0001" Then
BaselineEnd = Cl2.Offset(, 14).Value
Found = True
Exit Do
End If
Else
If ActivityCode = "A0003" Then
BaselineEnd = Cl2.Offset(, 14).Value
Found = True
Exit Do
End If
End If
Set Cl2 = .FindNext(Cl2)
Loop While Not Cl2 Is Nothing And Cl2.Address <> firstAddress
End If
End With
Cl.Offset(, 12).Value = IIf(Found, BaselineEnd, "Not Found")
Next Cl
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
How to approach a narcissist parent about their unkind and unreasonable treatment of a sibling?
TL;DR: My dad is calling my sister an embarrasment while I'm the "golden child" that seems to do most things right in his eyes. My dad seems to not realize that me and my sister talk often, and she expresses her frustrations to me often about his words.
Related to this question: What to say to steer passive-aggressive narcissist parent(s) away from saying guilt-tripping statements to me or other people?
The other day, she informed me that he was embarrassed that she did not give him anything for his birthday in front of his friends. On further investigation, I found that she indeed had photographed and developed (at school) two pictures and given them to him for his birthday. She simply forgot that the photos were in her room (she thought they were at our mother's house), and did not bring them out to show everyone. He feels that her thoughtful and simple gift of two photos she developed herself was not enough.
His words to my sister:
"I'm amazed lately at how unappreciated you make me feel."
She is away at camp for this week, and she expects a stern talking-to from him when she returns because she is an ungrateful child, and needs to learn that lesson. She is dreading it.
At this point, I know he will fire away at me for not behaving as he thinks I should, and there's nothing I can do to avoid it. I will just ignore his words and not attempt to explain myself, like I've done in the past. I have gone to counseling 8+ years for this, and I have mentally drawn the boundaries for myself. My #1 frustration is that he's taking this slight from her very personally.
I do see his side of it, and I understand his relationship with all three of his daughters have been rocky, and he's trying to get through it. However, I think he has Narcissist Personality Disorder. This exacerbates the issues that we have with each other.
How do I call my dad out on his demeaning statements towards my sister, and make him think twice about it?
A:
I don't know if there is anything that you can do about your father. If he can be persuaded to go to counseling, that would be great, but it doesn't sound like that's something you can count on.
My advice would be that you support your sister by standing up for her if he "attacks" her in your presence. It may not change his behavior, but the very fact that she has a champion who will stand up for her and who she knows loves her, is HUGE. I would suggest that you rehearse in your head what you are going to say. Your argument will be much more effective if you can stay in control of your emotions and not let them color your message.
And, just as important if not more, stand up for her in private. Bring the elephants out into the open, dissect them and let the poison out. Every time he dumps all over her, the fact that she has someone to express her hurt to will ease the pain.
My father sometimes did the same to me. In fact, I've been on both sides. When a parent criticizes one child and compares them unfavorably to another, they set up a resentment in one child and embarrassment in the other. Let her know that your father's favoritism embarrasses you and that it is hurtful to both of you and you will be able to keep the love and communication between the two of you strong, which is the best thing you can do for her.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reload page once after it's fully loaded with jquery
I would like that page is reloaded ONLY once, with jquery, but only if on page is specific form with unique ID, is that possible even?
Thanks!
A:
It can be done:
Add a script to the $(document).ready to check for your form / "magic" ID
If the condition is true check if document.referrer isn't yourself
If so, reload.
| {
"pile_set_name": "StackExchange"
} |
Q:
Save uploaded excel in database
I have a code where my client send an excel file to the server. The server (SpringBoot)
needs to 'translate' the MultiplartFile to an excel File.
From then, the data needs to be inserted into a database.
However, I never need to generate an excel but rather should insert the data from the spreadsheet into the database directly.
I first tried with :
@RequestMapping(value = "/insert", method = RequestMethod.POST, consumes = "multipart/form-data")
@ResponseBody
public MyMessage insertExcell(@RequestPart("typeFile") String typeFile,
@RequestPart("uploadFile") MultipartFile multipart, @RequestPart("dataUser") DataUser dataUser) {
BufferedReader br;
List<String> result2 = new ArrayList<String>();
try {
String line;
InputStream is = multipart.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
result2.add(line);
}
} catch (Exception e) {
}
for (int i = 0; i < result2.size(); i++) {
System.out.println("sentence" + result2.get(i));;
}
The output returns strange symbols.
Then again i tried with :
InputStream inputStream;
try {
inputStream = multipart.getInputStream ();
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (inputStream));
String line;
while ((line = bufferedReader.readLine()) != null)
{
System.out.println("linea era" + line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
The console output shows strange symbols.
How can i read the data from the excel file uploaded ?
A:
From what i understand, you need to read an Excel file, get your data then save it into a database.
Excel files are stored in various formats :
Excel 2003 Binary file format (BIFF8).
Xml Based format (for .xlsx)
If you simply try to read such a file, this would be quite a task...
Fortunately, Apache POI has a library that should help.
You can download it here.
Here is a simple example on how to read your excel file :
try (InputStream inputStream = multipartFile.getInputStream())
{
Workbook wb = WorkbookFactory.create(inputStream);
// opening the first sheet
Sheet sheet = wb.getSheetAt(0);
// read the third row
Row row = sheet.getRow(2);
// read 4th cell
Cell cell = row.getCell(3);
// get the string value
String myValue = cell.getStringCellValue();
// store in the database...
} catch (IOException e) {
//TODO
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Who introduced moments of a random variable first?
When, by whom and in which paper where moments of a random variable used first in probability theory?
A:
My answer taken from the closed version of this question here
From MathWords
Moment was taken into Statistics from Mechanics by Karl Pearson when he treated the frequency-curve (or observation curve) as the sheet enclosed by the curve and the horizontal axis. See his "Asymmetrical Frequency Curves," Nature October 26th 1893: "Now the centre of gravity of the observation curve is found at once, also its area and its first four moments by easy calculation." [OED].
The phrase method of moments was used in a statistics sense in the first of Karl Pearson’s "Contributions to the Mathematical Theory of Evolution," (Philosophical Transactions of the Royal Society A, 185, (1894), p. 75.). Pearson used the method to estimate the parameters of a mixture of normal distributions. For several years Pearson used the method on different problems but the name only gained general currency with the publication of his 1902 Biometrika paper "On the systematic fitting of curves to observations and measurements" (David 1995). In "On the Mathematical Foundations of Theoretical Statistics" (Phil. Trans. R. Soc. 1922), Fisher criticized the method for being inefficient compared to his own maximum likelihood method (Hald pp. 650 and 719).
Moment generating function. R. A. Fisher seems to have brought this term into English in his "Moments and Product Moments of Sampling Distributions.," Proceedings of the London Mathematical Society, Series 2, 30, (1929), p. 238. He probably took the term from V. Romanovsky "Sur Certaines Éspérances Mathématiques et sur l'Erreur Moyenenne du Coefficient de Corrélation, Comptes Rendus, 180, (1925), 1897-1899. Romanovsky refers to "la function génératrice des moments" (p. 1898).
A:
Long before Pearson, Chebyshev and his student A. A. Markov used moments to prove the Central Limit Theorem. The earliest paper of Chebyshev on this topic is dated 1887.
But I do not claim that Chebyshev "was the first". On my opinion, a question of the type "who was the first" is meaningless and usually impossible to answer.
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.530.4669&rep=rep1&type=pdf
Chebyshev's original paper is called "On two theorems in probability",
published in Russian In vol. 40 No 6 of the Imperial academy of sciences,
French translation in Acta Math 14, 305-315. It is freely available in French
in Chebyshev's Collected papers.
Remark. Chebyshev did not call them "moments" but used the name "integral residues".
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I return mocked item only on the x:th call?
I have run into a problem using PowerMock where I feel forced to create ugly code if I want to return a mocked item only once.
As an example I have the following code:
mockMap = spy(new HashMap());
HashMap<String, String> normalMap = new HashMap<>();
HashMap<String, String> normalMap2 = new HashMap<>();
HashMap<String, String> normalMap3 = new HashMap<>();
whenNew(HashMap.class).withNoArguments()
.thenReturn(normalMap)
.thenReturn(mockMap)
.thenReturn(normalMap2)
.thenReturn(normalMap3);
This of course works, but it feels very clunky, especially as I need to create a new hashmap for every new call.
So my question is: is there a way to tell PowerMock that it should stop interfering after a set amount of calls?
edit:
After reading the answers, I got the following:
final AtomicInteger count = new AtomicInteger(0);
whenNew(HashMap.class).withNoArguments().thenAnswer(invocation -> {
switch (count.incrementAndGet())
{
case 1:
return mockMap;
default:
return new HashMap<String, String>();
}
});
However it gives me a StackOverFlowError using the following code:
describe("test", () -> {
beforeEach(() -> {
mockStatic(HashMap.class);
final AtomicInteger count = new AtomicInteger(0);
whenNew(HashMap.class).withNoArguments().thenAnswer(invocation ->
{
switch (count.incrementAndGet())
{
case 5:
return mockMap;
default:
return new HashMap<String, String>();
}
});
});
it("Crashes on getting a new HashMap", () -> {
HashMap map = new HashMap<>();
map.put("test", "test");
HashMap normal = new HashMap<String, String>();
expect(normal.containsValue("test")).toBeTrue();
});
});
Worth noting is that I don't have a mockStatic(HashMap.class) in my larger tests that get the same errors(which I get rid of if I remove the mockStatic call)
A solution that works(but feels like a workaround) is building on that by editing the default statement into:
default:
normalMap.clear();
return normalMap;
A:
You can use Mockito's org.mockito.stubbing.Answer:
final AtomicInteger count = new AtomicInteger(0);
PowerMockito.whenNew(HashMap.class).withNoArguments()
.thenAnswer(new Answer<HashMap<String, String>>() {
@Override
public HashMap<String, String> answer(InvocationOnMock invocation) throws Throwable {
count.incrementAndGet();
switch (count.get()) {
case 1: // first call, return normalMap
return normalMap;
case 2: // second call, return mockMap
return mockMap;
case 3: // third call, return normalMap2
return normalMap2;
default: // forth call (and all calls after that), return normalMap3
return normalMap3;
}
}
});
Note that I had to use java.util.concurrent.atomic.AtomicInteger and declare it as a final variable for 2 reasons:
variables used inside the anonymous class must be final (because Java defined it that way)
if I create a final int, I can't do count++
Note: in this solution, you must also change all normalMap's to be final
Actually, if all your normalMap's are the same, you can just do:
PowerMockito.whenNew(HashMap.class).withNoArguments()
.thenAnswer(new Answer<HashMap<String, String>>() {
@Override
public HashMap<String, String> answer(InvocationOnMock invocation) throws Throwable {
count.incrementAndGet();
if (count.get() == 2) { // second call
return mockMap;
}
return normalMap; // don't forget to make normalMap "final"
// or if you prefer: return new HashMap<String, String>();
}
});
PS: as stated in this answer, instead of using AtomicInteger, you can also create an int counter inside the anonymous class (it's up to you to choose, as both work):
PowerMockito.whenNew(HashMap.class).withNoArguments()
.thenAnswer(new Answer<HashMap<String, String>>() {
private int count = 0;
@Override
public HashMap<String, String> answer(InvocationOnMock invocation) throws Throwable {
count++;
if (count == 2) { // second call
return mockMap;
}
return normalMap; // don't forget to make normalMap "final"
// or if you prefer: return new HashMap<String, String>();
}
});
And this also works with the switch solution as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamically changing data-text on twitter widget
I generate content for my tweet button as the page loads, but even when I have my script to run first widget.js still runs before, I tried using twttr.widget.load() to update the value but it didn't work.
Is it possible to update the value of the twitter button after it has already loaded initially? Or make it so it initializes after the content has loaded?
Below is the code I use.
I've tried placing widget.js before and after my script on the HTML too.
text = quote[0].content.substring(3, quote[0].content.length - 5);
document.querySelector("#quote").innerHTML = text;
document.querySelector(".twitter-share-button").setAttribute("data-text", text);
twttr.widgets.load(document.getElementById("tweet"));
HTML
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<script>window.twttr = (function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function(f) {
t._e.push(f);
};
return t;
}(document, "script", "twitter-wjs"));</script>
<script src="script.js"></script>
A:
I found a way to do it, here's what you need to know:
1) There's no need to have a twitter button in the initial HTML (this will only create a duplicate button that you'll need to delete later).
2) Simply create the button
var button = document.createElement('a');
button.classList += "twitter-share-button";
button.innerHTML = "Tweet";
button.setAttribute("data-text", text);
button.setAttribute("data-via", via);
button.setAttribute("href", "https://twitter.com/intent/tweet");
And append it wherever you want it to be
document.querySelector(".quote").appendChild(button);
After that all you need to do is reload the widget
twttr.widgets.load();
Since it loads asynchronously I don't know whether or not it's necessary to check before calling the load method, I've been reloading for a few minutes and haven't found any issues with it, keep this in mind if your button isn't loading properly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a definitive reference document for Ruby syntax?
I'm searching for a definitive document on Ruby syntax. I know about the definitive documents for the core API and standard library, but what about the syntax itself? For instance, such a document should cover: reserved words, string literals syntax, naming rules for variables/classes/modules, all the conditional statements and their permutations, and so forth.
I know there are many books and tutorials, yes, but every one of them is essentially a tutorial, each one having a range of different depth and focus. They will all, by necessity of brevity and narrative flow, omit certain details of the language that the author deems insignificant.
For instance, did you know that you can use a case statement without an initial case value, and it will then execute the first true when clause? Any given Ruby book or tutorial may or may not cover that particular lesser-known functionality of the case syntax. It's not discussed in the section in "Programming Ruby" about case statements. But that is just one small example.
So far the best documentation I've found is the rubyspec project, which appears to be an attempt to write a complete test suite for the language. That's not bad, but it's a bit hard to use from a practical standpoint as a developer working on my own projects.
Am I just missing something or is there really no definitive readable document defining the whole of Ruby syntax?
A:
The only document that can be reasonably described as "definitive" is the source code of parse.y in the YARV source tree.
The ISO Draft Specification contains a 39 page appendix with a summary of the grammar. Note, however, that ISO Ruby is a minimal subset of the intersection of Ruby 1.8 and 1.9. IOW: it doesn't describe anything that is only in 1.8 or only in 1.9 (so, the syntax additions in 1.9 like stabby proc and symbol hashes aren't described), nor does it describe everything in that intersection. ISO Ruby is a bit like ISO HTML in that regard.
The RubySpec project contains executable specifications for the Ruby language. It doesn't contain an explicit specification of the grammar, though. The only specification of the grammar is implicit in the examples themselves. Also, because RubySpec is an example-based spec, it can only show you specific examples of valid Ruby code, but it cannot tell you all possible valid Ruby programs like a grammar spec could. And, because RubySpec is itself executable Ruby code, it can only show you valid examples, not invalid ones.
The last thing that could be considered definitive is the book The Ruby Programming Language by David Flanagan and Yukihiro "matz" Matsumoto.
Note, however, that "the whole of Ruby syntax" is a rather daunting task, because Ruby's syntax is insanely complicated with a ginormous amount of weird corner cases.
A:
There is a draft of a Ruby standard in the works. You can get it here: http://ruby-std.netlab.jp/
Your example about case and Programming Ruby is poorly chosen. When Programming Ruby introduces case (on page 98 for the first edition; 141 for the second edition), Thomas says,
The Ruby case expression is a powerful beast: a multiway if on steroids. And just to make it even more powerful, it comes in two flavors.
He then briefly explains both ways to use case (with an explicit target after the initial case and without). He actually begins with the style you say he doesn't mention.
Your larger point is not unreasonable though. It will probably be helpful to have a standard.
| {
"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.