text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Are atoms unique?
Do atoms have any uniquely identifying characteristic besides their history?
For example, if we had detailed information about a specific carbon atom from one of Planck's fingerprints, and could time-travel to the cosmic event in which the atom formed, would it contain information with which we could positively identify that they two are the same?
A:
Fundamental particles are identical.
If you have two electrons, one from the big bang and the other freshly minted from the LHC, there is no experiment you can do to determine which one is which. And if there was an experiment (even in principle) that could distinguish the electrons then they would actually behave differently.
Electrons tend to the lowest energy state, which is the innermost shell of an atom. If I could get a pen and write names on all of my electrons then they would all fall down into this state. However since we can't tell one electron from another only a single (well actually two since there are two spins states of an electron) electron will fit in the lowest energy state, every other electron has to fit in a unique higher energy level.
Edit: people are making a lot of comments on the above paragraph and what I meant by making electrons distinguishable, so I will give a concrete example: If we have a neutral carbon atom it will have six electrons in orbitals 1s2 2s2 2p2. Muons and tauons are fundamental particles with very similar properties to the electron but different masses. Muons are ~200 times more massive than electrons and tauons are ~3477 times more massive than an electron.
If we replace two of the electrons with muons and two of the electrons with tauons all of the particles would fall into the lowest energy shell (which can fit two of each kind because of spin). If in theory these particles only differed in mass by 1% or even 0.0000001% they would still be distinguishable and so all fit on the lowest energy level.
Now atoms are not fundamental particles they are composite, I.E. composed of "smaller" particles, electrons, protons and neutrons.
Protons and neutrons are themselves composed of quarks. But because of the way that quarks combine, they tend to always be in the lowest energy level so all protons can be considered identical, and similarly with neutrons.
To take the example of carbon, there are several different isotopes, different number of neutrons, of carbon (mostly 12C but also ~1% 13C and ~0.0000000001% 14C {the latter which decays with a half life of ~5,730 years [carbon dating] but is replaced by reactions with the sun's rays in the upper atmosphere}).
If we take two 12C atoms, and force all of the spins to be the same. This is not too difficult for the electrons of the atom since the inner electrons do not have a choice of spin because every spin in every level is already full. So only outer electrons matter. The nucleons also have spin.
With our two 12C atoms with all of the same spins, we now have two indistinguishable particles which if you set up an appropriate experiment (similar in principle to the electrons not being able to occupy the same state) we will be able to experimentally prove that these two atoms is indistinguishable.
Answer time:
Are atoms unique?
No.
Do atoms have any uniquely identifying characteristic besides their history?
Their history of a particle does not affect it*. No particles are unique. Atoms may have isotopes or spin to identify one from another, but these are not unique from another particle with the same properties.
would it contain information with which we could positively identify that they two are the same?
Yes only because we could positively identify that this carbon atom is the same as almost every other carbon atom in existence.
*Unless it does, in which case it may be considered a different particle with different properties.
A:
Does position count as a characteristic? If so, then yes, atoms do have unique characteristics.
Edit: Perhaps I should rephrase this. If position counts as a characteristic, then yes, atoms do have unique characteristics.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to tell if a geo-point is on a road
I am looking for a robust way to determine if a geo point (long, lat) is located on a road
I am currently using openstreetmap overpass-api with the following query:
way[highway](around:3.0, {lat}, {lng});out;
And then I am looking for relevant values of "way" with "highway" from the following:
'motorway', 'trunk', 'primary', 'secondary', 'tertiary', 'unclassified', 'residential', 'service', 'tertiary_link', 'motorway_link', 'trunk_link', 'primary_link', 'secondary_link'
Yet I see that a 'road' is somehow not counted for its full width, but only its "middle spine", Here is an example of a grid with my classifier (Red means on a road, Green means not on a road):
I can estimate the road's width by its "lane" count, yet this is only an estimation, and not all roads has the "lane" tag.
What would be the best way to approach this problem?
My data is only relevant to the US
I can suffer some level of mistakes / errors
A batch / bulk solution is preferred
EDIT:
The picture demonstrates the problem, I can only be close to the road's spine, and I cannot tell if I am on a road if I am far from the spine,
It would be great if I could get the full-road-polygon and query over it
A:
I think this boils down to estimating the width of the streets:
https://stackoverflow.com/questions/25329738/how-to-get-the-osm-file-to-generate-width-of-the-streets#25330995
and then buffering the streets by their widths (actually half the street width either side of the centreline) and then doing a point-in-polygon operation or computing the point-line distance and thresholding by the half-width.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails accessing a shared custom validation in a module within a model
I'm trying to figure out how to create a shared custom validation that I can use across my models that I've placed within a lib/validations.rb folder.
module Validations
extend ActiveSupport::Concern
# included do
def email_format_validation
if self.email.present?
if !validates_format_of :email, with: email_regex
self.errors.add(:email, "doesn't exist")
end
end
end
def email_regex
/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
end
end
So in my model, this allows me to do:
validate :email_format_validation
In other models, I'm trying to just call email_regex:
validate :user_email, with: email_regex
which produces the following error:
undefined local variable or method `email_regex' for #<Class....>
I've tried using include Validations, extend Validations, require 'validations', etc. in my model with no luck. I've also tried placing the module methods within a class << self, using the included do block, setting the methods as self.email_regex and calling Validations.email_regex and yet nothing seems to work.
A:
I tried the following and it worked for me:
Created validations.rb in models/concerns
module Validations
extend ActiveSupport::Concern
def email_format_validation
if self.email.present?
if !validates_format_of :email, with: email_regex
self.errors.add(:email, "doesn't exist")
end
end
end
def email_regex
/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
end
end
In the model:
include Validations
class User < ApplicationRecord
validate :email_format_validation
validates :user_email, with: :email_regex
end
user_email is the field name
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add more than one Qmenu from other classes in MainWindow
I want a single menubar in my main window and be able to set the menus in the menubar from additional classes. Using the setMenuWidget command will overwrite the first menu option as shown in the code. In the classes where I set up the menu I think I may need to just set up a menu rather than a menubar, then set up the menubar in the main window.
This is what I would l like, which can be achieved by populating a single menubar in a class, though I am trying to avoid this method.
Instead only the second menu is show
import sys
from PyQt5.QtWidgets import QAction, QApplication, QMainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
class ToolBar0(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self)
bar = self.menuBar() # don't think I need a menubar here
file_menu = bar.addMenu('menu1')
one = QAction('one', self)
two = QAction('two', self)
file_menu.addAction(one)
file_menu.addAction(two)
class ToolBar1(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self)
bar = self.menuBar() # don't think I need a menubar here
file_menu = bar.addMenu('menu2')
one = QAction('one', self)
two = QAction('two', self)
file_menu.addAction(one)
file_menu.addAction(two)
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self, parent=None)
#should a menubar be set up here?
#For seting widgets in main window
self.Tool_Bar0 = ToolBar0(self)
self.setMenuWidget(self.Tool_Bar0)
###menu_bar0 is over written
self.Tool_Bar1 = ToolBar1(self)
#self.setMenuWidget(self.Tool_Bar1)
if __name__ == '__main__':
app = QApplication(sys.argv)
# creating main window
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
A:
You could use a base class with a method to return either a list of QMenu items containing QAction items or a list of QAction items and then render them in your QMainWindow toolbar in whichever way you want, here is an example:
import sys
from PyQt5.QtWidgets import QAction, QApplication, QMainWindow, QMenu
class WindowWithToolbar:
def __init__(self):
super().__init__()
def menu_items(self)->list:
pass
class Window1(WindowWithToolbar, QMainWindow):
def __init__(self):
WindowWithToolbar.__init__(self)
QMainWindow.__init__(self)
# New menu with actions
self.menu = QMenu('one')
self.menu.addActions([QAction('two', self), QAction('three', self)])
def menu_items(self):
return [self.menu]
class Window2(WindowWithToolbar, QMainWindow):
def __init__(self):
WindowWithToolbar.__init__(self)
QMainWindow.__init__(self)
def menu_items(self):
# Only actions
return [QAction('three', self), QAction('four', self)]
class MainWindow(WindowWithToolbar, QMainWindow):
def __init__(self):
QMainWindow.__init__(self, parent=None)
self.window1 = Window1()
self.window2 = Window2()
self.menu = QMenu('File')
self.helloAction = QAction('Hello')
self.menu.addAction(self.helloAction)
self._build_menu()
def menu_items(self)->list:
return [self.menu]
def _build_menu(self):
self._add_menu_items(self)
self._add_menu_items(self.window1)
self._add_menu_items(self.window2)
def _add_menu_items(self, windowWithToolbar: WindowWithToolbar):
for menu_item in windowWithToolbar.menu_items():
if isinstance(menu_item, QMenu):
self.menuBar().addMenu(menu_item)
elif isinstance(menu_item, QAction):
self.menuBar().addAction(menu_item)
if __name__ == '__main__':
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AppFabric Caching Serialization exception
I'm running with problems with AppFabric Caching 1.1. Try google it but nothing came up (or using the wrong keywords)
There is the follow scenario:
We have the cluster with 2 hosts up and running
We have our dev server using the appfabric cluster with no problem
We do night builds to a testing server (with no problems, all the configs are right) and here the appfabric have problems
We have one cache for dev and another to test
The object that we have problems is a list of classes A, and the class A have some properties and a list of class B. Both classes have serialize attribute and datacontract plus datamember.
In dev everything work as expected. We store/retrieve/delete from cache.
In test we store, but when try to retrieve have an exception.
The exception is:
Error Message: Object reference not set to an instance of an object.
Stack Trace: at
System.Runtime.Serialization.TypeName.LoadTypeWithPartialName(ITypeName
typeNameInfo, Assembly initialAssembly, String fullTypeName) at
System.Runtime.Serialization.TypeName.LoadTypeWithPartialName(ITypeName
typeNameInfo, Assembly initialAssembly, String fullTypeName) at
System.Runtime.Serialization.TypeName.GetType(Assembly
initialAssembly, String fullTypeName) at
System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.ResolveDataContractTypeInSharedTypeMode(String
assemblyName, String typeName, Assembly& assembly) at
System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.ResolveDataContractInSharedTypeMode(String
assemblyName, String typeName, Assembly& assembly, Type& type) at
System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode(XmlReaderDelegator
xmlReader, Int32 declaredTypeID, Type declaredType, String name,
String ns) at
System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator
xmlReader, Type declaredType, String name, String ns) at
System.Runtime.Serialization.NetDataContractSerializer.InternalReadObject(XmlReaderDelegator
xmlReader, Boolean verifyObjectName) at
System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator
reader, Boolean verifyObjectName) at
Microsoft.ApplicationServer.Caching.Utility.Deserialize(Byte[][]
buffers, Boolean checkTypeToLoad, Object context, IEnumerable1
knownTypes) at
Microsoft.ApplicationServer.Caching.Utility.Deserialize(Byte[][]
buffers, Boolean checkTypeToLoad) at
Microsoft.ApplicationServer.Caching.RoutingClient.SendMsgAndWait(RequestBody
reqMsg, IRequestTracker& tracker) at
Microsoft.ApplicationServer.Caching.DataCache.SendReceive(RequestBody
reqMsg, IMonitoringListener listener) at
Microsoft.ApplicationServer.Caching.DataCache.InternalGet(String key,
DataCacheItemVersion& version, String region, IMonitoringListener
listener) at
Microsoft.ApplicationServer.Caching.DataCache.<>c__DisplayClass49.b__48()
at
Microsoft.ApplicationServer.Caching.MonitoringListenerFactory.EmptyListener.Microsoft.ApplicationServer.Caching.IMonitoringListener.Listen[TResult](Func`1
innerDelegate) at
Microsoft.ApplicationServer.Caching.DataCache.Get(String key)
EDIT:
The classes are decorate with Serialize and DataContract attributes. The properties are decorated with DataMember attribute
A:
To sort it I use the Protocol Buffer and do the serialization myself.
When I open the dll's, I discover the AppFabric bypass if it is a byte array.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use a nib to configure DetailViewController?
I have multiple cells in a table referring to the same DetailViewController. How can I use nibs to be redirected to the same DetailViewControllers with different content?
A:
You can get the selected indexPath by this method.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
From this method you can load the DetailViewController by this,
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
UINavigationController *tableViewNavigationController = [[UINavigationController alloc] initWithRootViewController:detailViewController];
[self.navigationController presentViewController:tableViewNavigationController animated:YES completion:nil];
In the above method you can assign values what you want to change when you select different cells.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mobile data turns itself on again and again; could be caused by WhatsApp
My mobile data keeps turning on by itself and uses my data traffic. I think this is because of WhatsApp, but I'm not sure. Is there any other possible reason aside from WhatsApp? How should I stop it from happening?
Phone: Samsung GT9100i
Android Version: 4.2.1
A:
What other apps related to mobile data are you using? Is there any battery saver app that are using? they can turn your data on or off automatically.
Whatsapp doesn't have the permission to enable mobile data. So it must be some other app. still you can use 3G WatchDog to check if whatsapp is the culprit.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
R plotting frequency distribution
I know that we normally do in this way:
x=c(rep(0.3,100),rep(0.5,700))
plot(table(x))
However, we can only get a few dots or vertical lines in the graph.
What should I do if I want 100 dots above 0.3 and 700 dots above 0.5?
A:
Something like this?
x <- c(rep(.3,100), rep(.5, 700))
y <- c(seq(0,1, length.out=100), seq(0,1,length.out=700))
plot(x,y)
edit: (following OP's comment)
In that case, something like this should work.
x <- rep(seq(1, 10)/10, seq(100, 1000, by=100))
x.t <- as.matrix(table(x))
y <- unlist(apply(x.t, 1, function(x) seq(1,x)))
plot(x,y)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Symmetry Group Regular Tetrahedron
Looking for some help of how to do this, which could also be expanded to other shapes.
Thanks.
A:
Hint: Any symmetry of the tetrahedron must map vertices to vertices, and is completely determined by this mapping from vertices to the vertices. Label the vertices $A,B,C,D$ and consider the permutations of these vertices. Eliminate those that do not correspond to geometric symmetries of the tetrahedron. For example, if you rotate the tetrahedron so that $A$ and $B$ exchange places, then $C$ and $D$ also exchange places.
Since each symmetry is completely determined by its action on the four vertices, once you have identified the permutations of the vertices, you can forget about the rest of the tetrahedron and think only about the permutations.
Obtain an actual tetrahedron; tetrahedral dice are available online or in game stores. If you can't find an actual tetrahedron, make one. If you can't make one, find a cube (such as a die) and color four alternate corners with a red marker. These are the vertices of a regular tetrahedron, and any symmetry of the tetrahedron is therefore also a symmetry of the cube.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is the pressurization of propellant tanks necessary for structural integrity?
Propellant tank pressurization is a critical aspect of liquid propellant rocket design. Many designs use high pressure helium, heated and recirculated, however the propellant gases themselves can be used - at least in the case of LH2 as explained in this answer. In the case of Falcon 9 this is mentioned here and here as I've learned in the discussion and links associated with this question.
Another question Why do pressure-fed systems have to be pressurized with helium or nitrogen? addresses the question of why the choice of pressurization gas must be helium or nitrogen, and self-pressurized by their own boil-off gas. This is a different question. I am asking about the function or purpose of the pressurization, and the relative importance of two following possibilities.
I had thought the pressure was necessary only to feed the propellants into the pumps and other plumbing of the engine fast enough, but then I saw this line in the CSMonitor article: SpaceX launch explosion traced to helium system. Now what?:
Helium is injected into fuel tanks to keep them structurally sound as the launcher burns fuel during flight. This system apparently leaked during the static test.
Thinking about it, overpressure would certainly help maintain rigidity of the tank. Anyone who's seen the "crush the can" experiment can't forget it.
Question: Is the pressurization of propellant tanks actually necessary for structural integrity? And while maintaining pressure above ambient may be necessary to prevent buckling, is further positive pressure used in the mechanical design of a rocket to substantially stiffen the structure?
above: Image of the "Crush the Can" experiment, Ronald Lane Reese, Johns Hopkins University (1999).
A:
Pressure stabilization is used in some rockets, and to varying degrees.
the Atlas and Centaur use 'full-scale' pressure stabilization. The tank walls were so thin, an unpressurized stage would collapse under its own weight (huge PDF). The stage had to be pressurized (or kept in a support jig) at all times.
the Falcon 9 uses flight pressure stabilization. The tank walls are thick enough that a stage can bear its own weight, and does not need pressurization during manufacturing or transport. It does need pressurization in flight, to withstand the flight loads.
Saturn V used no pressure stabilization. The stage structure is strong enough to withstand flight loads on its own.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Css positioning, positioning issues
I am trying to positioning the name of the website to the top left of the page .I have the name of the page in foodies.com and in css i used the position:relative; top:10%; left :10%; but its displaying at near the middle of the page. Does anyone have any solutions. i am really struggling with positioning
html, body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
.intro {
height: 100%;
width: 100%;
margin: auto;
display: table;
top: 0;
background-size: cover;
background:url(https://picstatio.com/download/1600x900/864423/food-dishes-beer-bottle.jpg)no-repeat 50% 50%;
}
.intro .inner{
display: table-cell;
vertical-align: middle;
width: 100%;
max-width: none;
}
.name{
position: absolute;
top: 10%;
left: 0%;
}
.content {
max-width: 600px;
margin: 0 auto;
text-align: center;
}
.content h1 {
font-family: "Yantramana";
font-size: 600%;
font-weight: 100;
color: #E1EFE9;
line-height: 70%;
}
.btn{
font-family: "montserrat";
font-size: 135%;
font-weight: 400;
color: orange;
text-transform: uppercase;
text-decoration: none;
border: solid #ffffff;
padding: 10px 20px;
border-radius: 9px;
transition: all 0.7s;
}
.btn:hover {
color: #CBDFD6;
border: solid #CBDFD6;
}
.about-us{
height:100%;
width: 100%;
margin: auto;
display: table;
background-color: #ffffff;
background-size: cover;
position: relative;
}
.ab-content {
font-family: "Poiret One";
font-weight: lighter;
position: relative;
font-size: 150%;
left: 50%;
transform: translateX(-50%);
}
.ab-p{
text-align: center;
font-weight: lighter;
font-family: "montserrat";
}
h2{
text-align: center;
}
h3{
text-align: center;
font-family: "montserrat";
}
.ab-2p{
font-family:"montserrat";
font-size: 22px;
margin: 10px 10px;
}
ul {
display: flex;
position: absolute;
left: 50%;
transform: translate(-50%,-50%);
}
ul li {
list-style-type: none;
}
ul li a {
width: 80px;
height: 80px;
margin: 0 50px;
text-align: center;
font-size: 35px;
line-height: 80px;
display: block;
border: 3px solid orange;
border-radius: 50%;
color: orange;
position: relative;
overflow: hidden;
}
ul li a .fab{
position: relative;
color: orange;
transition: .5s;
}
ul li a:hover .fab {
transform: rotateY(360deg);
}
.color {
color:orange;
}
<!DOCTYPE html>
<head>
<title>Foodies</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="css/animate.css" rel="stylesheet"/>
<link href="css/waypoints.css" rel="stylesheet"/>
<script src="js/jquery.waypoints.min.js" type="text/javascript"></script>
<script src="js/waypoints.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
</head>
<body>
<section class="intro">
<div class="inner">
<h1 class="name">Foodies<span class="blue">.com</span></h1>
<div class="content">
<section class="os-animation" data-os-animation="bounceInUp" data-os-animation-delay=".3s">
<h1>Find <span class="color">Your</span> Taste!</h1>
</section>
<section class="os-animation" data-os-animation="slideInLeft" data-os-animation-delay="0s">
<a class="btn" href="#">Get Started</a>
</div>
</div>
</section>
<section class="about-us">
<div class="ab-inner">
<div class="ab-content">
<section class="os-animation" data-os-animation="slideInLeft" data-os-animation-delay="0s">
<h2 class="center"><span class="color">Our Mission</span></h2>
<section class="os-animation" data-os-animation="slideInUp" data-os-animation-delay=".5s">
<p class="ab-p">Our mission is to provide the best food ingedients.</p>
<section class="os-animation" data-os-animation="slideInUp" data-os-animation-delay=".5s">
<h3 class="ab-content"><span class="color">About</span></h3>
<section class="os-animation" data-os-animation="slideInUp" data-os-animation-delay=".6s">
<p class="ab-2p">Cooking is all about people. Food is maybe the only universal thing that really has the power to bring everyone together. No matter what culture, everywhere around the world, people get together to eat.Cooking is like snow skiing: If you don't fall at least 10 times, then you're not skiing hard enough.The fast-food industry is in very good company with the lead industry and the tobacco industry in how it tries to mislead the public, and how aggressively it goes after anybody who criticizes its business practices.The problem is when that fun stuff becomes the habit. And I think that's what's happened in our culture. Fast food has become the everyday meal.</p>
<h3 class="ab-content"><span class="color">Soical Media</span></h3>
<ul>
<li><a href="#"><i class="fab fa-facebook-f"></i></a></li>
<li><a href="#"><i class="fab fa-instagram"></i></a></li>
<li><a href="#"><i class="fab fa-twitter"></i></a></li>
<li><a href="#"><i class="fab fa-google-plus-g"></i></a></li>
</ul>
</div>
</div>
</section>
</body>
</html>
A:
I would revise the inner container that contains both the name and the content
Make the container not align things in the middle
.intro .inner {
vertical-align: initial;
}
Use margin to push the header and content into correct position
.name {
margin-bottom: 5em;
margin-left: 5%;
margin-top: 5%;
}
Hopefully that is closer to your desired layout.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
delete rows in csv based on specific column value python
I have a large csv with the following header columns id, type, state, location, number of students
and the following values:
124, preschool, Pennsylvania, Pittsburgh, 1242
421, secondary school, Ohio, Cleveland, 1244
213, primary school, California, Los Angeles, 3213
155, secondary school, Pennsylvania, Pittsburgh, 2141
etc...
The file is not ordered and I want a new csv file that contains all the schools with the number of students above 2000.
The answers that I found were regarding to ordered csv files, or splitting them after a specific number of rows.
A:
Here's a solution using csv module:
import csv
with open('fin.csv', 'r') as fin, open('fout.csv', 'w', newline='') as fout:
# define reader and writer objects
reader = csv.reader(fin, skipinitialspace=True)
writer = csv.writer(fout, delimiter=',')
# write headers
writer.writerow(next(reader))
# iterate and write rows based on condition
for i in reader:
if int(i[-1]) > 2000:
writer.writerow(i)
Result:
id,type,state,location,number of students
213,primary school,California,Los Angeles,3213
155,secondary school,Pennsylvania,Pittsburgh,2141
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Piranha CMS MVC tag problem with displaying blocks
So I have been learning Piranha CMS for .Net Core 3.1.
Having read the docs and studied the template I have hit a bit of wall in getting the information from within Blocks to display on the page correctly.
In the Razor Blog Template on the Page.cs the developer has used the below code to display the Blocks that the page has on screen
<h1>@Model.Data.Title</h1>
@Html.DisplayFor(m => m.Data.Blocks)
On the About Me page on the template website this displays as such:
Image of what should happen
On my own site, I have it written the same and have assigned some simple text blocks to the page to test it, however I get the following: My Site
Can anyone point me in the right direction as to what mistake I might be making?
Both the Startup.cs and other essential files are fine and don't have any major difference.
The only difference on the site I can see is mine having a lack of styling. But I don't see why that should affect it.
Cheers
A:
I've answered in the Gitter chat, but I'll answer here as well if someone else has the same question.
Display templates & Editor templates
The templating system is a built in feature of ASP.NET Core and assumes you have the following folders present in you project.
MVC
Views
Views/DisplayTemplates
Views/EditorTemplates
Razor Pages
Pages
Pages/DisplayTemplates
Pages/EditorTemplates
Calling templates
When you call DisplayFor() on a collection of objects, like the code you referenced from the Razor Blog template ASP.NET automatically selects the template with the name corresponding to type name. So in this case, if your block is of the type Piranha.Extend.Blocks.TextBlock it will try to locate the view file:
Pages/DisplayTemplates/TextBlock.cshtml
Now if you have your own loop in the view, say if you'd like to add a containing div around every block and give a single object into EditorFor() the standard rendering of ASP.NET will be executed which just prints out the Properties of the given object.
Won't work the way your want
@foreach (var block in Model.Data.Blocks)
{
<div class="myclass">
@Html.DisplayFor(m => block)
</div>
}
Workaround
The simple workaround is to just give in the name of the DisplayTemplate that you want to render the block. This can be easily achieved by writing:
@foreach (var block in Model.Data.Blocks)
{
<div class="myclass">
@Html.DisplayFor(m => block, block.GetType().Name)
</div>
}
Best regards
Håkan
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JQUERY, div with a fixed height (with a scrollbar) how to animate until it grows to no longer need a scroll bar?
JQUERY, div with a fixed height (with a scrollbar) how to animate until it grows to no longer need a scroll bar?
I have a div on a page with a CSS height:200px setting, which makes the DIV have a vertical scroll bar, which allows the user to scroll through a bunch of text.
I would like to animate the DIV to expand in height until all content in the div is shown, meaning no more scroll bar
I tried the following:
$("#view-container").animate({"height": "auto"}, "slow");
but that didn't work while this does:
$("#view-container").animate({"height": "1000px"}, "slow");
problem with that is the text size in the DIV is variable. Ideas?
Thanks
A:
What you can do:
Set the height to auto, then record the offsetHeight. Change the height back to what it was immediately - the users won't see the change at all as browsers are single threaded.
Then use jQuery (or not) to animate to that recorded height.
Example:
var vc = document.getElementById('view-container');
var vcold = vc.style.height;
vc.style.height = 'auto';
var vcheight = vc.offsetHeight;
vc.style.height = vcold;
$("#view-container").animate({"height": vcheight + "px"}, "slow");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Blender texturebaking not working (combing all textures into one)
I created a 3d model with a 3d scanning software called meshroom
. When I import the model into blender, the material of the object is divided into many textures (Pic.2). Now I try to combine them all into one. I have to say I never did this before, and so I watched two videos on YouTube.
(https://www.youtube.com/watch?v=9airvjDaVh4)
(https://www.youtube.com/watch?v=MH7Xdol5erw)
I created a second UV map called UV2 and created a node group in all textures with the image texture (called horse_color_bake) I want to bake it on (just a black 1024x1024
image). Then I just clicked on bake after changing the values on diffuse and Color (Pic.3). After I waited for some time, blender just crashes. Before that I get a note which says: "
Circular dependency for Image "
texture_1017.png"
from object "
horse 1"
. In another file I added the same textures on two cubes and tried it as well. It worked there perfectly fine. I hope you can help me. Thank you very much in advance.
Pic.1:
Pic.2:
Pic.3:
A:
This may help to solve your problem (Without having the scene here):
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Name for the 1-2-4 chord
Is there a name for the chord 1-2-4?
For instance, it's appearing in Schubert's Sonata D959 in the second bar: A-B-D.
A:
The measure in question:
B minor 7th. It's lacking the 5th (F♯), but that's okay, the 5th doesn't add much color. If you add it in to the right hand, you'll notice that it doesn't change the sound much.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add Wishlist button field in views in drupal 7?
I am working on commerce site. In my site I have 3 views & each view have display 3 products. If user can first visit the product then user get the wishlist button but I want to show "add to cart" or "wishlist" or "buy" button with all the products so user can directly purchase, no need to visit.
I already created Relation : "Content: Referenced products" & add Field : "Commerce Product: Add to Cart form". But no button show below product. Please help to solve. Thanks
A:
Most straightforward way is to use views to render your product display nodes. Instead of "fields" choose "node" and then choose your display mode. Perhaps use display_suite or panels to get more advanced control over what your products look like when rendered.
Sidenote, there's a great video I created that shows you how to use hook_form_alter to move the wishlist button around.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does this preg_replace not work? Removing HTML entities
Why does this preg_replace to remove HTML entities not work?
// Remove all HTML entities
$text = preg_replace('/&[A-Za-z0-9]+?;/',' ', $text);
I'm simply trying to replace all HTML entities like ( &###; , < , and etc. ) with spaces, but I seem to be missing something because it is not replacing them and I'm utterly confused now.
Test case
Code:
// Remove all HTML entities
$title="♥♥♥ I like cats ♥♥♥";
echo "BEFORE : ".$title."\n";
$title2 = preg_replace('/&[A-Za-z0-9]+?;/e',' ', $title);
echo "AFTER : ".$title2."\n";
Output:
BEFORE : ♥♥♥ I like cats ♥♥♥
AFTER : ♥♥♥ I like cats ♥♥♥
PHP Info:
PHP Version: 5.3.6-13 ubuntu 3.5
Regex Library: Bundled library enabled
A:
You're missing #
It should be this RegEx instead in your preg_replace call:
/&#[a-z\d]+;/i
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Salesforce Certified Platform Developer 1 : Lightning Component Framework
For the Salesforce Certified Platform Developer 1 exam, these two points are mentioned as part of the study guide but I am not sure at what level of technical understanding you need on these two topics specifically for the intent of passing this exam.
Describe the benefits of the Lightning Component framework
Describe the resources that can be contained in a Lightning
Component
Do you need to be very thorough with aura framework like how one should be with VF framework or the questions test only your basic understanding of this lightning comp framework ?
Has anyone who has completed/attended this exam in the recent times, throw some light on this ?
A:
I followed the transition track from advanced developer to the platform developer II exam. So I did not take the platform developer 1 exam, but got the certification all the same.
Take into consideration that these exams are reviewed and extended every release and it is thus likely that the questions on developing lightning will increase and so will their detail or complexity from what it may be now.
Having done nearly all other certifications I would interpret it like this:
Know how to compare Lightning to Visualforce
Know where you can use Lightning components and applications
Read the high level help/documentation introduction to see what benefits are mentioned to both end users and developers.
Understand how you develop (and deploy?) a lightning component
Developer a hello-world component and try to get some data from a controller
Do any trailhead modules on lightning components (may include the point above)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why are stars still distant from one another?
Why are stars so far from each other? Shouldn't gravity pull them closer over time? And if the effects of gravity are negligible is there an explanation why stars have to be so distant from one another?
The closest star is Alpha Centauri (I think) and it is 4.4 light years away.
A:
The initial star formation regions were regions that have a high enough mass density to form a star. The density of the early universe was not constant at different locations. Some regions had high enough density to form a star, and some didn't.
When a star forms it draws in matter from a large distance away. This forms an accretion disk and leaves a temporary relatively empty space around the star at a large distance away. There is no way a star can form in this low mass region. Once you get further away from this region the matter density may return to a level where a star can form. But this region is far from a star.
Yes, gravity from a particular star is pulling at other stars but there are many stars pulling on the particular star of interest. So the net force on the star may be very small.
A:
As jmh has answered, stars naturally form at large distances from each other. To add to the answer, what is the reason for this particular distance scale?
If we imagine a very large, homogeneous cloud of gas it will be unstable to gravitational collapse over the Jeans length scale $\lambda_J=c_s/\sqrt{G\rho}$ where $c_s$ is the speed of sound in the gas, $G$ the gravitational constant, and $\rho$ the density. For typical values this about a light-year, giving a sense of the distance scale.
But why are those values what they are? $G$ is a fundamental constant and since it is small we get long distances. The speed of sound depends on temperature and molecular mass; since molecules are very light it is high. Why are molecules light? This is because another fundamental constant, the ratio between proton and electron mass, is large. The density of gas in the universe is low, since the universe has a density close to the critical density (had it not been that, it would either have recollapsed or expanded so fast there would not have been many stars).
A universe where stars form much closer to each other than in ours needs to have strong gravity (making stars burn much hotter and be short lived, beside lots of gravitational interactions disrupting planetary orbits), have heavy molecules (making chemistry weird), or have a high density (likely collapsing rapidly). So it is likely that there would not be any life and observers there.
The question also asks why gravity does not pull them closer to each other. Note that if the cloud turns into stars with typical mass $M\approx \rho \lambda_J^3$ separated by distance $r\approx \lambda_J$ then the acceleration between them will be $a=GM/r^2=G\rho \lambda_J^3/\lambda_J^2=G\rho \lambda_J =\sqrt{G\rho}c_s$. So the accelerations will be very small, again for the same reasons as discussed above.
(Further, due to the ratio between the electromagnetic force strength and the gravitational force strength, objects like stars have equilibrium sizes that are small compared to $\lambda_J$, so they rarely collide with each other on this timescale. They just miss, and fly past. )
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does Java hang on my Mac when I try to use ImageIO?
Abruptly last afternoon, my Java (Groovy, actually) started hanging in ClassLoader.load(String, boolean) while trying to call ImageIO.read(file). The stack trace indicated it was trying to load AWT related code.
In case it was an IntelliJ or Gradle issue I tried the command-line, where it still hung, but successfully ran past that point if I specified -Djava.awt.headless=true, apparently related to the -XstartOnFirstThread SWT 2013 bug, but of course that meant I was unable to display windows from the program.
This obtained even with a trivial 'only load an image' program.
Contrarily, an existing Java-based application ran happily, and a brand new user on the same machine had no problems.
Moving all my account's . files and logging out/in, and checking my environment variables for suspicious things compared with the brand new user had no effect.
A:
I don't know precisely WHY this was happening, but it relates directly to having previously suffered a native crash:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x0000000131099b1b, pid=11165, tid=4867
#
# JRE version: Java(TM) SE Runtime Environment (8.0_31-b13) (build 1.8.0_31-b13)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.31-b07 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# C [libtesseract.dylib+0x156b1b] ELIST::length() const+0x5
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /Users/tim/git/t4jhack/hs_err_pid11165.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
because I just triggered it again, and the issue resurrected immediately.
The app crash says
AppMain quit unexpectedly.
Click reopen to open the application again.
This report will be sent to Apple automatically
[show details] [OK] [Reopen]
I clicked 'OK' and 'Reopen' variously - both cause the problem.
The 'fix' I stumbled across:
In System Preferences, open the Java Control Panel, where it will say:
The last time you opened Java, it unexpectedly quit while reopening windows.
Do you want to try to reopen its windows again?
If you choose not to reopen windows, you may have to open and
position the windows yourself.
[don't reopen] [reopen]
You want 'Reopen', then just OK the resulting window.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does stress for magical effects work outside of a conflict in the Dresden Files?
In The Dresden Files RPG, mental stress is accrued for casting spells. As you cast spells, you become more mentally fatigued. The mental stress track is cleared at the end of the conflict- so if you cast spells to defeat the big baddie, after he's defeated, and you take a second to catch your breath and clear your mind, your mental stress track is zeroed.
So my question- if you're not in a conflict, and no conflict is imminent, and you cast a spell for an effect, how and when is stress cleared? I'd think in most cases it wouldn't matter as if there's no conflict in the making, the effects of casting the spell beyond the moment wouldn't affect the story, but I was just wondering.
An example: The group is investigating a murder, and creeps into the office of one of the suspects. The office is locked, so the wizard p.i. casts a 1-stress rote in order to open the door. Then once inside, they find a scrap of fabric that the wizard p.i. realizes is the same as the fabric of the coat of one of the victims, so casts a psychometry spell with 4 shifts (equal to his conviction) to verify this, for another point of stress. After verifying, and seeing that there is a clock with a reflective surface facing the door, the Wizard P.I. picks that up and casts a 5 shift spirit spell to see everything that the surface reflected in the last day, for 2 more stress. He sees that in contrast to the suspect's tale, the victim was in his office just yesterday. So they leave to go question the suspect again. Scene over. Does the mental stress clear at this point?
My read of the rules says yes, but I wanted to verify that mental stress in non-conflict situations is just for record keeping and such (and as a herring perhaps to disguise conflict vs. non-conflict, i.e. if the suspect was going to return, they wouldn't know it).
A:
I would say that the stress continues either until the end of he scene or until such a time as the character can rest for a little time.
So, in your example, if after casting the last spell, a monkey demon were to burst in and combat start then the stress would remain. If on the other hand, the character made a cup of coffee and relaxed for a little while before the monkey demon attached, then they would regain the stress.
Since they are leaving the office to go and see the suspect, I would rule that yes, the stress is gone. However, if they knew that the suspect was on his way to the airport or the characters had to solve the mystery before midnight or the Queen of Winter will wear their skin for a hat, or they are under duress of any kind, then I would say that the stress does not clear. I am mean like that.
A:
The rules clearly state that stress clears at the end of a scene, as Sardathrion pointed out, and not at the end of a conflict as in the question. The trick here is in figuring out when scenes end, then.
My rule of thumb is to ask myself, "Has the emotional event of this scene ended yet?" It's better than a change of scenery, because these events, for instance, could all be in one scene:
The wizard and his friends are trying to rescue a little girl kidnapped by a Faerie prince who wants her for his cupbearer. They start at the girl's room.
The K9 cop's dog tracks her scent to an abandoned movie theater.
The wizard detects a recently closed Way, and he re-opens it.
The half-fae in the group takes them through the Nevernever to the prince's demnese.
Even though they've changed physical locations a lot, this is all one continuous emotional event - they're following the girl's trail, hoping they find her, wary for dangers on the way.
The Stress accrued along the way would clear at the end of this scene in my games, unless conflict broke out before they could get a breather. For instance, if they had a scene in which they planned their assault on the prince's stronghold, that would be a new scene with a Stress reset. But if they were discovered by the prince's guards and set upon before they could have another scene, I wouldn't clear the Stress.
You might refer to this answer for more on this general topic.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the original variant of the "Charles V Dominating Fury" statue?
The statue "Charles V Dominating Fury" by Leone Leoni is known in two variants, in one the emperor is naked, in the other he is armoured. I wonder which variant is the original?
A:
It's the same statue, the armour is removable.
The statue is today kept at the Museo Nacional Del Prado:
The Emperor stands over a nude figure representing Fury, which takes the form of a mature man in chains with an angry and hateful expression. Fury holds a lit torch in his right hand. The group rests on a base covered with arms and military trophies, crafted with a goldsmith’s attention to detail: a trident, a trompet, a mace, a quiver and even a lictor’s fasces with its hatchet, emphasize this group’s similarity to a work from Antiquity.
This idea is related to the Renassance mentality, which associated imperial power with the Roman past in both a political and an esthetic sense. In keeping with this tendency, the artists represent the emperor nude here, as in an ancient sculpture. To this, they added the armor, which can still be removed today.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Angular / Cordova / IOS : How to persist PHPSESSID cookie at app relaunch (using withCredentials)
I'm building an app using Angular 6 and Cordova 8.
I need to authenticate my users with the server so I made an interceptor to add on every requests I send the parameter withCredential set to true.
@Injectable()
export class AddCredentialsInterceptor implements HttpInterceptor {
constructor() {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
return next.handle(request);
}
}
It's working fine on web browsers and Android.
However, on IOS, every time I relaunch the application, the PHPSESSID is reset and my user is logged out.
Is there a way to persist it after app relaunch ? Maybe setting an expiry date ?
Thanks !
A:
The solution was indeed to set an expiry date to the cookie on the server side.
Then, the PHPSESSID is not reset at every app relaunch and can be persisted for a certain time.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Angular javascript array is empty?
Angular javascript array is empty?
I have an array of checkboxes databound to an angular scoped list
I need to check a few checkboxes and send bind them to a second angular scoped array:
My HTML:
<tr ng-repeat="item in pagedItems[currentPage]"
ng-controller="DealerComMaintainCtrl">
<td align="center">
<input type="checkbox" id="{{item.IdArticle}}"
ng-value="item.IdArticle"
ng-checked="selected.indexOf(item.IdArticle) > -1"
ng-click="toggleSelect(item.IdArticle)" />
</td>
<td>
<a href="/Dealercoms/ArticleDownload?FileName={{item.FileName}}&IdArticle={{item.IdArticle}}"
class="btn btn-xs btn-total-red btn-label"><i class="ti ti-download"></i></a>
</td>
<td>{{item.DateArticle | date:'dd/MM/yyyy'}}</td>
<td>{{item.Title}}</td>
<td>{{item.Archive}}</td>
</tr>
And JS in the controller:
$scope.selected = [];
$scope.toggleSelect = function toggleSelect(code) {
var index = $scope.selected.indexOf(code)
if (index == -1) {
$scope.selected.push(code)
} else {
$scope.selected.splice(index, 1)
}
}
$scope.ArchiveDocs = function() {
var selectedoptionz = $scope.selection;
console.log(selectedoptionz);
};
A:
I tried your code and i fixed the problem, by adding the controller on an element above the ng-repeat. The alert is only to check, what is in the selected-array. This is the code, which works fine on my system:
<html>
<head>
</head>
<body ng-app="app">
<table ng-controller="DealerComMaintainCtrl">
<tbody>
<tr ng-repeat="item in pagedItems" >
<td align="center">
<input type="checkbox" id="{{item.IdArticle}}" ng-value="item.IdArticle" ng-checked="selected.indexOf(item.IdArticle) > -1" ng-click="toggleSelect(item.IdArticle)" />
</td>
<td><a href="/Dealercoms/ArticleDownload?FileName={{item.FileName}}&IdArticle={{item.IdArticle}}" class="btn btn-xs btn-total-red btn-label"><i class="ti ti-download"></i></a></td>
<td>{{item.DateArticle | date:'dd/MM/yyyy'}}</td>
<td>{{item.Title}}</td>
<td>{{item.Archive}}</td>
</tr>
</tbody>
</table>
<!-- jQuery -->
<script src="./jquery-2.1.4/jquery.min.js"></script>
<!-- AngularJS -->
<script src="./angular-1.4.5/angular.min.js"></script>
<script>
var app = angular.module("app", []);
app.controller("DealerComMaintainCtrl", function($scope){
$scope.pagedItems = [
{IdArticle: 1, Title: "test1", Archive: "archiv1"},
{IdArticle: 2, Title: "test2", Archive: "archiv1"},
{IdArticle: 3, Title: "test3", Archive: "archiv1"},
{IdArticle: 4, Title: "test4", Archive: "archiv1"}
];
$scope.selected = [];
$scope.toggleSelect = function toggleSelect(code) {
var index = $scope.selected.indexOf(code)
if (index == -1) {
$scope.selected.push(code)
}
else {
$scope.selected.splice(index, 1)
}
alert(JSON.stringify($scope.selected));
}
});
</script>
</body>
</html>
Just try it, i hope it solve your problem...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
will x86 cpu perform an early end of multiplication when detects a zero-operand?
================Update=======================
Seems duplicate of Do modern cpus skip multiplications by zero?
But please allow me to reserve this post, because I didn't search out that post before my publish. And allow me to post my test result in the answer area.
==================Original Post=================
Take this function as example:
int mul(int a, int b, int c, int d){
return a*b*c*d;
}
When cpu enters this function call:
int result = mul(0, 1, 2, 3);
(assume we don't allow the compiler do any optimization and the machine code appears exactly as the program order.)
I know nowadays x86 CPU has out-of-order execution, will it perform an early end of multiplication when he found he got a zero-operand?
Thanks!
A:
No, a modern x86-64 CPU will not stop multiplying numbers just because one of them is zero. Out of order execution isn't going to prevent any of the instructions from running, it just might allow some to be executed well, out of order.
This is easy to verify using the code you wrote. Let's call it multiply.c:
int mul(int a, int b, int c, int d){
return a * b * c * d;
}
int main() {
for (int i = 0; i < 1e8; i++) {
int result = mul(0, 1, 2, 3);
}
}
Firstly verify that the code doesn't run any slower when the '0' is replaced with a '1':
gcc multiply.c -O0
time ./a.out
real 0m0.387s
user 0m0.378s
sys 0m0.002s
Re-running after changing the 0 to a 1 resulting in a real time of 0.384s, no statistical difference.
Next take a look at what assembly is being generated by gcc:
gcc -g -c -O0 multiply.c
otool -tvVX multiply.o
...
_mul:
pushq %rbp
movq %rsp, %rbp
movl %edi, -0x4(%rbp)
movl %esi, -0x8(%rbp)
movl %edx, -0xc(%rbp)
movl %ecx, -0x10(%rbp)
movl -0x4(%rbp), %ecx
imull -0x8(%rbp), %ecx
imull -0xc(%rbp), %ecx
imull -0x10(%rbp), %ecx
movl %ecx, %eax
popq %rbp
retq
nopw %cs:_mul(%rax,%rax)
You can see the three separate multiplies, so they aren't being compiled away or anything of that nature.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mysql create trigger syntax error used DELIMITER $$
i tried to prevent duplicated value on a column by this code but got syntax error:
if exists ( select * from tbl_baivietsp t ' at line 1
DELIMITER $$
CREATE TRIGGER key_as_linksp ON tbl_baivietsp
AFTER INSERT
AS
if exists ( select * from tbl_baivietsp t inner join INSERTED i on i.LINK_SP
LIKE CONCAT('%', t.LINK_SP ,'%'))
begin
rollback TRANSACTION
RAISERROR ('Duplicate Data', 16, 1);
end
go
$$
DELIMITER ;
Can't really know what the problem is after hours, thanks for your time helping me!
A:
You have written a Trigger code in TSQL (Microsoft SQL Server); however you are using MySQL. It is recommended to check the Trigger documentation at: https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html
DELIMITER $$
/* AFTER INSERT comes before the table name on which Trigger is being created */
CREATE TRIGGER key_as_linksp AFTER INSERT ON tbl_baivietsp
FOR EACH ROW BEGIN /* Instead of AS, Trigger block starts with FOR EACH ROW BEGIN */
IF EXISTS ( select 1 from tbl_baivietsp t
inner join INSERTED i
on i.LINK_SP LIKE CONCAT('%', t.LINK_SP ,'%')) THEN /* THEN is missing */
/* Throw Exception */
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Duplicate Data';
END IF; /* we use END IF instead of END to end an IF block */
END $$ /* Trigger block ends with END clause */
DELIMITER ;
In the case of MySQL, we use SIGNAL .. SET MESSAGE_TEXT .. to throw an exception inside the Trigger.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Launching urxvt with calendar (cal) using sxhkd
Hi I'm trying to launch cal with sxhkd. And it doesn't work, the terminal window is closed right after the command is executed.
I tried to do it using the following:
# launch urxvt 20x8 with cal
super + c
urxvt -geometry 20x8 -e cal -m
I also tried to set bspwm to open the window as floating with this: bspc rule -a urxvt:cal state:floating but it doesn't have any efect
A:
You need to add -hold on urxvt, in order to not destroy its window when the program executed within it exits.
urxvt -hold -geometry 20x8 -e cal -m
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the most effective algorithm to compare a large number of strings?
Let's take 2 string arraylists
List<String> namesListA = new ArrayList<>(/*50 000 strings*/);
List<String> namesListB = new ArrayList<>(/*400 000 strings*/);
removeAll method seems not working. After:
namesListA.removeAll(namesListB);
namesListA.size() is still 50000. Edit: Input data was incorrect, it actually works but takes a long lime.
I wrote the following brute-force code:
boolean match;
for (String stringA: namesListA)
{
match = false;
for (String stringB: namesListB)
{
if (stringA.equals(stringB))
{
match = true;
break;
}
}
if (!match)
{
finallist.add(stringA);
}
}
But it takes 8 hours to perform. it there any known effective algorithm for searching strings? Like to sort strings in alphabetical order and then search letter by letter or something like this.
A:
You could put elements of list namesListB into a new Set (preferably HashSet). Then it is much more effective to call namesListA.removeAll(setFromListB);, since the implementation of ArrayList.removeAll calls Collection.contains() which is much more effective in a Set (HashSet) than in an ArrayList (HashSet.contains() has constant time performance, while ArrayList.contains() has linear performance).
Anyway, namesListA.removeAll(namesListB); should work, if namesListA doesn't change, then the 2 lists have no elements in common.
Estimation of time complexity (N = namesListA.length, M = namesListB.length):
Creating the HashSet from namesListB: O(M)
Calling namesListA.removeAll(setListB): O(N * 1) = O(N)
In total: O(M + N) (which could be written as O(M) since M>N, but I'm not sure)
A:
Here's a solution in O(n*logn). Should be faster than the approaches posted yet.
Edit: If you don't need the exact element, my other approach is faster.
1.) Sort both lists
Use Collections.sort(...) for efficient sorting in O(n*logn).
2.) Compare with two iterators
Fetch two iterators over the two lists. Then:
while(leftIterator.hasNext() && rightIterator.hasNext(){
int comparisonResult = leftElement.compare(rightElement);
if (comparisonResult == -1){
leftElement = leftIterator.next();
}
else if (comparisonResult == 1){
rightElement = rightIterator.next();
}
else{
// found it!
return true;
}
}
(Sorry if I mistyped, don't have an IDE at my hand)
=> Sorting is in O(ilogi + jlogj))
=> Comparison is in O(i+j)
Result performance is efficiently in class O(n*logn). This should work nicely.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to evaluate $\iint_R \sin(\frac{y-x}{y+x})dydx$ with Jacobian substitution?
I want to calculate this integral with substitution $x=u+v , \ y=u-v$:
$$\iint_R \sin\left(\frac{y-x}{y+x}\right)dydx$$
$$R:= \{(x,y):x+y≤\pi, y≥0,x≥0\}$$
but I don't know how to set new bounds for $u$ and $v$.
A:
We have a transformation $T:\mathbb{R}^2\to \mathbb{R}^2$ where the coordinates of the first $\mathbb{R}^2$ are $(u,v)$ and those of the second $\mathbb{R}^2$ are $(x,y)$. We know the transformation is given by $T(u,v)=(u+v,u-v)$. This is a linear transformation with matrix given by
$$
M=
\begin{bmatrix}
1&1\\
1&-1
\end{bmatrix}.
$$
It has inverse matrix given by
$$ M^{-1}=\frac{-1}{2}
\begin{bmatrix}
-1&-1\\
-1&1
\end{bmatrix}.$$
You want to integrate over the convex triangular region $R$ with vertices $(0,0), (\pi,0),(0,\pi)$. We know that $(0,0)$ has unique preimage $(0,0)$, and we can compute the preimages of $(\pi,0)$ and $(0,\pi)$ using $M^{-1}$. $M^{-1}(\pi,0)=(\pi/2,\pi/2)$, and $M^{-1}(0,\pi)=(\pi/2,-\pi/2).$ So, $T^{-1}(R)$ is the convex region spanned by $(0,0), (\pi/2,\pi/2),(\pi/2,-\pi/2)$. Put another way, this is is the region
$$ T^{-1}(R)=\{(u,v):u\le \lvert v\rvert, v\le \pi/2\}.$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to do POST using requests module with Flask server?
I am having trouble uploading a file to my Flask server using the Requests module for Python.
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
UPLOAD_FOLDER = '/Upload/'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
file = request.files['file']
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('index'))
return """
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
<p>%s</p>
""" % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
I am able to upload a file via web page, but I wanted to upload file with the requests module like this:
import requests
r = requests.post('http://127.0.0.1:5000', files={'random.txt': open('random.txt', 'rb')})
It keeps returning 400 and saying that "The browser (or proxy) sent a request that this server could not understand"
I feel like I am missing something simple, but I cannot figure it out.
A:
Because you have <input> with name=file so you need
files={'file': ('random.txt', open('random.txt', 'rb'))}
Examples in requests doc: POST a Multipart-Encoded File
A:
You upload the file as the random.txt field:
files={'random.txt': open('random.txt', 'rb')}
# ^^^^^^^^^^^^ this is the field name
but look for a field named file instead:
file = request.files['file']
# ^^^^^^ the field name
Make those two match; using file for the files dictionary, for example:
files={'file': open('random.txt', 'rb')}
Note that requests will automatically detect the filename for that open fileobject and include it in the part headers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linked In retrieveTokenRequest returns "signature_invalid" problem
I am writing a web application with Linked In OAuth authentication. I use simple-linkedinphp library. It has worked good. But one day (not far ago) it became broken. I can't get token with use of retrieveTokenRequest() method. Even demo.php (from simple-linkedinphp library) doesn't work with my api and secret key.
Does anybody experienced such issue? I have got following response for retrieveTokenRequest() method:
array
'linkedin' =>
array
'oauth_problem' => string 'signature_invalid' (length=17)
'oauth_problem_advice' => string 'com.linkedin.security.auth.pub.LoginDeniedInvalidAuthTokenException while obtaining request token for :POST&https%3A%2F%2Fapi.linkedin.com%2Fuas%2Foauth%2FrequestToken&oauth_callback%3Dhttp%253A%252F%252Fapi.propertag.proj%252Fauthenticate%252Foauth%253Fprovider%253Dlinkedin%2526callback-url%253Dhttp%25253A%25252F%25252Fin.propertag.proj%25252Fopenid%25252Boauth.html%2526lType%253Dinitiate%2526lResponse%253D1%26oauth_consumer_key%3Dler1lhjlr04q%26oauth_nonce%3D37642191fbd5d7c3b69ab42cced8b9cc%26oauth_signat'... (length=656)
'info' =>
array
'url' => string 'https://api.linkedin.com/uas/oauth/requestToken' (length=47)
'content_type' => string 'application/x-www-form-urlencoded;charset=UTF-8' (length=47)
'http_code' => int 401
'header_size' => int 1090
'request_size' => int 602
'filetime' => int -1
'ssl_verify_result' => int 0
'redirect_count' => int 0
'total_time' => float 0.844714
'namelookup_time' => float 0.046769
'connect_time' => float 0.23863
'pretransfer_time' => float 0.630895
'size_upload' => float 0
'size_download' => float 819
'speed_download' => float 969
'speed_upload' => float 0
'download_content_length' => float 819
'upload_content_length' => float 0
'starttransfer_time' => float 0.844679
'redirect_time' => float 0
'certinfo' =>
array
empty
'oauth' =>
array
'header' => string 'Authorization: OAuth realm="http%3A%2F%2Fapi.linkedin.com",oauth_version="1.0",oauth_nonce="37642191fbd5d7c3b69ab42cced8b9cc",oauth_timestamp="1312808590",oauth_consumer_key="ler1lhjlr04q",oauth_callback="http%3A%2F%2Fapi.propertag.proj%2Fauthenticate%2Foauth%3Fprovider%3Dlinkedin%26callback-url%3Dhttp%253A%252F%252Fin.propertag.proj%252Fopenid%252Boauth.html%26lType%3Dinitiate%26lResponse%3D1",oauth_signature_method="HMAC-SHA1",oauth_signature="lsbQZvoII9Z5YsqM3aUPbLdiEoI%3D"' (length=481)
'string' => string 'POST&https%3A%2F%2Fapi.linkedin.com%3A80%2Fuas%2Foauth%2FrequestToken&oauth_callback%3Dhttp%253A%252F%252Fapi.propertag.proj%252Fauthenticate%252Foauth%253Fprovider%253Dlinkedin%2526callback-url%253Dhttp%25253A%25252F%25252Fin.propertag.proj%25252Fopenid%25252Boauth.html%2526lType%253Dinitiate%2526lResponse%253D1%26oauth_consumer_key%3Dler1lhjlr04q%26oauth_nonce%3D37642191fbd5d7c3b69ab42cced8b9cc%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1312808590%26oauth_version%3D1.0' (length=489)
'error' => string 'OAuth callback URL was not confirmed by the LinkedIn end-point' (length=62)
'success' => boolean false
A:
Did you make any changes to the Simple-LinkedIn Library code that may have caused it to break?
As for the demo script, because it is divided into various files, you have to make sure that you include your api key and secret in each file.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
window.load doesn't fire always on chrome?
I have this userscript:
// ==UserScript==
// @name test
// @namespace test
// @description show's an alert on load
// @include http://*
// @include https://*
// ==/UserScript==
window.addEventListener('load', function(){alert("loaded");}, false);
This works fine on Firefox on all pages but doesn't work at all on Chrome at some occasions.
One example is this website: http://lexin.nada.kth.se/lexin/
Entering the link in the address and hitting enter, loads the page normally but no alert is popped up. If you press F5 to refresh the page, the popup appears.
Is there some explanation to this weird behaviour?
A:
The cause of the problem is that the Content script is sometimes executed when the document has already fully loaded. This is illustrated using the following Content script ("User Script"):
// ==UserScript==
// @name Test
// @namespace Test
// @include *
// ==/UserScript==
window.addEventListener('load', function(){alert("loaded");}, false);
alert(document.readyState); // When this prints "complete", onload never runs
To solve the issue, use the @run-at document-start meta-rule, which causes the script to execute before the document is created:
...
// @run-at document-start
// ==/UserScript==
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rank students based on their average in MySQL
I have been researching and trying various queries to get this to work.
What I want to happen is to rank each student based on their average which will be calculated by using AVG(grade) and this will be grouped by student_id. The table with the necessary info is as follows:
assessment_id | student_id | grade | subject_id
What I would like to see after the query is:
student_id | AVG(grade) | rank
I would also like to get the rank of a student using PHP, for example (mysql_query) WHERE student_id = '1001'
The closest I have come to getting this was by using the query below:
SELECT student_id, AVG(grade), (@rn := @rn + 1) AS rank
FROM grades CROSS JOIN (SELECT @rn := 0) CONST
GROUP BY student_id ORDER BY AVG(grade) DESC
The problem with the query above is that it ranks the students based on their student_id number.
I have searched for solutions all over but they just seem to not solve what I am after. I would really appreciate your help towards this.
A:
I can't test this right now, but you probably want something like this:
SELECT student_id, avg, (@rn := @rn + 1) AS rank
FROM
(SELECT student_id, AVG(grade) as avg
FROM grades
GROUP BY student_id ORDER BY AVG(grade) DESC) agg
CROSS JOIN (SELECT @rn := 0) CONST
ORDER BY avg DESC
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Some Lonely Primes
I know, I know, yet another primes challenge...
Related
A lonely (or isolated) prime is a prime number p such that p-2, p+2, p-4, p+4 ... p-2k, p+2k for some k are all composite. We call such a prime a kth-times-isolated prime.
For example, a 5th-times-isolated prime is 211, since all of 201, 203, 205, 207, 209, 213, 215, 217, 219, 221 are composite. (p-2*5=201, p-2*4=203, etc.)
Challenge
Given two input integers, n > 3 and k > 0, output the smallest kth-times-isolated prime that is strictly larger than n.
For example, for k = 5 and any n in range 4 ... 210, the output should be 211, since that's the smallest 5th-times-isolated prime strictly larger than the input n.
Examples
n=55 k=1
67
n=500 k=1
503
n=2100 k=3
2153
n=2153 k=3
2161
n=14000 k=7
14107
n=14000 k=8
14107
Rules
If applicable, you can assume that the input/output will fit in your language's native Integer type.
The input and output can be given by any convenient method.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.
A:
Jelly, 17 13 bytes
_æR+⁼ḟ
‘ç1#Ḥ}
Try it online!
How it works
‘ç1#Ḥ} Main link. Left argument: n. Right argument: k
‘ Increment; yield n+1.
Ḥ} Unhalve right; yield 2k.
ç1# Call the helper link with arguments m = n+1, n+2, ... and k until 1 one
them returns a truthy value. Return the matching [m].
_æR+⁼ḟ Helper link. Left argument: m. Right argument: k
_ Subtract; yield m-2k.
+ Add; yield m+2k.
æR Prime range; yield the array of primes in [m-2k, ..., m+2k].
ḟ Filterfalse; yield the elements of [m] that do not occur in [k], i.e., [m]
if m ≠ 2k and [] otherwise.
The result to the left will be non-empty when m = 2k, as there always is
a prime in [0, ..., 2m], since m > n > 3.
⁼ Test the results to both sides for equality.
This yields 1 iff m is the only prime in [m-2k, ..., m+2k].
A:
Husk, 13 bytes
ḟ§=;ofṗM+ṡD⁰→
Try it online!
Explanation
Pretty straightforward.
ḟ§=;ofṗM+ṡD⁰→ Inputs are k and n.
→ Increment n
ḟ and find the first number m >= n+1 such that:
ṡD⁰ Take symmetric range [-2k,..,2k].
M+ Add m to each.
ofṗ Keep those that are prime.
§= Check equality with
; the singleton [m].
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Enable external SSH traffic on selected workstations within my network
I have already enabled an external SSH connection (with public and private keys) to my router, however... I would also like to enable an ssh connection to one of my internal workstations (permanently @ 192.168.1.3)
How would I enable remote access to this workstation from an external network? I dont see how port forwarding would work, because it can either route to the firewall router or to the workstation behind the router.
Please share some light on this for my simple mind.
I plan to setup a WinSCP (or Putty) ssh connection when remotely accessing the two network devices.
ps. my router is running openWRT.
Thanks!
A:
You're correct port forwarding port 22 doesn't help in this case.
A solution is to connect to your gateway device on a different port had have it forward the connection to port 22 on your internal host. You then need to use the -p option to specify the port e.g. if you forward port 2222 then
ssh -p 2222 [email protected] ...
You could also have your gateway device listen for it's connections on a non standard port and then have it forward port 22.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MongoDB update creates array inside array
I have been sitting with this problem for hours and was unable to find solution, so I decided to ask for your help. What is wrong in my query? The problem is it creates array inside array, though my desired result would be simple array.
BasicDBList list = new BasicDBList();
for (Paths pair : objects)
{
list.add(new BasicDBObject("path", pair.getPath())
.append("thumbnailPath, pair.getThumbnailPath()));
}
BasicDBObject updateCommand = new BasicDBObject();
updateCommand.append( "$push", new BasicDBObject( "imageContent", list ) );
WriteResult result = viewsCollection.update( new BasicDBObject(MongoFieldNames.ID, groupId), updateCommand, true, true );
And the result of pushed array is
"imageContent" : [
[
{
"path" : "sadL.png",
"thumbnailPath" : sad.png"
},
{
"path" : "someImgL.png",
"thumbnailPath" : "someimg.png"
}
]
]
A:
$push will create the array property if it doesn't exist. So in this case, it create the property "imageContent." then it pushes the value you've given: an array. What you want is probably just $set.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
InApp Purchase in Ionic 3 - How do I implement a payment between users?
I would like to implement a system in my app that allows one user to buy a digital product from another user. See this as an event ticket reservation system. The organizer is the seller and the final user is the buyer.
I would take a little fee to make it profitable.
Are those kind of payment subject to 30% commission from Google?
Do you know a secure system (PayPal maybe?) that could help me to set it up?
A:
Apple or Android in app purchases can be only used in conjunction with use cases defined by developer agreement.
All purchasing using an app is subject to the 30% fee, except for very specific use cases (like newspaper media subscription, etc.).
User-to-user real money transfer is a very tricky concept (as it basically allows funds transfer between individuals and tax and other authorities would want to control that) from both a legal and accounting points of view.
Unless you have serious business and you are willing to spent considerable resources to validate all nuances it is generally not a good easy idea to go with for an independent developer.
You can check Stripe Connect as the closest offering for web projects: https://stripe.com/connect
But also see their limitations section to see if it is even suitable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Data Warehouse Management Command Line Application - PowerShell or C# Console App
I'll preface this question by saying this is for a Microsoft only shop.
If you were to write a console app to manage a data warehouse what would you use:
1) Writing a custom environment for PowerShell (ala the latest flavors of Exchange / SQL Server)
2) Write it as a C# Console App
If #2 are there any frameworks that offload writing a "menu system" or any other tasks for you.
If this app needed to last 6 to 8 years - would you use PowerShell?
No one on the team currently has PowerShell experience, but we are quick learners.
A:
If you write your management functionality as PowerShell cmdlets, then you can surface that functionality either by letting people run cmdlets directly, or by wrapping them in a GUI. Going with PowerShell probably gives you the most long-term flexibility, and as MS implements more PowerShell cmdlets, it means that managing your data warehouse could be incorporated with other, larger business processes if necessary. I would probably NOT choose to write a C# console app - but I have a distinctly more "administrator" perspective. We admins are tired of having custom console apps tossed at us - the idea of PowerShell is to standardize everything in a way that supports both command-line and GUI administration.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Swift: location not being updated when returned from background
I have a Swift app that I am trying to update the location when the app is returned from the background, but it doesn't seem to work when returned from the background.
On launch of the app, I'll get the location just fine. After getting the location I call stopUpdatingLocation() so I don't continue to get the location:
locationManager.stopUpdatingLocation()
Then, in my AppDelegate.swift I startUpdatingLocation again:
func applicationWillEnterForeground(application: UIApplication) {
ViewController().locationManager.startUpdatingLocation()
}
This is my code so far:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error while updating location " + error.localizedDescription)
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var userLocation:CLLocation = locations[0] as CLLocation
println("\(userLocation.coordinate.latitude),\(userLocation.coordinate.longitude)")
locationManager.stopUpdatingLocation()
}
}
However, whenever I background the app (click home), and then return to the app the location isn't updated. Any idea what I might be doing wrong here?
A:
In applicationWillEnterForeground, the code is creating a new, local instance of ViewController that is never displayed, does not yet have a locationManager created and so has no effect.
It is not referring to the ViewController instance that already exists and is displayed (and has the locationManager instance that was originally started).
Instead, it should get a reference to the existing instance. Assuming ViewController is the root view controller, you could do:
func applicationWillEnterForeground(application: UIApplication) {
if let rvc = window?.rootViewController as? ViewController {
rvc.locationManager.startUpdatingLocation()
}
}
However, it might be better practice to let the ViewController class itself manage its own behavior. This way, the app delegate doesn't have to find a reference to the view controller's instance and it doesn't directly access the view controller's internal state and ViewController becomes more self-contained.
In addition to the app delegate method applicationWillEnterForeground, it's possible to monitor these events from anywhere using the UIApplicationWillEnterForegroundNotification notification.
In ViewController, you can register and unregister for the notification in (for example) viewWillAppear and viewWillDisappear. When registering, you indicate which method to call for the event and everything is handled inside ViewController (and the code in applicationWillEnterForeground can be removed).
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "willEnterForegound",
name: UIApplicationWillEnterForegroundNotification,
object: nil)
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: UIApplicationWillEnterForegroundNotification,
object: nil)
}
func willEnterForegound() {
locationManager.startUpdatingLocation()
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I securely connect to Cloudant using PouchDB?
I am creating a mobile app for Android and iOS using Cordova/PhoneGap and am using IBM's Cloudant database for storage. I am using the PouchDB javascript library to access the Cloudant database. Currently I have this code to access it...
db = new PouchDB('https://[myaccount].cloudant.com/[mydb]', {
auth: {
username: 'myusername',
password: 'mypassword'
}
});
I am aware that this is extremely insecure, and am wondering if there is a more secure way to connect to my database from within the app?
A:
One option you may like to consider is implementing a service (e.g. running in the cloud) for registering new users of your app. Registration logic could look something like this:
The handset code communicates with your application service requesting registration of the user
The service makes a call to Cloudant to create an API key which would is returned to the handset code
The handset code saves the API key 'username' and 'password' on the device. These credentials are then use in the auth: { username: 'myusername', password: 'mypassword' } object.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
If an angel can fall, can a demon rise?
My understanding is that archangel Lucifer was cast out of Heaven was because he refused to accept the humans and that was a sin in God's eyes. This tells us that angels can be bad.
From what I'm told, humans can commit no sin that God will not eventually forgive. He sees all sins equally. When a human doesn't seek forgiveness, that human's soul goes to Hell. In Hell, the soul is tortured, tormented and corrupted. It eventually becomes a demon.
So a demon is eventually a human soul and thus, God can still forgive the human if it takes a path of redemption.
But the question is, would God forgive a demon and allow it entrance into Heaven?
A:
If an angel can fall, can a demon rise?
According to most Christian teaching and traditions, the short answer is no.
Your question however does pose certain interesting perplexities to say the least.
First of all, I would like to make it clear that the Gospels do mention that there is such a thing as an unpardonable sin that man can commit.
The unpardonable/unforgivable sin or “blasphemy of the Holy Spirit” is mentioned in Mark 3:22–30 and Matthew 12:22–32. Jesus said, “Truly I tell you, people can be forgiven all their sins and every slander they utter” (Mark 3:28), but then He gives one exception: “Whoever blasphemes against the Holy Spirit will never be forgiven; they are guilty of an eternal sin” (verse 29). - What is the unpardonable sin / unforgivable sin?
Most theologians believe that the unpardonable sin the refusal of God's mercy and forgiveness and thus the individual condemns itself to hell of the damned because it refuses to be pardoned by god for it's sins. Thus the soul in hell becomes damned (not a demon) in hell who shares the company of Satan and all his demons for all eternity.
In Roman Catholic teaching there are six sins that blaspheme against the Holy Spirit. They are: 1. Despair (believing that one's evil is beyond God's forgiveness); 2. Presumption (glory without merit, that is, hope of salvation without keeping the Commandments, or expectation of pardon for sin without repentance); 3. Envying the goodness of another (sadness or repining at another's growth in virtue and perfection); 4. Obstinacy in sin (willful persisting in wickedness, and running on from sin to sin, after sufficient instructions and admonition); 5. Final impenitence (to die without either confession or contrition for our sins), and 6. Impugning the known truth (to argue against known points of faith, and this includes misrepresenting parts or all of the Christian faith to make it seem undesirable). - Eternal sin (Wikipedia)
For most denomination, the souls of men in hell are there for eternity and are known as the damned, not demons. The one notable exception is in Mormonism.
The other sense in which Mormons sometimes use the word "hell" is as a reference to what they call Outer Darkness, which is reserved for Satan and his spiritual minions, together with a few human beings that qualify as "sons of perdition."
Although this would be close to the classical conception of Hell, the Mormon belief is that very few will go there, for the bar to be sent there is quite high. One must have a sure knowledge (beyond faith) that Jesus is the Christ, and then reject him anyway in the face of such a knowledge. This is Judas Iscariot territory and really beyond the capacity of the average person to achieve.
Mormons also believe that just because you're dead doesn't mean the game is over. They take seriously the Descensus (mentioned in the Apostle's Creed), and believe that Jesus descended into the Spirit World during the three days that his body lay in the tomb to initiate the preaching of the Gospel to the spirits there, and organized this postmortem evangelization so that it continues even today. So even those who never had an opportunity to hear the Gospel will have such a chance in the next life.
Further, Mormons believe that there are certain necessary, salvific ordinances (what other Christians would call "sacraments"), that one must receive to achieve the Celestial (or highest) Kingdom. That is why Mormons perform these sacraments vicariously for the dead in their temples.
So, for instance, if a deceased person is baptized for the dead, that doesn't mean that person is considered a member of the Church or a Mormon; it simply means that the sacrament has been performed on his or her behalf and he or she has the option to accept it, but also the freedom of will to reject it.
So Bell's formulation that "everyone will have a place in heaven, whatever that turns out to be" is one that resonates with me, and I think he's on the right path.
I don't believe that a just God would subject people to eternal physical torment for ever and ever, especially when in many cases people simply did not have an opportunity to learn of the Gospel in this life through no fault of their own. - Mormon Damnation
Although Mormon theology allows for a soul in hell to be saved and eventually taken up into heaven, it should be noted that the Church of Latter Day Saints is not recognized as a Christian denomination by many other Christian communities.
In most Christian Churches, the term demon signifies a devil such as Lucifer, Satan, Beelzebub, Zebulun, Meridian or Asmodeus as well as all the other evil spirits in hell who are damned for eternity for their sins.
But then there is Origen!
Did Origen believe in the salvation of the devil? He clearly believed that all rational souls were able to be saved (Contra Celsum 4.99) and this would, on Origen's view of the nature of demonic forces, have included the devil and his demons. So the accusation was stirred up that he taught the salvation of demons. But, in a letter to his friends in Alexandria he explicitly denied that he thought the devil and his demons would be saved. So did he or didn't he? Tricky.
Perhaps the following passage explains how he could maintain both positions:
"For the destruction of the last enemy must be understood in this way, not that its substance which was made by God shall perish, but that the hostile purpose and will which proceeded, not from God but from itself, will come to an end. It will be destroyed, therefore, not in the sense of ceasing to exist, but of being no longer an enemy and no longer death. For to the Almighty nothing is impossible, nor is anything beyond the reach of cure by its maker.”
Peri Archon 3.6.5 - Origen on the Salvation of the Devil
An interesting storyline: The YouTube movie, Dark Angel The Ascent Full Moon has the basic story line of a demon raising to earth in order to try to do good! Movies never lie!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MappingException when migrating from Hibernate 3 / Grails 2.2.4 to Hiberate 5 / Grails 3.2.4
I have a project that uses grails 2.2.4 and hibernate 3. I am migrating it over to grails 3.2.4, which uses hibernate 5. I started by creating a grails 3.2.4 project from scratch, and now I am slowly copying over small bits of the code from the old project and getting it working. At first, I only copied over my User, UserRole, and Role classes and got my entire spring security login flow working. Then, I copied over my remaining domain objects and tried to start my project. My domain objects use GORM mappings, rather than JPA annotations. The project won't even start now and gets the following exception on start up (I linked to a public gist because the content is too long for what stack overflow allows).
https://gist.github.com/schmickie/10522d3a2b8a66b6fb79f76e2af0fd72
I did some searching online for the error and everything I can find says it's related to issues with setting up composite primary keys. However, I am not using any composite primary keys. Anyone have any ideas what's going wrong? The domain objects referenced in the error, Api and Method, are shown below.
class Api implements Serializable {
String name
boolean enabled
String apiVersion
String swaggerVersion
String resourcePath
String jsonData
boolean https = true
String regionSource
String contractName
String contractBasePath
Date dateCreated
Date lastUpdated
Date deprecationDate
static hasMany = [methods: Method, models: Model, apiServers: ApiServer]
static mapping = {
cache true
}
static constraints = {
name(nullable: false, blank: false)
enabled()
apiVersion(nullable: true, blank: true)
resourcePath(nullable: true, blank: true)
swaggerVersion(nullable: true, blank: true)
jsonData(type: 'text', nullable: true, blank: true)
dateCreated()
lastUpdated()
deprecationDate(nullable: true)
regionSource(nullable: true)
contractName(nullable: true)
contractBasePath(nullable: true)
}
public Method getMethod(String name) {
for (Method method : methods) {
if (method.name.equals(name)) {
return method
}
}
return null
}
}
class Method implements Serializable, Comparable<Method> {
String name
boolean enabled
String edgePath
HttpMethodEnum edgeHttpMethod
String servicePath
HttpMethodEnum serviceHttpMethod
String summary
String notes
boolean deprecatedMethod
String responseClass
SortedSet<EdgeParameter> edgeParameters
SortedSet<ServiceParameter> serviceParameters
Date dateCreated
Date lastUpdated
String publicResponseTransformScript
String baseResponseTransformScript
String regionFieldName
String platformFieldName
String apiKeyFieldName
String uriTransformScript
long cacheExpiry
static belongsTo = [api: Api]
static hasMany = [edgeParameters: EdgeParameter, serviceParameters: ServiceParameter, errorResponses: ApiErrorResponse]
static mapping = {
cache true
errorResponses sort: 'code', order: "asc"
}
static constraints = {
name(blank: false)
enabled()
edgePath(nullable: false, blank: false)
edgeHttpMethod(nullable: false, blank: false)
servicePath(nullable: false, blank: false)
serviceHttpMethod(nullable: false, blank: false)
summary(nullable: false, blank: false)
notes(nullable: true, blank: true)
deprecatedMethod()
responseClass(nullable: true, blank: true)
publicResponseTransformScript(nullable: true)
baseResponseTransformScript(nullable: true)
regionFieldName(nullable: true)
platformFieldName(nullable: true)
apiKeyFieldName(nullable: true)
uriTransformScript(nullable: true)
cacheExpiry(nullable: false, blank: true)
}
}
A:
Well, I figured it out. I did a lot of stepping through the hibernate/GORM initialization code. I found that the problem is actually with an unrelated mapping in the same class. In the Method class, there is another mapping shown above called errorResponses. When the method DefaultGrailsDomainClass.establishRelationshipForCollection is called to establish the relationship between the Api and Method classes, it calls another method GrailsClassUtils.getPropertiesOfType. This class iterates over all of the properties of the Method class and tries to find any whose type matches the type of the api association. Here is the method implementation:
public static PropertyDescriptor[] getPropertiesOfType(Class<?> clazz, Class<?> propertyType) {
if (clazz == null || propertyType == null) {
return new PropertyDescriptor[0];
}
Set<PropertyDescriptor> properties = new HashSet<PropertyDescriptor>();
try {
for (PropertyDescriptor descriptor : BeanUtils.getPropertyDescriptors(clazz)) {
Class<?> currentPropertyType = descriptor.getPropertyType();
if (isTypeInstanceOfPropertyType(propertyType, currentPropertyType)) {
properties.add(descriptor);
}
}
}
catch (Exception e) {
// if there are any errors in instantiating just return null for the moment
return new PropertyDescriptor[0];
}
return properties.toArray(new PropertyDescriptor[properties.size()]);
}
The first property it finds is the api property, which passes the isTypeInstanceOfPropertyTypecheck and is added to the properties Set. Due to a poorly named helper method named getApiErrorResponse, the call to BeanUtils.getPropertyDescriptors(clazz) included a field called apiErrorResponse in the returned collection. However, there is no such field in my Method class (there is a mapped association called errorResponses, but nothing called apiErrorResponse). Thus, the propertyType of the PropertyDescriptor for this non-existent field is null. Then, when isTypeInstanceOfPropertyType is called with the null value for currentPropertyType, it throws a NullPointerException. This results in the getPropertiesOfType method returning new PropertyDescriptor[0] as shown in the catch clause. Later down the line, this failure to return the property descriptor that maps to api causes an incorrect OneToOne mapping type to be generated for the association and that mapping is missing a mapped field as well.
Basically this was a case of the grails code not providing enough information about what really went wrong. It silently suppressed the NullPointerException that was occuring on another field, and the error on that other field was causing improper initialization of the api field. That meant the later error messages were improperly complaining because information/configuration was presumed to be missing when it wasn't, leading to a very confused engineer.
My ultimate fix was to move the getApiErrorResponse helper method out of the Method class and into MethodService. Note that having this helper method in my domain object worked fine in my old Grails project (Grails 2.2.4 with Hiberate 3) that I was migrating from, so it is presumably new behavior in the latest version of Grails/GORM/Spring/Groovy to assume that all get* methods map to fields. I don't know which of these would be the culprit, but they are all on newer versions than my old project.
I also submitted a PR to grails-core to log helpful error messages when these kinds of exceptions occur instead of silently swallowing them.
https://github.com/grails/grails-core/pull/10400
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Running good in browsers, but error by flash player directly : ReferenceError: Error #1056
I wrote a flex demo, customized spark TextInput skin with rounded corners and a search icon in it, like mac os x search box, it's running good in browsers (by Flash Player browser plug-in) either .html or .swf, but error by flash player directly.
the error:
ReferenceError: Error #1056: Cannot create property allowCodeImport on flash.system.LoaderContext.
at mx.core::CrossDomainRSLItem/completeCdRslLoad()
at mx.core::CrossDomainRSLItem/itemCompleteHandler()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
there is the test demo, includes source: http://www.ycoder.com/wp-content/uploads/2011/07/CustomComponentSkinTest.zip
CustomTextInput
package component{
import skin.CustomTextInputSkin;
import spark.components.TextInput;
[Style(name="icon", inherit="no", type="Object")]
[Style(name="radius", inherit="true", type="Number")]
public class CustomTextInput extends TextInput{
[Embed(source="/images/search.png")]
private const defaultIcon:Class;
public function CustomTextInput(){
super();
this.setStyle('icon', defaultIcon);
this.setStyle('radius', 10);
this.setStyle("skinClass", CustomTextInputSkin);
}
}
}
CustomTextInputSkin
<!-- border -->
<!--- @private -->
<s:Rect left="0" right="0" top="0" bottom="0" id="border" radiusX="{hostComponent.getStyle('radius')}" radiusY="{hostComponent.getStyle('radius')}" >
<s:stroke>
<!--- @private -->
<s:SolidColorStroke id="borderStroke" weight="1" />
</s:stroke>
</s:Rect>
<!-- fill -->
<!--- Defines the appearance of the TextInput component's background. -->
<s:Rect id="background" left="1" right="1" top="1" bottom="1" radiusX="{hostComponent.getStyle('radius')}" radiusY="{hostComponent.getStyle('radius')}" >
<s:fill>
<!--- @private Defines the background fill color. -->
<s:SolidColor id="bgFill" color="0xFFFFFF" />
</s:fill>
</s:Rect>
<!-- shadow -->
<!--- @private -->
<s:Rect left="1" top="1" right="1" height="1" id="shadow" radiusX="{hostComponent.getStyle('radius')}" radiusY="{hostComponent.getStyle('radius')}" >
<s:fill>
<s:SolidColor color="0x000000" alpha="0.12" />
</s:fill>
</s:Rect>
<s:HGroup id="textGroup" gap="0" height="100%" paddingLeft="4" paddingRight="4">
<!-- icon -->
<s:Image id="icon" includeIn="normal" x="0" y="0" source="{hostComponent.getStyle('icon')}" verticalAlign="middle" height="100%"/>
<!-- text -->
<!--- @copy spark.components.supportClasses.SkinnableTextBase#textDisplay -->
<s:RichEditableText id="textDisplay"
verticalAlign="middle"
widthInChars="10"
left="1" right="1" top="1" bottom="1" height="100%"/>
</s:HGroup>
test case
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:component="component.*" >
<s:VGroup paddingLeft="20" paddingTop="20">
<s:TextInput />
<component:CustomTextInput />
<component:CustomTextInput radius="12" icon="images/device.png" text="ABC Test ... hohoho" editable="false" />
</s:VGroup>
</s:Application>
A:
The reason is: Flex SDK 4.5 support only flash player 10.2+, and my standalone flash player version is 10.0., my flash player plug-in version is 10.2.. thinks
|
{
"pile_set_name": "StackExchange"
}
|
Q:
itertools product function two elements at a time in a list
I have the following list:
L = [0, 25, 50, 75, 100]
I want to find all the possible combinations for this list but two elements at a time, e.g:
Combi = [(0, 0), (0, 25), (25,0), (25, 25), (0, 0), (0, 50), (50, 0), (50, 50), (0, 0), (0, 75), (75, 0), (75, 75)...]
and so on.
Is there a concise way to achieve this?
A:
Seems like you want a product of all unique pairs in the input. You can tie together three itertools functions to achieve this:
from itertools import chain, combinations, product
L = [0, 25, 50, 75, 100]
print(list(chain.from_iterable(product(pair, repeat=2) for pair in combinations(L, 2))))
Output matches your spec:
[(0, 0), (0, 25), (25, 0), (25, 25), (0, 0), (0, 50), (50, 0), (50, 50), (0, 0), (0, 75), (75, 0), (75, 75), (0, 0), (0, 100), (100, 0), (100, 100), (25, 25), (25, 50), (50, 25), (50, 50), (25, 25), (25, 75), (75, 25), (75, 75), (25, 25), (25, 100), (100, 25), (100, 100), (50, 50), (50, 75), (75, 50), (75, 75), (50, 50), (50, 100), (100, 50), (100, 100), (75, 75), (75, 100), (100, 75), (100, 100)]
If you want to push all the work to the C layer (no generator expression byte code execution per combination), another import (and some even more excessively dense code) can get you there:
from functools import partial
print(list(chain.from_iterable(map(partial(product, repeat=2), combinations(L, 2)))))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error: 400: Your project does not own Dynamic Links domain
I'm using react-native-firebase to create dynamic links, when I create standard link everything works fine, but when I'm creating short link, it gives an error: "Error: 400: Your project does not own Dynamic Links domain". Any ideas how is possible to fix that?
UPDATE: problem occurs only in Android, in IOS works fine
Code for the creating short dynamic link:
onClickShare= () => {
const link =
new firebase.links.DynamicLink(redirectLink , Config.FIREBASE_CONFIG.dynamicLink)
.android.setPackageName(Config.ANDROID_PACKAGE_NAME)
.ios.setBundleId(Config.IOS_BUNDLE_ID)
.ios.setAppStoreId(Config.IOS_APP_STORE_ID)
.social.setDescriptionText(description)
.social.setTitle(this.props.event.title)
firebase.links()
.createShortDynamicLink(link, 'SHORT')
.then((url) => {
Share.share({
message: _('shareLinkMessage') + " " + url,
title: _('shareLinkTitle'),
}, {
// Android only:
dialogTitle: _('shareLinkAndroid'),
})
})
A:
If you get such error, update your google-services.json file!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Simplify trigonometric identities in complex expression
The function FullSimplify can easily reformat this expression
FullSimplify[Cos[omegan t]^2 + Sin[omegan t]^2]
(* output: 1 *)
However, it cannot simplify the same expression if contained in a larger expression:
sol = DSolve[m*(x''[t] + omegan^2 * x[t]) == B*Exp[I*omegad*t], x, t]
{{x->Function[{t},C[1] Cos[omegan t]+C[2] Sin[omegan t]-(B E^(I omegad t) (Cos[omegan t]^2+Sin[omegan t]^2))/(m (omegad-omegan) (omegad+omegan))]}}
Result:
$-\frac{B e^{i \omega_d t} \left(\sin ^2(\omega_n t)+\cos ^2(\omega_n t)\right)}{m (\omega_d-\omega_n) (\omega_d+\omega_n)}+c_2 \sin (\omega_n t)+c_1 \cos (\omega_n t)$
Instead of:
$-\frac{B e^{i \omega_d t}}{m (\omega_d^2-\omega_n^2)}+c_2 \sin (\omega_n t)+c_1 \cos (\omega_n t)$
What is the command I'm missing?
A:
Collect with its optional 3rd argument is very effective here
Collect[x[t] /. Flatten[sol], B, FullSimplify]
(* -((B E^(I omegad t))/(m omegad^2 - m omegan^2)) + C[1] Cos[omegan t] + C[2] Sin[omegan t] *)
In fact, Collect may not be needed here.
Note that simplification does not reach into the body of Function. You probably need to evaluate it before attempting to simplify.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Checkstyle check for duplicate classes
The project I am on is having horrible problems with class collisions in the classpath and developers reusing class names. For example, we have 16, yes 16 interfaces called Constants in this bloody thing and its causing all kinds of problems.
I want to implement a checkstyle check that will search for various forms of class duplication. here's the class
import java.io.File;
import java.util.List;
import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
import com.wps.codetools.common.classpath.ClassScanner;
import com.wps.codetools.common.classpath.criteria.ClassNameCriteria;
import com.wps.codetools.common.classpath.locator.ClasspathClassLocator;
/**
* This codestyle check is designed to scan the project for duplicate class names
* This is being done because it is common that if a class name matches a class
* name that is in a library, the two can be confused. Its in my best practice that
* the class names should be unique to the project.
*
*
*/
public class DuplicateClassNames extends AbstractFileSetCheck {
private int fileCount;
@Override
public void beginProcessing(String aCharset) {
super.beginProcessing(aCharset);
// reset the file count
this.fileCount = 0;
}
@Override
public void processFiltered(File file, List<String> aLines) {
this.fileCount++;
System.out.println(file.getPath());
ClassScanner scanner = new ClassScanner();
scanner.addClassCriteria(new ClassNameCriteria(file.getPath()));
scanner.addClassLocater(new ClasspathClassLocator());
List<Class<?>> classes = scanner.findClasses();
if (classes.size() > 0) {
// log the message
log(0, "wps.duplicate.class.name", classes.size(), classes);
// you can call log() multiple times to flag multiple
// errors in the same file
}
}
}
Ok, so the ClassScanner opens up the classpath of the current JVM and searches it with various criteria. This particular one is a class name. It can go into the source folders, and most importantly it can go into the libraries contained in the classpath and search the *.class files within the jar using ASM. If it finds copies based on the criteria objects that are presented, it returns an array of the files. This still needs some massaging before mainstream but im on a time budget here so quick and dirty it goes.
My problem is understanding the input parameters for the check itself. I copied from the example, but it looks like CheckStyles is giving me a basic IO file object for the source file itself, and the contents of the source file in a string array.
Do I have to run this array thru another processor before I can get the fully qualified class name?
A:
This is more difficult to do right than one might think, mostly because Java supports all kinds of nesting, like static classes defined within an interface, anonymous inner classes, and so on. Also, you are extending AbstractFileSetCheck, which is not a TreeWalker module, so you don't get an AST. If you want an AST, extend Check instead.
Since "quick and dirty" is an option for you, you could simply deduce the class name from the file name: Determine the canonical path, remove common directories from the beginning of the String, replace slashes with dots, cut off the file extension, and you are more or less there. (Without supporting inner classes etc. of course.)
A better solution might be to extend Check and register for PACKAGE_DEF, CLASS_DEF, ANNOTATION_DEF, ENUM_DEF, and INTERFACE_DEF. In your check, you maintain a stack of IDENTs found at these locations, which gives you all fully qualified class names in the .java file. (If you want anonymous classes, too, also register for LITERAL_NEW. I believe in your case you don't want those.)
The latter solution would not work well in an IDE like Eclipse, because the Check lifecycle is too short, and you would keep losing the list of fully qualified class names. It will work in a continuous integration system or other form of external run, though. It is important that the static reference to the class list that you're maintaining is retained between check runs. If you need Eclipse support, you would have to add something to your Eclipse plugin that can keep the list (and also the list from previous full builds, persisted somewhere).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to implement jQuery to PHP or how to get javascript-proceeded output of html page?
jQuery has some awsome methods, that I could really use while working with external htmls is there a way to somehow transform it into a PHP framework ?
EDIT: Many people missunderstood the question purpose - of course I know PHP's DOM but the real purpose was to be able to do same syntax (and use same methods) in PHP while working with external htmls.
EDIT2: possible solution would be something like get html string, add a jQuery string to it and somehow make PHP to get the javascript-processed output ?
A:
The traversal methods based on the CSS3 selector syntax has been replicated in PHPQuery.
https://code.google.com/p/phpquery/ is is a server-side, chainable,
CSS3 selector driven Document Object Model (DOM) API based on jQuery
JavaScript Library.
It's quite neat if you need to manipulate and query DOM structures, though in my experience it was quite slow.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Como faço para enviar vários valores para uma única Activity
Bom dia pessoal,
Estou com a seguinte situação:
Tenho 4 telas (Activity), são elas: MainActivity, DisiplinaActivity, AvaliacaoActivity e ResultadoFinalActivity.
A questão é, os dados coletados das telas DisiplinaActivity e AvaliacaoActivity retornam para a MainActivity e depois são enviados para a ResultadoFinalActivity.
Minha dúvida é: como faço para enviar esses dados através de chave,valor? Até agora tenho esse código, onde recebo os valores, mas não sei como enviar eles para a tela final.
Alguém já pegou algo assim ou consegue me dar uma luz?
Agradeço
public void proximaTela(View v) {
Intent enviarDados = null;
switch (v.getId()) {
case R.id.btnDisciplina:
enviarDados = new Intent(this, DisciplinaActivity.class);
enviarDados.putExtra("disciplina", disciplina);
startActivityForResult(enviarDados, Constantes.REQUEST_CODE_DADOS_DISCIPLINA);
break;
case R.id.btnAvalicao1:
enviarDados = new Intent(this, AvaliacaoActivity.class);
enviarDados.putExtra("avaliacao1", disciplina);
startActivityForResult(enviarDados, Constantes.REQUEST_CODE_DADOS_AVALIACAO);
break;
case R.id.btnAvalicao2:
enviarDados = new Intent(this, AvaliacaoActivity.class);
enviarDados.putExtra("avaliacao2", disciplina);
startActivityForResult(enviarDados, Constantes.REQUEST_CODE_DADOS_AVALIACAO2);
break;
case R.id.telaResultado:
enviarDados = new Intent(this, ResultadoActivity.class);
break;
default:
Toast.makeText(this, "Problema ao enviar ou receber dados!", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
if (requestCode == Constantes.REQUEST_CODE_DADOS_DISCIPLINA){
Bundle params = data.getExtras();
String disciplina = params.getString("nomeDisciplina");
String professor = params.getString("nomeProfessor");
}else if (requestCode == Constantes.REQUEST_CODE_DADOS_AVALIACAO){
Bundle params = data.getExtras();
String avaliacao1 = params.getString("tituloAvl1");
Double nota1 = params.getDouble("notaAvl1");
}else if (requestCode == Constantes.REQUEST_CODE_DADOS_AVALIACAO2){
Bundle params = data.getExtras();
String avalicao2 = params.getString("tituloAvl2");
Double nota2 = params.getDouble("notaAvl2");
}
}
}
Botão Salvar da tela DisciplinaActivity
public void btnSalvar(View v) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("nomeDisciplina", editnomeDisciplina.getText().toString());
intent.putExtra("nomeProfessor", editNomeProfessor.getText().toString());
startActivity(intent);
setResult(RESULT_OK,intent);
finish();
}
A:
Como faço para enviar esses dados através de chave,valor?
Assim como um Bundle faz?
private void iniciarActivityBundle(Bundle bundle, Class<?> cls) {
// Supondo que este método está em uma activity, this é o contexto
Intent intent = new Intent(this, cls);
intent.putExtras(bundle);
startActivity(intent);
}
Use-o quando for passar dados para uma activity dessa forma:
Bundle bundle = new Bundle();
bundle.putString("nomeDisciplina", "valor");
//bundle.putString("chave", "valor");
//bundle.putInt("chave", 0);
// ...
iniciarActivityBundle(bundle, ResultadoFinalActivity.class);
Na ResultadoFinalActivity, o mais cedo possível dentro do onCreate:
receberBundle(getIntent());
Na ResultadoFinalActivity, fora do onCreate, declare:
private void receberBundle(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String nomeDisciplina = extras.getString("nomeDisciplina");
if (!TextUtils.isEmpty(nomeDisciplina)) {
// ...
}
} else {
// Não recebemos dados
// Se for possível continuar a activity, faça, se não, aborte com finish();
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Accessing Collections
Can i ask for help??
so i have this relationship with bank accounts + the user who can access it
return $this->belongsToMany('App\BankAccount', 'permissions', 'user_id',
'account_id');
and then ill pass it to my view
$view->with('access', User::where('id', $user->id)->with('bankAccounts')->get());
this is how i access it
@foreach($access as $account)
<li>{{ $account->bankAccounts }}</a></li>
@endforeach
it gives me this output
[{"id":1,"account_name":"MBTC Mambaling","type":"1","branch":"Mambaling","account_number":"331-7-331504366","contact_person":"Armand Dela Cruz","contact_number":null,"created_at":"2017-06-26 03:16:13","updated_at":"2017-06-26 03:16:13","pivot":{"user_id":2,"account_id":1,"created_at":"2017-06-26 03:16:39","updated_at":"2017-06-26 03:16:39"}}]
how can i access each of the data present in the collection??
thanks for answering in advance guys
A:
You are returning a collection of users with the following query
User::where('id', $user->id)->with('bankAccounts')->get()
I would suggest altering this to something like the following:
User::find($user->id)->bankAccounts()
This will return the users attached bankAccounts as a collection. You can then access the properties like so:
@foreach($access as $account)
<li>{{ $account->account_name}}</a></li>
@endforeach
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iOS 6 MKMapView Memory Leak and Crashes app after some time
iOS 6 MKMapView seems to be using the tons of memory, when we starts zooming and playing around with the Map View in our application(for around 7-10 mins), When we come out of the controller which has MKMapView, its some how not releasing the total memory(I am using ARC in my App). I am allocating and initializing the MKMapView thru NIB.
Controller 1 -->Controller 2 (has MKMapView)
1.5MB -->40-60MB (I have used the Instruments to find out leaks, but of no use)
When i come back to Controller1 the live bytes seems to be 7-10MB, after every visit to controller 2 there is around 2-3MB of increment in the Live Bytes, after some time it crashes the application, in console it says "Received Memory Warning". can any one please help? If you need any more info please let me know. Thanks in Advance.
A:
This is because of the way MKMapView works. There's an operation pending, so MapKit is retaining the MKMapView and it hasn't actually been deallocated yet. That isn't itself a problem. The problem is that it's still sending messages to your delegate.
The workaround is simple: As part of your view controller's cleanup set the map view's delegate to nil, which will prevent MKMapView from sending messages to it.
This is documented in MKMapViewDelegate Protocol Reference:
Before releasing an MKMapView object for which you have set a delegate, remember to set that object’s delegate property to nil. One place you can do this is in the dealloc method where you dispose of the map view.
Edit: Give Oscar an upvote as well, just below, who provided the documentation quote here.
Given ARC, I suggest this means you should set your map view's delegate to nil in your view controller's dealloc.
You can do some thing like this which resolves my issue . Change the type of map helps it too.
- (void)applyMapViewMemoryHotFix{
switch (self.mapView.mapView.mapType) {
case MKMapTypeHybrid:
{
self.mapView.mapView.mapType = MKMapTypeStandard;
}
break;
case MKMapTypeStandard:
{
self.mapView.mapView.mapType = MKMapTypeHybrid;
}
break;
default:
break;
}
self.mapView.showsUserLocation = NO;
self.mapView.delegate = nil;
[self.mapView removeFromSuperview];
self.mapView = nil;
}
-(void)viewDidDisappear:(BOOL)animated
{
[self applyMapViewMemoryHotFix];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Triple integral conversion to cylindrical coordinates equals zero
I'm asked to convert this integral:
$$\int^1_0\int_{-\sqrt{1-y^2}}^0\int^{2-x^2-y^2}_0 x\ dz\ dx\ dy $$
to cylindrical coordinates. This is what I calculated for the limits:
$$\int^{2\pi}_0\int^0_{-1}\int^{2-r^2}_0r\cos\theta \ r\ dz\ dr \ d\theta $$
For $z$ I got $2-r^2$ as the upper limit as $r^2=x^2+y^2$.
For $r$ I got $0$ as the upper limit as $r\cos\theta=0$ and so $r=0$.
For the lower limit I got
\begin{align} r\cos\theta & =-\sqrt{1-r^2\sin^2\theta}\\
r^2\cos^2\theta & =1-r^2\sin^2\theta\\
r^2(\cos^2\theta+\sin^2\theta) & = 1\\
r&=\pm1
\end{align}
This is the first part that confuses me. Should the $r$ limits be $[-1,0]$ or $[-1,1]$? I assume its the former because the latter negates all terms in the integrand and just gives zero.
Then, since the $y$ limits are $[0,1]$, I assumed the $\theta$ limits are $[0,2\pi]$, however because the integrand is a $\cos\theta$ expression, integrating it gives a $\sin\theta$ expression and $\sin(0)$ and $\sin(2\pi)=0$, this also just makes the whole integral equate to zero.
I've tried to look at the problem graphically but the $x$ part confuses me. I've never been given a triple integral to convert to cylindrical coordinates in which the $x$ limits are in this form and am not sure how to approach.
A:
Hint
In fact your integral bounds are wrong (except that for $z$). Note that the set $$\{(x,y)\ |\ -\sqrt{1-y^2}< x< 0\ ,\ 0< y< 1\}$$defines a quarter-circle with the following form in polar coordinates$$\left\{(r,\theta)\ | \ 0<r<1\ , \ {\pi\over 2}<\theta<\pi\right\}$$so the integral would become$$\int_{\pi\over 2}^{\pi}\int_{0}^{1}\int_{0}^{2-r^2}r^2\cos \theta dzdrd\theta$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
FutureBuilder is not detecting no data
I need to show a message when no data is found in the response.I get the response like this [] when there is not data.How to handle when the future is empty.I went through many post and tried but when i try them either the error message is displayed or the data is displayed.\
future: _future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
debugPrint("HAs data");
return ListView.builder(
itemExtent: 80,
itemCount: myList.length,
itemBuilder: (BuildContext context, int i) {
return Card(
child: ListTile(
onTap: () {Navigator.push(context, MaterialPageRoute(builder: (context) =>DisplayReports(appointmentDetail:myList[i])));},
contentPadding: EdgeInsets.symmetric(
horizontal: 10.0, vertical:5.0),
leading: Container(
padding: EdgeInsets.only(right: 8.0),
decoration: new BoxDecoration(),
child: Icon(Icons.date_range,color: Colors.blueGrey,)
),
title: Text(
myList[i].doctorName,
style: TextStyle(fontSize: 20.0,
color: Colors.black, fontWeight: FontWeight.bold),
),
subtitle: Row(
children: <Widget>[
Text(
myList[i].apptDateTime != null ?
formatDate(DateTime.parse(myList[i].apptDateTime), [
dd, '/', M,'/',yyyy]) : " ",
overflow: TextOverflow.ellipsis,
maxLines: 1,
softWrap: false,
style: TextStyle(fontSize: 12, color: Colors.black54,),
),
],
),
trailing: IconButton(icon: Icon(Icons.more_vert),onPressed: (){},),
),
);
return LinearProgressIndicator();
});
},
A:
You can achieve by checking how much elements is in list.
i hope following code help you.
future: _future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
debugPrint("HAs data");
// here check is length of data is 0 then return specific widget which you want to return as i demonstrate with text widget.
if(myList.length==0){
return Text("You have not data");
}
return ListView.builder(
itemExtent: 80,
itemCount: myList.length,
itemBuilder: (BuildContext context, int i) {
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Action Filters in WCF Services
Is there something Like ActionFilterAttribute (From ASP.NET MVC) in WCF Services (Or anything like that). basically what I want to do is to log what is coming and goint to and from my services, and I don't want to write the logging code in every single ServiceContracts. yes the question is very general but you understand the idea what I want to do.
A:
Yes there is it called as MessageInspectors/ParameterInspectors , here you can read about them
http://msdn.microsoft.com/en-us/library/aa717047%28v=vs.110%29.aspx
This is exactly what you are looking for , WCF custom behavior log logging
http://www.codeproject.com/Articles/243352/LoggingBehavior-How-to-Connect-Log-prints-with-the
Only confusing thing is you can have message inspector on WCF service and WCF proxy as well , in your case you need only for service side
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does $i = -\frac{(2\;W({\pi\over2}))}{\pi}$
Let $x = -\frac{(2\;W({\pi\over2}))}{\pi}$, where $W$ denotes the Lambert W-function.
As
$${\log(i^2)\over i} = \pi$$
and $${\log(x^2)\over x}=\pi$$
Does $x = i$?
A:
Hint:assume $x=a+ib$ then $${\log(x^2)\over x}=\pi\to \pi(a+ib)=\log(x^2)=\ln(|x^2|)+i\arg(x^2)=2\mathrm{Ln}(|x|)+i2\arg(x)$$$$\to \begin{cases}
2\ \ln(|\sqrt{a^2+b^2}|)=\pi a \\
\pi b=2\arg(x) \\
\end{cases}$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to select non match
I have four columns of contact namely contact1, contact2, contact3, contact4.
How to write sql to get unique contacts from 4 contacts?
contact1 contact2 contact3 contact4
8888498756 8888498756 8888498756 8888498756
These are four same contacts how to get unique only in sql.
select ca.propno, ca.contact1, ca.contact2, ca.mobile1, ca.mobile2
from BIUSR.tbl_trn_customer_address ca
where ca.contact1 not in (ca.contact2, ca.mobile1, ca.mobile2)
A:
The DISTINCT and UNION might give you what you need.
SELECT DISTINCT propno, contact
FROM (
select ca.propno, ca.contact1 contact
from BIUSR.tbl_trn_customer_address ca
UNION
select ca.propno, ca.contact2 contact
from BIUSR.tbl_trn_customer_address ca
UNION
select ca.propno, ca.mobile1 contact
from BIUSR.tbl_trn_customer_address ca
UNION
select ca.propno, ca.mobile2 contact
from BIUSR.tbl_trn_customer_address ca) contacts
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Putting a texfield inside a table using Handlebars
I am new at using Handlebars, and I have simple question. I am trying to create table that contains a title and a text field next to it. When I try to place the textfields in the table, the textfields is placed on top of the table instead.
This is the code that I am using:
<!DOCTYPE html>
<html>
<head>
<title>Handlebars.js example</title>
</head>
<body>
<div id="placeholder">This will get replaced by handlebars.js</div>
<script type="text/javascript" src="handlebars-v1.3.0.js"></script>
<script id="myTemplate" type="text/x-handlebars-template">
<table>
{{#each names}}
<tr><th>{{name}}</th><input type="text"></tr>
{{/each}}
</table>
</script>
<script type="text/javascript">
var source = document.getElementById("myTemplate").innerHTML;
var template = Handlebars.compile(source);
var data = {
names: [
{ name: "foo",id:'id'},
{ name: "bar",id:'id' },
{ name: "baz",id:'id' }
]};
document.getElementById("placeholder").innerHTML = template(data);
</script>
</body>
</html>
What I am doing wrong?
A:
Your table structure is bad. You're missing a tbody and your input is in a row, but not in a th or td.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I access DB from django template?
Suppose I have a model Photo with an ImageField.
I tried to iterate all photo objects in a template by {% for photo in Photo.objects.all %}.
Nothing comes up.
Is this impossible?
A:
The usual way this is done is with a view that looks something like:
def photo_view(request):
return render_to_response('app_name/photos.html', {
'photos': Photo.objects.all()
})
And then the template (in app_name/templates/app_name/photos.html in this example) has something like:
{% for photo in photos %}
If you really want to do {% for photo in Photo.objects.all %}, then your view code must pass Photo via the context:
def photo_view(request):
return render_to_response('app_name/photos.html', {
'Photo': Photo
})
Bear in mind that this is not really any better of a way to do it, as template syntax is a lot more restrictive than Python. For example, there is no way to do {% for photo in Photo.objects.filter(...) %} in the template; the filtering needs to happen in the view.
A:
You might be thinking about it the wrong way.
The HTTP request gets routed to a view.
The view does any business logic (which may involve accessing the DB via ORM), and then passes any required data/objects as a context dictionary to the templating system.
The templating system only sees what it has been passed from the view. If the object is a lazily-evaluated ORM DB iterator, then sure, it can access DB. But the view must pass that object into the template's context.
Try {{Photo}} in your template to make sure it is actually being passed an object named "Photo" by the corresponding view. You may need to inspect source of the generated html (in case due to its repr it does something weird with angle brackets and doesn't display properly in your browser.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do I need to restart IIS when I change site.master
Recently we moved our server from testing to production.
We had an issue with caching some referenced scripts so we needed to edit site.master and put some artificial query parameters on our referenced scripts.
From what I thought you wouldn't need to restart IIS simply modifying a .master page, but the other day I tried uploading a handful .master pages because we eliminated some code on them, and the site went down until we restarted IIS.
Any insight to the way IIS and MASTER pages work would be stellar.
Thank You for your help.
A:
Generally speaking you wouldn't necessarily need to restart your website for a change in your master page. However, if you modify the code-behind you need to compile the site, because Sitefinity is a Web Application Project, not a Web Site Project. This means the full site is compiled to a DLL, so any changes in the code require a new compile to be run and pushed to your site.
In addition, Sitefinity makes use of caching to improve performance, so you might need to restart the site to clear the cache for any changes to things like master pages or user control (ascx) files as well.
I hope this is helpful!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Which proxy to use in sencha touch 2 when i have restful api
I am trying to make a sencha touch 2 mobile app. I have a restful api in server and i want to consume that in my mobile app. Which sencha proxy should i use (rest, ajax, jsonp)? Rest and ajax has issue with cross-site domain issue, so jsonp can be the solution. But how can i send jsonp request to rest api if i have parameters?
A:
You can use REST proxy if your services truly follows REST standards because that way proxy can provide you out-of-the-box functionality to operate on models.
Regarding cross-domain issues, please note that the way app behaves in desktop browser is different from its behaviour when it runs in phone so you are not forced to use JSONP if you don't want, AJAX can also work for you. Its good if you can use JSONP but please keep in mind its limitations of having no support for HTTP headers and other useful methods like POST, PUT & DELETE.
Please go through this for more information : How to use json proxy to access remote services during development
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change color of Triangle figure using drawRect on Swift
I have made triangle view, called UpTriangleView. It is used in order to show vote. When they are tapped, I want to change their color. I wanna UIColor.grayColor().setStroke() from instance, however I have no idea how to do it. Please tell me how to do it, if you know. Thank you for your kindeness.
class UpTriangleView: UIView {
override func drawRect(rect: CGRect) {
self.backgroundColor = UIColor.clearColor()
// Get Height and Width
let layerHeight = self.layer.frame.height
let layerWidth = self.layer.frame.width
// Create Path
let line = UIBezierPath()
// Draw Points
line.moveToPoint(CGPointMake(0, layerHeight))
line.addLineToPoint(CGPointMake(layerWidth, layerHeight))
line.addLineToPoint(CGPointMake(layerWidth/2, 0))
line.addLineToPoint(CGPointMake(0, layerHeight))
line.closePath()
// Apply Color
UIColor.grayColor().setStroke()
UIColor.grayColor().setFill()
line.lineWidth = 3.0
line.fill()
line.stroke()
// Mask to Path
let shapeLayer = CAShapeLayer()
shapeLayer.path = line.CGPath
self.layer.mask = shapeLayer
}
}
class QATableViewCell : UITableViewCell{
@IBOutlet weak var upTriangleView: UpTriangleView!
}
A:
Add a property to your UpTriangleView that is the color you want to draw it. Implement didSet and call setNeedsDisplay() if the color is set:
class UpTriangleView: UIView {
var color = UIColor.gray {
didSet {
self.setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
self.backgroundColor = .clear
// Get Height and Width
let layerHeight = self.layer.bounds.height
let layerWidth = self.layer.bounds.width
// Create Path
let line = UIBezierPath()
// Draw Points
line.move(to: CGPoint(x: 0, y: layerHeight))
line.addLine(to: CGPoint(x: layerWidth, y: layerHeight))
line.addLine(to: CGPoint(x: layerWidth/2, y: 0))
line.addLine(to: CGPoint(x: 0, y: layerHeight))
line.close()
// Apply Color
color.setStroke()
color.setFill()
line.lineWidth = 3.0
line.fill()
line.stroke()
// Mask to Path
let shapeLayer = CAShapeLayer()
shapeLayer.path = line.cgPath
self.layer.mask = shapeLayer
}
}
Now, demo it in a Playground (see picture below for results):
let utv = UpTriangleView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
utv.color = .yellow // now triangle is yellow
utv.color = .red // now triangle is red
setNeedsDisplay will tell iOS your view needs redrawing, and drawRect will be called again using the newly set color.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using DirectoryIterator to loop through a D: drive directory
I am trying to loop through this directory:
$path = "D:\\import\\statsummary\\";
Here is my code:
$path = "D:\\import\\statsummary\\";
//$path = "C:\\test";
//function load_csv($path, $filename){
if(is_null($filename)){
header('Content-type: text/plain');
$output = array();
foreach (new DirectoryIterator($path) as $file){
if($file->isFile()){
$output[] = $i++ . " " . $file->getFileName() . "\n";
$output[] = file($file->getPathName());
$output[] = "\n------------\n";
}
}
}
echo implode('', $output);
When I run this script, I get this error:
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(D:\import\statsummary\,D:\import\statsummary\): Access is denied. (code: 5)' in C:\inetpub\wwwroot\include\file_importer.php:10
Stack trace:
#0 C:\inetpub\wwwroot\include\file_importer.php(10): DirectoryIterator->__construct('D:\import\...')
#1 {main}
thrown in C:\inetpub\wwwroot\include\file_importer.php on line 10
But when I change it to a test directory on my C:\ drive, it runs just fine. I've even created a username to run PHP as directed in this post:
php - Unable to connect to network share - Stack Overflow
A:
Based on the DirectoryIterator class, something like this should work:
<?php
$path = "D:/import/statsummary";
$output=array();
$iterator = new DirectoryIterator(path);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
$filename= $fileinfo->getFilename();
$path=$fileinfo->getPathname();
$output[][$filename]=$path;
}
}
print_r($output);
?>
Update
Since you're getting access denied, you'll need to run the command prompt (CMD) window as Administrator more than likely. If this is on a link (lnk) you can change the permissions in the link settings.
For instance if you right-click on the shortcut for cmd as select properties, you would go to shortcut>advanced>Run as Administrator.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iPhone Uploading unique images to a server running PHP / MYSQL
I'm working on an iPhone app that will upload images to a web server. I was wondering if anyone had any tips on how to generate unique names for each image file that gets uploaded.
I'm sure there are a million ways to do this, but if anyone has any suggestions I'd really appreciate it! Thanks.
A:
you could create a GUID and save the image as that name ..
Thanks
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is in Typescript possible to define 'object of arrays of type string? (right position of type checking?)
I know in typescript an object can be typed either by ClassName (ES6 class) or by 'any'.
I also know you can define an array of string (string[]) and even an array of arrays of string (string[][]).
I need to express the type of an object whose properties are only arrays of type string.
e.g.
export var MY_VAR: any = {
<string[]> p1: [...]
}
I tried with something like any following object_name: but not luck.
I also tried any following object_name and before each object's array.
In either case I have syntax errors (see example above)
EDIT apparently
export var MY_VAR: any = {
<string[]> p1: [...]
}
works instead. however I don't understand what the difference is
A:
It's not very clear what you're asking for, but if I managed to get you right then:
interface MyType {
[key: string]: string[];
}
Or inline:
let myArrays: { [key: string]: string[] } = {};
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to make half round rect in BlackBerry application
Below email, user will enter email n below password a user will enter password, i m able to make square but upper square should be curve in upper side and lower square in lower side.
A:
Something I made that I think will do what you want. You just have to add them to this Manager. Note that I don't think I have it compensating for things like margin or padding, so you can either figure that in with the paint() method, or just enclose it in another Manager that has the proper padding/margin:
public class GroupFieldManager extends VerticalFieldManager {
private int _rounding;
private int _bgColor;
private int _borderColor;
private boolean _divider;
private int _dividerColor;
public GroupFieldManager(boolean divider, long style) {
super(style);
_rounding = 20;
_bgColor = 0xFFFFFF;
_borderColor = 0xAAAAAA;
_divider = divider;
_dividerColor = 0xAAAAAA;
}
public GroupFieldManager(boolean divider) {
this(divider, 0);
}
public GroupFieldManager() {
this(false, 0);
}
/**
* Sets whether or not to draw a divider
* @param on
*/
public void setDivider(boolean on) {
_divider = on;
}
/**
* Sets the color for the divider (also turns divider on)
* @param color
*/
public void setDividerColor(int color){
_dividerColor = color;
_divider = true;
}
/**
* Sets the background color for the grouping
* @param color
*/
public void setBackgroundColor(int color) {
_bgColor = color;
}
/**
* Sets the border color for the grouping
* @param color
*/
public void setBorderColor(int color) {
_borderColor = color;
}
/**
* Sets the amount of rounding for the border
* @param rounding
*/
public void setRounding(int rounding) {
_rounding = rounding;
}
protected void paint(Graphics graphics) {
int oldColor = graphics.getColor();
//draw the background
graphics.setColor(_bgColor);
graphics.fillRoundRect(0, 0, getWidth(), getHeight(), _rounding, _rounding);
//draw the border
graphics.setColor(_borderColor);
graphics.drawRoundRect(0, 0, getWidth(), getHeight(), _rounding, _rounding);
//draw dividers
if(_divider) {
graphics.setColor(_dividerColor);
int y = 0;
//go through each field, figure it's height, and draw a line under it
for(int i=0;i<getFieldCount();i++) {
if(i != getFieldCount() - 1) {
int height = getField(i).getHeight();
y += height;
graphics.drawLine(0, y, getWidth(), y);
}
}
}
graphics.setColor(oldColor);
super.paint(graphics);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
rename output files with iteration number and input with gnu parallel
I have a list of files (data1.txt, ... ,data6.txt) and I want to run the same commands on them 3 times as example. I am using gnu parallel
I want as output files: 1data1.txt, 2data1.txt, 3data1.txt, ... , 2data6.txt, 3data6.txt.
I tried:
for i in $(seq 3); do parallel -j 8 'myCommand data{}.txt > results/out/{$i}data{}.txt' ::: 1 2 3 4 5 6; done
but my output files are : {}data1.txt, ...., {}data6.txt
I've tried different possibilities but I don't have the expected results
A:
Use GNU Parallel's feature of making combinations:
parallel -j 8 myCommand data{2}.txt '>' results/out/{1}data{2}.txt' ::: 1 2 3 ::: 1 2 3 4 5 6
If your CPU has 8 threads you can leave out -j8. This is a good idea, if you later are going to run it on a bigger system.
You can also use --results (requires version >20170222):
parallel --results results/out/{1}data{2}.txt myCommand data{2}.txt ::: 1 2 3 ::: 1 2 3 4 5 6 >/dev/null
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python prefers unassigned local function over built-in function
The following Python script works well with Python 2.3 and Python 2.4 (which don't have a built-in definition of all():
#! /usr/bin/env python
# vim: set fileencoding=utf-8
# (c) Uwe Kleine-König
# GPLv2
import locale
import sys
f = file(sys.argv[1])
data = f.read()
def len_utf8_char(data):
if not 'all' in dir(__builtins__):
def all(seq):
for i in seq:
if not i:
return False
return True
def check_cont(num):
if all(map(lambda c: ord(c) >= 0x80 and ord(c) <= 0xbf, data[1:num])):
return num
else:
return -1
if ord(data[0]) < 128:
# ASCII char
return 1
elif ord(data[0]) & 0xe0 == 0xc0:
return check_cont(2)
elif ord(data[0]) & 0xf0 == 0xe0:
return check_cont(3)
elif ord(data[0]) & 0xf8 == 0xf0:
return check_cont(4)
elif ord(data[0]) & 0xfc == 0xf8:
return check_cont(5)
elif ord(data[0]) & 0xfe == 0xfc:
return check_cont(6)
i = 0
maxl = 0
while i < len(data):
l = len_utf8_char(data[i:])
if l < 0:
prefenc = locale.getpreferredencoding()
if prefenc not in ('UTF-8', 'ANSI_X3.4-1968'):
print prefenc
else:
print 'ISO-8859-1'
sys.exit(0)
if maxl < l:
maxl = l
i += l
if maxl > 1:
print 'UTF-8'
else:
print 'ANSI_X3.4-1968'
Now with Python 2.5 and later this fails as follows:
$ python2.5 guess-charmap guess-charmap
Traceback (most recent call last):
File "guess-charmap", line 43, in <module>
l = len_utf8_char(data[i:])
File "guess-charmap", line 30, in len_utf8_char
return check_cont(2)
File "guess-charmap", line 21, in check_cont
if all(map(lambda c: ord(c) >= 0x80 and ord(c) <= 0xbf, data[1:num])):
NameError: free variable 'all' referenced before assignment in enclosing scope
Removing the compatibility definition of all fixes the problem for Python 2.5+.
I wonder why Python doesn't pick the builtin all() in this case. Can somebody explain?
A:
When Python parses a function body, it looks for variable names that are used in assignments. All such variables are assumed to be local, unless the global variable declaration is used.
The def all assigns a value to the variable name all. Despite the assignment being inside an if-block, all is regarded as a local variable in all cases (whether or not the if-block is later executed).
When the if-block is not executed, all becomes an unbound local variable, thus raising a NameError.
If you move the if not 'all' ... block outside the def len_utf8_char, then
you will avoid this problem.
A:
For the same reason it happens with variables; the compiler has marked it as a local for the function, and so expects it to be a local. If you want to solve this then just do all = __builtins__.all in the else clause.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I can't get out of the research phase out of fear of missing out
One of the aspects I love about fiction writing is doing research. When I settle on an idea, I tend to go look for similar historical themes, stories that I can weave into my novel. I get excited about finding an inspiration that introduces a new character or overall enriches my story plot. The problem is that I can't get out of the research stage.
Every time I try to focus solely on writing my novel, I find myself besieged with anxiety. What if I missed something that would've made my novel better, richer?
For example, right now, I'm very comfortable with the plot of the novel I'm working on. I arrived at it after reading multiple primary texts covering an important period in American history. As I write, I can't shake off the idea that if I expand my research and continue reading from different sources, I might find more intriguing, complex narratives that could transform my novels.
Is this healthy? How should I treat the research part? And how can I overcome my anxiety?
A:
Do your research, but only after the first draft
The first draft is usually written to be butchered anyway. A big problem in writing is being too precious with your first draft, and not changing major problems because you don't want to redo the work. Kill two birds with one stone, and do the research specifically to poke holes in your first draft.
This stops you from never getting anything on the page because now you're writing without the constraints of research, and afterwards it helps you to deconstruct the first draft in a structural way by doing research. It also makes the research more targeted, and more efficient. You're not just researching the domain of your story in general, you're checking whether specific aspects of your story are realistic, and working around that.
Finally, since you're already rewriting to fix the problems that the research uncovers, you might as well fix any larger problems with the story structure.
Some research may be necessary before you put pen to paper, but restrict yourself here to research that inspires you. Look for little ideas, facts and characters that help you put the story together. Anything that worries you, put it aside until after the first draft has been written.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Calling GetStringTypeW from non-unicode Delphi (7)
I'm attempting to call GetStringTypeW from a non-unicode delphi application and, no matter what I do, I get ERROR_INVALID_FLAGS back. I couldn't find any code sample of that function in use either.
I also had to redifine the function header because the ones provided in windows.pas incorrectly identifies the 3rd parameter as a boolean (it's an INT)
here is my definition for the function:
function GetStringTypeW(dwInfoType: DWORD; lpSrcStr: PWideChar; cchSrc: Integer; lpCharType: Pointer): BOOL;
(For some reason, that function isn't defined as stdcall. Trying it to define it as stdcall will result in an access violation.)
And my call:
var
aCharType: Array of WORD;
APassword: WideString
begin
{..}
SetLength(aCharType, Length(APassword));
if not GetStringTypeW(CT_CTYPE1, PWideChar(APassword[1]), Length(APassword), @aCharType[0]) then
RaiseLastOSError;
{..}
The error I get is
System Error. Code: 1004.
Invalid flags.
I've verified that CT_CTYPE1 is equal to 1.
Does anyone know what could be wrong or have a code sample for using this function ?
A:
The declaration in Windows.pas is indeed wrong, but your correction is wrong, too. You've fixed the parameter types, but you need to fix the calling convention. It should be stdcall:
function GetStringTypeW(
dwInfoType: DWORD;
const lpSrcStr: PWideChar;
cchSrc: Integer;
lpCharType: PWordArray
): BOOL; stdacll;
Without the calling-convention fix, Delphi puts most of the parameters in registers, but the OS expects to find them on the stack. The stack doesn't contain the right values at the right places, to it fails. A bad calling convention can also lead to access violations because the stack is left in an inconsistent state, but since you immediately throw your own exception anyway, that might conceal the stack problems.
When you use stdcall, you get an access violation because you're passing a character and claiming it's a pointer. The OS attempts to dereference the "pointer," but since the character value doesn't represent a valid address, it fails. Type-cast the whole string, not just one character, when you call the function:
GetStringTypeW(CT_CTYPE1, PWideChar(APassword), Length(APassword), PWordArray(aCharType))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find index of string in list
I have two lists with the same number of elements, all of them strings. These strings are the same set but in a different order in each list with no duplicates.
list_a = ['s1', 's2', 's3', 's4', 's5', ...]
list_b = ['s8', 's5', 's1', 's9', 's3', ...]
I need to go through each element in list_a and find the index in list_b that contains that same element. I can do this with two nested for loops but there has to be a better/more efficient way:
b_indexes = []
for elem_a in list_a:
for indx_b, elem_b in enumerate(list_b):
if elem_b == elem_a:
b_indexes.append(indx_b)
break
A:
If there are no duplicates, you can just use list.index():
list_a = ['s1', 's2', 's3', 's4', 's5']
list_b = ['s8', 's5', 's1', 's9', 's3']
print [list_b.index(i) for i in list_a]
You only need to use one for loop, because you've said that the strings in list_a also appear in list_b, so there's no need to go if elem_b == elem_a: and iterate through the second list.
A:
In functional style:
map(list_b.index, list_a)
A list will be produced containing the index in list_b of each element in list_a.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to display image in imageview after captured using surfaceview class in android
i have code that capture the image using custom camera API, the problem is its not coming back to preview mode, main thing is i want display the captured image in imageview"
this is my code:
CameraPreview.java
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusMoveCallback;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
@SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
Camera.Parameters prams = mCamera.getParameters();
prams.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
mCamera.setParameters(prams);
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
mCamera.autoFocus(null);
} catch (IOException e) {
// left blank for now
}
}@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
MainActivity.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getName();
private Camera mCamera;
private CameraPreview mCameraPreview;
private Button captureButton;
private ImageView showImageView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
ImageView showImageView = (ImageView) findViewById(R.id.imageView1);
preview.addView(mCameraPreview);
captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:gravity="center" >
<FrameLayout
android:id="@+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_above="@+id/btns"
android:layout_alignParentTop="true" >
</FrameLayout>
<RelativeLayout
android:id="@+id/btns"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#ccc" >
<Button
android:id="@+id/button_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:background="@drawable/btn_white" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="22dp"
android:src="@drawable/backeff" />
</RelativeLayout>
</RelativeLayout>
A:
Hi Kindly try the below code..
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
private Button captureButton;
private ImageView showImageView;
protected String imageFilePath;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_view);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
showImageView = (ImageView) findViewById(R.id.imageView1);
preview.addView(mCameraPreview);
captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.takePicture(null, null, jpegCallback);
}
});
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
/** The jpeg callback. */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
File miDirs = new File(
Environment.getExternalStorageDirectory() + "/myphotos");
if (!miDirs.exists())
miDirs.mkdirs();
final Calendar c = Calendar.getInstance();
String new_Date = c.get(Calendar.DAY_OF_MONTH) + "-"
+ ((c.get(Calendar.MONTH)) + 1) + "-"
+ c.get(Calendar.YEAR) + " " + c.get(Calendar.HOUR)
+ "-" + c.get(Calendar.MINUTE) + "-"
+ c.get(Calendar.SECOND);
imageFilePath = String.format(
Environment.getExternalStorageDirectory() + "/myphotos"
+ "/%s.jpg", "te1t(" + new_Date + ")");
Uri selectedImage = Uri.parse(imageFilePath);
File file = new File(imageFilePath);
String path = file.getAbsolutePath();
Bitmap bitmap = null;
outStream = new FileOutputStream(file);
outStream.write(data);
outStream.close();
if (path != null) {
if (path.startsWith("content")) {
bitmap = decodeStrem(file, selectedImage,
CameraActivity.this);
} else {
bitmap = decodeFile(file, 10);
}
}
if (bitmap != null) {
showImageView.setImageBitmap(bitmap);
Toast.makeText(CameraActivity.this,
"Picture Captured Successfully:", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(CameraActivity.this,
"Failed to Capture the picture. kindly Try Again:",
Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
};
/**
* Decode strem.
*
* @param fil
* the fil
* @param selectedImage
* the selected image
* @param mContext
* the m context
* @return the bitmap
*/
public static Bitmap decodeStrem(File fil, Uri selectedImage,
Context mContext) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(mContext.getContentResolver()
.openInputStream(selectedImage));
final int THUMBNAIL_SIZE = getThumbSize(bitmap);
bitmap = Bitmap.createScaledBitmap(bitmap, THUMBNAIL_SIZE,
THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos
.toByteArray()));
return bitmap = rotateImage(bitmap, fil.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* Rotate image.
*
* @param bmp
* the bmp
* @param imageUrl
* the image url
* @return the bitmap
*/
public static Bitmap rotateImages(Bitmap bmp, String imageUrl) {
if (bmp != null) {
ExifInterface ei;
int orientation = 0;
try {
ei = new ExifInterface(imageUrl);
orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
} catch (IOException e) {
e.printStackTrace();
}
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_UNDEFINED:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
default:
break;
}
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
bmpHeight, matrix, true);
return resizedBitmap;
} else {
return bmp;
}
}
/**
* Decode file.
*
* @param f
* the f
* @param sampling
* the sampling
* @param check
* the check
* @return the bitmap
*/
public static Bitmap decodeFile(File f, int sampling) {
try {
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inJustDecodeBounds = true;
BitmapFactory.decodeStream(
new FileInputStream(f.getAbsolutePath()), null, o2);
o2.inSampleSize = sampling;
o2.inTempStorage = new byte[48 * 1024];
o2.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeStream(
new FileInputStream(f.getAbsolutePath()), null, o2);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
bitmap = rotateImage(bitmap, f.getAbsolutePath());
return bitmap;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
return null;
}
/**
* Rotate image.
*
* @param bmp
* the bmp
* @param imageUrl
* the image url
* @return the bitmap
*/
public static Bitmap rotateImage(Bitmap bmp, String imageUrl) {
if (bmp != null) {
ExifInterface ei;
int orientation = 0;
try {
ei = new ExifInterface(imageUrl);
orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
} catch (IOException e) {
e.printStackTrace();
}
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_UNDEFINED:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
default:
break;
}
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
bmpHeight, matrix, true);
return resizedBitmap;
} else {
return bmp;
}
}
/**
* Gets the thumb size.
*
* @param bitmap
* the bitmap
* @return the thumb size
*/
public static int getThumbSize(Bitmap bitmap) {
int THUMBNAIL_SIZE = 250;
if (bitmap.getWidth() < 300) {
THUMBNAIL_SIZE = 250;
} else if (bitmap.getWidth() < 600) {
THUMBNAIL_SIZE = 500;
} else if (bitmap.getWidth() < 1000) {
THUMBNAIL_SIZE = 750;
} else if (bitmap.getWidth() < 2000) {
THUMBNAIL_SIZE = 1500;
} else if (bitmap.getWidth() < 4000) {
THUMBNAIL_SIZE = 2000;
} else if (bitmap.getWidth() > 4000) {
THUMBNAIL_SIZE = 2000;
}
return THUMBNAIL_SIZE;
}
}
Let me know the if you have any queries..
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C stack/scope, variable's lifetime after functions ends
void someFunc()
{
int stackInt = 4;
someOtherFunc(&stackInt);
}
Is it the case that stackInt's address space could be reallocated after someFunc ends, making it unsafe to assume that the value passed to someOtherFunc represents the stackInt variable with value 4 that was passed to it? In other words, should I avoid passing stack variables around by address and expecting them to still be alive after the function they were initialised in has ended?
A:
Yes, definitely.
You don't have to avoid passing stack-allocated variables by reference/pointer altogether, though, just storing pointers or references to stack-allocated variables.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create a setter that updates a dom element with the new value?
Is there a way to make a setter that will update a DOM element whenever a property of the object is changed?
A:
I don't believe so. Without creating the setter, then x will be a plain jane property hanging off the object with no way of knowing when it has changed. Why do you want to avoid the setter? It's a pretty clean way to accomplish your goal.
But one small thing to keep in mind, Object.defineProperty, although more verbose, is more supported and "won" over set and get:
a = {};
Object.defineProperty(a, 'x', {
get: function() {
return this._x;
},
set: function(newX) {
this._x = newX;
$("#my_element").html(newX);
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I convert 1D array into 2D matrix on MATLAB?
I want to make heatmap with 1D array(s), this is my plan;
Let assume 4 points of center and each has array,
[center #1, L U] = {0, 1, 2, 5, 10, 7, 4, 2, 1, 0} *L R U D = Left, Right, Up, Down
[center #2, R U] = {0, 1, 1, 4, 12, 7, 5, 3, 2, 1}
[center #3, L D] = {0, 1, 3, 4, 11, 7, 4, 2, 1, 0}
[center #4, R D] = {0, 1, 3, 6, 11, 6, 5, 3, 1, 1}
And when 5th index of heatmap, ([#1]=10, [#2]=12, [#3]=11, [#4]=11) heatmap needs to be like this image.
Heatmap image
Also can predict heatmap is all blue when 1st index ([#1]=0, [#2]=0, [#3]=0, [#4]=0) and only right side has color that almost blue when last index. ([#1]=0, [#2]=1, [#3]=0, [#4]=1)
How can I get 2D matrix from 1D arrays on Matlab? Decreasing values from center can be linear or whatever.
A:
Based on your example you wish to produce always 4 n * n matrices, where the center point of each matrix gets the value in your arrays and all its 4-neighbors get a decreasing value until zero. Did I get it right?
Does this create one of the four matrices you wished to create? If so, just modify the parameters and make four matrices and draw them together
% your matrix size
size = 15
center = (size + 1) / 2
center_value = 5
mat_a = zeros(size,size);
mat_a(center,center) = center_value;
%loop all values until zero
for ii=1:center_value -1
current_value = center_value - ii;
update_mat = mat_a;
% loop over matrix, check if 4-neighbors non-zero
for x =1:size
for y =1:size
if ( mat_a(y,x) == 0 )
has_non_zero_neighbor = false;
% case 1
if ( x < size)
if (mat_a(y,x+1) > 0)
has_non_zero_neighbor = true;
endif
endif
% case 2
if ( y < size)
if (mat_a(y+1,x) > 0)
has_non_zero_neighbor = true;
endif
endif
%case 3
if ( x > 1)
if (mat_a(y,x-1) > 0)
has_non_zero_neighbor = true;
endif
endif
% case 4
if ( y > 1)
if (mat_a(y-1,x) > 0)
has_non_zero_neighbor = true;
endif
endif
%if non-zeros, update matrix item value to current value
if (has_non_zero_neighbor == true)
update_mat(y,x) = current_value;
endif
endif
end
end
mat_a = update_mat;
end
figure(1)
imshow(mat_a./center_value)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error in FROM clause: near '{'. Unable to parse query text
I'm trying to execute the following query for a Dataset:
SELECT
S.CUSIP, S.SecName,
ISNULL(RA.FinInstCode, '') AS RemarketingAgent,
S.IssueDate, S.MaturityDate, F2.FinInstName AS Trustee,
CASE WHEN SC1.ExpirationDate IS NULL
THEN '' ELSE ISNULL(F1.FinInstCode, '') END
AS CreditProvider,
CASE WHEN SC1.ExpirationDate IS NULL
THEN '' ELSE ISNULL(C1.CreditEnhancementCode, '') END
AS CreditType,
SC1.ExpirationDate AS CreditExpirationDate,
SC1.RefNum AS RefNumber
FROM
dbo.SecurityCreditEnhancementProvider SC1,
dbo.FinInst F1,
dbo.LUCreditEnhancement C1,
{ oj { oj dbo.Security S
LEFT OUTER JOIN
dbo.FinInst F2 ON S.TrusteeID = F2.FinInstID }
LEFT OUTER JOIN
dbo.FinInst RA ON S.RemarketingAgentID = RA.FinInstID }
WHERE
S.SecID = SC1.SecID
AND
SC1.CreditProviderID = F1.FinInstID
AND
SC1.CreditEnhancementID = C1.CreditEnhancementID
AND
C1.CreditEnhancementCode = 'LOC' OR
C1.CreditEnhancementCode = 'LIQUIDITY'
AND
(S.ActiveFlag = 'A')
AND
(S.SecTypeID NOT IN (4, 7))
ORDER BY CreditExpirationDate
When trying to run the query the error I get is " Error in FROM clause near:
'{' . Unable to parse query. "
Any help to fix this issue would be most appreciated.
Thanks,
EDIT 1: This is what is looks like after query designer changes the code:
FROM { oj { oj { oj { oj { oj dbo.SecurityCreditEnhancementProvider SC1 LEFT OUTER JOIN
dbo.FinInst F1 ON SC1.CreditProviderID = F1.FinInstID } LEFT OUTER JOIN
dbo.LUCreditEnhancement C1 ON SC1.CreditEnhancementID = C1.CreditEnhancementID } LEFT OUTER JOIN
dbo.Security S ON S.SecID = SC1.SecID } LEFT OUTER JOIN
dbo.FinInst F2 ON S.TrusteeID = F2.FinInstID } LEFT OUTER JOIN
dbo.FinInst RA ON S.RemarketingAgentID = RA.FinInstID }
Thanks all for there help.
A:
Formatting code in a case like this might be helpful. you had incorrect syntax in your FROM clause. I also updated the query to use JOIN Syntax on all tables instead of using commas between your tables.
SELECT S.CUSIP
, S.SecName
, ISNULL(RA.FinInstCode, '') AS RemarketingAgent
, S.IssueDate
, S.MaturityDate
, F2.FinInstName AS Trustee
, CASE WHEN SC1.ExpirationDate IS NULL THEN '' ELSE ISNULL(F1.FinInstCode, '') END AS CreditProvider
, CASE WHEN SC1.ExpirationDate IS NULL THEN '' ELSE ISNULL(C1.CreditEnhancementCode, '') END AS CreditType
, SC1.ExpirationDate AS CreditExpirationDate
, SC1.RefNum AS RefNumber
FROM dbo.SecurityCreditEnhancementProvider SC1
LEFT JOIN dbo.FinInst F1
ON SC1.CreditProviderID = F1.FinInstID
LEFT JOIN dbo.LUCreditEnhancement C1
ON SC1.CreditEnhancementID = C1.CreditEnhancementID
LEFT JOIN dbo.Security S
ON S.SecID = SC1.SecID
LEFT OUTER JOIN dbo.FinInst F2
ON S.TrusteeID = F2.FinInstID
LEFT OUTER JOIN dbo.FinInst RA
ON S.RemarketingAgentID = RA.FinInstID
WHERE (C1.CreditEnhancementCode = 'LOC' OR C1.CreditEnhancementCode = 'LIQUIDITY' )
AND (S.ActiveFlag = 'A')
AND (S.SecTypeID NOT IN (4, 7))
ORDER BY CreditExpirationDate
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to fix undefined method error in rails app using has_many?
I get an error when I try to visit the below url in my rails app.
http://localhost:3000/origtexts/1/reviews/new
routes.rb
resources :origtexts do
resources :reviews
end
It passes the param of the review (1) correctly but I the error I get is undefined method `review' for the line in ReviewsController#new.
reviews_controller.rb
class ReviewsController < ApplicationController
before_filter :find_origtext
before_filter :find_review, :only => [:show, :edit, :update, :destroy]
def new
@review = @origtext.review.build
end
def show
end
def create
@review = @origtext.reviews.build(params[:review])
if @review.save
flash[:notice] = 'Review has been created'
redirect_to [@origtext, @review]
else
flash[:alert] = 'Review has not been created'
render :action => 'new'
end
end
private
def find_origtext
@origtext = Origtext.find(params[:origtext_id])
end
def find_review
@review = @origtext.reviews.find(params[:id])
end
end
Any advice on how to fix this?
A:
Change review to reviews in this line
@review = @origtext.review.build
To
@review = @origtext.reviews.build
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Use regex to match Blogger (blogspot) permalinks
I have (hacked) this regex this far which matches any words between hyphens and separates them, leaving out articles that are 1 character. The reason I need these words separate is that Blogger manages to stop the url at 39 characters AND doesn't break any words. This works so far:
^((([a-zA-Z0-9]{2,39})-)+)(?:([a-zA-Z0-9]{1})-)((([a-zA-Z0-9]{2,39})-)+){2,39}$
Tested against /wishing-you-a-very-merry-christmas-and-a-happy-new-year.html
Matches: wishing-you-a-very-merry-christmas-and-
Replacement String: $1 (not working!!) it results in:
How do I get the 1-letter articles to NOT print in the results regex? And how do I test for and remove the last - in my results?
A:
You cannot build this with one regex.
The part with max 39 characters in length and not ending with - is no problem.
^\/?([\w-]{3,39})(?<!-).*
See it on Regexr
(?<!-) is a lookbehind assertion that ensures that the string is not ending with a hyphen.
But you cannot remove at the same time substrings with the length of 1.
On its own this is also no problem
(?<=[/-]|^)[^-]-|-[^-](?=[-./]|$)
See it here on Regexr
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Validating Checkbox not working in Rails 3.2
It worked in the previous rails version. I can't find a solution for this.
#Model
validate :branches_cannot_be_empty
def branches_cannot_be_empty
errors.add(:branches, "can't be empty") if branches.blank?
end
#View HAML
.field.checkbox
= f.label(:branch, "Assign to Branch")
-if @march.branch_ids.include? ( branch.id )
=check_box_tag "branches[#{branch.id}]", 1, true
-else
=check_box_tag "branches[#{branch.id}]"
= branch.name
A:
You cannot validate a checkbox like this - in a rails form (as well as most other frameworks, eg .net web forms) always send a value back for a checkbox.
When you render a checkbox, a hidden field is also rendered with the value of false. So if the checkbox is checked, you get a value of true but if a checkbox is not checked, you get the value of false not blank.
Read the gotcha section of the rails documentation here --> http://apidock.com/rails/ActionView/Helpers/FormHelper/check_box
|
{
"pile_set_name": "StackExchange"
}
|
Q:
android application has stopped unexpectedly NullPointerException
Im having this "Android application has stopped unexpectedly, please try again" (everytime i run the play class) and it turned out that there is an issue with the NullPointerException but im not quite sure how to fix it...
the java code
public class play extends Activity implements OnClickListener {
private Question currentQuestion;
private int currentQuestionIndex;
private ArrayList<Button> questionButton;
private TextView questionstextview;
private TextView questionnumber;
private TextView playerfeedback;
public TextView displayscore;
public int score;
private List<Question> QuestionList;
private int answerchoice;
public static int totalanswer;
public static int correctanswer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
Log.i("playclass", "this is play class running");
questionButton = new ArrayList<Button>();
questionButton.add((Button) findViewById (R.id.answerbutton1));
questionButton.add((Button) findViewById (R.id.answerbutton2));
questionButton.add((Button) findViewById (R.id.answerbutton3));
questionButton.add((Button) findViewById (R.id.answerbutton4));
currentQuestion = null;
currentQuestionIndex = 0;
View AnswerButton1 = findViewById(R.id.answerbutton1);
AnswerButton1.setOnClickListener(this);
View AnswerButton2 = findViewById(R.id.answerbutton2);
AnswerButton2.setOnClickListener(this);
View AnswerButton3 = findViewById(R.id.answerbutton3);
AnswerButton3.setOnClickListener(this);
View AnswerButton4 = findViewById(R.id.answerbutton4);
AnswerButton4.setOnClickListener(this);
Log.i("playclass", "aftersetlistener");
QuestionList = new ArrayList<Question>();
ArrayList <String> answer = new ArrayList<String>();
answer.add("8");
answer.add("9");
answer.add("3");
answer.add("1");
QuestionList.add(new Question("what is 4+4", answer, 0));
answer.add("17");
answer.add("20");
answer.add("15");
answer.add("14");
QuestionList.add(new Question("what is 7+8?", answer, 3));
answer.add("20");
answer.add("30");
answer.add("19");
answer.add("34");
QuestionList.add(new Question("what is 10+10?", answer, 0));
answer.add("12");
answer.add("11");
answer.add("13");
answer.add("14");
QuestionList.add(new Question("what is 6+6?", answer, 0));
answer.add("6");
answer.add("5");
answer.add("4");
answer.add("7");
QuestionList.add(new Question("what is 4+3?", answer, 3));
answer.add("7");
answer.add("9");
answer.add("10");
answer.add("11");
QuestionList.add(new Question("what is 3+7?", answer, 2));
questionstextview = (TextView) findViewById (R.id.questionstextview);
questionnumber = (TextView) findViewById (R.id.questionnumber);
displayscore = (TextView) findViewById (R.id.displayscore);
StartTrivia();
}
private void ButtonPress (Button answerButton){
final MediaPlayer soundfx = MediaPlayer.create(getApplicationContext(), R.raw.click);
soundfx.start();
for (int i=0; i< questionButton.size(); i++)
if (questionButton.get(i) ==answerButton)
if (i==currentQuestion.getAnswerIndex()){
score=+5;
totalanswer++;
correctanswer++;
displayscore.setText(Integer.toString(score));
Toast.makeText(getApplicationContext(), "Correct!!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Incorrect!!", Toast.LENGTH_SHORT).show();
}
currentQuestionIndex++;
if (currentQuestionIndex < QuestionList.size()){
StartTrivia();
}
else{
Intent result = new Intent (this, finalscreen.class);
startActivity(result);
}
}
public void StartTrivia(){
Log.i("playclass", "running StartTrivia()");
currentQuestion = QuestionList.get(currentQuestionIndex);
Log.i("playclass", "after get current question");
questionstextview.setText(currentQuestion.getquestion());
Log.i("playclass", "after set current question");
questionnumber.setText(Integer.toString(currentQuestionIndex+1));
Log.i("playclass", "after convert int to string for question number");
for (int i = 0; i < questionButton.size(); i++)
{
questionButton.get(i).setText(currentQuestion.getanswer().get(i));
Log.i("playclass", "after get question button");
}
}
public play() {
}
@Override
public void onClick(View v) {
}
}
The LogCat
I/mainactivity(372): this is Main Activity running<br>
I/playclass(372): this is play class running<br>
I/playclass(372): aftersetlistener<br>
I/playclass(372): running StartTrivia()<br>
I/playclass(372): after get current question<br>
I/playclass(372): after set current question<br>
I/playclass(372): after convert int to string for question number<br>
D/AndroidRuntime(372): Shutting down VM<br><br><br>
W/dalvikvm(372): threadid=1: thread exiting with uncaught exception (group=0x40015560)<br>
E/AndroidRuntime(372): FATAL EXCEPTION: main<br>
E/AndroidRuntime(372): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quizgame/com.example.quizgame.play}: java.lang.NullPointerException
E/AndroidRuntime(372): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
E/AndroidRuntime(372): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
E/AndroidRuntime(372): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
E/AndroidRuntime(372): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
E/AndroidRuntime(372): at android.os.Handler.dispatchMessage(Handler.java:99)<br>
E/AndroidRuntime(372): at android.os.Looper.loop(Looper.java:123)<br>
E/AndroidRuntime(372): at android.app.ActivityThread.main(ActivityThread.java:3683)<br>
E/AndroidRuntime(372): at java.lang.reflect.Method.invokeNative(Native Method)<br>
E/AndroidRuntime(372): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(372): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)<br><br>
E/AndroidRuntime(372): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)<br>
E/AndroidRuntime(372): at dalvik.system.NativeStart.main(Native Method)<br>
E/AndroidRuntime(372): Caused by: java.lang.NullPointerException<br>
E/AndroidRuntime(372): at com.example.quizgame.play.StartTrivia(play.java:157)<br>
E/AndroidRuntime(372): at com.example.quizgame.play.onCreate(play.java:98)<br>
E/AndroidRuntime(372): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)<br>
E/AndroidRuntime(372): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)<br>
E/AndroidRuntime(372): ... 11 more
A:
Looks like you have an index problem - is it really the case that this line:
questionButton.get(i).setText(currentQuestion.getanswer().get(i));
should have the index of the "questionButton" be the same as the index of "getanswer()" for the current question? What is the size of the answer array? It's probably getanswer() does not have as many elements as questionButton
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Magento fulltext search error
When I change the Magento search mode to fulltext or combined, I get the following error message:
There has been an error processing your request
SQL ERROR: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound
SQL QUERY:SELECT 6406 AS `query_id`, `s`.`product_id`, MATCH (s.data_index) AGAINST (:query IN BOOLEAN MODE) AS `relevance` FROM `catalogsearch_fulltext` AS `s`
INNER JOIN `catalog_product_entity` AS `e` ON e.entity_id = s.product_id WHERE (s.store_id = 1) AND (MATCH (s.data_index) AGAINST (:query IN BOOLEAN MODE))
Trace:
#0 /home/omit/public_html/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#1 /home/omit/public_html/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#2 /home/omit/public_html/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#3 /home/omit/public_html/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT 6406 AS ...', Array)
#4 /home/omit/public_html/lib/Varien/Db/Adapter/Pdo/Mysql.php(428): Zend_Db_Adapter_Pdo_Abstract->query('SELECT 6406 AS ...', Array)
#5 /home/omit/public_html/app/code/local/Mage/CatalogSearch/Model/Resource/Fulltext.php(385): Varien_Db_Adapter_Pdo_Mysql->query(Object(Varien_Db_Select))
#6 /home/omit/public_html/app/code/core/Mage/CatalogSearch/Model/Fulltext.php(136): Mage_CatalogSearch_Model_Resource_Fulltext->prepareResult(Object(Mage_CatalogSearch_Model_Fulltext), 'plastic', Object(Mage_CatalogSearch_Model_Query))
#7 /home/omit/public_html/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext/Collection.php(55): Mage_CatalogSearch_Model_Fulltext->prepareResult()
#8 /home/omit/public_html/app/code/local/Sns/Ajaxfilter/Model/Catalogsearch/Layer.php(77): Mage_CatalogSearch_Model_Resource_Fulltext_Collection->addSearchFilter('plastic')
#9 /home/omit/public_html/app/code/core/Mage/CatalogSearch/Model/Layer.php(42): Sns_Ajaxfilter_Model_Catalogsearch_Layer->prepareProductCollection(Object(Netzarbeiter_GroupsCatalog2_Model_CatalogSearch_Resource_Fulltext_Collection))
#10 /home/omit/public_html/app/code/core/Mage/Catalog/Model/Layer.php(290): Mage_CatalogSearch_Model_Layer->getProductCollection()
#11 /home/omit/public_html/app/code/core/Mage/Catalog/Model/Layer.php(220): Mage_Catalog_Model_Layer->_getSetIds()
#12 /home/omit/public_html/app/code/core/Mage/Catalog/Block/Layer/View.php(163): Mage_Catalog_Model_Layer->getFilterableAttributes()
#13 /home/omit/public_html/app/code/core/Mage/Catalog/Block/Layer/View.php(122): Mage_Catalog_Block_Layer_View->_getFilterableAttributes()
#14 /home/omit/public_html/app/code/core/Mage/Core/Block/Abstract.php(293): Mage_Catalog_Block_Layer_View->_prepareLayout()
#15 /home/omit/public_html/app/code/core/Mage/Core/Model/Layout.php(456): Mage_Core_Block_Abstract->setLayout(Object(Mage_Core_Model_Layout))
#16 /home/omit/public_html/app/code/core/Mage/Core/Model/Layout.php(472): Mage_Core_Model_Layout->createBlock('catalogsearch/l...', 'catalogsearch.l...')
#17 /home/omit/public_html/app/code/core/Mage/Core/Model/Layout.php(239): Mage_Core_Model_Layout->addBlock('catalogsearch/l...', 'catalogsearch.l...')
#18 /home/omit/public_html/app/code/core/Mage/Core/Model/Layout.php(205): Mage_Core_Model_Layout->_generateBlock(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#19 /home/omit/public_html/app/code/core/Mage/Core/Model/Layout.php(210): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))
#20 /home/omit/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(344): Mage_Core_Model_Layout->generateBlocks()
#21 /home/omit/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(269): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()
#22 /home/omit/public_html/app/code/local/Sns/Ajaxfilter/controllers/CatalogSearch/ResultController.php(191): Mage_Core_Controller_Varien_Action->loadLayout()
#23 /home/omit/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Sns_Ajaxfilter_CatalogSearch_ResultController->indexAction()
#24 /home/omit/public_html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('index')
#25 /home/omit/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->(Object(Mage_Core_Controller_Request_Http))
#26 /home/omit/public_html/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#27 /home/omit/public_html/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#28 /home/omit/public_html/index.php(91): Mage::run('', 'store')
#29 {main}
When I execute the same query in phpMyAdmin, I get the following:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':query IN BOOLEAN MODE) AS `relevance` FROM `catalogsearch_fulltext` AS `s` INN' at line 1
Any idea what is going on here?
A:
I haven't debug the code but I can see that the error was caused by
$adapter->query($sql, $bind);
With $bind is null or empty array().
However I don't think $bind would ever have those value, look in Mage_CatalogSearch_Model_Resource_Helper_Mysql4 function prepareTerms.
I can see that you have rewritten /app/code/local/Mage/CatalogSearch/Model/Resource/Fulltext.php . My guess would be the problem is in that class.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WCF Data Services + LINQ Projection into a custom type
I'm trying to project parts of a Display and its list of locations from a WCF Data service into a custom type. Is this doable in WCF Data Services in a Silverlight client? There is some help here, but it doesn't show getting a list back as well as simple strings.
Currently I'm getting "NotSupportedException: Constructing or initializing instances of the type UserQuery+Info with the expression d.Base.Title is not supported.".
It would be a bonus if you could tell me how to do Expand on Locations in this syntax (I know about Displays.Expand("Locations")) or if I need it.
LINQPad snippet
var displays = from d in Displays.Where(d => d.Id == 3136)
select new Info
{
Name = d.Base.Title,
};
displays.Dump();
}
public class Info
{
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
public IEnumerable<Location> locations;
public IEnumerable<Location> Locations
{
get{ return this.locations;}
set{ this.locations = value;}
}
A:
The problem is that you are effectively asking your WCF server to construct some type it has no knowledge about. Since it is unable to do so, you have to it yourself on your computer:
Displays
.Where(d => d.Id == 3136)
.AsEnumerable()
.Select(d => new Info { Name = d.Base.Title })
This will run the Where() on the server, but the Select() on your computer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Exporting classification error matrix Google Earth Engine
I did a supervised classification of land cover and I need to export the Validation error matrix to .csv file. When using 'Export.table.toDrive' an error message 'Invalid argument: 'collection' must be a FeatureCollection' appears. Is there any way how to do that?
var year99=ee.Image('LANDSAT/LE07/C01/T1_SR/LE07_191025_19990915')
.clip(table)
.updateMask(FinalMask);
// Input image
var input=year99;
// Select and visualize MODIS land cover, IGBP classification, for training.
var modis=ee.Image('MODIS/051/MCD12Q1/2013_01_01')
.select('Land_Cover_Type_1')
.clip(table)
.updateMask(FinalMask);
// Define a palette for the 18 distinct land cover classes.
var igbpPalette = [
'aec3d4', // water
'152106', '225129', '369b47', '30eb5b', '387242', // forest
'6a2325', 'c3aa69', 'b76031', 'd9903d', '91af40', // shrub, grass
'111149', // wetlands
'cdb33b', // croplands
'cc0013', // urban
'33280d', // crop mosaic
'd7cdcc', // snow and ice
'f7e084', // barren
'6f6f6f' // tundra
];
// Specify the min and max labels and the color palette matching the labels.
Map.setCenter(15.293, 50.659, 8);
Map.addLayer(modis,
{min: 0, max: 17, palette: igbpPalette},
'IGBP classification');
// Visualize input image
var visParams = {bands: ['B3', 'B2', 'B1'], min: 16, max: 1412};
Map.addLayer(input,visParams, 'input');
// Print input image and Modis Landcover image
print ('input',input);
print ('modis',modis);
// Sample the input imagery to get a FeatureCollection of training data.
var training = input.addBands(modis).sample({
numPixels: 500,
seed: 0,
region: table
});
// Make a Random Forest classifier and train it.
var classifier = ee.Classifier.randomForest(10)
.train(training, 'Land_Cover_Type_1');
// Classify the input imagery.
var classified = input.classify(classifier);
// Get a confusion matrix representing resubstitution accuracy.
var trainAccuracy = classifier.confusionMatrix();
print('Resubstitution error matrix: ', trainAccuracy);
print('Training overall accuracy: ', trainAccuracy.accuracy());
// Sample the input with a different random seed to get validation data.
var validation = input.addBands(modis).sample({
numPixels: 500,
seed: 1,
region:table
// Filter the result to get rid of any null pixels.
}).filter(ee.Filter.neq('B1', null));
// Classify the validation data.
var validated = validation.classify(classifier);
// Get a confusion matrix representing expected accuracy.
var testAccuracy = validated.errorMatrix('Land_Cover_Type_1', 'classification');
print('Validation error matrix: ', testAccuracy);
print('Validation overall accuracy: ', testAccuracy.accuracy());
// Display the input and the classification.
Map.centerObject(table, 8);
Map.addLayer(input, {bands: ['B3', 'B2', 'B1'], max: 0.4}, 'landsat');
Map.addLayer(classified, {palette: igbpPalette, min: 0, max: 17}, 'classification');
print('classified',classified);
A:
Without sharing the table it is impossible to recreate your error. You could share the complete script by using the "Get Link" button.
If you want to export the error matrix you need to cast it to a FeatureCollection first - just as the error message tells you.
var exportAccuracy = ee.Feature(null, {matrix: testAccuracy.array()})
// Export the FeatureCollection.
Export.table.toDrive({
collection: ee.FeatureCollection(exportAccuracy),
description: 'exportAccuracy',
fileFormat: 'CSV'
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Eclipse editor not showing error markers
My eclipse is not showing error in its file editor. I have tried cleaning and putting project on Build Automatically. However when I run it then I do see the compiler error in console and also in problem view just after saving the file. Does anyone have any idea how to fix this ?
This is the version of my eclipse:
Eclipse IDE for Java Developers Version: Neon.2 Release (4.6.2)
Adding more images:
A:
Check the Build Path of the project by right clicking the project and select Build Path -> Configure Build Path.
JDK is not properly configure for project. Configure your JDK instead of in-build JRE.
Also make sure your source folder is also configure in Build Path (for example MyProject/src) must listed as a Source folder.
In Java Compiler-->Errors/warning, click Restore Default.
Make sure "Build Automatically" is checked.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
create p12 certificate in windows for apple push notification
I'm doing push notification (server side) for iPhone in c#. I have "developer_Push_SSL_certi.cer" file.
How can i create .p12 certificate from .cer file? or i have to install the above .cer file in my PC?
what is the required file to send push notifications in server side(c#).
Please guide me guys, what is the certification process required for APN (server side) in windows.
A:
You dont need a mac to convert the certificate just use OpenSSL (http://www.openssl.org)
here are the commands
$ openssl x509 -in cert.cer -inform DER -outform PEM -out cert.pem
$ openssl pkcs12 -in key.p12 -out key.pem -nodes
$ openssl pkcs12 -export -inkey key.pem -in cert.pem -out certName.p12
A:
First install this new certificate (developer_Push_SSL_certi.cer) to your Mac.
Then open KeyChain Access and navigate to Keys from left menu. Find your development certificate.
Expand your certificate you will see both Private and Public lines and right click "Private" one, export this certificate with a password.
Thats enough for sending notifications from windows.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to update DB records using a dynamically generated link
I have a requirement to generate an email to administrator whenever a user sign up. Administrator will approve the registration by clicking on a link provided in email and database should get updated, without admin to login to administrator console.
I am looking for best practice to code this scenario with keeping application security intact. I can generate email with dynamic rendom value attached to the link(provided in email) URL, but i am not sure how to keep a track of this on application side?
Any thoughts?
A:
You could generate a random validation number when the user signs up, and store it in the database with the user record. Then generate an email with a link such as
http://foo.bar.com/approveUser.action?userId=<theUserId>&validationToken=<theRandomNumber>
When the approveUser action is invoked, check if the validation token stored in the database for the given user ID matches with the token sent as parameter, and if so, approve the user.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
checkbox to grey out text
I have an issue with checkbox. I am trying to grey out some text if the check box is not ticked but am unable to do so. I did this before but have forgotten and my code kinda got messed up coz i hadnt saved a copy of it.
this is the java.
package com.example.mobilebillforecaster;
import com.example.mbf.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
public class Eticorporate extends Activity {
protected void onCreate(Bundle Bundle)
{
super.onCreate(Bundle);
setContentView(R.layout.eti_corporate);
((CheckBox)findViewById(R.id.cRoam)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (((CheckBox)v).isChecked())
{
this.tbDataroam.setEnabled(true);
this.bIntroam.setEnabled(true);
this.dataroam.setEnabled(true);
return;
}
this.tbDataroam.setEnabled(false);
this.bIntroam.setEnabled(false);
this.dataroam.setEnabled(false);
}
});
this is the XML
<CheckBox
android:id="@+id/cRoam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@id/datalocal"
android:layout_marginTop="5.0dip"
android:checked="false"
android:onClick="onCheckboxClicked"
android:text="@string/checkroam" />
<TextView
android:id="@+id/dataroam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/datalocal"
android:layout_below="@+id/bIntroam"
android:layout_marginTop="18.0dip"
android:enabled="false"
android:text="@string/data_roam"
android:textAppearance="?android:textAppearanceMedium" />
<ToggleButton
android:id="@+id/tbDataroam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/bIntroam"
android:layout_marginTop="7.0dip"
android:layout_toRightOf="@id/nationalmins"
android:enabled="false"
android:text="@string/data_roam" />
<Button
android:id="@+id/bIntroam"
android:layout_width="250.0dip"
android:layout_height="50.0dip"
android:layout_alignRight="@id/bundle"
android:layout_below="@id/cRoam"
android:enabled="false"
android:text="@string/int_roam" />
i know this might be a simple thing but i just cant figure it out.
thanks,
A:
I would recommend the use of OnCheckedChangeListener instead.
Would look like this:
((CheckBox)findViewById(R.id.cRoam)).setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
{
this.tbDataroam.setEnabled(true);
this.bIntroam.setEnabled(true);
this.dataroam.setEnabled(true);
return;
}
this.tbDataroam.setEnabled(false);
this.bIntroam.setEnabled(false);
this.dataroam.setEnabled(false);
}
});
EDIT:
You need to obtain references to those 3 widgets before you try to access them:
ToggleButton tbDataroam = (ToggleButton) findViewById(R.id.tbDataroam);
Repeat for the other 2 widgets...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Hapi/Joi validation
What does these with() and without() function do in Joi validation?
const schema = Joi.object().keys({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
access_token: [Joi.string(), Joi.number()],
birthyear: Joi.number().integer().min(1900).max(2013),
email: Joi.string().email()
}).with('username', 'birthyear').without('password', 'access_token');
A:
Taken from the hapijs API Reference:
object.with(key, peers)
Requires the presence of other keys whenever
the specified key is present where:
key - the reference key.
peers - the required peer key names that must
appear together with key. peers can be a single string value or an
array of string values.
Translated to your example that means "When the key username is present the key birthyear must also be present".
object.without(key, peers)
Forbids the presence of other keys whenever
the specified is present where:
key - the reference key.
peers - the forbidden peer key names that
must not appear together with key. peers can be a single string value
or an array of string values.
Translated to your example that means "When the key password is present then the key access_token is not allowed to be present too".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I need an algorithm to find the best path
I need an algorithm to find the best solution of a path finding problem. The problem can be stated as:
At the starting point I can proceed along multiple different paths.
At each step there are another multiple possible choices where to proceed.
There are two operations possible at each step:
A boundary condition that determine if a path is acceptable or not.
A condition that determine if the path has reached the final destination and can be selected as the best one.
At each step a number of paths can be eliminated, letting only the "good" paths to grow.
I hope this sufficiently describes my problem, and also a possible brute force solution.
My question is: is the brute force is the best/only solution to the problem, and I need some hint also about the best coding structure of the algorithm.
A:
Take a look at A*, and use the length as boundary condition.
http://en.wikipedia.org/wiki/A%2a_search_algorithm
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Excluding one directory in .htaccess (not just rewrite rules)
Excluding one or more directories from rewrite rules in .htaccess files seems to be a common question. However, my .htaccess does more than just set rewrite rules. I've also set some server changes (we don't have suPHP on this server) as well as set some prepending of some php files. For example these are a few examples:
# Make files ending in .php, .html and .xml files etc. parsed by php.
AddType application/x-httpd-php .php .html .xml .css .js .le .txt
<FilesMatch "\.html$">
php_value auto_prepend_file "/home/2427/spwebsites/www.spwebsites.co.uk/incs/phps/config.php"
</FilesMatch>
# Internal Server Error
ErrorDocument 500 /admin/errors.html?code=500
RewriteEngine On
RewriteRule ^([a-zA-Z0-9-]+)/$ $1.html [L]
I don't want any of these set for one directory (where my word press installation is), is there a way I can do this? Can I set a conditional statement for the whole .htaccess file?
Adding a blank .htaccess file in the word press directory won't work because this won't undo the settings in the parent directory.
A:
I was just looking into your dilemma and it is a tricky one. It would be nice to be able to have the DirectoryMatch directive available in .htaccess ...
What you can try is to reset your values in the specific directory via another .htaccess file.
So in the case of the AddType perhaps, resetting it back to just ".php" might work (assuming it doesn't inherit the other values). Definitely not an ideal solution with out access to the main config file/ virtual host.
Here is a weird idea that you can try/test ... place the "wordpress" dir outside of the main root (or whereever you have the offending .htaccess file). Now route all requests to the wordpress (inner dir) to the outer dir. I wonder if Apache would not use the offending .htaccess considering the requests are being routed?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Returning objects by value?
im trying to return a local object from a function
and i have this problem
if i return the locally created object it returns null
DString DString :: operator + (const char* param)
{
// Variable definition
int nSize = ( this->GetLength() + (strlen(param)));
// Create a new char array in the opropriate size
char* cstrNewString = new char[nSize + 1];
// Append data
strcpy(cstrNewString, this->_cstrString);
strcat(cstrNewString, (char*)param);
cstrNewString[nSize] = '\0';
// Create a new DString to return
DString dstNewData(cstrNewString);
// Clean up
delete[] cstrNewString;
// Return data
return (dstNewData); // Null!
if i do the same exact thing only creating a new object in the return line such as this:
DString DString :: operator + (const char* param)
{
// Variable definition
int nSize = ( this->GetLength() + (strlen(param)));
// Create a new char array in the opropriate size
char* cstrNewString = new char[nSize + 1];
// Append data
strcpy(cstrNewString, this->_cstrString);
strcat(cstrNewString, (char*)param);
cstrNewString[nSize] = '\0';
// Create a new DString to return
DString dstNewData(cstrNewString);
// Clean up
delete[] cstrNewString;
// Return data
return (DString(dstNewData.ToCharArray())); // Not null, returns correctly!
it returns correctly.. why is it doing this and how can i fix this ?
A:
How is your copy constructor defined? In the first case, the copy
constructor is called; in the second no. You don't show us any of the
essential code for DString, but given the apparent semantics, it seems
almost certain that the compiler generated copy constructor will not
do the right thing. If you're DString contains a dynamically
allocated pointer (and I don't see how it could be otherwise), which is
deleted in the destructor, the copy constructor must make a deep copy.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is $\left\{f\in L^1(\mu)\colon\int_{\mathbb R} |f(x)|^2d\mu\ge 1\right\}$ a closed set of $L^1(\mu)$?
Let $\mu$ be the Lebesgue measure on $\mathbb R$. Let
\begin{align}
A:=&\left\{f\in L^1(\mu)\colon\int_{\mathbb R} |f(x)|^2d\mu\ge 1\right\},\\
B:=&\left\{f\in L^1(\mu)\colon\int_{\mathbb R} |f(x)|^2d\mu\le 1\right\}.
\end{align}
Is $A$ a closed subset of $L^1(\mu)$?
Is $B$ a closed subset of $L^1(\mu)$?
My attempt:
First, let's consider 1. Suppose $\{f_n\}$ is a sequence of functions in $L^1(\mu)$ satisfying $\int_{\mathbb R}|f_n(x)|^2d\mu\ge 1$ with $\lim_{n\to\infty}\int_{\mathbb R}|f_n(x)-f(x)|d\mu=0$ we want to show that either $\int_{\mathbb R}|f(x)|^2d\mu\ge 1$ or there exists a sequence of $\{f_n\}$ with $\int_{\mathbb R}|f(x)|^2d\mu< 1$.
I have tried to apply some basic techniques like:
\begin{align}
\int_{\mathbb R}|f(x)|^2d\mu&=\int_{\mathbb R}|f(x)-f_n(x)+f_n(x)|^2d\mu\\
\end{align}
But then I got stuck. My problem is I am not able to fit the $L^1$ norm of $f_n-f$ and the $L^2$ norm of $f_n$ together. Can someone give me a hint? Thank you.
A:
1). No. Consider $f_n(x) = \sqrt{n}1_{[0,\frac{1}{n}]}(x)$. Then $\int_{\mathbb{R}} |f_n(x)|^2dx = 1$ for each $n$ whilst $f_n \to 0$ in $L^1$.
2). Yes. Say $(f_n)_n \in B$ and $f_n \to f$ in $L^1$. Then some subsequence $f_{n_k} \to f$ pointwise a.e.. Fatou's Lemma implies $\int_{\mathbb{R}} |f(x)|^2dx \le \liminf_{n \to \infty} \int_{\mathbb{R}} |f_n(x)|^2dx \le 1$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I read/parse following text using Clojure?
The structure of Text is like this;
Tag001
0.1, 0.2, 0.3, 0.4
0.5, 0.6, 0.7, 0.8
...
Tag002
1.1, 1.2, 1.3, 1.4
1.5, 1.6, 1.7, 1.8
...
Files can have any number of TagXXX things and each Tag can have any number of CSV value lines.
==== PPPS. (Sorry for these stuffs :-)
More improvements; now it takes 1 seconds or so for 31842 lines of data on my atom laptop, which is 7 times faster than original code. However, C version is 20 times faster than this.
(defn add-parsed-code [accu code]
(if (empty? code)
accu
(conj accu code)))
(defn add-values [code comps]
(let [values comps
old-values (:values code)
new-values (if old-values
(conj old-values values)
[values])]
(assoc code :values new-values)))
(defn read-line-components [file]
(map (fn [line] (clojure.string/split line #","))
(with-open [rdr (clojure.java.io/reader file)]
(doall (line-seq rdr)))))
(defn parse-file [file]
(let [line-comps (read-line-components file)]
(loop [line-comps line-comps
accu []
curr {}]
(if line-comps
(let [comps (first line-comps)]
(if (= (count comps) 1) ;; code line?
(recur (next line-comps)
(add-parsed-code accu curr)
{:code (first comps)})
(recur (next line-comps)
accu
(add-values curr comps))))
(add-parsed-code accu curr)))))
==== PPS.
Though I cannot figure out why first one is 10 times faster than second one, instead of
slurp, map and with-open does make reading faster; though whole reading/processing time
does not that reduced (from 7 sec. to 6 sec)
(time
(let [lines (map (fn [line] line)
(with-open [rdr (clojure.java.io/reader
"DATA.txt")]
(doall (line-seq rdr))))]
(println (last lines))))
(time (let [lines
(clojure.string/split-lines
(slurp "DATA.txt"))]
(println (last lines))))
==== PS.
Skuro's solution did work. But the parsing speed is not that fast so I have to use C-based parser (which reads 400 files in 1~3 secs, whereas clojure does take 1~4 secs for single file; yes file sizes are rather large) for reading and constructing DB and clojure for statistical analysis part only.
A:
The following parses the above file keeping any values line separated. If that's not what you want you can change the add-values function. The parsing state is held in the curr variable, while accu holds previously parsed tags (i.e. all the lines that appeared before a "TagXXX" was found). It allows for values without a tag:
UPDATE: side effect now encapsulated in a dedicated load-file function
(defn tag? [line]
(re-matches #"Tag[0-9]*" line))
; potentially unsafe, you might want to change this:
(defn parse-values [line]
(read-string (str "[" line "]")))
(defn add-parsed-tag [accu tag]
(if (empty? tag)
accu
(conj accu tag)))
(defn add-values [tag line]
(let [values (parse-values line)
old-values (:values tag)
new-values (if old-values
(conj old-values values)
[values])]
(assoc tag :values new-values)))
(defn load-file [path]
(slurp path))
(defn parse-file [file]
(let [lines (clojure.string/split-lines file)]
(loop [lines lines ; remaining lines
accu [] ; already parsed tags
curr {}] ; current tag being parsed
(if lines
(let [line (first lines)]
(if (tag? line)
; we recur after starting a new tag
; if curr is empty we don't add it to the accu (e.g. first iteration)
(recur (next lines)
(add-parsed-tag accu curr)
{:tag line})
; we're parsing values for a currentl tag
(recur (next lines)
accu
(add-values curr line))))
; if we were parsing a tag, we need to add it to the final result
(add-parsed-tag accu curr)))))
I'm not quite excited about the above code, but it does the job. Given a file like:
Tag001
0.1, 0.2, 0.3, 0.4
0.5, 0.6, 0.7, 0.8
Tag002
1.1, 1.2, 1.3, 1.4
1.5, 1.6, 1.7, 1.8
Tag003
1.1, 1.2, 1.3, 1.4
1.1, 1.2, 1.3, 1.4
1.5, 1.6, 1.7, 1.8
1.5, 1.6, 1.7, 1.8
It produces the following result:
user=> (clojure.pprint/print-table [:tag :values] (parse-file (load-file "tags.txt")))
================================================================
:tag | :values
================================================================
Tag001 | [[0.1 0.2 0.3 0.4] [0.5 0.6 0.7 0.8]]
Tag002 | [[1.1 1.2 1.3 1.4] [1.5 1.6 1.7 1.8]]
Tag003 | [[1.1 1.2 1.3 1.4] [1.1 1.2 1.3 1.4] [1.5 1.6 1.7 1.8] [1.5 1.6 1.7 1.8]]
================================================================
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Drag and drop ImageView into a container for verification
To understand it better read this :
First game :
Skate QuestionMark
Archery QuestionMark
Swim QuestionMark
---------------------------
Water Bow Wheel
If user drags Water to Skate or Archery QuestionMark it will animate to the list (because it is not correct)
If user drags twice incorrect (it will mark the one that is correct from the answer list)
If user still fail in the third try it will drag to the incorrect one and then it will highlight or just change the color doesn't matter to red.
If user drags to the correct one it will highlight green and replace QuestionMark with the correct one (I do not want to be draggable anymore that image)
------
Game 2 (is more or less the same...)
There's no QuestionMark column, there's only :
Skate
Swim
Archery
--------------
(Lot of answers)
Now the way to play is the same (about the fails and etc) the thing is now when I drag any answer to the correct one it won't replace the correct one, it will just disappear and if it fails instead of highlighting all the corrects one it will highlight the correct answer (for instance; if I drag wheel to Swim once, it doesn't happen anything just animate to the place where it was, if I do it twice it will highlight the Skate one, and if it fails at third one it just drag wherever he did and highlight with red)
I'm planning to build an app that does a simple check, I'm calling an endpoint and I'll get some params, and then I'll know how many ImageView are going to be displayed in the screen.
This is like a puzzle, and it would look like this :
So I have different options, which contains only one correct answer, I'm planing the way to achieve this, could be able to drag "Bow" to the questionmark infront of "skateboarding" and then says that is not correct, then drag it to the "archery" one and replace the questionmark for the ImageView from the bottom that contains the word "Arrow".
Layout should contain one column for Question (this should be the sports) then another one in front of the Question one and should be the Answer one, then below them should contain the Options one.
Was it clear? Otherwise let me know and I'll try to explain it a little bit with more details.
EDIT
What I thought is having like a class that contains a list of Answers or just create like :
RightList : (id:1,id:2,id:3)
LeftList : (id:1, id:2, id:3)
DownList : (Bow = id:2),(Skate = id:1), (Ball = id:3)
Then doing the drag and drop thing when the DragEvent.ACTION_DROP or DragEvent.ACTION_DRAG_ENDEDI do not know which one, check (Pseudocode below)
if(imageDragged.id==location.id) then replace the question mark image for imageDragged
else animate the image to the place where it comes
I do not know if creating a class that implements onDragListener() or something like that, I'd like to have it generic so I can use it on different games like for instance :
SKATE(id:1) ARCHERY(id:2) FOOTBALL(id:3)
Answers : TABLE(C.A. id:1) BOW(C.A. id:2) GRASS(C.A. id:3) GOAL(C.A. id:3) BALL(C.A. id:3) ARROW(C.A. id:2) AXES(C.A. id:1) WHEELS(C.A. id:1)
So if I drag and drop for instance BOW to FOOTBALL then it should display that is bad, otherwise say that it's good.
A:
EXAMPLE 1/3
Just for reference and summarize everything. Here is one 100 lines code, within single Activity and imports, representing all this behavior even with simple animation.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bind()
}
private fun bind() {
addQuestions()
addAnswers()
}
@SuppressLint("InflateParams")
private fun addQuestions() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_question, null)
view.setOnDragListener(DragListener())
questionContainer.addView(view)
}
}
@SuppressLint("InflateParams")
private fun addAnswers() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_answer, null)
view.setOnTouchListener(DragItemTouchListener())
answerContainer.addView(view)
}
}
private inner class DragItemTouchListener : OnTouchListener {
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
return if (motionEvent.action == MotionEvent.ACTION_DOWN) {
dragMultiple(view)
true
} else {
false
}
}
private fun dragMultiple(view : View) {
val data = ClipData.newPlainText("", "")
val shadowBuilder = DragShadowBuilder(
view
)
val parent = view.parent as ViewGroup
view.startDragAndDrop(data, shadowBuilder, view, 0)
parent.removeView(view)
}
}
private inner class DragListener : OnDragListener {
override fun onDrag(v: View, event: DragEvent): Boolean {
when (event.action) {
DragEvent.ACTION_DRAG_STARTED -> {
}
DragEvent.ACTION_DRAG_ENTERED -> {
}
DragEvent.ACTION_DRAG_EXITED -> {
}
DragEvent.ACTION_DROP -> {
animateDropEffect(v as ViewGroup, event.localState as View)
}
DragEvent.ACTION_DRAG_ENDED -> {
}
else -> {
}
}
return true
}
private fun animateDropEffect(into: ViewGroup, view: View) {
into.addView(view)
val params = (view.layoutParams as FrameLayout.LayoutParams)
.apply {
gravity = Gravity.END
}
view.layoutParams = params
}
}
}
All Xmls used. Below xml for all examples below.
/* activity_main.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/mainContainer"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="500dp"
android:animateLayoutChanges="true">
<LinearLayout
android:id="@+id/questionContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true">
<LinearLayout
android:id="@+id/answerContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</FrameLayout>
/* item_question.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:padding="5dp">
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="start"
android:background="@android:color/holo_blue_bright">
</View>
<View
android:id="@+id/questionView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="end"
android:background="@android:color/holo_orange_light">
</View>
</FrameLayout>
/* item_answer.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:tag="Test">
<LinearLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="@android:color/darker_gray">
</LinearLayout>
</FrameLayout>
EXAMPLE 2/3
It's not a problem to make dragging for few elements following with a the same approach. Here is a little crappy, but simple example.
Modified code for second example. Xml stay the same.
class MainActivity : AppCompatActivity() {
var activeOneDrag : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bind()
}
private fun bind() {
addQuestions()
addAnswers()
}
fun getRandomColor(): Int {
return Color.argb(255, Random.nextInt(255),
Random.nextInt(255), Random.nextInt(255))
}
@SuppressLint("InflateParams")
private fun addQuestions() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_question, null)
view.setOnDragListener(DragListener())
questionContainer.addView(view)
}
}
@SuppressLint("InflateParams")
private fun addAnswers() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_answer, null)
(view as ViewGroup).getChildAt(0).setBackgroundColor(getRandomColor())
view.setOnTouchListener(DragItemTouchListener())
answerContainer.addView(view)
}
}
private inner class DragItemTouchListener : OnTouchListener {
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
return if (motionEvent.action == MotionEvent.ACTION_DOWN) {
dragMultiple(view)
true
} else {
false
}
}
private fun dragMultiple(view : View) {
val parent = view.parent as ViewGroup
parent.removeView(view)
/**
* Some other logic with selective multiple View.
* Just getting neighbor in our case
*/
var anotherView : View? = null
if (!activeOneDrag) {
anotherView = parent.getChildAt(
parent.indexOfChild(view) + 1)
parent.removeView(anotherView)
}
activeOneDrag = !activeOneDrag
/**
* As you can see, there is postDelay here.
* But only for our case with animateLayoutChanges,
* with delays removing View! In your samples, you could remove it
* with listener on your own animation, if any!
*/
parent.postDelayed({
val layout = LinearLayout(this@MainActivity)
val params = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT)
params.gravity = Gravity.BOTTOM
layout.layoutParams = params
layout.orientation = LinearLayout.HORIZONTAL
layout.addView(view)
if (anotherView != null) {
layout.addView(anotherView)
}
layout.visibility = INVISIBLE
mainContainer.addView(layout)
parent.post {
layout.startDragAndDrop(
ClipData.newPlainText("", ""),
DragShadowBuilder(layout), layout, 0)
}
}, 400)
}
}
private inner class DragListener : OnDragListener {
override fun onDrag(v: View, event: DragEvent): Boolean {
when (event.action) {
DragEvent.ACTION_DRAG_STARTED -> {
}
DragEvent.ACTION_DRAG_ENTERED -> {
}
DragEvent.ACTION_DRAG_EXITED -> {
}
DragEvent.ACTION_DROP -> {
val view = event.localState as View
(view.parent as ViewGroup).removeView(view)
view.visibility = VISIBLE
animateDropEffect(v as ViewGroup, event.localState as View)
}
DragEvent.ACTION_DRAG_ENDED -> {
}
else -> {
}
}
return true
}
private fun animateDropEffect(into: ViewGroup, view: View) {
into.addView(view)
val params = (view.layoutParams as FrameLayout.LayoutParams)
.apply {
gravity = Gravity.END
}
view.layoutParams = params
}
}
}
EXAMPLE 3/3
As I see, it's not clear, how to change simple actions with animation or Drag listening area. Here is another simple example of doing all actions
class MainActivity : AppCompatActivity() {
@Volatile
var state : State = State.INACTIVE
enum class State {
ACTIVE, INACTIVE, HANDLED
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bind()
}
private fun bind() {
addQuestions()
addAnswers()
}
private fun getRandomColor(): Int {
return Color.argb(255, Random.nextInt(255),
Random.nextInt(255), Random.nextInt(255))
}
@SuppressLint("InflateParams")
private fun addQuestions() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_question, null)
view.findViewById<View>(R.id.questionView)
.setOnDragListener(DragListener())
questionContainer.addView(view)
}
}
@SuppressLint("InflateParams")
private fun addAnswers() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_answer, null)
(view as ViewGroup).getChildAt(0).setBackgroundColor(getRandomColor())
view.setOnTouchListener(DragItemTouchListener())
answerContainer.addView(view)
}
}
private inner class DragItemTouchListener : OnTouchListener {
val ITEM_INDEX_D = "Index-From"
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
return if (motionEvent.action == MotionEvent.ACTION_DOWN) {
createDrag(view)
true
} else {
false
}
}
private fun createDrag(view : View) {
val parent = view.parent as ViewGroup
view.tag = Pair(ITEM_INDEX_D,
parent.indexOfChild(view))
view.startDragAndDrop(ClipData.newPlainText("", ""),
DragShadowBuilder(view), view, 0)
parent.removeView(view)
parent.setBackgroundColor(Color.WHITE)
}
}
private inner class DragListener : OnDragListener {
override fun onDrag(parent: View, event: DragEvent): Boolean {
val view = event.localState as View
when (event.action) {
DragEvent.ACTION_DRAG_STARTED -> {
state = State.ACTIVE
}
DragEvent.ACTION_DRAG_ENTERED -> {
}
DragEvent.ACTION_DRAG_EXITED -> {
}
DragEvent.ACTION_DROP -> {
state = State.HANDLED
animateDropEffect(parent, view)
return true
}
DragEvent.ACTION_DRAG_ENDED -> {
if (state == State.ACTIVE) {
state = State.INACTIVE
animateMoveBack(view,
(view.tag as Pair<*, *>).second as Int)
}
return true
}
else -> {
}
}
return true
}
private fun animateMoveBack(view: View, index : Int) {
answerContainer.addView(view, index)
}
private fun animateDropEffect(into: View, view: View) {
val parent = (into.parent as ViewGroup)
parent.addView(view)
val params = (view.layoutParams as FrameLayout.LayoutParams)
.apply {
gravity = Gravity.END
}
view.layoutParams = params
checkIsCorrect(parent)
}
private fun checkIsCorrect(parent : ViewGroup) {
val correct = Random.nextBoolean()
val colorFrom = Color.WHITE
val colorTo : Int = if (correct) 0x8000ff00.toInt() else 0x80ff0000.toInt()
ObjectAnimator.ofObject(
parent,
"backgroundColor",
ArgbEvaluator(),
colorFrom,
colorTo
)
.setDuration(1000)
.start()
}
}
}
UPDATE
The last update from the comments sections. I think it's enough, and of course you would need you changes. So just change two "if" statement to align with your requirements and animation.
class MainActivity : AppCompatActivity() {
enum class State {
ACTIVE, INACTIVE, HANDLED
}
var state : State = State.INACTIVE
var failsCount = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bind()
}
private fun bind() {
addQuestions()
addAnswers()
}
private fun getRandomColor(): Int {
return Color.argb(255, Random.nextInt(255),
Random.nextInt(255), Random.nextInt(255))
}
@SuppressLint("InflateParams")
private fun addQuestions() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..3) {
val view = inflater.inflate(R.layout.item_question, null)
view.findViewById<View>(R.id.questionView)
.setOnDragListener(DragListener())
questionContainer.addView(view)
}
}
@SuppressLint("InflateParams")
private fun addAnswers() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..3) {
val view = inflater.inflate(R.layout.item_answer, null)
(view as ViewGroup).getChildAt(0).setBackgroundColor(getRandomColor())
view.setOnTouchListener(DragItemTouchListener())
answerContainer.addView(view)
}
}
private inner class DragItemTouchListener : OnTouchListener {
val ITEM_INDEX_D = "Index-From"
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
return if (motionEvent.action == MotionEvent.ACTION_DOWN) {
createDrag(view)
true
} else {
false
}
}
private fun createDrag(view : View) {
val parent = view.parent as ViewGroup
view.tag = Pair(ITEM_INDEX_D,
parent.indexOfChild(view))
view.startDragAndDrop(ClipData.newPlainText("", ""),
DragShadowBuilder(view), view, 0)
parent.removeView(view)
parent.setBackgroundColor(Color.WHITE)
}
}
private inner class DragListener : OnDragListener {
val ANIM_DURATION_LONG = TimeUnit.SECONDS.toMillis(1)
val ANIM_DURATION_SHORT = TimeUnit.MILLISECONDS.toMillis(500)
val GREEN_ALPHA = 0x8000ff00.toInt()
val RED_ALPHA = 0x80ff0000.toInt()
val ANIM_COLOR = "backgroundColor"
override fun onDrag(parent: View, event: DragEvent): Boolean {
val view = event.localState as View
when (event.action) {
DragEvent.ACTION_DRAG_STARTED -> {
state = State.ACTIVE
}
DragEvent.ACTION_DRAG_ENTERED -> {
}
DragEvent.ACTION_DRAG_EXITED -> {
}
DragEvent.ACTION_DROP -> {
state = State.HANDLED
animateDropEffect(parent, view)
return true
}
DragEvent.ACTION_DRAG_ENDED -> {
if (state == State.ACTIVE) {
state = State.INACTIVE
animateMoveBack(view,
(view.tag as Pair<*, *>).second as Int)
}
return true
}
else -> {
}
}
return true
}
private fun animateMoveBack(view: View, index : Int) {
answerContainer.addView(view, index)
}
private fun animateDropEffect(into: View, view: View) {
val parent = (into.parent as ViewGroup)
parent.addView(view)
val params = (view.layoutParams as FrameLayout.LayoutParams)
.apply {
gravity = Gravity.END
}
view.layoutParams = params
checkIsCorrect(parent)
}
private fun checkIsCorrect(parent : ViewGroup) {
val correct = false
if (correct) {
animateColorChange(parent, true)
return
}
if (++failsCount > Companion.MAX_FAIL_COUNT) {
animateColorChange(parent, false)
return
}
animateWrongAttempt(parent)
}
private fun animateWrongAttempt(parent: ViewGroup) {
val questionMark = parent.findViewById<View>(R.id.questionView)
questionMark.setBackgroundColor(Color.RED)
val va = ValueAnimator.ofFloat(1f, 1.1f)
va.interpolator = BounceInterpolator()
va.duration = ANIM_DURATION_SHORT
va.addUpdateListener { animation ->
questionMark.scaleX = animation.animatedValue as Float
questionMark.scaleY = animation.animatedValue as Float
}
va.start()
}
private fun animateColorChange(parent : ViewGroup, right : Boolean) {
val colorFrom = Color.WHITE
ObjectAnimator
.ofObject(parent, ANIM_COLOR,
ArgbEvaluator(), colorFrom,
if (right) GREEN_ALPHA else RED_ALPHA)
.setDuration(ANIM_DURATION_LONG)
.start()
}
}
companion object {
const val MAX_FAIL_COUNT = 2
}
}
And new xml.
/* activity_main.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/mainContainer"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="500dp"
android:animateLayoutChanges="true">
<LinearLayout
android:id="@+id/questionContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true">
<LinearLayout
android:id="@+id/answerContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</FrameLayout>
/* item_question.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:paddingTop="10dp">
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="start"
android:layout_margin="5dp"
android:background="@android:color/holo_blue_bright">
</View>
<View
android:id="@+id/questionView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="end"
android:layout_margin="5dp"
android:background="@android:color/holo_orange_light">
</View>
</FrameLayout>
/* item_answer.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:tag="Test">
<LinearLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="@android:color/darker_gray">
</LinearLayout>
</FrameLayout>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Header not 100% in width when zoomed in
This is kind of weird, and I don't know how to explain this much here. When you zoom in to my website and scroll to the right, the header part + title box is missing. This does not happen when it is zoomed out. Previously, I set the body-width to 1024px and when I zoom out the entire page zooms out to the left (which is not desired if someone has a higher screen resolution) and I prefer it to remain centered. So, I let the body fill the full width but this does not appear to do so for the top part. Not sure what is causing it.
header {
width: 100%;
body {
width: 100%;
}
See my website here and you will be able to understand.
JS fiddle here: http://jsfiddle.net/D22Jd/
Zoom in and scroll to the right to see what I meant
A:
Adding the below code to CSS will fix your issue.
html, body {
min-width: 1024px; /*adjust as per your need*/
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to copy entire SQL Server 2008 database, applying WHERE clause to restrict copied data
To allow more realistic conditions during development and testing, we want to automate a process to copy our SQL Server 2008 databases down from production to developer workstations. Because these databases range in size from several GB up to 1-2 TB, it will take forever and not fit onto some machines (I'm talking to you, SSDs). I want to be able to press a button or run a script that can clone a database - structure and data - except be able to specify WHERE clauses during the data copy to reduce the size of the database.
I've found several partial solutions but nothing that is able to copy schema objects and a custom restricted data without requiring lots of manual labor to ensure objects/data are copied in correct order to satisfy dependencies, FK constraints, etc. I fully expect to write the WHERE clause for each table manually, but am hoping the rest can be automated so we can use this easily, quickly, and frequently. Bonus points if it automatically picks up new database objects as they are added.
Any help is greatly appreciated.
A:
Snapshot replication with conditions on tables. That way you will get your schema and data replicated whenever needed.
This article describes how to create a merge replication, but when you choose snapshot replication the steps are the same. And the most interesting part is Step 8: Filter Table Rows. of course, because with this you can filter out all the unnecessary data to get replicated. But this step needs to be done for every entity and if you've got like hundreds of them, then you'd better analyze how to do that programmatically instead of going through the wizard windows.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JOIN two SELECTs with Doctrine
I need to write this query with Doctrine. How can I write it down using QueryBuilder?
SELECT charges.id, charges.currency, charges.total_transactions,
charges.total_volume, charges.commission, refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds
ON charges.id = refunds.id AND charges.currency = refunds.currency
A:
You can use Native SQL and map results to entities:
use Doctrine\ORM\Query\ResultSetMapping;
$rsm = new ResultSetMapping;
$rsm->addEntityResult('AppBundle:Charges', 'charges')
->addEntityResult('AppBundle:Refunds', 'refunds')
->addFieldResult('charges', 'id', 'id')
->addFieldResult('charges', 'currency', 'currency')
->addFieldResult('charges', 'total_transactions', 'total_transactions')
->addFieldResult('charges', 'total_volume', 'total_volume')
->addFieldResult('charges', 'commission', 'commission')
->addFieldResult('refunds', 'total_payouts', 'total_payouts')
;
$sql = "
SELECT
charges.id,
charges.currency,
charges.total_transactions,
charges.total_volume,
charges.commission,
refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds ON charges.id = refunds.id AND charges.currency = refunds.currency
WHERE some_field = ?
";
$query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
$query->setParameter(1, $name);
$entities = $query->getResult();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is implicit transformation of numerical types inconsistent between "for/comprehension" expressions compared to(!) assignment operations?
Why is desugaring and implicit transformation of numerical types inconsistent between "for/comprehension" expressions compared to(!) assignment operations?
I'm sure there are many general perspectives on this but I couldn't figure out a concise and logical explanation for the current behavior. [Ref:"Behavior of Scala for/comprehension..."
]
For the sake of correctness all translations below was generated with the scala compiler ("scalac -Xprint:typer -e")
For example, during implicit numeric assignment transformation the Destination type is dominant:
Source: var l:Long = 0
Result : val l: Long = 0L
Source: var l:Long = 0.toInt
Result : var l: Long = 0.toInt.toLong
During implicit transformation of "for/comprehension" expressions the Source type is dominant:
Source: for (i:Long <- 0 to 1000000000L) { }
Result : 0.to(1000000000L).foreach(((i: Long) => ()))
Source: for (i <- 0L to 1000000000L) { }
Result : scala.this.Predef.longWrapper(0L).to(1000000000L).foreach[Unit](((i: Long) => ()))
A:
There are two completely different things going on. First, assignment:
val l: Long = 0
We have an Int that is being assigned to a Long. That shouldn't be possible, unless there is an implicit conversion from Int to Long, which we can verify like this:
scala> implicitly[Int => Long]
res1: Int => Long = <function1>
Since there is such a conversion, that conversion is applied.
Next, the for-comprehension:
for (i:Long <- 0 to 1000000000L) { }
This doesn't work because the to method called on Int (actually called on scala.runtime.RichInt, through an implicit conversion) only admits an Int argument, not a Long argument.
The to method called on a Long (RichLong) does admit a Long argument, but there are two reasons why that doesn't apply on the expression above:
To get to RichLong's to method, the Int would have to be first converted into a Long, and then into a RichLong, and Scala does not apply two chained implicit conversions, ever. It can only convert Int to RichInt or to Long, not Int to Long to RichLong.
To apply such conversion, there would have to be some indication a Long was required in first place, and there isn't. The i: Long does not refer to the type of 0 to 1000000000L, whereas l: Long does refer to the type of 0 in the first example.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do I have copyright on my code if someone else owns the LLC and the domain?
I have been the sole coder on a project for 4 years. I have a partner (not legally, yet but about to go through the process.) Right now, he owns 100% of the company and domain. Before the project release, I am to get 65% and he 35%. How can I secure my interest through copyright? What control does he have over my source code if I have it copyrighted? What process do I need to do to protect my interest and keep everyone playing fair? The completed code is not posted on his server yet.
A:
One issue that would come up is whether the code that you've produced is a "work for hire". The author of software holds copyright, except if it is created in the course of employment for company A, in which case A would hold the copyright. There is no bright line that easily distinguishes employment from other relations. If the coder is an "independent contractor", the product would not be a work for hire. Just because you say that you are an independent contractor does not mean that you are. If you are, there would have to be a written agreement to the effect that this is a work for hire (this article reviews some of the issues, relevant to a decision in New York). Usually, writing software is not a "work for hire", though it would be if you were a salaried employee of MS that wrote snippets of code. Work for hire falls into "employee" and "specially commissioned" categories, and software is not in the realm of the "specially commissioned" category.
In order for a company to use software that you hold the rights to, you have to grant them a license. If you fail to write out the terms of the license and just hand it over in exchange for something of value, the courts may eventually sort it out and find that you at least granted the company an implicit license to use the software. Rather than bothering with the expense and pain of the courts, you can negotiate agreeable terms. You could, hypothetically speaking, say that you retain all copyright in the product, and grant the company a license to use it on their servers (but not to modify or redistribute it). Or you could assign the rights to the company in exchange for gaining a 65% interest in the company: the possibilities are endless. Only you know what your interest is (and only he knows what his interest is), and nobody knows what "fair" is. What the law cares about is what you agreed to. So the first step would be to discuss your interests, and see what the common interest is, along with trade-offs of interest. Then write an agreement that describes that.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
mongoDB Object DBCursor has no method 'sort'
so i created a collection called food with 2 objects that were saved no problem. Using find() yielded no issues either. However, when I entered the following:
db.food.find().sort({averageRating:-1}).select({_id: 1}).limit(2)
I get the error:
JS Error: TypeError: Object DBCursor has no method 'sort'
What am i doing wrong?
A:
Is this what you are looking for?
db.food.find({},{_id:1}).sort({"averageRating":-1}).limit(2);
It selects only 2 id fields ordered by average rating descending.The fields that are to be returned are specified by the second parameter in find(),which in this case is _id.
select is not a valid command in mongoDb as far as I know.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.