text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Why don't the miners just take profit from our coins and make the coin worthless?
You own a very valuable thing and you want to go to holiday without it, but there is nobody who you trust and who can look after the thing. So you take somebody unknown to guard it. You pay him a fee hoping he doesn't run away with the valuable think. How much would you pay?
I think you should pay for the fee minimum the value of the valuable thing!
But now to bitcoin. Do the story again:
You own a very valuable coin which is guarded by somebody unknown (the miners). You pay him a fee (mining profit) that is much less than the value of the coin (market cap of bitcoin). Why don't the miners hold short positions on the coin, bring value of the coin down with a large majority attack which destroys any trust in the coin and go with benefit from the destruction?
I asked this fundamental question about bitcoin in a stricter way 2 days before in this question and similar in this question and there is also a bounty for an answer, but there is only less interest and no upvotes and no good answers. I think the question is fundamental, and so I tried to do it in an easy analogy now.
A:
Because miners do not actually own/ or have access to the bitcoins which are being spent in a transaction.
They simply choose a number of transactions which have valid signatures, and put them together with the hash they created/solved, thus creating a valid block.
See https://en.bitcoin.it/wiki/Block_hashing_algorithm for more information.
The person that owns the private key owns the bitcoin, which (unless you share it ofcourse) would be something miners, or anyone in general, won't have access to.
EDIT:
There's currently ~12.000.000 TH/S, In order to gain 51% of the hashpower, ( which is needed to always be faster, thus control the bitcoin chain), you would atleast need 12.000.001++ TH/S, lets say we would generate this power with an Antminer S9+, currently the fastest, (i believe?) which has an average speed of 11.5TH/S
12.000.001TH/s / 11.5 = 1043479 Antminers, which would cost a total of
1043479*2000= 2.1 billion$
If you're willing to spend that much money just to short bitcoin, you have to ask yourself if it's going to viable, and profitable.
Even if there's a majority attack, miners still can't decide the protocol rules. See What can an attacker with 51% of hash power do?
as to what is actually possible with a 51% majority of the hashpower.
You could then speculate on the price going down, but then again, it might not, leaving you with extreme losses.
Also, you would probably be able to earn way more by simply mining the majority of the blocks and its fees.. 25 Bitcoin every 10 minutes ( since you have the majority) = 250k$ every 10 minutes. ( At the current exchange rate. )
250.000*6*24=36.000.000$ in blockrewards each day alone.
So, i'm not saying that you can't theorethically making profit shorting it while trying to destroy it with a majority hashpower, but that there are probably better options.
| {
"pile_set_name": "StackExchange"
} |
Q:
Review of approach to client-side only hashing and encryption for web application
Background: I have little knowledge of hashing and encryption, so please bear with me.
I have posted a related question here: https://softwareengineering.stackexchange.com/questions/232261/options-for-client-side-encryption-of-local-web-databases for the programming perspective, which may give some background. That question was about the general feasibility of the overall product. In a sense, this question is a follow-up, about the actual implementation, but as it is more technical on the security side I felt it would be better posted here. Feel free to post on either question/both questions as appropriate.
I have been tasked in securing local data for a web application that can be used offline, so interaction with the server for authentication and encryption is not an option. This would be optional, for users who would like an extra layer of protection on top of the hardware encryption.
The application will be for a single user per device. The goal is to try and reduce the risk of unauthorised access to sensitive data if a device is lost or stolen.
My initial ideas of how I could do this are:
Require the user to enter a password every time the application starts.
Hash the password using PBKDF2, storing the hash and the salt locally, e.g. in WebSQL.
User would then enter their password, it could be re-hashed using the loaded salt and compared against the stored hash.
Store the password in a JavaScript variable locally, perhaps using a different hashing method to what is used to store in the database?
Use this as a key for encrypting and decrypting (using AES) data in the database.
The local data will be encrypted - however the encryption/decryption logic will be evident from looking at the JavaScript source code. So the key used to encrypt/decrypt cannot just be the stored, hashed password, as that would be obvious.
Q: How could this approach be improved? Would hashing the password in two different ways, one for storage, and one for encryption/decryption, be sufficient? Is there anything more that I could be doing, bearing in mind the limitations of working with web storage and without a server/external hardware to assist?
Also - although the user will be working offline with the application, so the data needs to be local and encrypted, there will be an initial connection to the server to actually download the application. So if there is anything I can do based on that initial connection that might help then let me know.
A:
You are going about it wrong. There is no point at all to a hash for authentication if the comparisons are being done locally because an attacker can simply inject the hash value directly into memory and bypass the authentication check.
For local purposes, you have to use something like your second part of your idea, but that part should be done using existing standards. What you need is a key derivation function. A key derivation function is an algorithm that can securely take a password and use it to form an encryption key. Since the keys that are built are frequently relatively weak, it should be used to encrypt a truly random key which is then used for the actual encryption and decryption of the DB.
Using an encryption based approach, it becomes irrelevant if the user forces a key in to memory because they will be unable to access the encrypted data. The encryption itself acts as both the authentication and data protection mechanism. (If you want a way to verify proper decryption, you can always encrypt a known value and check the decryption of that value.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Edit Sketch options for digitizing polygons
Trying my hand at building a methodology on QGIS as opposed to ESRI, and I'm having some issues with simple digitizing of irregular polygons. The edit sketch graphic that appears when adding a new polygon feature is only transparent in the area where no coverage exists of previously added vertices. The problem arises when trying to digitize a polygon that has internal angles. It gets to a point in the digitizing that you can no longer see your base map to digitize from. I have looked at QGIS digitizing options and how found nothing to adjust the transparency of the edit sketch polygon. so I might be able to see the underlying map as I digitize. Screenshots below to illustrate my point.
Is there a way to combat this, other than to complete the polygon and then go in and modify individual nodes to position correctly?
[SOLVED] - By Jake below. I missed the simple ability to modify the Alpha channel of the rubberband setting.
A:
You can increase the transparency in "Settings / Options" "Digitizing" by changing the "Line Color" in the "Rubberband" section: Click on the coloured rectangle, and set the Alpha channel to something lower (100, say).
| {
"pile_set_name": "StackExchange"
} |
Q:
What is a simple algorithm / approach to store key-value (number-number) pairs *in disk* for quick access by key?
I need to store many Long-Long pairs in disk, not in memory, for example:
(123, 2)
(1253, 3)
(12345, 6)
...
So later I can easily do:
long value = get(123); // => 2
Is there a simple approach to do that? I am hoping it does not need to be as complicated as a hashtable in disk.
To make it clear, the pairs will NOT be stored in memory, they will be written straight to a file or set of files in disk.
A:
There are multiple key/value stores available. A quite comprehensive list can be found here.
One good alternative is to use MapDB which is a fast and easy-to-use NoSQL database which supports disk storage and transactions.
To use it, simply follow the instructions in the cheat sheet:
File file = new File(“dbFileName”);
DB db = DBMaker.newFileDB(file).make();
//use map
Map map = db.getHashMap(“mapName”);
map.put(“aa”,”bb”);
//commit and close database
db.commit();
db.close();
Plus, it obviously works for Long values as well!
| {
"pile_set_name": "StackExchange"
} |
Q:
Event Reciever on Item created
I am working on creating a event reciever on a custom list ..
my senario: I have a customizes newform.aspx and this form has a field called ticketID as hidden ..in the newform..so when a user creates a new item this Ticketid is created (i m thinking abt using event reciever for this) .. and when ever the user goes and edits the form..he can see this ticketid in that form..
ticket id gen..we have 3 locations dallas,kansas,london..so if the first user comes from dallas..the id for him will be inctick1d..and after if the 2nd person comes in and creates new item from kansas his id will be inctick1k..now again if the user from dallas comes in and create an new item his id will be inctick2d--this logic i m planning to write in event reciever under item added event
but it seems like if i use an item added event ..the ticket gen logic will fire when the first time the new item is created(which is what i want) but also for the item any other empty field value which was previously empty becomes assigned(which i dont want).
A:
ItemAdded event fires only when Item is added first time, not when you revisit the item and update it.
If your id is fixed (i mean inctick1d for all persons from Dallas), and just depends on location and location is a drop down (not a lookup), you can also consider using calculated column.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I change the encoding of a subtitle file?
I downloaded a Greek subtitle for a movie, and this is what I see when I open it with Gedit.
Subtitle works great on VLC, all perfect.
But what if I want to edit this subtitle with some Greek words? I instantly get an error about character encoding.
I hit retry and then VLC doesn't recognize the subtitles...
A:
For subtitle edition/translation (text-based subtitles, that is), I strongly suggest Gaupol.
sudo apt-get install gaupol
Besides of gaupol, you can also try Subtitle Editor and Gnome Subtitles.
However, from the screenshots, it is clear that your .srt file is not encoded in Unicode.
As it turns out, iconv does change the encoding of the file to UTF-8, but the converted file will still have the same characters you see when opening in Gedit.
The solution I found is this:
Open Gaupol and go to menu File → Open or click on the button Open.
There is a selection menu in the lower part of the open window, titled Character encoding. Click on Other... (last option).
Select an appropriate encoding for your file, e.g. Greek ISO-8859-7, and click on the button Accept.
Now open your .srt file and make sure all characters are correctly rendered. Otherwise, repeat the above procedure with another encoding. You can run the command file -bi yourfile.srt to determine the correct encoding of your file (although I've read the results are not necessarily exact).
With your subtitle file open in the correct character encoding, now go to the menu File → Save as... and change the character encoding option (again, at the bottom of the window) to UTF-8 and save the file (possibly with a new name, for safety).
This same procedure of adding the codepage will work for Gedit. Yet I leave the instructions for Gaupol since this question is about subtitle files.
Good luck.
A:
iconv -f ISO-8859-7 -t UTF-8 Input_file.srt > Output_file.srt
Open them from Kate editor you can see the proper text, if you still need to open them from Gedit, in other words, permanently change the codification run the above terminal command.
A:
I'd recommend enca. Unlike gaupol, you can handle not only subtitle-files, but any text file.
Install enca:
sudo apt-get install enca
To figure out the encoding of the file, see if enca can guess it:
enca <file>
or, if it fails and you know the language of the text file, than run for example
enca -L ru <file>
and see what it gives you. Get the list of supported languages from man enca.
I'd recommend to convert to UTF-8, you can do it by running
enconv -x utf8 <file>
or, again, if enca cannot guess the language by
enconv -L ru -x utf8 <file>
that should do the trick.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to call a function in a user defined function im Emacs?
I use defun to define a function in my .emacs file:
(defun myfun ()
"i am already loaded the color-theme lib"
(color-theme-initialize)
(color-theme-darkblue))
Then I want to use this function in my mode-hook:
(add-hook 'python-mode-hook
'(lambda ()
(myfun)
(...)))
But I got an error saying that the color-theme-initialize function is void.
P.S. my ~/.emacs snippet
(progn (require 'color-theme)
(color-theme-initialize))
(progn (setq-default indent-tabs-mode nil)
(setq-default tab-width 2)
(setq indent-line-function 'insert-tab))
(add-hook 'emacs-lisp-mode-hook
'(lambda ()
(color-theme-resolve)
(show-paren-mode t)
(linum-mode t)))
A:
You need to require (or otherwise load) the library which provides color-theme-initialize. I'm guessing (require 'color-theme).
| {
"pile_set_name": "StackExchange"
} |
Q:
Choosing same color after Wild (+4)
Playing Uno this weekend, one of the players played a Wild+4 but chose the same color that was in play (this led to a successful challenge). I had thought that, regardless of what's in the player's hand, the player could not choose the same color after playing a Wild+4 - it had to change to one of the other 3 colors. A player could choose the same color after playing a regular Wild, though.
Looking at the rules, though, I did not see this restriction; only that the player playing the Wild+4 must not have any cards of the same color in play. Given that my Uno deck is a fairly recent version, I'm wondering if older versions did have that rule? Or maybe it was just a house rule. If so, is that a common house rule? Or maybe it just stemmed from the need to not have the current color in your hand...
A:
These rules appear to be from 2001, and these rules appear to be from 2003. Both sets of rules do not indicate any restrictions on the choice of colour after either wild.
The points from both rules about Wild Draw 4 are:
You play it and choose the colour to continue.
The next player draws 4 and misses their turn.
You can only play this if you don't have a card of the matching colour.
You can break the above rule.
The person drawing 4 may challenge you. If they win, the you draw 4 instead. If they lose, they draw an additional 2. (Note that they still miss their next turn)
Neither set of rules have any limitation on the colour choice.
For further reference, there's this question regarding the history of UNO rules. The 1983 rules found there follow the same draw 4 rules as the more recent rules printings.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the WebGLActiveInfo function?
In Chrome, open your JavaScript console and you will find WebGLActiveInfo as a global variable. I've tried looking for documentation on this function but nothing comes up.
Naively calling it will produce a TypeError: Illegal constructor, which is frustrating because it's a black box:
function WebGLActiveInfo() { [native code] }
What does this function do? How can I use it?
A:
It's not a function, it's the name of a native Object. Same as WebGLRenderingContext, WebGLTexture, Blob, or XMLHTTPRequest. Type any of those and you'll get the same function signature.
WebGLActiveInfo objects are returned from gl.getActiveUniform and gl.getActiveAttrib
| {
"pile_set_name": "StackExchange"
} |
Q:
Native ComboBox not displaying choices correctly
EDIT: It seems that ListPicker is the way to go but I have had further problems with that detailed Microsoft.Phone.Controls.Toolkit ListPicker throws XamlParseException
I have the following ComboBox in code:
<ComboBox x:Name="Result" Grid.Column="6" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="Black" Background="White">
<ComboBoxItem Content="Win" />
<ComboBoxItem Content="Place" />
<ComboBoxItem Content="Lose" />
</ComboBox>
But it does not display as I would have expected. When you drop down the ComboBox the options don't appear, it's just like empty items. See below:
However, when an item is selected, it displays correctly and the correct index/item is returned. See below:
I'm sure there is something simple I have missed but can't put my finger on it.
EDIT: Ok I am posting the full code for this. I have a user control, OddsRow, that looks like this:
<UserControl xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" x:Class="MojoPinBetOddsCalculator.OddsRow"
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"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="480" d:DesignWidth="480">
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="70"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*"></ColumnDefinition>
<ColumnDefinition Width="70*"></ColumnDefinition>
<ColumnDefinition Width="30*"></ColumnDefinition>
<ColumnDefinition Width="70*"></ColumnDefinition>
<ColumnDefinition Width="70*"></ColumnDefinition>
<ColumnDefinition Width="70*" ></ColumnDefinition>
<ColumnDefinition Width="100*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock x:Name="RowNumber" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBlock>
<TextBox x:Name="OddsNumerator" Grid.Column="1" Width="90" Height="70" HorizontalAlignment="Center" TextAlignment="Center" VerticalAlignment="Center" MaxLength="3" InputScope="TelephoneNumber"></TextBox>
<TextBlock x:Name="Slash" Grid.Column="2" Text="/" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
<TextBox x:Name="OddsDenominator" Grid.Column="3" Width="90" Height="70" VerticalAlignment="Center" TextAlignment="Center" MaxLength="3" HorizontalAlignment="Center" InputScope="TelephoneNumber"></TextBox>
<CheckBox x:Name="EachWay" Grid.Column="4" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="10,0,0,0" />
<CheckBox x:Name="Place" Grid.Column="5" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0" Width="71" Margin="10,0,0,0" Padding="0" />
<ComboBox x:Name="Result" Grid.Column="6" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="Black" Background="White">
<ComboBoxItem Content="Win" />
<ComboBoxItem Content="Place" />
<ComboBoxItem Content="Lose" />
</ComboBox>
</Grid>
</UserControl>
And it is displayed in the MainPage like so:
<phone:PhoneApplicationPage xmlns:my="clr-namespace:MojoPinBetOddsCalculator"
x:Class="MojoPinBetOddsCalculator.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="BET ODDS CALCULATOR" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="calculate" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" HorizontalAlignment="Stretch">
<Grid x:Name="Scrollable">
<ScrollViewer>
<Grid x:Name="BettingGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid x:Name="BetList">
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="70"></RowDefinition>
<RowDefinition Height="70"></RowDefinition>
<RowDefinition Height="70"></RowDefinition>
<RowDefinition Height="70"></RowDefinition>
<RowDefinition Height="70"></RowDefinition>
<RowDefinition Height="70"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*"></ColumnDefinition>
<ColumnDefinition Width="70*"></ColumnDefinition>
<ColumnDefinition Width="30*"></ColumnDefinition>
<ColumnDefinition Width="70*"></ColumnDefinition>
<ColumnDefinition Width="70*"></ColumnDefinition>
<ColumnDefinition Width="70*"></ColumnDefinition>
<ColumnDefinition Width="100*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="EW" Style="{StaticResource PhoneTextNormalStyle}" Grid.Row="0" Grid.Column="4" HorizontalAlignment="Center" />
<TextBlock Text="Place" Style="{StaticResource PhoneTextNormalStyle}" Grid.Row="0" Grid.Column="5" HorizontalAlignment="Center" />
<TextBlock Text="Result" Style="{StaticResource PhoneTextNormalStyle}" Grid.Row="0" Grid.Column="6" HorizontalAlignment="Center" />
<my:OddsRow Grid.Row="1" Grid.ColumnSpan="7" Row="1"/>
<my:OddsRow Grid.Row="2" Grid.ColumnSpan="7" Row="2"/>
<my:OddsRow Grid.Row="3" Grid.ColumnSpan="7" Row="3"/>
<my:OddsRow Grid.Row="4" Grid.ColumnSpan="7" Row="4"/>
<my:OddsRow Grid.Row="5" Grid.ColumnSpan="7" Row="5"/>
<my:OddsRow Grid.Row="6" Grid.ColumnSpan="7" Row="6"/>
</Grid>
<Grid x:Name="ControlsGrid" Grid.Row="1">
<Button x:Name="AddRowButton" Background="#BFFFFFFF" BorderBrush="#BFFFFFFF" Foreground="Black" Content="Add Row" FontSize="16" Click="AddRowButton_Click" Height="70" />
</Grid>
</Grid>
</ScrollViewer>
</Grid>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
Separately the ComboBox works, and also the code for the OddsRow works as expected... separately. When combined it doesn't display the items.
OddsRow.xaml.cs
public partial class OddsRow : UserControl
{
private int m_Row;
public OddsRow()
{
InitializeComponent();
}
public int Row
{
get
{
return m_Row;
}
set
{
m_Row = value;
RowNumber.Text = m_Row + " - ";
}
}
}
A:
For the love of everything, please do not use the stock ComboBox. Use something like ListPicker. It will make your application look more consistent with the Metro UI.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cant figure out why my character, word and line count will work with file input but not from stdin
Im pretty new to C programming and I am having trouble with stdin. My code is supposed to display the number of words, lines and characters contained in an input file or standard input. If its displaying the numbers from a file, then the name of the file needs to be along side of the number of words, lines and characters like so:
0 0 0 test.txt
I am able to do this but then stdin will not work and I get
"Segmentation Fault (core dumped)"
enum state
{
START,
WORD,
DELIM,
};
FILE *
input_from_args(int argc, const char *argv[])
{
if (argc == 1){
return stdin;
} else {
return fopen(argv[1], "r");
}
}
void
wcount(FILE *src, FILE *dest, const char *argv[])
{
int ch, wc, lc, cc;
enum state cstate;
wc = lc = cc = 0;
cstate = START;
while ((ch = fgetc(src)) != EOF){
cc++;
switch (cstate){
case START:
if (isspace(ch)){
cstate = DELIM;
if (ch == '\n'){
lc++;
}
} else{
cstate = WORD;
wc++;
}
break;
case DELIM:
if (ch == '\n'){
lc++;
} else if (!isspace(ch)){
cstate = WORD;
wc++;
}
break;
case WORD:
if (isspace(ch)){
cstate = DELIM;
if (ch == '\n'){
lc++;
}
}
break;
}
}
fprintf(dest, "%d\t%d\t%d\t%s\n", wc, lc, cc, argv[1]);
}
I have a feeling the reason I'm running into this problem has to do with the argv[] in my wcount function.
Sorry for the wall of text in this post, I'm new to this site and don't exactly know how I should be posting questions. Thanks
edit: the file is specified after I compile and run the program.
So i say
./tstats test.txt
and it displays
0 0 0 test.txt
A:
In
void wcount(FILE *src, FILE *dest, const char *argv[])
You get the argument argv just to use it at
fprintf(dest, "%d\t%d\t%d\t%s\n", wc, lc, cc, argv[1]);
But you use it without checking if it actually exists, something you did do in the input_from_args function.
So you either pass argc as an argument for wcount too and do:
if (argc == 1) {
fprintf(dest, "%d\t%d\t%d\tstdin\n", wc, lc, cc); // no argv[1]
else {
fprintf(dest, "%d\t%d\t%d\t%s\n", wc, lc, cc, argv[1]);
}
Or you pass instead of argv a char* filename argument, that you check outside of the call of wcount, and proceed with a
fprintf(dest, "%d\t%d\t%d\t%s\n", wc, lc, cc, filename);
call.
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery click event not working properly with an element
<button type="button" class="add-to-cart"><i class="material-icons">add_shopping_cart</i>cumpara</button>
<button class="added add-to-cart"><i class="material-icons check">check</i><i class="material-icons clear">clear</i>Adaugat in cos</button>
I have these two buttons with this CSS code:
.add-to-cart
{
position: relative;
overflow: hidden;
line-height: em(48);
background: complement($rodie);
border: none;
color: $gray-100;
text-transform: uppercase;
height: em(48);
width: 100%;
font-size: em(18);
display: inline-block;
transition: all 250ms ease-out;
&.clicked
{
transform: translateX(-100%);
}
&:hover
{
background: complement(darken($rodie, 10%));
}
i
{
position: absolute;
right: 0;
top: 0;
font-size: em(18);
height: em(48);
width: em(48);
line-height: em(44);
}
}
.added
{
position: absolute;
right: -100%;
top: 90%;
z-index: 22;
background: $verde-jungla;
&:hover
{
background: $verde-jungla;
}
&.clicked
{
transform: translateX(-100%);
}
.check
{
left: 0;
}
}
.clear
{
transition: all 100ms ease-in-out;
height: em(48);
width: em(48);
right: 0;
background: desaturate(red, 30%);
&:hover
{
background: desaturate(darken(red, 10%), 30%);
}
}
I want the button to respond to a click event by transitioning the second button, which has an icon and a message (that informs the user that the product has been added to the cart) attached to it. The first transition works. When I click on the button, the other one appears as it's supposed to, but when the clear "button" (the <i> with the class of clear) is pressed, it's not working.
This is the JQuery code:
$('.add-to-cart').click(function(){
$('.add-to-cart').addClass("clicked");
});
$('.clear').click(function(){
event.preventDefault();
$('.add-to-cart').removeClass("clicked");
});
Keep in mind that if I change the selected element of the second click event, the process works just fine.
A:
Having the .clear button inside an .add-to-cart is asking for problems.
When you click .clear, at the same time you click .add-to-cart.
You did add event.preventDefault, but you don't just want to prevent the default. You also need to prevent the event from "bubbling" up.
Also, the variable event does not exist, you need to add it as the name of the first argument.
Try:
$('.clear').click(function(event){
event.stopPropagation();// Stop bubbling up
event.preventDefault();
$('.add-to-cart').removeClass("clicked");
});
But a far better solution would be to move .clear outside of the button that has .add-to-car.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding an outlet in a water heater closet
I have a closet in my garage which currently contains my water shutoff valve and a natural gas water heater. I'm planning on adding a whole-house water filter that requires a little bit of power (36w max) so I put a GFCI outlet in the closet and ran 12/2 NM cable up into the attic. Now, there's a closet on the other side of the wall where my outlet is that contains two power circuits, but they're used for a different purpose (media closet) so I was planning on tying into a outlet in the attic that's off of the branch circuit marked "garage" on my breaker box. Does this make the most logical sense? It's a bit more work but it seems the most logically consistent to me. My garage is supposedly GFCI protected as well, but I can't be 100% sure since I don't have a wiring diagram, hence why I added another GFCI outlet in the circuit. Am I off in my thinking on this? Edit: I also put the outlet maybe 3-4 feet off the ground just to add in a safety margin for the natural gas, in case there's a leak.
A:
For a load so small as < 50 watts, I wouldn't worry about what circuit I was adding it to. I'd recommend using the closest one easily accessible.
Before spending the money to buy a GFCI outlet, I'd check to see if the location I'm tapping into was already GFCI protected. There are GFCI testers out there, and I'd recommend using one if you have one. If not, use a small incandescent lamp that you can switch on and off without touching any metalwork of the lamp; and a discarded grounded (3-prong) plug. Turn the lamp off and temporarily connect the two prongs of the lamp to the ground and hot wires of the 3-prong plug.
Plug it in to the source outlet and briefly turn it on and off. That will safely trip its GFCI protection if it has GFCI protection. Probably quickly enough that you won't even see the lamp light up. If the lamp lights up, then your source isn't gfci protected and it's worth the money to use a GFCI outlet. I'd recommend adding that outlet in a position as near the circuit breaker panel as possible to get the best utilization of it though. So replace the most upstream outlet and use the one you pulled out of the wall, in the new location.
Put the outlet at a height that is convenient and accessible. The risk with a gas leak is if there is a spark and that spark occurs in an area of atmosphere with the proper mixture of gas and oxygen for ignition. A plug in an outlet is't going to make sparks just sitting there. It's only a risk when plugging and unplugging.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding a sidebar on Google maps that display's polygon attributes
when clicked on a polygon (Postcode area) the infowindow shows the attributes of that polygon. What I'm trying to do is display the polygon attribute into a sidebar instead of the popup window. here is my code http://jsfiddle.net/Shamiri/7eb3fyt2/ which has the polygon and infowindow, on the right is what I'm hoping to get.
<!DOCTYPE html>
<html>
<head>
<title>SA POSTCODES</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100%; }
#wrapper { position: relative; }
#over_map_left { position: relative; background-color: transparent; top: 10px; left: 10px; z- index: 99; background: white; }
#over_map_right { position: absolute; background-color: transparent; top: 50px; right: 10px; z-index: 99; background: white; padding: 10px }
table {
width:100%; }
table#t01 tr:nth-child(even) {
background-color: #eee;}
table#t01 tr:nth-child(odd) {
background-color:#fff;}
table#t01 th {
background-color: black;
color: white;}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 6,
center: {lat: -28, lng: 137.883},
mapTypeId: google.maps.MapTypeId.ROADMAP });
var infowindow = new google.maps.InfoWindow({
maxWidth: 800 });
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Load GeoJSON.
map.data.loadGeoJson('https://dl.dropbox.com/s/hgh6g4y34ne02xj/sampleData2.json');
// Color each layer gray. Change the color when the isColorful property
// is set to true.
map.data.setStyle(function(feature) {
var color = 'gray';
if (feature.getProperty('isColorful')) {
color = feature.getProperty('color');
}
return /** @type {google.maps.Data.StyleOptions} */({
fillColor: color,
strokeColor: color,
strokeWeight: 1
});
});
// When the user clicks, set 'isColorful', changing the color of the letters.
map.data.addListener('click', function(event) {
event.feature.setProperty('isColorful', true);
});
map.data.addListener('mouseover', function(event) {
map.data.revertStyle();
map.data.overrideStyle(event.feature, {strokeWeight: 8});
});
map.data.addListener('mouseout', function(event) {
map.data.revertStyle();
});
map.data.addListener('click', function(event) {
infowindow.setContent(event.feature.getProperty('POSTCODE')+"<br>"+ '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
'<div id="bodyContent">'+
'<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' + event.feature.getProperty('SUBURB'));
infowindow.setPosition(event.latLng);
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-34)});
infowindow.open(map);
});
map.data.addListener('click', function(event) {
infowindow.setContent('<h1 id="firstHeading" class="firstHeading"> SUBURB INFO </h1>'+ '<p> Suburb name:' +event.feature.getProperty('SUBURB') + '</p> <b> POSTCODE:' + event.feature.getProperty('POSTCODE') + '<p> Unemployment:' +event.feature.getProperty('SHAPE.LEN')+'</p>');
infowindow.setPosition(event.latLng);
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-34)});
infowindow.open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="over_map_right">
<h2>SUBURB Information</h2>
<table id="t01">
<tr>
<th>Suburb</th>
<th>Postcode</th>
<th>Unemployment</th>
</tr>
<tr>
<td>Suburb1</td>
<td>postcode1</td>
<td>Unemployment1</td>
</tr>
<tr>
<td>Suburb2</td>
<td>postcode2</td>
<td>Unemployment2</td>
</tr>
</table>
</div>
</body>
</html>
A:
As far as I understand, only selected Suburb information would be displayed on sidebar.
So, instead table cells, if a span or div with an ID attribute be placed.
And use the same statements of getting data from event, and assign the value to innerHtml of the div or span.
E.g. document.getElementById('divIdOrSpanId').innerHTML = event.feature.getProperty('SUBURB');
Hopefully this would solve it for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
How intialize rabbitmq via masstransit?
I try to implement rabbitmq via masstransit as in instruction https://masstransit-project.com/usage/transports/rabbitmq.html#cloudamqp
But Bus (IBusControl) doesn't have Factory method.
Bus.Factory.CreateUsingRabbitMq
MassTransit, MassTransit.RabbitMQ - 6.2.0 version.
Do you know what I forgot include?
A:
I had a conflict with a method called Bus and static class Bus.
Should use namespace path
MassTransit.Bus.Factory.CreateUsingRabbitMq
| {
"pile_set_name": "StackExchange"
} |
Q:
Was the Fellowship supposed to visit Galadriel originally?
In Gandalf's and co original plan (pre-Moria), was the Fellowship supposed to visit Lothlórien and meet Galadriel?
A:
It does seem that way (emphasis mine):
I shall take you by the road that Gandalf chose, and first I hope to come to the woods where the Silverlode flows into the Great River-out yonder.' They looked as [Aragorn] pointed, and before them they could see the stream leaping down to the trough of the valley, and then running on and away into the lower lands, until it was lost in a golden haze.
'There lie the woods of Lothlórien!' said Legolas.
Fellowship of the Ring Book II Chapter 6: "Lothlórien"
'Your quest is known to us,' said Galadriel, looking at Frodo. 'But we will not here speak of it more openly. Yet not in vain will it prove, maybe, that you came to this land seeking aid, as Gandalf himself plainly purposed.
Fellowship of the Ring Book II Chapter 7: "The Mirror of Galadriel"
[I]s all this Company going with you to Minas Tirith?'
'We have not decided our course,' said Aragorn. 'Beyond Lothlórien I do not know what Gandalf intended to do. Indeed I do not think that even he had any clear purpose.'
Fellowship of the Ring Book II Chapter 8: "Farewell to Lórien"
It's also implied that Elrond's sons were sent to Lothlórien as part of the scouting effort:
The sons of Elrond, Elladan and Elrohir, were the last to return; they had made a great journey, passing down the Silverlode into a strange country, but of their errand they would not speak to any save to Elrond.
Fellowship of the Ring Book II Chapter 3: "The Ring Goes South"
| {
"pile_set_name": "StackExchange"
} |
Q:
alarmManager.cancel not working
I'm trying to stop a repeating alarm.
I already looked all over the web for solution, but my code seems fine...
Still it doesn't stop the alarm...
Here's a little bit of code (FM is a file-writing object)
public void StartAlarm() {
Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar alarm = Calendar.getInstance();
alarm.setTimeInMillis(System.currentTimeMillis());
alarm.set(Calendar.HOUR_OF_DAY, 15);
alarm.set(Calendar.MINUTE, 0);
long alarmCal=alarm.getTimeInMillis();
if (alarmCal<=new Date().getTime()) {
alarm.add(Calendar.DAY_OF_MONTH, 1);
}
am.setRepeating(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender);
FM.Write("startAlarm()");
}
public void StopAlarm() {
if (isAlarmRunning()) {
Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(sender);
FM.Write("alarm canceled");
isAlarmRunning();
}
public boolean isAlarmRunning() {
Intent intentToCheck = new Intent(getApplicationContext(),AlarmReciever.class);
boolean alarm = PendingIntent.getBroadcast(getApplicationContext(), 0, intentToCheck,
PendingIntent.FLAG_NO_CREATE) != null;
FM.Write("alarm = "+alarm);
if (!alarm) {
return false;
}
else
return true;
}
Thanks!
A:
How are you verifying that the alarm is still there? You need to use an equivalent PendingIntent (same intent, same flags) to stop the alarm, and it does work. BTW, your isAlarmRunning() method checks whether a PendingIntent exists, which is not the same as the alarm being registered. It could return true even though the alarm has been deleted.
A:
use this in both function
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
| {
"pile_set_name": "StackExchange"
} |
Q:
Opening an Application via Terminal
I am a new user of precise pangolin and learning to use the terminal. I just wonder whether there is any easy command/combination of commands to open an application (LibreOffice Writer, for example) via terminal, just like we use sudo apt-get install <<packagename>> to install an application.
A:
You can just type the the name of the application you want to start. In your case it would be libreoffice or if you want to go to writer directly you can type libreoffice --writer
A:
If you do not want the application tied to a controlling terminal you can type the application name followed by & disown.
In @Germar's example the full command would read libreoffice & disown. This would enable you to close the terminal you launched from, and continue using libreoffice.
| {
"pile_set_name": "StackExchange"
} |
Q:
When to pass a pointer and when to pass the memory address of a pointer?
I am looking at the following piece of code:
StJetEvent* jets = 0;
jetChain->SetBranchAddress("AntiKtR060NHits12",&jets);
Where we have that:
The class of jetChain is TChain
and the definition of SetBranchAddress is:
Int_t TChain::SetBranchAddress ( const char * bname, void * add, TBranch ** ptr = 0)
The definition of the relevant parameters inside of the the argument of the SetBranchAddress is:
bname is the name of a branch.
add is the address of the branch.
For some reason, when I look at SetBranchAddress("AntiKtR060NHits12",&jets), based on the definition of the function SetBranchAddress, I would think that the second parameter that needs to be passed is a pointer, but instead the address of the pointer jets is passed. This is consistent with what the definition of what the second parameter is, but from my basic understanding, I thought that void * add means to pass a pointer and NOT the address of the pointer.
Can someone please provide me with some clarification, please? Thank you very much!
A:
The syntax &z returns a pointer to z. The terms "address of X" and "pointer to X" mean almost exactly the same thing.
int z;
int* q = &z; // now q is a pointer to z
int** r = &q;
When we say "q is a pointer to z", we mean two things:
The type of 'q' is pointer to whatever type 'z' is.
The value of 'q' is the address of 'z'.
So here, 'r' is a pointer to 'q' for the same reasons.
| {
"pile_set_name": "StackExchange"
} |
Q:
General question on subsequences
I was wondering if it possible for a sequence to have three different subsequences, one converging to 1, one to 2, and another to 3? I think it does but don't know what the sequence is.
A:
Just take a sequence that converges to 1, one that converges to 2, and another that converges to 3, and interleave them.
(E.g. 1,2,3,1,2,3, $\cdots$ )
A:
The sequence defined by $$a_n=\begin{cases}1-\frac{1}{n} :\quad n\equiv0\pmod{3}\\2-\frac{1}{n}:\quad n\equiv1\pmod{3}\\3-\frac{1}{n}:\quad n\equiv2\pmod{3}\end{cases}$$suffices for $n>0$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Excel vlookup of untrimmed cell
I want to use vlookup but the column in the table that is to be searched has occasional entries with a trailing space. But vlookup cannot find these because of the trailing space.
vlookup('Smith',tablename, columnnumber,TRUE) cannot find 'Smith '.
The table is from an external database that I cannot edit. Setting the third parameter of vlookup to FALSE does not work either, although you would think that Smith is the next closest thing to Smith.
A:
You cannot wildcard your VLOOKUP function's lookup_value without risking a false positiove on Smithers when you are searching for Smith. However, the IFERROR function can pass control to an alternate VLOOKUP that appends a single space to the lookup_value.
=IFERROR(vlookup("Smith", tablename, columnnumber, FALSE), IFERROR(vlookup("Smith"&CHAR(32), tablename, columnnumber, FALSE), ""))
If Smith cannot be found then append a space character and try again. If it still fails, give up and pass back a zero-length string.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cancel deployment on TFS programmatically via C#
I want to abort running deployment via TFS API with C#.
A:
You can use .NET client libraries for Azure DevOps Services (and TFS).
This code snippet cancel a release:
string projectName = "";
int releaseId = 1;
string collectionUri = "";
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
// Connect to Azure DevOps Services
VssConnection connection = new VssConnection(new Uri(collectionUri), creds);
ReleaseHttpClient releaseClient = connection.GetClient<ReleaseHttpClient>();
ReleaseUpdateMetadata releaseUpdateMetadata = new ReleaseUpdateMetadata()
{
Comment = "Abandon the release",
Status = ReleaseStatus.Abandoned
};
// Abandon a release
WebApiRelease updatedRelease = releaseClient.UpdateReleaseResourceAsync(releaseUpdateMetadata, projectName, releaseId ).Result;
More details and examples you can find here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't fit my navbar links inside the navbar
I'm setting up a portfolio page for an assignment. I made some changes to my code, and now my navbar isn't working properly. I can't get my page links to fit in my actual navbar they are sitting below it for some reason.
I've tried messing with the padding and margins, but that's not doing anything. It was working fine at one point but I'm not sure what changed.
HTML:
<nav>
<p>STEVEN KANG</p>
<ul>
<li class="rightLinks"><a data-scroll-target="contact">Contact</a></li>
<li class="rightLinks"><a data-scroll-target="projects">Portfolio</a></li>
<li class="rightLinks"><a data-scroll-target="bio">Bio</a></li>
</ul>
<div class="menu-toggle">
<a href="javascript:void(0);" class="icon"><i class="fa fa-bars"></i></a>
</div>
</nav>
CSS
nav {
background-color: black;
height:60px;
color: #666666;
position: fixed;
top:0;
left:0;
right:0;
width: 100%;
}
nav p {
font-weight: bold;
margin-top: 25px;
margin-left: 10px;
color: white;
text-align: left;
}
nav a {
color: red;
}
nav ul {
margin-bottom: 5em;
}
.rightLinks {
list-style: none;
float: right;
margin-right: 50px;
margin-left: 15px;
}
Those bio, portfolio, and contact links should be on the right centered inside the navbar mirroring my element saying my name.
I feel like it's a simple fix, I'm just not sure what's wrong right now.
A:
I've taken a look at your code. It looks like you need to to utilise floats and a clearfix in order to achieve this.
Take a look at: https://codepen.io/mrmathewc/pen/OKbXRY
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Steven Kang - Developer</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="index.css">
<link href="https://fonts.googleapis.com/css?family=Rubik&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Karla&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<nav>
<div class="float-left">
<p>STEVEN KANG</p>
</div>
<ul class="float-right">
<li class="rightLinks"><a data-scroll-target="contact">Contact</a></li>
<li class="rightLinks"><a data-scroll-target="projects">Portfolio</a></li>
<li class="rightLinks"><a data-scroll-target="bio">Bio</a></li>
</ul>
<div class="menu-toggle">
<a href="javascript:void(0);" class="icon"><i class="fa fa-bars"></i></a>
</div>
<div class="clearfix"></div>
</nav>
</body>
CSS:
* {
box-sizing: border-box;
}
body {
text-align: center;
}
h1 {
font-family: 'Rubik', sans-serif;
font-size: 48px;
}
h2 {
font-family: 'Rubik', sans-serif;
font-size: 30px;
}
h3 {
font-family: 'Karla', sans-serif;
font-size: 20px;
color: #0047b3;
;
}
p {
font-family: 'Karla', sans-serif;
font-size: 16px;
color: black;
font-weight: bold;
}
nav {
background-color: black;
height:60px;
color: #666666;
position: fixed;
top:0;
left:0;
right:0;
width: 100%;
}
nav p {
font-weight: bold;
margin-top: 25px;
margin-left: 10px;
color: white;
text-align: left;
}
nav a {
color: #0047b3;
}
nav ul {
margin-bottom: 5em;
}
.rightLinks {
list-style: none;
float: right;
margin-right: 50px;
margin-left: 15px;
}
.float-left {
float: left;
}
.float-right {
float: right;
}
.clearfix { clear: both; }
I would recommend looking into Flexbox though, floats can give you some headaches.
Here's a basic example: https://codepen.io/mrmathewc/pen/wVoWgV
You'll need to extend the above to your code. This may help you understand Flexbox more: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
| {
"pile_set_name": "StackExchange"
} |
Q:
Was Leverrier-Adams prediction of Neptune a lucky coincidence?
According to historians both Adams and Leverrier used Bode's law to guess the distance to Neptune, which led to a vast overestimation of its orbital period (Adams - 227 years, Le Verrier - 218 years, actual - 165 years). Apparently, their estimate of Neptune's mass was also largely off. Nonetheless, both came up with a position in the sky close to each other's, and to the actual one:"The only actual value they were close to, if one looks at the table, is the location in the sky it would be found. It is possible that both men were simply lucky with this. We shall never truly know."
This is somewhat mystifying. The first thought is that their errors in distance and mass "compensated" each other, although I am not familiar with this type of calculation to tell if this makes sense. But it should be possible to tell if they were "simply lucky" or not. For instance, is the prediction of Neptune's position in the sky based on the parameters they assumed correct only for a short time period or more broadly? Is it the case that visible orbital deviations of Uranus only determine some function of Neptune's distance and mass, but not each value separately? And was their value close to the actual one? Did anybody look into these kinds of questions? Is there a "reason" for the correct prediction despite the erroneous estimates, or were they indeed "simply lucky"?
A:
Although this may not be what you're looking for... They weren't "simply lucky." In fact, they didn't use Bode's law at all- they used calculations based on Neptune's supposed gravitational effect on Uranus. In fact, had the two used Bode's law, they would never have found Neptune, as the Bode "law" would predict a completely different location. (This is when the "law" became discredited)
Astronomers noticed that the then-newly discovered planet, Uranus was appearing at its predicted positions later than what would be expected- this meant something should be tugging on it from behind, the opposite of its direction of motion. From the angle of this apparent slowing, astronomers could tell what angle the perturbing "bully" planet was from- applying this over multiple places in the Uranian orbit, and newtons laws of gravity, enabled them to predict where this new planet was at multiple given times, thus being able to predict its orbit. Then, they predicted where it should be at a certain time and looked for it- there it was!
Thus, it was not sheer coincidence and luck that this planet was discovered; rather, their math was what led them to it.
Note that the perturbations could be attributed to bodies of different mass at different distances from Uranus -I take it that's the reason for the two astronomers' miscalculation of
Neptune's orbital semi-major axis.
NOTE- Please don't downvote it if it's not what you were looking for, I will try to fix that if I haven't.
| {
"pile_set_name": "StackExchange"
} |
Q:
Access violation in printing out float value using printf
I get runtime Access Violation when I try to run the following line:
float x;
x = 29.600;
printf("%f", x);
This is a *.C file within CPP project, running in kernel space.
OS is vxworks 6.7
On the other hand, integer values are being printing out just fine.
Also if it might help, the float values are print out for single time.During the initialization of the full application.
Task has floating point support, so that should not be problem as well.
Same section of code is running fine on windows platform/MVCE
NOTA BEFORE CLOSING BECAUSE OF NO MVCE OR EVIDENTLY CORRECT C CODE :
This question is about kernel mode on an embedded system. A MVCE should at least contains kernel code and all the kernel developping environment reference.
Also in kernel developpement it is not really surprising because of kernel limitation for performance improvement that some perfectly correct code breaks in the context.
A:
This worked for me:
In the Kernel configuration (project explorer), windriver workbench explicitly provides option to add support for floating point math , this solved the whole issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Who benefits from flanking?
While DnD 5e no longer includes flanking as a standard rule, they have an optional rule that covers it. I've not played earlier versions, but I imagine it's very similar (if not identical) to the standard rule that existed in earlier versions. Here is the optional flanking rule from DMG p. 251:
When a creature and at least one of its allies are adjacent to an enemy and on opposite sides or corners of the enemy's space, they flank that enemy, and each of them has advantage on melee attack rolls against that enemy. - (DMG p. 251)
So if a medium creature (taking up just one square) has three adjacent enemies, two of whom are on opposite sides or corners, do all three have advantage, or just the two who are flanking?
A B A
B T OR A T A OR B T
A A etc.
Where "A" and "B" are allies and "T" is the target creature.
In each of these examples, "B" is not causing the target creature to be flanked, as there isn't another creature on the opposite side to "T" from it. Does B still get advantage?
Put another way, could we say that if a creature is flanked (see above) then all melee attacks against them are made with advantage? Or would it be better to say if "they flank that enemy, [...] both of them [have] advantage on melee attack rolls?"
A:
When dealing with Medium creatures, yes, it might read more easily to say "both". The "each of them" becomes important when dealing with Large or bigger creatures, which take up so much space that multiple creatures can fit side by side on one end.
The rule, from the viewpoint of the attacker, is basically:
Am I adjacent to an enemy?
Is at least one of my allies also adjacent to the creature on the opposite end?
If yes, you have flanking.
For an example of when the "each" comes into play, see below diagram of three Allies flanking a Giant. In this situation, all three Allies attack with advantage due to flanking, because "Am I adjacent to an enemy and is there an ally adjacent on the opposite of the creature" is true for all three.
A A
G G
G G
A
On the other hand, in this situation, that doesn't work.
A
G G A
G G
A
While the top and bottom attacker have advantage due to flanking, the one on the right does not.
A:
Only the A's are flanking.
When a creature and at least one of its allies are adjacent to an enemy and on opposite sides or corners of the enemy's space, they flank that enemy, and each of them has advantage on melee attack rolls against that enemy. - (DMG p. 251)
By the grammar of the sentence "each of them" refers to the two allies which are flanking. There is no reference to any additional allies in the entire passage, nor is it written in a way which would imply that while being flanked, the creature has taken on a conditional status.
It is specifically the 'flankers' who gain a conditional status and
subsequently now have an advantage bonus, if-and-only-if: they are
uniquely positioned to flank (by being on opposite sides).
Furthermore, this interpretation is backed up by previous editions of
D&D.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding main title to Bullet Graph
Can you suggest a way to add a main title to that graph? The gridBulletGraphV function can be found here.
ytd2005 <- data.frame(
measure=c("Revenue", "Profit", "Avg Order Size", "New Customers", "Cust Satisfaction"),
units=c("U.S. $ (1,000s)", "%", "U.S. $", "Count", "Top Rating of 5"),
low=c(150, 20, 350, 1400, 3.5),
mean=c(225, 25, 500, 2000, 4.25),
high=c(300, 30, 600, 2500, 5),
target=c(250, 26, 550, 2100, 4.2),
value=c(275, 22.5, 310, 1700, 4.5)
)
nticks <- c(7, 7, 7, 6, 7)
format <- c("s", "p", "s", "k", "s")
col1 <- c("#a5a7a9", "#c5c6c8", "#e6e6e7")
gridBulletGraphV(ytd2005, nticks=nticks, format=format, bcol=col1, font=11, scfont=9)
A:
You can do that by changing the function. I added a ptitle="text" parameter to the function and added the following code just before for (i in 1:n) {:
# Title
vp <- viewport(layout.pos.row = 1)
pushViewport(vp)
grid.text(label = ptitle,
just = "centre",
gp = gpar(fontsize=font*1.5, col="black", fontface="bold"),
x = .5,
y = 0.1)
upViewport()
You can now call the function with:
gridBulletGraphV(ytd2005, nticks=nticks, format=format, bcol=col1, font=11,
scfont=9, ptitle="Plot Title")
which gives the following result:
The revised gridBulletGraphV function:
gridBulletGraphV <- function(bgData, nticks=3, format="s", bcol=c("red", "yellow", "green"), tcol="black", vcol="black", font=25, scfont=15, ptitle="text") {
# Data Prep
n <- nrow(bgData)
nam <- c("low", "mean", "high", "target", "value")
datMat <- as.matrix(bgData[, nam])
# Nticks/Format Prep
if (length(nticks) == 1) {
nticks <- rep(nticks, n)
}
if (length(format) == 1) {
format <- rep(format, n)
}
# Layout
hl <- rep(1, n + 2)
hu <- c("lines", rep("null", n), "lines")
layout <- grid.layout(4, n + 2, widths = unit(hl, hu),
heights = unit(c(1, 1, 5, 2), c("lines", "null", "null", "lines")))
# Set Layout
grid.newpage()
pushViewport(plotViewport(c(0, 0, 0, 0), layout = layout))
# Title
vp <- viewport(layout.pos.row = 1)
pushViewport(vp)
grid.text(label = ptitle,
just = "centre",
gp = gpar(fontsize=font*1.5, col="black", fontface="bold"),
x = .5,
y = 0.1)
upViewport()
for (i in 1:n) {
#
vp <- viewport(layout.pos.row = 3,
layout.pos.col = i+1)
pushViewport(vp)
# Sublayout
subLayout <- grid.layout(nrow = 1,
widths = unit(c(1, 2, 1), c("null", "null", "null")),
ncol = 3)
pushViewport(plotViewport(c(0, 0, 0, 0), layout=subLayout))
vp <- viewport(layout.pos.row = 1,
layout.pos.col = 2,
yscale = c(0, datMat[i, 3]))
pushViewport(vp)
# x-Axis Labels
# Formatierung Label
if (format[i] == "s") {
brks <- labels <- round(seq(0, datMat[i, 3], length=nticks[i]), 0)
} else if (format[i] == "p"){
brks <- labels <- round(seq(0, datMat[i, 3], length=nticks[i]), 0)
labels <- paste0(labels, "%")
} else if (format[i] == "k") {
brks <- labels <- round(seq(0, datMat[i, 3], length=nticks[i]), 0)
labels <- format(labels, digits=10, nsmall=0, decimal.mark=".", big.mark=",")
}
grid.yaxis(at=brks, label=labels, gp=gpar(fontsize=scfont, col="black", fontface="bold"))
grid.rect(y = c(0, datMat[i, 1:2]) / datMat[i, 3],
height = unit(diff(c(0, datMat[i, 1:3])), "native"),
x = rep(0.5, 3),
width = 1,
just = "bottom",
gp = gpar(fill=bcol, col=bcol))
grid.rect(y = c(0, datMat[i, 5]),
height = unit(diff(c(0, datMat[i, 5])), "native"),
x = 0.5,
width = 0.5,
gp = gpar(fill=vcol, col=vcol), just="bottom")
a <- datMat[i, 1] * 0.01
grid.rect(y = datMat[i, 4] / datMat[i, 3],
height = unit(a, "native"),
x = 0.5,
width = 0.8,
gp = gpar(fill=tcol, col=tcol), just="bottom")
upViewport(n=3)
# Annotation
pushViewport(plotViewport(c(0, 0, 0, 0), layout=layout))
vp <- viewport(layout.pos.row = 2,
layout.pos.col = i+1)
pushViewport(vp)
# Sublayout 1: Same layout as graph
subLayout <- grid.layout(nrow = 1,
ncol = 3,
widths = unit(c(1, 2, 1), c("null", "null", "null")))
pushViewport(plotViewport(c(0, 0, 0, 0), layout=subLayout))
vp <- viewport(layout.pos.row = 1,
layout.pos.col = 2)
pushViewport(vp)
# Sublayout 2: two rows of text; centred middle of graph
subLayout <- grid.layout(nrow = 3,
ncol = 1,
widths = unit(c(1, 1), c("null", "null")))
pushViewport(plotViewport(c(0, 0, 0, 0), layout=subLayout))
# First Text: Measure
vp <- viewport(layout.pos.row = 2,
layout.pos.col = 1)
pushViewport(vp)
grid.text(label = bgData$measure[i],
just = "bottom",
gp = gpar(fontsize=font, col="black", fontface="bold"),
x = .5,
y = 0.1)
upViewport()
# Second Text: Unit
vp <- viewport(layout.pos.row = 3,
layout.pos.col = 1)
pushViewport(vp)
grid.text(label = bgData$units[i],
just = "bottom",
gp = gpar(fontsize=font, col="black"),
x = .5,
y = .5)
upViewport(n=5)
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
dynamic router in express
I have several types of projects, each project handles a different code.
I want to make a route handler for every project.
For example
router.use('/projects/dog_name', dog)
router.use('/projects/cat_name', cat)
The project name is dynamic and comes from retrieving data from the database and is updated from time to time.
What can I do?
A:
If it's going to be code that decides how to treat the router, then you probably want one generic route that can then use code logic to distribute the handling of the route dynamically based on some sort of dynamic lookup:
let dynamicRoutes = new Map([["golden", dog], ["persian", cat]]);
router.use("/projects/:name", (req, res, next) => {
let target = dynamicRoutes.get(req.params.name);
if (target) {
target(req, res, next);
} else {
next();
}
});
Then, you can add/remove items from the dynamicRoutes data structure to add/remove new dynamic routes at any time. If you have logic involving a database lookup, you can use that instead of the map.get(). Or, maybe for performance reasons, you don't query the database on every route hit, but rather query the database when something changes and update the dynamicRoutes data structure (like a cache) whenever you know something has changed in the database.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Firebase SimpleLogin in a non android Java environment
I have server written in Java, the server is writing to my firebase and I would like to add authentication to ensure that it is only my server that can perform these updates.
I have included the firebase-simple-login-LATEST.jar in my class path and altered by code to attempt to authenticate based on a user/password combination see below
Firebase fb = new Firebase("https://myfirebase.firebaseio.com");
SimpleLogin sl = new SimpleLogin(fb);
sl.loginWithEmail("[email protected]", "password", new SimpleLoginAuthenticatedHandler() {
@Override
public void authenticated(Error error, User user) {
if (error == null) {
// Do some work here
}
}
});
My problem is that even though my server is pure java and not running any aspects of android, I get run time errors complaining that
java.lang.ClassNotFoundException: android.net.Uri
I presume there is some internal dependency in the simple login java code. I am wondering if there is a pure Java (with no android dependency) jar file that I can use as I do not really want to have to include a load of android jars in my build
A:
The simple login jar depends on the Android runtime, but if you just want to authenticate a server, you can do one of two things:
Use your Firebase secret as the auth credential
Generate a specific admin token for your server
See the documentation here: https://www.firebase.com/docs/security/custom-login.html
Helper libraries are available in several languages for generating your own token.
| {
"pile_set_name": "StackExchange"
} |
Q:
How would I design a client-side Queue system?
OVERVIEW
I'm working on a project and I've come across a bit of a problem in that things aren't happening in the order I want them to happen. So I have been thinking about designing some kind of Queue that I can use to organize function calls and other miscellaneous JavaScript/jQuery instructions used during start-up, i.e., while the page is loading. What I'm looking for doesn't necessarily need to be a Queue data structure but some system that will ensure that things execute in the order I specify and only when the previous task has been completed can the new task begin.
I've briefly looked at the jQuery Queue and the AjaxQueue but I really have no idea how they work yet so I'm not sure if that is the approach I want to take... but I'll keep reading more about these tools.
SPECIFICS
Currently, I have set things up so that some work happens inside $(document).ready(function() {...}); and other work happens inside $(window).load(function() {...});. For example,
<head>
<script type="text/javascript">
// I want this to happen 1st
$().LoadJavaScript();
// ... do some basic configuration for the stuff that needs to happen later...
// I want this to happen 2nd
$(document).ready(function() {
// ... do some work that depends on the previous work do have been completed
var script = document.createElement("script");
// ... do some more work...
});
// I want this to happen 3rd
$(window).load(function() {
// ... do some work that depends on the previous work do have been completed
$().InitializeSymbols();
$().InitializeBlock();
// ... other work ... etc...
});
</script>
</head>
... and this is really tedious and ugly, not to mention bad design. So instead of dealing with that mess, I want to design a pretty versatile system so that I can, for example, enqueue $().LoadJavaScript();, then var script = document.createElement("script");, then $().InitializeSymbols();, then $().InitializeBlock();, etc... and then the Queue would execute the function calls and instructions such that after one instruction is finished executing, the other can start, until the Queue is empty instead of me calling dequeue repeatedly.
The reasoning behind this is that some work needs to happen, like configuration and initialization, before other work can begin because of the dependency on the configuration and initialization steps to have completed. If this doesn't sound like a good solution, please let me know :)
SOME BASIC WORK
I've written some code for a basic Queue, which can be found here, but I'm looking to expand its functionality so that I can store various types of "Objects", such as individual JavaScript/jQuery instructions and function calls, essentially pieces of code that I want to execute.
UPDATE
With the current Queue that I've implemented, it looks like I can store functions and execute them later, for example:
// a JS file...
$.fn.LoadJavaScript = function() {
$.getScript("js/Symbols/Symbol.js");
$.getScript("js/Structures/Structure.js");
};
// another JS file...
function init() { // symbols and structures };
// index.html
var theQueue = new Queue();
theQueue.enqueue($().LoadJavaScript);
theQueue.enqueue(init);
var LJS = theQueue.dequeue();
var INIT = theQueue.dequeue();
LJS();
INIT();
I also think I've figured out how to store individual instructions, such as $('#equation').html(""); or perhaps even if-else statements or loops, by wrapping them as such:
theQueue.enqueue(function() { $('#equation').html(""); // other instructions, etc... });
But this approach would require me to wait until the Queue is done with its work before I can continue doing my work. This seems like an incorrect design. Is there a more clever approach to this? Also, how can I know that a certain function has completed executing so that the Queue can know to move on? Is there some kind of return value that I can wait for or a callback function that I can specify to each task in the Queue?
WRAP-UP
Since I'm doing everything client-side and I can't have the Queue do its own thing independently (according to an answer below), is there a more clever solution than me just waiting for the Queue to finish its work?
Since this is more of a design question than a specific code question, I'm looking for suggestions on an approach to solving my problem, advice on how I should design this system, but I definitely welcome, and would love to see, code to back up the suggestions :) I also welcome any criticism regarding the Queue.js file I've linked to above and/or my description of my problem and the approach I'm planning to take to resolve it.
Thanks, Hristo
A:
I would suggest using http://headjs.com/ It allows you to load js files in parallel, but execute them sequentially, essentially the same thing you want to do. It's pretty small, and you could always use it for inspiration.
I would also mention that handlers that rely on execution order are not good design. I am always able to place all my bootstrap code in the ready event handler. There are cases where you'd need to use the load handler if you need access to images, but it hasn't been very often for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
Illegal scheme supplied, only alphanumeric characters are permitted
Every time I access admin panel I get this error message.
I encountered this problem after I change base_url in core_config_data to http://magento.local/magento/, the previous is http://localhosts/magento/. Anyway I changed it back but the problem still be exist.
Note: Also add "127.0.0.1 magento.local" in host file
Here is a full trace
a:5:{i:0;s:67:"Illegal scheme supplied, only alphanumeric characters are permitted";i:1;s:2782:"#0 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Model\Store.php(773): Zend_Uri::factory(' `http://localho...`')
1 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Model\Store.php(607): Mage_Core_Model_Store->isCurrentlySecure()
2 C:\xampp\htdocs\Magento\app\Mage.php(382): Mage_Core_Model_Store->getBaseUrl('skin', NULL)
3 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Model\Design\Package.php(349): Mage::getBaseUrl('skin', NULL)
4 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Model\Design\Package.php(503): Mage_Core_Model_Design_Package->getSkinBaseUrl(Array)
5 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Block\Abstract.php(1035): Mage_Core_Model_Design_Package->getSkinUrl('reset.css', Array)
6 C:\xampp\htdocs\Magento\app\design\adminhtml\default\default\template\login.phtml(32): Mage_Core_Block_Abstract->getSkinUrl('reset.css')
7 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Block\Template.php(241): include('C:\xampp\htdocs...')
8 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Block\Template.php(272): Mage_Core_Block_Template->fetchView('adminhtml\defau...')
9 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Block\Template.php(286): Mage_Core_Block_Template->renderView()
10 C:\xampp\htdocs\Magento\app\code\core\Mage\Adminhtml\Block\Template.php(81): Mage_Core_Block_Template->_toHtml()
11 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Block\Abstract.php(919): Mage_Adminhtml_Block_Template->_toHtml()
12 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Block\Text\List.php(43): Mage_Core_Block_Abstract->toHtml()
13 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Block\Abstract.php(919): Mage_Core_Block_Text_List->_toHtml()
14 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Model\Layout.php(555): Mage_Core_Block_Abstract->toHtml()
15 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Controller\Varien\Action.php(390): Mage_Core_Model_Layout->getOutput()
16 C:\xampp\htdocs\Magento\app\code\core\Mage\Adminhtml\controllers\IndexController.php(82): Mage_Core_Controller_Varien_Action->renderLayout()
17 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Controller\Varien\Action.php(418): Mage_Adminhtml_IndexController->loginAction()
18 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Controller\Varien\Router\Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('login')
19 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Controller\Varien\Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
20 C:\xampp\htdocs\Magento\app\code\core\Mage\Core\Model\App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
21 C:\xampp\htdocs\Magento\app\Mage.php(684): Mage_Core_Model_App->run(Array)
22 C:\xampp\htdocs\Magento\index.php(87): Mage::run('', 'store')
23 {main}";s:3:"url";s:25:"/magento/index.php/admin/";s:11:"script_name";s:18:"/magento/index.php";s:4:"skin";s:5:"admin";}
A:
Make sure the base_url is a valid URI Schema, so it should be http://magento.local/magento/.
Afterwards clear your cache and the issue should be solved.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails - how to restrict user from entering more than one record per association
I am new to rails and have not been able to find something for this.
In my app, I have Products, Reviews, & Users.
Reviews belongs_to users & products while both users and products "has_many" reviews.
However, I want to restrict users from entering multiple reviews per product (each product is unique). So if a user creates a review for a product and tries to write another review for the same product, they'd be told they are not allowed to but can edit their existing review.
My question is: Should I do this at the controller level, or is possible to do it with a validation (which seems like a simpler solution)? Just not sure how to approach it.
A:
You can easily do this with a model validation, and an index would help as well. Warning though, if you do the unique index without the accompanying ActiveRecord validation your saves will fail silently and cause a usability/debugging headache.
This should do it:
class Review < ActiveRecord::Base
validates :user_id, :uniqueness => { :scope => :product_id,
:message => "Users may only write one review per product." }
end
If you want to add the index, try this in a migration:
class AddUniquenessConstraintToReviews < ActiveRecord::Migration
add_index :review, [:user_id, :product_id],
:name => "udx_reviews_on_user_and_product", :unique => true
end
Edit: As a full-time Rails dev I still refer to the ActiveRecord docs for refreshers on the syntax of these things pretty regularly. You should too!
| {
"pile_set_name": "StackExchange"
} |
Q:
List item marker and list item text are not aligning
I am getting the following result in my web browser:
The checkmarks appear slightly raised with respect to the text, but I would like the text to be all lined up. What should I do?
I have the following HTML:
<ul class="train">
<li>
<p><?php echo $pageContents->getContents("comptrainLI1"); ?></p>
<ul class="traininner">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>jQuery</li>
<li>PHP</li>
<li>SQL</li>
<li>WordPress CMS</li>
<li>Magento CMS</li>
</ul>
</li>
<li>
<p><?php echo $pageContents->getContents("comptrainLI2"); ?></p>
<ul class="traininner">
<li>C</li>
<li>C++</li>
<li>C#</li>
<li>Java</li>
</ul>
</li>
</ul>
and CSS:
div#mainContent ul.train {
list-style-position: inside;
list-style-image: url("../images/checkmark-round-whiteOnGreen.jpg");
font-size: 18pt;
}
div#mainContent ul.train ul.traininner {
padding-left: 20px;
list-style-image: url("../images/checkmark-round-whiteOnGreen.jpg");
}
A:
I don't think it's possible to know the reason for the misalignment based on the limited code you posted in your question. It could be something in your PHP. So I've posted a general solution.
li {
list-style-type: none;
margin-bottom: 5px;
}
ul.traininner li::before {
content: '';
display: inline-block;
vertical-align: bottom;
padding: 10px 20px 0 0;
height: 10px;
width: 10px;
background-image: url("http://i.imgur.com/F05JSPD.png");
background-repeat: no-repeat;
}
<ul class="train">
<li>
<ul class="traininner">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>jQuery</li>
<li>PHP</li>
<li>SQL</li>
<li>WordPress CMS</li>
<li>Magento CMS</li>
</ul>
</li>
<li>
<ul class="traininner">
<li>C</li>
<li>C++</li>
<li>C#</li>
<li>Java</li>
</ul>
</li>
</ul>
jsFiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Google's Platform.js Plugin
My website seemed slow. For that reason, I decided to dive in and look at ways to improve performance. On the server-side, everything looks good. But on the client-side, there's a lot of JavaScript that's slowing things down. When I looked at the load stack, I noticed two culprits.
The two worst offenders were https://apis.google.com/js/platform.js and https://www.google-analytics.com/analytics.js. I use the former for +1 buttons and the latter for analytical purposes. As of right now, I'm loading them like this:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '[MyId]', 'auto');
ga('send', 'pageview');
</script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
I was under the impression that platform.js included Google Plus and Google Analytics. So, I thought I could condense down to a single external JS library using something like this:
(function(w,d,s,g,js,fs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js,fs);
js.onload=function(){
g.load('analytics');
};
}(window,document,'script'));
This at least loads the Google Plus plugin. However, it doesn't actually log visits any more. It looks like g.load brings in Analytics. But, my ID isn't being assigned anywhere. At the same time, I do not see where to assign it in the platform.js version.
Can anyone provide any insights? I would love to be able to load one less external resource if possible.
Thank you.
A:
I was under the impression that platform.js included Google Plus and Google Analytics.
No, this is not true. platform.js allows you to load the Google Analytics API client libraries (which are used to programmatically report on your GA data), but that is different from analytics.js (which is used to send tracking data to GA).
Based on the code you've shown, both of these libraries are being loaded asynchonrously, so they should not interfere with the load time of your site. They may slow down when the window.load event fires, but that doesn't really mean your site is loading slower, since it shouldn't affect the loading of your application-critical resources.
If you really want to load these libraries without affecting any load metrics at all, you can postpone loading them until after the window.load event fires, but honestly I'd only do that if you have other code that is waiting until window.load fires to initialize.
A:
It's hard to understand why these 2 libraries slow down the page, they usually work with async technologies (and the)
The Platform weighs less than 20 Kbs, and usually this library is hosted in a CDN, so maybe you host is not so fat then the European (the tested one), but I can discard this option because American and Latam Server are quite good too.
I've read the platform.js and has no common point with the analytics.js, why you think that it's included?. Maybe Google Analytics is included on an Iframe or other resources which is confusing you, but if you don't use the command correctly ga('create'), no information will be sent to your account. Maybe you still got the library but the information is being sent to another account (this happens a lot when some iframes are embedded, they includes Google Analytics but in a different domain, and the data is sent to 2 different accounts, this can be difficult to understand at the beginning).
But, remain your main doubt, if I understand it.
You want to keep a single library for both, I think that it's not possible to do. I checked the platform.js and has no reference to the Ga object (the one used on Google Analytics) or even to the collect URL (where you send the information to Google Analytics). The GA main Snippet also does some extra things, likes keep the date of the execution to be used used later.
What I can recommend to you?
Review the number of hits, with the network console, the Google analytics hits are sent to http://www.google-analytics.com, via HTTP forcing an HTTPS call if you are not using SSL(you have twice all the hit, but analytics will only use the secured one). Or use Tag Assistant to see this. Check that your implementation is still alive.
Maybe you can check Google Tag Manager, this tool can be configured to load the library on the DOM on in the PageView (HTML.load), I don't recommend you this practices, you'll reduce the number of hits sent to the tool (and get fewer Sessions).
Move the code to the bottom of the page. This is not a good idea due to the same reason before.
this, but it's still not correct to do it, you only delay the load of the library
$( document ).ready(function() {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '[MyId]', 'auto');
ga('send', 'pageview');
});
All of this keeping both code separately
I highly recommend you check if these 2 libraries are the real reason.
| {
"pile_set_name": "StackExchange"
} |
Q:
How To Create Topic in FCM Notifications
I'm trying Firebase-Notification API the service is worked perfect when i send downstream message from console to app, but how to send message to topic registered users ?
i did in android side
FirebaseMessaging.getInstance().subscribeToTopic("TopicName");
but when i try send downstream message from console to topic it's says
This project does not have any topics
EDIT :
i figured out that after mapping the topic it's take up to 1 day to show up in Firebase Console
A:
This is an alternate path.
If you subscribe a client app to an unexisting topic then the topic will also be created without having to call any firebase url request.
It' will also take a couple of hours to appear on Firebase Console.
By using google shared example: https://github.com/firebase/quickstart-android/tree/master/messaging you can confirm the same.
FirebaseMessaging.getInstance().subscribeToTopic("news");
Log.d(TAG, "Subscribed to news topic");
A:
First, given that IID_TOKEN is your registration token and TOPIC_NAME is the topic you want to create, you need to create topic by making a POST request to
https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME
And to check your created Topics make a GET request on this URL
https://iid.googleapis.com/iid/info/nKctODamlM4:CKrh_PC8kIb7O...clJONHoA?details=true
and insert your API_KEY in your Request HEADERS
Authorization: key=YOUR_API_KEY
Your topic will take up to 1 day to show up in Firebase console so for testing you can make curl request or use sofware like Advanced REST client
A:
Firebase takes time to create new topic in console. In my case, new topic was created after 4 hours.
| {
"pile_set_name": "StackExchange"
} |
Q:
For loop with array not printing the proper result
New on js , code is below. Here i am unable print the proper result. I think there is something wrong with + "names[i]" this portion of code.
var names = ["aha","mk", "jk","hk","fhf"];
for (i=1;i<=names.length;i++){
console.log("I know someone called "+ "names[i]");
}
A:
Omit the quotes around names[i].
It should be:
var names = ["aha","mk", "jk","hk","fhf"];
for (i=1;i<=names.length;i++){
console.log("I know someone called "+ names[i]);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
FloatActionButton is not hiding when scrolling
I'm tryng to hide my FAB when scroll down in my Activity but is not working. Why??? Inside the fragment tag has fragments with RecyclerView.
Here's my Activity xml code:
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.principal.PrincipalActivity">
<fragment
android:id="@+id/PrincipalActivity_navHostFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/principal_nav_graph" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/PrincipalActivity_bottom_navigation"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/colorPrimary"
app:itemIconTint="@drawable/bottom_navigation_colors"
app:itemTextColor="@android:color/white"
app:layout_anchor="@id/PrincipalActivity_navHostFragment"
app:layout_anchorGravity="bottom"
app:menu="@menu/bottom_navigation_menu_principal" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/PrincipalActivity_fabItensPedido"
style="@style/Widget.MaterialComponents.FloatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="70dp"
android:src="@drawable/ic_carrinho"
app:backgroundTint="@color/colorAccent"
app:fabSize="auto"
app:layout_anchor="@id/PrincipalActivity_navHostFragment"
app:layout_anchorGravity="bottom|end"
app:layout_behavior=".utils.ScrollAnimationFAB" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
This is the Layout Behavior that i'm using using in the FAB Button, but is not working in the activity, only in the fragments inside the fragment tag.
class ScrollAnimationFAB extends CoordinatorLayout.Behavior<FloatingActionButton> {
public ScrollAnimationFAB(){
super();
}
public ScrollAnimationFAB(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull FloatingActionButton child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) {
return axes == ViewCompat.SCROLL_AXIS_VERTICAL ||
super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target,
axes, ViewCompat.TYPE_TOUCH);
}
@Override
public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull FloatingActionButton child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type, @NonNull int[] consumed) {
Log.v("Msg", "dyConsumed: " + dyConsumed + ", dyUnConsumed: " + dyUnconsumed);
if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
child.hide(new FloatingActionButton.OnVisibilityChangedListener() {
@Override
public void onHidden(FloatingActionButton fab) {
super.onHidden(fab);
fab.setVisibility(View.INVISIBLE);
}
});
} else if (dyConsumed < 0 && dyUnconsumed == 0 && child.getVisibility() != View.VISIBLE) {
child.show();
}
}
}
Please help me.
A:
I solve the ploblem this way:
recyclerView =
rootView.findViewById<RecyclerView>(R.id.recyclerView).apply {
this.setHasFixedSize(true)
this.layoutManager = LinearLayoutManager(activity?.baseContext)
this.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (dy > 0)
activity_fab.hide()
else
activity_fab.show()
}
})
}
The FAB view is inside my activity. But this code above is inside the fragment. I call the FAB in my fragment this way: (activity as AppCompatActivity).findViewById(R.id.activity_fab).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to disconnect AVPlayer from AVPlayerItem?
I want to reuse an AVPlayerItem but keep getting this error:
An AVPlayerItem cannot be associated with more than one instance of AVPlayer
Before trying to reuse it, I destroy the previous AVPlayer like this:
[self.player pause];
[self.player replaceCurrentItemWithPlayerItem:nil];
self.player = nil;
why is the AVPlayerItem still associated and how can I disconnect it?
Here is a Gist with a full reproduction of the problem (only 50 lines btw): https://gist.github.com/sbiermanlytle/14a6faab515f7691b810789086ae9e50
You can run it by creating a new Single View app, and supplanting the ViewController implementation with that code.
A:
You can't disconnect AVPlayerItems. I guess the private property that points to the player is not weak, so dereferencing the item by setting current player item to NULL does not automatically set the item's player property to NULL..
Simply create a new one. Either with the URL, in which case the cache system will return an AVAsset instantly ( Just another guess... ), or, better, with the asset of the PlayerItem you want to 'disconnect'.
AVPlayerItem* newPlayerItem = [AVPlayerItem playerItemWithAsset:playerItem.asset];
There is no performance loss doing this. The item is just a 'handle' to the asset, which contains the data for real. So don't be afraid to trash and create new items on the fly.
| {
"pile_set_name": "StackExchange"
} |
Q:
writing a single servlet to add/edit/delete an Item and also to list items
I need to create a single Servlet to handle listing of some Items, adding new items, editing existing items and also deletion of items.
I wrote JSP pages for edit an item and showing a list of items. In itemslisting.jsp, I have put delete and edit links for each item but I am not very sure about how to construct the methods in Servlet.
itemslisting.jsp
...
<table>
<c:forEach var="item" items="${items}" varStatus="listCount">
<tr><td>${listCount.count} </td>
<c:url value="edititem" var="edititemurl">
<c:param name="itemId" value="${item.item_id}" />
</c:url>
<td><a href="${edititemurl }" >${item.name}</a></td>
<c:url value="deleteitem" var="deleteitemurl">
<c:param name="itemId" value="${item.item_id}" />
</c:url>
<td><a href="${deleteitemurl}" >DELETE</a></td>
</tr>
</c:forEach>
</table>
...
<a href="<c:url value="addItem"/>">add new item </a>
...
In our training we were asked to create separate servlets to add, edit, list and delete Items. In those cases mapping can be done for each of these urls to the appropriate servlet but it feels silly to create that many servlets. How do I configure the different urls in the above jsp to a single ItemServlet? Do I have to pass some extra parameter to indicate the operation, say like edititem along with the edititemurl?
I tried to create a skeleton of the doGet() method:
public void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
String additemop = req.getParameter("additemoperation");
String edititem = req.getParameter("additemoperation");
String itemId = req.getParameter("itemId");
...
if(additemop!=null){
showAddItemPage(req,resp);
}
else if((edititemop!=null) && (itemId != null)){
showEditItemPage(req,resp);
}
else{
showListItemsPage(req,resp);
}
}
I don't know if this is the way to do this, please correct me if I am wrong.
A:
You can pass a parameter with your url, like:
myapp/item?action=get
Using separate urls for these is easier and less error-prone, though. That is likely why you were taught that way in the first place.
You need to be careful what you do with HTTP GET and what you do with POST. Using GET like you do in your example (to add an item) is bad, you don't want to do anything that modifies data with GET. Especially don't make deletion a GET, or the first webcrawler that comes along can wipe out your database. :-O Also check out something called Post-Redirect-Get, it is a common pattern for avoiding duplicate form submissions and making your pages bookmarkable.
I recommend checking out a rapid-development framework, like Play. The raw jsp/servlet stuff here is just too tedious to grind out. You have already been through the hard way once, so you won't be missing out on anything.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rotate the vertexes of a cube using a rotation matrix
I'm trying to rotate a cube's vertexes with a rotation matrix but whenever I run the program the cube just disappears.
I'm using a rotation matrix that was given to us in a lecture that rotates the cube's x coordinates.
double moveCubeX = 0;
float xRotationMatrix[9] = {1, 0, 0,
0, cos(moveCubeX), sin(moveCubeX),
0, -sin(moveCubeX), cos(moveCubeX)
};
I'm adding to the moveCubeX variable with the 't' key on my keyboard
case 't':
moveCubeX += 5;
break;
And to do the matrix multiplication I'm using
glMultMatrixf();
However when I add this into my code when running it the cube has just disappeared. This is where I add in the glMultMatrixf() function.
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(pan, 0, -g_fViewDistance,
pan, 0, -1,
0, 1, 0);
glRotatef(rotate_x, 1.0f, 0.0f, 0.0f); //Rotate the camera
glRotatef(rotate_y, 0.0f, 1.0f, 0.0f); //Rotate the camera
glMultMatrixf(xRotationMatrix);
I'm struggling to see where it is I have gone wrong.
A:
OpenGL uses matrices of size 4x4. Therefore, your rotation matrix needs to be expanded to 4 rows and 4 columns, for a total of 16 elements:
float xRotationMatrix[16] = {1.0f, 0.0f, 0.0f, 0.0f,
0.0f, cos(moveCubeX), sin(moveCubeX), 0.0f,
0.0f, -sin(moveCubeX), cos(moveCubeX), 0.0f,
0.0f, 0.0f, 0.0f, 1.0f};
You will also need to be careful about the units for your angles. Since you add 5 to your angle every time the user presses a key, it looks like you're thinking in degrees. The standard cos() and sin() functions in C/C++ libraries expect the angle to be in radians.
In addition, it looks like your matrix is defined at a global level. If you do this, the elements will only be evaluated once at program startup. You will either have to make the matrix definition local to the display(), so that the matrix is re-evaluated each time you draw, or update the matrix every time the angle changes.
For the second option, you can update only the matrix elements that depend on the angle every time the angle changes. In the function that modifies moveCubeX, add:
xRotationMatrix[5] = cos(moveCubeX);
xRotationMatrix[6] = sin(moveCubeX);
xRotationMatrix[9] = -sin(moveCubeX);
xRotationMatrix[10] = cos(moveCubeX);
| {
"pile_set_name": "StackExchange"
} |
Q:
Spark: Is "count" on Grouped Data a Transformation or an Action?
I know that count called on an RDD or a DataFrame is an action. But while fiddling with the spark shell, I observed the following
scala> val empDF = Seq((1,"James Gordon", 30, "Homicide"),(2,"Harvey Bullock", 35, "Homicide"),(3,"Kristen Kringle", 28, "Records"),(4,"Edward Nygma", 30, "Forensics"),(5,"Leslie Thompkins", 31, "Forensics")).toDF("id", "name", "age", "department")
empDF: org.apache.spark.sql.DataFrame = [id: int, name: string, age: int, department: string]
scala> empDF.show
+---+----------------+---+----------+
| id| name|age|department|
+---+----------------+---+----------+
| 1| James Gordon| 30| Homicide|
| 2| Harvey Bullock| 35| Homicide|
| 3| Kristen Kringle| 28| Records|
| 4| Edward Nygma| 30| Forensics|
| 5|Leslie Thompkins| 31| Forensics|
+---+----------------+---+----------+
scala> empDF.groupBy("department").count //count returned a DataFrame
res1: org.apache.spark.sql.DataFrame = [department: string, count: bigint]
scala> res1.show
+----------+-----+
|department|count|
+----------+-----+
| Homicide| 2|
| Records| 1|
| Forensics| 2|
+----------+-----+
When I called count on GroupedData (empDF.groupBy("department")), I got another DataFrame as the result (res1). This leads me to believe that count in this case was a transformation. It is further supported by the fact that no computations were triggered when I called count, instead, they started when I ran res1.show.
I haven't been able to find any documentation that suggests count could be a transformation as well. Could someone please shed some light on this?
A:
The .count() what you have used in your code is over RelationalGroupedDataset, which creates a new column with count of elements in the grouped dataset. This is a transformation. Refer:
https://spark.apache.org/docs/1.6.0/api/scala/index.html#org.apache.spark.sql.GroupedDataset
The .count() that you use normally over RDD/DataFrame/Dataset is completely different from the above and this .count() is an Action. Refer: https://spark.apache.org/docs/1.6.0/api/scala/index.html#org.apache.spark.rdd.RDD
EDIT:
always use .count() with .agg() while operating on groupedDataSet in order to avoid confusion in future:
empDF.groupBy($"department").agg(count($"department") as "countDepartment").show
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot create database in Visual Studio
I have an application on Visual Studio 2010, Visual c#. I have created a database for the application and it used to ran just fine. But today when I ran my application, the database wasn't working. I deleted the .mdf file and tried to create a new one, but a get this error
A network-related or instance-specific error occurred while establishing a
connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured
to allow remote connection.(provider:SQL Network Interfaces, error: 26 - Error
Locating Server/Instance Specified)
I don't know what to do in order to be able to create a database again, since I don't know that happened in the first place to disable it.
A:
A few things I can think of...
Is SQL Server installed/up and running?
Do you already have a non-user instance database named the same thing in SQL Server?
Is your connection string set up properly?
| {
"pile_set_name": "StackExchange"
} |
Q:
flotgraph using functions for conditional radius
I have a dataset where each node contains a date and a value.
I don't want flot to draw a circular point at ever value, especially if the value is zero
so in my graph's options I have:
points: {
show: true,
radius: 3
},
but how do I have `radius: function (x) { return x.value>0?3:0 };
is this possible in flot, if so what is the syntax?
A:
Flot expects radius to be a number. The simplest way to achieve this would be to create two series with the same color. The first contains all the datapoints and points: { show: false } and the second contains only those datapoints where y > 0 and lines: { show: false }.
| {
"pile_set_name": "StackExchange"
} |
Q:
Compilation error when passing Integer into generic method with Function>
I have some code with 3 overriding methods that perform the same operation ( code is identically for each method) on the Inputs, the only difference between them is the input parameter type
private List<String> extractDoubleValues(Function<MyClass, List<Double>> extractions)
private List<String> extractLongValues(Function<MyClass List<Long>> extractions)
private List<String> extractIntegerValues(Function<MyClass, List<Integer>> extractions)
I was trying to attempt to replace these 3 methods with a single method that makes us of generic wildcards as follows
private List<String> extractNumberValues(Function<MyClass, List<? extends Number>> extractions)
When I attempt to use the above generic method in place of one of the 3 type specific methods
Function<MyClass, List<Integer>> intExtractions;
List<String> extractedValues = extractNumberValues(intExtractions);
I get a the following compilation error on the second line of code above
Error:(59, 80) java: incompatible types: java.util.function.Function<MyClass,java.util.List<java.lang.Double>> cannot be converted to java.util.function.Function<MyClass,java.util.List<? extends java.lang.Number>>
I've successfully replaced duplicate methods with the wildcard before, as bellow
List<String> convertNumberListToStringList(List<Integer> numberList)
List<String> convertNumberListToStringList(List<Double> numberList)
with
List<String> convertNumberListToStringList(List<? extends Number> numberList)
I'm new to the idea of generics so I was curious as why the above would fail to compile? I do not quite understand why it would fail to compile
A:
Major problem(or i should say feature?) here is generic are used only during compilation. During runtime you do not have any information about generic. In other words you have to consider List<Integer> and List<Double> and completelly different types. If you see inside Fucntion class you will see <T, R> without wildcard. So even Function use List<Integer> and List<Double> as completelly different types. If y ou want to say to Function that R will be something of List type, you have to code it like:
Function<SomeClass, ? extends List<? extends SomeOtherClass>>
By code above you are telling that R will be List for sure and list will contain instances of SomeOtherClass.
Main point during work with generic is that generic changes original class to some other class...
| {
"pile_set_name": "StackExchange"
} |
Q:
Auto Encapsulate Field Refactoring, Difference between 'Use field' and 'Use Property'?
On Visual Studio 2017, I have two options when using the Auto Encapsulate Field Refactoring Tool:
Use Property
Still use field
I have tested the different option on a basic class:
public class Test_EncapsulateFieldRefactoring_Property
{
public int id;
public string name;
}
But both option gave the same result:
public class Test_EncapsulateFieldRefactoring_Property
{
private int id;
private string name;
public int Id { get => id; set => id = value; }
public string Name { get => name; set => name = value; }
}
Why do those options exist? Where is the difference (in code generated , "useage"*)?
Disclamer:
The screenshot is a on French VS. So option translations are made by me, real option text may differ.
I know the difference between field and property. I have checked a lot of topics to see if it was not a dupe. I could have missed one.
*, Can't find a good translation for this one: "in the way you use it". But in this context not the difference in use between as field and property but in the menu option.
A:
In English, the options are called:
Encapsulate field (and use property)
Encapsulate field (but still use field)
The difference is in what it does to usages of the field. The first option will update all usages of that field to use the new properties that it creates. The second option doesn't change existing usages of the field elsewhere in your code.
So if elsewhere you have this code:
var test = new Test_EncapsulateFieldRefactoring_Property();
test.name = "Hello";
You'll find that the first option updates test.name to the new test.Name property, but the second option doesn't.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calling paint() from another method in Java
what I am trying to achieve in Java is to be able to paint random shapes from another method without having to have those shapes already drawn from the start (user picks x, y, w, h themselves)
Here is what I have so far:
public class Design extends JComponent {
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
super.paintComponent(g);
}
public void drawRect(int xPos, int yPos, int width, int height) {
Graphics g = null;
g.drawRect(width, height, xPos, yPos);
}
}
As you can see above, I have the drawRect function coded but do not understand how to make it so when I call the drawRect() function, it gets the paint() function to draw a rectangle instead which is EXACTLY what the paint function does, inside it, you type g.drawRect() and your x,y,w,h.
The reason why I am doing this and not just straight up using paint() is because i'm trying to make a component so instead of having to type out the paint() function everytime, I just add this class to my Swing and it's done.
Hope you understand what I'm trying to achieve here.
Thanks.
A:
You need to do all paintings inside paintComponent() method with calling super.paintComponent().
I suggest you to store all needed shapes in List and draw all of them in paintComponent().
Instead of drawRect use something like addRect which adding new shape to your List and call repaint() method. Examine next simple example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class TestFrame extends JFrame {
public TestFrame() {
System.out.println("as".equalsIgnoreCase(null));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
pack();
setVisible(true);
}
private void init() {
final Design d = new Design();
d.addRect(0,0,10,20);
JButton b = new JButton("add");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Random r = new Random();
int w = r.nextInt(100);
int h = r.nextInt(100);
d.addRect(0,0,w,h);
}
});
add(d);
add(b,BorderLayout.SOUTH);
}
public static void main(String... strings) {
new TestFrame();
}
private class Design extends JComponent {
private static final long serialVersionUID = 1L;
private List<Shape> shapes = new ArrayList<Shape>();
public void paint(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for(Shape s : shapes){
g2d.draw(s);
}
}
public void addRect(int xPos, int yPos, int width, int height) {
shapes.add(new Rectangle(xPos,yPos,width,height));
repaint();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(100,100);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove by vector method that the quadrilateral whose diagonal bisect each other is a parallelogram.
Prove by vector method that the quadrilateral whose diagonal bisect each other is a parallelogram.
My Attempt
I have tried till here. Then please help to complete the proof.
A:
Given conditions are
$\vec{CM} = \vec{MA}$
$\vec{MB} = \vec{OM}$
It can be seen using the triangle law of addition that
$\vec{CB} = \vec{CM} + \vec{MB}$
$\vec{OA} = \vec{OM} + \vec{MA}$
It can clearly be seen that $\vec{CB} = \vec{OA}$ (substitute the first 2 equations into any one of the last 2 equations). And by the theorem "If two sides of a quadrilateral are parallel and equal, the quadrilateral is a parallelogram (see the $4^{th}$ characterisation here)", the result is proved.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sql queries not executed on H2 database
Recently i changed from HSQLDB to H2, changed a bit of code and my queries stopped executing.
I test my SQL code with RazorSQL where i try to access my DB from , bud to my suprise there is no table created,no errors thrown no null pointers , valid sql, db file created - everything seems to be running alright bud no content in database whatsoever.
Here are a crucial parts of my database access/creation.
I use connector class to create connect to database
public class H2DatabaseConnector {
private Connection connection;
private Statement statement;
private ResultSet resultSet;
public static final String[] PREP_STATEMENTS = new String[]{};
public static final String DB_FILE_NAME = File.separator + "dboc";
public static final String DB_DIR = Info.OC_DIR + "oc_database\\";
static {
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
public H2DatabaseConnector(String username, String password) {
try {
openConnection(username, password);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
.....
//data credentials are correct
private void openConnection(String username, String password) throws SQLException {
connection = DriverManager.getConnection("jdbc:h2:file:" + DB_DIR + DB_FILE_NAME+";DATABASE_TO_UPPER=false", username, password);
statement = connection.createStatement();
}
public void execute() {
}
}
And utility class where i execute my sql commands
public class DbUtil {
public static final void createUsersTable(){
new H2DatabaseConnector(Info.Db.DB_MAIN_USERNAME,Info.Db.DB_MAIN_PASSWORD) {
@Override
public void execute() {
try {
getStatement().execute("CREATE TABLE users(name VARCHAR(255) NOT NULL,password VARCHAR(255) NOT NULL,email VARCHAR(255));");
System.out.println("Table Created users");
getStatement().executeUpdate("INSERT INTO users VALUES ('sa','sa',NULL);");
closeConnection();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}.execute();
}
}
Execution is going thru as expected bud no table is created.
Why is this happening? There are no errors shown,and sql syntax is correct since when i open database in **RazorSQL and create/insert table there everything works.**
Any ideas? Im literally stuck on this for a whole day.
A:
It's possible that re-using the Statement could be causing you issues, but since I don't have a fully runnable example to go on, it's difficult to be sure...
So, I did this really quick test (using 1.4.182)...
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test {
public static void main(String[] args) {
try {
Class.forName("org.h2.Driver");
try (Connection con = DriverManager.getConnection("jdbc:h2:file:./Test;DATABASE_TO_UPPER=false", "sa", "sa")) {
try (Statement stmt = con.createStatement()) {
stmt.execute("CREATE TABLE if not exists users(name VARCHAR(255) NOT NULL,password VARCHAR(255) NOT NULL,email VARCHAR(255))");
con.commit();
}
try (PreparedStatement stmt = con.prepareStatement("INSERT INTO users (name, password, email) VALUES (?,?,?)")) {
stmt.setString(1, "sa");
stmt.setString(2, "sa");
stmt.setString(3, null);
int rows = stmt.executeUpdate();
System.out.println(rows + " where inserted");
con.commit();
}
try (PreparedStatement stmt = con.prepareStatement("select * from users")) {
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
String name = rs.getString(1);
String password = rs.getString(2);
String email = rs.getString(3);
System.out.println(name + "; " + password + "; " + email);
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Which when run the first time outputs...
1 where inserted
sa; sa; null
When run the second time outputs...
1 where inserted
sa; sa; null
sa; sa; null
Personally, I would isolate each Statement to a single task, in fact, I tend to isolate each Connection as well, but that's because I'm paranoid ;)
A:
After further examination of my code : code in original post is working and no change was needed.
Problem that i was facing was a way i tryed to connect to my database from RazorSQL , JDBC URL that i used didnt matched exact URL that i used in my code i ommited ;DATABASE_TO_UPPER=false which in turn let me connect to it bud Schema of db was not changed. After using correct JDBC URL, i was able to see table with data in RazorSQL.
If you have same problem like i did try to use JDBC URL that you use in code, also with options afterwards.
Failed URL
jdbc:h2:file:C:\Users\tomas\.OpenChannel\oc_database\dboc
Correct url
jdbc:h2:file:C:\Users\tomas\.OpenChannel\oc_database\dboc;DATABASE_TO_UPPER=false
I woud have never expected that this coud have been a problem. :D
| {
"pile_set_name": "StackExchange"
} |
Q:
Replacement for old Radeon HD 4870 1-Gb 256 bit GDDR5
I'm looking for a similar AMD cheap modern replacement of this card (Radeon HD 4870 1-Gb 256 bit GDDR5) for my old computer but i'm not very sure about the way to go. Price between (50$-100$)
What modern AMD card would have a similar or better performance and work with my computer in that price range?
The PC specs are:
Intel Quad Q9550 2.83 Ghz
RAM: 4 Gb 1333 MHz
Motherboard: ASRock G41C-GS
PSU: 750 W
A:
If you're looking to purchase new, and want roughly comparable single-precision computing power, I recommend the MSI Radeon R7 250, $75 from Newegg. It's got about 70% the single-precision speed of the 4870, twice the RAM, and draws half the power. Note that if you need double-precision computing power, this is a bad choice: it's only 20% as powerful as your current card.
If you need double-precision computing power, I recommend you look on Amazon or Ebay for another 4870. The HD 4000 series had unusually high double-precision performance, and a modern replacement will run you at least $200.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript - Change event trigger multiple times
I have the following table.
<table class="table invoice-items-table">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr class="invoice-item-row">
<td>
<select class="selectpicker invoice-item-select" title="Select an Item">
<option value="1">PHP Development</option>
</select>
</td>
<td class="text-right">
<input class="form-control invoice-item-quantity" value="1" type="text">
</td>
<td class="text-right">
<input class="form-control invoice-item-price" value="0.00" type="text">
</td>
<td class="text-right" style="padding-top:18px!important;">
<span class="invoice-item-amount">0 </span>
<span class="invoice-currency">₹</span>
</td>
</tr>
<tr class="invoice-item-add-row">
<td colspan="7">
<a href="#" class="link invoice-item-add text-center">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add an Item
</a>
</td>
</tr>
</tbody>
</table>
For on-click event of a.invoice-item-add I append more table rows tr to the table, here is the code for that.
$('.invoice-item-add').on('click', function() {
var itemRowClone = $('.invoice-item-row').last().clone();
itemRowClone.find('input, textarea').val('');
itemRowClone.find('.bootstrap-select').replaceWith(function() { return $('select', this); });
itemRowClone.find('.selectpicker').selectpicker();
$('.invoice-item-add-row').before(itemRowClone);
return false;
});
This works perfectly fine, until I want to trigger select.invoice-item-select, here is how I trigger it.
$(document).on('change', '.invoice-item-select', function() {
// Code here...
});
my problem is, this on-change gets fired multiple times based on the number of elements added dynamically, if there is one tr.invoice-item-row it gets fired twice, if there are two tr.invoice-item-row it gets fired four times, basically it fires times two.
I understand that the tr.invoice-item-row are added dynamically and we are using $(document).on('change', '.invoice-item-select', function()... to listen to the trigger.
How do I make sure this on-change event is fired only once?
Thanks.
A:
I ended up using this solution
$(document).on('change', '.invoice-item-select', function(e) {
if (e.handled !== true) {
e.handled = true;
return;
}
// Code here
});
Although this does not stop from multiple firing of events, I can at-least stop the code execution for subsequent triggers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting text to a TextView in Fragment A after adding and removing Fragment B
I have fragment A, on TextView click I add another Fragment B, I want to update the TextView of Fragment A when I remove Fragment B, any ideas on how to do that?
A:
As Shubhank Gupta mentioned use a boolean when you remove Fragment B set it true and in Fragement A onResume() check for that boolean if it is true then change the text.
In Fragment B when removing it:
isTextChange = true;
In Fragment A:
@Override
public void onResume() {
super.onResume();
if(isTextChange){
mTextView.setText("Text you want");
isTextChange = false;
}
}
Edit:
or you can override isUserVisibleHint() method inside Fragment A and check there.
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
if(isTextChange){
mTextView.setText("Text you want");
isTextChange = false;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What exactly happens when git creates a branch does it copy files from main folder?
So I decided to learn git to host a little project for school using github pages, this is my first day with git and I think I understand a bit how it works, however I'm curious to know what happens when I create a branch, does git copy files from main folder to another folder ? How does it revert changes when I do checkout master (on sublime text I immediately see changes) ? Thanks
A:
What happens when I create a branch?
Nothing on the working tree (the files on your disk), git creates a new ref pointing to the current commit. That's why creating branches is so fast.
How does it revert changes when I do checkout master?
It updates the working tree to match the master branch, working out just what needs to change to achieve that.
I suggest you read this to properly grok what's going on: http://ftp.newartisans.com/pub/git.from.bottom.up.pdf
| {
"pile_set_name": "StackExchange"
} |
Q:
Date function - Error in sql
I have a members table with field DataNa type date.
I would like to make a query like:
Select DateDiff (year, datana, dateserial (year,12,31)) as years, ....
from members ... etc ...
Year is a parametric value. But the system tells me that DateSerial is not a recognized value of default function name.
I also tried to do:
Select DateDiff (year, datana, datevalue ('31/12/' + year)) as years, ....
from members ... etc ...
It says it also is not a DateValue recognized default function name
I'm using SQL Server 2008R2
A:
Are you looking for something like this?
SELECT DATEDIFF(YEAR, datana, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, -1)) years
FROM members
This part
DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, -1)
returns last day of the current year (e.g. 2013-12-31)
Here is SQLFiddle demo
| {
"pile_set_name": "StackExchange"
} |
Q:
"python way" to parse and conditionally replace every element in 2D list
I have a list which consists of further lists of strings which may represent words(in the alphanumeric sense) or ints, e.g.
myLists = [['5','cat','23'],
['33','parakeet','scalpel'],
['correct','horse','battery','staple','99']]
I want to parse the array so that all integer representations are converted to ints. I have a simple function, numParser(string) to this end:
def numParser(s):
try:
return int(s)
except ValueError:
return s
With my c/java background I would normally just iterate through both arrays, changing each value (the fact that those arrays would be homogeneous notwithstanding). But I'm new to python and thought there might be a better way to do this, so I searched around and found a couple SO posts regarding map() and list comprehension. List comprehension didn't seem like the way to go because the lists aren't uniform, but map() seemed like it should work. To test, I did
a=['cat','5','4']
a = map(numParser, a)
Which works. Without thinking, I did the same on a nested loop, which did not.
for single_list in myLists:
single_list = map(numParser, rawData)
Now, after receiving an unchanged 2D array, it occurs to me that the iterator is working with references to the array, not the array itself. Is there a super snazzy python way to accomplish my goal of converting all integer representations to integers, or do I need to directly access each array value to change it, e.g. myLists[1][2] = numParser(myLists[1][2])?
A:
You can do this with list comprehension:
>>> [map(numParser, li) for li in myLists]
[[5, 'cat', 23], [33, 'parakeet', 'scalpel'], ['correct', 'horse', 'battery', 'staple', 99]]
A:
Here is one way to do it:
for single_list in myLists:
for i, item in enumerate(single_list):
single_list[i] = numParser(item)
The advantage of this method is you actually replace the elements in the existing lists, not creating new lists.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript turns my php visible
This is test123.php:
<?php
echo "<html>";
echo "<head>";
echo "</head>";
echo "<body>";
echo '<form class="show_playerlist" id="show_playerlist" onsubmit="return false">';
echo '<center><input type="submit" value="Submit"></center><br>';
echo "</form>";
echo '<span id="test" style="display:none">ok</span>';
echo '<script type="text/javascript" src="jqueryui/js/jquery-1.8.2.min.js"></script>';
echo '<script type="text/javascript" src="test123.js">';
echo "</script>";
echo "</body>";
echo "</html>";
?>
This is the test123.js:
$(".show_playerlist").submit(function(){
$("#test").show();
});
When I open the php in my browser and submit the form, I can see the php by using Firebug:
In Firebug between CSS and DOM there is script, which should be only showing my javascript. But it also shows the test123.php AFTER executing the javascript.
Without any javascript the php isn't shown in Firebug script, as it should be.
A:
That's not your PHP showing, that's the HTML ... firebug shows javascript, and if your html has javascript ONLY in an attribute (like onsubmit in your example), it wont get shown in firebug until it fires
When it is shown, it's shown in the context of the HTML (not PHP) that it is contained in - so, displays the source of your page, the HTML source that is
This also works this way in the firefox built in developer tools in the debugger tab
This will also show up in the debugger tab only once the submit button is pressed - save it as .html - PHP is irrelevant
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form onsubmit='return false;' >
<input type="submit" value="Submit">
</form>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
If a triangle has side lenghts $a,b,c$ where $c$ is the largest prove that its obtuse if $c^2>a^2+b^2$ and acute if $c^2<a^2+b^2$.
I was thinking about this and I cant get to a formal proof. I have a sort of mental image where you draw $a$ and $b$ perpendicular and the $c$ is too small to connect the two endpoints. So the right angle enclosed by $a$ and $b$ has to be reduced a bit so that $c$ can connect the end of $a$ to $b$. But this is not really a proper proof. I searched the internet and this idea is used in a lot of places but nowhere proven. This is not homework, but I was writing a little program to determine whether a given triangle will be obtuse, acute or right-angled. Any help would be much appreciated :) Thanks in advance.
A:
The "law of cosines" tells us that $$a^2=b^2+c^2-2bc \cos A$$This is a useful generalisation of Pythagoras to triangles which are not right-angled, and validates your observation.
Note that noticing things which are not immediately obvious is one of the most powerful ways in which mathematicians make progress!!
| {
"pile_set_name": "StackExchange"
} |
Q:
how to view source code of programs (python)
Python newbie here....I was interested in writing a basic touch typing tutor program in python. I was wondering what is the best way to download source code of applications that people have written that are of a similar nature (to use as a guide to learn from). I went to http://pypi.python.org/ and downloaded some packages but I'm not quite sure how to view the actual python code. Which file are you supposed to open. I found a run.py file in one of them and it doesn't seem to even work when I try to run it. I'm sure I'm missing something here.
Thanks!
A:
You can also use inspect to view the code from the interpreter. So say your file is named "test.py" and it's on your PYTHONPATH (if you don't know what that is, then make sure you are in the same directory as "test.py").
>>> import inspect
>>> import test # this imports test.py
>>> print inspect.getsource(test)
def hello(name):
print("Hello %s" % name)
If you were using IPython, then you could also do:
In [1]: import test
In [2]: test??
You can't edit the code like this... but you can view it.
A:
Double-clicking a .py script will execute the script (and may not send any useful results to the screen). To view the source you can open a .py file with IDLE (which comes with Python) or even Notepad although a more advanced text editor or IDE is recommended. See Is there a good, free Python IDE for Windows for IDE recommendations by the stackoverflow community. Good luck, and welcome to the Python community!
| {
"pile_set_name": "StackExchange"
} |
Q:
C# DataGridView clean up
I have a BindingList which is the data source for a Bindingsource, which in turn is a data source for a DataGridView.
(The objects are purely managed, and do not have anything that requires calling .Dispose().)
When I wish to clear the list, and hence clear the grid, I am simply calling BindingSource.Clear(), which as far as I can tell clears the underlying BindingList containing my objects, and because it is data-bound to the grid, the rows in the grid disappear.
Should I be doing anything else to the grid (or anything else), to ensure that all the data has been cleaned up?
Thanks.
A:
No, you don't need to.
Just make sure you clear the binding source. As soon all references to the List are out of scope it will be garabge collected on the next collection cycle.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java : Convert string to use in url as part of a get
Hello I shall get straight to the point, I am trying to use a EditText input to use in a php url i want the url to to be like thi when it runs.
http://www.free-map.org.uk/course/mad/ws/hits.php?artist=Oasis
SO I tried
URL url = new URL("http://www.free-map.org.uk/course/mad/ws/hits.php?artist=",et1);
but i get the error
Here is the main part of my code.
class MyTask extends AsyncTask<Void,Void,String>
{
EditText et1 = (EditText)findViewById(R.id.et1);
public String doInBackground(Void... unused)
{
HttpURLConnection conn = null;
try
{
URL url = new URL("http://www.free-map.org.uk/course/mad/ws/hits.php?artist=",et1);
conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
if(conn.getResponseCode() == 200)
{
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String result = "", line;
while((line = br.readLine()) !=null)
result += line;
return result;
}
else
return "HTTP ERROR: " + conn.getResponseCode();
}
catch(IOException e)
{
return e.toString();
}
finally
{
if(conn!=null)
conn.disconnect();
}
}
A:
You can't append EditText with String. You have to append input from EditText.
To get input from EditText use -
EditText et1 = (EditText)findViewById(R.id.et1);
final String input = et1.getText().toString();
// then append it
URL url = new URL("http://www.free-map.org.uk/course/mad/ws/hits.php?artist="+input);
| {
"pile_set_name": "StackExchange"
} |
Q:
Start and stop Fiddler from command line
I have the following requirement:
I need to start Fiddler from the command line. It will start capturing my traffic immediately. After some time, I want to stop capturing the traffic, but not close Fiddler.
What is the best way to achieve this ? I've explored Fiddler's command-line options, but they will only start Fiddler and not stop it. Also, killing the Fiddler process will not save my session safely. Please help.
A:
There are several ways to do this. The simplest is to run
%programfiles(x86)%\fiddler2\execaction.exe stop
This calls the execaction program in the Fiddler install folder, passing it the command stop. The stop message is sent to Fiddler, whose script handler (click Rules > Customize Rules, scroll to OnExecAction) will interpret it as a command to detach as the system proxy.
To reattach the proxy, use start as the command. You can see what other commands are available (and add your own) by looking at the OnExecAction function.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to say "I think studying English is easier for Brazilians than for Japanese"
I wanna say "I think that for Brazilians, studying English is easier than it is for Japanese"
I know how to make simple comparisons like
お寿司の価格の方がラーメンより高い
but I am having trouble coming up with that sentence, specifically because the only place I can check if it is right is Google translator, but I know it is not reliable... my attempt is:
ブラジル人にとって英語を勉強する方が日本人にとってより簡単だと思うよ
Thanks!
A:
I think your attempt is a literal translation. I translate it as ブラジル人が英語を習得する(覚える)方が日本人より簡単だと思うよ.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does coffee grounds do to plants like tomatoes?
I've heard about using coffee grounds on tomato plants, and was wondering what it does to the plant.
A:
Coffee grounds come up in gardening because they're a daily source of "green" (Nitrogen) fuel for the compost pile. The other half, browns, are easy to come by (leaves, tiny twigs, etc), and generally a 50/50 ratio is necessary to maintain for good compost. Hence, piles are always hurting for greens so gardeners are happy for a daily dose, even if it's just a filter full of used coffee grounds.
As to what they add to compost besides nitrogen, not much chemically besides having an almost neutral pH while many greens are acidic. They're just a great green source all around. They won't go bad and smell so you can store them in your house until you compost them, and they decompose quicker than most greens.
(Seemed opinion-heavy so I hunted this up:) http://homeguides.sfgate.com/fertilize-tomato-plants-coffee-grounds-35715.html
Adding coffee grounds without composting to your garden is asking for trouble. Before they produce nitrogen for plants to use, they have to decompose. The decomposition process rips nitrogen out of the soil, and will negatively affect your plants.
http://extension.oregonstate.edu/lane/sites/default/files/documents/cffee07.pdf
If you're looking to turn household waste into garden fuel - by all means take up composting. But it's never a good idea to go from the kitchen right to the garden bed.
http://www.vegetable-gardening-with-lorraine.com/homemade-compost-bin.html (no school like the old school)
A:
There's a good answer on how to generally use coffee grinds as a fertilizer right here.
It's a good source of nitrogen, though your plants won't be able to directly use it until it's broken down. The direct benefits on a tomato plant specifically come from the fact that coffee grinds are slightly acidic and that tomato plants like their soil slightly acidic (most sources from a quick Google search say around 6-7, here, here, and here).
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to prove a matrix is always convergent.
I have a matrix $Z$ of the form $Z = \left[Q^{-1}-Q^{-1}A^T\left(AQ^{-1}A^T\right)^{-1}AQ^{-1}\right]\Phi$
where,
$\Phi$ is a diagonal matrix of real non-negative values.
$\Theta$ (not explicitly in the equation above) is another diagonal matrix of real non-negative values.
$Q = \Phi + \Theta$ such that $Q$ is a diagonal matrix of real positive values.
$A$ is a rectangular matrix of the form $\left[J \quad -I\right]$ where the elements of $J$ are real values and $I$ is the identity matrix of appropriate size.
Matrix dimensions are as follows:
$\Phi, \Theta, Q$ are of dimension $(n+m)\times (n+m)$.
$A$ is of dimension $m\times (n+m)$.
$J$ is of dimension $m\times n$.
$I$ is of dimension $m\times m$.
$Z$ is the plant matrix of a discrete time linear time-invariant state space equation, and I have reason to believe that, given the properties above, $Z$ is always convergent. As the state space equation is in discrete time, the conditions for a convergent plant are that all eigenvalues must have magnitude $\leq 1$. Also, should there be an eigenvalue with magnitude $= 1$, its multiplicity must be 1 to be at least Lyapunov stable.
I would appreciate any help in either proving or disproving my claim.
So far, I have been able to prove that $Q^{-1}\Phi$ and $Q^{-1}A^T\left(AQ^{-1}A^T\right)^{-1}AQ^{-1}\Phi$ are both symmetric positive semi-definite. I have tried applying the Sherman–Morrison–Woodbury formula only to show that $Z$ is singular. I can also show that $Q^{-1}\Phi$ has a spectral radius $\leq 1$ but not the same for $Q^{-1}A^T\left(AQ^{-1}A^T\right)^{-1}AQ^{-1}\Phi$.
A:
In general, for (possibly noninvertible) complex square matrices $A$ and $B$, the spectra of $AB$ and $BA$ are identical. Therefore the spectrum of $Z$ is identical to that of the real symmetric matrix
\begin{align*}
\widetilde{Z}
:=&\Phi^{1/2}\left[Q^{-1}-Q^{-1}A^T\left(AQ^{-1}A^T\right)^{-1}AQ^{-1}\right]\Phi^{1/2}\\
=&\Phi^{1/2}Q^{-1/2}\left[I - Q^{-1/2}A^T(AQ^{-1}A^T)^{-1}AQ^{-1/2} \right]Q^{-1/2}\Phi^{1/2}\\
=&\Phi^{1/2}Q^{-1/2}\left(I-P\right)Q^{-1/2}\Phi^{1/2},
\end{align*}
where $P := Q^{-1/2}A^T(AQ^{-1}A^T)^{-1}AQ^{-1/2}$ is an orthogonal projection (because it is real symmetric and $P^2=P$). Therefore, $I-P$ is also an orthogonal projection. As $A$ has full rank, it follows that the eigenvalues of $I-P$ are $0$ (of multiplicity $m$) and $1$ (of multiplicity $n$). Since all diagonal entries of $\Phi^{1/2}Q^{-1/2}$ do not exceed $1$, the spectral norm and in turn the spectral radius of $\widetilde{Z}$ are also $\le1$.
Now, $1$ is a repeated eigenvalue of $\widetilde{Z}$ (or $Z$) if and only if the eigenspaces of $\Phi^{1/2}Q^{-1/2}$ and $I-P$ corresponding to the eigenvalue $1$ have a two- or higher dimensional intersection. Such undesired cases can happen, for instances, when (a) $\Phi=Q$ or (b) when $J=0,\,n\ge2$ and some two among the first $n$ entries of $\Phi^{1/2}Q^{-1/2}$ are equal to $1$. However, if $n=1$ or $\Phi^{1/2}Q^{-1/2}$ has at most one diagonal entry equal to $1$, then it is guaranteed that $1$ is not a repeated eigenvalue of $Z$.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS mover Canvas
Al mover el hacia cualquier lado, el canvas deja de funcionar, me gustaría saber como moverlo de forma correcta hacia el margen derecho de la pantalla
HTML
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>plantillapaint</title>
<meta name="description" content="">
<meta name="author" content="satur">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="stylesheet" href="combinandoto.css">
<script src="combinandoto.js"></script>
</head>
<body>
<div id="paint">
<table>
<tr>
<td><canvas width="500" height="500" id="canvas" onmousemove="pintar(event);" onmousedown="activar();" onmouseup="desactivar();"></canvas></td>
<td class="herramientas">
<a href="#" onclick="lapiz();"><img src="Fotos/lapiz.png" width="50" height="auto" /></a>
<a href="#" onclick="borrador();"><img src="Fotos/goma.png" width="50" height="auto"/></a> <br>
<div style="width: 10px; height: 10px;" onclick="stamano(3);"></div><br />
<div style="width: 20px; height: 20px;" onclick="stamano(5);"></div><br />
<div style="width: 30px; height: 30px;" onclick="stamano(10);"></div><br />
<div style="width: 40px; height: 40px;" onclick="stamano(20);"></div><br />
<input type="color" id="colores" onchange="scolor();"/>
<a href="#" download="canvas.png" id="guardarimagen" >Guardar como imagen</a>
</td>
</tr>
</table>
</div>
<script>
document.getElementById("guardarimagen").addEventListener("click", guardari, false);
</script>
</body>
CSS:
#paint {
margin-left: 500px;
}
#canvas {
border : solid 1px;
cursor : url('imagenes_del_rancio/lapizcursor.gif'), default;
}
.herramientas {
width: 100px;
}
.herramientas div {
background-color: black;
}
.herramientas div:hover{
border: solid red 1px;
}
.herramientas img:hover{
border: solid red 1px;
}
JAVASCRIPT:
var color = "#000000";
var tamaño = 10;
var pintura = false;
function pintar(event){
var canvas = document.getElementById("canvas");
var cuadro = canvas.getContext("2d");
var x = event.clientX-15;
var y = event.clientY+35;
if(pintura){
cuadro.fillStyle = color;
cuadro.fillRect(x, y, tamaño, tamaño);
}
}
function activar(){
pintura = true;
}
function desactivar(){
pintura = false;
}
function borrador(){
document.getElementById("canvas").style.cursor = "url('imagenes_del_rancio/borradorcursor.png'), crosshair";
color="#FFFFFF";
document.getElementById("colores").setAttribute("disabled", "");
}
function lapiz(){
document.getElementById("canvas").style.cursor = "url('imagenes_del_rancio/lapizcursor.gif'), crosshair";
color = document.getElementById("colores").value;
document.getElementById("colores").removeAttribute("disabled");
}
function scolor(){
color = document.getElementById("colores").value;
}
function stamano (numero)
{
tamaño = numero;
}
function guardari()
{
var canvas = document.getElementById("canvas");
var imagen = canvas.toDataURL("image/png");
this.href = imagen;
}
A:
El problema es el clientX y el clientY. Ambos toman el valor de la pantalla y la pos en la que esta el cursor. Es decir que cuando tu canvas esta a la derecha toma la coordenada desfasada. Para eso tiene que restar la propia posición del canvas a tu coordenada x,y:
var rect = canvas.getBoundingClientRect();
var x= event.clientX - rect.left;
var y= event.clientY - rect.top;
Luego el resto fue cambiar de lugar el td para q el canvas se vea a la derecha.
var color = "#000000";
var tamaño = 10;
var pintura = false;
function pintar(event) {
var canvas = document.getElementById("canvas");
var cuadro = canvas.getContext("2d");
var rect = canvas.getBoundingClientRect();
var x= event.clientX - rect.left;
var y= event.clientY - rect.top;
// var x = event.clientX - rect.left;
// var y = event.clientY - rect.top;
if (pintura) {
cuadro.fillStyle = color;
cuadro.fillRect(x, y, tamaño, tamaño);
}
}
function activar() {
pintura = true;
}
function desactivar() {
pintura = false;
}
function borrador() {
document.getElementById("canvas").style.cursor = "url('imagenes_del_rancio/borradorcursor.png'), crosshair";
color = "#FFFFFF";
document.getElementById("colores").setAttribute("disabled", "");
}
function lapiz() {
document.getElementById("canvas").style.cursor = "url('imagenes_del_rancio/lapizcursor.gif'), crosshair";
color = document.getElementById("colores").value;
document.getElementById("colores").removeAttribute("disabled");
}
function scolor() {
color = document.getElementById("colores").value;
}
function stamano(numero) {
tamaño = numero;
}
function guardari() {
var canvas = document.getElementById("canvas");
var imagen = canvas.toDataURL("image/png");
this.href = imagen;
}
#paint {
margin - left: 500 px;
}
#paint table{
float:right;
}
#canvas {
border: solid 1px black;
cursor: url('imagenes_del_rancio/lapizcursor.gif'),
default;
}
.herramientas {
width: 100 px;
}
.herramientas div {
background - color: black;
}
.herramientas div: hover {
border: solid red 1 px;
}
.herramientas img: hover {
border: solid red 1 px;
}
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>plantillapaint</title>
<meta name="description" content="">
<meta name="author" content="satur">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="stylesheet" href="combinandoto.css">
<script src="combinandoto.js"></script>
</head>
<body>
<div id="paint">
<table>
<tr>
<td class="herramientas">
<a href="#" onclick="lapiz();"><img src="Fotos/lapiz.png" width="50" height="auto" /></a>
<a href="#" onclick="borrador();"><img src="Fotos/goma.png" width="50" height="auto" /></a> <br>
<div style="width: 10px; height: 10px;" onclick="stamano(3);"></div><br />
<div style="width: 20px; height: 20px;" onclick="stamano(5);"></div><br />
<div style="width: 30px; height: 30px;" onclick="stamano(10);"></div><br />
<div style="width: 40px; height: 40px;" onclick="stamano(20);"></div><br />
<input type="color" id="colores" onchange="scolor();" />
<a href="#" download="canvas.png" id="guardarimagen">Guardar como imagen</a>
</td>
<td>
<canvas width="500" height="500" id="canvas" onmousemove="pintar(event);" onmousedown="activar();" onmouseup="desactivar();"></canvas>
</td>
</tr>
</table>
</div>
<script>
document.getElementById("guardarimagen").addEventListener("click", guardari, false);
</script>
</body>
Te adjunto una respuesta de SO desde la q me base para responderte y que tiene unos ejemplos muy buenos.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using DNS in iproute2
In my setup I can redirect the default gateway based on the source address. Let's say a user is connected through tun0 (10.2.0.0/16) is redirect to another vpn. That works fine!
ip rule add from 10.2.0.10 lookup vpn1
In a second rule I redirect the default gateway to another gateway if the user access a certain ip adress:
ip rule add from 10.2.0.10 to 94.142.154.71 lookup vpn2
If I access the page on 94.142.154.71 (myip.is) the user is correctly routed and I can see the ip of the second vpn. On any other pages the ip address of vpn1 is shown.
But how do I tell iproute2 that all request at e. g. google.com should be redirected through vpn2?
A:
There is a good chance that an A-Record resolves to multiple ip addresses:
% dig +short google.com
209.85.148.101
209.85.148.102
209.85.148.113
209.85.148.138
209.85.148.139
209.85.148.100
So you have to loop through them and add a rule for each of them like this
dig +short google.com | while read IP; do
ip rule add from 10.2.0.10 to "$IP" lookup vpn2
done
Also you should think about a refresh cronjob.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS what value does Canvas Skew use in setTransform?
http://www.w3schools.com/tags/canvas_settransform.asp
context.setTransform(a,b,c,d,e,f);
W3C schools says "Skew the the drawings horizontally", but which value does it use?
It seems it's not degrees like the CSS skews things, and neither does it use PI. Explanation?
A:
In your example transform, the b & c would respectively represent the horizontal and vertical skew.
The transform matrix is arranged like this:
context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY);
The amount of skew is a tangent angle that's expressed in radians.
So this will skew 30 degrees horizontally:
var tan30degrees=Math.tan( 30*Math.PI/180 );
ctx.save();
ctx.setTransform(1,tan30degrees,0,1,0,0);
ctx.fillRect(100,100,50,50);
ctx.restore();
A:
transformation matrix—a set of nine numbers that are used to transform a two-dimensional array, such as a bitmap, using linear algebra. the last set of the matrix is always 0 0 1 so it takes six different parameters
Please have a look at this
https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/MatrixTransforms/MatrixTransforms.html
| {
"pile_set_name": "StackExchange"
} |
Q:
What usage does 有 have in ~的有 (e.g. 偏向于data reseacher的有)
In the following sentence over 知乎:
从我的观察来看,不同企业对于data scientist这个title的定义其实是有分歧的,偏向于data reseacher的有,多见于大型IT企业,百度大脑的data scientist们多属于这一类型,他们搞的是比较前沿的深度学习,平常会读大量paper可能自己也会发;偏向于data creative的有,各种企业都会储备,会ETL,懂模型、懂行业,会展示沟通,比较能够创造直接的价值。偏向于data developer的也有但是很少,他们不懂模型,只要给他们算法公式,他们就能用编程语言帮你实现,实现算法是重要的技能,但是这种不懂模型不懂行业的,现在大多企业都不太会给这样的人data scientist的title了。
The grammar book does not seem to have this usage of 有.
I feel that the meaning is similar to 关于 or 至于 (at least in this context), so the relevant sentence above can be rewritten as follows:
关于偏向于data researcher (or suffix "的话" here?),
关于data developer,虽然他们比减少,
However, grammatically how does 有 work here? I just check out the Chinese grammar wiki but didn't find any relevant pages.
A:
I am a native speaker and consider myself a "data" person.
From my perspective, he didn't end the sentence properly and his array of sentences could be changed a bit like below so it's easier to understand.
从我的观察来看,不同企业对于data scientist这个title的定义其实是有分歧的。
有偏向于data reseacher的,多见于大型IT企业。百度大脑的data scientist们多属于这一类型,他们搞的是比较前沿的深度学习,平常会读大量paper可能自己也会发文章。
The purpose of 有...的 is to illustrate his/her point using example(s).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find exponent coefficients in a sum of exponents?
It is easy to determine a coefficient 'c' of exp(c*x), just log it and find slope. Or if it's
exp(c1*x) + exp(c2*x)
then after log from 0 to the right of left we would find 'c1' and 'c2'. But what if we have more terms? For example, such a sum
exp(x) + exp(1.5*x) + exp(2.5*x) + exp(3*x)
if you loged it, almost would have no difference between
exp(x) + exp(3*x)
So, please, how could I find them in another way?
A:
If you know, that
$$y(x) = \exp(c_1 x)+\exp(c_2 x)+\cdots+\exp(c_n x),$$
then
calculate $y(1), y(2), \ldots, y(n)\;$: $\;p_1 = y(1), p_2 = y(2), \ldots, p_n=y(n)$.
You'll get system of equations:
$$\left\{
\begin{array}{r}
\exp(c_1)+\exp(c_2)+\cdots+\exp(c_n)=p_1; \\
\exp(2c_1)+\exp(2c_2)+\cdots+\exp(2c_n)=p_2; \\
\cdots \cdots \cdots \qquad \qquad \qquad \qquad \\
\exp(nc_1)+\exp(nc_2)+\cdots+\exp(nc_n)=p_n.
\end{array}
\right.
$$
If denote $s_1=\exp(c_1), s_2=\exp(c_2), \ldots, s_n=\exp(c_n)$, then
$$\left\{
\begin{array}{r}
s_1+s_2+\cdots+s_n=p_1; \\
s_1^2+s_2^2+\cdots+s_n^2=p_2; \\
\cdots \cdots \cdots \qquad \qquad \\
s_1^n+s_2^n+\cdots+s_n^n=p_n.
\end{array}
\right.
$$
With the help of Power sum symmetric polynomial
you'll find values $e_1,e_2, \ldots, e_n$ $-$ elementary symmetric polynomials:
$$\left\{
\begin{array}{l}
e_1 = s_1+s_2+\cdots+s_n = p_1; \\
e_2 = s_1s_2+s_1s_3+\cdots+s_{n-1}s_n = \dfrac{1}{2}(p_1^2-p_2); \\
\cdots \cdots \cdots\qquad \qquad \\
e_n = s_1s_2\cdots s_n=\dfrac{1}{n}\sum\limits_{j=1}^n (-1)^{j-1}e_{n-j}p_j;
\end{array}
\right.
$$
so $s_1,s_2,\ldots,s_n$ are roots of equation
$$s^n-e_1\cdot s^{n-1}+\cdots+(-1)^{n-1}e_{n-1}\cdot s+(-1)^n e_n=0.$$
Finally, when you will find roots $s_1,s_2,\ldots,s_n$,
$$c_j=\ln(s_j), \; j=1,\ldots,n.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Sending MIDI data over HTTP
How can I efficiently transfer MIDI data to remote client over HTTP (POST)?
There are no real time issues here, I just don't know how to encode the data.
Should I use plain string-pairs? I think a better way will be to just send the binary data
over the HTTP, I just don't know how to do it.
Thank You
A:
Two options:
Encode the MIDI in base 64 and send it as the body of the POST (not sure what language you're using but most languages should have base 64 support readily available)
Go the multipart/form-data route and actually send the file
Honestly, I prefer option #1 even if it means a slight overhead on size (average ~30%). Just keeps things cleaner.
| {
"pile_set_name": "StackExchange"
} |
Q:
Drag div element with canvas to another
I'm having my first experience in developing html5 applications. My issue is to make room plan. In the top of the page I have elements to drag to the bottom map area (they are copied). In the map area I can move elements, but not copy.
I've built drag'n'drop with help of image elements. But now I want to use canvas for updating numbers on images. I want to use canvas text functions for updating images.
The problem is when I copy canvas element from the top, html inserts well, but it is not drawn in some reasons.
Please, watch code here http://jsfiddle.net/InsideZ/MuGnv/2/. Code was written for Google Chrome.
A:
EDIT:
I made a few small tweaks here: http://jsfiddle.net/MuGnv/5/
Note the changes made to the drawImg function:
function drawImg(src, targetClass) {
$(targetClass).each(function() {
var ctx = $(this).get(0).getContext('2d');
var img = new Image();
img.src = src;
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
});
}
Anytime a drop event is handled, the images are drawn again. This was the missing component as the image was only being drawn once.
| {
"pile_set_name": "StackExchange"
} |
Q:
Knockout/JavaScript Ignore Multiclick
I'm having some problems with users clicking buttons multiple times and I want to suppress/ignore clicks while the first Ajax request does its thing. For example if a user wants add items to their shopping cart, they click the add button. If they click the add button multiple times, it throws a PK violation because its trying to insert duplicate items into a cart.
So there are some possible solutions mentioned here: Prevent a double click on a button with knockout.js
and here: How to prevent a double-click using jQuery?
However, I'm wondering if the approach below is another possible solution. Currently I use a transparent "Saving" div that covers the entire screen to try to prevent click throughs, but still some people manage to get a double click in. I'm assuming because they can click faster than the div can render. To combat this, I'm trying to put a lock on the Ajax call using a global variable.
The Button
<a href="#" class="disabled btn btn-default" data-bind="click: $root.AddItemToCart, visible: InCart() == false"><span style="SomeStyles">Add</span></a>
Knockout executes this script on button click
vmProductsIndex.AddItemToCart = function (item) {
if (!app.ajaxService.inCriticalSection()) {
app.ajaxService.criticalSection(true);
app.ajaxService.ajaxPostJson("@Url.Action("AddItemToCart", "Products")",
ko.mapping.toJSON(item),
function (result) {
ko.mapping.fromJS(result, vmProductsIndex.CartSummary);
item.InCart(true);
item.QuantityOriginal(item.Quantity());
},
function (result) {
$("#error-modal").modal();
},
vmProductsIndex.ModalErrors);
app.ajaxService.criticalSection(false);
}
}
That calls this script
(function (app) {
"use strict";
var criticalSectionInd = false;
app.ajaxService = (function () {
var ajaxPostJson = function (method, jsonIn, callback, errorCallback, errorArray) {
//Add the item to the cart
}
};
var inCriticalSection = function () {
if (criticalSectionInd)
return true;
else
return false;
};
var criticalSection = function (flag) {
criticalSectionInd = flag;
};
// returns the app.ajaxService object with these functions defined
return {
ajaxPostJson: ajaxPostJson,
ajaxGetJson: ajaxGetJson,
setAntiForgeryTokenData: setAntiForgeryTokenData,
inCriticalSection: inCriticalSection,
criticalSection: criticalSection
};
})();
}(app));
The problem is still I can spam click the button and get the primary key violation. I don't know if this approach is just flawed and Knockout isn't quick enough to update the button's visible binding before the first Ajax call finishes or if every time they click the button a new instance of the criticalSectionInd is created and not truely acting as a global variable.
If I'm going about it wrong I'll use the approaches mentioned in the other posts, its just this approach seems simpler to implement without having to refactor all of my buttons to use the jQuery One() feature.
A:
You should set app.ajaxService.criticalSection(false); in the callback methods.
right now you are executing this line of code at the end of your if clause and not inside of the success or error callback, so it gets executed before your ajax call is finished.
vmProductsIndex.AddItemToCart = function (item) {
if (!app.ajaxService.inCriticalSection()) {
app.ajaxService.criticalSection(true);
app.ajaxService.ajaxPostJson("@Url.Action("AddItemToCart", "Products")",
ko.mapping.toJSON(item),
function (result) {
ko.mapping.fromJS(result, vmProductsIndex.CartSummary);
item.InCart(true);
item.QuantityOriginal(item.Quantity());
app.ajaxService.criticalSection(false);
},
function (result) {
$("#error-modal").modal();
app.ajaxService.criticalSection(false);
},
vmProductsIndex.ModalErrors);
}
}
you could use the "disable" binding from knockout to prevent the click binding of the anchor tag to be fired.
here is a little snippet for that. just set a flag to true when your action starts and set it to false again when execution is finished. in the meantime, the disable binding prevents the user from executing the click function.
function viewModel(){
var self = this;
self.disableAnchor = ko.observable(false);
self.randomList = ko.observableArray();
self.loading = ko.observable(false);
self.doWork = function(){
if(self.loading()) return;
self.loading(true);
setTimeout(function(){
self.randomList.push("Item " + (self.randomList().length + 1));
self.loading(false);
}, 1000);
}
}
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<a href="#" data-bind="disable: disableAnchor, click: doWork">Click me</a>
<br />
<div data-bind="visible: loading">...Loading...</div>
<br />
<div data-bind="foreach: randomList">
<div data-bind="text: $data"></div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does Dagger not allow multiple qualifier annotations per element?
Say I have two services AService and BService, both of which require an api key.
So in my modules, I can't do something like:
@Provides @Singleton @A @ApiKey String provideAKey() { return "a"; }
@Provides @Singleton @B @ApiKey String provideBKey() { return "b"; }
(Dagger would complain with "Only one qualifier annotation is allowed per element").
Instead what I have to do, is define two separate qualifiers for each combination: @ApiKeyA and @ApiKeyB.
For a service with multiple dependencies, (think network client, request headers, etc.) it gets cumbersome to define these qualifiers for each combination, rather than simply combine different annotations.
Is there a reason why this explicitly disallowed?
A:
It's to simplify Dagger's implementation, and to make it faster.
| {
"pile_set_name": "StackExchange"
} |
Q:
Php flush() browser doesn't show until some data stored into cache
Well i have the following code:
<?php
while(1==1){
echo"piece<br>";
flush();
};
?>
The problem with this code is that the server doesn't send 1 line (piece<br>) at the time..
Sends 10 lines per flush or whatever..
I tried this echo"piece<br>".str_repeat("\n",4096)
but it doesn't work.I don't know what to do..
Any advice?
Edit: The code into my previous question but i can't write html :(
Edit2: I have upload my script here. Works fine only in Internet Explorer.
A:
You may be having a problem with browser-side caching. I've had this problem with Safari; using Firefox allowed me to see the data live.
If you see this with different browsers, then you may be hitting some server-side caching:
http://php.net/manual/en/function.flush.php
| {
"pile_set_name": "StackExchange"
} |
Q:
htaccess url rewrite not working properly
I know this has been asked a couple of times, but I've been wraking my brain about this for hours now and I just can't seem to figure it out.
So I have a url: http://example.com/product.php?id=123
which I'd like to rewrite to http://example.com/product/123
I have this code:
RewriteRule ^product/([^/\.]+)/?$ product.php?id=$1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([A-Za-z-\s0-9]+)$ /product.php?id=$1 [L]
And it makes the http://example.com/product/123 url work, but the images are not loaded, I guess because the php tries to find them in the /product directory, and also if I enter the orignal url it doesn't get rewritten.
So can you help me how to solve these?
Any help is much appreciated!
A:
Put this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} \s/+product\.php\?id=([^\s&]+) [NC]
RewriteRule ^ product/%1? [R=301,L]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
RewriteRule ^product/([^/.]+)/?$ product.php?id=$1 [L,QSA]
RewriteRule ^([A-Za-z\s0-9-]+)/?$ /product.php?id=$1 [L,QSA]
For problems with css/js/images use absolute path in your css, js, images files rather than a relative one. Which means you have to make sure path of these files start either with http:// or a slash /.
You can try adding this in your page's HTML header: <base href="/" />
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Mysql Update Execute Command
I am trying to execute the following command, setting "store"="result", for the row where the code column equals "code".
cursor.execute("""UPDATE pjStores SET %s=%s WHERE code=%s""", (store, result, code))
I keep receiving the following error though:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''1087'=1 WHERE code='Madness16'' at line 1")
Where the variables from the command were:
store=1087
result=1
code=Madness16
This is my first time really using mysql, so I am new to this. I've been stuck on this line for ~2 hours now, and cannot figure out what I am doing wrong. I tried the following command in mysql, and it ran correctly:
UPDATE pjStores SET `1087`=1 WHERE code='Madness16'
More code as requested:
# Step through stores
cursor.execute("SHOW COLUMNS FROM pjStores")
stores = cursor.fetchall()
cursor.execute("SELECT code FROM pjStores")
codes = cursor.fetchall()
for store in stores[1:]: # Hack to skip first entry
pj.setStore(store[0])
for code in codes:
result = pj.checkCode(code[0])
cursor.execute ("""UPDATE pjStores SET %d=%s WHERE code=%s""", (store[0], result, code[0]))
A:
You may want to try something like this instead, (assuming this is not prone to sql injection attacks - meaning the data is trusted and not user provided)
...
for code in code:
result = pj.checkCode(code[0])
query = """UPDATE pjStores SET `%s` = %%s WHERE `code` = %%s""" % store[0]
cursor.execute(query, (result, code[0]))
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculating the distance between two annotations: iOS 5
I am able to drop two annotations(source, destination) for the required points. But, now I want to determine the distance between them. I looked for the solution and came across one on :
Calculating distance between two points
but the solution:
CLLocationDistance distance = [location1 getDistanceFrom:location2];
getDistanceFrom: is deprecated in iOS 5. Please can anybody suggest me a way to do so using Google Maps API to find the actual distance between the points
While looking up for options, I came across another solution:
CLLocation *locA = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:coordinate2.latitude longitude:coordinate2.longitude];
CLLocationDistance distance = [locA distanceFromLocation:locB];
NSLog(@"DISTANCE : %f", distance/1000);
But, I am not sure whether this solution is correct. The distance that it returns is it the actual distance between source and destination by road? I tried comparing it on google maps, it approximately matches. Please verify if its the correct approach?
Thanks in advance
A:
How about distanceFromLocation:?
Source
A:
distanceFromLocation: Method work fine in my code
** Distance display in meter
CLLocation *location =[[CLLocation alloc] initWithLatitude:[@"23.039698" doubleValue] longitude:[@"72.571663" doubleValue]];
CLLocation *loc = [[CLLocation alloc] initWithLatitude:[@"23.0422" doubleValue] longitude:[@"72.5644" doubleValue]];
CLLocationDistance distanceMeter = [location distanceFromLocation:loc];
| {
"pile_set_name": "StackExchange"
} |
Q:
Azure VMSS without a public ip
I am trying to create a azure virtual machine scale set (VMSS) without a public ip for rolling upgrade policy (zero downtime). All the examples I find requires a configuration with a public IP. Even the wizard on azure forces to create a public ip. Can a VMSS with rolling upgrade be created without a public ip?
I can create a manual upgrade_policy VMSS without a loadbalancer or healthprobe without public ips. But I am unable to create a 'Rolling' upgrade_policy vmss without public ip.
A:
Q: Can a VMSS be created without a public ip? if so how?
Why not? When you create the VMSS in the Azure portal like the screenshot below, you do not need to select to use a load balancer, then it will create a VMSS without any public IP.
Update:
Take a look at the screenshot below:
Rolling upgrade policy
VMSS configuration
As you see, the VMSS still does not have the public IP, but the rolling upgrade policy is set as you want. You just need to set the monitor application health extension:
| {
"pile_set_name": "StackExchange"
} |
Q:
Realtek RTL8822CE is unable to detect WiFi networks
I bought a HP Stream 11 (Model 11-AK1035NR). I have installed Lubuntu 18.04 on a USB stick to use for it.
I have gotten the WiFi working before on this laptop after playing with it for a few hours. I had to install this again because of a crash on my USB stick. So WiFi is capable on this laptop, but I don't know exactly how I did it.
I have updated the kernel to Linux Kernel 5.2.2 with no success so far (although it does have the rtw88 which I have read is required). I've also looked around this site and saw a fix for RTL8821CE and then compiling a module and that didn't work either.
I have ran dmesg and this is what I got in terms of the WiFi hardware:
[ 14.699016] rtw_pci 0000:01:00.0: Direct firmware load for
rtw88/rtw8822c_fw.bin failed with error -2
[ 14.699025] rtw_pci 0000:01:00.0: failed to request firmware
[ 14.706008] rtw_pci 0000:01:00.0: failed to load firmware
[ 14.708202] rtw_pci 0000:01:00.0: failed to setup chip efuse info
[ 14.710395] rtw_pci 0000:01:00.0: failed to setup chip information
[ 14.720471] rtw_pci: probe of 0000:01:00.0 failed with error -22
A:
The problem is this:
Direct firmware load for rtw88/rtw8822c_fw.bin failed with error -2
Please install the latest version of linux-firmware which contains it:
wget http://security.ubuntu.com/ubuntu/pool/main/l/linux-firmware/linux-firmware_1.178.3_all.deb
sudo dpkg -i linux*.deb
Reboot.
| {
"pile_set_name": "StackExchange"
} |
Q:
What scope do JAX-RS 2 filters have?
I am using RestEasy 3.0.2 which is one of the first JAX-RS 2 implementations and run my application within a Tomcat 7. I also make use of injection in my application via WELD which is integrated with RestEasy via its CDI adaptor. Everything works fine so far.
Now, I wrote an implementation of a ContainerRequestFilter to perform authentication of incoming requests before they hit a resource. The JAX-RS standard says that injection is possible for every resource and every other JAX-RS component that is annotated with a @Provider annotation.
Here is a simplified version of my filter implementation:
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
@Inject
AuthenticationProvider authenticationProvider;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
authenticationProvider.authenticate(requestContext);
}
}
Note: AuthenticationProvider is @RequestScoped.
In general, this solution works. The components are being injected and requests are being processed as expected.
But I am still in doubt in which scope the filter is living. If it was application-scoped then this would obviously lead to "funny" concurrency issues that cannot be found with deterministic tests.
I have looked into various documentation, guides and examples but I have found none that uses injection with filters or says something about the filter scope.
A:
For RestEasy, the answer is given in the RestEasy documentation concerning CDI integration:
A CDI bean that does not explicitly define a scope is @Dependent
scoped by default. This pseudo scope means that the bean adapts to the
lifecycle of the bean it is injected into. Normal scopes (request,
session, application) are more suitable for JAX-RS components as they
designate component's lifecycle boundaries explicitly. Therefore, the
resteasy-cdi module alters the default scoping in the following way:
If a JAX-RS root resource does not define a scope explicitly, it is
bound to the Request scope.
If a JAX-RS Provider or javax.ws.rs.Application subclass does not define a scope
explicitly, it is bound to the Application scope.
Therefor JAX-RS filters annotated with @Provider are @ApplicationScoped.
The documentation also says that a JAX-RS provider can be associated with any scope by putting the proper annotation to it. So in general, the scope of a JAX-RS filter can be customized.
It is important to notice that it is safe to inject @RequestScoped objects into an @ApplicationScoped filter. This is, because CDI does not inject a reference to the actual object but to a proxy. When a method is invoked on the proxy, a separate instance of the object will be used for each request behind the scenes.
Here the according WELD documentation:
4.9. Client proxies
Clients of an injected bean do not usually hold a direct reference to
a bean instance, unless the bean is a dependent object (scope
@Dependent).
Imagine that a bean bound to the application scope held a direct
reference to a bean bound to the request scope. The application-scoped
bean is shared between many different requests. However, each request
should see a different instance of the request scoped bean—the current
one!
...
Therefore, unless a bean has the default scope @Dependent, the
container must indirect all injected references to the bean through a
proxy object. This client proxy is responsible for ensuring that the
bean instance that receives a method invocation is the instance that
is associated with the current context. The client proxy also allows
beans bound to contexts such as the session context to be serialized
to disk without recursively serializing other injected beans.
I used the following code to validate this (assume that the entityManager is produced as @RequestScoped in the example):
@Provider
public class OtherTestFilter implements ContainerRequestFilter {
@Inject
EntityManager entityManager;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Session session = (Session) entityManager.getDelegate();
System.out.println(session.hashCode());
}
}
This gives a different hash value of session for every request processed by the filter. So theory and practice match here.
| {
"pile_set_name": "StackExchange"
} |
Q:
android username password input
I need to accept values (username and password) from the user, when he clicks menu button and one of the button that says login. When the login button is clicked, a pop up should show up that accepts the values and should have an ok button.
Expecting a pop something like when we try to download an app from apple store (iphone)
Could some one please guide me how to do this. Also... this menu is to be visible for a MapActivity class which implements LocationListener
thanks
A:
This tutorial should be enough for you to get started, just change the custom dialog XML layout to two edit texts.
Tutorial
| {
"pile_set_name": "StackExchange"
} |
Q:
Do hotels in general expect that guests will take the toiletries provided with them?
When I have moved the shampoos and soaps from where they are placed in the room in the hotel, even if I clearly have not used it all up the people who clean the room will provide additional supplies.
Does this mean that hotels expect that the guests will use or take these types of items with them (or even provide them as complimentary items), or is it just a procedural task to replace them everyday?
A:
There is no straight answer to this question. Basically, every hotel/brand has its own policy when it comes to amenities. Then, inside the hotel, every housekeeper will eventually manage its inventory and use it differently.
Then, from my own experience, what I have seen :
1/ You'll most of the time get new ones if you have started using the ones available initially. This is especially true for shampoos and shower gel. For soap, it is more random and depends on the soap size.
2/ When amenities are high grades (like famous beauty brands), you less frequently get new ones. This is because their costs is obviously higher. We should take here into consideration the fact that in some rooms/suites, the value of amenities can sometimes cross 50 €...
3/ What I have seen is that every time you ask for new amenities, you get those. Never got a negative answer on this.
4/ If you have left the items unused, then you'll rarely get additional ones, especially if they haven't been moved.
And yes, hotels expect that you'll take the items with you, especially if those are high grade. This is what most of the guests are doing. Few reasons for that :
1/ People tend to think that the quality of hotel amenities is usually better than what they can buy at the supermarket. This is sometimes right, sometimes wrong (especially for hair conditioner).
2/ People see this as a kind of gift/souvenir that they are happy to bring back with them.
3/ Hotels market those in a way that you'll take them. This is a way for them to introduce themselves in your bathroom and make sure you remember about the good time you had at their hotel. It helps building branding. This is also true for beauty product brands working with hotels.
| {
"pile_set_name": "StackExchange"
} |
Q:
upgrading database in android studio not working
I am trying to updgrade the sqlite version number from 1 to 2 but onupgrade method is not getting called.
do i have to delete application in the device and then install the application to test it ?
Only method which get called is DatabaseHelper and onCreate
No other method get called.
In DatabaseHelper.java file
private static final int DBVersion = 1; // I had change this value to 2.but it is not working.
public DatabaseHelper(Context context, CursorFactory cf) {
super(context, DBName, cf, DBVersion);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE_Table);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
//This is not called.If it called i will add the changed here
}
another class for dataprovider.java
@Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext(), null);
return true;
}
A:
using :-
@Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext(), null);
SqliteDatabase db = dbHelper.getWritableDatabase(); //<<<<<<<<<<<
return true;
}
attempts to open the database and thus onCreate/onUpgrade would be called.
- onCreate only if the database does not exist.
- onUpgrade only if the database exists AND the specified version number is greater than the database version stored in the database.
That is when instantiating the Database Helper (subclass of SQLiteOpenHelper) no attempt is made to open the database.
The attempt to open the database is only made when the SQLiteDatabase's getWritableDatabase (or getReadableDatabase) are called. Both attempt to open the database. Noting that getWritableDatabase or getReadableDatabase may well be called implicitly.
Note the above does not include directly using the SQliteDatabase's OPEN methods.
Alternative Fix
I personally tend to force the open when constructing the database helper by using :-
public DatabaseHelper(Context context, CursorFactory cf) {
super(context, DBName, cf, DBVersion);
this.getWritableDatabase();
}
I tend to save the returned SQLiteDatabase into a class variable and then use that rather than using this.getWritableDatabase() in the underlying methods.
| {
"pile_set_name": "StackExchange"
} |
Q:
All the group formatting available in Mathematica
I was wondering how many pre-defined group formatting style there is in Mathematica. From Format -> Style, one see that we can go from Title (for Alt+1) to Subsubsection (Alt+6). However, this does not seem to be exhaustive. This is because, if I press Tab on a line created from any of those formattings (from Alt+1 to Alt+6), then I can automatically "move down one level" each time. However, from Subsubsection, it seems that I can still go 2 more levels down, after which Tab does its "normal" job.
Are these 2 additional formattings somewhere to be found in some documentation? Are they in any way "special" and can I assign keyboard shortcuts for them as for the other ones?
A:
The option StyleKeyMapping controls "Tab" and "Backspace" does to the style (AFAIK, it is not documented).
Row[Table[Most@NestWhileList["Tab" /. CurrentValue[{StyleDefinitions, #, StyleKeyMapping}]&,
i, Not[StringMatchQ[#, "Tab"]] &] // Column[Style[#, #] & /@ #] &,
{i, {"Chapter", "Title", "Section", "Item", "ItemParagraph", "ItemNumbered"}}], Spacer[10]]
The styles "Subsubsubsection" and "Subsubsubsubsection" are not listed in the Format >> Style menu.
The StyleKeyMapping option value for some "*section" styles are:
CurrentValue[{StyleDefinitions, "Subsection", StyleKeyMapping}]
{"Tab" -> "Subsubsection", "Backspace" -> "Section",
KeyEvent["Tab", Modifiers -> {Shift}] -> "Section"}
CurrentValue[{StyleDefinitions, "Subsubsection", StyleKeyMapping}]
{"Tab" -> "Subsubsubsection", "Backspace" -> "Subsection",
KeyEvent["Tab", Modifiers -> {Shift}] -> "Subsection"}
CurrentValue[{StyleDefinitions, "Subsubsubsection", StyleKeyMapping}]
{"Tab" -> "Subsubsubsubsection", "Backspace" -> "Subsubsection",
KeyEvent["Tab", Modifiers -> {Shift}] -> "Subsubsection"}
To see the full style definitions, you can use
CurrentValue[{StyleDefinitions, "Subsubsubsection"}]
{CellMargins -> {{66, Inherited}, {2, 10}},
StyleKeyMapping -> {"Tab" -> "Subsubsubsubsection",
"Backspace" -> "Subsubsection",
KeyEvent["Tab", Modifiers -> {Shift}] -> "Subsubsection"},
CellGroupingRules -> {"SectionGrouping", 60},
PageBreakBelow -> False, LanguageCategory -> "NaturalLanguage",
CounterIncrements -> "Subsubsubsection",
CounterAssignments -> {{"Subsubsubsubsection", 0}, {"Item",
0}, {"Subitem", 0}, {"Subsubitem", 0}, {"ItemNumbered",
0}, {"SubitemNumbered", 0}, {"SubsubitemNumbered", 0}},
MenuSortingValue -> None, FontFamily -> "Source Sans Pro",
FontSize -> 15, FontWeight -> "Bold",
FontColor -> RGBColor[0.778286411841001, 0.4230563820859083, 0.16115053025101092`]}
Similarly for 'Subsubsubsubsection".
| {
"pile_set_name": "StackExchange"
} |
Q:
C - program compiling, but unable to provide arguments
I'm on a Mac and in terminal I'm compiling my program
gcc -Wall -g -o example example.c
it compiles (there are no errors), but when I try to provide command line arguments
example 5 hello how are you
terminal responds with "-bash: example: command not found"
how am supposed to provide the arguments I want to provide after compiling?
A:
Run it like this with path:
./example 5 hello how are you
Unless the directory where the example binary is part of the PATH variable, what you have won't work even if the binary you are running is in the current directory.
A:
It is not a compilation issue, but an issue with your shell. The current directory is not in your PATH (look with echo $PATH and use which to find out how the shell uses it for some particular program, e.g. which gcc).
I suggest testing your program with an explicit file path for the program like
./example 5 hello how are you
You could perhaps edit your ~/.bashrc to add . at the end of your PATH. There are pro and conses (in particular some possible security issues if your current directory happens to be sometimes a "malicious" one like perhaps /tmp might be : bad guys might put there a gcc which is a symlink to /bin/rm so you need to add . at the end of your PATH if you do).
Don't forget to learn how to use a debugger (like gdb). This skill is essential when coding in C (or in C++). Perhaps consider also upgrading your gcc (Apple don"t like much its current GPLv3 license so don't distribute the recent one; try just gcc -v and notice that the latest released GCC is today 4.8.1).
| {
"pile_set_name": "StackExchange"
} |
Q:
Itemprop errors
I checked my blog-article' page on validator.w3.org and it keeps show this errors:
Error 1:
The **itemprop** attribute was specified, but the element is not a property of any item.
My blog code:
<h1 class="blogtitle entry-title" itemprop="itemReviewed" itemscope itemtype="http://schema.org/Thing">↩
<span itemprop="name">The article title</span>↩
</h1>
Error 2:
The itemprop attribute was specified, but the element is not a property of any item.
The code:
<h1 class="blogtitle entry-title" itemprop="itemReviewed" itemscope itemtype="http://schema.org/Thing">↩
<span itemprop="title">Article title</span>
</h1>
So in that code I have 2 itemprop errors.
Then Error 3:
The itemprop attribute was specified, but the element is not a property of any item.
The code:
<a href="http://www.website.com/author/Siteauthors" itemprop="author" target="_blank"><span class="vcard author author_name"><span class="fn">Siteauthors</span></span></a>
So How Can I solve this errors? I want my page to have no errors, and only these errors still! I read some articles about this "itemtrop" but I didn't understand much!
Any help is welcome!!!!!
A:
You have to explicitly provide a property (and a type for the property). To do so, you need to add an itemtype to your <html> tag.
In your specific instance, you need to change:
<html lang="en-US">
to:
<html lang="en-US" itemscope itemtype="http://schema.org/WebPage">
And it will successfully validate.
In Schema.org, everything is a Thing. Thing has many child types, listed under "More specific Types". Start there and choose the most specific type for your content. In this example, I chose WebPage, but you could choose any type.
Credit to: https://stackoverflow.com/a/29124838/836695
| {
"pile_set_name": "StackExchange"
} |
Q:
Update Generic list using LINQ
I am looking a way to update index property of generic list Item.
For example I have a class:
public class ItemInfo
{
public int SRNO { get; set }
public Name{ get; set }
}
now I have List<ItemInfo> myList with number of items.
and want to update ItemInfo.SRNO of each Item with incremented value
like if list item has 10 items then "SRNO" should be update like
1
2
.
.
.
10
A:
Actually you don't need LINQ like this:
infoList.Select((info, i) => { info.SRNO = i + 1; return info });
or
Enumerable.Range(0, infoList.Count).Select(i =>
{
var info = infoList[i];
info.SRNO = i+1;
return info;
});
Use simple for-loop:
for (int i = 0; i < infoList.Count; i++)
{
info[i].SRNO = i + 1;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento 2 Customers not displayed in admin grid
When a customer registers, the details are loaded to the database and the customer is able to login and do the purchases. But in the Customer -> All Customers I am not seeing any registered customers. Please help. I have attached the screenshots in this link.
A:
It seems that your customer_grid is not indexing properly. Run the following commands in the root of your magento folder.
bin/magento indexer:reset customer_grid
Then run the indexer:reindex on customer_grid again
bin/magento indexer:reindex customer_grid
Finally clear the cache
Hope this works
| {
"pile_set_name": "StackExchange"
} |
Q:
leaflet Property-Routing-does-not-exist-on-type-typeof-import
I have made a post but not getting any responses. Im new to leaflet and dont know whats going on or why. I believe I added everything the documents say to add but I'm still getting the error.
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
import L from 'leaflet';
ERROR TypeError: Cannot read property 'control' of undefined
My Code here:
var polylineRouteB = L.Routing.control({...});
A:
In order your L.Routing class not to be undefined you need to get a reference to the map and use it there when map is loaded but before this step you need to configure angular.json to search your assets folder for the markers icons otherwise this issue arises.
import {
latLng,
tileLayer,
Icon, icon, Marker
} from 'leaflet';
import 'leaflet';
import 'leaflet-routing-machine';
declare let L;
...
// Override default Icons
private defaultIcon: Icon = icon({
iconUrl: 'assets/marker-icon.png',
shadowUrl: 'assets/marker-shadow.png'
});
ngOnInit() {
Marker.prototype.options.icon = this.defaultIcon;
}
onMapReady(map: L.Map) {
L.Routing.control({
waypoints: [
L.latLng(57.74, 11.94),
L.latLng(57.6792, 11.949)
],
routeWhileDragging: true
}).addTo(map);
}
Template
<div style="height: 800px;"
leaflet
[leafletOptions]="options"
(leafletMapReady)="onMapReady($event)">
</div>
Demo
Note also that his library does not permit unlimited requests to the server thus it returns frequently 429 HTTP responses.
| {
"pile_set_name": "StackExchange"
} |
Q:
Want a deeper understanding of lists
Here's my sample code for a programming problem asking to split a string and sort the individual words to avoid duplicates. I know that this code is 100% correct, but I'm not really sure what the purpose of lst = list() line of code is?
How does the program know to put the file romeo in the list?
fname = input("Enter file name: ")
romeo = open(fname)
lst = list()
for line in romeo:
line = line.rstrip()
line = line.split()
for e in line:
if e not in lst:
lst.append(e)
lst.sort()
print(lst)
A:
The purpose of lst = list() is to create an instance of list called lst.
You could also replace it by
lst = []
it's exactely the same.
The line lst.append(e) is filling it. Here more about the append method
| {
"pile_set_name": "StackExchange"
} |
Q:
Output div contents and styling to image
I have a type of word cloud that I developed. Its really just a simple database search result that applies random CSS styling (size, color, vertical layout, etc) to keywords to make it look pretty inside a div or single cell table. These keywords get retrieved via a PHP/mySQL function.
I would like to be able to output that DIV/table cell's (whichever would work better) contents along with the CSS styling to an image file. I've seen posts suggesting HTML2Canvas but haven't had any luck getting the search results with the CSS to show up in the image and not even sure if its possible in this case.
Any ideas to point me in the right direction?
Thanks,
A:
You could use an html to pdf script, like this one, and then use the imagick php function to convert that to an image.
Source: http://buffernow.com/html-to-image-php-script/
| {
"pile_set_name": "StackExchange"
} |
Q:
Python delete from date column row contains string
I have joined two dataframes: one containing annual date and another created using date range for monthly date.
After joining two dataframes, there are some duplicate date values for which I assigned suffix '_dup'.
Now, how do I drop the rows containing '_dup' values. My dataframe is as below:
Now, I used following code to remove/drop the date row containing '_dup'
for i in range (117):
if df5.iloc[i,0].str.contains ('_dup'):
del df5.loc[i,0]
I get error :
AttributeError Traceback (most recent call last)
<ipython-input-171-ae80d413249e> in <module>()
1 for i in range (117):
----> 2 if df5.iloc[i,0].str.contains ('_dup'):
3 del df5.loc[i,0]
AttributeError: 'str' object has no attribute 'str'
I also tried the code:
df5[~df5.index.str.contains("_dup")]
It is giving error that:
AttributeError: Can only use .str accessor with string values (i.e. inferred_type is 'string', 'unicode' or 'mixed')`
A:
Your issue is that df5.iloc[i,0] accesses a single str datapoint in the column, so you cannot apply the str function to it again. You can apply the str.contains function to the whole column at once like so:
df = df.loc[~df["col_name"].str.contains("dup")]
However the str.contains function won't work if there are mixed datatypes in the column. In that case you would need to convert the type first (df["col_name"] = df["col_name"].astype(str)). Or if your duplicate values were the only datapoints with string type you can just filter out based on type like so:
df.loc[~df["col_name"].apply(lambda x: isinstance(x, str))]
| {
"pile_set_name": "StackExchange"
} |
Q:
Intuitively, why is compounding percentages not expressed as adding percentages?
I pursue only intuition; please do not answer with formal proofs. I already know the theoretical reason: because each percentage expresses a different base. $1.$ But why not intuitively?
My problem: Whenever adding percentages, I am always initially tempted to add them as cardinal numbers, before resisting myself and spending $\geq 5$ minutes recollecting the following algebra and surmounting the temptation, all of which reveal chasms in my comprehension.
$\bbox[5px,border:2px solid gray]{ \text{ Optional Reading and Supplement: } }$
If the price of apricots ($a$) increases by $p_a$ and the price of cherries ($c$) increases by $p_c$, where $0 \le p_a,p_c \leq 1$; then the $\color{green}{ \text {Correct new price =} (1 + p_a)a + (1 + p_c)c. \tag{2}}$
But adding the percentages as cardinal numbers produces the: $\color{darkred}{ \text { Incorrect new price =} (1 + p_a + p_c)( a + c) = \color{green}{(1 + p_a)a + (1 + p_c)c} \color{#FF4F00}{ + p_ac + p_ca.} \tag{3}}$
The existence of the 2 orange terms proves $2 \neq 3$, but do not reveal the intuition.
PS: This question is motivated by the first sentence of this quote in this question.
A:
Say something costs $\$100$ and the price goes up by $50\%$.
$50\%$ of $\$100$ is $\$50$, so the new price is $\$150$.
Then it goes up by $50\%$ again.
$50\%$ of $\$150$ is $\$75$, so the new price is $\$225$.
The point is that the second time, you're taking $50\%$ of a larger quantity.
A:
This answer is based on the premise that the motivation behind
the question is to explain the fallacy described
in this question on philosophy.SE.
One point of confusion is the use of the word price.
In general, when we must spend money on several resources (flour, labor, utilities, and rent) to make a loaf of bread, the price of a loaf is
not determined by the prices of the resources used in its production.
Rather, it is determined by the cost of those resources,
which is determined by both the price of each resource and the
quantity of each resource consumed in making the loaf.
For example, if rent is $\$2000$ per month, that does not mean the
baker must charge more than $\$2000$ for one loaf in order to make a profit.
Rather, if the bakery produces $10000$ loaves each month, the baker could
accurately say that each loaf cost $\$0.20$ of rent to produce,
in addition to other costs.
So, assuming the only things the baker has to pay for are for flour, labor, utilities, and rent, the baker's cost to make a loaf of bread is
$$ B = F \cdot Q_F + L \cdot Q_L + U \cdot Q_U + R \cdot Q_R, $$
where $F$, $L$, $U$, and $R$ are the prices of flour, labor, utilities, and rent, and $Q_F$, $Q_L$, $Q_U$, and $Q_R$ are the quantities of
each of those resources that the baker has to expend on each loaf.
Now, assuming the amount of each resource per loaf remains constant,
it is true that a $10$ percent increase in the price of one resource
corresponds to a $10$ percent increase in the cost of that resource.
For example, if the price of flour goes up $10$ percent, from $F$ to
$(1 + 0.10)F$, the cost of flour per loaf also increases $10$ percent,
because
$$ ((1 + 0.10)F) \cdot Q_F = (1 + 0.10)(F \cdot Q_F). $$
Of course, if we just say "cost" instead of price when describing
the baker's expenses, we bypass all of these complications. So let's do that.
What happens, then, when the costs of all these items increase?
The baker was writing checks to four different groups of people before
-- the flour merchants, his laborers, the utility companies, and his landlord -- and he is still writing checks to the same four groups of people.
The amount of each group of checks has merely increased.
So if the baker was paying $\$600$ to the flour merchants each month before,
and flour goes up $10$ percent, now he must pay the flour merchants
$\$660$ each month.
If the baker was previously paying his laborers a total of
$\$5000$ per month, and labor rates increase $20$ percent,
he must now pay his laborers $\$6000$ per month.
That is, for flour and labor, the new costs add up to
$$ (1 + 0.10) 600 + (1 + 0.20) 5000, $$
which are analogous to the terms $(1 + p_a)a + (1 + p_c)c$
if we say that $a$ and $c$ were the previous
total costs of apricots and cherries
we bought, rather than their unit prices.
Similarly, if utilities and rent were $\$200$ and $\$2000$, respectively,
and these go up $10$ percent each, the baker's total costs after
all these increases are
\begin{align}
(1 + 0.10) 600 + (1 + 0.20) 5000 + (1 + 0.10) 200 + (1 &+ 0.10) 2000 \\
&= 660 + 6000 + 220 + 2200 \\
&= 9080.
\end{align}
There are no other added costs. When we say labor increased $20$ percent,
that $20$ percent accounts for all of the extra money the baker must
pay his laborers, and likewise the percentage increases in each other cost
account for all the extra money the baker must pay each of the other
three groups of people.
Given all of that, what would it mean to take the $10$-percent increase
in flour and multiply it by the cost of labor? This would be
$0.10 \cdot \$5000 = \$500$ in our example; but to whom does the
baker pay this extra $\$500$?
If each of the baker's costs individually had gone up $50$ percent,
then indeed his cost per loaf would also have increased $50$ percent.
Here's how. Before the increase, the baker's total costs were
$$ 600 + 5000 + 200 + 2000 = 7800.$$
That's $\$0.78$ per loaf (since the bakery produces $10000$ loaves).
After $50$-percent increases in flour, labor, utilities, and rent,
all occurring in the same month, the baker's costs would be
$$ 900 + 7500 + 300 + 3000 = 11700,$$
which is $1.17$ per loaf, which is indeed a $50$-percent increase.
But of course that's not what happened at all, and the baker
either is not paying attention to his own accounts
(or is trying to fool us) when he says it is what happened.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the point (no-pun) of XPointer ranges?
XPointer spec talks about ranges that, as far as I understand, mean you can target two nodes in an XML document and get everything in between them or something. Do people really use this? What is it useful for?
A:
I have never used this, actually. But when I work with XSLT, I quite often find myself needing a way of expressing a range (i.e., "select all nodes from xpathX to xpathY") and a bit depending on the structure, it is quite hard to do this correct. Like I said, I don't use it, but if I could apply XPointer in my projects, I would use it if this feature was implemented.
You ask what it is useful for. A simple example: consider a log file. You can simply request a range from point X to Y (i.e., a date range), which can be far easier then the classical approach with XPath. I.e., it is easier and clearer to express.
| {
"pile_set_name": "StackExchange"
} |
Q:
Acrescentando elementos a um dicionário somente se a chave não existir
Tenho que criar uma função que acrescenta os dados de um novo aluno em um dicionário.
Entrada:
alunos: dicionario com os dados dos alunos
nome: nome do aluno (chave)
notas: lista com as notas de um aluno (valor)
Retorno:
A função deve retornar o dicionário com as modificações realizadas*
Observação: Caso a chave já exista no dicionário, deve retornar o dicionário sem nenhuma alteração.
Esse é meu código, que retorna "já cadastrado", sendo que o valor foi inserido pela primeira vez:
alunos = dict()
def adicionar_aluno ( alunos , nome , notas ):
alunos[nome]=[notas]
if nome in alunos:
return 'já cadastrado'
else:
return alunos
nome = input ( 'nome: ' )
notas = float ( input ( 'nota: ' ) )
a=adicionar_aluno(alunos, nome, notas)
print(a)
A:
Isso acontece por causa da ordem em que as coisas são feitas (e que poderia ser detectado fazendo um teste de mesa).
Primeiro você adiciona o aluno no dicionário:
alunos[nome]=[notas]
Depois você verifica se esse aluno está no dicionário:
if nome in alunos:
Ou seja, esse if sempre será verdadeiro, porque o aluno que você está verificando já foi adicionado na linha anterior.
O que você deve fazer é cadastrar o aluno somente se ele não existir no dicionário (ou seja, dentro do else):
def adicionar_aluno ( alunos , nome , notas ):
if nome in alunos:
return 'já cadastrado'
else:
alunos[nome] = [notas]
return alunos
Se bem que os requisitos dizem que deve sempre retornar o dicionário, então basta modificar a condição para só acrescentar o aluno se ele não existir:
def adicionar_aluno ( alunos , nome , notas ):
if nome not in alunos:
alunos[nome] = [notas]
return alunos
Ou seja, se o aluno não existe no dicionário, adiciona (repare no not in, que verifica se o aluno não está no dicionário). Se ele já existir, não precisa fazer nada (por isso nem precisa do else).
No final, retorne o dicionário. Se ele entrou no if, ele terá o novo aluno. Se ele não entrou no if, será retornado sem modificações.
Só achei estranho a sua função retornar uma mensagem ou o próprio dicionário. Talvez seja melhor ela retornar True ou False, indicando se o aluno foi ou não cadastrado. Não precisa retornar o próprio dicionário porque o mesmo é modificado dentro da função:
alunos = dict()
def adicionar_aluno ( alunos , nome , notas ):
if nome in alunos:
return False
else:
alunos[nome] = [notas]
return True
nome = input('nome: ')
nota = float(input('nota: ' ))
if adicionar_aluno(alunos, nome, nota):
print(f'aluno {nome} adicionado')
else:
print(f'aluno {nome} já cadastrado')
| {
"pile_set_name": "StackExchange"
} |
Q:
a tag and span vertical alignment issue
Iam having a issue and dont know why, i already google it, tryed several solutions and i cant resolve. Hope you guys can help me with it.
At this website, http://armada-lusitana.org/entry/
Bottom of page, "Changelog" link, then a span next to it, its supose that span do vertical-align: middle.
Its not working, but if i delete the "changelog" full "a" tag from the DOM, it works like a charm, so i was thinking it is something to do with the "a" messing with the "span".
Thank you for your time and answers.
A:
You are only applying the vertical-align to <span>s, so you should wrap the <a> inside a <span> as you do for your images:
<span><a>Changelog</a></span>
<span><img src="img.jpg"></span>
<span><img src="img.jpg"></span>
| {
"pile_set_name": "StackExchange"
} |
Q:
Restrict user login on kernel level in Linux
It is possible (and rationally?) to restrict login for any user in a system after some event (for example logout of some user) by kernel haking? May be other ways are exists?
If it is possible, which part of kernel sources needs to be modified?
A:
This should do the trick:
touch /etc/nologin
Not wise to touch the kernel for this type of problem. See man nologin. The "root" user can still log in.
| {
"pile_set_name": "StackExchange"
} |
Q:
css3 animation on click
The following zip contains the website html and required files: http://dl.getdropbox.com/u/4281191/login.zip
When you hover the html (html:hover) you see a animation that transforms the container into a loginbox, I want that to happen when I click on "Login" at the "Hello, Guest" menu instead.
Anyway to get this done? I'm new to js...
Additional info:
the css is inside the html,
and the css3 animation gets triggered by:
html:hover id/class {
property: value;
}
Thanks for any help!
And I can't vote at comments since I don't have enough reputation...but I could do some free design work for the person who helps me ^^
A:
I still don't know much about animations, but for what matters here, you could use something like the .classname:active or .classname:focus selectors. But as soon as you click something inside it (e.g. a text box), the style will disappear.
So, for this, it really depends. Do you just want a menu that has links that take the user to another page (for this case, you'll be fine) or do you want a login form (for this case, forget it, use jquery)?
For today and future reference, save this link because it'll be your best friend:
http://www.w3.org/TR/selectors/#selectors
Update
Yes, I hovered but I didn't look at the code. I looked now and, unfortunately, the answer is no. You can't affect some upper level object like that using CSS.
For that use jQuery. The simpler way would be use jQuery to add a class to the element you want to change (like $("#the-object-id").addClass('class-name')). To keep the effect add the duration argument. Read this page about Adding a class using jQuery.
| {
"pile_set_name": "StackExchange"
} |
Q:
Most Supported Java Date/Time Class
I have an issue with date/time age calculations on Android Studio. I have used calander instance and it seemed to work for the most part but every now and then it seems to be Inaccurate.
I switched to LocalDate which looks way cleaner but, as far as I can tell through my research is only supported by API 26 and higher. I think Joda Time has the same issue.
My question is this: What is the best method to calculate the elapsed time between two dates that is the most accurate (factoring in leap years, months with different number of days, etc) and is supported by lower API versions (ie 17 and up)?
I have been researching and it appears that the answer may be the basic calander instance but then I come back to reliability and accuracy issue. Any input would be greatly appreciated.
A:
tl;dr
Use the ThreeTenABP library in work with earlier versions of Android.
Period.between(
LocalDate.of( 2017 , Month.JUNE , 23 ) ,
LocalDate.now( ZoneId.of( “Europe/Paris” ) )
)
Use java.time
The original date-time classes bundled with the earliest versions of Java were well-intentioned but are an awful ugly confusing mess. Always avoid Date, Calendar, etc.
Joda-Time was an amazing industry-leading effort to make a serious robust date-time framework. Its principal author, Stephen Colebourne, went on to use the lessons learned there to produce its successor, the java.time classes built into Java 8 & 9, defined by JSR 310. The Joda-Time project is now in maintenance mode, and migration to java.time is advised.
Much of the java.time functionality is back-ported to Java 6 and Java 7 in the ThreeTen-Backport project. That project includes a utility class for converting to/from the legacy types so your new code may interoperate with old existing code. Further adapted for earlier Android in the ThreeTenABP project.
For example, on the Java platform you would call:
java.time.LocalDate localDate = java.time.LocalDate.of( 2018 , 1 , 23 ) ; // January 23rd, 2018.
…whereas on early Android using the ThreeTen-Backport/ThreeTenABP projects you would call:
org.threeten.bp.LocalDate localDate = org.threeten.bp.LocalDate.of( 2018 , 1 , 23 ) ; // January 23rd, 2018.
Span of time
To calculate elapsed time as a span of time unattached to the timeline, use either:
Period for years, months, days
Duration for hours, minutes, seconds, and fractional second in nanoseconds.
More simply put…
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
| {
"pile_set_name": "StackExchange"
} |
Q:
CakePHP 3 - Como fazer rollback
No cakephp 2 nos os saves de forma transacional com $data_source->begin(); ,$data_source->commit();, ou $data_source->rollback();.
Então quando eu precisava inserir em mais de uma tabela, e os dados fosse dependentes caso ocorresse qualquer erro eu fazia o rollback
lendo a documentação do cakephp 3, vi mudou o processo, mas eu não consegui reproduzir.
No trecho de código abaixo depois de salvar no model Users, eu quero salvar o Tokens, mas caso ocorra um erro no Tokens quero fazer rollback no Users.
por exemplo, a entidade Tokens é obrigatório ter o campo "token", quando entrar na exception quer fazer rollback e não registrar no banco o User.
Mas quando faço o Users sempre é salvo no banco.
$connection = ConnectionManager::get('default');
$return = $connection->transactional(function ($connection) use($json) {
try {
$obj = $this->Users->newEntity();
$obj = $this->Users->patchEntity($obj, $json);
$User = $this->Users->save($obj);
//$token["token"] = $json["google_token"];//forçando erro
$token["user_id"] = $User->id;
$obj = $this->Tokens->newEntity();
$obj = $this->Tokens->patchEntity($obj, $token);
$Token = $this->Tokens->save($obj);
$return["success"] = true;
$return["message"] = "Cadastrado com sucesso";
$return["data"] = $User;
//fazer o commit
} catch (\Exception $e) {
$return["success"] = false;
$return["data"] = $e->getMessage();
$return["message"] = "Falha ao cadastrar ";
//fazer o rollback
}
return $return;
});
A:
Fui sabotado pelo MySql Workbench.
Ele gerava as tabelas com a engine MyISAM que não possui suporte ao rollback, mesmo estando marcado como InnoDB.
Resolvendo isso funcionou.
| {
"pile_set_name": "StackExchange"
} |
Q:
asp.net Login control: what's wrong?
I'm working on ASP.NET app and in the master page C# code I want to access the login control, so I have the following code:
Login login = new Login();
login = this.Master.FindControl("login") as Login;
But, I get exception " Object reference not set to an instance of an object" when this line
login = this.Master.FindControl("login") as Login;
is executed.
I can't see what can be wrong...
Thanks.
A:
If the code mentioned above is in the master page, then try removing the Master portion of the code...
for example
login = this.FindControl("login") as Login;
The reason why this would work is because the current master page, is not embedded within another Master page. Therefore, you'll get an "object not set" error when trying to access the master's Master page (i.e. this.Master.FindControl())
Just wondering, if this is the case, is there a reason why you can't access the control by its name?
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.