text
stringlengths 175
47.7k
| meta
dict |
---|---|
Q:
A webapp that uses Spring AMQP is that consired to be 1 client?
Hi there i am wondering if i create a webapp that uses Spring AMQP. Is that single webapp 1 AMQP client? Or is every request made by a user that results into an AMQP call a client, so potentially x numbers of clients?
A:
I don't know AMQP much, but I suspect it has the same terminology as jms. In that sense your application is probably pooling connections to AMQP broker for better performance. Each connection in a pool is treated as a separate client (competing consumer).
Thus each request is not really creating a new connection (client), but your application isn't a single client as well. In fact, when your application tries to access AMQP broker, it picks any connection from the pool and puts it back once it's done. Another request can reuse the same connection (client) or use a different, idle one.
| {
"pile_set_name": "StackExchange"
} |
Q:
How create a JLabel when I pass with mouse on the button
(JAVA) I would that when I move my mouse on a particular button I can read the function of this button like a Jlabel that it is created expressly for this event under the mouse position.
I think at this approach:
1) capture mouseEvent and in particular MouseEntered
2) create a Jlabel and display it
I want know if exists another approach to do this or only my method. Anyone can help me?
A:
The easiest way is to provide a ToolTip. The framework then takes care about the label and event handling.
Note: setToolTipText is a method of JControl, so this work with other controls as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
QEmu-ARM-Ubuntu: CPU1: failed to boot: -38
How to fix "CPU1: failed to boot: -38" issue in QEmu?
I am hosting Ubuntu 16.04 on Virtual Box from Windows 10. Inside that Ubuntu 16.04, there is QEmu emulating ARM processor, running Ubuntu Trusty (14.04). When the ARM-Ubuntu boots, it prints to console "CPU1: failed to boot: -38" and something similar multiple times. Is it a matter of some command-line switch to QEmu, or configuration files? Or is it a bug or lack of support of QEmu ARM emulation inside another VM?
Effectively the ARM-Ubuntu uses only 1 core out of 6 available in the physical machine and the middle virtual machine.
To setup ARM-Linux on QEmu I mostly followed these steps. I had to do something differently, e.g. because Ubuntu Sauce is no more available. Specifically the steps I did are:
# 1) setup the rootfs
sudo apt-get install qemu-user-static qemu-system-arm
mkdir vexpress
cd vexpress
mkdir qemu-img
# Create 8-GB image
dd if=/dev/zero of=./vexpress-8G.img bs=8M count=1024
sudo losetup -f ./vexpress-8G.img
sudo mkfs.ext4 /dev/loop0
sudo mount /dev/loop0 qemu-img
# Bootstrap Ubuntu Trusty armhf rootfs in the qemu-img directory
# For Ubuntu versions later than Trusty some commands fail
# For Ubuntu versions before Saucy there is no port to ARM
# Ubuntu Saucy is not supported anymore
sudo qemu-debootstrap --arch=armhf trusty qemu-img
sudo cp `which qemu-arm-static` qemu-img/usr/bin/
# setup serial console, apt repositories and network
sudo chroot qemu-img
sed 's/tty1/ttyAMA0/g' /etc/init/tty1.conf > /etc/init/ttyAMA0.conf
echo "deb http://ports.ubuntu.com trusty main restricted multiverse universe" > /etc/apt/sources.list
apt-get update
echo -e "\nauto eth0\niface eth0 inet dhcp" >> /etc/network/interfaces
# root password
passwd
# 2) pick and install a kernel
# Fix locale problems http://askubuntu.com/questions/162391/how-do-i-fix-my-locale-issue
locale
sudo locale-gen "be_BY.UTF-8"
sudo locale-gen "en_US"
sudo locale-gen "en_US.UTF-8"
sudo dpkg-reconfigure locales
apt-get install wget ca-certificates
wget https://launchpad.net/ubuntu/+archive/primary/+files/linux-image-3.13.0-24-generic-lpae_3.13.0-24.46_armhf.deb
dpkg -i linux-image-3.13.0-24-generic-lpae_3.13.0-24.46_armhf.deb
# So far I'm getting the following warnings:
# Warning: cannot read table of mounted file systems: No such file or directory
# warning: failed to read mtab
# !!! press CTRL+D to exit the chroot
^D
# 3) Boot it up
# copy kernel, initrd and dtb files
sudo cp qemu-img/boot/vmlinuz-3.13.0-24-generic-lpae .
sudo cp qemu-img/boot/initrd.img-3.13.0-24-generic-lpae .
sudo cp qemu-img/lib/firmware/3.13.0-24-generic-lpae/device-tree/vexpress-v2p-ca15-tc1.dtb .
# umount the rootfs img
sudo umount qemu-img
sudo chmod 777 vmlinuz-3.13.0-24-generic-lpae
sudo chmod 777 initrd.img-3.13.0-24-generic-lpae
sudo chmod 777 vexpress-v2p-ca15-tc1.dtb
sudo chmod 777 vexpress-8G.img
# http://unix.stackexchange.com/questions/167165/how-to-pass-ctrl-c-in-qemu
# Allow Ctrl+C and Ctrl+Z on guest, changing them on host to Ctrl+] and Ctrl+[
stty intr ^]
stty susp ^j
qemu-system-arm --drive format=raw,if=sd,file=vexpress-8G.img -kernel vmlinuz-3.13.0-24-generic-lpae -initrd initrd.img-3.13.0-24-generic-lpae -M vexpress-a15 -serial stdio -m 2048 -append 'root=/dev/mmcblk0 rw mem=2048M raid=noautodetect rootwait console=ttyAMA0,38400n8 devtmpfs.mount=0' -dtb ./vexpress-v2p-ca15-tc1.dtb
# Still getting error: "CPU1: failed to boot: -38"
A:
The specific machine you're emulating (vexpress-v2p-ca15-tc1) is a dual-core one, so the kernel will try to bring up the secondary CPU it sees described in the DTB you're passing. However, since QEMU is only emulating a single CPU, the secondary naturally fails to come online on account of not existing.
The message in and of itself is perfectly harmless, but if you're allergic to error messages, just add maxcpus=1 to the kernel command line to prevent Linux even trying to bring up any secondary cores. If you really want to emulate both cores, pass the -smp 2 option to QEMU, although it may well result in more emulation overhead and be slower overall.
| {
"pile_set_name": "StackExchange"
} |
Q:
Placing a sign, given from a generator, not working
I am using the Animated Scoreboard sign generator. The problem is that when I place the sign that the generator gave me, the sign looks like this:
As you can see the content is "" instead of Click Here. What am I doing wrong?
Note: I use Minecraft 1.9 with OptiFine 1.9 pre 04.
Also note: I am doing this on a vanilla server.
The command I use that is generated can be found here: http://pastebin.com/VehNSpnx
A:
If you are using the 1.8 version of Minecraft then the problem could be that you are using the 1.9 version of Sign Generator.
I recommend using https://minecraftcommand.science/command-sign-generator for any 1.8 signs.
Another problem could be mods you have downloaded. If you have an older version of Minecraft and you are using a higher version mod/ or vice versa then that could be causing the problem. Both are trying to use different versions of Minecraft causing disruptions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to format vue template to have all tag attributes at the same line
Several iterations ago one of our devs applied --fix with eslint rule vue/max-attributes-per-line on whole codebase so we are having max 1 attribute per line in our vue templates.
Is there any way to format it back?
was trying to use phpStorm format option "wrap attributes": "Do not wrap" but it doesnt work on already wrapped attributes..
any ideas?
A:
Make sure to disable Keep line breaks and set Wrap Attributes: to Do not wrap in File | Settings | Editor | Code Style | HTML | Other
| {
"pile_set_name": "StackExchange"
} |
Q:
ssh.net check file extension
I used SSH.NET library to connect to sftp server and manage to download file from server. In the server there is lot of file types I only need CSV file to download. How can I check the file extension GetExtension is not working in SSH.NET. Help is highly appreciate.
foreach (var file in files)
{
if (!file.Name.StartsWith("."))
{
string remoteFileName = file.Name;
using (Stream fileStream = System.IO.File.OpenWrite(Path.Combine(sFilePath, file.Name)))
{
sftp.DownloadFile(file.FullName, fileStream);
}
}
}
A:
I found a solution I'm posting it here for helping anyone who has the same problem like me.
string fname = file.Name;
string ext = fname.Substring(fname.Length - 4, 4);
if (ext == ".csv")
{
//code goes here
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Shopping PHP API Last Page ProductList
I am cycling through the Product List pages, I know each page returns several fields and one of them is nextPageToken, the thing is that so far, all pages have this token, I haven't been able to find a way to recognize the last page.
Any idea on how to do it?
A:
the last page is simply the page with no nextPageToken in the body it returns
| {
"pile_set_name": "StackExchange"
} |
Q:
Exclude some classes from Proguard's keep rules
I have a library that is about to be obfuscated using ProGuard. "Library mode" is almost applicable for my use case, i.e. it is almost fine to keep all public and protected classes and class members.
However due to Java's visibility requirements some members cannot be made package private or private and thus they are public classes although they should not be in the library. I would like to have them obfuscated to make it more clearly that these classes do not belong to the public api, as well as to get better obfuscation and smaller library jars.
Is there a way to exclude some items from a proguard "keep" rule without specifying each of these items by name (using the '!').
Ideally I would like to annotate these classes and members with a tagging annotation, but as far as I understand Proguard can only be told to keep items with certain annotations.
A:
You can only keep items indeed. If you want to exclude certain class members, you have to do so by listing or annotating the class members that you do want to keep. When specifying a class name, you can provide a list, optionally with "!" to exclude names. When specifying a class member name and type, that is not possible. Still, in both cases, you can use wildcards. If you pick special names for your internal classes, this might work:
-keep public class * {
public protected *** !myInternalField*;
public protected *** !myInternalMethod*(...);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Existe alguma maneira de autoajustar o site para celulares?
estou fazendo um mini-projeto onde no PC o mesmo não apresenta problemas na visualização da página. Mas quando testo no celular a coisa muda um pouco de figura, vejam o print dos dois testes por favor:
No primeiro a parte do painel fica ocupando o footer, o meu código é basicamente este:
<div class="panel panel-default">
<div class="panel-body">
Conteúdo aqui.
</div></div>
Já no segundo o site fica todo deformado, a ponto de certos objetos desaparecerem da página. Existe algum ajuste ou script que posso usar para contornar esse problema? Obrigado desde já.
A:
Existe sim, você pode inclusive utilizar algum framework exemplo: Bootstrap.
Vou deixar um exemplo abaixo caso você não queira utilizar nenhum framework e fazer tudo na 'mão' :
/* Small devices ( @screen-sm-min Phones (<768px) ) */
@media (min-width: 368px) {
}
/* Small devices (@screen-sm-min tablets, 768px and up) */
@media (min-width: 768px) {
}
/* Medium devices ( @screen-md-min desktops, 992px and up) */
@media (min-width: 992px) {
}
/* Large devices ( @screen-lg-min large desktops, 1200px and up) */
@media (min-width: 1200px) {
}
Agora dentro de cada @media você pode alterar seus containers, elementos, etc... de acordo com a resolução.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting Datacontext
Okay, I'm going to try and explain my excercise now..
This is my PageOverzicht.xaml, and this code works. It gives me a dropdown with the colors of the flowers in (blue, orange, white, ...). Now the datacontext is hardcoded to find the flowers with white color.
Goal: set datacontext via code behind, so that the next step can be to use selectionchanged property to select flowers with the selected color.
So now I need to set datacontext first so that it is not hardcoded to white..
Listbox consists out of xml nodes, names of plants that have the color white, using the Page_Loaded method from PageOverzicht.
<Page x:Class="Planten_BIS.PageOverzicht"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Planten_BIS"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="PageOverzicht">
<Page.Resources>
<XmlDataProvider x:Key="CatalogDataSource" XPath="catalog" Source="data/catalogus.xml"></XmlDataProvider>
<DataTemplate x:Key="listItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Name="ImageName" Visibility="Collapsed" Text="{Binding XPath=botanical, StringFormat=images/{0}.jpg}" />
<Border BorderBrush="white" BorderThickness="2" CornerRadius="10" Background="{StaticResource AchtergrondKleur}">
<Rectangle Width="100" Height="100" RadiusX="10" RadiusY="10">
<Rectangle.Fill>
<ImageBrush ImageSource="{Binding Text, ElementName=ImageName}" />
</Rectangle.Fill>
</Rectangle>
</Border>
<StackPanel Orientation="Vertical" Margin="10" VerticalAlignment="Center">
<ListBoxItem Content="{Binding XPath=common}"/>
<ListBoxItem Content="{Binding XPath=price}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</Page.Resources>
<Grid>
<ListBox Name="ListboxFlowers" Background="Transparent" Foreground="white" DataContext="{Binding Source={StaticResource CatalogDataSource}, XPath=color[@name\=\'White\']/plant}" ItemsSource="{Binding}" ItemTemplate="{StaticResource listItemTemplate}"></ListBox>
</Grid>
</Page>
little part from xml where data comes from:
<?xml version="1.0" encoding="ISO8859-1" ?>
<catalog>
<color name="White">
<plant>
<common>Jacob's Ladder</common>
<botanical>Polemonium caeruleum i</botanical>
<zone>Annual</zone>
<light>Shade</light>
<price>$9.26</price>
<availability>022199</availability>
<color>white</color>
<description>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</description>
</plant>
Mainwindow with frame to PageOverzicht:
<Window x:Class="Planten_BIS.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
xmlns:local="clr-namespace:Planten_BIS"
mc:Ignorable="d"
Title="Plant Catalog" Height="600" Width="800">
<Window.Resources>
<Style x:Key="buttonStyle" TargetType="Button">
<Setter Property="Background" Value="{StaticResource ToolBarKleur}" />
<Setter Property="BorderBrush" Value="{StaticResource RandKleur}" />
<Setter Property="Foreground" Value="{StaticResource LetterKleur}" />
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="6" />
</Style>
<Style x:Key="comboStyle" TargetType="ComboBox">
<Setter Property="Background" Value="{StaticResource ToolBarKleur}" />
<Setter Property="BorderBrush" Value="{StaticResource RandKleur}" />
<Setter Property="Foreground" Value="{StaticResource LetterKleur}" />
<Setter Property="Width" Value="100" />
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="6" />
</Style>
<XmlDataProvider x:Key="CatalogDataSource" XPath="catalog" Source="data/catalogus.xml"></XmlDataProvider>
<CollectionViewSource x:Key="cvsColors" Source="{StaticResource CatalogDataSource}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="color" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
<DataTemplate x:Key="comboItemTemplate">
<Label Content="{Binding XPath=@name}"/>
</DataTemplate>
</Window.Resources>
<DockPanel LastChildFill="True">
<ToolBar Background="{StaticResource ToolBarKleur}" DockPanel.Dock="Top">
<Button Style="{StaticResource buttonStyle}" Content="Backward"></Button>
<Button Style="{StaticResource buttonStyle}" Content="Forward"></Button>
<ComboBox Style="{StaticResource comboStyle}" SelectedIndex="0" ItemsSource="{Binding Source={StaticResource CatalogDataSource}, XPath=color}" ItemTemplate="{StaticResource comboItemTemplate}"></ComboBox>
</ToolBar>
<Frame Source="PageOverzicht.xaml" Name="frame" NavigationUIVisibility="Hidden">
<Frame.Background>
<ImageBrush ImageSource="assets/background.jpg" Stretch="UniformToFill"/>
</Frame.Background>
</Frame>
</DockPanel>
</Window>
A:
The data source handling should be moved to a control which is the common parent of the ComboBox and the Frame, in this case I chose the MainWindow.
You should add the required DependecyProperty definitions to the MainWindow which can be used for data binding for the ComboBox.ItemsSource, ComboBox.SelectedItem and the Frame.DataContext.
For the XML handling I replaced the XMLDataProvider with an XElement data source which allows LINQ To XML in order to comfortably filter or traverse the XML object tree in C#.
Now the ComboBox binds to a collection of XElement items representing XML color nodes. The selected ComboBox item is a single XML color element. The descendant plant nodes of color are used to set the Frame.DataContext, which is inherited to the Page.DataContext. The ListBox in the Page now binds its ItemsSource directly to the DataContext which is the MainWindow.PlantsOfSelectedColor property. Alternatively, e.g. if you need to set the Page.DataContext to something different, you can let the Binding traverse the visual tree to find the MainWindow.PlantsOfSelectedColor using RelativeSource FindAncestor for the Binding.RelativeSource of ListBox.ItemsSource.
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public static readonly DependencyProperty PlantColorNodesProperty = DependencyProperty.Register(
"PlantColorNodes",
typeof(IEnumerable<XElement>),
typeof(MainWindow),
new PropertyMetadata(default(IEnumerable<XElement>)));
public IEnumerable<XElement> PlantColorNodes
{
get => (IEnumerable<XElement>) GetValue(MainWindow.PlantColorNodesProperty);
set => SetValue(MainWindow.PlantColorNodesProperty, value);
}
public static readonly DependencyProperty SelectedPlantColorNodeProperty = DependencyProperty.Register(
"SelectedPlantColorNode",
typeof(XElement),
typeof(MainWindow),
new PropertyMetadata(default(XElement), OnSelectedPlantColorNodeChanged));
public XElement SelectedPlantColorNode
{
get => (XElement) GetValue(MainWindow.SelectedPlantColorNodeProperty);
set => SetValue(MainWindow.SelectedPlantColorNodeProperty, value);
}
public static readonly DependencyProperty PlantsOfSelectedColorProperty = DependencyProperty.Register(
"PlantsOfSelectedColor",
typeof(IEnumerable<XElement>),
typeof(MainWindow),
new PropertyMetadata(default(IEnumerable<XElement>)));
public IEnumerable<XElement> PlantsOfSelectedColor
{
get => (IEnumerable<XElement>) GetValue(MainWindow.PlantsOfSelectedColorProperty);
set => SetValue(MainWindow.PlantsOfSelectedColorProperty, value);
}
public MainWindow()
{
InitializeComponent();
// Open XML an collect all 'color' nodes
this.PlantColorNodes = XElement.Load("data/catalogus.xml").Elements("color");
}
private static void OnSelectedPlantColorNodeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var colorNode = e.NewValue as XElement;
// Get the 'plant' child nodes of the selected 'color' node
(d as MainWindow).PlantsOfSelectedColor = colorNode.Elements();
}
}
MainWindow.xaml
<Window>
<DockPanel LastChildFill="True">
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=PlantColorNodes}"
SelectedItem="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=SelectedPlantColorNode}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Attribute[name].Value}" />
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox>
<Frame DatContext="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=PlantsOfSelectedColor}"
Source="PageOverzicht.xaml" />
</DockPanel>
</Window>
PageOverzicht.xaml
<Page>
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Element[botanical].Value}" />
<TextBlock Text="{Binding Element[common].Value}"/>
<TextBlock Text="{Binding Element[price].Value}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Page>
| {
"pile_set_name": "StackExchange"
} |
Q:
Best approach to additive collection mapping with Orika?
Is it possible to define an additive mapping strategy for collections with Orika?
I am currently using a mixture of Orika and a custom implementation - however its not an approach that will scale very well.
A:
Yes, actually in Orika, you can define any merge strategy for collection all you have to do is to register a custom mapper between two collections
please take a look at this unit test .
| {
"pile_set_name": "StackExchange"
} |
Q:
periods converted to underscores
Fellow coders, i have a function in a codeigniter controller that accepts a couple of parameters one of them being an email address. it is called liked this:
domain/path/mycontroller/myfunc/email@gmail.com/anotherparam
what the controller is receiving is: email@gmail_com
i have allowed periods and '@' in my CI config:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-@';
and my .htaccess is the following:
RewriteEngine On
RewriteBase /myapp/
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /myapp/index.php?/$1 [L]
Any thoughts on how i can solve this problem?
thanks
A:
Found a related post on the CI forum from 2008:
http://codeigniter.com/forums/viewthread/94091/
Looks like some people were having the exact same problem, and tweaking the $config['uri_protocol'] in config.php was the solution.
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of "AUTO" works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'AUTO' Default - auto detects
| 'PATH_INFO' Uses the PATH_INFO
| 'QUERY_STRING' Uses the QUERY_STRING
| 'REQUEST_URI' Uses the REQUEST_URI
| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol'] = "QUERY_STRING";
At least one person reported that the QUERY_STRING value fixed their problem. If this doesn't work, try one of the other delicious flavors settings.
Hope this gets you on the right path to a solution.
| {
"pile_set_name": "StackExchange"
} |
Q:
Column Space of a matrix contained in Null Space of other matrix
So I have $CS(A)$ is the subset of $NS(B)$. How do I show that $(AB)^2$ is zero matrix. $A$ and $ B$ are $n$ by $n$ matrices.
A:
Consider any vector $x.$ Then $ABx\in \rm{CS}(A).$ Since $\rm{CS}(A)\subset \rm{NS}(B)$ we have that $BABx=0.$ So
$$(AB)^2x=ABABx=A0=0.$$ Since $x$ is arbitrary we conclude that $(AB)^2=0.$
| {
"pile_set_name": "StackExchange"
} |
Q:
how to include blade file in Laravel 5.2
I am developing Laravel application and I need add comment form to My each task file regarding to each project.
this is comments/form.blade.php
<form class="form-vertical" role="form" method="post" action="{{ route('projects.comments.create', $project->id) }}">
<div class="form-group{{ $errors->has('comments') ? ' has-error' : '' }}">
<textarea name="comments" class="form-control" style="width:80%;" id="comment" rows="5" cols="5"></textarea>
@if ($errors->has('comments'))
<span class="help-block">{{ $errors->first('comments') }}</span>
@endif
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">Add Comment</button>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
I am going to include this form file to show.blade.php file in tasks folder in view file.
this is show.blade.php
<h2>{{ $tasks->project->project_name }}</h2>
<hr>
{{$tasks->task_name}}
<hr>
{!!$tasks->body!!}
<hr>
@include('comments.form')
commentController.php
public function postNewComment(Request $request, $id, Comment $comment)
{
$this->validate($request, [
'comments' => 'required|min:5',
]);
$comment->comments = $request->input('comments');
$comment->project_id = $id;
$comment->user_id = Auth::user()->id;
$comment->save();
return redirect()->back()->with('info', 'Comment posted successfully');
}
routes.php
Route::post('projects/{projects}/comments', [
'uses' => 'CommentsController@postNewComment',
'as' => 'projects.comments.create',
'middleware' => ['auth']
]);
but finally got this error massage
Undefined variable: project (View: C:\Users\Nalaka\Desktop\acxian\resources\views\comments\form.blade.php)
how can fix this problem?
A:
You have not defined $project anywhere but you have $tasks from which you are getting project name already in show.blade.php so if you have project id also there in $tasks->project data then you can use this variable in view change form tag in comments/form.blade.php as below:
<form class="form-vertical" role="form" method="post" action="{{ route('projects.comments.create', $tasks->project->id) }}">
| {
"pile_set_name": "StackExchange"
} |
Q:
Xdebug can't connect back to Docker host
I've just setup Docker on my machine & have an Nginx/PHP7 (FPM)/MySQL setup all working fine, but having installed Xdebug on the PHP container I can't get it to connect back to PHPStorm on my host machine.
Here's my PHP Xdebug config…
zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-
20151012/xdebug.so
xdebug.remote_log=/usr/local/var/log/xdebug.log
xdebug.remote_enable=1
xdebug.remote_host=192.168.99.1
xdebug.remote_port=9000
xdebug.remote_connect_back=1
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_autostart=true
When browsing, with the Xdebug enable cookie set for the container, there's no prompt for a connection. If I browse a locally hosted site, there is, so I know PHPStorm's listening correctly.
On the local machine, I can telnet to port 9000…
$ telnet 192.168.99.1 9000
Trying 192.168.99.1...
Connected to 192.168.99.1.
Escape character is '^]'.
^]
telnet> quit
Connection closed.
… however I cannot from either the boot2docker VM, or the container. When I try it just sits there doing nothing. Both the VM and the container can, however, ping the host machine just fine.
I've tried disabling my Mac's firewall, but still no joy.
I'm not quite sure how to disable the firewall on the boot2docker VM.
Any insight into why this won't work would be greatly welcomed. Thanks in advance.
A:
Xdebug recommended config inside Container:
zend_extension = xdebug.so
xdebug.remote_enable = 1
xdebug.remote_connect_back = 0
xdebug.remote_host = docker.for.mac.localhost
xdebug.remote_port = 9000
xdebug.remote_handler = dbgp
xdebug.remote_mode = req
xdebug.remote_autostart = 1
xdebug.idekey = PHPSTORM
Since Docker-17.06, you can access services hosted on Mac inside Container, via the static host name: docker.for.mac.localhost
I WANT TO CONNECT FROM A CONTAINER TO A SERVICE ON THE HOST ?
The Mac has a changing IP address (or none if you have no network access). From 17.06 onwards our recommendation is to connect to the special Mac-only DNS name docker.for.mac.localhost which resolves to the internal IP address used by the host.
see https://docs.docker.com/docker-for-mac/networking/#i-cannot-ping-my-containers
| {
"pile_set_name": "StackExchange"
} |
Q:
Quickly kill processes containing word
$ ps aux | grep ruby
user 1565 3.7 0.1 4307464 17696 s000 S+ 7:31AM 0:00.61 /Users/user/.rbenv/versions/2.3.1/bin/ruby bin/rails c
user 1579 0.0 0.0 4268020 788 s001 S+ 7:31AM 0:00.00 grep ruby
user 1489 0.0 0.0 0 0 ?? Z 7:29AM 0:00.00 (ruby)
How do I quickly kill all these processes?
What I tried:
kill -9 `ps aux | grep ruby`
My environment:
$ bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)
Copyright (C) 2007 Free Software Foundation, Inc.
$ uname -a
Darwin MacBook-Pro.local 18.0.0 Darwin Kernel Version 18.0.0: Wed Aug 22 20:13:40 PDT 2018; root:xnu-4903.201.2~1/RELEASE_X86_64 x86_64
$
A:
As Haxiel commented, my recommendation would be to use pkill:
pkill -9 ruby
| {
"pile_set_name": "StackExchange"
} |
Q:
Dialogs between users in iPhone
How to make similar dialogues between users in iOS as shown in the picture. Should I use just for this ScrollView and Labels or I can using some standart way?
A:
you have to create it. here is a nice tut that creates a chat bubble. take a look at his work and you'll see how it can be done. http://alexbarinov.github.io/UIBubbleTableView/
also here is the link to a github project that could be useful for you. https://github.com/AlexBarinov/UIBubbleTableView
alex has done a great job explaining everything, so this might be what you are looking for.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does integrating WebRTC one to one audio/video calls affect the performance of web application
After knowing about some great features of WebRTC, I thought of using WebRTC one to one audio/video calls in my web application. The web application is for many organizations/entities of a category who can register and keep recording several records daily for their internal working and about their clients. The clients of these individual organizations/entities also have access to the web application to access their details.
The purpose of using WebRTC is for communication between clients and organizations. Also for daily inquires by new people to these organizations about products and services.
While going through articles on google etc. I found broadcasting or one to many calls requires very high bandwidth to users if we don't make use of Media Server.
So what is the case for one to one calls?
Will it affect the performance of web application or bring any critical situation if several users are making audio/video calls(one to one) to each other simultaneously as a routine?
The number of users will be very large and users will be recording daily several entries as their routine work. But still it is manageable and application will be running smoothly but I am not sure about the new concept WebRTC. Will it require a very high hosting plan? Is using WebRTC for current scenario suitable or advisable?
A:
WebRTC by its nature is Peer-to-Peer. Meaning that the streaming data is handled CLIENT side. All decoding, encoding, ICE candidate gathering/negotiation, and media encrypting/transmitting will happen on the client side and not on server side. So, you will be providing the pages, client side JS, and some data exchange(session negotiation signalling) but all in all, it is not a huge amount of work. It should be easily handled without having to worry about your host machine being over worked.
All that said, here are the only a performance concerns that would POSSIBLY affect your hosting server.
Signalling session startup, negotiations, and tare down. This is very minimal(only some json data at the beginning of a session). This should not be too much of a burden but you should be aware that if 1000 sessions start at the same time, you will have a queue of messages to direct to the needed parties. How you determine the parties, forward the messages, and what work you do server side could all affect performance. If written smartly(how to store sessions, how to forward messages, etc.) should not be a terrible burden.This could easily done with SignalR since you are on ASP.NET or you could use a separate one running Node.js(or the same box, does not matter) if you so desired.
RTP TURN relay if needed. This will probably be through a different server(or the same one as your hosting server if you want). For SOME connections, a TURN server is needed and any production ready WebRTC solution should take this into account. Here is a good open source turn server. Bandwidth usage here could be very high as RTP packets are sent to this server and the forwarded to the peer in the connection.
If you are recording the streams, you may have increased hosting traffic depending on how you implement it. Firefox supports client side recording of the streams but Chrome does not(they say it is in the works currently). You could use existing JS libraries to record the feeds client side and then push them anywhere you want. You could also push all the data through a MediaServer that will mux, demux, and forward the data to be recorded anywhere you like. Janus-Gateway videoroom is a good lightweight example of a mediaserver.
Client side is a different story.
There are higher level concerns in the Javascript. If you use one of the recording JS libraries, this is especially evident as they do canvas captures numerous times a second which are a heavy hit and would degrade the user experience.
CPU utilization by the browser will increase as the quality of the video being streamed increases. This is rather obvious as HD video frames take more CPU power to encode/decode than SD frames.
Client side bandwidth usage can also be an issue. Chrome and Firefox try to modify the bitrate of each video/audio feed dynamically but the video Bitrate can go all the way up to 2 Mbps. You can cap this in Chrome( by adding an attribute in the SDP) but not in Firefox(last I checked) as of yet.
| {
"pile_set_name": "StackExchange"
} |
Q:
compare datetime values just by date
i wish to compare to datetime values just by date, not by hour. How can i do so ?
I want to remove some values that are outside an interval selected by me :
if (DateTime.Compare(DateTime.Parse(t.Rows[i][1].ToString().Trim()), dateTimePicker1.Value) < 0 || DateTime.Compare(DateTime.Parse(t.Rows[i][1].ToString().Trim()), dateTimePicker2.Value) > 0)
/*remove comand*/
A:
Use the DateTime.Dateproperty for this, since this contains only the date part of the DateTimeobject.
if (DateTime.Compare(DateTime.Parse(t.Rows[i][1].ToString().Trim()).Date,
dateTimePicker1.Value.Date) < 0 || DateTime.Compare(DateTime.Parse(t.Rows[i]1].ToString().Trim()).Date,
dateTimePicker2.Value.Date) > 0)
A:
Be also aware of Utc and Locale issue.
For me it's important to do all compare in Utc !
So do something like
Datetime d1, d2;
d1 = d1.toUniversalTime().Date;
d2 = d2.toUniversalTime().Date;
if(DateTime.Compare(d1, d2))....
A:
DateTime d1, d2';
...
// following will compare by date and time both
d1 == d2
// following will compare by date only
d1.Date == d2.Date
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if a Non-ASCII word exists in a string List
I have this list scraped from a web page
scraped = ['24 hour front desk', 'Bar / Lounge', 'Business centre', 'Café']
I want to check whether Cafe exists in the list or not?
I am doing this:
if "Caf" in scraped:
print("Yes")
else:
print("No")
It always prints No
Reason I am writing Caf that from the scraped list, it always comes in non-ascii character Café
How can I perform this check without doing this # -*- coding: utf-8 -*-?
A:
if "Caf" in scraped:
checks if the literal string "Caf" is in the list, which it is not.
To check if "Caf" is in any of the strings in the list, use:
if any("Caf" in s for s in scraped)
To check for non-ascii characters, you can always use unicode escape sequences:
>>> "Caf\xe9" == 'Café'
True`
| {
"pile_set_name": "StackExchange"
} |
Q:
yii2 losing user identity after login redirect
i have looked at the other similar questions, and while this one (Yii2 user identity loss after page redirection) asks pretty much the same question, there is no solution that applies to my situation.
i have created a new identity class, i have implemented all the necessary methods and implemented the IdentityInterface. note that it does NOT extend ActiveRecord, but rather extends my own base Model class that does not derive from AR.
everything seems to work fine, i can log in and be correctly authenticated. i have traced the code and i can see that my identity class is correctly set in Yii::$app->user after IdentityInterface::validatePassword() and User::login() have been called.
however, once the login succeeds and the user is redirected, Yii::$app->user contains an empty IdentityInterface, rather than the one that was there immediately prior to the redirect.
in SiteController::actionLogin(), i have modified the code from:
return $this->goHome();
to:
$tmp = $this->goHome();
// echo '<pre>';var_dump(Yii::$app->user);echo '</pre>';exit;
return($tmp);
and i can see that Yii::$app->user still has the correct identity up until the return() statement.
can anyone tell me why i am losing my identity? i have traced through everything i can think of: yii\web\Controller, yii\base\Controller, yii\web\Response, SiteController, yii\web\User, etc...
any help at all would be greatly appreciated. thanks!
A:
Same problem, after 3 days find solution and I it working.
My User model is:
namespace app\models;
use Yii;
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
public $username;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tbl_users';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'email', 'password'], 'required'],
[['email'], 'unique'],
[['role', 'status'], 'integer'],
[['created', 'last_update'], 'safe'],
[['name', 'email', 'password'], 'string', 'max' => 250]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'email' => 'Email',
'password' => 'Password',
'role' => 'Role',
'status' => 'Status',
'created' => 'Created',
'last_update' => 'Last Update',
];
}
public function getAuthKey() {
}
public function getId() {
return $this->id;
}
public function validateAuthKey($authKey) {
}
public static function findIdentity($id) {
}
public static function findIdentityByAccessToken($token, $type = null) {
}
public static function findByEmail($email)
{
return static::findOne(array('email'=>$email));
}
public function validatePassword($password)
{
return $this->password === $password;
}
}
I change:
public static function findIdentity($id) {
}
to:
public static function findIdentity($id) {
return self::findOne(array('id'=>$id));
}
It working for me.
A:
I had the same problem. I had my custom class implementing yii\web\IdentityInterface. I made sure that session was enabled and enableAutologin was also true, but I had no luck at all.
Finally, I realized that in config/web.php there's a setting 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true]
Of course, the identityClass is the default in a basic yii application. After setting this value to my custom class, identity was finally persisted.
| {
"pile_set_name": "StackExchange"
} |
Q:
sharing a single service across multiple angular 5 applications
I'm running multiple small angular 5 applications as widgets inside my backbase application. Now I'm trying to write a global service, which is at window level, and share across all applications.
Currently, I'm making the service static and using in each widget and using webpack to create widget specific bundle. Here I was able to achieve http caching with rxjs operators.
But I feel this might not be the right way to implement it. Is there any better way to share a singleton service across multiple angular 5 applications in a single project.
A:
Previously if you want to share something between multiple Angular projects that was pretty tricky. You'll have to do one of the following:
Create a package contains shared code and publish it to private or public NPM registry
Create a GIT submodule and reference it on both of your projects
But now I'm guessing the Library support introduced in Angular 6 would suits your needs the best.
For details see:
Angular - Creating Libraries
It's similar to publish your shared package to NPM but Angular CLI (and ng-packagr) really made it super simple.
A:
Technically one of your modules ("main" module) can export its own service via window object, other modules ("clients") can inject wrapper service:
class ServiceWrapper implements IService
{
private readonly instance:IService;
constructor(){
this.instance = window['myService'] as IService;
}
public someMethod():void {
this.instance.someMethod();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is this considered bad attitude?
In my post Imagine I'm on a spacecraft that was accelerated to 1.0$c$ could I only move backwards?, I asked something that came into my mind and I wasn't able to find an answer for it here.
After I posted it, the list of related posts (the list under the title before posting didn't!) showed a question what seemed to be the same. I had a look, found there my answer and marked my post as dupe of that one. Now after that was done I'm getting more and more downvotes for it. What might this reason be? Should I have deleted the post instead?
A:
No, you have done the right thing. With some many questions on the site it's very easy to miss the fact that a duplicate exists, and to be fair the site search isn't as great as it could be.
Don't attach too much significance to the downvotes. It's easy to feel that downvotes are a personal criticism, but really they are just a statement that the question isn't appropriate for the site. Personally I don't downvote duplicates just because they are duplicates, though I know some site members feel differently.
Downvoting does remove the question from the site home page, so there is an argument that a question should be downvoted when we don't want it to appear there. Maybe that's why you have the two downvotes.
I believe that it's generally bad form to delete a question. I can't remember the reasons for this, but I'm sure I have seen comments from the moderators that in general questions shouldn't deleted. Just leave the question - there is an automated cleanup process for downvoted questions that springs into life after a couple of weeks.
For what it's worth you should be congratulated for responding to the duplicate link, reviewing the duplicate and deciding that your question is indeed answered by the existing one. Too many people just abandon their duplicate questions and leave it to the moderators to close.
A quick footnote to summarise David's comments below:
I was a bit hasty to suggest you shouldn't delete your question. The Stack Exchange has various checks to detect users who it thinks aren't being serious, and it will eventually block those users from asking any more questions. One of the criteria it uses is the number of times the user asks a question then deletes it - hence my vague memory that deleting your own questions is a bad thing. However deleting one question, or even a few questions, isn't likely to cause a problem. So you should feel free to delete your question if you want to.
A footnote to the footnote:
As it happens the issue of how deleted questions affect your status has just arisen in the question What is the "positive question record"?. This explains why having lots of deleted question is bad.
| {
"pile_set_name": "StackExchange"
} |
Q:
$E[X^4]+E[X]^4 \geq 2E[X^2]^2$ for $X \geq 0$
I was wondering whether this inequality is actually true. It seems to hold for discrete distributions, for the Normal and the Poisson distribution. Furthermore, after applying AM-GM, it can be seen that a sufficient condition for this inequality to hold is the following inequality
$$
\|X\|_4 \|X\|_1 \geq \|X\|_2^2
$$
where the norms are the respective norms in $L_p$.
A:
No. Consider $X$ following a Bernoulli distribution with parameter $p\in[0,1]$. Then, since $X^4 =X^2 = X$, your inequality is equivalent to $\mathbb{E}[X]+\mathbb{E}[X]^4 \geq 2\mathbb{E}[X]^2$, i.e.,
$$
p + p^4 \geq 2p^2
$$
which is not always true for $p\in[0,1]$. (E.g., it fails for $p=3/4$).
| {
"pile_set_name": "StackExchange"
} |
Q:
How To: View MFC Doc File in Python
I want to use Python to access MFC document files generically? Can CArchive be used to query a file and view the structure, or does Python, in opening the document, need to know more about the document structure in order to view the contents?
A:
I think that the Python code needs to know the document structure.
Maybe you should make a python wrapper of your c++ code.
In this case, I would recommend to use http://sourceforge.net/projects/pycpp/>pycpp which is my opinion a great library for making python extensions in c++.
| {
"pile_set_name": "StackExchange"
} |
Q:
If in a turing machine, whenever the head tries to move left, it gets rewinded all the way to the leftmost cell.
ASSUMPTION : Turing Machine has one sided infinite tape(right to be precise).
Given following constrained (deterministic single-tape) Turing Machine, what is the class of language recognized by it.
Restraint:
The Turing machine, on each transition can perform three operations(wrt moving L,R,S)
1.) It can move right by one cell.
2.) It can stay on current cell.
3.) It can move to the leftmost cell. (restraint)
So Does this turing machine accepts all the languages accepted by a Unrestrained turing machine or not.
I think it accepts all that an unrestricted turing machine can accept, but I am still doubtful.
A:
This type of machines is indeed equivalent in power to ordinary Turing machines. In fact, even if you remove the ability to perform the second type of moves (stay on the current cell), the power of the machine will not be affected. Here is how such a restricted TM can be converted to an unrestricted one.
When the machine needs to move the head to the right, it first puts a special mark, e.g. $\sim$, upon the current symbol. Then it goes all the way back to the leftmost cell, and starts moving rightward. While the machine does so, if another special mark, e.g. $\bullet$, is discovered on a symbol, it gets removed from it. Once the head encounters $\sim$, the machine replaces it with $\bullet$ and moves the head one cell to the right. This combination of moves is equivalent to one move to the right performed by an ordinary TM. Note that the symbol in the left adjacent cell is now marked with $\bullet$.
When the head needs moving to the left, there are three possibilities.
The head points to the leftmost cell. In this case the tape contains no symbols marked with $\bullet$.
The head points to the cell adjacent to the leftmost cell. In this case the tape does contain a symbol marked with $\bullet$, which is located in the leftmost cell.
The head points to neither the leftmost cell nor its adjacent cell. In this case the tape also contains a symbol marked with $\bullet$, which is not in the leftmost cell. This is the symbol the head needs to move to.
The first case can be handled by marking the current symbol with $\sim$, moving the head to the leftmost cell and checking if the current symbol has $\sim$ upon it. If it does, remove it and remain in this cell, the move is now complete. Otherwise, check if the current symbol has $\bullet$ upon it. If it does, remove it, move the head to the adjacent cell, remove $\sim$ from the symbol in that cell and move to the leftmost cell again. This handles the second case. To deal with the last case perform the following steps.
Mark the current symbol with $\bullet$.
Move the head one cell to the right.
Check if the current symbol is marked with $\bullet$.
If it is, remove $\bullet$, move the head one cell to the right, remove $\sim$, move the head to the leftmost cell and scan the tape for an occurrence of $\bullet$. Once it is found, move the head one cell to the right and finish.
Otherwise, put $\bullet$ upon it, move the head to the leftmost cell and scan the tape for the first occurrence of $\bullet$. Once it is found, remove it, move the head one cell to the right and proceed with step 2.
This simulates one move leftward performed by an ordinary TM. Note, that unless the head is pointing to the leftmost cell, the symbol in the left adjacent cell is marked with $\bullet$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does Russell's paradox affect Cantor's set theory?
I've been studying naive set theory and I have been told that Russell's paradox causes problems in Cantor's set theory when sets get "too big".
I don't understand why this causes a problem. I know how the paradox effected Frege's work in terms of logic but not Cantor.
Any help will be appreciated,
Thanks
A:
Maybe they meant that due to Russell's paradox there cannot be a 'universal set': a set of 'everything'.
Here's why: Assuming there would be a set of everything $U$, then we can consider the set $D$ defined as $\{ x \in U | x \not \in x \}$. We could thus say that $D$ contains all 'normal' sets, where a 'normal' set is a set that does not contain itself as an element.
Now, since $U$ is universal, we have $D \in U$. But is $D \in D$? Well, if $D \in D$, then by definition of $D$, we don't put $D$ in $D$, i.e. $D \not \in D$. But if $D \not\in D$, then by definition of $D$ we would put $D$ in $D$, i.e. $D \in D$. Hence, we obtain $D \in D$ if and only if $D \not \in D$, which is a contradiciton.
So, using the logic behind Russell's paradox, there cannot be a universal set. ... And yes, that would certainly be a set that can be said to be 'too big'.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to save the value of textarea to localstorage then display it in the same textarea
I'm creating a simple note storing application and would like the values of all text areas to be saved to the local storage when the user hits a save button. When the user returns I would like the textareas to display the saved notes. Below I will add the relevent code. As for now, when I reload the page the textareas aren't filled with the notes and I can't figure out why.
JSLint errors: https://gyazo.com/c2271b41e83a7d3f81ee024386832e5b
HTML:
<div id="container">
<button id="note1btn" data-role="button">Note #1</button>
<textarea id="note1input" class="textarea hide" rows="10" cols="50"></textarea>
<button id="note2btn" data-role="button">Note #2</button>
<textarea id="note2input" class="textarea hide" rows="10" cols="50"></textarea>
<button id="note3btn" data-role="button">Note #3</button>
<textarea id="note3input" class="textarea hide" rows="10" cols="50"></textarea>
<button id="note4btn" data-role="button">Note #4</button>
<textarea id="note4input" class="textarea hide" rows="10" cols="50"></textarea>
<button id="note5btn" data-role="button">Note #5</button>
<textarea id="note5input" class="textarea hide" rows="10" cols="50"></textarea>
<button id="note6btn" data-role="button">Note #6</button>
<textarea id="note6input" class="textarea hide" rows="10" cols="50"></textarea>
<button id="note7btn" data-role="button">Note #7</button>
<textarea id="note7input" class="textarea hide" rows="10" cols="50"></textarea>
<button id="note8btn" data-role="button">Note #8</button>
<textarea id="note8input" class="textarea hide" rows="10" cols="50"></textarea>
<button id="note9btn" data-role="button">Note #9</button>
<textarea id="note9input" class="textarea hide" rows="10" cols="50"></textarea>
<button id="note10btn" data-role="button">Note #10</button>
<textarea id="note10input" class="textarea hide" rows="10" cols="50"></textarea>
<button id="savenotesbtn" data-role="button">Save</button>
</div>
JS:
$(document).ready(function () {
var savesnotesbtn = document.getElementById("savenotesbtn");
//FILL TEXT AREAS WITH NOTES
for (var i = 1; i < 11; i++) {
$("#note" + i + "input").val(localStorage.getItem("note" + i));
}
//SWIPE LEFT
$(document).on('swipeleft', '.ui-page', function (event) {
if (event.handled !== true) { // This will prevent event triggering more then once
var nextpage = $.mobile.activePage.next('[data-role="page"]');
// swipe using id of next page if exists
if (nextpage.length > 0) {
$.mobile.changePage(nextpage, {transition: "slide", reverse: false}, true, true);
}
event.handled = true;
}
return false;
});
//SWIFE RIGHT
$(document).on('swiperight', '.ui-page', function (event) {
if (event.handled !== true) { // This will prevent event triggering more then once
var prevpage = $(this).prev('[data-role="page"]');
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, {transition: "slide", reverse: true}, true, true);
}
event.handled = true;
}
return false;
});
//DISPLAY NOTE
$("body").on('click', '[id^="note"]', function (e) {
$(this).next('textarea').toggleClass("hide");
});
$(".textarea").on('input', function () {
$("#savenotesbtn").addClass("notSaved");
});
savesnotesbtn.addEventListener("click", saveNotes);
});
//SAVE NOTES
function saveNotes() {
//Change styles of button
$("#savenotesbtn").removeClass("notSaved").addClass("Saved");
//Save notes in local storage
for (var i = 1; i < 11; i++) {
localStorage.getItem("note" + i, $("#note" + i + "input").val());
}
}
A:
Get values by .val() instead of value (value is property from vanilla javascript, not jQuery):
$(document).ready(function () {
var savesnotesbtn = document.getElementById("savenotesbtn");
//FILL TEXT AREAS WITH NOTES
for (var i = 1; i < 11; i++) {
$("#note" + i + "input").val(localStorage.getItem("note" + i));
}
function saveNotes() {
//Change styles of button
$("#savenotesbtn").removeClass("notSaved").addClass("Saved");
// Save data to localstorage
for (var i = 1; i < 11; i++) {
localStorage.setItem("note" + i, $("#note" + i + "input").val());
}
};
savesnotesbtn.addEventListener("click", saveNotes);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find the used characters in a subsetted font?
I have PDF files which are dynamically generated, with text, vectors, and subsetted fonts. I can see which fonts are used in various viewers - is there a way of displaying the actual subsetted characters of those fonts?
For example, I see the document contains the subsetted subsetted fonts "AAAAAC+FreeMono" and "AAAAAD+DejaVuSans". How do I find how many characters were subsetted from these fonts, and what characters they were?
(I tried loading the fonts in FontForge, but it just crashes while opening the file)
A:
The solution is to save the font data to a file and load it into a font editor. A subset font file is still a valid font file but it is possible that FontForge expects some data in the font that is not there. I have seen also many fonts that are not properly subset and this could also cause loading problems in a font editor.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a new instance from a class object in Python
I need to dynamically create an instance of a class in Python. Basically I am using the load_module and inspect module to import and load the class into a class object, but I can't figure out how to create an instance of this class object.
Please help!
A:
I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it.
class k:
pass
a = k()
k2 = a.__class__
a2 = k2()
At this point, a and a2 are both instances of the same class (class k).
A:
Just call the "type" built in using three parameters, like this:
ClassName = type("ClassName", (Base1, Base2,...), classdictionary)
update
as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.
To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:
instance = ClassObject()
The mechanism for instantiation is thus:
Python does not use the new keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable:
Its class' __call__ method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in type). The normal behavior of this call is to invoke the (pseudo) static __new__ method on the class being instantiated, followed by its __init__. The __new__ method is responsible for allocating memory and such, and normally is done by the __new__ of object which is the class hierarchy root.
So calling ClassObject() invokes ClassObject.__class__.call() (which normally will be type.__call__) this __call__ method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations)
class type:
...
def __call__(cls, *args, **kw):
constructor = getattr(cls, "__new__")
instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)
instance.__init__(cls, *args, **kw)
return instance
(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__ and passing it to other classes - but it is what happen "in real life" - if object.__new__ is called with any extra parameters it raises a type error - however, any custom implementation of a __new__ will get the extra parameters normally)
A:
This is how you can dynamically create a class named Child in your code, assuming Parent already exists... even if you don't have an explicit Parent class, you could use object...
The code below defines __init__() and then associates it with the class.
>>> child_name = "Child"
>>> child_parents = (Parent,)
>>> child body = """
def __init__(self, arg1):
# Initialization for the Child class
self.foo = do_something(arg1)
"""
>>> child_dict = {}
>>> exec(child_body, globals(), child_dict)
>>> childobj = type(child_name, child_parents, child_dict)
>>> childobj.__name__
'Child'
>>> childobj.__bases__
(<type 'object'>,)
>>> # Instantiating the new Child object...
>>> childinst = childobj()
>>> childinst
<__main__.Child object at 0x1c91710>
>>>
| {
"pile_set_name": "StackExchange"
} |
Q:
Mathematica not evaluating q derivative of Jacobi theta function
Jacobi theta functions, $\theta_a(u,q)$ for $a=1,2,3,4$ are defined in the unit disk $|q|<1$.
For some reason that I would like to understand, Mathematica does not evaluate numerically the $q$ derivatives of these functions, regardless the value of $u$ (at least for the dozen of values that I tried).
Plotting their imaginary and real parts shows that all of them undergo the same problem.
Plot[{Re[(EllipticTheta^(0,0,1))[1,-.5,q]],Im[(EllipticTheta^(0,0,1))[1,-.5,q]]},{q,0,1}]
Plot[{Re[(EllipticTheta^(0,0,1))[2,-.5,q]],Im[(EllipticTheta^(0,0,1))[2,-.5,q]]},{q,0,1}]
Plot[{Re[(EllipticTheta^(0,0,1))[3,-.5,q]],Im[(EllipticTheta^(0,0,1))[3-.5,q]]},{q,0,1}]
Plot[{Re[(EllipticTheta^(0,0,1))[4,-.5,q]],Im[(EllipticTheta^(0,0,1))[4,-.5,q]]},{q,0,1}]
Heuristically, the limit point is 0.52830188679244577999999999999999...999...
D[EllipticTheta[1,-0.28I,q],q]/.q->0.52830188679244577999999999
0. +0.909738 I
Evaluation above it returns no result;
D[EllipticTheta[1,-0.28I,q],q]/.q->0.52830188679244578
(EllipticTheta^(0,0,1))[1,0. -0.28 I,0.528302]
A:
As it turns out, one can use the PDE satisfied by the Jacobi theta functions to compute the required values:
With[{z = -7 I/25, q = 0.52830188679244577999999999},
{Derivative[0, 0, 1][EllipticTheta][1, z, q],
-Derivative[0, 2, 0][EllipticTheta][1, z, q]/(4 q)}]
{0.9097375919067572916312 I, 0.*10^-23 + 0.90973758336986133322032 I}
(Note that there is a discrepancy between the two evaluations, but I am more inclined to trust the second result instead of the first, since computing the $z$-derivatives for theta functions is much more numerically well-behaved.)
Now, for the case in the OP that could not be numerically evaluated:
With[{z = -7 I/25, q = 0.52830188679244578},
-Derivative[0, 2, 0][EllipticTheta][1, z, q]/(4 q)]
9.99066*10^-16 + 0.909738 I
| {
"pile_set_name": "StackExchange"
} |
Q:
L-series of difference of two cusp forms
Let $f=\sum_{n\geq 1} a_nq^n$ and $g=\sum_{n\geq 1} b_nq^n$ be two distinct cusp eigenforms of same weight $k\geq 2$ with real Fourier coefficients. We normalize the coefficients by defining: $\widetilde {a_n}:=\frac{a_n}{n^{(k-1)/2}}$ and similarly $\widetilde{b_n}:=\frac{b_n}{n^{(k-1)/2}}$. I was wondering if there is a quick way to see that $$\sum_{p-prime}\frac {\widetilde{a_p}-\widetilde{b_p}}{p^s}$$ is bounded as $s\to 1^{+}$.
A:
Let $L(s,f)$ denote the $L$-function of a Hecke eigenform $f$, normalised so that the critical line is $\Re(s) = 1/2$. Then for $\Re(s) > 1$,
\[L(s,f) = \prod_p \frac{1}{1 - \lambda_f(p) p^{-s} + p^{-2s}} = \prod_p \frac{1}{(1 - \alpha_f(p) p^{-s}) (1 - \beta_f(p) p^{-s})},\]
where $\lambda_f(p)$ is the normalised $p$-th Hecke eigenvalue and $\alpha_f(p) + \beta_f(p) = \lambda_f(p)$, $\alpha_f(p) \beta_f(p) = 1$; by Deligne's proof of the Ramanujan conjecture, $|\alpha_f(p)| = |\beta_f(p)| = 1$. It follows that for $\Re(s) > 1$,
\[\log L(s,f) = \sum_{p} \frac{\lambda_f(p)}{p^s} + \sum_{p} \sum_{k = 2}^{\infty} \frac{\alpha_f(p)^k + \beta_f(p)^k}{kp^{ks}},\]
and the second term is uniformly bounded as $s \searrow 1$ (in fact, this only requires the weaker bound $|\alpha_f(p)|, |\beta_f(p)| \leq p^{1/2 - \delta}$ for some $\delta > 0$). Moreover, the $L$-function $L(s,f)$ is nonvanishing and has no poles on the line $\Re(s) = 1$ (by the usual proof of the prime number theorem; see chapter 5 of Iwaniec and Kowalski), so $\log L(s,f) \to \log L(1,f)$ as $s \searrow 1$.
In particular, it follows that $\sum_{p} \frac{\lambda_f(p)}{p^s}$ is bounded as $s \searrow 1$, and the same is obviously true for $\sum_{p} \frac{\lambda_f(p) - \lambda_g(p)}{p^s} = \sum_{p} \frac{\lambda_f(p)}{p^s} - \sum_{p} \frac{\lambda_g(p)}{p^s}$.
Similarly, let $L(s,\mathrm{sym}^2 f)$ denote the symmetric square $L$-function, so that for $\Re(s) > 1$,
\[L(s,f) = \prod_p \frac{1}{1 - \lambda_f(p^2) p^{-s} + \lambda_f(p^2) p^{-2s} - p^{-3s}} = \prod_p \frac{1}{(1 - \alpha_f(p)^2 p^{-s}) (1 - p^{-s})
(1 - \beta_f(p)^2 p^{-s})}.\]
Then for $\Re(s) > 1$,
\[\log L(s,\mathrm{sym}^2 f) = \sum_{p} \frac{\lambda_f(p^2)}{p^s} + \sum_{p} \sum_{k = 2}^{\infty} \frac{\alpha_f(p)^{2k} + 1 + \beta_f(p)^{2k}}{kp^{ks}}.\]
Again, $L(s,\mathrm{sym}^2 f)$ is nonvanishing and has no poles on the line $\Re(s) = 1$ (though when the nebentypus is nonprincipal, there may be a pole; see this question). So the same argument goes through (though this time, we need bounds towards the generalised Ramanujan conjecture of the form $|\alpha_f(p)|, |\beta_f(p)| \leq p^{1/4 - \delta}$ for some $\delta > 0$, which is certainly known).
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it idiomatic to say "please always close the door behind you"?
my sister's bedroom is face to my bedroom and she play music loudly, which is disturbing me. So, I said to her, please always close the door behind you. I would like to have her remember this, and close the door next time without my reminder, close our own doors to avoid disturbing each other.
Is it an idiomatic expression?
A:
"Always" may sound more commanding than you want and actually if you are not her boss, it may not be justifiable to say that.
"Behind you" is redundant when it's obvious, so you end up with "Close the door, please."
If she's a decent human being, she'll understand even better if you give here some reasoning: I try to study (sleep, or so), and your music is disturbing me, so would you...? If you have a good reason, you'll find the right words.
| {
"pile_set_name": "StackExchange"
} |
Q:
Chrome Extension webRequest.onBeforeRequest Cancel Page
I am attempting to create a chrome extension that queries an external source as a reference to block or allow through a particular page. The following is part of my code. I am new to javascript, and scope always seems to be something that screws me up.
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
var http = new XMLHttpRequest();
var url = "http://xxx.xx.xxxx";
var params = "urlCheck="+encodeString_(details.url);
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
guilt = 0;
console.log(guilt);
}else if(http.readyState == 4 && http.status == 404){
guilt = 1;
console.log(guilt);
}
}
http.send(params);
if(guilt == 1){
return {cancel: true};
}else{
return {cancel: false};
}
},
{urls: ["<all_urls>"],
types:["main_frame"]
},
["blocking"]
);
Any help would be greatly appreciated! Thanks.
A:
You can't do that.
Your code does not work as expected because XHR is asynchronous; your onreadystatechange is executed after the whole outer function finishes. So guilt will be undefined or, worse, stale (from the last request).
For more information, see this canonical question: Why is my variable unaltered after I modify it inside of a function?
However, if you try to fix this, you'll notice that you can't return a response from within the async handler.
This is intentional: there is no function to pass and then call later (like sendResponse in Messaging API), because Chrome will not wait for you. You are expected to respond to a blocking call in a deterministic and fast way.
If the optional opt_extraInfoSpec array contains the string 'blocking' (only allowed for specific events), the callback function is handled synchronously. That means that the request is blocked until the callback function returns.
You could try to bypass it by using synchronous XHR calls. That is not a very good idea in general, since loading a remote response takes a long time, and synchronous XHR is considered deprecated. Even though you limited your queries to "main_frame" requests, this still adds an uncertain delay to each load.
A proper way to do that would be to load a set of rules from a server and update it periodically, and when a request occurs validate it against this local copy of rules. This is the approach extensions like AdBlock use.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are Velomobiles street legal in the UK?
I saw a question about velomobiles and recumbent bikes and I was wondering if they were street legal in the UK?
Can you ride one on a cycle path or would you have to stick to roads?
A:
References: Bikehub - Cycling and the Law, Traffic Signs Regulations and General Directions 1994, Road Vehicles Lighting Regulations 1989
A velomobile or recumbent bike is covered by the same law as regular bicycles:
"pedal cycle" means a unicycle, bicycle, tricycle, or cycle having four or more wheels, not being in any case mechanically propelled unless it is an electrically assisted pedal cycle of such class as is to be treated as not being a motor vehicle
So it's legal to use to ride one on the road in the UK.
Cycle paths are a bit more complicated as some legislation refers to "bicycles" and some to "pedal cycles", so it would depend on how many wheels you've got and what type of cycle path / cycle lane / cycle track you wanted to use.
If you want to use a velomobile or recumbent bike on the road between sunset and sunrise then you may have problems. To be legal you'd need 2 pedal reflectors on each pedal and these have to be clearly visible from the front and rear. The design of most velomobiles and recumbent bikes do not meet this requirement. This law is rarely (if ever) enforced, I think your main worry on this point is if you were involved in an accident then the other party might try to use your lack of reflectors to show negligence.
Note - If your velomobile or recumbent bike is electrically powered then there are additional regulations that must be complied with, but I think that's beyond the scope of the question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to export all the command line output to a file without manually redirecting via > symbol?
I have a python (2.7) script that has various print statements and other things. Now, I want to export the entire command-line output to a file. As most people know, this is very easy to do manually using the below command:
script.py > file.txt
But I want to make > file.txt also as a part of my python script itself instead of having to redirect manually every time the script is run.
I tried using the with command but it only exports a specific object out into a file but not all the print statements, dataframes, and etc.
Is there a way to achieve this? I'm not well-versed in unix or python. Can someone please help me with some ideas?
Thanks in advance.
A:
you can use the sys module and add the following line at the begin of your code:
import sys
sys.stdout = open('file.txt', 'w')
| {
"pile_set_name": "StackExchange"
} |
Q:
Does .NET 3.5 allow to use the new features of Windows 7?
Some of the applications running on Windows 7 (Internet Explorer, Google Chrome, in example) use the icon they present in the task bar to show a little progress bar. Is it possible to use that feature using the .NET Framework 3.5?
A:
Try the Windows API Code Pack
http://code.msdn.microsoft.com/WindowsAPICodePack
This assembly provides access to Windows specific features like the tool bar. It allows for just the scenario you're looking for.
| {
"pile_set_name": "StackExchange"
} |
Q:
Hibernate Composite Key Nested Object Criteria Missing From Clause
Currently I am trying to use hibernate (version 4.3.Final) to retrieve an object with a composite primary key containing another hibernate bean association. The criteria I am using is as follows:
session.createCriteria(IdentityIdentifierHibernateBean.class)
.setFetchMode("key.type", FetchMode.JOIN);
.createAlias("key.type","typeAlias",JoinType.INNER_JOIN);
.add(Restrictions.and(
Restrictions.eq("key.value", "value"),
Restrictions.eq("typeAlias.id", "id value")))
.list();
When I run this I get an error of:
1. SQL Error: 0, SQLState: 42P01
2. missing FROM-clause entry for table "typealias1_"
Which the reason is apparent when I view the generated sql as shown below:
select
this_.type as type4_4_0_,
this_.value as value1_4_0_,
this_.id as id2_4_0_, this_.scope as scope3_4_0_
from
identityIdentifier this_
where
(this_.value=? and typealias1_.id=?)
When running createAlias (or createCritera) isn't hibernate suppose to generate a join statement? I have tried both methods and tried creating aliases for the composite primary key as well. Either way, neither of these methods works as a join statement is never created. Is this a bug with resolving nested hibernate beans referenced in an embedded composite primary key? Or am I missing something....
For reference here's a simplified version of the hibernate classes (hashCode, equals and setters not included):
@Entity
@Table(name = "identityIdentifier")
public class IdentityIdentifierHibernateBean implements Serializable {
private IdentityIdentifierPrimaryKey key;
@EmbeddedId
public IdentityIdentifierPrimaryKey getKey() {
return key;
}
}
@Embeddable
public class IdentityIdentifierPrimaryKey implements Serializable {
private String value;
private IdentityIdentifierTypeHibernateBean type;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "type", referencedColumnName="id", unique = true, nullable = false)
public IdentityIdentifierTypeHibernateBean getType() {
return type;
}
@Column(name = "value", unique = false, nullable = false, length = 255)
public String getValue() {
return value;
}
}
@Entity
@Table(name = "identityIdentifierType")
public class IdentityIdentifierTypeHibernateBean implements Serializable {
private String id;
@Id
@Column(name = "id", unique = true, nullable = false, length=38)
public String getId() {
return id;
}
}
A:
After countless hours of trying to get the criteria API to work (which I genuinely believe is broken for composite keys at this point) I decided to switch to using HQL query instead. After about 20 minutes, I was easily able to get a working query. Word for the wise, don't use composite keys and the criteria api in combination.
Query query=session.createQuery(
"select distinct identity from IdentityIdentifierHibernateBean as identity "
+ "inner join identity.key.type as type "
+ "where (identity.key.value=:value and type.id=:typeid)")
.setParameter("value", type.getIdentityIdentifierValue())
.setParameter("typeid", type.getTypeOfIdentityIdentifier());
beanList = (List<IdentityIdentifierHibernateBean>) query.list();
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex and file processing
This question relates to R but really isn't language specific per se. I have a bunch of csv files with this general format "sitename_03082015.csv". The files have 5 columns and various rows
Host MaximumIn MaximumOut AverageIn AverageOut
device1 30.63 Kbps 0 bps 24.60 Kbps 0 bps
device2 1.13 Mbps 24.89 Kbps 21.76 Kbps 461 bps
device5 698.44 Kbps 37.71 Kbps 17.49 Kbps 3.37 Kbps
I ultimately want to read in all the files and merge which I can do but during the merge I want to read the site name and date and add it to each related line so the output looks like this
Host MaximumIn MaximumOut AverageIn AverageOut Site Name Date
device1 30.63 Kbps 0 bps 24.60 Kbps 0 bps SiteA 3/7/15
device12 1.13 Mbps 24.89 Kbps 21.76 Kbps 461 bps SiteA 3/8/15
device1 698.44 Kbps 37.71 Kbps 17.49 Kbps 3.37 Kbps SiteB 3/7/15
device2 39.08 Kbps 1.14 Mbps 10.88 Kbps 27.06 Kbps SiteB 3/8/15
device3 123.43 Kbps 176.86 Kbps 8.62 Kbps 3.78 Kbps SiteB 3/9/15
With my R code I can do the following:
#Get list of file names
filenames<- list.files(pattern = ".csv$")
#This extracts everything up to the underscore to get site name
siteName <- str_extract(string = filenames, "[^_]*")
# Extract date from file names use
date <- str_extract(string = filenames, "\\d{8}" )
With the below R code I can merge all the files but that will be without the added columns of site name and date that I want.
myDF<-do.call("rbind", lapply(filenames, read.table, header=TRUE, sep=","))
I just can't get my head around how to do the extracts for site and date adding and populating the columns to create my ideal dataframe which is the second table above.
The solution that best worked for me was posted below :)
A:
The way that immediately comes to my mind is to do cbind while reading information with additional infor and do rbind afterwards. Something similar to this:
myDF<-do.call("rbind",
lapply(filenames,
function(x) cbind(read.table(x, header=TRUE, sep=","),
"Site Name" = str_extract(string = x, "[^_]*"),
"Date" = as.Date(str_extract(string = x, "\\d{8}"), "%m%d%Y"))))
| {
"pile_set_name": "StackExchange"
} |
Q:
What happens when two clients send UDP packets to a Socket
Lets assume Host X has a UDP Socket running on Port 1337.
Now Host Y and Z both send a UDP Packet to port 1337 of Host X.
Are the packets going to be de-muxed?
A:
UDP is a transfer protocol with no guarantees of delivery and doesn't have much of an implementation.
When both host Y an Z send a UDP packet to port 1337, and assuming both packets arrive, the application listening on port 1337 decides what happens with those packages. The application can choose which packet to demux, to demux both or to demux neither.
Hope this clears things up
| {
"pile_set_name": "StackExchange"
} |
Q:
Multi-Target .NET Standard 2.0 and .NET 4.5 fails due to missing .net 4.5 framework
On my dev box I have .net 4.6.2 and dotnet-sdk-2.1 installed. I originally had 4.0 then 4.5 then 4.6.2
I am able to run dotnet build on a project which multi-targets to both netstandard2.0 and net45 like this:
<TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
I am able to build it successfully and run unit tests etc. I see the bin directory contains subdirectories for each target framework and contains all the DLLs.
When I try to put together my CI build on a teamcity agent which is built on Windows Server 2016. I get an error:
The reference assemblies for framework ".NETFramework,Version=v4.5" were not found.
This is puzzling to me because the machine has .NET 4.6.2 SDK installed. (It also has the dotnet sdk 2.1 installed)
Doing some googling around I see many mentioning that the frameworks should be in the dictory:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\
And when I check the Server 2016 machine I see the directory and I see subdirectory: v4.6.2 no subdirectories for 4.5
On my dev box however I see all kinds of directories there: 4.5, 4.0, 3.5, 4.6.2 ...
I can't install framework 4.5 SDK on the Server 2016 machine because it already has a higher version installed. So it seems I can't build targeting .NET 4.5 on that machine.
As a sanity check I changed my csproj file to:
<TargetFrameworks>netstandard2.0;net462</TargetFrameworks>
And I was able to build the project successfully. So the build does work but it requires 4.6.2 on that machine. It does not work neither if I target net46.
What am I doing wrong here?
Is there a way for me to be able to multi-target my project to net45 on the Server 2016 machine?
A:
TL;DR: install the .NET Framework 4.5 Developer Pack to build .NET Framework 4.5 projects.
You say that your server has the .NET Framework 4.6.2 Developer Pack installed, and you are trying to build a .NET Framework 4.5 project with it.
Unlike runtime packs, where each version contains (so to speak) the previous version, you need to have the developer pack for the exact version of the framework you are targetting.
| {
"pile_set_name": "StackExchange"
} |
Q:
Lorentz symmetry and Noether's theorem
I'm trying to overcome some misunderstanding that I have in Noether's theorem.
There is formula in David Gross's Lectures on QFT for Noether's theorem:
$$J^\mu_\alpha=\mathcal{L}X^\mu_\alpha+\Pi^\mu_i\left[\Psi_{i\alpha}-\partial_\nu\phi_i X^i_\alpha\right]$$
$J^\mu_\alpha$ - conserved vector current, $\Pi^\mu_i$-canonical momentum, $X^\mu_\alpha$ and $\Psi_{i\alpha}$ are generators of symmetry which are defined by $$x'^\mu=x^\mu+X^\mu_\alpha \omega^\alpha,$$
$$\phi'(x'^\mu)=\phi(x^\mu)+\Psi_{i\alpha} \omega^\alpha,$$
Particularly I'm working out Lorentz symmetry:
$$x'^\mu=\Lambda^\mu_\nu x^\nu$$
Infinitesimal version of this transformation is: $\Lambda^\mu_\nu=\delta^\mu_\nu+\omega^\mu_\nu$, where $\omega^\mu_\nu=-\omega^\nu_\mu$ is antisymmetric.
So, my problem that I dont understand why (they write this expression in many sources, not only in Gross)
$$X^{\mu,\alpha}_\beta=\delta^\mu_\alpha x^\beta-\delta^\mu_\beta x^\alpha$$.
If I'm calculating $X^{\mu,\alpha}_\beta\omega^\beta_\alpha$, I get $2\omega^\mu_\nu x^\nu$, not the $\omega^\mu_\nu x^\nu$. Also I've done this calculation:
$$f(x'^\mu)=f(x^\mu+\omega^\mu_\alpha x^\alpha)\approx f(x^\mu)+\omega_{\alpha \mu}x^\alpha \partial^\mu f = f(x^\mu) + \frac 1 2 \omega_{\alpha \mu} \left(x^\mu \partial^\alpha-x^\alpha \partial^\mu \right)f $$
If $f=x^\mu$ (coordinate function), then $$X^{\mu,\alpha}_\beta=\frac 12\left(\delta^\mu_\alpha x^\beta-\delta^\mu_\beta x^\alpha\right).$$
What exactly am I doing wrong?
A:
I think this calculation is the answer for your question:
$$\sum_{\alpha,\mu}\frac 1 2 \omega_{\alpha \mu} \left(x^\mu \partial^\alpha-x^\alpha \partial^\mu \right)=\frac 1 2 \sum_{\alpha<\mu}\omega_{\alpha \mu} \left(x^\mu \partial^\alpha-x^\alpha \partial^\mu \right)+\frac 1 2 \sum_{\mu<\alpha}\omega_{\alpha \mu} \left(x^\mu \partial^\alpha-x^\alpha \partial^\mu \right)=\frac 1 2 \sum_{\alpha<\mu}\omega_{\alpha \mu} \left(x^\mu \partial^\alpha-x^\alpha \partial^\mu \right)+\frac 1 2 \sum_{\alpha<\mu}\omega_{\mu\alpha } \left(x^\alpha \partial^\mu-x^\mu \partial^\alpha \right)=\frac 1 2 \sum_{\alpha<\mu}\omega_{\alpha \mu} \left(x^\mu \partial^\alpha-x^\alpha \partial^\mu \right)+\frac 1 2 \sum_{\alpha<\mu}\omega_{\alpha \mu} \left(x^\mu \partial^\alpha-x^\alpha \partial^\mu \right)=\sum_{\alpha<\mu}\omega_{\alpha \mu} \left(x^\mu \partial^\alpha-x^\alpha \partial^\mu \right)$$
Where I
Splited sum in "$\alpha<\mu$" and "$\mu<\alpha$" parts.
Changed $\alpha \leftrightarrow \mu$
Used antisymmetric property of $\omega_{\alpha \mu}$ and $\left(x^\mu \partial^\alpha-x^\alpha \partial^\mu \right)$
| {
"pile_set_name": "StackExchange"
} |
Q:
Sum only matched values from two columns
Hello Everyone,
Does anyone know how to sum the Hours from column B (Hours) if column A numbers matched with column E and sum by months.
Example, take February data as an example, since only 3000 & 4000 existed in both column A & column E, that's why I need to sum the hours (20+10=30) from column B by it's month below.
I also attached the example excel sheet below.
https://www.dropbox.com/s/0s51g1i8g6s6e2d/Test.xls?m
Thanks in advance. :-)
A:
You could get complicated with customer functions but if having an extra column (potentially hidden) doesn't matter then this would work:
In cell D2 enter:
=iferror(vlookup($A2,$E$2:$E$20,1,FALSE),"x")
Drag the formula down.
Under each month you can then put:
=sumifs($B$2:$B$16,$C$2:$C$16,B$22,$D$2:$D$16,"<>x")
Drag the formula across
This assumes you can change the month format in either column C or row 22 to be the same, ie. Jan, Feb, Mar or January, February, March etc.
Written on the fly and not tested so excuse any minor errors...
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does ReadDirectoryChangesW omit events?
I use ReadDirectoryChangesW to watch a specified directory and update indexing structures whenever a change is detected. I use the following code (roughly)
var
InfoPointer : PFileNotifyInformation;
NextOffset : DWORD;
...
while (not Terminated) do begin
if ReadDirectoryChangesW (FDirHandle, FBuffer, FBufferLength, True,
FFilter, @BytesRead, @FOverlap, nil) then
begin
WaitResult := WaitForMultipleObjects (2, @FEventArray, False, INFINITE);
if (WaitResult = waitFileChange) then
begin
InfoPointer := FBuffer;
repeat
NextOffset := InfoPointer.NextEntryOffset;
...
PByte (InfoPointer) := PByte (InfoPointer) + NextOffset;
until NextOffset = 0;
end;
end;
end;
Filter is
FFilter := FILE_NOTIFY_CHANGE_FILE_NAME or
FILE_NOTIFY_CHANGE_DIR_NAME or
FILE_NOTIFY_CHANGE_SIZE or
FILE_NOTIFY_CHANGE_LAST_WRITE;
and the directory handle is obtained like this:
FDirHandle := CreateFile (PChar (FDirectoryWatch.WatchedDirectory),
FILE_LIST_DIRECTORY or GENERIC_READ,
FILE_SHARE_READ or FILE_SHARE_WRITE or FILE_SHARE_DELETE,
nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS or
FILE_FLAG_OVERLAPPED, 0);
When I delete multiple files I get only one event and NextOffset is 0! And when I delete a directory I get only one event for the directory. What if I want one event for each file in the directory?
Any help would be appreciated.
A:
It seems to me that you are mixing the various ways to use ReadDirectoryChangesW(), you do both specify the FILE_FLAG_OVERLAPPED flag when opening the directory and provide a pointer to the lpOverlapped parameter, meaning you want to wait on the event in the structure and handle the asynchronous I/O; and at the same time you call ReadDirectoryChangesW() in a loop in a worker thread. I would first try again with lpOverlapped set to nil, as you have a dedicated thread and can use the synchronous mode.
In the documentation of the ReadDirectoryChangesW() API function the different ways to use it are described. Note that it is also possible that the buffer overflows, so change events can be lost anyway. Maybe you should rethink your strategy of relying solely on this function, comparing snapshots of directory contents could work as well.
Edit:
Your edited code looks better. In my tests however ReadDirectoryChangesW() did work as advertised, there were either several data entries in the returned buffer, or there were more than one buffer to process. This depends on timing, after hitting a breakpoint in Delphi I get several entries in one buffer.
For completeness I attach the test code, implemented using Delphi 5:
type
TWatcherThread = class(TThread)
private
fChangeHandle: THandle;
fDirHandle: THandle;
fShutdownHandle: THandle;
protected
procedure Execute; override;
public
constructor Create(ADirectoryToWatch: string);
destructor Destroy; override;
procedure Shutdown;
end;
constructor TWatcherThread.Create(ADirectoryToWatch: string);
const
FILE_LIST_DIRECTORY = 1;
begin
inherited Create(TRUE);
fChangeHandle := CreateEvent(nil, FALSE, FALSE, nil);
fDirHandle := CreateFile(PChar(ADirectoryToWatch),
FILE_LIST_DIRECTORY or GENERIC_READ,
FILE_SHARE_READ or FILE_SHARE_WRITE or FILE_SHARE_DELETE,
nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS or FILE_FLAG_OVERLAPPED, 0);
fShutdownHandle := CreateEvent(nil, FALSE, FALSE, nil);
Resume;
end;
destructor TWatcherThread.Destroy;
begin
if fDirHandle <> INVALID_HANDLE_VALUE then
CloseHandle(fDirHandle);
if fChangeHandle <> 0 then
CloseHandle(fChangeHandle);
if fShutdownHandle <> 0 then
CloseHandle(fShutdownHandle);
inherited Destroy;
end;
procedure TWatcherThread.Execute;
type
PFileNotifyInformation = ^TFileNotifyInformation;
TFileNotifyInformation = record
NextEntryOffset: DWORD;
Action: DWORD;
FileNameLength: DWORD;
FileName: WideChar;
end;
const
BufferLength = 65536;
var
Filter, BytesRead: DWORD;
InfoPointer: PFileNotifyInformation;
Offset, NextOffset: DWORD;
Buffer: array[0..BufferLength - 1] of byte;
Overlap: TOverlapped;
Events: array[0..1] of THandle;
WaitResult: DWORD;
FileName, s: string;
begin
if fDirHandle <> INVALID_HANDLE_VALUE then begin
Filter := FILE_NOTIFY_CHANGE_FILE_NAME or FILE_NOTIFY_CHANGE_DIR_NAME
or FILE_NOTIFY_CHANGE_SIZE or FILE_NOTIFY_CHANGE_LAST_WRITE;
FillChar(Overlap, SizeOf(TOverlapped), 0);
Overlap.hEvent := fChangeHandle;
Events[0] := fChangeHandle;
Events[1] := fShutdownHandle;
while not Terminated do begin
if ReadDirectoryChangesW (fDirHandle, @Buffer[0], BufferLength, TRUE,
Filter, @BytesRead, @Overlap, nil)
then begin
WaitResult := WaitForMultipleObjects(2, @Events[0], FALSE, INFINITE);
if WaitResult = WAIT_OBJECT_0 then begin
InfoPointer := @Buffer[0];
Offset := 0;
repeat
NextOffset := InfoPointer.NextEntryOffset;
FileName := WideCharLenToString(@InfoPointer.FileName,
InfoPointer.FileNameLength);
SetLength(FileName, StrLen(PChar(FileName)));
s := Format('[%d] Action: %.8xh, File: "%s"',
[Offset, InfoPointer.Action, FileName]);
OutputDebugString(PChar(s));
PByte(InfoPointer) := PByte(DWORD(InfoPointer) + NextOffset);
Offset := Offset + NextOffset;
until NextOffset = 0;
end;
end;
end;
end;
end;
procedure TWatcherThread.Shutdown;
begin
Terminate;
if fShutdownHandle <> 0 then
SetEvent(fShutdownHandle);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TForm1.FormCreate(Sender: TObject);
begin
fThread := TWatcherThread.Create('D:\Temp');
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
if fThread <> nil then begin
TWatcherThread(fThread).Shutdown;
fThread.Free;
end;
end;
Deleting a directory does indeed only return one change for it, nothing for the files contained in it. But it does make sense, as you are watching the handle of the parent directory only. If you need notifications for subdirectories you probably need to watch them as well.
A:
We've had the same problem with losing events, especially if a lot of changes happens at the same time, ie. 500 files are copied to the monitored directory.
In the end we found Cromis and use the Directory watch. We have never looked back again.
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple example of how to use ast.NodeVisitor?
Does anyone have a simple example using ast.NodeVisitor to walk the abstract syntax tree in Python 2.6? The difference between visit and generic_visit is unclear to me, and I cannot find any example using google codesearch or plain google.
A:
ast.visit -- unless you override it in a subclass, of course -- when called to visit an ast.Node of class foo, calls self.visit_foo if that method exists, otherwise self.generic_visit. The latter, again in its implementation in class ast itself, just calls self.visit on every child node (and performs no other action).
So, consider, for example:
>>> class v(ast.NodeVisitor):
... def generic_visit(self, node):
... print type(node).__name__
... ast.NodeVisitor.generic_visit(self, node)
...
Here, we're overriding generic_visit to print the class name, but also calling up to the base class (so that all children will also be visited). So for example...:
>>> x = v()
>>> t = ast.parse('d[x] += v[y, x]')
>>> x.visit(t)
emits:
Module
AugAssign
Subscript
Name
Load
Index
Name
Load
Store
Add
Subscript
Name
Load
Index
Tuple
Name
Load
Name
Load
Load
Load
But suppose we didn't care for Load nodes (and children thereof -- if they had any;-). Then a simple way to deal with that might be, e.g.:
>>> class w(v):
... def visit_Load(self, node): pass
...
Now when we're visiting a Load node, visit dispatches, NOT to generic_visit any more, but to our new visit_Load... which doesn't do anything at all. So:
>>> y = w()
>>> y.visit(t)
Module
AugAssign
Subscript
Name
Index
Name
Store
Add
Subscript
Name
Index
Tuple
Name
Name
or, suppose we also wanted to see the actual names for Name nodes; then...:
>>> class z(v):
... def visit_Name(self, node): print 'Name:', node.id
...
>>> z().visit(t)
Module
AugAssign
Subscript
Name: d
Index
Name: x
Store
Add
Subscript
Name: v
Index
Tuple
Name: y
Name: x
Load
Load
But, NodeVisitor is a class because this lets it store information during a visit. Suppose all we want is the set of names in a "module". Then we don't need to override generic_visit any more, but rather...:
>>> class allnames(ast.NodeVisitor):
... def visit_Module(self, node):
... self.names = set()
... self.generic_visit(node)
... print sorted(self.names)
... def visit_Name(self, node):
... self.names.add(node.id)
...
>>> allnames().visit(t)
['d', 'v', 'x', 'y']
This kind of thing is a more typical use case than ones requiring overrides of generic_visit -- normally, you're only interested in a few kinds of nodes, like we are here in Module and Name, so we can just override visit_Module and visit_Name and let ast's visit do the dispatching on our behalf.
A:
Looking at the code in ast.py it's not that hard to copy paste and roll your own walker. E.g.
import ast
def str_node(node):
if isinstance(node, ast.AST):
fields = [(name, str_node(val)) for name, val in ast.iter_fields(node) if name not in ('left', 'right')]
rv = '%s(%s' % (node.__class__.__name__, ', '.join('%s=%s' % field for field in fields))
return rv + ')'
else:
return repr(node)
def ast_visit(node, level=0):
print(' ' * level + str_node(node))
for field, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
ast_visit(item, level=level+1)
elif isinstance(value, ast.AST):
ast_visit(value, level=level+1)
ast_visit(ast.parse('a + b'))
Prints out
Module(body=[<_ast.Expr object at 0x02808510>])
Expr(value=BinOp(op=Add()))
BinOp(op=Add())
Name(id='a', ctx=Load())
Load()
Add()
Name(id='b', ctx=Load())
Load()
A:
generic_visit is called when a custom visitor (ie visit_Name) can't be found. Here's a piece of code I wrote recently with ast.NodeVisitor: https://foss.heptapod.net/pypy/pypy/-/blob/80ead76ab428100ffeb01109c7fc0d94f1048af2/py/_code/_assertionnew.py It interprets the AST nodes to gain debugging information about some of them and falls back in with generic_visit when a special implementation isn't provided.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to open files with an incremental numbers?
Right now I'm doing this:
filenames = ['ch01.md', 'ch02.md', 'ch03.md', 'ch04.md', 'ch05.md', 'ch06.md']
with open('chall.txt', 'w') as outfile:
for fname in filenames:
But I have many files written as chxx.md (until ch24.md). Is there any what to modify the script using ranges? So I don't have to type in all the files names?
A:
You can probably use glob. It's an easy way to collect files with the use of wildcard characters.
import glob
filenames = glob.glob('/yourDirectory/ch*.md') # Will give you a list of all the file names
with open('chall.txt', 'w') as outfile:
for fname in filenames:
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the blending matrix change between calculating various curve segments in a uniform cubic B-splines approximation?
I would like to ask about uniform (periodic) cubic B-splines (approximation, no interpolation).
$$B=1/6\begin{bmatrix}-1&3&-3&1\\3&-6&3&0\\-3&0&3&0\\1&4&1&0\end{bmatrix}$$
$B$ is the matrix of coefficients that allows calculating a single curve segment with the formula:
$$ Q_i(u)=[u^3 u^2 u^1 1]B \begin{bmatrix}P_{i-3}\\P_{i-2}\\P_{i-1}\\P_{i}\end{bmatrix} $$
When $i=3$ I calculate the first segment of the curve. My question is when $i=4$ and I want to calculate the second segment of the curve I must change the $4$ control points but does $B$ change or not?
A:
No, the $B$ matrix (basis coefficient matrix) does not change from one segment to the next. It is a property of the type of spline you're using, in this case cubic B-splines. If you used Bézier splines or Hermite splines instead, you'd have a different $B$ matrix.
| {
"pile_set_name": "StackExchange"
} |
Q:
GAEUnit doesn't automatically refresh code
I'm using GAEUnit for unit testing my GAE app. However, anytime I make a change to my code (not the test case code, but actual app code) and rerun the tests, it doesn't use my newly updated code, but the previous version. I have to stop the app completely from the terminal by hitting control+c, then start it up again for the tests to take in my new code. Any ideas why that is?
A:
The latest SDK has an issue with not reloading changed code, not specific to GAEUnit: http://code.google.com/p/googleappengine/issues/detail?id=8383
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change progressbar background color using javascript
I was looking for how to change the ext.net progressbar background color using JavaScript. possibly adding a CSS class to the progressbar from JavaScript.
I have tried adding a css class but failed. Actually I cant find the function which will facilitate me to add the CSS class to it.
any help will be appreciated.
EDIT:
javascript:
function ShowProgressBar(progressBar, progressValue, message) {
progressBar.show();
progressBar.updateProgress(progressValue, message);
//need to add the css class here something like progressBar.addClass('green-bar')
}
CSS:
.green-bar{
background:#008000;
}
A:
Guys i have solved the issue. just need to change the CSS class name.
CSS:
.green-bar .x-progress-bar{
background:#008000;
}
JavaScript:
progressBar.addClass('green-bar'); //obviously i have removed the added css class after use.
| {
"pile_set_name": "StackExchange"
} |
Q:
Play Framework 1: tag to include javascript file only once
In Play Framework 1, is there a tag which includes javascript file only once in the generated page?
Example:
I want following code:
#{press.script 'my.script.js'}
#{press.script 'my.script.js'}
to inject my.script.js declaration into resulting page only once, so that Play generates the following:
<script src="/path/to/my.script.js"></script>
Please note that press module should be of version >= 1.0.22.
So far, anything but not what's needed was found:
#{press.script 'my.script.js'} simply throws exception when specified twice with same js file
version 1.0.11 of press module added ignoreDuplicates tag property which, as per documentation, should do what's needed, but in next version it was mysteriously removed ...
version 1.0.12 of press module added possibility to add press.allowDuplicates to configuration, but in next version it was again mysteriously removed ...
#{press.single-script 'my.script.js'} simply compresses js file and adds <script> twice to generated file
Please advise
A:
I don't think there is. I have solved a similar problem like this.
Let's say I have one template, main.html. All other templates extend this one. Main.html includes scripts.html. Based on the current URL, the Controller renders form.html which extends main.html. In form.html I have a widget which needs my.script.js. To make sure it's only included on this page (which needs the script) I've set the following variable:
#{set useMyScript: true /}
In scripts.html, I will check this variable and render this script only if needed:
#{if useMyScript}
#{press.script 'my.script.js'}
#{/if}
So, this is not exactly your case, but I am pretty sure you can set useMyScript to true multiple times with this solution and include the Javascript only once.
I hope this helps!
| {
"pile_set_name": "StackExchange"
} |