text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Python subprocess package does not report errors from subprocess?
On some machine, for the following piece of code
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.STDOUT);
out, err = p.communicate()
This script would just hang at p.communicate() and does not return.
After I manually run the command, I finally see the error messages.
Why is this, and how should I solve it?
Thanks.
A:
I guess your program never ends?
when you call communicate() it does different things under different os. But it always waits for the launched process to exit on its own eg. calls p.wait().
p.wait() terminates only if the rocess terminates.
Solutions:
You could copy the source code of subprocess.Popen._communicate and alter it so it does not use wait() but time.sleep and some timeout
You write your own code that reads stdout and stderr and stops if the program outputs too much stderr
You change the main() function of the file that never ands this way
way
def main():
## here is you program code
if __name__ == '__main__':
import thread, sys, time
_id = thread.start_new(main, ())
time.sleep(1)
t = time.time() + 100 # execute maximum 100 + 1 seconds
while t > time.time() and _id in sys._current_frames():
time.sleep(0.001)
If you want to look at the source of subprocess you can find it at subprocess.__file__.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you reference "this" in an Angular2 component template?
I have an Angular2 component:
class A {
filter(..)
}
In the template for A, I have
<.. list | pipe:filter ..>
Inside of pipe I call filter, the problem is I do not have a reference to "this", since JS is dynamically scoped I can't access the instance variables of A inside of filter when I call it. Is there a way to get a "this" reference?
A:
You shouldn't need this. You should be able to call filter() and it should get interpolated without the need for this. But you need to put it in {{ }} i.e.
{{list | pipe:filter()}}
Here's a plunker
| {
"pile_set_name": "StackExchange"
} |
Q:
Insert a space between two variables
I have a problem to add space and comma between two variables:
<td><?php echo '<a href=https://www.google.de/maps/place/
'.$row['ort'].$row['strasse'].' target="_blank">'.$row['ort'].'</a>';?></td>
The results is
BerlinKolnerweg
but I want to insert space and comma like this:
Berlin, Kolnerweg
This does not work:
.$row['ort'].', ' .$row['strasse'].
Can you help me?
A:
I added a space (escaped as %20) and a comma in the url. I moved the php into the anchor-tag instead of echoing out the whole thing. Try if this works:
<a href="https://www.google.de/maps/place/<?php echo $row['ort'].',%20'.$row['strasse']; ?>" target="_blank">
<?php echo $row['ort'].', '.$row['strasse']; ?>
</a>
| {
"pile_set_name": "StackExchange"
} |
Q:
Save/Load jFreechart TimeSeriesCollection chart from XML
I'm working with this exemple wich put rondom dynamic data into a TimeSeriesCollection chart.
My problem is that i can't find how to :
1- Make a track of the old data (of the last hour) when they pass the left boundary (because the data points move from the right to the left ) of the view area just by implementing a horizontal scroll bar.
2- Is XML a good choice to save my data into when i want to have all the history of the data?
public class DynamicDataDemo extends ApplicationFrame {
/** The time series data. */
private TimeSeries series;
/** The most recent value added. */
private double lastValue = 100.0;
public DynamicDataDemo(final String title) {
super(title);
this.series = new TimeSeries("Random Data", Millisecond.class);
final TimeSeriesCollection dataset = new TimeSeriesCollection(this.series);
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
final JPanel content = new JPanel(new BorderLayout());
content.add(chartPanel);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
setContentPane(content);
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart result = ChartFactory.createTimeSeriesChart(
"Dynamic Data Demo",
"Time",
"Value",
dataset,
true,
true,
false
);
final XYPlot plot = result.getXYPlot();
ValueAxis axis = plot.getDomainAxis();
axis.setAutoRange(true);
axis.setFixedAutoRange(60000.0); // 60 seconds
axis = plot.getRangeAxis();
axis.setRange(0.0, 200.0);
return result;
}
public void go() {
final double factor = 0.90 + 0.2 * Math.random();
this.lastValue = this.lastValue * factor;
final Millisecond now = new Millisecond();
System.out.println("Now = " + now.toString());
this.series.add(new Millisecond(), this.lastValue);
}
public static void main(final String[] args) throws InterruptedException {
final DynamicDataDemo demo = new DynamicDataDemo("Dynamic Data Demo");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
while(true){
demo.go();
Thread.currentThread().sleep(1000);
}
}
}
A:
The example uses the default values specified in TimeSeries for the maximum item age and count. You'll want to change them to suit your requirements.
XML is fine, but it's voluminous for high rates; plan accordingly.
See also this example that uses javax.swing.Timer to avoid blocking the event dispatch thread.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to install n on Windows?
I just installed n on my Mac and everything is cool but is not installing on Windows. The process I did on Mac is:
sudo npm install -g n
sudo n 0.12.7
so what is the equivalent of doing that on Windows?
A:
From the documentation:
(Unfortunately n is not supported on Windows yet. If you're able to make it work, send in a pull request!)
So there is no equivalent of doing that on Windows short of forking the source code and figuring out how to make it work.
| {
"pile_set_name": "StackExchange"
} |
Q:
simple if/else form check(should be simple)
simple if/else took a dump on me.....it was working fine(copied from prev proj), made some
changes and now nothing.
i deleted it all and wrote a simple function to check for empty and nothing, the form is still going to next page...and it was JUST working.
so now i make the simplest possible one and so...its still messed up so, what am i missing.
should b simple.
i need a break lol
heres the code.
html:
<form name="mainForm" action="formProc.php" method="get" id="mainForm" onSubmit="return allChecks();" >
<input type="text" name="name" id="name"/>
</form>
js:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
//formVars
var name = $('#name');
function allChecks(){
if(name.val()==""){
alert("lopan");
return false;
}
if(name.val()===""){
alert("lopan");
return false;
}
if(name.val()== null){
alert("lopan");
return false;
}
return false;
}
});
</script>
As you can see...im basically TRYING to force a "false" on the form and it
STILL goes onto the next page.
so dummying it down even further.
i create another button in the form with type="button", declare it and well, this
var btn= $('#clearF');
btn.click(allChecks);
Then this works...so im lost.
edit***
im trying to force a false/prevent from going to next page because, as i was adding validation to the fields, i noticed it went through to next page whether value was true or not...after troubleshooting a while i decided to see why its going to next page by itself...hence the trying to force false and failing the prevent it from going to next page.
***end edit
Any tips/ideas/point out some DUMB thing im doing....dont hesitate to point it out
Thanks in advanced.
A:
allChecks is not 'visible' for your markup. It is inside of $(document).ready() handler. To make it 'visible' just declare it like this:
window.allChecks=function(){
| {
"pile_set_name": "StackExchange"
} |
Q:
Use specific ServiceProvider in Laravel 4
Laravel 4 ships with the php artisan routes command. This shows a list of registered routes on the command line. Instead of showing the registered routes on the command line, I would like to get its values within a controller.
The following method does exactly what I want:
Illuminate\Foundation\Console\RoutesCommand()
Unfortunately this is a protected method, so it doesn't work when I try something like this:
$rc = new Illuminate\Foundation\Console\RoutesCommand(new Illuminate\Routing\Router);
print_r($rc->getRoutes());
How can I access this method to display the registered routes in my Laravel 4 app?
Or even better; how can I access methods of any autoloaded service provider?
A:
You can get all routes like this:
$routes = App::make('router')->getRoutes();
foreach($routes as $name => $route)
{
//do your stuff
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ListView com primeira coluna ultrapassando limite
Olá! Fiz um formulário usando a biblioteca MaterialSkin
Nessa biblioteca há um componente chamado ListView (que seria semelhante ao ListView do WinForms) que a primeira coluna fica bugada. Vejam essa imagem:
O correto seria ficar os três pontinhos assim como na coluna CPF-CNPJ, porém, a primeira coluna fica sobrepondo todas as outras quando tem muitos caracteres. Alguém sabe qual pode ser a solução pra isso?
Edit 1 : De preferência uma forma que não seja simplesmente dar um substring nos caracteres da primeira coluna!!
Edit 2: Estou preenchendo a tabela com o seguinte código:
fornecedores = new Fornecedor().retornaItens(tbFiltro.Text,30);
lstFornecedores.Items.Clear();
foreach (Fornecedor fornecedor in fornecedores)
{
var item = new ListViewItem(new string[ {fornecedor.nome,fornecedor.cpfcnpj,fornecedor.tipoPessoa.ToString(),fornecedor.endereco});
lstFornecedores.Items.Add(item);
}
A:
Consegui resolver! Como a falha era só na primeira coluna, eu criei uma primeira coluna com width de 0 e preenchi com uma string vazia. Assim ele corta automaticamente :)
fornecedores = new Fornecedor().retornaItens(tbFiltro.Text, 30);
lstFornecedores.Items.Clear();
foreach (Fornecedor fornecedor in fornecedores)
{
var item = new ListViewItem(new string[]
{"",fornecedor.nome,fornecedor.cpfcnpj,fornecedor.tipoPessoa.ToString(),fornecedor.endereco});
lstFornecedores.Items.Add(item);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Making horizontal menu to the center of the div
I have tried to make horizontal menu and it succeed. But how to make it to the center of the div as I have tried to put text-align:center, vertical-align:middle, and display:inline. They are not working at all..
First of all, my HTML would be like this below
.nav {
border:1px solid #CCC;
border-width:1px 0;
list-style:none;
margin:0 auto;
padding:20px 0;
width:100%;
text-align: center;
}
ul.nav-menu {
list-style: none;
padding: 0;
font-size: 14px;
line-height: 14px;
font-family: 'latoregular';
margin: 0 auto;
width: 100%;
text-align:center;
}
ul.nav-menu:after {
content: "";
clear: both;
display: block;
overflow: hidden;
visibility: hidden;
width: 0;
height: 0;
}
ul.nav-menu li {
float: left;
margin: 0 0 0 10px;
position: relative;
}
ul.nav-menu li:first-child {
margin: 0;
}
<div class="nav">
<ul class="nav-menu">
<li> <a href="#" class="selected"> HOME </a> </li>
<li> <a href="#"> PORTFOLIO </a> </li>
<li> <a href="#"> BLOG </a> </li>
<li> <a href="#"> CONTACT </a> </li>
</ul>
</div>
And lastly, here is JSFIDDLE.
How to push .nav-menu into the center of the .nav? Any ideas?
A:
Remove the width and add display: inline-block to your ul.nav-menu:
ul.nav-menu {
list-style: none;
padding: 0;
font-size: 14px;
line-height: 14px;
font-family: 'latoregular';
margin: 0 auto;
display: inline-block; // add display: inline-block;
text-align:center;
}
You've already done the rest (setting text-align: center on the parent container).
Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
MBaaS Push: How to send payloads larger than 256 bytes?
With iOS 8, the payload size limit for push notifications has been increased to 2 kilobyes. In an attempt to make use of this with MBaaS Push on Bluemix, I received the following error message: "Bad Request - The notification payload exceeds the maximum size limit ( 256 bytes) allowed for iOS platform." (FPWSE1080)
Is there a way to work around this limitation? If not, are there any plans for MBaaS Push to support the increased payload size?
I need cross-platform support, so using the MobileFirst for iOS Push service is not an option.
A:
This is a current limitation and there are no plans for MBaaS to support the increased payload size.
Apologies for the inconvenience.
| {
"pile_set_name": "StackExchange"
} |
Q:
Exception in SharePoint 2010 Web Service and Other Problems
everyone!
I'm having problems with my SharePoint 2010 installation. I have SP1 + the August 2012 CU and I am running on Windows 7. It's a fresh installation, although I had SP installed previously on my machine, all of the databases and 14 hive files were deleted prior to the new installation.
The problem is the infamous
System.InvalidOperationException: An exception was thrown in a call to a policy export extension.
I was having problems managing all of my service applications (user profile, managed metadata, bcs), and enabled the inclusion of exceptions for the WCF web services. When I directly access http://:32843/SecurityTokenServiceApplication/securitytoken.svc, here's the exception I get:
System.InvalidOperationException: An exception was thrown in a call to a policy export extension.
Extension: System.ServiceModel.Channels.TransportSecurityBindingElement
Error: Security policy export failed. The binding contains a TransportSecurityBindingElement but no transport binding element that implements ITransportTokenAssertionProvider. Policy export for such a binding is not supported. Make sure the transport binding element in the binding implements the ITransportTokenAssertionProvider interface. ----> System.InvalidOperationException: Security policy export failed. The binding contains a TransportSecurityBindingElement but no transport binding element that implements ITransportTokenAssertionProvider. Policy export for such a binding is not supported. Make sure the transport binding element in the binding implements the ITransportTokenAssertionProvider interface.
at System.ServiceModel.Channels.TransportSecurityBindingElement.System.ServiceModel.Description.IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext policyContext)
at System.ServiceModel.Description.MetadataExporter.ExportPolicy(ServiceEndpoint endpoint)
--- End of inner ExceptionDetail stack trace ---
at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleDocumentationRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
at SyncInvokeGet(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
The application pool SharePoint Web Services Root is running as a domain account which is a local administrator. It has access to all of the SP databases.
When I try to manage one of my service applications, for example, bcs, I get this on ULS:
WcfSendRequest: RemoteAddress: 'http://<host>:32843/35a0bc1b97c14b1698ca561f63631ce8/ProfilePropertyService.svc' Channel: 'Microsoft.Office.Server.UserProfiles.IProfilePropertyService' Action: 'http://Microsoft.Office.Server.UserProfiles/GetProfileProperties' MessageId: 'urn:uuid:ac76a7a3-b15b-405b-9c65-1e83f67baddd'
Exception occured while connecting to WCF endpoint: System.ServiceModel.Security.SecurityAccessDeniedException: Access is denied. Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown
at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Office.Server.UserProfiles.IProfilePropertyService.GetProfileProperties()
at Microsoft.Office.Server.UserProfiles.ProfilePropertyServiceClient.<>c__DisplayClass1.<GetProfileProperties>b__0(IProfilePropertyService channel)
at Microsoft.Office.Server.UserProfiles.MossClientBase`1.ExecuteOnChannel(String operationName, CodeBlock codeBlock)
UserProfileApplicationProxy.InitializePropertyCache: Microsoft.Office.Server.UserProfiles.UserProfileException: System.ServiceModel.Security.SecurityAccessDeniedException
at Microsoft.Office.Server.UserProfiles.MossClientBase`1.ExecuteOnChannel(String operationName, CodeBlock codeBlock)
at Microsoft.Office.Server.UserProfiles.ProfilePropertyServiceClient.ExecuteOnChannel(String operationName, CodeBlock codeBlock)
at Microsoft.Office.Server.UserProfiles.ProfilePropertyServiceClient.GetProfileProperties()
at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.RefreshProperties(Guid applicationID)
at Microsoft.Office.Server.Utilities.SPAsyncCache`2.GetValueNow(K key)
at Microsoft.Office.Server.Utilities.SPAsyncCache`2.GetValue(K key, Boolean asynchronous)
at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.InitializePropertyCache()
...
I understand lots of people are complaining about this, but haven't been able to find a solution, and tried most of those described on the Internet.
My current user, as well as the user running the service application pool, are set as administrators for all of the service applications and are also farm administrators.
Also, all services are running, except User Profile Synchronization, which I don't need.
Everything on Central Administration seems to work fine, and I can even manage the Secure Store.
Also, I can't login as the farm administrator, which is the farm account! Normally, when I access Central Administration, it logs me in automatically (as System Account); if I try to login as a different user, and specify it properly (domain\account), it just keeps presenting the login dialog box!
How can I debug this?
A:
I found out. I needed to reinstall SharePoint as stand-alone on my development machine. More information here: http://weblogs.asp.net/ricardoperes/archive/2012/09/19/fixing-sharepoint-2010-permission-problems-on-windows-7.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is frequency equal to the inverse of period?
I am really struggling with this concept, please help. I know that the period is simply the time for 1 for one complete cycle, but how come the frequency is 1 over this? It is confusing to me
A:
Let's clarify your definition of frequency first. Frequency is simply the number of oscillations a body performs in one second. Time period is the time taken for one complete oscillation. As you get 1 oscillation in T seconds, you get 1/T oscillation in 1 second.
| {
"pile_set_name": "StackExchange"
} |
Q:
Designing the structure of a NinJump-like game using J2Me
I'm trying to create a NinJump-like game using J2ME, and I've run into some problems with the animation.
My game built this way:
A thread is started as soon as the game is started. A while loop runs infinitely with a 20ms delay using thread.sleep().
The walls constantly go down - each time the main while loop runs, the walls are animated.
The ninja is animated using a TimerTask with a 30ms interval.
Each time the player jumps, the player sprite is hidden, and another sprite appears, which performs the jump using a TimerTask: 20ms interval, each time the task is executed the sprite advances the its next frame and it also moves (2px each time).
The problem is that when the player jumps, the wall animation suddenly gets slow. Also, the jumping animation is not smooth, and I just can't seem to be able to fix it using different animation time intervals.
I guess there's something wrong in the way I implemented it. How can the problems I mentioned above?
A:
Don't use TimerTask to animate the sprites, do it on the main game loop.
| {
"pile_set_name": "StackExchange"
} |
Q:
`munmap_chunk(): invalid pointer` and SIGABRT in Fortran Fourier transform
For a project in my mater's degree I have to make a program to calculate the Fourier transform of a signal.
I open the data of a .dat file and then I have to use a subroutine to calculate the Fourier transform of my signal and return it in an array. I calculate the real part and the imaginary part of the Fourier transform.
"npts" is the number of points in my sine wave.
"nbft" is the number of frequency of my Fourier transform.
"temps" mean "time" in French.**
"F_reel" if the real part of the Fourier transform.
"F_im" is the imaginary part.
"delta_nu" is the temporal resolution.
"freq" is the frequency.
"signal" is the sine wave value.
I tried to translate the program so you can understand what I try to do.
Everything seems to be fine but I keep getting the error SIGABRT.
I think the problem is in my subroutine, at the step 2 but I am not able to find how to solve the problem.
Here is my code :
program puissance_sinus1_nom
!!!!! MAIN PROGRAM !!!!!
! DECLARATION OF CONSTANTS AND VARIABLES
implicit none
integer :: i, ios=0, npts, nbft
double precision, dimension(:), allocatable :: freq, puis
double precision, dimension(:), allocatable :: temps, signal
! INSTRUCTIONS
! 1. Open the file
open(25, file='sinus1_nom.dat', status='old', &
action='read', iostat=ios)
! 2. Lines count
read(25,*)npts ! The number of points (npts) is indicated
! in the 1st line of the file I open
allocate(temps(npts))
allocate(signal(npts))
write(*,*)" "
do i = 1,npts
read(25,*)temps(i),signal(i)
enddo
if (mod(npts,2) .eq. 0) then
nbft = npts/2 +1
else
nbft = (npts +1)/2
endif
write(*,*)"Number of frequencies :",nbft
write(*,*) " "
write(*,*) " "
! 3. Use of subroutine
allocate(freq(nbft))
allocate(puis(nbft))
call calcul_fourier(npts,signal,temps,nbft,freq,puis)
! Close everything
deallocate(freq)
deallocate(puis)
deallocate(temps)
deallocate(signal)
close(25)
end program puissance_sinus1_nom
!!!!! SUBROUTINE !!!!!
subroutine calcul_fourier(npts,signal,temps,nbft,freq,puis)
! DECLARATION OF VARIABLES
implicit none
integer :: i, k
double precision :: delta_nu, pi=4*atan(1.)
double precision, dimension(nbft) :: F_reel, F_im
integer, intent(in) :: npts, nbft
double precision, dimension(npts), intent(in) :: temps, signal
double precision, dimension(nbft), intent(out) :: freq, puis
! INSTRUCTIONS
! 1. Frequency resolution calculation
delta_nu = (1./temps(npts))*1.d6
write(*,*)"delta_nu = ",delta_nu," micro Hz"
! 2. Calculation of real and imaginary parts of Fourier transform
do k=1, nbft
freq(k) = (k-1)*delta_nu
enddo
do k=0, nbft+1
F_reel(k) = 0
F_im(k) = 0
do i=1, npts
F_reel(k) = F_reel(k) + (2./npts)*signal(i)*cos(2*pi*freq(k)*temps(i))
F_im(k) = F_im(k) + (2./npts)*signal(i)*sin(2*pi*freq(k)*temps(i))
enddo
write(*,*)F_reel(k) ! display to see if it works
enddo
write(*,*) " "
write(*,*) " "
write(*,*) " "
! 3. power calculation (magnitude^2)
do k=1,nbft
puis(k) = F_reel(k)**2 + F_im(k)**2
enddo
end subroutine calcul_fourier
I use write(*,*)F_reel(k) to display the value of the real part of the Fourier transform to check if the program behave correctly, and I am expecting it to return me all the value it calculates.
However, I keep getting this message:
*** Error in `./puissance_sinus1_nom.x': munmap_chunk(): invalid pointer: 0x0000000000e07d10 ***
Program received signal SIGABRT: Process abort signal.
Backtrace for this error:
#0 0x7F4E9392D407
#1 0x7F4E9392DA1E
#2 0x7F4E92E4A0DF
#3 0x7F4E92E4A067
#4 0x7F4E92E4B447
#5 0x7F4E92E881B3
#6 0x7F4E92E8D98D
#7 0x4013A6 in calcul_fourier_
#8 0x401C0A in MAIN__ at puissance_sinus1_nom.f90:?
Abandon
Obviously I am doing something wrong, but I can't see what it is.
Do you have any idea?
A:
Your loop
do k=0, nbft+1
F_reel(k) = 0
F_im(k) = 0
do i=1, npts
F_reel(k) = F_reel(k) + (2./npts)*signal(i)*cos(2*pi*freq(k)*temps(i))
F_im(k) = F_im(k) + (2./npts)*signal(i)*sin(2*pi*freq(k)*temps(i))
enddo
write(*,*)F_reel(k) ! display to see if it works
enddo
accesses indexes 0 and nbft+1, but you arrays are declared from 1 to nbft:
double precision, dimension(nbft) :: F_reel, F_im
That is an error, you cannot access arrays out of bounds.
This error can be found by your compiler. Just enable error checking, use flags such as -Wall -fcheck=all for gfortran or -warn -check for Intel. Consult your compiler's manual.
BTW, computing the Fourier transform from the definition is very inefficient, you should use the Fast Fourier Transform (FFT). There are many libraries you can use.
| {
"pile_set_name": "StackExchange"
} |
Q:
Relativelayout align top and bottom
I would like to align center horizontial & center vertical all 3 buttons as 1 button in my relativelayout!
I used LinearLayout with parameter android:layout_weight, but Buttons's height is modified.
This is my layout file. Thanks!
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Main" >
<Button
android:id="@+id/bt_singleColor"
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_margin="@dimen/button_margin"
android:background="@drawable/button_circle"
android:padding="@dimen/button_padding"
android:text="@string/button_01"
android:textColor="@color/button_text_color" />
<Button
android:id="@+id/bt_shake"
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_below="@+id/bt_singleColor"
android:layout_centerHorizontal="true"
android:layout_margin="@dimen/button_margin"
android:background="@drawable/button_circle"
android:padding="@dimen/button_padding"
android:text="@string/button_02"
android:textColor="@color/button_text_color" />
<Button
android:id="@+id/bt_autoColor"
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_below="@+id/bt_shake"
android:layout_centerHorizontal="true"
android:layout_margin="@dimen/button_margin"
android:background="@drawable/button_circle"
android:padding="@dimen/button_padding"
android:text="@string/button_03"
android:textColor="@color/button_text_color" />
A:
You can use something like
<RelativeLayout to match parent or fill parent>
<LinearLayout with wrap_content and layout centerInParent>
<Button/>
<Button/>
<Button/>
</LinearLayout>
</RelativeLayout>
meaning that the LinearLayout is centered absolutely in the Relative layout and you can play with this alignment if you want something else. While for the Linearlayout you have wrap_content to detect its size based on the buttons size, margin and padding. Also don't forget about orientation for LinearLayout.
| {
"pile_set_name": "StackExchange"
} |
Q:
Postfix AUTH failed for SMTP (ubuntu)
I'm using a webmin with virtualmin setup on a Ubuntu with Postfix and Dovecot for pop, I can recieve messages but not send them, it only works with local php driven mails, when I try to connect to the smtp server I get:
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "***", port 25, isSSL false
220 *** ESMTP Postfix (Ubuntu)
DEBUG SMTP: connected to host "****", port: 25
EHLO localhost
250-****
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH PLAIN DIGEST-MD5 CRAM-MD5 NTLM LOGIN
250-AUTH=PLAIN DIGEST-MD5 CRAM-MD5 NTLM LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "10240000"
DEBUG SMTP: Found extension "VRFY", arg ""
DEBUG SMTP: Found extension "ETRN", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "AUTH", arg "PLAIN DIGEST-MD5 CRAM-MD5 NTLM LOGIN"
DEBUG SMTP: Found extension "AUTH=PLAIN", arg "DIGEST-MD5 CRAM-MD5 NTLM LOGIN"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
535 5.7.8 Error: authentication failed: authentication failure
Authentication Failed
this is my postfix/main.cf
# See /usr/share/postfix/main.cf.dist for a commented, more complete version
# Debian specific: Specifying a file name will cause the first
# line of that file to be used as the name. The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no
# appending .domain is the MUA's job.
append_dot_mydomain = no
# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h
readme_directory = no
# TLS parameters
smtpd_use_tls=no
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.
myhostname = ***
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = ***
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
virtual_alias_maps = hash:/etc/postfix/virtual
smtpd_sasl_auth_enable = yes
smtpd_recipient_restrictions = permit_mynetworks reject_unauth_destination
smtpd_tls_security_level = none
I've been searching for over 7hours now and getting ready to shoot myself so any help is grealty appreciated :)
A:
You didn't configure Postfix to use Dovecot as authentication type. Do it. See the documentation for more information. http://www.postfix.org/postconf.5.html#smtpd_sasl_type
Additional follow the Dovecot Wiki and Postfix manual.
| {
"pile_set_name": "StackExchange"
} |
Q:
What technology/language is needed to put together an Instant messenger - integrated notifier?
My team and I are struggling to put together a notification software to incorporate onto our site, so that users who have added our bot on their IM client (eg. MSN, AIM, Yahoo Messenger) would be able to get alerted when something relevant is relating to them. We'd also need to be able to check to see what their status is (online, offline, busy).
Do you know if this could be done with straight PHP, or what other language would need to come into play to make something like this possible?
Thanks!
Donny
A:
... not sure if I understood you correctly: Do you have already a IM-Bot running? If so, it should provide you the necessary API to get your work done (have a look at the documentation of the bot you are using.)
In case you are actually looking for a bot that may be run on MSN/AIM/Yahoo/etc. I'd recommend to have a look on Bitlbee which is a IRC server that may connect to IM networks. With help of Net_SmartIRC Package from PHP pear you'll be able to connect to it and gather the information you need. Hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Refrescar Página
Tengo esta función que guarda datos de un formulario y al guardar o cancelar, alerta al usuario.
necesito implementar function () {window.location.href = "/Home/TablaSSMN"}si los datos fueron enviados.
No entiendo donde colocarlo
function AlertContactado() {
var form = $("#FormContactado");
var url = form.attr("action");
var data = form.serialize();
swal({
title: "¿Seguro(a) que deseas Guardar?",
text: "¿Realmente que quieres guardar?",
type: "info",
showCancelButton: true,
confirmButtonText: "Si, ¡Guardalo!",
cancelButtonText: "Cancelar",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
$.ajax({
url: url,
type: "POST",
processData: false,
data: data,
contentType: false,
success: function (result) {
swal("¡Hecho!", "Los Datos se han guardado satisfactoriamente", "success");
}
});
} else {
swal("¡Cancelado!", "Usted a cancelado el guardado", "error");
}
});
};
A:
// Codigo anterior
$.ajax({
url: url,
type: "POST",
processData: false,
data: data,
contentType: false,
success: function (result) {
swal("¡Hecho!", "Los Datos se han guardado satisfactoriamente", "success");
// La función setTime, se encarga de ejecutar algo despues de un determinado tiempo
// El primer párametro de esta función es otra función que sera lo que ejecute
// El segundo párametro sera un tiempo en milisegundos, que le indicara cuanto tiempo debe de esperar antes de ejecutar el primer párametro
setTimeout(function () {
window.location.href = "/Home/TablaSSMN";
}, 3000)
}
});
// Código posterior
Puedes leer mas sobre la documentación de
setTimeOut
| {
"pile_set_name": "StackExchange"
} |
Q:
Query that finds objects with ANY TWO association ids (Rails 4)
BACKGROUND: Posts have many Communities through CommunityPosts. I understand the following query returns posts associated with ANY ONE of these community_ids.
Post.joins(:communities).where(communities: { id: [1,2,3] })
OBJECTIVE: I'd like to query for posts associated with ANY TWO community_ids in the array. Having either communities 1 and 2, communities 1 and 3, or communities 2 and 3.
EDIT: Please assume that length of the array is unknown. Used this array of explanation purposes. It will be current_user.community_ids instead of [1,2,3].
A:
This will get you all posts having exactly any two associations from the current user's communities:
Post.select("posts.*, count(distinct(communities.id))").joins(:communities).where("communities.id in (?)", current_user.community_ids).group("posts.id").having("count(distinct(communities.id)) = 2")
Apparently, to relax the restriction, you'll need to change the condition in the having clause to >=.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to identify correct url
I have list of URL in txt file I am using it for performance test, since URL were not formed correctly java.IO.exeption were thrown,I would like to know how to check correctness of URL? and whether it is working fine? I have more than 35 K url checking manually will consume lot's of time.
A:
To check whether URL are properly formed try casting the string to an URI object.
eg:
public void validURLs(List<string> urlList)
{
int line = 1;
for(string s : urlList)
{
try
{
URI test = new URI(s);
}
catch(Exception e)
{
System.err.println(s + " is not a valid URL, item " + line);
}
line ++;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make tableviewcell text editable on touch in iPhone SDK?
In my iPhone app, I have a table view.
I want that when the user selects (or basically touches) on the cell of the tableview then he/she should be able to edit the cell contents.
How can I do that?
A:
@PARTH in order to make your UITableView cells editable i suggest u to give textfields to your cell....
eg:- In
-(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath {
CGRect cellRectangle = CGRectMake (0, 10, 300, 70);
CGRect Field1Frame = CGRectMake (10, 10, 290, 70);
UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:cellRectangle reuseIdentifier:identifier] autorelease];
UITextField *textField;
//Initialize Label with tag 1.
textField = [[UITextField alloc] initWithFrame:Field1Frame];
textField.tag = 1;
[cell.contentView addSubview:textField];
[textField release];
return cell;
}
and in your cellForRowAtIndexPath method // Configure the cell.
UITextField *txtTemp = (UITextField *)[cell.contentView viewWithTag:1];
use this where u want in your tableview accordingly otherwise hide it.....Hope it will help u!!
| {
"pile_set_name": "StackExchange"
} |
Q:
Associate groups or attributes to a SharePoint user
I need to associate some groups or attributes to a SharePoint user and be able to query for those, maybe by using the _vti_bin/UserGroup.asmx or /_vti_bin/UserProfileService.asmx.
Is this possible in SharePoint 2010? I'm thinking about the User Profile Service Application -> Manage User Properties section. Is that the place or is there something easier?
I would think a custom list with the user as a first column and a list of groups/attributes as a second column would be a possible workaround but maybe there's something out of the box?
Could I have those groups read from Active Directory?
A:
To achieve this, You can add custom properties to a user profile . Check this out : http://technet.microsoft.com/en-us/library/cc262327.aspx.
You can also map Active Directory attribute to a user profile property.Check this out : http://technet.microsoft.com/en-us/library/ee721049.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
How to best utilize jQuery to programmatically generate HTML elements
I have a bunch of Javascript functions that look like the following:
function generateBusinessImage (business) {
var business_image = document.createElement('img');
business_image.setAttribute('class','photo');
business_image.alt = business.name;
business_image.title = business.name;
business_image.align = 'right';
business_image.src = business.photo_url;
return business_image;
}
This seems like a good canidate for a refactor. From reviewing a few different jQuery docs, it would appear that I should be able to do something similar to this pseudo code:
return var business_image = document.createElement('img').
setAttribute('class','photo').
alt(business.name).
title(business.title).
align('right').
src(business.photo_url);
Am I on the right track?
Thanks!
EDIT
I'm calling the function above with the following code and the line where I do appendChild on div with generateBusinessImage is where my errors are occurring with some of the answers below:
var div = document.createElement('div');
var div_class = document.createAttribute('class');
div.setAttribute('class','business');
div.appendChild(generateBusinessImage(business));
A:
You can create all that with jQuery via chained calls:
function generateBusinessImage (business) {
return $('<img class="photo" align="right" />')
.attr('alt', business.name)
.attr('title', business.name)
.attr('src', business.photo_url)
.get(0)
}
(Note on the get(0) on the last line: to remain backwards compatible with your existing caller of generateBusinessImage() I return the DOM element jQuery created, by calling .get(0))
References:
jQuery.attr
jQuery.fn.get
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I run AVAssetReader at the same rate on a secondary thread as it does on the main thread?
I have an OpenGL iOS application and am using an AVAssetReader to read frames from a video and texture a simple model with the video content.
Everything is working as expected, except I am using the AVAssetReader on a secondary thread and binding the textures on the main thread. The problem with this is that the video is running very slow, frame by frame.
Is there any way to synchronise the video position with the current time so that it doesn't appear to be going in slow motion?
Extra Info
This is how I read the video (on the secondary thread):
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* fullPath = [[documentsDirectory stringByAppendingPathComponent:@"sample_video.mp4"] retain];
NSString *urlAddress = fullPath;
NSURL *url = [NSURL fileURLWithPath:urlAddress];
AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
NSArray *tracks = [urlAsset tracksWithMediaType:AVMediaTypeVideo];
AVAssetTrack *track = [tracks objectAtIndex:0];
NSDictionary* trackDictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
forKey:(id)kCVPixelBufferPixelFormatTypeKey];
AVAssetReaderTrackOutput *asset_reader_output = [[AVAssetReaderTrackOutput alloc] initWithTrack:track outputSettings:trackDictionary];
AVAssetReader *asset_reader = [[AVAssetReader alloc] initWithAsset:urlAsset error:nil];
[asset_reader addOutput:asset_reader_output];
[asset_reader startReading];
while (asset_reader.status == AVAssetReaderStatusReading){
CMSampleBufferRef sampleBufferRef = [asset_reader_output copyNextSampleBuffer];
if (sampleBufferRef){
[self performSelectorOnMainThread:@selector(bindNewFrame) withObject:nil waitUntilDone:YES];
}
CMSampleBufferInvalidate(sampleBufferRef);
CFRelease(sampleBufferRef);
}
[pool release];
A:
I solved this by moving the content of the while loop in another function then used NSTimer to call that function at a rate of 1.0/track.nominalFrameRate
| {
"pile_set_name": "StackExchange"
} |
Q:
Searchkick results are not relevant
I have a problem with a relevant search. Results of following request are very strange:
Candidate.search('martin', fields: [:first_name, :last_name],
match: :word_start, misspellings: false).map(&:name)
["Kautzer Martina",
"Funk Martin",
"Jaskolski Martin",
"Gutmann Martine",
"Wiegand Martina",
"Schueller Martin",
"Dooley Martin",
"Stiedemann Martine",
"Bartell Martina",
"Gerlach Martine",
"Green Martina",
"Lang Martine",
"Legros Martine",
"Ernser Martina",
"Boehm Martina",
"Green Martine",
"Nolan Martin",
"Schmidt Martin",
"Hoppe Martin",
"Macejkovic Martine",
"Emard Martine"]
Why Martina is going earlier than Martin?
Searckick config:
searchkick language: %w(German English), word_start: [:first_name, :last_name]
A:
Searchkick 1.4 fixes this issue. There's even a test case dedicated to this question :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Apache-Commons Sanselan AIOOBE when decompressing PackBits TIFF
Out-of-the-box ArrayIndexOutOfBoundsException when attempting to use Apache-Commons Sanselan to load a TIFF that was compressed with PackBits compression.
Code:
import org.apache.sanselan.*;
public class TIFFHandler {
public static Image loadTIFF(String fileName) throws ImageReadException, IOException {
File imageFile = new File(fileName);
BufferedImage bi = Sanselan.getBufferedImage(imageFile);
return bi;
}
public static void main(String[] args) throws IOException, ImageReadException {
String TIFFFILE = "test_image.tif";
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
BufferedImage bi = (BufferedImage) loadTIFF(TIFFFILE);
ImageIcon ii = new ImageIcon(bi);
JLabel lbl = new JLabel(ii);
panel.add(lbl);
frame.setVisible(true);
}
}
Stack trace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 426
at org.apache.sanselan.common.PackBits.decompress(PackBits.java:55)
at org.apache.sanselan.formats.tiff.datareaders.DataReader.decompress(DataReader.java:127)
at org.apache.sanselan.formats.tiff.datareaders.DataReaderStrips.readImageData(DataReaderStrips.java:96)
at org.apache.sanselan.formats.tiff.TiffImageParser.getBufferedImage(TiffImageParser.java:505)
at org.apache.sanselan.formats.tiff.TiffDirectory.getTiffImage(TiffDirectory.java:163)
at org.apache.sanselan.formats.tiff.TiffImageParser.getBufferedImage(TiffImageParser.java:441)
at org.apache.sanselan.Sanselan.getBufferedImage(Sanselan.java:1264)
at org.apache.sanselan.Sanselan.getBufferedImage(Sanselan.java:1255)
at TIFFHandler.loadTIFF(FieldSheetHandler.java:42)
at TIFFHandler.main(FieldSheetHandler.java:90)
I've attempted an analysis of the problem, but I'm pretty lost...any directions would be really helpful. TIFF images are a pain in the a**.
A:
You can try the updated version of Commons Imaging from the Apache snapshot repository. The Javadoc is not online yet, you'll have to build it by checking out the code from SVN and running mvn javadoc:javadoc.
If you find more issues or want to suggest an improvement you can file them in JIRA. Also the developers will be happy to help you if you have questions regarding the usage of the API. They await you on the mailing list.
| {
"pile_set_name": "StackExchange"
} |
Q:
image not correctly resized in chrome, compared to Firefox
I have an html page displaying an image.
When the image is larger than the window of the browser, the image is resized (keeping the same ratio) to fit in the window with Firefox.
But with Chrome, the image is compressed
Here is the html code:
<div class="container">
<div class="auto">
<img class="full-width" src="http://laurent.delrocq.free.fr/test/img-1.jpg" />
<div class="absolute">
<img src="http://laurent.delrocq.free.fr/test/left.png" alt="#" class="left">
<img src="http://laurent.delrocq.free.fr/test/right.png" alt="#" class="right">
</div>
</div>
</div>
and the css:
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.container {
text-align: center;
}
.auto {
width:auto;
height:auto;
position:relative;
display:inline-block;
}
.absolute {
position:absolute;
top:0;
left:0;
height:100%;
width:100%;
z-index:2;
}
.left {
position:absolute;
top:50%;
left:15px;
transform: translateY(-50%);
}
.right {
position:absolute;
top:50%;
right:15px;
transform: translateY(-50%);
}
.full-width {
width:auto;
max-width:100%;
max-height: 100vh;
height:100%;
}
How can I change the code so that it works (resize) both on Firefox and Chrome ?
A:
I finally used js to set the correct size of the div according to the size of the image.
html:
<div class='fill-screen'>
<img id="photo" class='make-it-fit' src='https://upload.wikimedia.org/wikipedia/commons/f/f2/Leaning_Tower_of_Pisa.jpg'>
<div id="over_image">
<div class="left">
<a href="https://en.wikipedia.org/wiki/Arrow_(symbol)#/media/File:U%2B2190.svg" style="outline:0">
<img src="http://laurent.delrocq.free.fr/test/left.png" alt="#">
</a>
</div>
<div class="right">
<a href="https://en.wikipedia.org/wiki/Arrow_(symbol)#/media/File:U%2B2192.svg">
<img src="http://laurent.delrocq.free.fr/test/right.png" alt="#">
</a>
</div></div>
</div>
css:
div.fill-screen {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
text-align: center;
}
img.make-it-fit {
max-width: 100%;
max-height: 100%;
}
#over_image {
margin:0px;
padding:0px;
display: inline-block;
text-align: center;
color: #fff;
position: absolute;
height:100%;
background: rgba(0,0,0,.5);
}
.left{
opacity:0;
position:absolute;
width:20%;
height:100%;
}
.left a, .right a{
position: absolute;
top: 50%;
left:50%;
transform: translate(-50%, -50%);
}
.right{
opacity:0;
position:absolute;
margin-left: 80%;
width:20%;
height:100%;
}
.left:hover{
opacity:1;
}
.right:hover{
opacity:1;
}
js:
function resizeDiv()
{
var img = document.getElementById('photo');
var width = img.clientWidth;
var height = img.clientHeight;
var left = img.offsetLeft;
var top = img.offsetTop;
document.getElementById('over_image').style.width= width + 'px';
document.getElementById('over_image').style.height= height + 'px';
document.getElementById('over_image').style.top= top + 'px';
document.getElementById('over_image').style.left= left + 'px';
}
$(document).ready(function() {
resizeDiv();
})
$(window).resize(function() {
resizeDiv();
})
The corresponding jsfiddle is here: https://jsfiddle.net/4kxjt813/
| {
"pile_set_name": "StackExchange"
} |
Q:
eval(): can't assign to function call
Yet another question for my cookie clicker...
Here is the code I made that produces an error:
cps=cps+bcps[buych]
c=c-bprice[buych]
eval(buych)=eval(buych)+1
cps is a variable,
c is a variable,
b1,b2,b3,b4,b5 are variables
buych is a string (Which I get from an input() command)
bcps and bprice are maps (shown below)
bcps = {"b1":'1',
"b2":'5',
"b3":'10',
"b4":'20',
"b5":'25'}
bprice = {"b1":'10',
"b2":'20',
"b3":'30',
"b4":'40',
"b5":'50'}
So, what I'm trying to achieve is:
-Take the input string value, which will be 'b1','b2', 'b3', 'b4', 'b5'
-Increase cps buy it's value within bcps
-Decrease c by it's value within bprice
-Use eval to convert the 'b#' to b#
-Increase b# by 1
When running the script, I do not get error text in the python shell. Instead, I get a pop-up that says "Can't assign to function call". The error is highlighted as the first white space before the eval(). I really don't get this, as I have no functions within the error.
Thanks for reading,
Cookie Monster
A:
eval(buych) is a function call -- you're calling the function eval(). You can only assign to variables, you can't assign to the result of a function.
You need to concatenate the variable into a valid assignment expression, and exec that:
exec(buych + '=' + buych + '+1')
eval is for evaluating expressions, you have to use exec to execute a whole statement.
But if you find yourself needing to do this, you're usually doing something wrong. Instead of computing variable names and expressions, you should use lists or dicts so you can refer to them using an index or key.
| {
"pile_set_name": "StackExchange"
} |
Q:
Maximizing the volume of a box.
Suppose that the paper is 45 cm wide and 60 cm long. how much should you cut from the corners to form the box with maximum capacity, and what would be the width, length and volume of the resulting box?
A:
Imagine cutting an $x$ by $x$ square out of each corner, and turning up the $4$ flaps to form a lidless box.
The height of the box will be $x$. The width will be $45-2x$, and the length $60-2x$.
so the volume $V(x)$ of the box will be given by
$$V(x)=x(45-2x)(60-2x).$$
We want to maximize $V(x)$, where $0\le x\le 45/2$.
To maximize, go through the usual calculus routine. First multiply out the terms in $V(x)$.
Added: Multiply out our expression for $V(x)$. We get $V(x)=4x^3-210x^2+2700x$. Thus $V'(x)=12x^2-420x+2700$. Set this equal to $0$ and solve for $x$. It is convenient but not necessary to first divide through by $12$. We get $x^2-35x+225=0$. Solve using the Quadratic Formula. We get $x=\frac{35\pm\sqrt{325}}{2}$. One of the roots is outside our interval. The endpoints $x=0$ and $x=45/2$ give $0$ volume. So volume is maximized when $x=\frac{35-\sqrt{325}}{2}$.
Now if we want to find the maximum volume, substitute the above value of $x$ in the expression for $V(x)$. The same applies to the length and width of the base. It seems sensible to use a decimal approximation to $x$ in these final calculations.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to assign multiple constants to an array at once, not at the time of declaration?
This is a C# newbie question.
Consider the following array declaration and initialization:
// This declare the array and initialize it with the default values
double[] MyArray = new double[3];
Somewhere in my code, I initialize the array as follows:
MyArray[0] = 1d;
MyArray[1] = 2d;
MyArray[2] = 3d;
I know that I can assign multiple constants at once to the array at the time of declaration as follows:
double[] MyArray = new double[3] {1d, 2d, 3d};
How to do such an initialization but not at the time of declaration in C#?
In VB.NET, it can be done as follow:
Dim MyArray(3) As Double
...
MyArray = {1#, 2#, 3#} ' Assign multiple values at once
Update
The reason why I want to separate between declaration and initialization is that the initialization will be inside a loop.
A:
I know that I can assign multiple constants at once to the array at the time of declaration as follows:
double[] MyArray = new double[3] {1d, 2d, 3d};
This code doesn't really assign all the values at once... it actually does the same thing as this:
double[] MyArray = new double[3];
MyArray[0] = 1d;
MyArray[1] = 2d;
MyArray[2] = 3d;
There's no specific syntax to assign multiple values to an existing array.
If you need to do it in a loop, you can do this:
double[] MyArray = new double[3];
for (int i = 0; i < MyArray.Length; i++)
{
MyArray[i] = i + 1;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is switch statement the same as if statement in this specific code?
I am trying to understand whether a specific switch statement is equivalent to this if statement.
if (killstreak == 1) //If killstreak is 1, give one throwing knife and write Mr. Kniferino on screen.
{
attacker.GiveWeapon("throwingknife_mp");
attacker.Call("iprintlnBold", "^2Mr. Kniferino");
attacker.SetPerk("specialty_scavenger", true, false);
}
if (killstreak == 2) //If killstreak is 3, give 10 bullets and write You've received 10 bullets on screen.
{
attacker.Call("setweaponammoclip", "iw5_fnfiveseven_mp_tactical", 8);
attacker.Call("setweaponammostock", "iw5_fnfiveseven_mp_tactical", 0);
attacker.Call("iprintlnBold", "^2You've received 10 ^1bullets");
}
if (killstreak == 3) //If killstreak is 2, give Scavenger and write Scavenger on screen.
{
AfterDelay(10, () =>
attacker.SetPerk("specialty_scavenger", true, true));
attacker.Call("iprintlnBold", "^4Scavenger");
}
So would this if statement be equivalent to this switch statement?
switch (killstreak)
{
case 1:
attacker.GiveWeapon("throwingknife_mp");
attacker.Call("iprintlnBold", "^2Mr. Kniferino");
attacker.SetPerk("specialty_scavenger", true, false);
break;
case 2:
attacker.Call("setweaponammoclip", "iw5_fnfiveseven_mp_tactical", 8);
attacker.Call("setweaponammostock", "iw5_fnfiveseven_mp_tactical", 0);
attacker.Call("iprintlnBold", "^2You've received 10 ^1bullets");
break;
case 3:
AfterDelay(10, () =>
attacker.SetPerk("specialty_scavenger", true, true));
attacker.Call("iprintlnBold", "^4Scavenger");
break;
}
If something isn't clear, I'll happily explain again.
A:
Almost, but not quite. The outcome in your case will be the same (so you could say that they are different ways of achieving the same logic). The difference is that your if statement tests would all be executed, while the switch would only evaluate once, than branch to the appropriate case.
You could add else statements to terminate early but still there is a fundamental difference between switch statements and if/else chains. The latter give you more flexibility, while the switch could technically, be optimized by the compiler into a branch table, and the condition (if it's an expression) will only be evaluated once.
This would be more like a switch statement but still, not exactly the same:
if (killstreak == 1)
{
/* case 1 */
}
else if (killstreak == 2) // only tested if killstreak != 1
{
/* case 2 */
}
else if (killstreak == 3) // only tested if killstreak != 1 and != 2
{
/* case 3 */
}
But as I said, this is still not entirely the same. A switch statement may be translated by the compiler into equivalent code to the if/else chain above, but it could be translated into a lookup table too, something more like this:
BranchTable = [CASE1_ADDR, CASE2_ADDR, CASE3_ADDR]
goto BranchTable[killstreak]
CASE1_ADDR:
/* code for test 1*/
goto AFTER_SWITCH_ADDR;
CASE2_ADDR:
/* code for test 2*/
goto AFTER_SWITCH_ADDR;
CASE3_ADDR:
/* code for test 3*/
AFTER_SWITCH_ADDR:
/* code following swtich statement */
| {
"pile_set_name": "StackExchange"
} |
Q:
What do certain item attributes in Dungeon Siege 3 mean?
In Dungeon Siege 3 certain items have enhancements and there is no indication about what they actually do.
I'm specifically curious about these qualities:
Retribution
Bloodletting
Doom
Warding
Vampire
Weakening
Withering
Momentum
Stagger
How are these properties affecting my game play? Other traits are self-explanatory (blocking, agility, armor) but the ones mentioned above have totally eluded me.
A:
These effects are described in the help topics (if you hit esc, then choose Help Topics). Basically they just affect combat damage in various ways. Specifically:
Retribution: sometimes damages the attacker when you get hit
Bloodletting: sometimes causes bleeding when you hit enemies
Doom: increases critical strike damage (I think)
Warding: I checked this; it provides a chance to stun enemies that hit you.
Sure excited for this game to be out for real though!
A:
Most (not all) of these are worthless in a couple aspects:
An effect that has a "low chance" is pretty worthless I'd imagine, since the chance doesn't change. It's not like there is an instant death effect or anything, to which a low chance would still be effective. Also, "low damage" would be bad too. Speaking of which, it's hard to imagine how there is low/moderate/high damage, but at the same time, the amount you have of that effect determines its damage. So I guess if you have 50 of something, but it's defined as "low damage", I guess that means that 50 is more like 10, for instance; it's like a modifier of the amount you have I guess.
These descriptions of these effects (along with many other things) don't tell you much at all about exactly how much damage they do, or their duration/chance sometimes. You could have a sword that has 50 lightning damage, but for all we know, that's equal to about 5 DPS at a certain point in the game (which further complicates things). This game does a horrible horrible job at giving you anything more than a vague description. I mean how the hell did the game designers let descriptions like this get by: "Each time Anjali is hit, there is a 3% chance per rank that her attacker will suffer a burning over time effect." A "burning over time effect" means nothing in that wording. Nothing.
So with that said, unless it's one of the 2-3 stats that we know works good (like Vampire), or it's really obvious, just stick with the basic stats.
| {
"pile_set_name": "StackExchange"
} |
Q:
Deckset app alternative
Mac OSX have a good app called deckset http://decksetapp.com/.
This app make slides from markdown text....
Someone know an alternative for ubuntu?
A:
You might want to check remark.js.
It's not as easy to use as DeckSet but it does the job pretty well.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to tell if a Java application was started by WebStart
Our app has 3 ways to launch...
Applet in a web-page
Desktop application
WebStart
WebStart currently launches the applet but we prefer it to launch the desktop class instead. However, the desktop version expects all resources to be there already whereas WebStart should download resources like an applet.
Specific code in each case is not the problem, but figuring out which way the app was launched is... we don't want to try downloading content for the full desktop application.
A:
Some ideas:
Set a property in the JNLP files to indicate it is JWS.
Do a try/catch on loading one of the JNLP API classes. They will not be on the run-time class-path of the 'naked' desk-top app., but will for the apps. launched by JWS. Some examples of loading the JNLP API classes can be seen in these demos.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is Powershell not recognizing System.Data inside Add_Type block?
I am trying to write a PS script that will open a stored proc, pass parameters and execute that proc, then output the data to a DataSet. That all seems to work, but whern I try to create a .NET object inside an Add-Type block, I get the error:
The type or namespace 'Data' does not exist in the namespace 'System'
(are you missing an assembly reference?)
Here's the code:
Add-Type @'
using System.Data;
using System.Collections.Generic;
public class TestObject
{...}
'@
The part that's really confusing me is that I create a DataSet in another part of the code, outside of the .NET class, and the reference to System.Data.DataSet works fine.
Any thoughts on this are greatly appreciated.
A:
You need to add System.Data to the -ReferencedAssemblies parameter of Add-Type
| {
"pile_set_name": "StackExchange"
} |
Q:
Installing and running 2048 game on android device for offline playing.
I am trying to run 2048 game's android version at github (https://github.com/uberspot/2048-android ), for offline playing, but the game wont load correctly on a nexus-5 device. I have cloned the git and have a local copy saved on disk. After importing it as a local GIT project in eclipse, it compiles without any error but the game does not load correctly in the webview when testing it on device. Plain html content is displayed but the grid of tiles is absent.
Please share the correct way to import this git project into eclipse adt and the changes to be done in code in order to run it correctly.
A:
There is an APK file on the root of the repository.
Download it and then install it on your device :
adb install ~/Download/2048.apk
It works on my Nexus 4 !
| {
"pile_set_name": "StackExchange"
} |
Q:
Splitting PDF file into single pages using PyPDF2
I'm trying to split a 3 page PDF into 3 separate PDF files. I have been trying to use the following code:
from PyPDF2 import PdfFileReader, PdfFileWriter
pdf_file = open('Sample.pdf','rb')
pdf_reader = PdfFileReader(pdf_file)
pdf_writer = PdfFileWriter()
pageNumbers = pdf_reader.getNumPages()
for i in range (pageNumbers):
pdf_writer.addPage(pdf_reader.getPage(i))
split_motive = open('Sample_' + str(i+1) + '.pdf','wb')
pdf_writer.write(split_motive)
split_motive.close()
pdf_file.close()
But that always seems to generate 3 PDF files:
The first page of the source PDF
The first and second page of the source PDF
The first, second and third page of the source PDF
Can anyone help?
A:
Move pdf_writer = PdfFileWriter() into the loop body.
from PyPDF2 import PdfFileReader, PdfFileWriter
pdf_file = open('Sample.pdf','rb')
pdf_reader = PdfFileReader(pdf_file)
pageNumbers = pdf_reader.getNumPages()
for i in range (pageNumbers):
pdf_writer = PdfFileWriter()
pdf_writer.addPage(pdf_reader.getPage(i))
split_motive = open('Sample_' + str(i+1) + '.pdf','wb')
pdf_writer.write(split_motive)
split_motive.close()
pdf_file.close()
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I fix stuttering and lag issues in Deus Ex HR Director's Cut?
Just got this game of the sale, looking forward to playing it.
Unfortunately, I've received massive stutering and lag issues. I have a pretty amazing gaming rig, as I can run BL2, AC4 at max to high settings with no stutter. So this shouldn't be an issue for me.
From what I can tell online, there's also very few solutions out there. One of the options was to edit registry settings, but that doesn't change a thing still.
Any way I can optimize the game to remove this "lag"? It's plenty annoying, and the problem doesnt seem to go away even when I lower the settings down to nothing.
A:
Assuming you have a NVidia graphics card (which is what normally causes this problem) you can make the following registry change to resolve this issue:
Open the Windows registry editor:
Open the Start Menu
Type in regedit.exe
For the original release:
Go to HKEY_CURRENT_USER\Software\Eidos\Deus Ex: HR
For the Director's Cut:
Go to HKEY_CURRENT_USER\Software\Eidos\Deus Ex: HRDC for Director's Cut
Change this value to 1 to disable graphics optimisations:
Set D3D11_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS to 1
Alternatively, if the above doesn't resolve the issue for you, you can also try setting the following values as well - this should work regardless of graphics card vendor;
In HKEY_CURRENT_USER\Software\Eidos\Deus Ex: HRDC, locate AllowJobStealing and set it to 0
Finally, specifically for owners of NVidia graphics cards;
In HKEY_CURRENT_USER\Software\Eidos\Deus Ex: HRDC\Graphics, locate AtiForceFetch4 and set it to 0
For the original release of Deus Ex: Human Revolution, change the above registry keys from HKEY_CURRENT_USER\Software\Eidos\Deus Ex: HRDC to HKEY_CURRENT_USER\Software\Eidos\Deus Ex: HR.
| {
"pile_set_name": "StackExchange"
} |
Q:
Volume of overlap between two convex polyhedra
I have two convex polyhedra represented by triangle meshes. I can easily determine if they are in contact or not, but when they are in contact then I would like to determine the volume of their overlap.
I suspect it may involve doing edge/triangle intersection tests, recording points from intersections when found, then generating a convex hull from those points and determining its volume.
If anyone knows of an existing method for this, it would be much appreciated! I already have methods for determining things like minimum distance needed for separation.
A:
There is software that will compute the intersection (or union) of two closed triangle meshes as another closed triangle mesh. In fact, I wrote a program that reliably computes arbitrary triangle mesh intersections and unions.
Once you have a closed triangle mesh of the intersection region, there is in fact a very nice formula for the volume. The formula is obtained by using the divergence theorem:
$$
\int\int\int_V (\nabla\cdot\mathbf{F}) \operatorname{d}\!V = \int\int_S (\mathbf{F}\cdot \mathbf{n}) \operatorname{d}\!A \tag{1}
$$
where $\mathbf{F}:\mathbb{R}^3\rightarrow\mathbb{R}^3$ is any $C^1$ vector field and $\mathbf{n}$ is the exterior pointing unit surface normal. Define $\mathbf{F}(x,y,z) = (x,y,z)$. Then the left side of $(1)$ is just $3V$ (three times the volume of the region enclosed by the mesh). To compute the surface integral for a single triangle $ABC$, the barycentric coordinates surface parameterization works very well. The barycentric coordinates for $A$ are $(u,v)=(1,0)$, for $B$ they are $(u,v)=(0,1)$ and for $C$ $(0,0).$ Barycentric coordinates map $(u,v)$ to $(x,y,z)$ like this:
$$
(x,y,z) = uA + vB + (1-u-v)C = u(A-C) + v(B-C) + C. \tag{2}
$$
Since $\mathbf{n}$ is orthogonal to all vectors in the plane of the triangle, $\mathbf{F}\cdot \mathbf{n}$ is very easy to compute: it's just $C\cdot\mathbf{n}$ or equivalently $A\cdot\mathbf{n}$ or $B\cdot\mathbf{n}$ since $(A-C)\cdot\mathbf{n} = (B-C)\cdot\mathbf{n} = 0.$ Using $(2)$ it is easy to compute $\mathbf{x}_u = A-C$ and $\mathbf{x}_v = B-C.$ So the surface integral is
$$
\begin{align}
\int\int_S (\mathbf{F}\cdot \mathbf{n}) \operatorname{d}\!A &= \int_0^1\int_0^{1-v} (C\cdot\mathbf{n}) |(A-C) \times (B-C)| \operatorname{d}\!u \operatorname{d}\!v \\
& = (C\cdot \mathbf{n})|(A-C) \times (B-C)| / 2 \\
& = (C\cdot ((A-C)\times (B-C))) / 2.
\end{align}
$$
The last equality above is true since $\mathbf{n} = ((A-C)\times (B-C)) / |(A-C)\times (B-C))|.$ So the formula for the volume of a closed triangle mesh is just
$$
V = \frac{1}{6}\sum_{i=1}^N (C_i\cdot ((A_i - C_i)\times (B_i - C_i))) \tag{3}
$$
where $A_i$, $B_i$, and $C_i$ are the vertices of the $i$th triangle of the mesh and $N$ is the number of triangles in the mesh.
I use the formula $(3)$ all the time. You could test it on some sphere meshes. Just make sure that the face vertex order is consistent and produces an exterior facing normal. This means that if a triangle of your mesh is parallel to the screen and the exterior pointing normal pointing directly at you, the vertices $A$, $B$, and $C$ of the triangle must have counter-clockwise orientation.
| {
"pile_set_name": "StackExchange"
} |
Q:
radio buttons misbehaving when another tkinter is open
While using Python Tkinter, why does an open window change the behaviour of the radio buttons in some other window?
#!/usr/bin/env python3
import tkinter as tk
def close_button():
raise SystemExit
# open first window
root1 = tk.Tk()
# open second window and display radio buttons
root2 = tk.Tk()
root2.protocol('WM_DELETE_WINDOW', close_button)
var = tk.IntVar()
var.set(1)
tk.Radiobutton(root2, variable = var, value = 1).pack()
tk.Radiobutton(root2, variable = var, value = 2).pack()
tk.Radiobutton(root2, variable = var, value = 3).pack()
tk.Button(root2, text = 'print selection', command = lambda : print(var.get())).pack()
root1.mainloop()
root2.mainloop()
This program opens the two windows corresponding to root1 and root2. Here's what the second window looks like.
The grey dots vanish if I click on any of the radio buttons, as seen below.
However, clicking the print selection button prints '1', irrespective of the selection!
On the other hand, if root1 is not created, the radio buttons do not misbehave.
Clicking on print selection prints the correct value: '1', '2' or '3', depending on which of the three is selected.
So, my question is: why are the radio buttons of root2 misbehaving when there is another window root1 open? (I am using classes in my program, but I have stripped it down to the bare minimum in this example.)
Writing the root1.mainloop() statement immediately below root1 = tk.Tk() is not an option because my application needs to have both windows open simultaneously.
A:
You never use Tk() twice in an application. Instead you need to use a single root window with Tk() and for every new window after that you need to use Toplevel().
Do this instead:
#!/usr/bin/env python3
import tkinter as tk
def close_button():
raise SystemExit
root = tk.Tk()
top = tk.Toplevel(root)
top.protocol('WM_DELETE_WINDOW', close_button)
var = tk.IntVar()
var.set(1)
tk.Radiobutton(top, variable=var, value=1).pack()
tk.Radiobutton(top, variable=var, value=2).pack()
tk.Radiobutton(top, variable=var, value=3).pack()
tk.Button(top, text='print selection', command=lambda : print(var.get())).pack()
root.mainloop()
| {
"pile_set_name": "StackExchange"
} |
Q:
CMake error: ROOT should be built as an out of source build
I am trying to build the project ROOT. There is a command to build using cmake ../root. Whenever, I try to run this command it gives me this error:
Harshits-Air:root harshitprasad$ cmake ../root
-- Found a Mac OS X System 10.13
-- Found a 64bit system
-- Found LLVM compiler collection
-- ROOT Platform: macosx
-- ROOT Architecture: macosx64
-- Build Type: RelWithDebInfo
-- Compiler Flags: -Wc++11-narrowing -Wsign-compare -Wsometimes-uninitialized -Wconditional-uninitialized -Wheader-guard -Warray-bounds -Wcomment -Wtautological-compare -Wstrncat-size -Wloop-analysis -Wbool-conversion -m64 -pipe -W -Wshadow -Wall -Woverloaded-virtual -fsigned-char -fno-common -Qunused-arguments -pthread -std=c++11 -stdlib=libc++ -O2 -g -DNDEBUG
CMake Error at cmake/modules/RootNewMacros.cmake:1041 (message):
ROOT should be built as an out of source build, to keep the source
directory clean. Please create a extra build directory and run the command
'cmake <path_to_source_dir>' in this newly created directory. You have
also to delete the directory CMakeFiles and the file CMakeCache.txt in the
source directory. Otherwise cmake will complain even if you run it from an
out-of-source directory.
Call Stack (most recent call first):
CMakeLists.txt:107 (ROOT_CHECK_OUT_OF_SOURCE_BUILD)
I'm not able to understand what this error means? It would be great if anyone can help me out with this issue. Thanks!
A:
The error message simply tells you to create an additional build folder e.g. build next to the ROOT project folder root, change to this directory and call cmake ../root from there.
TLDR; To simply call the following sequence starting from the root folder:
cd ..
mkdir build
cd build
cmake ../root
| {
"pile_set_name": "StackExchange"
} |
Q:
Processing Semicolon on Command line
I have two batch files which is used to run a large C++ build, the first one starts the processes, creating directories and figuring out what to send to the second script. If certain information is presented to the first script, I have a routine that pops up a window and asks for a password. This is passed to the second script by calling the second script like this
call script2.bat -pw:myPassword
where myPassword is something the user entered.
now, i have been testing this script and one of my users password contains a semicolon, so we get this
call script2.bat -pw:my;Password
I found by putting in quotes I can get this into the second script OK
call script2.bat -pw:"my;Password"
However, the command line parsing breaks when I try to do this
for /F "tokens=1,2 delims=:" %%a in ( "%1" ) DO SET switch=%%a&value=%%b
if I echo %1 it shows like this
-pw:"my;Password"
But with echo on when the script runs I see
for /F "tokens=1,2 delims=:" %%a in ( "-pw:"my Password"" ) DO SET switch=%%a&value=%%b
and it parses as switch=-pw and value="my
What I eventually need is for value to contain my;Password so I can pass it to another program
Any ideas on how to get this to parse correctly
Here re 2 batch file that issulstrate the problem:
a.bat:
echo on
call b.bat -pw:eatme
call b.bat -pw:eat;me
call b.bat -pw:"eat;me"
call "b.bat -pw:\"eat;me\""
b.bat:
echo on
echo %1
for /F "tokens=1,2 delims=: " %%a in ( "%1" ) DO SET switch=%%a&SET value=%%b
echo switch=%switch%
echo value=%value%
A:
I found a little trick to get around the way the shell is interpreting the value of "%1" in the FOR /F loop: instead of parsing the string, parse the output of the command ECHO %1, like this:
FOR /F "tokens=1,2 delims=:" %%a IN ( 'ECHO %1' ) DO ECHO Switch: %%a Value: %%b
This works if you put the password in quotes on the command line (call script2.bat -pw="my;password"), so we'll have to remove the quotes as follows:
SET VALUE=%VALUE:~1,-1%
So this is the code I came up with:
ECHO OFF
ECHO Arguments: %1
FOR /F "tokens=1,2 delims=:" %%a IN ( 'ECHO %1' ) DO (
SET SWITCH=%%a
SET VALUE=%%b
)
ECHO SWITCH: %SWITCH%
SET VALUE=%VALUE:~1,-1%
ECHO VALUE: %VALUE%
...which returns the following results:
Arugments: -pw:"my;Password"
SWITCH: -pw
VALUE: my;Password
A:
Try escaping the ; with a ^.
call script2.bat "-pw:my^;Password"
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot find Mercurial global configuration file on osx
I am new to Bitbucket. I am trying to setup my computer to access Bitbucket using the following instructions. On Step 5, I am told to add ssh = ssh -C to file ~/.hgrc. I can't seem to find the file. Has anyone done this step successfully? How do I go about it?
A:
It seems you don't have Mercurial installed at all. Step 3 of Bitbucket tutorial gives detailed description how to install it from MacPorts.
Once you have Mercurial installed just create .hgrc manually and add your configuration.
| {
"pile_set_name": "StackExchange"
} |
Q:
if-statement Indentation not working emacs
I am new to emacs. I have been using this configuration for emacs:
(setq column-number-mode t)
(setq c-default-style "linux"
c-basic-offset 4)
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(custom-enabled-themes (quote (wheatgrass))))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
Generally, the indentation is correctly handled by emacs automatically. For an if-statement, however, even if I could see the correct indentation in emacs then in an other editor the tab is not shown.
I have been editing a *.c file and the mode is "C/l mode defined in ‘cc-mode.el’. Major mode for editing C code".
Here an example:
If I create an c file in emacs with the following code:
int main() {
int x = 1;
if (x > 0)
x++;
else
x--;
printf("Value of x: %d\n", x);
return 0;
}
If I visualize this code in different editor or I copy it from an emacs into another editor the output is the following:
int main() {
int x = 1;
if (x > 0)
x++;
else
x--;
printf("Value of x: %d\n", x);
return 0;
}
Basically, it seems that even if it looks like it is correctly indenting the if statement it has not added any tab character in the if statement.
What is the problem? How could I fix it?
A:
Emacs is mixing tabs and spaces for indentation, and your other editor is using a different tab width.
Looking at your examples I can ascertain that in Emacs tab-width is 8, c-basic-offset is 4, and indent-tabs-mode is t.
If we prefix the number of spaces (s) and/or tabs (t) needed with that configuration:
0 |int main() {
4s| int x = 1;
|
4s| if (x > 0)
1t| x++;
4s| else
1t| x--;
|
4s| printf("Value of x: %d\n", x);
|
4s| return 0;
0 |}
In your other editor your tab width is obviously equivalent to only 4 spaces, and hence "4s" and "1t" are displayed as the same width.
If you M-x set-variable RET tab-width RET 4 RET in Emacs, you will see the same thing.
n.b. M-x whitespace-mode can visualise the indentation characters for you.
For best cross-editor compatibility, either use only spaces for indentation -- indent-tabs-mode set to nil -- or if you prefer tabs then you should ensure that tab-width and c-basic-offset are the same value, which means that every level of indentation will be a tab (at least in languages where indentation is by some specific amount, as opposed to aligning with arbitrary other code).
It seems that you do want tabs, so try this configuration:
(add-hook 'c-mode-hook 'my-c-mode-hook)
(defun my-c-mode-hook ()
"Custom `c-mode' behaviours."
(setq c-basic-offset 4)
(setq tab-width c-basic-offset)
(setq indent-tabs-mode t))
If you were going with spaces-only then you would just disable indent-tabs-mode:
(add-hook 'c-mode-hook 'my-c-mode-hook)
(defun my-c-mode-hook ()
"Custom `c-mode' behaviours."
(setq indent-tabs-mode nil))
Or you could disable it by default, rather than for a specific major mode. indent-tabs-mode is always a buffer-local value, but if you change its default value then that will affect all future buffers in which it isn't set explicitly:
(setq-default indent-tabs-mode nil)
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing order of integration for the triple integral $ \int\limits_{0}^{2} \int\limits_{0}^{2z} \int\limits_{y}^{2y} f_{(x,y,z)}\; dx\, dy\, dz $
I need to change order of integration for the following triple integral:
$$
\int\limits_{0}^{2}
\int\limits_{0}^{2z}
\int\limits_{y}^{2y}
f_{(x,y,z)}\; dx\, dy\, dz
$$
The domain of integration is graphically described in the following images:
Y-Z plane
X-Y plane
By setting $f_{(x,y,z)} = 1$, I verified my results, comparing them to the original integral using WA, which yields $\frac{16}{3} \cong 5.33$.
The requirement
What I'm trying to do is to change the order of integration, so that:
The volume will be projected onto the X-Z plane
Having x to be a function of z (or vice versa - z a function of x).
But I can't find a relation between them.
My accomplishments
I succeeded in converting the given integral to the following equivalents:
Volume projected onto the Z-X plane ($dz\, dx\, dy$)
This requires the limits of y to be scalars.
$$
\int\limits_{0}^{4}
\int\limits_{y}^{2y}
\int\limits_{\frac{y}{2}}^{2}
f_{(x,y,z)}\; dz\, dx\, dy
$$
WA's result.
Volume projected onto the X-Z plane ($dx\, dz\, dy$)
$$
\int\limits_{0}^{4}
\int\limits_{\frac{y}{2}}^{2}
\int\limits_{y}^{2y}
f_{(x,y,z)}\; dx\, dz\, dy
$$
WA's result.
Volume projected onto the Z-Y plane ($dz\, dy\, dx$)
$$
\int\limits_{0}^{4}
\int\limits_{\frac{x}{2}}^{x}
\int\limits_{\frac{y}{2}}^{2}
f_{(x,y,z)}\; dz\, dy\, dx
+
\int\limits_{4}^{8}
\int\limits_{\frac{x}{2}}^{4}
\int\limits_{\frac{y}{2}}^{2}
f_{(x,y,z)}\; dz\, dy\, dx
$$
WA's result for 1st integral and WA's result for 2nd integral.
A:
Here we have a 3D picture of the entire region ($x$ horizontal, $y$ depth, $z$ height):
In blue we see the $x$-$y$ plane, while the pink part stretches both through the $y$-$z$ plane and the $x$-$y$ plane. This side is determined by the equation $x = y$, so the image can be a bit off-putting. Suppose we cut at $y = 2$, then we obtain:
Here we see what's going on: for fixed $y$, our 3D shape actually is a square! In other words: given $y$, the dependence of $z$ on $x$ or vice versa is utterly trivial: the bounds do not change with varying $z$ or $x$.
This is of course already implied by the equations we obtained, but it's probably more convincing to see this actually happening. I hope that clears the air for you.
The images are courtesy of Mathematica 8's RegionPlot3D command:
RegionPlot3D[
y <= x <= 2 y && 0 <= y <= 2 z && 0 <= z <= 2, {x, 0, 8}, {y, 0,
8}, {z, 0, 2}, Mesh -> None, PlotPoints -> 200]
RegionPlot3D[
y <= x <= 2 y && 2 <= y <= 2 z && 0 <= z <= 2, {x, 0, 8}, {y, 0,
8}, {z, 0, 2}, Mesh -> None, PlotPoints -> 200]
| {
"pile_set_name": "StackExchange"
} |
Q:
I Have an issue while map the shoppingcart items. Getting this error TS2339: Property 'items' does not exist on type 'unknown'
shopping-cart.service.ts
import { Product } from 'shared/models/product';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/map';
import { take } from 'rxjs/operators';
import { ShoppingCart } from 'shared/models/shopping-cart';
import { Observable } from 'rxjs';
@Injectable()
export class ShoppingCartService {
constructor(private db: AngularFireDatabase) {}
async getCart(): Promise<Observable<ShoppingCart>> {
const cartId = await this.getOrCreateCartId();
return this.db
.object('/shopping-carts/' + cartId)
.map(x => new ShoppingCart(x.items)); **// Getting error at x.items **
}
async addToCart(product: Product) {
this.updateItem(product, 1);
}
I am getting this error
error TS2339: Property 'items' does not exist on type 'unknown'
A:
You don't have a type on x. By default implicit 'any' type is not allow.
So you have 3 choices you can use [] notation, you can set the type to any
.map((x:any) => new ShoppingCart(x.items));
or type it
interface CartResponse {
items:Array;
}
.map((x:CartResponse) => new ShoppingCart(x.items));
| {
"pile_set_name": "StackExchange"
} |
Q:
What happens to the reviews that people write for journal articles after they're sent back to the author?
Are they almost always kept confidential? Or is there protocol for sharing them?
A:
In my experience, the contents of the comments of other referee reports are only made indirectly available. Since the authors are normally expected to provide a response to the reviews, the relevant criticisms and comments of the other referees are typically mentioned or discussed in that document. Outside of that, however, there's often little direct sharing of referee reports. None of the eight or nine journals for which I've reviewed (physics, chemistry, chemical engineering) have allowed me to see directly the reviews submitted by the other referees.
At any rate, the results are almost always kept confidential, unless it is an "open" referee process by design. (There are a few journals now that make the refereeing process a part of the publication record for a given paper; an example is The Cryosphere.)
A:
Some journals/conferences have explicit guidelines that tell you to treat the reviews confidential. I'm not aware of any journal that makes the reviews and authors' response publically available when a paper is published.
I think publishing reviews for your papers would in general be frowned upon, even if there's no explicit rule saying that you can't. That said, I've been wondering about that myself and we had discussions about it at our school because the quality of some reviews is very bad and making them public might help improve the quality of peer reviewing in the long term.
I personally try to write reviews in a way that I wouldn't object to them being published with my name on it (although all the reviews I've done so far have been anonymous).
| {
"pile_set_name": "StackExchange"
} |
Q:
Does GLPK have any option for making a small fractional to 0
I am using GLPK for solving a minimization linear programming problem in octave. its giving me some variable values like 0.0000000000277 or 0.999999999999. I want to get that 0.0000000000277 as 0 and that 0.999999999999 as 1. Does GLPK has any option for doing this? Any help will be really appreciated.
A:
GLPK has an option called Solution Rounding which you can set to round off tiny values 0. Look for Solution Rounding among these options in GLPK.
However, for other values you will have to do a bit of post-processing by writing some code.
If 0.9 < x < 1.1, set x = 1 etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
python - Using pandas structures with large csv(iterate and chunksize)
I have a large csv file, about 600mb with 11 million rows and I want to create statistical data like pivots, histograms, graphs etc. Obviously trying to just to read it normally:
df = pd.read_csv('Check400_900.csv', sep='\t')
doesn't work so I found iterate and chunksize in a similar post so I used
df = pd.read_csv('Check1_900.csv', sep='\t', iterator=True, chunksize=1000)
All good, i can for example print df.get_chunk(5) and search the whole file with just
for chunk in df:
print chunk
My problem is I don't know how to use stuff like these below for the whole df and not for just one chunk
plt.plot()
print df.head()
print df.describe()
print df.dtypes
customer_group3 = df.groupby('UserID')
y3 = customer_group.size()
I hope my question is not so confusing
A:
Solution, if need create one big DataFrame if need processes all data at once (what is possible, but not recommended):
Then use concat for all chunks to df, because type of output of function:
df = pd.read_csv('Check1_900.csv', sep='\t', iterator=True, chunksize=1000)
isn't dataframe, but pandas.io.parsers.TextFileReader - source.
tp = pd.read_csv('Check1_900.csv', sep='\t', iterator=True, chunksize=1000)
print tp
#<pandas.io.parsers.TextFileReader object at 0x00000000150E0048>
df = pd.concat(tp, ignore_index=True)
I think is necessary add parameter ignore index to function concat, because avoiding duplicity of indexes.
EDIT:
But if want working with large data like aggregating, much better is use dask, because it provides advanced parallelism.
A:
You do not need concat here. It's exactly like writing sum(map(list, grouper(tup, 1000))) instead of list(tup). The only thing iterator and chunksize=1000 does is to give you a reader object that iterates 1000-row DataFrames instead of reading the whole thing. If you want the whole thing at once, just don't use those parameters.
But if reading the whole file into memory at once is too expensive (e.g., takes so much memory that you get a MemoryError, or slow your system to a crawl by throwing it into swap hell), that's exactly what chunksize is for.
The problem is that you named the resulting iterator df, and then tried to use it as a DataFrame. It's not a DataFrame; it's an iterator that gives you 1000-row DataFrames one by one.
When you say this:
My problem is I don't know how to use stuff like these below for the whole df and not for just one chunk
The answer is that you can't. If you can't load the whole thing into one giant DataFrame, you can't use one giant DataFrame. You have to rewrite your code around chunks.
Instead of this:
df = pd.read_csv('Check1_900.csv', sep='\t', iterator=True, chunksize=1000)
print df.dtypes
customer_group3 = df.groupby('UserID')
… you have to do things like this:
for df in pd.read_csv('Check1_900.csv', sep='\t', iterator=True, chunksize=1000):
print df.dtypes
customer_group3 = df.groupby('UserID')
Often, what you need to do is aggregate some data—reduce each chunk down to something much smaller with only the parts you need. For example, if you want to sum the entire file by groups, you can groupby each chunk, then sum the chunk by groups, and store a series/array/list/dict of running totals for each group.
Of course it's slightly more complicated than just summing a giant series all at once, but there's no way around that. (Except to buy more RAM and/or switch to 64 bits.) That's how iterator and chunksize solve the problem: by allowing you to make this tradeoff when you need to.
A:
You need to concatenate the chucks. For example:
df2 = pd.concat([chunk for chunk in df])
And then run your commands on df2
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server Cannot Call Methods on Date
I've got a DATETIME column in a SQL Server 2008 table called ShiftDate. I want to convert this to a DATE column in a query:
SELECT ID, ScheduleID, ShiftDate, CONVERT(DATE, ShiftDate) AS ProductionDate
FROM dbo.ScheduleResults
I am editing this query in SSMS. If I run the query in a standard query window, I don't get any errors. If I run this in the View editor window, I get the error "Cannot Call Methods on Date".
I've tried the CAST method but it gets the same error.
SELECT ID, ScheduleID, ShiftDate, CAST(ShiftDate AS DATE) AS ProductionDate
FROM dbo.ScheduleResults
The full error message is:
Executed SQL statement: SELECT ID, ScheduleID, ShiftDate, CAST(ShiftDate as DATE).ToString() AS ProductionDate FROM dbo.ScheduleResults
Error Source: .Net SqlClient Data Provider
Error Message: Cannot call methods on date.
I am inclined to think this is a bug in SSMS, but I would like to get some feedback from StackOverflow folks as to how to convert a datetime column to a date. I can easily convert it to a string column, but it is not ideal as Excel will not see it as a date.
A:
You are correct, it is a bug in SSMS. I'm using SQL Server Management Studio 2008 R2 and when I try to create a View using the built-in designer, I get the same error message as you:
SQL Execution Error
Error Source: .Net SqlClient Data Provider
Error Message: Cannot call methods on date.
As @Aaron Bertrand mentioned, to solve the issue, select 'New Query' and create the View in the Query window. For your code, it would be:
CREATE VIEW myView AS
SELECT ID, ScheduleID, ShiftDate, CAST(ShiftDate AS DATE) AS ProductionDate
FROM dbo.ScheduleResults
A:
It seems to be a real bug as mentioned above by https://stackoverflow.com/users/464923/will, inherited from MS Access old days with all it's inconveniences, You have just to ignore the error message and save your view then run it in a regular SSMS window, no error will be thrown .
| {
"pile_set_name": "StackExchange"
} |
Q:
Can TIdHTTPServer and TIdHTTP in same executable connect?
I have a program which uses a TIdHTTPServer. Now I want to write some automated tests using a TIdHTTP which talks to the TIdHTTPServer. The test code is in the program itself.
When the TIdHTTP tries to connect a 'Socket Error # 10061 Connection refused.' exception is raised. I'm guessing that's beacuse the TIdHTTPServer is using the port already.
Is it possible for a TIdHTTPServer and a TIdHTTP which are in the same executable to talk to each other at all? If so, how?
A:
Yes, they can run in the same executable and connect to each other. Simply specify (one of) TIdHTTPServer's listening IP(s) in the URL that you pass to TIdHTTP, eg:
with IdHTTPServer1.Binding.Add do
begin
IP := '127.0.0.1';
Port := 80;
end;
IdHTTPServer1.Active := True;
...
IdHTTP1.Get('http://127.0.0.1/');
| {
"pile_set_name": "StackExchange"
} |
Q:
error 3706 provider cannot be found. it may not be properly installed
All.
I have used a DLL approach explained on How to securely store Connection String details in VBA
This code is running very well on windows 10 64 bit and MS Office 64 bit. But same copy of the files i am not able to use on Wndows 8.1 Pro and MS Office 64 bit.
DLL generated is converted to host machnines environment by using
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\regasm c:\windows\syswow64\OraConnection.dll /tlb /codebase
But still same error i am facing. About environment variables care has been taken.
My Connection string is
"Provider=OraOLEDB.Oracle; Data Source = ; User ID =; Password=";
A:
In the Succesfull machine i was using Release 12.2.0.1.0 for ODAC 12.2c Release 1 as oracle client.
But saw a latest version of the oracle client as 64-bit ODAC 12.2c Release 1 (12.2.0.1.0) for Windows x64 which was released on 1st June 2017.
Installed the same. And my error was resolved. When i observed system environment variables i saw few things added into it.
E:\app\client\Admin\product\12.2.0\client_1;E:\app\client\Admin\product\12.2.0\client_1\bin;C:\Users\Admin\Oracle\;
I dont know actually what they did. But error was resolved.
Can anybody throw highlight on this?
| {
"pile_set_name": "StackExchange"
} |
Q:
Drawing 3D objects
I'm looking to draw a 3D cylinder with javascript by copying the layers and applying an increased margin to these elements. I have tried to set the height of the element in my input and run the copy function while total margin of the copied elements is lower than the set height of elements.
http://jsfiddle.net/yuX7Y/3/
<form>
<input type="number" id="userHeight" />
<button type="submit" onclick="circleHeight">Submit</button>
</form>
<div class="circle">
</div>
<div class="slice">
</div>
$(document).ready(function(){
var initMargin = 4;
var totalMargin = 0;
var i = 0;
function copy(){
$(".slice").clone().appendTo( ".content" ).css({'margin-top': totalMargin + "px"});
console.log("cloned");
i++;
totalMargin = initMargin + 4;
}
function setH(){
while(i < (document.getElementById("userHeight").value)){
copy();
}
if(i>100){
initMargin = 4;
i=0;
}
}
});
A:
Jump To The Result: http://jsfiddle.net/yuX7Y/15/
Notes
This Fiddle/question intrigued me so I went ahead and looked at it for a little while. There were actually a number of issues, some obvious and some less obvious. Somewhat in the order I noticed them these are some of the issues:
jQuery wasn't included in the fiddle
The click event wasn't wired up correctly - it was actually trying to submit the form. You need to use e.preventDefault to stop the form from submitting. Since you were already using jQuery I just wired up with the jQuery click event:
$("#recalculateHeight").click(function (e) {
e.preventDefault();
setH();
});
Because of the use of "global" variables (variables not initialized within the routines), the submit would only work once. Instead of this, I moved variable declarations to the appropriate routine.
Calling $(".slice").clone() clones ALL slice elements on the page. The first time you clone, this is fine. But after that you are cloning two elements, then three elements, etc (as many slice elements as are on the page). To solve this I created a slice template like:
<div class="slice" id="slice-template" style="display: none"></div>
Then you can clone to your hearts content like $("#slice-template").clone(). Just don't forget to call the jQuery show() method or set display back to block on the cloned element.
Finally, if you want to repeat the process many times you need to be able to clear previous elements from the page. I find this easiest to do by creating containers, then clearing the contents of the container. So I put all of the "slices" into this container:
<div class="content">
Now when you want to clear the content node you can just call $(".content").empty();.
I also made a few style based changes in my Fiddle, but those don't make it work or not work, they just help me read the code! So, there you have it! Best of luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
Why doesn't this code deadlock?
I expect the following code to deadlock when Clear tries to lock on the same object that Build has already locked:
void Main()
{
(new SiteMap()).Build();
}
class SiteMap
{
private readonly object _lock = new object();
public void Build()
{
lock (_lock)
{
Clear();
Console.WriteLine("Build");
}
}
public void Clear()
{
lock (_lock)
{
Console.WriteLine("Clear");
}
}
}
Output:
Clear
Build
Edit 1
Thank you all for your answers.
If I add a call to Build inside the lock of Clear (keeping the rest of the code the same):
public void Clear()
{
lock (_lock)
{
Build();
Console.WriteLine("Clear");
}
}
A deadlock does occur (or at least that's what I think, LINQ Pad crashes).
According to your answers, this shouldn't happen, because it's still the same thread.
Thanks!
A:
In C#, a thread holding a lock can enter the same lock without blocking.
The lock statement, as well as the Monitor class on which it is built, is reentrant in .NET.
Edit in response to your edit:
When you add the call to Build inside clear, the code doesn't deadlock - it is calling itself recursively. It's not blocking, but rather running forever (until, eventually, you hit a StackOverflowException), because Build calls Clear which calls Build again which calls Clear, etc....
A:
The documentation for lock says:
If another thread attempts to enter a locked code, it will wait (block) until the object is released.
The key word is "another". A thread does not block itself, just other threads. If another thread had owned the lock, then lock would block.
This saves a lot of headaches.
A:
I will not because clear is called within the same thread which already applied the lock.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get first related image from table while selecting all the records
I have 4 tables in database
Table 1: playlists
id name user_id
1 name1 3
2 name2 3
Table 2: videos
id name media_id
1 vid1 4
2 vid2 5
Table 3: playlist_has_video
id playlist_id video_id
1 1 2
2 1 1
Table 4: media
id filename
4 test.png
Now, I would like to select all the session where user_id=3 + first media.filename of video which belongs to playlist.id=1
See table playlist_has_video there is 2 video belongs to session.id=1
so select first video image only if there is many video belongs to that playlist
My desire output will be :
id session.name image
1 name1 test.png
Question is complicated to understand.
A:
You should use:
SELECT
pl.`id`,
pl.`name` AS 'session.name',
m.`filename` AS image
FROM `playlists` pl
INNER JOIN `playlist_has_video` plhv ON plhv.`playlist_id` = pl.`id`
LEFT JOIN `videos` v ON v.`id` = plhv.`video_id`
INNER JOIN `media` m ON m.`id` = v.`media_id`
WHERE pl.`user_id` = 3
ORDER BY m.`id`
LIMIT 1
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get api gateway address in order to call it from angular container in docker compose
i have a docker compose file in which there are several containers among which there are an api gateway and another one with an angularjs application (the website of this stack). The api gateway is concerned to call correct apis of several containers presents in the compose file. But i need to call the api gateway from the website (angular container) and
i would like to know what is the best practices for get the address of the api gateway container in order to call it from angular container (or from browser anyway..).
For the moment i working in local, so i specify
localhost:PortOfApiGateway/apis/...
and everything work fine, but obviously if try to connect from another host it not works...
Any suggestion?
A:
Depending on your environment, I see several possible solutions.
1. You can have a config file in Angular
For example, Angular Cli provides 2 files: environment.ts and environment.prod.ts
The content of the file can be:
export const environment = {
production: false,
apiBaseUrl: 'http://localhost:3000'
};
and the equivalent for production can be the real DNS url
This is provided by Angular CLI but you can do the same without the CLI. The idea here is that the files are chosen at compile time.
2. Always use the same server
You can assume that the hostname will be the same as the one you got your Angular app from:
import { Location } from '@angular/common';
// Get the hostname
this.hostname = location.host;
if (this.hostname.indexOf(':') > 0) {
this.hostname = this.hostname.substr(0, this.hostname.indexOf(':'));
}
// Add a port or a subdomain to get the API url:
this.apiUrl = 'http://' + this.hostname + ':8080';
Variables in compose?
As you said in an earlier comment, the calls are made from the browser, so outside Docker. I don't see an easy way to put this information in the compose file. That said I would be interested to find out.
I hope it helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Approximation factor of NP-complete problems
We talked about the following theorem in class but I am still having problems to understand it:
For a NP-complete decision problem "Does a valid solution with a value $\leq K$ exist?" there is no approximation algorithm for the corresponding minimization problem with an approximation factor $\lt 1 + 1/K$.
Why is this necessarily true? And where does that upper bound $1 + 1/K$ come from?
A:
The crucial assumption here is that the value is an integer.
If the value is an integer, then telling whether there is a valid solution with value $\le 10$ is as hard as telling whether there is a valid solution with value $\le 10.999$ (it's the question). Thus, you shouldn't expect a polynomial-time approximation algorithm with approximation factor $10.999/10$ or better -- if you had such an approximation algorithm, you could tell whether there was a valid solution with value $\le 10.999$, which would tell you whether there is a valid solution with value $\le 10$, which would let you solve the original problem, which would mean that you have found a polynomial-time algorithm for a NP-complete problem. That would be unexpected.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to easily commenting PHP+HTML code
Especially for easy and small projects, I leave pure HTML in my PHP source code and I simply add the relevant PHP when needed, and so many times I have something like this:
<div class="header-info">
<p><?php echo $w["emailText"][$lang];?></p>
</div>
Now, apart from it being good or bad practice, how can I easily comment out the whole 3 lines?
If I enclose them in HTML comments like these (sorry for the space but otherwise they are not printed):
< !--
... my code ...
-->
then PHP is still executed. If I enclose them in something like
<?php
if (0) {
?>
... my code ...
<?php
}
?>
then the nested "?>" will close my PHP if(0).
Again, I am fully aware that I should better use a Model-View-Controller approach and not mix different "worlds", but as said, for small projects it does not make sense and I am just asking if there is another solution to the 2 that I proposed :)
Thank you
A:
If you do not needed, why not remove it completely? If you want to prevent div tag from outputing to browser, then you can comment all of them, like following.
<?php /*
<div class="header-info">
<p><?php echo $w["emailText"][$lang];?></p>
</div>
*/ ?>
| {
"pile_set_name": "StackExchange"
} |
Q:
ValidationMessageFor is missing from ASP.NET MVC VS 2010
I have installed VS 2010 and created a new MVC application with it.
I have looked in the futures library as well as the source code from Code Plex and I can see that the function is in the ValidationExtensions class in the source code from Code Plex. Does anyone know how to get the source code from code plex to install with VS 2010 or do I just need to wait?
I suppose the easiest solution would be to just create my own ValidationExtensions and put the code in there but I am wondering what other things are different?
A:
I got this from Auriel, a developer on the ASP.NET team.
VS2010 Beta 2 ships with MVC 2 Preview 2, not MVC 2 Beta. MVC 2 Beta is not supported on VS2010 Beta 2. Yeah, the terminology is a bit confusing, unfortunately. :(
If you really need to get MVC 2 Beta to work on VS2010 Beta 2, see http://haacked.com/archive/2009/11/17/asp.net-mvc-2-beta-released.aspx#74907. Please note that this is entirely unsupported and could put your system into an unstable state. When VS2010 is released, it will include the final release version of MVC 2.
| {
"pile_set_name": "StackExchange"
} |
Q:
Block all users except localhost from phpmyadmin and mysql
I recently installed the XAMPP stack on a desktop and connected via a laptop on the local network. To my surprise, I was able to access phpmyadmin and delete update all mysql tables. Though I understand that I shouldn't use xampp for production (and I'm not), I would still like to learn how to manage these types of obvious security flaws. I know that I can block access to directories via .htacces (http://forum.directadmin.com/showthread.php?t=29089), but I would like something that is a little more comprehensive. How would you restrict running of mysql queries from anywhere except localhost? Is there a way without .htaccess? I thought this was partially the purpose of the root user.
A:
MySQL defined users with domains. If you look at your user_privileges table in the information_schema database you will see that they all have domains. If all your users are defined strictly as localhost, there will be no remote access.
Also, you can edit my.cnf to turn off tcp access to the database, forcing all connections to be by socket. under [mysqld], include the line skip-networking. You will have to configure all your apps to use the socket connection, but I like the socket better anyway.
This will do nothing to protect your data from someone using phpMyAdmin, if phpMyAdmin is installed on the same machine as the database. The safest thing to do is get rid of that app. That's often not practical, however, as it's a useful tool, and so you need to configure phpMyAdmin to require that users authenticate themselves. That means NOT putting the password in the config file. You will need to think about how long sessions are before reauthentication, and things like that.
phpMyAdmin fills me with a rage hotter than a thousand suns whenever I try to configure it, but it is definitely possible to set things up so a password is required each time you connect to the database through phpMyAdmin. You can further limit the damage phpMyAdmin abusers can do my making sure it only connects as a user with limited privileges (for instance, only able to modify the database you're working on at the moment).
| {
"pile_set_name": "StackExchange"
} |
Q:
Sum of segments inside a right triangle.
I am interested for a problem involving the sum of segments inside a right triangle. Consider a right triangle of hypotenuse $\overline{BC}$ and catheti $\overline{AB}$ and $\overline{AC}$. From the right angle, trace the segment $\overline{AP_1}$ forming an angle $\alpha$ with the cathetus $\overline{AB}$. $P_1$ is a point on the hypotenuse. Trace, then, the segment $\overline{P_1P_2}$ perpendicular to $\overline{AB}$ ($P_2$ is a point on this cathetus).
By continuing the process, trace the segment $\overline{P_2P_3}$, forming an angle $\alpha$ with the cathetus $\overline{AB}$, with $P_3$ on the hypotenuse, and trace $\overline{P_3P_4}$ perpendicular to $\overline{AB}$, with $P_4$ on the cathetus. And so on.
Does exist a closed form on $\overline{BC}, \overline{AB}, \overline{AC}$and $\alpha$ for the sum
$$ \sum_{i=0}^{\infty}\overline{P_iP_{i+1}}?$$ Set $P_0 = A$.
A:
Extend the first line $AP_1$ through the hypotenuse till it reaches a point $D$ such that $\angle{ABD}$ is a right-angle. If you add every odd-numbered segment ($P_0P_1,\; P_2P_3,\;\ldots$) it is the same as length of $AD$.
Similarly, if you add every even-numbered segment ($P_1P_2,\; P_3P_4,\;\ldots$) it is the same as length of $BD$.
Therefore, $$\sum_{i=0}^{\infty}\overline{P_iP_{i+1}} = \overline{AD} + \overline{BD} = \overline{AB}(\sec{\alpha} + \tan{\alpha}).$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Model Null reference exception in mvc view
The problem is getting null reference exception when passing data from controller to view
I am Passing a model to the view from the controller like this:
{
ViewBag.PartId = id;
var viewmodel= new Orderviewmodelnew();
var order = new OrderMnagernew().GetSingleOrderField(id);
viewmodel.ProjectId=order.ProjectId;
return View(viewmodel);
}
And in the View I have code like this
@model DreamTrade.Web.BL.ViewModels.OrderViewModelnew
Home>Project @Model.ProjectID==null??//projected is of type guid
Customer :@(Model.CreatedBy??string.empty)
Project :@Model.ProjectID
@Model.ProjectDetail
CreatedBy:@Model.CreatedBy
Creation Date:@Model.CreationDate
CompletedBy :@Model.ModifiedBy
Completion Date:@Model.LastModified
@Model.Image
@Html.Action("OrderIndex", "Ordernew", new { PartId = Guid.Parse("C0497A40-2ADE-4B23-BA9F-1694F087C3D0") })
I have Tried like this
@if(Model.ProjectId==Null)
{/....}
In the controller i tried like this by not passing model if it is null
var order = new OrderMnagernew().GetSingleOrderField(id);
if(order!=null)
{
viewmodel.ProjectId=order.ProjectId;
return View(viewmodel);
}
return View()
The problem with this the projectid in the view is showing exception.
I Want to display empty string if it is null and show the remaining part..
A:
This code is wrong:
@Model.ProjectID==null??string.empty
if ProjectID is nullable type, you should write:
@(Model.ProjectID ?? string.empty)
Added:
Replace:
return View()
with:
return View(new Orderviewmodelnew())
because null object doesn't have any properties
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails i18n - How to translate enum of a model
I've got the following model:
class Person < ActiveRecord::Base
enum gender: [:female, :male]
...
end
Then I added the selection of the gender to its form, like this:
<%= form_for ([@person]) do |f| %>
...
<div class="form-group">
<%= f.collection_radio_buttons :gender, Person.genders, :first, :first %>
</div>
...
<% end %>
But instead of displaying the constant as a string I want to translate it to Portuguese.
I already tried to add it to the pt.yml file under people but didn't work.
pt:
activerecord:
attributes:
female: Feminino
male: Mascúlino
I know this question is very similar to How to use i18n with Rails 4 enums but that question is already marked as answered and I'm searching for a better and simpler solution...
Thank you for taking your time to help me :)
A:
After reading How to use i18n with Rails 4 enums answers more carefully I came to this solution:
According rails guides - "In the event you need to access nested attributes within a given model, you should nest these under model/attribute at the model level of your translation file" -
the yml file should look like this:
pt:
activerecord:
attributes:
person/gender:
female: Feminino
male: Mascúlino
We need to create a method to return a translated enum since there isn't any method capable of translating an entire enum at once. Rails just has the method to translate a value given a key, i.e People.human_attribute_name("gender.female").
Ok, we'll create a new method but where should we put it?
I think Helpers are the best place to put it because I'm changing the enum values in order to easily attach them to the form collection, although most of the answers suggested to put it in the Models.
Now my person_helper.rb looks like this:
def human_attribute_genders
Hash[Person.genders.map { |k,v| [k, Person.human_attribute_name("gender.#{k}")] }]
end
And my view:
<%= f.collection_radio_buttons :gender, human_attribute_genders, :first, :second %>
Pretty simple and it works just fine!
If anyone has any suggestion to improve my solution I would be happy to hear it from you :)
For example, I could extract the method to application_helper.rb like this:
def human_attribute_enum(model_name, enum_attr, attr_name)
Hash[enum_attr.map { |k,v| [k, I18n.t("activerecord.attributes.#{model_name}/#{attr_name}.#{k}")] }]
end
But it'd require passing a lot of parameters in the view...
| {
"pile_set_name": "StackExchange"
} |
Q:
Passiv des Modalverbes in Subjektivbedeutung
Ich habe den folgenden Satz selber geschrieben, indem ich mich nur auf mein Bauchgefühl verlassen habe. Ich konnte die Regel, die beschreibt, wie man in Vergangenheit einen Passiv des Modalverbes in Subjektivbedeutung bildet, nicht finden.
Der Satz lautet:
“Berichten zufolge sollen die vegetarischen Burger auf demselben Grill gebraten worden wie die, die aus dem echten Fleisch zubereitet wurden.“
Ich bin mir nicht sicher, ob die Form, die fettgedruckt ist, auch die richtige ist.
A:
Modalverben im Regelfall mit Infinitiv. Infinitive im Deutschen:
Infinitiv Präsens: vergessen
Infinitiv Perfekt: vergessen haben
Infinitiv Präsens Passiv: vergessen werden
Infinitiv Perfekt Passiv: vergessen worden sein
Infinitiv Präsens Zustandspassiv: vergessen sein
Infinitiv Perfekt Zustandspassiv: vergessen gewesen sein
Infinitiv Perfekt 2 (Superperfekt): vergessen gehabt haben
Beispiele:
Er will die ganze Geschichte vergessen.
Sie muss den Termin vergessen haben.
Das darf auf keinen Fall vergessen werden.
Da liegt ein Schlüssel, der muss vergessen worden sein.
In zwei, drei Jahren wird das alles sicher vergessen sein. (halbmodales 'wird')
?Das kann nicht "vergessen" gewesen sein, er muss es absichtlich getan haben.
Er muss den Schlüssel vergessen gehabt haben - sonst wäre er doch nicht noch einmal zurückgefahren!
A:
Die korrekte Form für eine Passivform in der Vergangenheit (Perfekt) ist soll [...] gebraten worden sein.
Ich wäre allerdings auch nicht auf die Regel gekommen, also danke an @RHa aus den Komentaren. "Sollen" als Modalverb benötigt in der Regel ein infinites Hauptverb (außer es darf in Ausnahmefällen weggelassen oder ersetzt werden).
Im Präsens würde der Satz übrigens heißen soll [...] gebraten werden.
| {
"pile_set_name": "StackExchange"
} |
Q:
Please help me de-cipher this line of bash scripting code
What does this mean?
h2t=$((exec 2>&-; (which lynx >/dev/null && echo lynx -stdin -dump) \
|| which html2text || which cat) |tail -n 1)
Ok, h2t=... means it's setting a variable.
I thought double-parens were for arithmetic operations. If that's the case I don't see any arithmetic there, and I'm thoroughly baffled.
Of course, there is a 15-line comment block above that line of code, which explains the intent. Unfortunately the comment is in unicode version of ancient sumerian, and I cannot interpret it.
**Only kidding! There is no comment.
Addendum: This is from https://github.com/micha/resty/blob/master/resty
A:
twalberg in a comment to my answer spotted it. Turns out the outer $() assigns a command line, depending on the availability of various tools that might be able to convert HTML to text.
Therefore h2t contains either the lynx -stdin -dump command line, or failing that (i.e. lynx not available), html2text or as a last resort cat. The commands for the latter two come from the which invocations, the one for the former from the echo.
It converts HTML to text from stdin.
Let's split it up.
exec 2>&- sets up a redirect in the subshell (shuts up stderr, IIRC)
the next sub-subshell tries to see whether lynx is installed and runs it, taking input from stdin.
the other parts after the || make not much sense because they only evaluate whether html2text and cat are installed, but don't run them
then we fetch the last line from that first subshell
Scratch that. Since it's an echo it doesn't do anything. Looks like prototyping to me.
Taking it apart to make more readable:
$(
exec 2>&-
(
which lynx >/dev/null &&
echo lynx -stdin -dump
) ||
which html2text ||
which cat
) |
tail -n 1
)
| {
"pile_set_name": "StackExchange"
} |
Q:
When I export Chinese characters from Oracle forms to Excel, they are not Chinese anymore
I have problem with Chinese characters when I export them from Oracle forms 10g to Excel on Windows 7. Although they look like Chinese but they are not Chinese characters. Take this into consideration that I have already changed the language of my computer to Chinese and restarted my computer. I use owa_sylk utility and call the excel report like:
v_url := 'http://....../excel_reports.rep?sqlString=' ||
v_last_query ||
'&font_name=' ||
'Arial Unicode MS'||
'&show_null_as=' ||
' ' ;
web.show_document(v_url,'_self');
Here you can see what it looks like:
Interestingly, when I change the language of my computer to English, this column is empty. Besides, I realized that if I open the file with a text editor then it has the right Chinese word, but when we open it with Excel we have problem.
Does anyone has a clue?
Thanks
A:
Yes, the problem comes from different encodings. If DB uses UTF-8 and you need to send ASCII to Excel, you can convert data right inside the owa_sylk. Use function convert.
For ex. in function owa_sylk.print_rows change
p( line );
on
p(convert(line, 'ZHS32GB18030','AL32UTF8'));
Where 'ZHS32GB18030' is one of Chinese ASCII and 'AL32UTF8' - UTF-8.
To choose encoding parameters use Appendix A
You can also do
*SELECT * FROM V$NLS_VALID_VALUES WHERE parameter = 'CHARACTERSET'*
to see all the supported encodings.
| {
"pile_set_name": "StackExchange"
} |
Q:
Query which excludes elements meeting a specific condition
I'm facing a problem trying to develop a query for this simple database I've created. It gathers 3 suppliers identified by a code (CODICEFORNITORE) which sells products such as phone or cereals, each one of them identified by another code (CODICEPRODOTTO). What I'm trying to accomplish is to get back the number of suppliers who do not sell any Apple product. The association between the products and its supplier is tracked thanks to a third table called Catalogue (CATALOGO).
I've thought that the best way to do that is by a EQUI JOIN between PRODUCT TABLE and CATALOGUE TABLE, then trying to count the number of Apple products sell by suppliers and then exclude those whose count is less or equal to 0. But I can't succed in creating such a query.
I have no problem in counting how many suppliers sell Apple products instead.
Achieving the opposite is quite simple (and I'm sure I could do it even in a easier way):
SELECT COUNT(CODICEFORNITORE) AS NUMERO_FORNITORI_APPLE --- This the number of apple supplier
FROM CATALOGO C JOIN PRODOTTI P ON C.CODICEPRODOTTO = P.CODICEPRODOTTO
GROUP BY CODICEFORNITORE, MARCA
HAVING Marca = 'Apple';
--- this returns 1 as expected ---
What I'm trying to achieve should return '2' based on the following table
Thanks in advance and sorry for poor english
A:
You can get the list of suppliers who supply at least one product and have no Apple products using:
SELECT CODICEFORNITORE
FROM CATALOGO C JOIN
PRODOTTI P
ON C.CODICEPRODOTTO = P.CODICEPRODOTTO
GROUP BY CODICEFORNITORE
HAVING SUM(CASE WHEN Marca = 'Apple' THEN 1 ELSE 0 END) = 0;
And you can get the count using a subquery:
SELECT COUNT(*)
FROM (SELECT CODICEFORNITORE
FROM CATALOGO C JOIN
PRODOTTI P
ON C.CODICEPRODOTTO = P.CODICEPRODOTTO
GROUP BY CODICEFORNITORE
HAVING SUM(CASE WHEN Marca = 'Apple' THEN 1 ELSE 0 END) = 0
) c;
Alternatively, if you have a table of suppliers, you can use NOT EXISTS:
SELECT COUNT(*)
FROM FORNITORE F
WHERE NOT EXISTS (SELECT 1
FROM CATALOGO C JOIN
PRODOTTI P
ON C.CODICEPRODOTTO = P.CODICEPRODOTTO
WHERE F.CODICEFORNITORE = C.FORNITORE AND
P.Marca = 'Apple'
);
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is it that the second code gives the desired result while the first doesn't?
When I use functions I get the desired result which is:-
1)The command window asks me to give input every time so I can input 'q' as many times as I want and can even enter 'e' to exit
2) Every time I press 'q' score decreases by 1
whereas in the code without functions the following happens:-
1) I press 'q' and the score keeps decreasing indefinitely
2) Cannot enter another input like 'e' once entered 'q'
#include<iostream>
using namespace std;
int main()
{
char h;
cin>>h;
int n = 10;
do{
system("cls");
cout<<"score is"<<n;
if(h == 'q')
{
n=n-1;
}
}while(h != 'e');
return 0;
}
CODE 2 with FUNCTION:-
#include<iostream>
using namespace std;
char input;
int n = 10;
bool over = false;
void ip()
{
system("cls");
cout<<"score is"<<n;
cin>>input;
switch(input)
{
case 'q':
n--;
break;
case 'e':
over = true;
break;
}
}
int main()
{
do{
ip();
}while(!over);
return 0;
}
Please explain to me how is the program looping through the function and how is it looping through the 'IF' statement alone. Because the condition statement is there in the function also (switch statement) so why isn't the function decreasing the score or the value of 'n' indefinitely??
A:
I figured out my mistake in the first code (without functions) the cin>> statement should be inside do-while loop so that after every loop input is asked.
| {
"pile_set_name": "StackExchange"
} |
Q:
before() and beforeAll() hooks are not getting recognised in WebdriverIO-Mocha framework having Jest as assertion library
before() and beforeAll() are not getting recognised in WebdriverIO-Mocha framework having Jest as assertion library.
For a ReactNative project we're building UI Automation using webdriver.IO+mocha. As its ReactNative, so main project code-base already has a extensive Jest library in built in the project.
Dependencies:
"jest": "23.6.0",
"jest-junit": "^5.2.0",
"jest-matchers": "^20.0.3",
"jest-transform-stub": "^1.0.0",
"wdio-mocha-framework": "^0.6.4",
"wdio-screenshots-cleanup-service": "0.0.7",
"wdio-spec-reporter": "^0.1.4",
"wdio-visual-regression-service": "^0.9.0",
"webdriverio": "^4.12.0"
I am getting error:
ERROR: beforeAll is not defined
Also, unable to use Mocha's before() function at the same time.
Surprisingly editor is recognising beforeEach()
how to solve this issue, so that I can start using hooks like - before(), beforeAll() etc.
A:
You're trying to use the Jest style hooks, but you're still running it through Mocha.
Use before, beforeEach, afterEach and after (the Mocha style ones).
You can still use Jest for your assertions (assuming you load them in correctly), but you can't use their style of hooks.
| {
"pile_set_name": "StackExchange"
} |
Q:
Derivative of $(I_n+\alpha xx^T)^{\frac{1}{2}}$
Assume that $\alpha$ is a real scalar and $x$ is a real vector of order $n$. If $I_n$ is an identity matrix of order $n$, how to compute the derivative of $(I_n+\alpha xx^T)^{\frac{1}{2}}$ with respect to $\alpha$ and $x$, respectively?
A:
Define the matrix
$$\eqalign{
A &= \sqrt{I+\alpha xx^T} \cr
A^2 &= I+\alpha xx^T \cr
}$$
and define separate variables for the length and direction of the $x$ vector
$$\eqalign{
\lambda &= \|x\| \cr
n &= \lambda^{-1}x \cr
}$$
We can create an ortho-projector $P$ with $n$ in its nullspace
$$\eqalign{
P &= I - nn^T \cr
P^2 &= P^T = P,\,\,\,\,\,P n &= 0 \cr
}$$
Notice that
$$\eqalign{
(P+\beta nn^T)^2
&= P + \beta^2 nn^T \cr
&= I + (\beta^2-1) nn^T \cr
}$$
By choosing $\,\,\beta=\sqrt{1+\alpha\lambda^2}\,\,\,$ we can equate this to $A^2$, which then yields
$$\eqalign{
A &= P+\beta nn^T \cr
}$$
Now take the derivative wrt $\alpha$
$$\eqalign{
\frac{dA}{d\alpha}
&= \frac{d\beta}{d\alpha}\, nn^T \cr
&= \frac{\lambda^2}{2\beta}\,nn^T = \frac{1}{2\beta}xx^T \cr
}$$
To find the gradient wrt $x$, start by finding differentials of the relevant quantities
$$\eqalign{
d\lambda &= \lambda^{-1}x^Tdx = n^Tdx \cr
d\beta &= \frac{\alpha\lambda\,d\lambda}{\beta}
= \frac{\alpha\lambda}{\beta}\,n^Tdx \cr
dn &= \lambda^{-1}P\,dx \cr
dP &= -(dn\,n^T+n\,dn^T)\cr
}$$
So the differential of $A$ is easy enough to find
$$\eqalign{
dA &= nn^T d\beta + \beta\,d(nn^T) + dP \cr
&= nn^T d\beta + (\beta-1)(dn\,n^T+n\,dn^T) \cr
&= nn^T\,\frac{\alpha\lambda}{\beta}\,(n^T\,dx)
+ \frac{\beta-\!1}{\lambda}(P\,dx\,n^T+n\,dx^TP) \cr
}$$
but casting this into the form of gradient (i.e. a 3rd order tensor) using standard matrix notation is impossible. You must introduce special (isotropic) higher-order tensors, or resort to vectorization, or to index notation in order to proceed. Index notation is the best route.
If you contract the differential with matrices from the standard basis $E_{ij}=e_ie_j^T$ you can find the gradient on a component-wise basis
$$\eqalign{
E_{ij}:dA = dA_{ij}
&= n_in_j\,\frac{\alpha\lambda}{\beta}\,(n^T\,dx)
+ \frac{\beta-\!1}{\lambda}(n_jp_i^T\,dx + n_ip_j^Tdx) \cr
\frac{\partial A_{ij}}{\partial x}
&= n_in_j\,\frac{\alpha\lambda}{\beta}\,n
+ \frac{\beta-\!1}{\lambda}(n_jp_i + n_ip_j) \cr
}$$
where $p_k=Pe_k$ is the $k^{th}$ column of $P$ and $n_k$ is the $k^{th}$ element of $n$.
However, if you just want to calculate how $A$ will change in response to a change in $x$, using the differential is sufficient.
| {
"pile_set_name": "StackExchange"
} |
Q:
Preserving Column Order - Python Pandas and Column Concat
So my google-fu doesn't seem to be doing me justice with what seems like should be a trivial procedure.
In Pandas for Python I have 2 datasets, I want to merge them. This works fine using .concat. The issue is, .concat reorders my columns. From a data retrieval point of view, this is trivial. From a "I just want to open the file and quickly see the most important column" point of view, this is annoying.
File1.csv
Name Username Alias1
Tom Tomfoolery TJZ
Meryl MsMeryl Mer
Timmy Midsize Yoda
File2.csv
Name Username Alias 1 Alias 2
Bob Firedbob Fire Gingy
Tom Tomfoolery TJZ Awww
Result.csv
Alias1 Alias2 Name Username
0 TJZ NaN Tom Tomfoolery
1 Mer NaN Meryl MsMeryl
2 Yoda NaN Timmy Midsize
0 Fire Gingy Bob Firedbob
1 TJZ Awww Tom Tomfoolery
The result is fine, but in the data-file I'm working with I have 1,000 columns. The 2-3 most important are now in the middle. Is there a way, in this toy example, I could've forced "Username" to be the first column and "Name" to be the second column, preserving the values below each all the way down obviously.
Also as a side note, when I save to file it also saves that numbering on the side (0 1 2 0 1). If theres a way to prevent that too, that'd be cool. If not, its not a big deal since it's a quick fix to remove.
Thanks!
A:
Assuming the concatenated DataFrame is df, you can perform the reordering of columns as follows:
important = ['Username', 'Name']
reordered = important + [c for c in df.columns if c not in important]
df = df[reordered]
print df
Output:
Username Name Alias1 Alias2
0 Tomfoolery Tom TJZ NaN
1 MsMeryl Meryl Mer NaN
2 Midsize Timmy Yoda NaN
0 Firedbob Bob Fire Gingy
1 Tomfoolery Tom TJZ Awww
The list of numbers [0, 1, 2, 0, 1] is the index of the DataFrame. To prevent them from being written to the output file, you can use the index=False option in to_csv():
df.to_csv('Result.csv', index=False, sep=' ')
| {
"pile_set_name": "StackExchange"
} |
Q:
Optional и OptionalInt
В чём отличие Optional<Integer> и OptionalInt, и в каких случаях какой из этих типов лучше применять?
A:
Отличие в том, что при наличии значения Optional<Integer>.get вернет объект (Integer), а OptionalInt.getAsInt — примитивное значение (int).
Соответственно, чтобы избежать лишнего обертывания примитивных значений при работе с int применяется OptionalInt , а при работе с объектами Integer — Optional<Integer>.
Рассмотрим на примере интерфейса с двумя методами:
interface Test {
int getInt();
Integer getInteger();
}
При обработке значений имеет смысл использовать соответствующие классы (на примере Stream API):
List<Test> list = //получаем список
OptionalInt intFirst = list.stream().mapToInt(Test::getInt).findFirst();
Optional<Integer> integerFirst = list.stream().map(Test::getInteger).findFirst();
Использование IntStream и OptionalInt для поля типа Integer потенциально приведет к NullPointerException. Использование Optional<Integer> и Stream<Integer> для int приведет к лишнему обертыванию значений.
Необходимость специальных классов обусловлена тем, что в Java примитивные типы не могут использоваться в качестве параметров обобщенных типов. Из за этого классы Stream<T> и Optional<T> не могут быть использованы для работы с примитивными значениями.
Использовать вместо примитивов классы-обертки непозволительно из-за затрат производительности на упаковку значений в объекты. Поэтому для часто используемых примитивных типов создан набор специальных классов: IntStream, LongStream, DoubleStream и OptionalInt, OptionalLong, OptionalDouble.
| {
"pile_set_name": "StackExchange"
} |
Q:
index out of bound while looping through a list and deleting some of the elements in python
I'm trying to loop through a list of numbers from 2 to 10000 and delete the mutliples of 2,3,4, and to 100 but not these numbers but everytime i delete an item the length of the list shrinks so it produces an index out of bound error how do i fix it?
A:
Here is an example that might work for you.
It leverages list comprehension.
I didn't quite understand your code, especially the index increment in the while loop that only runs until multiple is 101.
def is_multiple(number):
for m in range(2, 101):
if number is not m and number % m == 0:
return True
numbers = range(2, 10000)
numbers = [n for n in numbers if not is_multiple(n)]
print(numbers)
| {
"pile_set_name": "StackExchange"
} |
Q:
Loss of data when passing it to Cipher.update while using DES (Node.js)
Here's the deal:
I have a Buffer of data structured like this:
[39 bytes of header] + [body] + [padding] (calculated by me).
If I save it to a file, I can actually recognize the structure, and everything seems fine.
Then, I have to DES-CBC encrypt this buffer, and what I do is
a) Instantiate the DES wrapper, which has a key, and calculates a new IV (autoPadding: false on the Cipher object it creates, too)
b) Pass the buffer to the DES wrapper
c) The buffer then gets encrypted as follows:
(data is the buffer, en is the Cipher object)
var buf1 = en.update(data);
When I output buf1 on a file (and then, in my case, on a socket) and retrieve it's bytes, then decrypt it I obtain the following structure:
[header][body]
But when I output data on a file and retrieve it's bytes, I get the starting structure.
I know I should also append en.final() to buf1, but in my case I don't need those values, also with autoPadding being false it would just throw an error.
A:
The API provides you with a contract. One of the properties of the contract is that you need to call Cipher#final([output_encoding]) when you finished encrypting. Even if the padding doesn't need to be handled by the Cipher instance, the code is written for re-usability and therefore expects to be used in the same way regardless of padding options.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reading the right registry location for an MSI that can be installed for Everyone or Just Me
I have an application with an installer in Visual Studio 2008 which can be installed for Everyone or Just Me by the user. The installer writes some registry values that can be changed by the application. The installer is configured for any cpu.
From documentation on MSDN I've put the registry values under the "Machine/User Hive" key in the installer, the behaviour seems to be that for Everyone the registry keys appear under HKLM\Software\Wow6432Node\My App and for Just Me they appear under HKCU\Software\My App.
My problem comes when trying to read the values inside the application. It seems to me that with this cleverness in the installer there might be some "right way" of ensuring my app gets the right registry location, but try as I might my books and my google-fu has failed me :(
I'd be very grateful for any assistance with this.
Edit:
No replies and still no luck in documentation, so I guess there isn't a nice way of doing this, I went with checking for the localmachine key then the currentuser key (if localmachine was blank). Seemed a bit odd but gets the job done!
A:
I guess there isn't a nice way of doing this, I went with checking for the localmachine key then the currentuser key (if localmachine was blank) in a ternary operation, and it seems to have worked.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting Dhtmlx Scheduler Timeline View hour header to 12-hour format
In Dhtmlx Scheduler Timeline View, how can I set the Hour header from military time(24hour) to 12-hour format?
I have found some responses on their forum but this doesnt seem to work.
scheduler.config.hour_date = "%h:%i %A";
Any help would be appreciated. Thanks!
A:
Hour format must be specified in timeline configuration object with x_date property.
Here is the example:
scheduler.createTimelineView({
name: "timeline",
x_unit: "hour",
x_date: "%h:%i %A",
x_step: 1,
x_size: 24,
y_unit: [
{key:1, label:"James Smith"},
{key:2, label:"John Williams"},
{key:3, label:"David Miller"},
{key:4, label:"Linda Brown"}
],
y_property: "section_id",
render:"bar"
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get json data in my case?
I am trying to use httml get to get the json
I have something like
.controller('testController', function($scope, $state, $http) {
$http({
url: "/json/test.json",
method: "GET",
}).success(function(data) {
$scope.testData = data;
console.log(data)
});
//outside of the $http scope but under the same controller, I have
//It shows undefined.
console.log($scope.testData)
})
I know we have to keep data our of the login codes so I don't want to modify the data inside the $http. Is there anyway to accomplish this? Thanks!
A:
First, don't put this in a controller. Move it to a Service. That's what Services are designed for.
Second, the $http service is asynchronous. Your result only exists in the success callback, and your console.log will be called before the http request is finished. You need to assign it to a scope variable to use it outside of the callback, and expect it to be empty until the call back is complete.
http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app provides an example of an AngularJS authentication service, if that's what you're doing.
To go with your example:
.controller('testController', function($scope, $state, $http) {
$scope.testData = {};
$http({
url: "/json/test.json",
method: "GET",
}).success(function(data) {
$scope.testData = data;
$scope.logData();
});
$scope.logData = function() {
console.log($scope.testData);
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
First project with Zend framework on netbeans not working properly
I've installed the latest Zend Framework on the latest netbeans application and I've created my first project succesfully
The only problem I have is when I hit Run on netbeans it doesn't show the actual web page, it shows me the directory where I saved the project to instead of the Public folder.
I've followed the instructions on their quickstart guide but I can't seem to fix that problem.
Anyone have a suggestion?
A:
You have to configure Netbeans to run your project correctly; it's not Zend's fault.
Right click on your project and select Set as Main Project, if not already
Right click again and select Properties
Under Run Configuration, choose Run As: and select Local Web Site (running on local server
Make sure your Project URL points to your web server (for example: http://localhost/myproject/)
Make sure your Index File is correct.
This all assumes that you are using a local webserver (example: Zend Server CE, or WAMP).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to detect dimensions of file using File API and Dropzone.js
Using Dropzone.js, I need to detect the dimesions of the image when added files and apply them to its parent .details div. The following code code works and return an alert with the added image width.
myDropzone.on("addedfile", function(file, xhr) {
var fr;
fr = new FileReader;
fr.onload = function() {
var img;
img = new Image;
img.onload = function() {
return alert(img.width);
};
return img.src = fr.result;
};
return fr.readAsDataURL(file);
});
The thing is that I have no idea how to assign the width to its parent .details element which set the preview width of the preview.
I try replacing the alert for this code but it doesn't do anything.
$(this).parent('.details').css('height',img.height);
I'm a bit lost in how to relate the value inside the onload function to applying it to its parent class.
A:
With the latest version of dropzone you don't have to write this code yourself.
Simply read the file.width and file.height properties that are set on the file object when the thumbnail is generated.
The problem, why your CSS doesn't affect the element, is because you didn't specify the unit, px in this case. So your code can be:
myDropzone.on("thumbnail", function(file) {
$(this.element).parent('.details').css('height', file.height + 'px');
});
| {
"pile_set_name": "StackExchange"
} |
Q:
free() on struct member causes Hardfault only in Debug
I am working on a STM32F7.
A Hardfault is triggered when I hit the free() in the following (simplified) code:
typedef struct
{
uint8_t size;
uint8_t* data;
}my_struct;
void foo()
{
my_struct msg;
msg.size = 5;
msg.data = malloc(msg.size);
if(msg.data != NULL)
{
free(msg.data); // Hardfault
}
}
Going step by step with GDB in the free() I found the assembly instruction that caused the Hardfault:
ldrd r1, r3, [r5, #8]
The value of r5 is 0x5F0FE9D0
CFSR is 0x8200 and both MMFAR and BFAR registers contains 0x5F0FE9D8,
Looking at LDRDR problems on the net, I tried to add __attribute__((__packed__)) to my_struct definition.
It is supposed to force the compiler to generate 2xLDR instead when using unaligned memory access via pointers/structures.
By doing that, I no longer have an Hardfault at runtime. OK...
Out of curiosity, I wanted to inspect the addresses via GDB after this modification, and surprise ! Nothing changes (I mean about the addresses) and I ends up hitting the LDRD instruction again, despite the packed, and generating my Hardfault (but only in GDB-debug execution).
I launched a new run after removing the attribute and compared the value of MMFAR and BFAR registers and when I am not in GDB I got 0x41AFFE60
Why can't I see the 2xLDR in the debugger ?
More generally, why don't I have the same behavior with and without GDB ?
Is the packed trick is the good solution for my issue ?
P.S. I am running FreeRTOS and have defined configCHECK_FOR_STACK_OVERFLOW to 2 and configASSERT, nothing triggers.
A:
Both 0x5F0FE9D8 and 0x41AFFE60 are marked as reserved in the STM32F7 memory map (chapter 2 of the Reference Manual). It means that the heap is corrupted.
Why can't I see the 2xLDR in the debugger ?
Because free() is in a precompiled static library, it's not recompiled.
More generally, why don't I have the same behavior with and without GDB ?
If the heap contains random junk, either because it's not initialized properly, or overwritten by some unrelated piece of code, you might get some different junk when you connect things to, or disconnect things from the board. Or whenever some environmental factor changes.
Is the packed trick is the good solution for my issue ?
No, it just manages to hide the problem by sheer luck. With a corrupt heap, all bets are off.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extract values from two columns of a dataframe to make a dictionary of keys and values
I have a dataframe containing several columns of data. If there are two columns 'reaction' and 'abundance'. There are multiple times each of these will show such as:
reaction product abundance 1.0 1.5 2.0 2.5 3.0 3.5 4.0 ... \
0 023Na-a 010020.tot 1 0 0 0 0 0 0 0 ...
1 023Na-a 012023.tot 1 0 0 0 0 0 0 0 ...
2 035Cl-a 010022.tot 0.3775 0 0 0 0 0 0 0 ...
3 035Cl-a 008018.tot 0.3775 0 0 0 0 0 0 0 ...
4 037Cl-a 013025.tot 0.1195 0 0 0 0 0 0 0 ...
.. ... ... ... .. .. .. .. .. .. .. ...
For every instance of reaction, the abundance will be the same. I would like to create a dictionary of the reaction and abundances:
dict = {'023Na-a': 1,
'035Cl-a': 0.3775,
'037Cl-a': 0.1195}
A:
import pandas as pd
data = [['023Na-a', '010020.tot', 1, '...'],
['023Na-a', '012023.tot', 1, '...'],
['035Cl-a', '010022.tot', 0.3775, '...'],
['035Cl-a', '008018.tot', 0.3775, '...'],
['037Cl-a', '013025.tot', 0.1195, '...']]
df = pd.DataFrame(data, columns=['reaction', 'product', 'abundance', 'etc'])
df[['reaction', 'abundance']].set_index('reaction').to_dict()['abundance']
result
{'023Na-a': 1.0, '035Cl-a': 0.3775, '037Cl-a': 0.1195}
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the best way to prime/refresh a url in varnish 4 using a single http request?
The force cache miss note states:
Forcing cache misses do not evict old content. This means that causes Varnish to have multiple copies of the content in cache. In such cases, the newest copy is always used. Keep in mind that duplicated objects will stay as long as their time-to-live is positive.
I don't want to keep multiple copies in the cache. Is my approach of priming the url valid? Where I manually evict the old content by adding them to the ban lurker. And then forcing a cache miss myself to replace the content which were banned.
acl purge_prime {
"127.0.0.1";
"::1";
}
sub vcl_recv {
if (req.method == "PRIME") {
if (!client.ip ~ purge_prime) {
return(synth(405,"No priming for you. (" + client.ip + ")"));
}
# Add to the ban lurker. Purging existing pages.
ban("obj.http.x-host == " + req.http.host + " && obj.http.x-url == " + req.url);
# Call the backend to fetch new content and add it to the cache.
set req.method = "GET";
set req.hash_always_miss = true;
}
# ... other custom rules.
}
# ... other subroutines below, e.g. adding ban-lurker support etc.
The logic makes sense to me, I'm just worried because no-one else has done it (which I'm assuming there's a reason for).
Is this the wrong approach over using purge with restart, if so what's the best way to prime a url using a single http request?
A:
I suppose that your approach is simply not good because it uses bans.
Using purges as opposed to bans will allow you to leverage grace mode.
Restarts are perfectly fine - they will not result in two or more HTTP requests, but rather push the request through the VCL state machine once again.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the correct way to handle factual errors in quotes?
NB: This is not referring to simply correcting misquoted text or typos.
The answer to this question contains a paragraph quoted from "The Classical Tradition" (by Grafton, Anthony, Glenn W. Most, and Salvatore Settis) that listed a number of military academies including the École Polytechnique in Paris.
This was recently edited because the editor believed that "The Ecole Polytechnique does not aim anymore to train officers. The Ecole Spéciale Militaire de Saint Cyr is the one responsible for it." and the original text was replaced with the new institution. While this edit may genuinely be correcting a factual error in the quote, I don't believe that a quoted text should be edited in this manner as it means the quote is no longer a true representation of the source material. I rejected the edit for this reason but others accepted it and the edit went ahead.
Surely there is a better way to highlight/correct factual errors in quoted material than editing the quote itself?
A:
I've had to slap friendly fingers here before for that kind of thing. If its represented as a quote, it needs to be verbatim. If the person wants to paraphrase, it should not have quotes around it or be in a quotation block.
That being said, in the case of an English translation of a quote, I think it would be fair to tweak someone else's translation if the goal is to translate what was said better. Just don't represent your new translation as the previous translator's work.
The traditional way to note errors in the quoted source itself is by following it with the notation [sic]. This is a Latin adverb used here to mean roughly "Yes, I know there are issues, but this is how it was said."
A:
You are correct. It is inappropriate to modify the quote in this case, especially without any note that the quote has been altered. I have restored the quote and inserted [sic] after the name of the old academy (using the function of sic to indicate a surprising assertion), and I added the editor's note on the current academy in small text after the quote.
| {
"pile_set_name": "StackExchange"
} |
Q:
make Json.NET ignore $type if it's incompatible
I had a property of type IReadOnlyList<RoadLaneDto>. To be compatible elsewhere, I changed it to RoadLaneDto[]. Now, when I deserialize my old data, I get this error:
Newtonsoft.Json.JsonSerializationException : Type specified in JSON 'System.Collections.Generic.List`1[[Asi.Shared.Interfaces.DTOs.Map.RoadLaneDto, Asi.Shared.Interfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not compatible with 'Asi.Shared.Interfaces.DTOs.Map.RoadLaneDto[], Asi.Shared.Interfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Path 'Shapes[0].Lanes.$type', line 78, position 132.
What is the right approach to make these compatible? Can I make the $type a suggestion rather than a requirement? Can I write a custom converter of some kind that would handle this situation?
A:
In general I don't recommend serializing collection types, for precisely this reason: you want to be free to change the type of collection (though not necessarily the type of collection item) without serialization problems. If you want to implement a collection-interface-valued property with a specific collection type that differs from Json.NET's defaults, say a HashSet<T> for an ICollection<T>, you can allocate it in the default constructor of the containing class, and Json.NET will use the pre-allocated collection. To serialize only object types and not collection types, set TypeNameHandling = TypeNameHandling.Objects.
That being said, the following converter will swallow type information when deserializing an array of rank 1:
public class IgnoreArrayTypeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsArray && objectType.GetArrayRank() == 1 && objectType.HasElementType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (!CanConvert(objectType))
throw new JsonSerializationException(string.Format("Invalid type \"{0}\"", objectType));
if (reader.TokenType == JsonToken.Null)
return null;
var token = JToken.Load(reader);
var itemType = objectType.GetElementType();
return ToArray(token, itemType, serializer);
}
private static object ToArray(JToken token, Type itemType, JsonSerializer serializer)
{
if (token == null || token.Type == JTokenType.Null)
return null;
else if (token.Type == JTokenType.Array)
{
var listType = typeof(List<>).MakeGenericType(itemType);
var list = (ICollection)token.ToObject(listType, serializer);
var array = Array.CreateInstance(itemType, list.Count);
list.CopyTo(array, 0);
return array;
}
else if (token.Type == JTokenType.Object)
{
var values = token["$values"];
if (values == null)
return null;
return ToArray(values, itemType, serializer);
}
else
{
throw new JsonSerializationException("Unknown token type: " + token.ToString());
}
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then you can use it like:
public class RootObject
{
[JsonProperty(TypeNameHandling = TypeNameHandling.None)] // Do not emit array type information
[JsonConverter(typeof(IgnoreArrayTypeConverter))] // Swallow legacy type information
public string[] Lanes { get; set; }
}
Or, you can use the converter globally in settings and have it swallow type information for all arrays:
var settings = new JsonSerializerSettings { Converters = new JsonConverter[] { new IgnoreArrayTypeConverter() }, TypeNameHandling = TypeNameHandling.All };
Json.NET does support multidimensional arrays so extending support to arrays of rank > 1 would be possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
ERROR Error: Uncaught (in promise): The request contains malformed or mismatching credentials [ App ID does not match requested project. ]
I have tried to perform phone authentication using firebase,After putting the latest google-services.json file, the app was unable to generate OTP, It was throwing this error:
ERROR Error: Uncaught (in promise): The request contains malformed or mismatching credentials [ App ID does not match requested project. ]
A:
My problem is solved. I Just delete my build folder, uninstall app from device and then run my project again, now its working fine succesfully connected with firebase.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Retrieve data within specified dates from Multiple Tables in MySQL
I want to fetch those users that not performed action_id 110 within specified date range
Date Range
From - 2014-04-01
To - 2014-08-08
tbl_user
userid name email db_add_date
1 steve [email protected] 2014-04-08 01:11:37
2 mark [email protected] 2014-07-18 07:10:01
3 nelson [email protected] 2014-05-28 14:02:04
4 andrew [email protected] 2014-01-12 10:42:39
5 himou [email protected] 2014-03-22 23:32:04
tbl_points
id userid action_id points
1 2 110 10
2 1 100 45
3 1 110 10
4 4 104 25
5 3 100 28
Result will be
-------------
name email
-------------
nelson [email protected]
andrew [email protected]
himou [email protected]
A:
You should really have a DATETIME on the tbl_points, or maybe tbl_action, (instead of)/(as well as) the tbl_user for this, but using your current structure:
SELECT t.name, t.email
FROM tbl_user tu
LEFT JOIN tbl_points tp
ON tu.userid = tp.userid
AND tp.action_id = 110
WHERE tu.db_add_date NOT BETWEEN '2014-04-01' AND '2014-08-08'
AND tp.id IS NULL
| {
"pile_set_name": "StackExchange"
} |
Q:
get an array of dates for the past week in format dd_mm
I need to have an array of dates for whole days of the last week, including the current day, for e.g
['05/06', '04/06', '03/06', '02/06', '01/06', '31/05', '30/05']
(format dd/mm)
how can i do this?
I know there is the Date() object, but other than that I'm stumped.
logic along the lines of:
var dates = [];
var today = new Date();
for (var i = 0; i<7; i++){
var date = today - (i+1);
dates.push(date);
}
A:
So you want an array containing todays date and a further 6 elements, with todays date-1, todays date-2 etc...?
var dates = [];
var date = new Date();
for (var i = 0; i < 7; i++){
var tempDate = new Date();
tempDate.setDate(date.getDate()-i);
var str = tempDate.getDate() + "/" + tempDate.getMonth();
dates.push(str);
}
console.log(dates);
Output: ["5/5", "4/5", "3/5", "2/5", "1/5", "31/4", "30/4"]
If you need numbers with leading 0's, try this:
var dates = [];
var date = new Date();
for (var i = 0; i < 7; i++){
var tempDate = new Date();
tempDate.setDate(date.getDate()-i);
var str = pad(tempDate.getDate()) + "/" + pad(tempDate.getMonth());
dates.push(str);
}
console.log(dates);
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
Output: ["05/05", "04/05", "03/05", "02/05", "01/05", "31/04", "30/04"]
| {
"pile_set_name": "StackExchange"
} |
Q:
How I can store images in Database by using url to images
My problem is that I want to store images in database, but I don't want to store them physically in my project as static files, I want to save in database url to images which are already uploaded somewhere in Internet. How can I do this, just use CharField or TextField as type of field and paste url? But I also want later to display this photo in my template.
class Image(models.Model):
name = models.CharField(max_length=25, verbose_name='Image name')
image_file =
def __str__(self):
return self.name
A:
If you want to use the external image source link in you django project, all you need is storing image source link in you model which you already did this in you models.py:
name = models.CharField(max_length=25, verbose_name='Image name')
But if consider this that you can't use google images source's link because of some limit, read this article to understand why :
What Happened To Google Image Search And Why You Can No Longer View Images Directly
by the way you can use urlfiled instead of using charfiled, because it's only store urls. Django urlfield
after storing your image source link in your model, you can get it in you view the pass it too template and load the image in your template without downloading your image.
if you need any further help, ask and will happy to help.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cколько раз слово встречается в строке
Нужно узнать количество вхождений этого слова в строке.
Пример строки
'type, status, date, status'
Ищем вхождение слова status
A:
Вариант "в лоб" с помощью indexOf:
function countWord(source, word) {
if(!word)
return 0;
var res = 0, index = 0;
while((index = source.indexOf(word)) >= 0) {
source = source.substring(index + word.length);
res++;
}
return res;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Can someone explain something in this short Reverse Proxy guide?
Forgive my inexperience, but what rake file is he referring to, and how do I run it?
http://overwatering.org/blog/2012/04/reverse-proxy-javascript-app/
A:
It looks like he's set up a Rakefile to start Apache and run it in the foreground.
In your directory, just add that gist to a file named Rakefile and then run rake apache from the command line.
Alternatively, you could just type what is inside the exec %Q block if you don't want to set up a rake file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple Python program to create numeric values based on Unicode values, would like tips to streamline my code
print("This program will calculate the numeric value of a name given as input.")
name = input("Please enter your full name: ")
name_list = name.split(' ')
name_list2 = []
for x in name_list:
y = list(x)
for x in y:
name_list2.append(x)
print(name_list2)
num_value = 0
for x in name_list2:
y = ord(x)
print("The numeric value of", x, "is", y)
num_value = num_value + y
print("The numeric value of your name is: ", num_value)
Any tips on how to simplify this is appreciated, with my knowledge I couldn't see an easier way to split the list, split out each character (to avoid adding in the whitespace value of 32), and then add them up.
A:
You can iterate over the name and sum the ord's of each character excluding spaces from the count with if not ch.isspace():
name = input("Please enter your full name: ")
print("The numeric value of your name is: ", sum(ord(ch) for ch in name if not ch.isspace()))
If you want to see each letter use a for loop:
name = input("Please enter your full name: ")
sm = 0
for ch in name:
if not ch.isspace():
y = ord(ch)
print("The numeric value of", ch, "is", y)
sm += y
print("The numeric value of your name is: ", sm)
| {
"pile_set_name": "StackExchange"
} |
Q:
Change value of parameters inside Laravel Job Class
I'm trying to send an email with a job class in Laravel, the point is I need to keep track of the notificactions sent by mail. I have a table named "Notifications" wich has the columns status and lastUpdated (these are the one regarding this issue).
In order to update the row of the Notifications table I need to know the ID of that row.
I'm trying to change the value of a parameter which is a model being sent as parameter, inside a job class. This model is a "Notifications"
My question here is, do the parameters inside a job class persist to the next call once they've been changed from inside the class? Apparently is not working that way. If this is not possible, can someone suggest any workaround?
class SendReminderEmail extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
public function __construct($lastNotification)
{
$this->lastNotification = $lastNotification;
}
//NULL means it's the first time the job has been called
protected $lastNotification;
public function handle(Mailer $mailer)
{
$mailer->send('user.welcome', ['username' => 'Luis Manuel'], function($message)
{
$message->from('[email protected]', 'Luis');
$message->to('[email protected]', '[email protected]');
$message->subject('Subject here!');
});
if(count($mailer->failures()) > 0)
{
if($this->lastNotification == null)
{
$this->lastNotification = new Notification;
$this->lastNotification->status = false;
$this->lastNotification->lastUpdated = Carbon::now();
}
else
{
$this->lastNotification->status = false;
$this->lastNotification->lastUpdated = Carbon::now();
}
$this->lastUpdated->save();
}
}
}
A:
How I solved it:
Before dispatching the job inside a controller I created the Notification model, saved it an then passed it to the job class as parameter.
public function ActionSomeController()
{
$notification = new Notifiaction;
$notification->save();
$newJob = (new SendReminderEmail($notification));
$this->dispatch($newJob);
}
And in the Job Class :
public function __construct($notification)
{
$this->notification = notification;
}
public function handler(Mailer $mailer)
{
/*
* Some extra code abover here
*/
$this->notification->lastUpdated = Carbon::now();
}
And it works like a charm!
| {
"pile_set_name": "StackExchange"
} |
Q:
2003-2006 Honda Accord v6 - ATF refill amount
Greetings one and all,
I recently changed the transmission on my 03 Honda Accord V6 (Original could not go into reverse), I am trying to find out how much transmission fluid I should put back in it, I did some research online and some folks are saying 7 Quarts and some are saying 12. Can anyone here provide me with a credible answer to this question please?
I am trying to get my hands on a manual or someone from the Honda dealership to verify. If I find the info I will post the answer here, assuming no one replies before then.
Thanks Alot
A:
According to page 364 of the Owner's Manual, the V6 model has a capacity of 6.9 to 7.6 US quarts.
If you did not drain the torque converter, you should start with the "change" amount, then check levels.
Do not over fill it.
Note: unsure if you have the coupe or sedan. I selected the manual for the sedan. I would thing the capacities would be the same, but check anyway.
| {
"pile_set_name": "StackExchange"
} |
Q:
What .gitignore should I use for PHP in Github?
Github.com and Github Desktop both asked the format of .gitignore I wanna use when creating a new repo. But PHP is not in the selection.
So which should I select?
A:
Then try one of the PHP gitignore proposed by gitignore.io
It mainly depends on the editor you are using.
For instance: phpstorm+all.
In the OP's case, for Wordpress:
# Created by https://www.gitignore.io/api/wordpress
# Edit at https://www.gitignore.io/?templates=wordpress
### WordPress ###
# ignore everything in the root except the "wp-content" directory.
!wp-content/
# ignore everything in the "wp-content" directory, except:
# "mu-plugins", "plugins", "themes" directory
wp-content/*
!wp-content/mu-plugins/
!wp-content/plugins/
!wp-content/themes/
# ignore these plugins
wp-content/plugins/hello.php
# ignore specific themes
wp-content/themes/twenty*/
# ignore node dependency directories
node_modules/
# ignore log files and databases
*.log
*.sql
*.sqlite
# End of https://www.gitignore.io/api/wordpress
| {
"pile_set_name": "StackExchange"
} |
Q:
SVG graphic in FPDF
I need SVG data to print to an FPDF generated PDF. I'm bringing in said data from a post variable named $svg. When I try and write the variable to the page I get the entire data in text, not as an image (as expected), is there a way to get FPDF to draw the $svg on to the PDF? Below is my terrible attempt. Thanks.
$pdf->Write( 6, $svg);
A:
In PHP TCPDF supports .svg (http://www.tcpdf.org/)
| {
"pile_set_name": "StackExchange"
} |
Q:
PostgreSQL & Heroku - cannot connect to the database
I'm trying to add a column to a table via my Django app with South but keep getting the following error upon running the python manage.py migrate <app name> command:
conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not translate host name "ec2-107-21-99-105.comp
ute-1.amazonaws.com" to address: Temporary failure in name resolution
Does anybody have an idea why this is happening? I'm a newbie to both South AND the PostgreSQL database management system (which Heroku uses), so I am more than a bit confused.
A:
Make sure you have defined your default database in settings.py like this:
DATABASES = {
'default': dj_database_url.config(default=os.environ.get('DATABASE_URL'))
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Extracting and Printing multiple elements from different vectors in R
I have a Data Frame with over 20 columns and am trying to create a new object which returns the maximum value of one vector and also returns the value in the same row of a different vector/variable. I have been reading through many many pages/sites on extracting elements but none that I have found seem relevant in my context.
Here is the code I am using:
object <- DF[which.max(DF[,ColNumber]),"VARNAME"]
What this line of code is doing is finding the row that corresponds to the maximum value for ColNumber and then printing ONLY the value of VARNAME for that row. How can I get R to return/print BOTH VARNAME's value AND the max value?
A:
An alternative using dplyr. First select columns of interest from dataset, mtcars. Then filter the max value of disp.
data(mtcars)
library(dplyr)
select(mtcars, mpg, disp) %>% filter(disp==max(disp))
# mpg disp
# 1 10.4 472
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP OOP: retrieve data from database
I'm pretty new to OOP (and also in PHP programming), and I have some troubles using objects and interfacing them with db data (MySql in my case, but this is irrelevant).
I have on the DB a table USERS. I declared a class User in the PHP code, with the various properties and methods I need. The problem is interfacing this thing to db.
I put code to retrieve data from the db in the constructor, so when I need to work on a specific user, I simply write $user = new User($user_id); and start working with the object.
When I've done I call a method on the object to save data on db, and this works pretty well.
The problem arise when I need data about many users in a single page, as in showing the complete list of users. With this approach, when I need the list of users, I have to instantiate all the objects, and this causes the code to make too many queries of the type SELECT * FROM users WHERE user_id = ..., instead than a single query such as SELECT Only_needed_fields FROM users WHERE 1 LIMIT 20 as I would've done in procedural code.
Which is the correct OOP approach to such a problem? Which is the good-practise alternative to retrieving data in the constructor?
Notice Please, don't suggest using frameworks of any kind - I'd like learn pure OOP PHP before using abstraction layers -
A:
Your problem is that you are not seperating the layers of your application. What you should do is have a factory class instantiating your users that handles the database calls and let the user class only handle the business logic. This will also contribute to the testability of your code.
Your factory class could have two methods. One for loading a single user and instantiating it and another for loading a set of users.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I use a macOS installation on an external drive with different hardware
If I install macOS Mojave to an external USB drive using computer A, can I then use that drive and macOS installation on a computer B with different hardware? And then back on computer A? Even if possible, is it risky or il-advised?
A:
Yes, you can do this confidently. It is neither risky nor ill-advised. It has been very well supported since the very earliest days of the Macintosh platform.
The only gotchas to be wary of is that you need to use a version of macOS that supports whatever machines you want to use it on. In some cases, if a new model of Mac comes out after, say, macOS Mojave 10.14.2 ships, that new Mac hardware might require a special version of 10.14.2 that has a few extra drivers and bug fixes that the general public release of 10.14.2 didn't have. So sometimes you have to make sure that you're installing that special version of macOS (in this example 10.14.2) on that external mass storage device. Then, once the next macOS update ships (in this example 10.14.3), it will have all the special pieces that were required by that new hardware, so you no longer need a special version to boot that hardware; you can just use the publicly released 10.14.3.
| {
"pile_set_name": "StackExchange"
} |
Q:
What exactly does it mean for a scalar function to be Lorentz invariant?
If I have a function $\ f(x)$, what does it mean for it to be Lorentz invariant? I believe it is that $\ f( \Lambda^{-1}x ) = f(x)$, but I think I'm missing something here.
Furthermore, if $g(x,y)$ is Lorentz invariant, does this means that $g(\Lambda^{-1}x,\Lambda^{-1}y)=g(x,y)$?
$\ $
EDIT: Allow me to explain the source of my confusion....I've been looking at resources online, where it says that the definition should be $\phi^{\prime}(x^{\prime})=\phi(x)$. But $\phi^{\prime}(x)=\phi(\Lambda^{-1}x)$ under a Lorentz transformation $x^{\prime}=\Lambda x$. So then I get:
$\phi^{\prime}(x^{\prime})=\phi(\Lambda^{-1}x^{\prime})=\phi(\Lambda^{-1}\Lambda x)=\phi(x)$
This seems completely trivial, and doesn't look like a condition I would need to check on a case-by-case basic.
A:
It may look trivial, but that's what it is.
A Lorentz scalar is an element of the 0-dimensional vector space considered as a representation space of the trivial $(0,0)$ representation of the Lorentz group.
In other words, a scalar $s$ transforms trivially:
$$s \rightarrow s' = s$$
A Lorentz vector is an element of the 4-dimensional vector space considered as a representation space of the standard $(\frac{1}{2}, \frac{1}{2})$ representation of the Lorentz group.
In other words, a vector $\mathbf{v}$ transforms as:
$$\mathbf{v} \rightarrow \mathbf{v}' = \mathbf{\Lambda} \mathbf{v}$$
$\mathbf{\Lambda}$ is the Lorentz transformation matrix.
A scalar function, such as $\phi(\mathbf{x})$ maps a Lorentz vector to a Lorentz scalar, i.e.
$$\mathbf{x} \mapsto \phi(\mathbf{x})$$
Consequently, it transforms to
$$ \mathbf{\Lambda x} \mapsto \phi'(\mathbf{\Lambda x}) = \phi(\mathbf{x}) $$
Therefore,
$$\phi' (\mathbf{x}) = \phi (\mathbf{\Lambda^{-1} x})$$
Indeed,
$$\phi' (\mathbf{x'}) = \phi (\mathbf{\Lambda^{-1} \Lambda x}) = \phi (\mathbf{x})$$
A:
You can also think of a scalar this way: it's a function $F$ that maps points of spacetime to numbers.
So, if $q$ is a point in spacetime, the representative of $F$ relative to a coordinate system $q \rightarrow x(p)$ is, say, $f$, defined by $f(x(q)) = F(q)$. If we have a second coordinate system $x' = \Lambda \cdot x$, then the representative of $F$ with respect to the new coordinate system is $f'(x'(q)) = F(q)$, so $f'(\Lambda \cdot x(q)) = f(x(q))$ or $f'\circ \Lambda = f$ or, finally, $f' = f \circ \Lambda^{-1}$.
The point is that while $F$ is independent of any coordinate system, its representatives w.r.t. different coordinate systems have to be related in this way since they're all tied to the same $F$.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.