text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Consulta SQL que genere filas dependiendo de cantidad
Tengo una tabla productos en MySQL, que guarda el código de barras y la cantidad de Stock de un producto.
Lo que necesito es generar una consulta SQL de manera a que se puedan repetir las filas con cierta información de un sólo producto dependiendo de la cantidad que tenga en Stock.
Serían tipo filas ficticias. Por ejemplo, si yo tengo 35 productos en stock, la consulta me debería devolver 35 veces el código de barra del producto como resultado.
La tabla productos tiene la siguiente estructura:
id_prod codbar_prod des_prod pre_com stock_act
1 27478255368371 ASDFADSFADFS 50000 10
2 27478255368372 ASDESCRIPCION 150000 116
Si por ejemplo necesito saber el código de barra del producto 1. Realizaría una consulta de la siguiente manera:
SELECT codbar_prod FROM productos WHERE id_prod=1;
Me devuelve lo siguiente:
codbar_prod
--------------
27478255368371
De esta manera funciona, pero lo que necesitaria es que dicho resultado de consulta se repita teniendo en cuenta la cantidad en stock en este caso; sería por ejemplo un resultado similar al siguiente:
codbar_prod
--------------
27478255368371
27478255368371
27478255368371
27478255368371
27478255368371
27478255368371
27478255368371
27478255368371
27478255368371
27478255368371
A:
@cnbandicoot tiene razon, lo duplicas en tu aplicación, en caso de que no quieras hacerlo así, lo que debes es generar vistas solo con números, de la siguiente forma
-- Generas 16
CREATE VIEW generator_16
AS SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL
SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL
SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL
SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL
SELECT 15;
-- Generas 256
CREATE VIEW generator_256
AS SELECT ( ( hi.n * 16 ) + lo.n ) AS n
FROM generator_16 lo, generator_16 hi;
-- Generas 4096
CREATE VIEW generator_4k
AS SELECT ( ( hi.n * 256 ) + lo.n ) AS n
FROM generator_256 lo, generator_16 hi;
-- Generas 65536
CREATE VIEW generator_64k
AS SELECT ( ( hi.n * 256 ) + lo.n ) AS n
FROM generator_256 lo, generator_256 hi;
-- Generas 1048576
CREATE VIEW generator_1m
AS SELECT ( ( hi.n * 65536 ) + lo.n ) AS n
FROM generator_64k lo, generator_16 hi;
Obtenido de la siguiente liga https://stackoverflow.com/questions/10423767/sql-repeat-a-result-row-multiple-times-and-number-the-rows/10432083#10432083
Al realizar tu consulta
SELECT codbar_prod
FROM productos p
INNER JOIN generator_64k g ON g.n BETWEEN 1 AND p.stock_act
WHERE id_prod=1
| {
"pile_set_name": "StackExchange"
} |
Q:
What does the : mean in rails before a variable name?
For example, : symbol - I'm trying to work out what the : means, and how it differs, say, for example, from @ and also from no symbol whatsoever.
If there's a guide that would be really helpful!
A:
It's a symbol, which is a Ruby language construct.
Symbols are similar to strings, but this blog post explains the details.
@ means an instance variable on the class: it's basically a variable that's shared among all methods on an instance of a class. It has no relation to :.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there an option to run second time the same program in Qt?
I'm creating simple online game in Qt Creator. I've created server project which analyse received data and take decisions. Also I created player project which sends requests to server for permission to move, shoot etc. Player project should be universal for Player 1 and Player 2.
Is there an option to run player project twice in Qt Creator?
I need it to test how server and player project behaves when second player connects.
A:
I'm using Qt Creator 4.3.1: You can do that in Tools > Options... > Build & Run. Under the General tab, set the "Stop applications before building:" to "None"
A:
Open 3 Qt Creators, 1 for the server 2 for the players and then run all of them. I have made a server-client multiplayer game in Qt and that is how i tested it.
For every client(player) open a Qt Creator.
EDIT:
You can also create release versions and start them, but you waste a lot of time creating a release version every time you want to debug.
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento2 - where the admin console user preferences stored?
I have logged into the admin panel of Magento 2, gone to products->catalog and have set the 'per page' limit to 900.
My Magento instance can't return 900 records in one page so it crashes, and a div with a spinner remains active after an error message appears saying 'Attention: Something went wrong' - so I can't revise the 900 to a more suitable number.
I've tried clearing cache/client cookies, etc - but nothing is happening. I can't seem to find where the catalog product grid limit value is being stored.
Please if someone can assist, it would be good.
Thanks,
A:
It seems your grid preference is saved in bookmark table
Go to your database and find ui_bookmark table
find the namespace entry with product_listing and remove current or both current and default. Don't worry magento will generate the default again runtime
| {
"pile_set_name": "StackExchange"
} |
Q:
AttributeError: module 'time' has no attribute 'clock' in Python 3.8
I have written code to generate public and private keys. It works great at Python 3.7 but it fails in Python 3.8. I don't know how it fails in the latest version. Help me with some solutions.
Here's the Code:
from Crypto.PublicKey import RSA
def generate_keys():
modulus_length = 1024
key = RSA.generate(modulus_length)
pub_key = key.publickey()
private_key = key.exportKey()
public_key = pub_key.exportKey()
return private_key, public_key
a = generate_keys()
print(a)
Error in Python 3.8 version:
Traceback (most recent call last):
File "temp.py", line 18, in <module>
a = generate_keys()
File "temp.py", line 8, in generate_keys
key = RSA.generate(modulus_length)
File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/PublicKey/RSA.py", line 508, in generate
obj = _RSA.generate_py(bits, rf, progress_func, e) # TODO: Don't use legacy _RSA module
File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/PublicKey/_RSA.py", line 50, in generate_py
p = pubkey.getStrongPrime(bits>>1, obj.e, 1e-12, randfunc)
File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 282, in getStrongPrime
X = getRandomRange (lower_bound, upper_bound, randfunc)
File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 123, in getRandomRange
value = getRandomInteger(bits, randfunc)
File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 104, in getRandomInteger
S = randfunc(N>>3)
File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 202, in read
return self._singleton.read(bytes)
File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 178, in read
return _UserFriendlyRNG.read(self, bytes)
File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 129, in read
self._ec.collect()
File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 77, in collect
t = time.clock()
AttributeError: module 'time' has no attribute 'clock'
A:
From the Python 3.8 doc:
The function time.clock() has been removed, after having been deprecated since Python 3.3: use time.perf_counter() or time.process_time() instead, depending on your requirements, to have well-defined behavior. (Contributed by Matthias Bussonnier in bpo-36895.)
A:
time.clock() was removed in 3.8 because it had platform-dependent behavior:
On Unix, this returns the current processor time (in seconds)
On Windows, this returns wall-clock time (in seconds)
# I ran this test on my dual-boot system as demonstration:
print(time.clock()); time.sleep(10); print(time.clock())
# Linux: # Windows:
# 0.0382 # 26.1224
# 0.0384 # 36.1566
So which function to pick instead?
Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.
Use time.process_time()
Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time.
Use time.perf_counter()
time.time() also measures wall-clock time but can be reset, so you could go back in time
time.monotonic() cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter()
A:
Check if you are using PyCrypto, if yes, uninstall it and install PyCryptodome which is a fork of PyCrypto
PyCrypto is dead as mentioned on project issue page
Since both these libraries can coexist, it could be an issue too
pip3 uninstall PyCrypto
pip3 install -U PyCryptodome
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting textarea newlines into and tags by JavaScript
I'm using a textarea in an html form and I'm trying to reformat its content into a valid html format by using <p> and <br/> tags.
I wrote this script and it seems to work but I wanted to make sure I'm not missing anything. So I'm asking for feedback. I'm aware that I'm not taking into consideration the possibility that the user might explicitly input html tags, but that's no problem because I'll be issuing the result in PHP anyway.
Thanks in advance.
An example to the output:
<p>Line 1<br/>Line 2</p><p>Line 4<br/><br/><br/>Line 7</p>
and the code:
function getHTML() {
var v = document.forms[0]['txtArea'].value;
v = v.replace(/\r?\n/gm, '<br/>');
v = v.replace(/(?!<br\/>)(.{5})<br\/><br\/>(?!<br\/>)/gi, '$1</p><p>');
if (v.indexOf("<p>") > v.indexOf("</p>")) v = "<p>" + v;
if (v.lastIndexOf("</p>") < v.lastIndexOf("<p>")) v += "</p>";
if (v.length > 1 && v.indexOf("<p>") == -1) v = "<p>" + v + "</p>";
alert(v);
}
Please note that this is a code meant to be part of a CMS and all I care to do by JavaScript is to rebuild the textarea result with those 2 tags. Kind of WYSIWYG issue...
A:
Here's what I came up with.
function encode4HTML(str) {
return str
.replace(/\r\n?/g,'\n')
// normalize newlines - I'm not sure how these
// are parsed in PC's. In Mac's they're \n's
.replace(/(^((?!\n)\s)+|((?!\n)\s)+$)/gm,'')
// trim each line
.replace(/(?!\n)\s+/g,' ')
// reduce multiple spaces to 2 (like in "a b")
.replace(/^\n+|\n+$/g,'')
// trim the whole string
.replace(/[<>&"']/g,function(a) {
// replace these signs with encoded versions
switch (a) {
case '<' : return '<';
case '>' : return '>';
case '&' : return '&';
case '"' : return '"';
case '\'' : return ''';
}
})
.replace(/\n{2,}/g,'</p><p>')
// replace 2 or more consecutive empty lines with these
.replace(/\n/g,'<br />')
// replace single newline symbols with the <br /> entity
.replace(/^(.+?)$/,'<p>$1</p>');
// wrap all the string into <p> tags
// if there's at least 1 non-empty character
}
All you need to do is call this function with the value of the textarea.
var ta = document.getElementsByTagName('textarea')[0];
console.log(encode4HTML(ta.value));
| {
"pile_set_name": "StackExchange"
} |
Q:
Replaced FX 4300 with FX 4350, motherboard claims it to be incompatible
My friend got a FX 4350 and replaced his FX 4300, the gigabyte GA-78LMT-S2 motherboard is now claiming the old CPU is incompatible and it underclocks it, completely removing the purpose of using the new CPU, it also disables two CPU cores, the other FX works perfectly. Any idea what is causing this? It's undercooked to 2.7ghz from 4.2 stock without our doing so, it is just the motherboard. We have also reset the bios settings
A:
The GA-78LMT-S2 (rev. 1.2) does not support the FX 4350
Source: GA-78LMT-S2 (rev. 1.2) CPU Compatability List
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery/HTML: How to use variable within onClick
I'm really stuck on this project that I'm doing. Below is my code. I am using the Google Maps API by the way.
var arr = new Array();
arr[0] = lat1, lon1
arr[1] = lat2, lon2
arr[2] = lat3, lon3
for (each i in arr){
var newCenter = "<button onClick='map.setCenter(arr[i])'>Center Map</button>";
$("#myTable").append(newCenter);
}
Now I know that
'map.setCenter(arr[i])'
is incorrect because it's basically hard coding "arr[i]" into the DOM. What I want to do is use arr[i] as a variable so that the DOM has:
<button onClick='map.setCenter(arr[0])'>Center Map</button>
<button onClick='map.setCenter(arr[1])'>Center Map</button>
<button onClick='map.setCenter(arr[2])'>Center Map</button>
I have tried
"<button onClick='map.setCenter(" + arr[i] + ")'>Center Map</button>"
but that doesn't work. I have been stuck on this for a pretty long time. Any help would be appreciated. Thank you.
A:
1- to loop an array you use for (var i = 0 ; i < arr.length ;i++) and not the in operator.
2- You need to create your links on a separate function to obtain closure, (explanation here)
3- you array should hold google.maps.LatLng() objects.
var arr = new Array();
arr[0] = new google.maps.LatLng(lat1, lon1);
arr[1] = new google.maps.LatLng(lat2, lon2);
arr[2] = new google.maps.LatLng(lat3, lon3);
for (var i = 0 ; i < arr.length ;i++) {
var button = createbutton(arr[i],i);
}
function createbutton(latlon,index) {
var button = document.createElement('button');
var container = document.getElementById('containerDiv');
button.onclick = function(){map.setCenter(latlon)};
button.value = 'Center Map at ' + index;
container.appendChild(button);
}
...and in your HTML:
<div id ="containerDiv"></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Template10.Validation/UWP/C# How to make new design ? , error : Collection property __implicit_propery is null
I want to modify "Template10.Validation" style when Validation error is happened.
Here is my Target style.
and I tried .. but There is strange errors...
<validate:ControlWrapper Property="{Binding SettingEmailModel}" PropertyName="EmailReceivers">
<validate:ControlWrapper.Template>
<ControlTemplate TargetType="validate:ControlWrapper">
<StackPanel DataContext="{TemplateBinding Property}">
<TextBlock Text="IsValid" />
<TextBlock Text="{Binding IsValid}" />
<TextBlock Text="Errors" />
<TextBlock Text="{Binding Errors.Count}" />
<ContentPresenter Content="{TemplateBinding Content}" />
<TextBlock x:Name="ValidationNotifyTextBlock" Text="{Binding Errors[0]}">
<Interactivity:Interaction.Behaviors>
<Core:DataTriggerBehavior Binding="{Binding IsValid}" Value="True">
<Core:ChangePropertyAction TargetObject="{Binding ElementName=ValidationNotifyTextBlock}"
PropertyName="Foreground" Value="Red"/>
</Core:DataTriggerBehavior>
<Core:DataTriggerBehavior Binding="{Binding IsValid}" Value="False">
<Core:ChangePropertyAction TargetObject="{Binding ElementName=ValidationNotifyTextBlock}"
PropertyName="Foreground" Value="Black"/>
</Core:DataTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</TextBlock>
</StackPanel>
</ControlTemplate>
</validate:ControlWrapper.Template>
<Grid>
<TextBox Text="{Binding SettingEmailModel.EmailReceivers, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
MinHeight="400" Style="{StaticResource SettingStyle_MultilineTextBox}"/>
</Grid>
</validate:ControlWrapper>
Here is error message "Collection property __implicit_propery is null"
1) I tried both ver 1.1 and ver 2.0 of "Microsoft.Xaml.Behaviors.Uwp.Managed"
I do not know why the error is happened..
Please advice me or, Can you make a style for my design ?
A:
For your requirement, you could create ErrorTextBoxStyle for the TextBox that has been verifyed. And use it in the follwing ControlWrapper ControlTemplate.
<validate:ControlWrapper PropertyName="FirstName">
<validate:ControlWrapper.Template>
<ControlTemplate TargetType="validate:ControlWrapper">
<Grid>
<ContentPresenter Content="{TemplateBinding Content}"/>
</Grid>
</ControlTemplate>
</validate:ControlWrapper.Template>
<TextBox
Width="{StaticResource FieldWidth}"
Header="First Name"
Text="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<Interactivity:Interaction.Behaviors>
<behaviors:ValidationBehavior PropertyName="FirstName">
<behaviors:ValidationBehavior.WhenValidActions>
<Core:ChangePropertyAction PropertyName="Style" Value="{x:Null}" />
</behaviors:ValidationBehavior.WhenValidActions>
<behaviors:ValidationBehavior.WhenInvalidActions>
<Core:ChangePropertyAction PropertyName="Style" Value="{StaticResource ErrorTextBoxStyle}" />
</behaviors:ValidationBehavior.WhenInvalidActions>
</behaviors:ValidationBehavior>
</Interactivity:Interaction.Behaviors>
</TextBox>
</validate:ControlWrapper>
ErrorTextBoxStyle
<Style x:Key="ErrorTextBoxStyle" TargetType="TextBox">
<Setter Property="Foreground" Value="White" />
<Setter Property="BorderBrush" Value="Red"/>
</Style>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to capture video and to save into documents directory of iPhone
I want to capture video in iphone4 and at completion I want to store in documents directory of iPhone.Please help .I am able to capture video using
UIImagePickerController but not able to save it into documents directory.
A:
If you want to save videos with a UIImagePicker, you can easily save them to the Photos Album via:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info; {
NSURL * movieURL = [[info valueForKey:UIImagePickerControllerMediaURL] retain];// Get the URL of where the movie is stored.
UISaveVideoAtPathToSavedPhotosAlbum([movieURL path], nil, nil, nil);
}
This allows you to save it to the Photos Album, and keep a reference path to the movie for use later. I'm not quite sure if this is what you need, but it does allow you to save movies.
EDIT: If you really want to save the Movie to documents directory, simply take the above code, and change the line:
UISaveVideoAtPathToSavedPhotosAlbum([movieURL path], nil, nil, nil);
to
NSData * movieData = [NSData dataWithContentsOfURL:movieURL];
This will give you the data of the movie, and from there, you can write that data to the documents directory. Hope that helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
If I only have a range, is it acceptable to calculate an average out of it?
Supposed I have only this data point available:
Concentration = (1.1 - 2.0 g/L).
Is it acceptable to conclude :
(Theoretical) average = ((1.1 + 2.0) * 0.5) = 1.55 g/L?
Or would that considered to be statistically incorrect by a reviewer of a scientific thesis (in a medical field)?
EDIT 3: Complete rephrase:
If I have only 2 data points out of a range, and nothing else, could I declare this as the only available data and therefore, calculate an arithmetic mean out of it?
Like: "I have a range which represents two samples, the lowest one and the highest one. I don't know how many samples were in between. Therefore, I assume there were just those two samples, and calculate the average of those two. And add a note that this average value has been calculated out of a range, and should be considered as less reliable than others with more samples".
EDIT 4:
whubers comment on the question is what I was looking for:
Mid-range.
I don't have enough points to upvote the other answers, sorry. If whuber will write an answer instead of a comment I will mark it as correct.
A:
The average calculation will be correct if the underlying distribution is symmetric and the endpoints of your interval were chosen by the same criterion.
For example, the above calculation is correct if the distribution of your concentration is normal and the interval refers to the interquartile range.
The calculation will not in general be true if the distribution is asymmetric such as a log-normal distribution.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why would Dissolve stop working in ArcGIS for Desktop?
I have an ArcMap Add-In that completes various geoprocessing steps, including Dissolve (using ESRI.ArcGIS.DataManagementTools.Dissolve). This tool worked at 10.0, but I just upgraded to 10.1 SP1 and it no longer works. I have run the tool on the same feature class in 10.0 and 10.1 and it worked in 10.0 but does not work in 10.1 SP1.
I'm attempting to dissolve on 2 fields, single part, in case that's relevant.
I can still complete the dissolve manually inside of ArcMap, but every time I try to run it programmatically, it crashes with the ever-helpful "Error HRESULT E_FAIL has been returned from a call to a COM component."
Upgrading to 10.2 is not an option because the rest of my organization won't be upgrading to 10.2 for at least another year.
Has anyone else encountered this? Any suggestions on how to solve this problem? Knowledge of something that changed at 10.1 that would require some extra conditions in order for dissolve to run correctly...?
A:
Thanks to prompting by thehealingprocess, I did investigate a little more and the GP messages indicate the proper error is actually "Workspace or data source is read only"...which a bunch of others have encountered here as a bug at 10.1: http://forums.arcgis.com/threads/80394-Error-“Workspace-or-data-source-is-read-only.”-from-file-geodatabases. Now to see if I can implement one of those changes to fix it...
Didn't think to check the messages in the first instance since the GP ran just fine in ArcMap, just not in code.
UPDATE and FINAL ANSWER: I contacted ESRI support and the manifestation I was seeing - the code didn't work but executing manually in ArcMap did - prompted him to have me try ExecuteAsync instead of Execute to try to avoid conflicts with background processes. Apparently ExecuteAsync is effectively what ArcMap uses. When I did this, the tool completed successfully. So, there is a bug (he referenced NIM 094612), but the workaround is to use ExecuteAsync rather than Execute. Hope this helps someone else!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to configure custom domain name for Amazon ECR
Amazon Elastic Container Repositories (ECR) have quite human-unfriendly URIs, like 99999999999.dkr.ecr.eu-west-1.amazonaws.com. Is it at all possible to configure custom domain name for an ECR?
Simplistic solution would be to create a CNAME record to point to the ECR URI, but this doesn't really work (SSL certificate doesn't match the domain name, passwords generated by aws ecr get-login don't pass, cannot push images tagged with custom domain name...).
Are there other options?
A:
Unfortunately, AWS does not support custom domain names for ECR. You'll have to make do with the auto-generated ones for now. There are 'hacks' about, which centre around Nginx proxies, but it really isn't worth the effort.
| {
"pile_set_name": "StackExchange"
} |
Q:
disable RabbitAutoConfiguration programmatically
Is there a programmatic(properties based) way of disabling RabbitAutoConfiguration in spring boot (1.2.2).
Looks like spring.rabbitmq.dynamic=false disables just the AmqpAdmin but not the connection factory etc.
We want a model where app properties might be sourced from spring cloud config (includes control bus) or via -D jvm args. This decision is made at deployment time.
When properties are sourced from -D jvm args, we disable the spring cloud config client but rabbit keeps throwing exceptions such as :
[org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer] - [Co
nsumer raised exception, processing can restart if the connection factory suppor
ts it. Exception summary: org.springframework.amqp.AmqpConnectException: java.ne
t.ConnectException: Connection refused: connect]
A:
First you need to exclude RabbitAutonfiguration from your app
@EnableAutoConfiguration(exclude=RabbitAutoConfiguration.class)
Then you can import it based on some property like this
@Configuration
@ConditionalOnProperty(name="myproperty",havingValue="valuetocheck",matchIfMissing=false)
@Import(RabbitAutoConfiguration.class)
class RabbitOnConditionalConfiguration{
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Efficient non-interactive use of vim
I use vim to non-interactively write a single C language function to a file.
First a tags file is created with ctags.
To write the main() function to file func.c I then use
vim -R -U NONE -u NONE -c ":ta main" -c ":.,/^}/w!func.c" -c :q
In other words this runs 3 vim commands non-interactively:
:ta main to jump to main()
:.,/^}/w!func.c to write from the current line to the next closing curly at the start of a line
:q to quit
I have tried to make this efficient by not wasting time reading user or system startup files (-U NONE -u NONE) and avoiding .swp file creation (-R).
There are two snags remaining I couldn't get rid of:
If this is run as part of a pipe I get the Vim: Warning: Output is not to a terminal warning and (apparently) a one second delay.
If I save the stdout of this command I still see lots of terminal escape sequences being used, and messages such as "func.c" 58 lines, 1707 characters written being generated.
Is there a way to avoid each of these?
A:
This sounds like silent batch mode (:help -s-ex) could work for your use case. Else, you can't get around full automation (with some of the downsides that you describe).
Silent Batch Mode
For very simple text processing (i.e. using Vim like an enhanced 'sed' or 'awk', maybe just benefitting from the enhanced regular expressions in a :substitute command), use Ex-mode.
REM Windows
call vim -N -u NONE -n -i NONE -es -S "commands.ex" "filespec"
Note: silent batch mode (:help -s-ex) messes up the Windows console, so you may have to do a cls to clean up after the Vim run.
# Unix
vim -T dumb --noplugin -n -i NONE -es -S "commands.ex" "filespec"
Attention: Vim will hang waiting for input if the "commands.ex" file doesn't exist; better check beforehand for its existence! Alternatively, Vim can read the commands from stdin. You can also fill a new buffer with text read from stdin, and read commands from stderr if you use the - argument.
Full Automation
For more advanced processing involving multiple windows, and real automation of Vim (where you might interact with the user or leave Vim running to let the user take over), use:
vim -N -u NONE -n -c "set nomore" -S "commands.vim" "filespec"
Here's a summary of the used arguments:
-T dumb Avoids errors in case the terminal detection goes wrong.
-N -u NONE Do not load vimrc and plugins, alternatively:
--noplugin Do not load plugins.
-n No swapfile.
-i NONE Ignore the |viminfo| file (to avoid disturbing the
user's settings).
-es Ex mode + silent batch mode -s-ex
Attention: Must be given in that order!
-S ... Source script.
-c 'set nomore' Suppress the more-prompt when the screen is filled
with messages or output to avoid blocking.
| {
"pile_set_name": "StackExchange"
} |
Q:
Given a real number, find the lowest value you can add to it to create a real palindrome
Given a real number, n, find the lowest real number, m, such that n+m is a real palindrome.
For example
If the number is 101.099 , to add to 0,002 , we get the real palindrome 101.101 . Another example would be the number 13.31 , which is already a real palindrome and must add 0 so that it stays that way. A final example is the number 100.9 , which should add 0.1 so that the number becomes 101.
Can anyone offer an algorithm/some advice to help me solve this problem?
A:
I am assuming that the decimal is relevant to the number being palindromic.
Observation 1: the problem you provided is equivalent to finding the smallest "real palindrome" which is larger than the given value, and then taking the difference of this palindrome and the given number.
Observation 2: Since every real number only has one decimal point we know that the decimal part of the number must be a mirror of the integer part. So given the integer part you can generate the only "real palindrome" that can be associated with it. For instance, if the integer part of the real palindrome is 123 then the palindrome must be 123.321.
These observations should be a solid starting place for you to approach the problem :)
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I connect a LXC container to an IP alias?
I currently have 3 IP addresses going to the same server. The /etc/network/interfaces file on the host is as follows:
auto eth0
iface eth0 inet static
address XXX.XXX.132.107
gateway XXX.XXX.132.1
netmask 255.255.255.0
auto eth0:0
iface eth0:0 inet static
address XXX.XXX.130.21
gateway XXX.XXX.130.1
netmask 255.255.255.0
auto eth0:1
iface eth0:1 inet static
address XXX.XXX.132.244
gateway XXX.XXX.132.1
netmask 255.255.255.0
auto lo
iface lo inet loopback
I would like the host to be accessible from XXX.XXX.132.107, one LXC container to be accessible from XXX.XXX.130.21, and another LXC container accessible from the XXX.XXX.132.244. I have tried a few bridging set ups, but have been unsuccessful. Has anybody done this before? Is it even possible? Thank you!
A:
I know of 2 ways to do what you would like.
Network bridging
IPTables Nat
We'll start out with IPTables NAT since your ifconfig output already has IP Aliases setup.
Typical Host server
My 'ifconfig' output shows 'eth0' as main interface with 2 IP Aliases setup, along with the LXC generated bridge interface.
# ifconfig
eth0 Link encap:Ethernet HWaddr 08:00:27:d9:66:ac
inet addr:172.16.10.71 Bcast:172.16.10.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:7 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:578 (578.0 B)
eth0:1 Link encap:Ethernet HWaddr 08:00:27:d9:66:ac
inet addr:172.16.10.72 Bcast:172.16.10.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
eth0:2 Link encap:Ethernet HWaddr 08:00:27:d9:66:ac
inet addr:172.16.10.73 Bcast:172.16.10.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
lxcbr0 Link encap:Ethernet HWaddr de:45:c9:13:2b:74
inet addr:10.0.3.1 Bcast:10.0.3.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:508 (508.0 B)
The below command shows our 2 LXC containers and their IP addresses.
# lxc-ls -f<br>
NAME STATE IPV4 IPV6 AUTOSTART<br>
-------------------------------------------<br>
test1 RUNNING 10.0.3.247 - NO<br>
test2 RUNNING 10.0.3.124 - NO
Doing an 'ifconfig' will show your 2 new interfaces created for your LXC Containers. See
below for mine.
# ifconfig
veth05DUGY Link encap:Ethernet HWaddr fe:4c:2c:df:1d:c3
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:39 errors:0 dropped:0 overruns:0 frame:0
TX packets:40 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3706 (3.7 KB) TX bytes:3822 (3.8 KB)
vethTUTFID Link encap:Ethernet HWaddr fe:58:4b:19:25:3e
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:42 errors:0 dropped:0 overruns:0 frame:0
TX packets:57 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3956 (3.9 KB) TX bytes:5580 (5.5 KB)
Below shows them being part of the bridge.
# brctl show lxcbr0
bridge name bridge id STP enabled interfaces
lxcbr0 8000.fe4c2cdf1dc3 no veth05DUGY
vethTUTFID
So now the actual work. We will be using IPTables to do the forwarding. Below is the default setup before our additions
# iptables -nL -t nat
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
MASQUERADE all -- 10.0.3.0/24 !10.0.3.0/24
So Here we go do the following.
# iptables -t nat -A PREROUTING -d 172.16.10.72 -j DNAT --to-destination 10.0.3.247
# iptables -t nat -A PREROUTING -d 172.16.10.73 -j DNAT --to-destination 10.0.3.124
The 2 above commands add IPTables rules to forward all IP traffic from the eth0:* IP to the respective IP's on the LXC Containers.
You should see the below when verifying.
# iptables -nL -t nat
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
DNAT all -- 0.0.0.0/0 172.16.10.72 to:10.0.3.247
DNAT all -- 0.0.0.0/0 172.16.10.73 to:10.0.3.124
So at this point you now have those IP's forwarded to the Containers. To make this persistent you can create a /etc/iptables.rules file and from your /etc/network/interfaces file add a "post-up" for 'iptables-restore' to restore those rules at bootup. e.g. 'post-up iptables-restore < /etc/iptables.rules' could be added under your iface line in /etc/network/interfaces.
Below is an example of network bridging. You need to remove your IP Aliases for the below to work. See example output below for what you should start out with.
Host server
$ ifconfig
eth0 Link encap:Ethernet HWaddr 08:00:27:d9:66:ac
inet addr:172.16.10.71 Bcast:172.16.10.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:7 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:578 (578.0 B)
lxcbr0 Link encap:Ethernet HWaddr de:45:c9:13:2b:74
inet addr:10.0.3.1 Bcast:10.0.3.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:508 (508.0 B)
We won't be using the lxcbr0 interface in this case.
Create a bridge interface for use for the LXC containers.
The below command will create a 'br0' interface for use with our bridge. You will need to add the eth0 interface to the bridge. See that command farther down.
** BE WARNED ** following the bellow commands will immediately brake remote connection with server and make the server not reachable via internet anymore. These instructions assume local connection.
# brctl addbr br0
# ip link set br0 up
# brctl addif br0 eth0
# brctl show br0<br>
bridge name bridge id STP enabled interfaces<br>
br0 8000.080027d966ac no eth0
So the above commands add 'eth0' to br0 bridge and shows it being there. Next we need to move the IP address from eth0 to br0.
# ip addr del 172.16.10.71/24 dev eth0
# ip addr add 172.16.10.71/24 dev br0
You should now have similar below.
# ifconfig
br0 Link encap:Ethernet HWaddr 08:00:27:d9:66:ac
inet addr:172.16.10.71 Bcast:172.16.10.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:77 errors:0 dropped:0 overruns:0 frame:0
TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:6281 (6.2 KB) TX bytes:648 (648.0 B)
eth0 Link encap:Ethernet HWaddr 08:00:27:d9:66:ac
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:87 errors:0 dropped:0 overruns:0 frame:0
TX packets:16 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:8183 (8.1 KB) TX bytes:1296 (1.2 KB)
Next we need to edit your LXC configuration file for your 2 containers.
If your system is default, you should have the following.
ls -l /var/lib/lxc
total 12
drwxr-xr-x 3 root root 4096 Aug 10 11:23 test1
drwxr-xr-x 3 root root 4096 Aug 10 11:34 test2
The above output should show both of your LXC containers. Under each directory is a file named 'config' that we need to edit.
# vi /var/lib/lxc/test1/config
Replace the line that says 'lxc.network.link = lxcbr0' with 'lxc.network.link = br0'. Do this for both containers.
Next you need to edit both containers /etc/network/interfaces file and add the real IP address as eth0 for both.
So in my examples.
I would put the 172.16.10.72 IP in test1 configuration file such as '/var/lib/lxc/test1/rootfs/etc/network/interfaces'. This is updating the file from the Host machine without being inside the container yet. You of course can boot up the container and edit /etc/network/interfaces. Either way works.
If you need any clarification or additional help just add a comment asking for help.
-Frank
| {
"pile_set_name": "StackExchange"
} |
Q:
Colour difference in plot between normal variable and factor variable
I am using plot function on mtcars dataset.
I am trying to add colour to the plots based on mtcars$cyl variable
The distinct values in cyl variable is 4,6 and 8
First i tried this:
plot(x=mtcars$wt, y=mtcars$mpg, col = mtcars$cyl)
I got points plotted on blue,purple and grey colour.
Then I converted cyl variable into a factor and tried the same plot again,
mtcars$fcyl <- as.factor(mtcars$cyl)
plot(x=mtcars$wt, y=mtcars$mpg, col = mtcars$fcyl)
But this time I got black,red and green
I want to understand how assigning the variable as factor changes the colour. What happens behind?
A:
I want to understand how assigning the variable as factor changes the colour. What happens behind?
In R, factors are just integers under the hood. In the plot function, integers are converted to eight different colors (repeating), which are 8 colors that can be visually separated.
Try this:
plot(x=1:16, y=1:16, col = 1:16, pch=16)
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I code the slid down content to slideup when mouse is off the trigger and slid down content?
I've gotten the webdsn-drop to slide up when the mouse is off of this div but it still stays up when the mouse is off the#web button. How can I make the div disappear when the mouse is off both the #web button and the #webdsn-drop
Thank you for all help!
HTML:
<div id="navbar">
<div id="nav-container">
<h1>PORTFOLIO</h1>
<a href="#">Logo Design</a>
<a href="#">Business Cards</a>
<a id="pf" href="posters+flyers.html">Posters & Flyers</a>
<a id="web" href="#">Website Design</a>
</div>
</div>
<div id="webdsn-drop">
<div id="border">
<h1>WEBSITE DESIGN</h1>
</div>
</div>
<div id="pfdsn-drop">
<div id="border">
<h1>POSTERS & FLYERS</h1>
</div>
</div>
CSS:
#navbar {
width: 100%;
background-color: #fcfcfc;
overflow: auto;
position: fixed;
left: 0px;
top: 0px;
overflow: hidden;
z-index: 10;
}
#nav-container {
max-width: 950px;
min-width: 745px;
margin: 0 auto;
}
#nav-container h1 {
float: left;
margin: 0 auto;
padding-top: 10px;
font-family: "calibri light";
font-size: 25px;
letter-spacing: 0.3em;
margin-left: 5px;
transition: color 0.3s ease;
}
#nav-container a {
float: right;
display: block;
padding: 15px 15px;
text-decoration: none;
color: black;
font-family: "calibri light", sans-serif;
font-size: 18px;
transition: background-color 0.5s ease;
}
#nav-container a:hover {
background-color: #f4f4f4;
transition: background-color 0.5s ease;
}
#nav-container a:active {
background-color: #bfbfbf;
}
#nav-container h1:hover {
color: #aaaaaa;
transition: color 0.3s ease;
}
/*-----------WEB-DESIGN-DROP---------*/
#border{
width: 950px;
margin: 0 auto;
}
#border h1{
position: absolute;
border: solid;
border-color: white;
border-width: 1px;
display: inline;
padding: 10px 20px;
border-radius: 10px;
}
#webdsn-drop{
background-color: #3f3f3f;
margin-top: 50px;
width: 100%;
position: fixed;
left: 0px;
top: 0px;
z-index: 9;
font-family: 'calibri light';
font-size: 12px;
letter-spacing: 5px;
height: 400px;
color: white;
display: none;
}
JQUERY:
$(document).ready(function(){
$('#web').hover(function() {
$('#webdsn-drop').slideDown();
}, function() {
$('#webdsn-drop').mouseleave(function(){
$('#webdsn-drop').slideUp();
});
});
});
A:
Try it
I added the line $('#web').Hover() In order that there would be no repeated opening with multiple hover
$(document).ready(function () {
$('#web').hover(function () {
if ($('#webdsn-drop').is(":hidden")) {
$('#webdsn-drop').slideDown();
}
}, function () {
$('#webdsn-drop').slideUp();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript/Canvas появление объекта через заданное время
Подскажите, как реализовать появление объекта (красного квадрата) через setTimeout()
Я реализовал по-другому, но почему-то кажется, что так не правильно, или такое решение имеет место быть?
var canvas = document.getElementById("d1");
var ctx = canvas.getContext("2d");
var pressedLeft = false;
var pressedRight = false;
var pressedUp = false;
var pressedBottom = false;
document.addEventListener("keydown", keyDown, false);
document.addEventListener("keyup", keyUp, false);
function keyDown(e) {
if(e.keyCode == 37) {
pressedLeft = true;
}
else if(e.keyCode == 39) {
pressedRight = true;
}
else if(e.keyCode == 38) {
pressedUp = true;
}
else if(e.keyCode == 40) {
pressedBottom = true;
}
}
function keyUp(e) {
if(e.keyCode == 37) {
pressedLeft = false;
}
else if(e.keyCode == 39) {
pressedRight = false;
}
else if(e.keyCode == 38) {
pressedUp = false;
}
else if(e.keyCode == 40) {
pressedBottom = false;
}
}
var player = {
x: 10,
y: 10,
pW: 130,
pH: 130,
draw: function() {
ctx.beginPath();
ctx.rect(this.x, this.y, this.pW, this.pH);
ctx.fillStyle = "black";
ctx.fill();
ctx.closePath();
}
}
var box = {
x: 5,
y: 5,
bW: 140,
bH: 140,
timer: 0,
draw: function() {
ctx.beginPath();
ctx.rect(this.x, this.y, this.bW, this.bH);
ctx.fillStyle = "red";
ctx.fill();
ctx.closePath();
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
box.timer++;
if(box.timer >= 150) {
box.draw();
}
player.draw();
if(pressedRight) {
player.x = 162;
}
if(pressedLeft) {
player.x = 10;
}
if(pressedUp) {
player.y = 10;
}
if (pressedBottom) {
player.y = 162;
}
}
setInterval(draw, 1000/60);
#d1 {
border: 3px solid black;
background: #fff url('http://jscoder.ru/bg1.jpg');
}
<canvas id="d1" width="300" height="300"></canvas>
A:
Не совсем понятно, зачем Вам постоянно перерисовывать квадрат, а не делать это в обработчикe события:
var canvas = document.getElementById("d1");
var ctx = canvas.getContext("2d");
document.addEventListener("keyup", keyUp, false);
function keyUp(e) {
if (e.keyCode == 37) {
player.x = 10;
} else if (e.keyCode == 39) {
player.x = 162;
} else if (e.keyCode == 38) {
player.y = 10;
} else if (e.keyCode == 40) {
player.y = 162;
}
draw();
}
var player = {
x: 10,
y: 10,
pW: 130,
pH: 130,
draw: function() {
ctx.beginPath();
ctx.rect(this.x, this.y, this.pW, this.pH);
ctx.fillStyle = "black";
ctx.fill();
ctx.closePath();
}
}
var box = {
x: 5,
y: 5,
bW: 140,
bH: 140,
timer: 0,
draw: function() {
ctx.beginPath();
ctx.rect(this.x, this.y, this.bW, this.bH);
ctx.fillStyle = "red";
ctx.fill();
ctx.closePath();
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
box.draw();
player.draw();
}
draw();
#d1 {
border: 3px solid black;
background: #fff url('http://jscoder.ru/bg1.jpg');
}
<canvas id="d1" width="300" height="300"></canvas>
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL 5.1 to MySQL 5.6 update causes php-cgi error: PDO issue?
I recently performed a MySQL upgrade on Windows Server 2008R2, moving from MySQL 5.1 to MySQL 5.6.22 (Community Edition). The server is currently using PHP 5.3.0.
Things went just fine for all my WordPress installs (no problems on cutover); however, all my Drupal 7 sites are now generating 500 errors (coming from php-cgi.exe via php5ts.dll from what I can tell).
To address concerns about the broad nature of the question, this is the specific Windows event log message:
Faulting application name: php-cgi.exe, version: 5.3.0.0, time stamp: 0x4a492a25
Faulting module name: php5ts.dll, version: 5.3.0.0, time stamp: 0x4a4929bb
Exception code: 0xc0000005
Fault offset: 0x0015e1b0
Faulting process id: 0x7bb4
Faulting application start time: 0x01d01fa8dec6e9a6
Faulting application path: C:\PHP\php-cgi.exe
Faulting module path: C:\PHP\php5ts.dll
Report Id: 2e661541-8b9c-11e4-a303-001b210e0a6a
I've checked database credentials, time zone defaults, and haven't changed IIS settings, folder permissions, or anything of that nature.
The one difference that stands out is that Drupal uses PDO for access, and I'm wondering if there is a potential issue there with the version being used, since all these sites worked fine with MySQL 5.1.
PDO seems to be showing version 5.0.5-dev (rev 1.3.2.27).
I can't locate anything that leads to identification, troubleshooting or resolution.
(I'm off to try to replicate with just a simple PDO test.)
Has anybody encountered this and/or have documentation that might help isolate/resolve things?
NOTE: The closest I've come is to somebody using PDO drivers for MSSQL (not MySQL) where there was a faulty Drupal layer on top of PDO. Details here - http://forums.iis.net/t/1181446.aspx?PHP+5+3+8+Problems
UPDATE:
Not PDO...
The following example (with real values) works fine.
$dsn = 'mysql:host=localhost;dbname=DBNAME';
$username = 'USER';
$password = 'PASS';
$options = array();
$dbh = new PDO($dsn, $username, $password, $options);
if ($dbh) {
$stmt = $dbh->query('SELECT * FROM MYTABLE LIMIT 1');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($results);
}
else {
echo 'Failed.';
}
UPDATE 2:
I have double checked any options set by the prior install of MySQL 5.1 that might not have been carried over. I realize more things are auto-set and defaults might have changed, which could be part of the issue.
The other issue that might come into play is changing the server collation default from utf8 to utf8mb4 ... It looks like Drupal 7 should support this (discussion, in the framework of Drupal 8 goes back to 2011 - https://www.drupal.org/node/1314214). The tables continue to show ut8 collation, so data should be unaffected.
MySQL 5.6 does introduce explicit_defaults_for_timestamp but I haven't been able to find anything implying it should be an issue either (setting 0/1 results in the same error).
A:
As noted above, the whole thing was resolved by pushing the default character set back to utf8 from the incompatible (for Drupal, but not for WordPress) utf8mb4...
Relevant my.ini settings as follows:
[client]
default-character-set = utf8 # not utf8mb4
[mysql]
default-character-set = utf8 # not utf8mb4
[mysqld]
# REF: http://stackoverflow.com/a/24487309/3174018
collation-server = utf8_unicode_ci
character-set-server = utf8 # not utf8mb4
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add xml file data into ArangoDb?
<InputParameters>
<Textbox>
<Text>ABCD</Text>
<Text>EFGH</Text>
<Text>HIJK</Text>
</Textbox>
</InputParameters>
Suppose i have to add this xml file data into arangodb. How would one able to do so ?
A:
Since version 2.7.1 the aragodb-java-driver supports writing (createDocumentRaw(...)) and reading (getDocumentRaw(...)) of
raw strings.
Example:
arangoDriver.createDocumentRaw("testCollection", "{\"test\":123}",
true, false);
With JsonML you can convert a XML string into a JSON string and store it into ArangoDB:
// writing
String xml = "<recipe name=\"bread\" prep_time=\"5 mins\"</recipe> ";
JSONObject jsonObject = JSONML.toJSONObject(string);
DocumentEntity<String> entity = arangoDriver.createDocumentRaw(
"testCollection", jsonObject.toString(), true, false);
String documentHandle = entity.getDocumentHandle();
// reading
String json = arangoDriver.getDocumentRaw(documentHandle, null, null);
JSONObject jsonObject2 = new JSONObject(str);
String xml2 = JSONML.toString(jsonObject2));
You can find more examples in the arangodb-java-driver git repository.
| {
"pile_set_name": "StackExchange"
} |
Q:
Summarize a Variable by All But Group
I have a data.frame and I need to calculate the mean per "anti-group" (i.e. per Name, below).
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
My desired output is like below, where the values for Rate1 and Rate2 are the means of the column's values not found in each group. Please disregard the value, I have made it up for the example. I'd prefer to do this using dplyr if possible.
Name Rate1 Rate2
Aira 38 52.2
Ben 30.5 50.5
Cat 23.8 48.7
Any help much appreciated! Thank you!
PS - Thanks to Ianthe for copying their question and their question's data but changing the question slightly. (Mean per group in a data.frame)
A:
One option could be:
df %>%
mutate_at(vars(Rate1, Rate2), list(sum = ~ sum(.))) %>%
mutate(rows = n()) %>%
group_by(Name) %>%
summarise(Rate1 = first((Rate1_sum - sum(Rate1))/(rows-n())),
Rate2 = first((Rate2_sum - sum(Rate2))/(rows-n())))
Name Rate1 Rate2
<chr> <dbl> <dbl>
1 Aira 38 52.2
2 Ben 30.5 50.5
3 Cat 23.8 48.7
Or in a less tidy form:
df %>%
group_by(Name) %>%
summarise(Rate1 = first((sum(df$Rate1) - sum(Rate1))/(nrow(df)-n())),
Rate2 = first((sum(df$Rate2) - sum(Rate2))/(nrow(df)-n())))
| {
"pile_set_name": "StackExchange"
} |
Q:
(Ruby) Getting internal server error message
I've been trying to work out what's going on with my 2 codes but they aren't linking together.
This is my .rb file:
require 'sinatra'
require 'twitter'
require 'erb'
include ERB::Util
config = {
:consumer_key => '..' ,
:consumer_secret => '..' ,
:access_token => '..' ,
:access_token_secret => '..'
}
client = Twitter::REST::Client.new(config)
get '/following' do
buddy = client.friends('skg22')
@follow = buddy.take(20)
erb :following
end
The following.erb file:
<!DOCTYPE html>
<html>
<head>
<title>Twitter Management Interface</title>
</head>
<body>
<h1>Twitter Management Interface</h1>
<h2>List of Friends</h2>
<% unless @follow.nil? %>
<table border="1">
<tr>
<th>ID</th>
<th>User</th>
</tr>
<% @follow.each do |friend| %>
<tr>
<td><%= friend.id %></td>
<td><%= friend.user.screen_name %></td>
</tr>
<% end %>
</table>
<% else %>
<p>No friends.</p>
<% end %>
</body>
</html>
I've been driving myself crazy over the past few hours trying to figure out what's the error but every attempts at modification I made doesn't seem to get rid of the error message.
A:
The .rb file
require 'sinatra'
require 'twitter'
require 'erb'
include ERB::Util
config = {
:consumer_key => '..' ,
:consumer_secret => '..' ,
:access_token => '..' ,
:access_token_secret => '..'
}
client = Twitter::REST::Client.new(config)
get '/following' do
buddy = client.friends('skg22')
@follow = buddy.take(20)
erb :following
end
.ERB file
<!DOCTYPE html>
<html>
<head>
<title>Twitter Management Interface</title>
</head>
<body>
<h1>Twitter Management Interface</h1>
<h2>List of Friends</h2>
<% unless @follow.nil? %>
<table border="1">
<tr>
<th>ID</th>
<th>User</th>
</tr>
<% @follow.each do |friend| %>
<tr>
<td><%= friend.id %></td>
<td><%= friend.screen_name %></td>
</tr>
<% end %>
</table>
<% else %>
<p>No friends.</p>
<% end %>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
how to display characters in jPasswordField rather than * sign in java?
I am working with jPasswordField in java in order to make a log in system.
I have used jTextField for name input and jPasswordField for password. I want to create an option of "Show Characters" in my program that may allow the user to view the characters he has typed in passwordfield.
I have tried
retrieving data from password field
converting it into string
displaying that string in passwordfield using .setText() method
But this did not work, as it displays everything in esteric (*****) form.
Please help...
A:
hidePasswordCheckbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
httpProxyPassword.setEchoChar('*');
} else {
httpProxyPassword.setEchoChar((char) 0);
}
}
});
You have to use httpProxyPassword.setEchoChar((char) 0); for that.
Here httpProxyPassword is a name of textbox you can use as per your's.
| {
"pile_set_name": "StackExchange"
} |
Q:
Develop nucleotide sequence
I would like to develop these expressions that are in this form:
a <- "[AGAT]5GAT[AGAT]7[AGAC]6AGAT"
I would like to convert the expression like this:
b <- "AGATAGATAGATAGATAGATGATAGATAGATAGATAGATAGATAGATAGATAGACAGACAGACAGACAGACAGACAGAT"
As you can see, the number after the hook means the number of times the pattern is found.
For the moment I use sub(".*[*(.*?) *].*", "\\1", seq) for select character between [] and replicate(i, "my_string") for replicate sequence between [] but I do not find how to make it work with my data.
I hope to be pretty clear.
A:
We use gsub to create 1s where there is no number before the [ ('a1'), then extract the letters and numbers separately ('v1', 'v2'), do the replication with strrep and paste the substrings to a single string ('res')
library(stringr)
a1 <- gsub("(?<![0-9])\\[", "1[", a, perl = TRUE)
v1 <- str_extract_all(a1, '[A-Z]+')[[1]]
v2 <- str_extract_all(a1, "[0-9]+")[[1]]
res <- paste(strrep(v1, as.numeric(c(tail(v2, -1), v2[1]))), collapse='')
res
-output
#[1] "AGATAGATAGATAGATAGATGATAGATAGATAGATAGATAGATAGATAGATAGACAGACAGACAGACAGACAGACAGAT"
-checking with the 'b'
identical(res, b)
#[1] TRUE
A slightly more compact regex would be to change the first step
a1 <- gsub("(?<=[A-Z])(?=\\[)|(?<=[A-Z])$", "1", a, perl = TRUE)
v1 <- str_extract_all(a1, '[A-Z]+')[[1]]
v2 <- str_extract_all(a1, "[0-9]+")[[1]]
res1 <- paste(strrep(v1, as.numeric(v2)), collapse="")
identical(res1, b)
#[1] TRUE
data
a <- '[AGAT]5GAT[AGAT]7[AGAC]6AGAT'
b <- 'AGATAGATAGATAGATAGATGATAGATAGATAGATAGATAGATAGATAGATAGACAGACAGACAGACAGACAGACAGAT'
A:
Try this:
a<-"[AGAT]5GAT[AGAT]7[AGAC]6AGAT"
list<-unlist(strsplit(unlist(strsplit(a,"\\]")),"\\["))
number<-suppressWarnings(as.numeric(gsub("([0-9]+).*$", "\\1", list)))
number[is.na(number)]<-1
seq<-gsub('[0-9]+', '', list)
out<-paste(rep(seq[2:(length(seq))],number[c(3:length(number),2)]),collapse = '')
b="AGATAGATAGATAGATAGATGATAGATAGATAGATAGATAGATAGATAGATAGACAGACAGACAGACAGACAGACAGAT"
out==b
[1] TRUE
The output is correct, but I don't know if is a general solution for every kind of data in input
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I ensure my Playstation 2 will last a long time?
I'm still using a Playstation 2. I'm aware that nothing lasts forever, but I would like to make the Playstation 2 last as long as it can. I bought it roughly when Playststion 2 was released but chipped from the start (was legal then and I think it still is in my country). I use it around 0-2 times a month. Let say 1 on average. When I play it usually 2 or more players and we play long sessions +12 hours.
What can I do to improve the lifetime of the console?
A:
Firstly, I think it's important that you noted that nothing lasts forever. The PS2 has components that will eventually wear out over time, even if preserved or used sparingly.
Most notably, it is likely that one or all of these components will eventually fail:
Controllers - Obviously wear & tear use but also the rubber domes that provide both the button 'depress' and spring-back can eventually wear out.
Memory Cards - Memory cards are built on a type of Flash memory that - like all flash memory - has limited reads and writes. Eventually they will also fail.
Power supply - Capacitors wear out over time, even when not used
Disk drive - Spin motor can burn out and/or rubber and plastic components can become brittle and break with age or rapid heat/cool cycles.
This includes the Clamshell lid or disk drive tray (depending on whether you have a slim or phat PS2), either way plastic clips or the parts that control ejecting DVDs will wear out.
This isn't an exhaustive list of what can break but they will be the most common complaints of broken hardware. Note that if any of these happen to you that all hope is not lost, most of these parts are replaceable, and there are third-party (i.e. not Sony) vendors that still offer replacement parts (and will for years to come).
Now, in terms of your actual question of how to look after your PS2 so that it will have a long lifetime, it's all the simple stuff really:
Make sure it has a lot of ventilation in a dust-free environment
Don't play it in areas of excessive heat or humidity (don't play during heat waves or humid days unless you have air conditioning keeping everything cool and dry),
Keep it away from sources of heat (like fireplaces or heaters)
Don't leave it on 'idling' or 'paused' for extended periods of time.
Don't set it up somewhere where it's likely to be knocked off (or pulled off by someone tripping over a cable) - avoid 'hard shocks'
Don't throw your controller across the room when you're losing.
Put your disks back in their case when you're done playing.
Pack everything away when you're done - don't leave controllers around where someone can step/trip on them.
| {
"pile_set_name": "StackExchange"
} |
Q:
How are these pole zero plots created
Back around 5 BC, where C stands for the programming language, engineers would photograph their oscilloscope's display to record their test results.
This appears to be such a photograph, taken from this Wikipedia article on Elliptic filters.
The photo is described as follows:
Log of the absolute value of the gain of an 8th order elliptic filter in complex frequency space. The white spots are poles and the black spots are zeroes. There are a total of 16 poles and 8 double zeroes. What appears to be a single pole and zero near the transition region is actually four poles and two double zeroes as shown in the expanded view below. In this image, black corresponds to a gain of 0.0001 or less and white corresponds to a gain of 10 or more.
I have seen plots like this many times and always wondered how they were created. In other words, what methods and equipment were used to do this? They even show poles in the RHP, which doesn't make much sense.
A:
You can follow the links to the Mathematica source code, copy-pasted here:
xp2[xi_] :=
Module[{g, num, den}, g = Sqrt[4*xi^2 + (4*xi^2*(xi^2 - 1))^(2/3)];
num = 2*xi^2*Sqrt[g];
den = Sqrt[8*xi^2*(xi^2 + 1) + 12*g*xi^2 - g^3] - Sqrt[g^3];
num/den];
xz2[xi_] := xi^2/xp2[xi];
t[xi_] := Sqrt[1 - 1/xi^2];
(*Use particular values for low-order functions*)
r1[xi_, x_] := x;
r2[xi_, x_] := ((t[xi] + 1)*x^2 - 1)/((t[xi] - 1)*x^2 + 1);
r3[xi_, x_] :=
x*((1 - xp2[xi])*(x^2 - xz2[xi]))/((1 - xz2[xi])*(x^2 - xp2[xi]));
(*Use nesting property for higher-degree functions*)
r4[xi_, x_] := r2[r2[xi, xi], r2[xi, x]];
r8[xi_, x_] := r4[r2[xi, xi], r2[xi, x]];
ellgain[xi_, w_, w0_, ep_] := 1/Sqrt[1 + ep^2*r8[xi, w/w0]^2];
DensityPlot[
w0 = 1;
ep = 0.5;
xi = 1.05;
min = 0.0001;
max = 10;
Log[Abs[
ellgain[xi, sig + I*w, w0*I, ep]
]],
{sig, -4, 4},
{w, -4, 4},
PlotRange -> {Log[min], Log[max]},
PlotPoints -> 100,
ColorFunction -> GrayLevel,
ClippingStyle -> {Black, White}
]
| {
"pile_set_name": "StackExchange"
} |
Q:
How far does $\eta$-reduction go?
A term is is normal form, if there are no more redexes. But I'm confused as to what that means.
E.g. $\lambda x. f x$ isn't in normal form, obviously, because it contains an $\eta$-redex. But is $\lambda x. f$ in a normal form? Because applying any kind of term, would always result in the same term.
And even one step beyond, can a lambda term even be in normal form if it is a lambda abstraction? Because I know of pointfree programming, which tries to remove any kind of lambda abstraction, and people say that that has its origin in $\eta$-reduction. But pointfree usually implies applying combinators (which lead us to combinatory logic).
As I see it currently, the only "reduction" $\eta$-reduction can do, is the kind, where the a bound variable appears once in the body, and that is at the end at the same position as the parameter itself, e.g.:
$\lambda x y z. x f g x y z = \lambda x. x f g x$
Is this correct?
A:
In the lambda calculus, a term is in beta normal form if no beta reduction is possible. A term is in beta-eta normal form if neither a beta reduction nor an eta reduction is possible.
So, $\lambda x. f x$ is in beta normal form but not in beta-eta normal form.
But is λx.f in a normal form?
Yes, it is in both beta and beta-eta normal forms.
Because applying any kind of term, would always result in the same term.
Yes, you are right, but this term does not match the $\lambda x.fx$ format, so it cannot be eta-reduced.
the only "reduction" η-reduction can do, is the kind, where the a bound variable appears once in the body, and that is at the end at the same position as the parameter itself
You're correct. Eta-reduction expresses the idea of extensionality, which in this context is that two functions are the same if and only if they give the same result for all arguments. Eta-reductions converts $\lambda x.f x$ into $f$ whenever $x$ does not appear free in $f$.
| {
"pile_set_name": "StackExchange"
} |
Q:
mongodb queries both with AND and OR
can I use combination of OR and AND in mongodb queries?
the code below doesn't work as expected
db.things.find({
$and:[
{$or:[
{"first_name" : "john"},
{"last_name" : "john"}
]},
{"phone": "12345678"}
]});
database content:
> db.things.find();
{ "_id" : ObjectId("4fe8734ac27bc8be56947d60"), "first_name" : "john", "last_name" : "hersh", "phone" : "2222" }
{ "_id" : ObjectId("4fe8736dc27bc8be56947d61"), "first_name" : "john", "last_name" : "hersh", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8737ec27bc8be56947d62"), "first_name" : "elton", "last_name" : "john", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8738ac27bc8be56947d63"), "first_name" : "eltonush", "last_name" : "john", "phone" : "5555" }
when querying the above query - i get nothing!
> db.things.find({$and:[{$or:[{"first_name" : "john"}, {"last_name" : "john"}]},{"phone": "12345678"}]});
>
I'm using mongo 1.8.3
A:
db.things.find( {
$and : [
{
$or : [
{"first_name" : "john"},
{"last_name" : "john"}
]
},
{
"Phone":"12345678"
}
]
} )
AND takes an array of 2 expressions OR , phone.
OR takes an array of 2 expressions first_name , last_name.
AND
OR
first_name
last_name
Phone Number.
Note: Upgrade to latest version of MongoDB, if this doesn't work.
A:
Shorter to use an implicit AND operation:
db.things.find({
$or : [
{"first_name": "john"},
{"last_name": "john"}
],
"phone": "12345678"
})
A:
I believe $and is only supported in MongoDB v2.0+. I'm surprised that the console accepted the expression in the first place. I'll try to recreate against a 1.8 server I have.
Also check 10Gen's Advanced Query Documentation for $and.
Update
I entered your sample data into both a v1.8x and v2.0x MongoDB server. The query works on the v2.0x and fails on the v1.8x. This confirms my (and Miikka's) suspicions that the problem is with $and and your server version.
I found a (arguably) clever workaround for this on the Web here. I hope this helps.
-SethO
| {
"pile_set_name": "StackExchange"
} |
Q:
preferredStatusBarStyle never called
My view controller hierarchy is SWRevealViewController -> UINavigationViewController -> MyController1. MyController1 presents MyController2 using self.present. MyController2 is not within UINavigationViewController and presentation is modal (device is iPhone). In viewWillAppear of MyController2 I call self.setNeedsStatusBarAppearanceUpdate(), but preferredStatusBarStyle is never called by the system and status bar appearance remains same (as it was for MyViewController1). Am I missing something here?
EDIT
info.plist has View controller-based status bar appearance set to YES
A:
in your info.plist
View controller-based status bar appearance make it YES
A:
Our issue was a container VC.
So had to tell it to allow the contained (visible) VC to call the shots:
final class ContainerVC: UIViewController {
final var centerVC: UIViewController? // set to an OtherVC elsewhere
override var childViewControllerForStatusBarHidden: UIViewController? {
return centerVC
}
override var childViewControllerForStatusBarStyle: UIViewController? {
return centerVC
}
}
final class OtherVC: UIViewController {
override var prefersStatusBarHidden: Bool {
return true
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
}
A:
This is what worked for me in my VC...
self.modalPresentationCapturesStatusBarAppearance = true
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery where clause on json
Say I have a sample json data like:
var data = {
"items": [{
"id": 1,
"category": ["cat1","cat2"]
}, {
"id": 2,
"category": ["cat1","cat3"]
}, {
"id": 3,
"category": ["cat11","cat2"]
}]
};
Now How to return only data which contains cat1
I have tried with jquery grep like
var returnedData = $.grep(data.items, function (element, index) {
return element.category.indexOf("cat1") == 1;
});
But it's not giving me correct output which should return first and second object.
Thanks.
A:
indexOf returns index(0...n - position in array) or -1 if value does not exists in array. You need change condition to check index on > -1. In your variant you always check index == 1, but cat1 has index 0 - that's why you get empty result.
var returnedData = $.grep(data.items, function (element) {
return element.category.indexOf('cat1') >= 0;
});
Example
| {
"pile_set_name": "StackExchange"
} |
Q:
VS2010 Different publishing locations based on configuration
I'm trying to divide my solution by three configurations:
Development
Testing
Release
All above will have different publishing location, so users can work with release, do their test in testing and see what is new in development release. All three versions will be build with different name postfixes and icons and installed on each user workstation.
For now I get :
Unable to install this application because an application with the
same identity is already installed. To install this application,
either modify the manifest version for this application or uninstall
the preexisting application."
I can't even install this more than once at one workstation.
So What can I do to achive this?
A:
You can not install the same application multiple times unless you change the deployment. The easiest way to do this is by changing the assembly name. This article explains this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Property-based or constructor-based dependency injection
I just start to study Spring and I have a question:
In order to inject a bean, when is it better to use property-based dependency injection:
<bean id="myFirstClass" class="...">
<property name="targetProperty">
<bean id="TheBeanIwantToInject" class="..."/>
</property>
</bean>
instead of constructor-based dependency injection
<bean id="myFirstClass" class="...">
<constructor-arg ref="TheBeanIwantToInject"/>
</bean>
or it's just two equivalent solutions?
A:
If you want to create immutable objects then the constructor-arg variant is the only option. I prefer that one.
| {
"pile_set_name": "StackExchange"
} |
Q:
¿No han notado que la documentacion en español no es buena?
Puede existir una sección de stackoverflow dedicado para la habla hispana, pero cuando se trata de buscar como implementar una librería o alguna funcionalidad, la mayoría por no decir todos, los más completos son los que están en inglés.
No les parece?
A:
Lo que hace rico en conocimientos a StackOverflow es la gran cantidad de preguntas y respuestas que tiene. A día de hoy tiene más de 17 millones de preguntas y respuestas, acumuladas a lo largo de más de 10 años. StackOverflow en español tiene algo más de 81.000 preguntas acumuladas en algo más de 3 años. Además del tiempo, el número de usuarios de uno u otro es completamente diferente: SOes apenas tiene 1300 usuarios con una reputación de más de 100, mientras que SO tiene casi medio millón.
La única manera de aumentar y mejorar el conocimiento acumulado de la versión en español es mediante los usuarios: necesitamos usuarios activos que pregunten y respondan dudas. Esto requiere un esfuerzo, por supuesto: cada vez que no encuentres una respuesta en español pero sí en inglés, podrías crear esa pregunta y auto-responderla, ya sea traduciendo la respuesta original o aportando los conocimientos aprendidos desde cualquier otra fuente.
También puedes sencillamente preguntar y/o responder preguntas de otros usuarios para que entre todos vayamos añadiendo lo que sabemos.
Para bien o para mal, es el único camino.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it OK to return lua_integer type instead of lightuserdata in Lua when returning a C pointer?
My C library returns a C pointer to lua environment, and I need to do some simple operations based on the value of that C pointer, just like:
my_pointer = c_pointer + 4
Since I can do nothing with lightuserdata so I am wondering if that is all right to return a lua_integer type for C pointer, instead of lightuserdata, so that I can do the simple manipulation based on the value of C pointer
A:
I'll ignore the fact that c_pointer + 4 is not a "simple operation", due to the fact that C++ uses pointer arithmetic. So the result of that expression would vary depending on what type c_pointer is.
I'll assume that you want to expose the pointer as a number to Lua, which it can do numerical arithmetic to. Then you'll convert it back to a pointer at some point.
This will work... so long as you're only compiling for 32-bit machines. In 64-bit compiles, pointers will be 64-bits in size. So you can't convert them into doubles and back without loss of data.
Furthermore, you're likely to run into basic type trouble. If you expose a pointer as an integer, then presumably you've also exposed some function to Lua that takes this pointer-as-an-integer. Which means that the Lua program can shove any number at that function, which it will dutifully pretend is a pointer.
That's bad.
The correct way to do this is to not expose a pointer to Lua at all. If you need Lua to do math operations on a "pointer", expose a full userdata type that represents a pointer. But it should store the original pointer and an offset in its userdata. Overload the arithmetic operations on it, so that the user can add numbers to it and so forth. The user's additions and such should affect the offset, not the pointer. Or expose a dedicated memory buffer object, rather than a pointer.
Alternatively, expose the pointer as an opaque value, then have all of your APIs take an opaque pointer + an offset as a Lua number.
In short, don't expose pointers to Lua.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multicast between applications on the same host
From what I've read, it should be possible for two applications on the same host to be able to send and receive datagrams via multicast. I was trying to implement this, using the following Java code (which is a slightly modified version of what is given in the Javadoc for MulticastSocket):
public static void main(String[] args) throws IOException{
NetworkInterface nic = NetworkInterface.getByName("wlan4");
int port = 6789;
InetAddress group = InetAddress.getByName("228.5.6.7");
MulticastSocket s = new MulticastSocket(port);
s.setNetworkInterface(nic);
s.joinGroup(group);
if(args.length > 0 && args[0].equals("send")){
System.out.println("SEND MODE");
String msg = "Hello";
DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(),
group, port);
s.send(hi);
}else{
byte[] buf = new byte[1000];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
System.out.println("RECEIVE MODE");
s.receive(recv);
System.out.println(MessageFormat.format("Received: {0}",
new String(recv.getData()).trim()));
s.leaveGroup(group);
}
}
If I run the above code, giving send as input argument, the program executes just fine, it sends the packet and then terminates. However if I want to receive a packet, the program is blocked by the receive method as it never gets a datagram. I tested this by running multiple instances of the application on my machine, both with one and several receivers and one sender. Non gets any message at any time.
If I, on the other hand let the application receive what it just sent (by running the receive method unconditionally of wheter the application is sending), it works fine for that application alone. This triggers me to believe that the JVM instance has an exclusive bind on that socket, disallowing others to use it (even if the option getReuseAddress() returns true for MulticastSockets).
I'm running under Windows 10, and have verified that the UDP packet gets sent to the network using Wireshark, so I figured it has to do with that the packet is not delivered to the two applications.
What can I do in order to allow two applications to communicate over multicast on the same port number?
EDIT:
The overall idea is for a server to send a datagram to all listening clients on the network chosen (hence why the NIC is specified in the example as "wlan4"), irrespectively of where they are executed (e.g. on the same host as the server or not).
A:
After some debugging, I realized that I could receive multicast packets from several applications if the application itself were sending and receiving multicast datagrams. It turns out that sending a packet to the multicast group somehow triggers this functionality. It seems like a bug to me.
However, in order to get the above example work as expected, I had to send (and discard) a first datagram to the multicast channel. I did this in the most simple way, by changing the else block to the following:
byte[] buf = new byte[1000];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
s.send(new DatagramPacket("A".getBytes(), 1, group, port));
s.receive(recv);
System.out.println("RECEIVE MODE");
s.receive(recv);
System.out.println(MessageFormat.format("Received: {0}",
new String(recv.getData()).trim()));
s.leaveGroup(group);
| {
"pile_set_name": "StackExchange"
} |
Q:
Accessing getter functions inside a class using pointers
I just moved from C to C++ so i'm trying to understand the differences between classes and structs.
I'm building a code that deals with binary search trees and i'm using classes.
class Node
{
public:
// C'tor D'tors
Node();
Node(int valinput);
~Node();
// Getters
Node * getrson() const { return rson; }
Node * getlson() const { return lson; }
int getval() const { return val; }
// Setters
void setlson(Node* input) { lson = input; }
void setrson(Node* input) { rson = input; }
void setval(int input) { val = input; }
private:
int val;
Node * lson;
Node * rson;
};
I know I shouldn't access private variables directly, therefore I should use get functions. I'm building recursive functions so I use object pointers:
Node* insertion(Node* root,int val);
int checkheight(Node* root);
Node* rotate(Node* root, direction direction);
When I want to access the right son of the right son of some node, do I need to write something like:
if(root->getrson()->getrson() != nullptr)
Will this code work? Is there any "more natural" way of writing it? Should I just use structs instead of classes in this case?
A:
Yes, it will work and this is the "natural" way of doing this when you use getter functions.
When you use a struct instead, then the line would not look much different:
if(root->rson->rson != 0)
To increase the efficiency of the call, you may make the getter functions inline. However, most compilers do this implicitly by default for optimization, so there should be no need for it. In that case there is not overhead in using getter functions.
| {
"pile_set_name": "StackExchange"
} |
Q:
NSString to const char * convert with Greek characters
I'm trying to convert an NSString which contains a greek word to a const char. I'm trying to convert the string with UTF-8 encoding which is for greek language and when i'm logging the char out, it has junk in it. Please a little help here..
//this is the greek word
NSString *letter = textFieldLetter.text;
//NSString to const char conversion for the sql query
const char *cLetter = (const char *)[letter cStringUsingEncoding:NSUTF8StringEncoding];
//this contains junk!
NSLog(@"letter: %s",cLetter);
A:
You don't have to use UTF8, instead use Unicode (NSUnicodeStringEncoding).
If you see the NSStringEncoding will see this options (have more):
enum {
NSWindowsCP1253StringEncoding = 13, /* Greek */
NSUTF16StringEncoding = NSUnicodeStringEncoding,
NSUTF16BigEndianStringEncoding = 0x90000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
NSUTF16LittleEndianStringEncoding = 0x94000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
NSUTF32StringEncoding = 0x8c000100,
NSUTF32BigEndianStringEncoding = 0x98000100, /* NSUTF32StringEncoding encoding with explicit endianness specified */
NSUTF32LittleEndianStringEncoding = 0x9c000100 /* NSUTF32StringEncoding encoding with explicit endianness specified */
};
typedef NSUInteger NSStringEncoding;
You can see a specific Greek lenguage: NSWindowsCP1253StringEncoding
If is don't work, you can try to use other UTF16 or UTF32. But I think Unicode work for you.
-- edit
Take in mind that NSLog(@"%s",string); can not decode a unicode character. So, it will really show the mess.
To test if it work, do the conversion, and redo it. If is the same, so you don't lost data.
const char *cLetter = (const char *)[letter cStringUsingEncoding:NSUnicodeStringEncoding];
NSString *original = [NSString stringWithCString:cLetter encoding:NSUnicodeStringEncoding];
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a view which would list related content for current article?
I try to create a view which would list related content (some articles) to a content type article.
Here is what i’ve done. I’ve created a field "Entity reference" in the content types "Article". It works. I can see in database the related article ID .
Then, I create a view with a block. It works, i can see all articles listed in that view (which is visible on each article).
Here is my issue. I need to display only articles related to the current article. So, in contextual filter, i have tried with
Content: ID and also tried with advanced/Relationships but without success. I don’t see my related articles.
How can I do ?
I’ve also tried a different way (create a twig) and even if it works, it is not the best solution i think
A:
Ignore using fields in the View. This has been and will always be problematic IMO for 95% of Views people are making.
You need the Content ID argument from the URL so the correct node is selected, but here is where it takes a turn:
Set the view to show "Content" and give it a view mode, for instance, create a view mode called "Related Content" for nodes. In the field display for that view mode, only set the "Related Articles" field to be visible. Set its field formatter to "Rendered Entity", and create a view mode for that content type and theme it. On that content type, you would have title and body, or whatever fields you want to show (hard to tell without seeing a design).
Now the View will pull the node, render it, and in turn render the nodes that are being referenced in a view mode.
Then, you would get something like this, for example:
That is a View that looks at the current node, and renders it. The view mode has a field (Related Content), which is a node reference, and those nodes are rendering in a "Preview" view mode - and this is the result. All of the markup lives in two twig files (for the node--node-type--view-mode.html.twig) and the Views configuration is super simple.
The Views display would be a block, and you can place that block in whatever region works for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fxcop custom rule not showing in Fxcop GUI
I've created a Fxcop custom rule and defined the xml file. When I add the custom rule assembly in Fxcop GUI it is not showing the rule. Please find below the related info:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.FxCop.Sdk;
namespace TestCustomRules
{
public class TestRule : BaseIntrospectionRule
{
public TestRule() : base("TestRule", "TestCustomRules.TestRules", typeof(TestRule).Assembly) { }
public override ProblemCollection Check(Member member)
{
Problems.Add(new Problem(new Resolution("TEST Rule {0}", "Chill out")));
return Problems;
}
}
}
The xml file:
<?xml version="1.0" encoding="utf-8" ?>
<Rules FriendlyName="Test Rules">
<Rule TypeName="TestRule" Category="TestRule" CheckId="TR1000">
<Name>Test Rule</Name>
<Description>Test Rule</Description>
<Owner>Vibgy Joseph</Owner>
<Url />
<Resolution>This is just a test rule.</Resolution>
<Email />
<MessageLevel Certainty="99"> Warning</MessageLevel>
<FixCategories> Breaking </FixCategories>
</Rule>
</Rules>
Following is the info displayed in Fxcop when I add it. Please note that the Total Children is 0.
FxCop Rule Assembly c:\users\vibgy.j\documents\projects\01_common\testcustomrules\testcustomrules\bin\debug\testcustomrules.dll
{
Checked : True (Boolean)
Children : Count == 1 (NodeBaseDictionaryCollection)
Container : Count == 10 (NodeBaseDictionary)
DefaultCheckState : True (Boolean)
DisplayName : TestCustomRules.dll (String)
FileIdentifier : C:\Users\vibgy.j\Documents\Projects\01_Common\TestCustomRules\TestCustomRules\bin\Debug\TestCustomRules.dll (String)
FileName : C:\Users\vibgy.j\Documents\Projects\01_Common\TestCustomRules\TestCustomRules\bin\Debug\TestCustomRules.dll (String)
FullyQualifiedName : C:\Users\vibgy.j\Documents\Projects\01_Common\TestCustomRules\TestCustomRules\bin\Debug\TestCustomRules.dll (String)
HasChildren : True (Boolean)
HasMessages : True (Boolean)
ImageIndex : 1 (Int32)
LoadExceptions : Microsoft.FxCop.Common.ExceptionCollection (ExceptionCollection)
LocalFileName : TestCustomRules.dll (String)
Messages : Count == 0 (MessageStatusNodeBaseMessageDictionary)
Metadata : <null> (Object)
Name : c:\users\vibgy.j\documents\projects\01_common\testcustomrules\testcustomrules\bin\debug\testcustomrules.dll (String)
Rules : Count == 0 (RuleDictionary)
Status : New (NodeStatus)
TotalChildren : 0 (Int32)
TotalChildrenChecked : 0 (Int32)
Version : 1.0.0.0 (String)
}
A:
Oops! I've missed to set the property 'Build Action' for xml file to 'Embedded Resource'. Now it's getting displayed in Fxcop.
| {
"pile_set_name": "StackExchange"
} |
Q:
how do I use XUI tween?
I don't understand how to use XUI tween. On the xui website, they give the following example code:
x$('#box').tween([{left:'100px', backgroundColor:'green', duration:.2 }, { right:'100px' }]);
What is that supposed to do? I created a <div id="box"></div>, ran the line of js code above, but nothing happened. Here's my complete code:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="xui.min.js"></script>
<script type="text/javascript">
x$('#box').tween([{left:'100px', backgroundColor:'green', duration:.2 }, { right:'100px' }]);
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
Nothing happens...
A:
So, XUI's tween seems to be a work in process. In fact, in the master branch code on GitHub you find:
// queued animations
/* wtf is this?
if (props instanceof Array) {
// animate each passing the next to the last callback to enqueue
props.forEach(function(a){
});
}
*/
So, in short, the array-based tween properties appear busted at the moment. In addition, XUI's tween seems to be a little flakey when dealing with properties that are not currently set on the DOM element. (For example, setting the background-color on a transparent element turns it black...rather than the intended color.)
That said, the single tween and callback work well on previously set properties. So take a look at the following (and excuse the inline css):
<html>
<head>
<script type="text/javascript" src="http://xuijs.com/downloads/xui-2.3.2.min.js"></script>
<script type="text/javascript">
x$.ready(function(){
setTimeout(function(){
x$('#box').tween({'left':'100px', 'background-color':'#339900', duration:2000}, function(){
x$('#box').tween({'left':'500px', duration:2000});
});
}, 500);
});
</script>
</head>
<body style="position:relative;">
<div id="box" style="position:absolute;top:50px;left:500px;width:100px;height:100px;background-color:#fff;border:1px solid #000;">the box</div>
</body>
</html>
Because #box now has a css background-property and left position explicitly set, it is relatively easy to produce an effect similar to the one desired.
One-half second after the page loads, #box should spend 2 seconds moving from left:500px to left:100px while turning the background color from white to green. Then, using the callback, #box moves back to its original position at left:500px--taking another 2 seconds to get back.
Obviously, this does not answer your exact question but for those (like me) who stumble upon this, it provides a workaround for the time being.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android - How to switch theme on runtime
Could someone tell me how i can switch the the theme from holo to holo light in my application on runtime ?
I would like to have two buttons in settings to choose light or black theme.
How can it be set applicationwide and not only for the activity ?
I already tried a few things with setTheme() but i wasn't able to change the theme when i click a button.
This is my Settings activity where i would like to set the theme:
public class SettingsActivity extends Activity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(android.R.style.Theme_Holo_Light);
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
}
well this works and my Theme is set but as i am saying i would like to change it systemwide by pressing a button.
Thanks !
A:
You cannot change the theme of other applications (thank goodness).
The only way to somewhat accomplish this would be to create your own build of the operating system with your own theme as the device default theme. However, applications that do not use the device default theme (i.e. they explicitly set the theme to Holo, Holo light, etc) will not get the device default theme.
Edit- To accomplish this application-wide using a base Activity, create an Activity that looks like this:
public class BaseActivity extends Activity {
private static final int DEFAULT_THEME_ID = R.id.my_default_theme;
@Override
public void onCreate(Bundle savedInstanceState) {
int themeId = PreferenceManager.getDefaultSharedPreferences(context)
.getInt("themeId", DEFAULT_THEME_ID);
setTheme(themeId);
super.onCreate(savedInstanceState);
}
}
Then all of your Activities should extend this BaseActivity. When you want to change the theme, be sure to save it to your SharedPreferences.
A:
As you can see theme is setting on the onCreate() and before setContentView(). So you should call the oncreate() method again when you want to change the theme. But the onCreate() function will be called only once in the life cycle of an Activity.
There is a simple way to do this. I am not sure that it is the best way.
Suppose you want to apply new theme to Activity 1 on a button click.
inside the onClick event
Save the theme to be applied such that it should be retained even after the application restart (preferences or static volatile variables can be used).
Finish the current activity (Activity 1) and call a new activity (Activity 2).
Now in Activity 2
Call Activity 1 and finish current activity (Activity 2).
In Activity 1
Apply the saved theme inside onCreate.
Hope it is not confusing.. :)
| {
"pile_set_name": "StackExchange"
} |
Q:
A function that depends on properties of the input argument?
I was just wondering if one can write a mathematical function whose parameters depend on the properties of the input argument, and if yes, then how. Say, for example, a function that gives out the square of the argument if the argument if odd and gives out cube of the argument if the argument is even. How do I write this function mathematically? Also, how do I study this function and understand its properties? Any help regarding this, including other resources, would be very helpful.
PS: I belong to the field of biochemistry, so I don't have much knowledge regarding mathematics, I just keep studying maths as a hobby; so forgive me if my question is too naïve. Also, sorry for the computer science-like explanation of my question, I ain't familiar with terminology in this field :)
A:
You can write the definition of such $f$ like this:
$$f(n)=\begin{cases}n^2&\text{if }n\text{ is odd}\\n^3&\text{if }n\text{ is even}\end{cases} $$
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem with testing a Windows service
I want to make a Windows service that will access my database. My database is SQL Server 2005.
Actually I am working on a website and my database is inside our server. I need to access my database every second and update the records. For that purpose I need to make a Windows service that will install into our server and perform the task.
I have been accessing the database from my local machine and then running the service, but problem is I'm not sure how I can test this service.
I tried to install into my local machine. It installed and then I ran the service but it did not perform the task and I think service is not able to connect with the database.
There is no problem in the service nor its installer. The only issue is how to test my Windows service.
A:
You can always create a service / console app hybrid, and use the console app for testing purposes.
What you need to do is something like this - in your program.cs, change the Main method to either run the service, or optionally run as a console app:
static class Program
{
static void Main(params string[] args)
{
string firstArgument = string.Empty;
if (args.Length > 0)
{
firstArgument = args[0].ToLowerInvariant();
}
if (string.Compare(firstArgument, "-console", true) == 0)
{
new YourServiceClass().RunConsole(args);
}
else
{
ServiceBase[] ServicesToRun = new ServiceBase[] { new YourServiceClass() };
ServiceBase.Run(ServicesToRun);
}
}
and then on your service class, which inherits from ServiceBase and has the OnStart and OnStop, add the RunConsole method like so:
public void RunConsole(string[] args)
{
OnStart(args);
Console.WriteLine("Service running ... press <ENTER> to stop");
//Console.ReadLine();
while (true)
{ }
OnStop();
}
Now if you want to run the app to test its functionality, just launch the EXE with a -console command line parameter, and put a breakpoint in the RunConsole method.
A:
You can attach the visual studio solution to the windows service application. Then you can debug the windows service as you do a normal project.
Debug --> Attach to process.
A:
Use a logger to report errors !
Try catch every possible error and log them in a file and/or better send an email : remember "no one hears a service dying" !
Log4Net has logger to handle rolling files, dabatase persistence and even SMTP message. For example, see : http://logging.apache.org/log4net/release/config-examples.html
You'll have probably to check the log file for errors quite regularly. To avoid this kind of chore, I often use the SMTP appender.
Cheers,
B.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python side-by-side merge of comma-delimited text files
Suppose I have two text files with the content shown below.
Text file 1:
Apple, 0
Pear, 1
Orange, 0
Text file 2:
Apple, 1
Pear, 1
Orange, 1
I wish to merge them in a side-by-side fashion, keeping only the left "column", which is identical for both text files, of text file 1. That is, I wish to produce the following merged text file.
Merged text file:
Apple, 0, 1
Pear, 1, 1
Orange, 0, 1
I'm trying to find how to---in a reasonably small amount of code---perform such a merge. But, in the real problem, there can be any number of text files. How can I do this in Python?
Assumptions:
Every text file will have exactly the same number of rows.
Every text file will be a comma delimited file with exactly 1 comma per line.
For every row in every text file, the value to the left of the comma is exactly the same.
A:
fileinput.input will take a list is files, use an ordereddict to concat all the values and maintain order:
from collections import OrderedDict
d= OrderedDict()
import fileinput
with open("joined.txt","w") as f:
for line in fileinput.input(["file1.txt","file2.txt","file3.txt","file4.txt"]):
spl = line.strip().split(",")
d.setdefault(spl[0],[])
d[spl[0]] += spl[1:]
for k,v in d.items():
f.write("{} {}\n".format(k,",".join(v)))
If they are all in their own directory you can pass os.listdir to fileinput:
from collections import OrderedDict
d= OrderedDict()
import fileinput
import os
with open("joined.txt","w") as f:
for line in fileinput.input(os.listdir("path_to")):
spl = line.strip().split(",")
d.setdefault(spl[0],[])
d[spl[0]] += spl[1:]
for k,v in d.items():
f.write("{} {}\n".format(k,",".join(v)))
If they are not the only files but follow a pattern you can use glob:
import fileinput
import os
import glob
with open("joined.txt","w") as f:
for line in fileinput.input(glob.glob("./file*.txt")):
spl = line.strip().split(",")
d.setdefault(spl[0],[])
d[spl[0]] += spl[1:]
for k,v in d.items():
f.write("{} {}\n".format(k,",".join(v)))
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing form data from one webpage to another
I was trying to send form data from one webpage to another using this:
Passing data from one web page to another
I am pasting the javascript code of the function i created:
function store(){
window.localStorage.setItem("name",document.getElementById("name").value);
window.localStorage.setItem("email",document.getElementById("email").value);
window.localStorage.setItem("tele",document.getElementById("tele").value);
window.localStorage.setItem("gender",document.getElementById("gender").value);
window.localStorage.setItem("comment",document.getElementById("comments").value);
window.location.href = "contact.html";
}
But the Problem is that the window.location.href is not working and the webpage is not redirected.
I have seen the console for errors but there aren't any.
Can anyone tell Where is the fault?
EDIT 1:
Validate function:
function validate(){
var comment = document.getElementById("comments").value;
var gender = document.getElementById("gender").value;
var len = comment.length;
if (len > 100)
{
alert("Reduce the length of the comment less than 100 characters");
}
else if (gender == "Select Gender")
{
alert("Please Select a gender");
}
else {
store();
}
}
Form's html:
<form class="form-horizontal" role="form">
Submit Button:
<input type="submit" id="submit" value="Submit" onclick="validate()">
A:
Have a look at this plunker:
https://plnkr.co/edit/P4XqhYciFxZeYlRbWXtd?p=preview
<form class="form-horizontal" role="form">
<textarea rows="4" cols="50" id="comments" placeholder="Enter comments"></textarea>
<br />
<select id="gender">
<option value="Select Gender">Select Gender</option>
<option value="male">male</option>
<option value="female">female</option>
</select>
<br />
<button type="button" id="submit" onclick="validate()">Go</button>
</form>
I have updated the plunker. The page is redirecting and you can see that the values are saved in the local storage. It works fine.
Perhaps you had a problem because of your input submit, I used a button instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
Two dimensional table index generator using Python's itertools
I'd like to place items from a list at sequential indexes of a table, with the number of columns being controlled by the input. I know how to do this the "boring" way by incrementing or resetting integers at the end of each column, but I figure there is probably a more elegant way to do this with Python's itertools library.
Consider this list:
items = ["Apple", "Orange", "Pear", "Strawberry", "Banana"]
Here is the boring way:
def table_indexes(items, ncol):
col = 0
row = 0
for item in items:
yield (col, row)
col += 1
if col >= ncol:
# end of row
col = 0
row += 1
This would yield indexes that place the items at the following table indexes:
| Apple | Orange |
| Pear | Strawberry |
| Banana | |
I'd like to find a function in itertools or elsewhere that can yield a sequence of index pairs where one index in each pair cycles through a sequence of numbers repeatedly (column numbers), and the other index increases by 1 every time the first cycle repeats? Like so:
def table_indexes(items, ncol):
cols = ... # e.g. itertools.cycle(range(ncol))
rows = ... # needs to be an iterator yielding sequences of [i]*ncol where i is the current row index
yield zip(cols, rows):
Can the solution be extended to N dimensions?
A:
looks like you can use repeat.
from itertools import chain, repeat
def table_indexes(items, ncol):
cols = chain.from_iterable(repeat(range(ncol), len(items)//ncol + 1))
for x, (col, item) in enumerate(zip(cols, items)):
yield x//ncol, col, item
items = ["Apple", "Orange", "Pear", "Strawberry", "Banana"]
list(table_indexes(items, 3))
output:
[(0, 0, 'Apple'),
(0, 1, 'Orange'),
(0, 2, 'Pear'),
(1, 0, 'Strawberry'),
(1, 1, 'Banana')]
more details, the repeat gives us an list of columns
repeat(range(ncol), len(items)//ncol + 1) --> [[0, 1, 2], [0, 1, 2]]
and while we loop through the enumeration of the items, the construction x // ncol gives us the number of the row.
| {
"pile_set_name": "StackExchange"
} |
Q:
where can I find information about my phone by imei
where can I find information about my phone by imei? I want to buy a second hand phone, but I heard that many are declared stolen or lost and after you buy it, police will come and take it away. The phone I want to buy is htc sensation with android 2.3
A:
My suggestion is imeidata.net. I've gotten incorrect data from the sites mentioned in other answers.
For example, for my phone, imei.info gives the wrong data:
Model: Sidekick LX Brand: T-MOBILE
imeidata.net is correct:
IMEI: 3536910674xxxxx
Allocating Body: BABT
Type Allocation Code: 35369106
Serial Number: 749450
Luhn Checksum: 9
Manufacturer: SAMSUNG KOREA
Brand: SAMSUNG
Model: SM-G355H
| {
"pile_set_name": "StackExchange"
} |
Q:
C# - how to make a sequence of method calls atomic?
I have to make a sequence of method calls in C# such that, if one of them fails, the subsequent methods should not be called. In short, the set of calls should be made atomic. How do I achieve this in C#?
A:
I think you're confusing the word "atomic" with something else. Atomic is when an operation cannot be interrupted and is usually done in multi threaded scenarios to protect shared resources.
What you want is normal control flow logic and the solution depends on what your methods looks like.
One solution could be to have them return a boolean indicating whether or not it succeeded:
bool success = false;
success = MethodA();
if (!success)
return;
success = MethodB();
if (!success)
return;
// or even like this as suggested in another answer
if (MethodA() &&
MethodB() &&
MethodC())
{
Console.WriteLine("All succeeded");
}
You could also use exceptions and wrap all your method calls inside a try-catch block. If one of them fails (throws an exception), your catch block will execute and nothing after that method call in the try-block will get a chance to run.
try
{
MethodA();
MethodB();
MethodC();
}
catch (MyMethodFailedException)
{
// do something clever
}
If you need rollback functionality, you have to get into transactions but that's a whole bigger topic.
A:
TransactionScope might be what you need see here
void RootMethod()
{
using(TransactionScope scope = new TransactionScope())
{
/* Perform transactional work here */
SomeMethod();
SomeMethod2();
SomeMethod3();
scope.Complete();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Confused about drawing a rectangle in WPF
I want to draw a rectangle on a canvas in WPF. For drawing a line I can do this:
line.X1 = ls.P0.X;
line.Y1 = ls.P0.Y;
line.X2 = ls.P1.X;
line.Y2 = ls.P1.Y;
MyCanvas.Children.Add(line);
...in other words the location is a property of the line itself. I want to draw a rectangle the same way, i.e., assign its coordinates and add it to my canvas. But the examples I've seen online so far seem to look like this:
rect = new Rectangle
{
Stroke = Brushes.LightBlue,
StrokeThickness = 2
};
Canvas.SetLeft(rect,startPoint.X);
Canvas.SetTop(rect,startPoint.X);
canvas.Children.Add(rect);
...in other words it doesn't look like the rectangle has an inherent location, but instead its location is set by calling a method of Canvas. Is this true - Lines have inherent coordinates but Rectangles do not? Is there any way to have a rectangle in WPF with an inherent location, like a line, or do I have to roll my own (using lines)?
A:
You could use a Path control with a RectangleGeometry like this:
var rect = new Path
{
Data = new RectangleGeometry(new Rect(x, y, width, height)),
Stroke = Brushes.LightBlue,
StrokeThickness = 2
};
canvas.Children.Add(rect);
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I loop through an array in Vue half the amount of times as there are items?
I have an array of data:
[
{
type: select,
options: [foo, bar],
label: foo,
required: true
},
{
type: text,
options: [],
label: bar,
required: false
},
{
type: checkbox,
options: [],
label: baz,
required: true
}
]
and a Vue template:
<b-row>
<b-col>
<label :for="{{label}}">{{ label }}<span class="required" v-if="required"/></label>
{{ checks type and injects proper form element here }}
</b-col>
</b-row>
I'm trying to figure out how best to loop through each object, and place each one into its own <b-col>, with only two columns per row so that it looks similar to the following structure:
<b-row>
<b-col>
<label for="size">foo<span class="required" v-if="required"/></label>
<b-form-select id="size">
<options>foo</options>
<options>bar</options>
</b-form-select>
</b-col>
<b-col>
<label for="size">bar<span class="required" v-if="required"/></label>
<b-form-text id="size"/>
</b-col>
</b-row>
<b-row>
<b-col>
<label for="size">baz<span class="required" v-if="required"/></label>
<b-form-select id="size"/>
</b-col>
<label for="size">barbaz<span class="required" v-if="required"/></label>
<b-form-select id="size"/>
</b-col>
</b-row>
...etc.
I'm struggling to find the best approach to accomplish this cleanly and in a vue-like manner.
A:
You can just iterate through the array, place each element inside a b-col and specify the width of each of those columns to be 50%, like this:
<b-row>
<b-col v-for="item in array" sm="6">
...do something with item
</b-col>
</b-row>
sm="6" tells bootstrap to use the amount of space equal to 6 columns (i.e. 50%)
I am not sure about vue-bootstrap, but the bootstrap documentation states:
If more than 12 columns are placed within a single row, each group of
extra columns will, as one unit, wrap onto a new line
https://getbootstrap.com/docs/4.1/layout/grid/#column-wrapping
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I save a XML file (sourced from API) at runtime?
I am needing to get data from my online CRM to my website. The data is sourced from an API, which returns a long list of XML code. I then need to process this XML using PHP to put it on my website (only part of it is needed).
I know XSLT is preferred over PHP for XML processing but I haven't learnt XSLT as yet (getting to that next week) so will use PHP for now.
Just need to know how to save the API's XML file to my server at runtime so I can reference it in my PHP?
A:
Instead of PHP's painstaking XML parsing script, you may want to check out json_decode() which can convert an XML object into an associative array.
eg. $data = json_decode($xmlData, true);
check out https://stackoverflow.com/a/6534234/668703 for a complete example.
As for saving the content on to your server, check out file_put_contents (http://au1.php.net/function.file-put-contents), just keep in mind that you'll need a string to store into the file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to permanently miss items?
In Bastion, some levels have items lying on the ground. Some of them merely provide NPC dialog, others are weapon upgrade materials, all of them give a small XP bonus.
The levels I've already cleared are marked with a red star on the map, and I can't revisit them.
If I clear a level without picking up all the items, are they lost forever, or would I be able to replay the level in this case? Can I miss out on weapon upgrades by not being thorough enough?
A:
All items that you miss turn up in the Lost and Found item shop. The only penalty for missing them is that you have to buy them instead of getting them for free.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic Linq OrderBy null error
I'm using dynamic Linq to order a result set depending on which column is passed in. I'm using this to order a table when a user clicks on a table column.
If the property im ordering on is a class which is null the code falls over, i want to be able to dynamically orderby a string but cater for nulls if the property is a class.
This is the code from the System.Linq.Dynamic class im using.
public static IQueryable OrderBy(this IQueryable source, string ordering,
params object[] values)
{
if (source == null) { throw new ArgumentNullException("source"); }
if (ordering == null) { throw new ArgumentNullException("ordering"); }
ParameterExpression[] parameters = new ParameterExpression[1]
{
Expression.Parameter(source.ElementType, "")
};
IEnumerable<DynamicOrdering> enumerable = new ExpressionParser(
parameters, ordering, values).ParseOrdering();
Expression expression = source.Expression;
string str1 = "OrderBy";
string str2 = "OrderByDescending";
foreach (DynamicOrdering dynamicOrdering in enumerable)
{
expression = (Expression) Expression.Call(typeof (Queryable),
dynamicOrdering.Ascending ? str1 : str2, new Type[2]
{
source.ElementType,
dynamicOrdering.Selector.Type
}, new Expression[2]
{
expression,
(Expression) Expression.Quote((Expression) Expression.Lambda(
dynamicOrdering.Selector, parameters))
});
str1 = "ThenBy";
str2 = "ThenByDescending";
}
return source.Provider.CreateQuery(expression);
}
and calling it like this
if (property.PropertyType == typeof(Sitecore.Data.Items.Item))
{
orderByProperty = property.Name + ".Name";
}
else
{
orderByProperty = property.Name;
}
return tableOrder == TableOrder.az
? projects.OrderBy(orderByProperty + " ascending").ToList()
: projects.OrderBy(orderByProperty + " descending").ToList();
the property is sometimes a class, if this is the case i want to be able to order it by a field called name on the class. The above code works but if the property is a class and null then it falls over.
How do I order by a field and have the null items at the end?
A:
I've found the answer. Replace the OrderBy query in the System.Linq.Dynamic.DynamicQueryable class with the below. It will handle nulls in a property that is an object.
public static IQueryable OrderBy(this IQueryable source, string ordering,
params object[] values)
{
//This handles nulls in a complex object
var orderingSplit = ordering.Split(new char[] {' '},
StringSplitOptions.RemoveEmptyEntries);
var sortField = orderingSplit[0];
var splitted_sortField = sortField.Split(new char[] { '.' },
StringSplitOptions.RemoveEmptyEntries);
if (splitted_sortField.Length > 1)
{
sortField = "iif(" + splitted_sortField[0] + "==null,null," + sortField + ")";
}
ordering = orderingSplit.Length == 2
? sortField + " " + orderingSplit[1]
: sortField;
if (source == null) throw new ArgumentNullException("source");
if (ordering == null) throw new ArgumentNullException("ordering");
ParameterExpression[] parameters = new ParameterExpression[] {
Expression.Parameter(source.ElementType, "") };
ExpressionParser parser = new ExpressionParser(parameters, ordering, values);
IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
Expression queryExpr = source.Expression;
string methodAsc = "OrderBy";
string methodDesc = "OrderByDescending";
foreach (DynamicOrdering o in orderings)
{
queryExpr = Expression.Call(
typeof(Queryable), o.Ascending ? methodAsc : methodDesc,
new Type[] { source.ElementType, o.Selector.Type },
queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters)));
methodAsc = "ThenBy";
methodDesc = "ThenByDescending";
}
return source.Provider.CreateQuery(queryExpr);
}
Taken the code from here and baked it directly into the Dynamic Linq function.
Null Reference Exception in a Dynamic LINQ Expression
| {
"pile_set_name": "StackExchange"
} |
Q:
"invalid qualifier" error with array.Contains
my father wanted a macro in Excel, but for that kind of problem he needs Visual Basic. I decided to help him, but I never wrote a Visual Basic code so I was kind of putting the code together from internet forums and mnsd, but then I ran into this problem and I don't know how to solve it.
Dim strArray() As String
Dim TotalRows As Long
Dim i As Long
TotalRows = Rows(Rows.Count).End(xlUp).Row
ReDim strArray(1 To TotalRows)
For i = 2 To TotalRows
If Not strArray.Contains(Cells(i, 1).Value) Then
strArray(i) = Cells(i, 1).Value
End If
Next
This is only a part of the code, but here is the bug.
It show an error that says
"Invalid qualifier"
and highlights strArray in strArray.Contains(Cells.... I can't solve it so I'm asking here. I think that there is a really easy solution, but I wasn't able to find it online.
Thanks in advice
Tomas
A:
The variable strArray is a plain array of type string not a List or other object so it doesn't have a "Contains" method you will have to do something like:
Dim strArray() As String
Dim TotalRows As Long
Dim i As Long
TotalRows = Rows(Rows.Count).End(xlUp).Row
ReDim strArray(1 To TotalRows)
For i = 2 To TotalRows
Dim x As Long
Dim contains As Boolean
contains = False
For x = LBound(strArray) To UBound(strArray)
If strArray(x) = Cells(i, 1).Value Then
contains = True
End If
Next
If Not contains Then
strArray(i) = Cells(i, 1).Value
End If
Next
Note that Lbound and Ubound will get the upper and lower bound of the array which can change because you Redim the array. You could also just use 1 to TotalRows since you "know" the size of the array but since I don't know how complex your actual code is I include Lbaound and Ubound in case you need them in your actual code.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to verify user url matches user in token in Django-Rest-Framework
I'm trying to create an object (called Post) in DRF where one of the fields is user, which should represent the user that created the object. I'm using Token-authentication, and I want to make sure that the request.user matches the user passed to the object. However, I'm using HyperLinkedModelSerializers so I pass the url of the user to the PostSerializer.
How do I get the url of the request.user? Do I have to create a url field in my user?
Here's the serializer classes:
class UserSerializer(serializers.HyperlinkedModelSerializer):
User = get_user_model()
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('username', 'password')
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
return user
class PostSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Post
fields = ('id', 'user', 'caption', 'video_link')
def create(self, validated_data):
return Post(**validated_data)
and here's the viewset
class PostViewSet(viewsets.ModelViewSet):
serializer_class = PostSerializer
queryset = Post.objects.all()
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
A:
If the user logged in system, you can rewrite PostSerializer like following:
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('caption', 'video_link')
def create(self, validated_data):
post = Post(user=self.request.user, caption=validated_data['caption'], video_link=validated_data['video_link'])
post.save()
return validated_data
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between simple object literal and nested object literal
Simple Object Literal:
var obj = {};
obj.name = 'stackoverflow';
obj.age = 13;
vs
Nested Object Literal:
var obj = {
name: 'stackoverflow',
age: 13
}
What is the difference between Simple Object Literal and Nested Object Literal?
Which way is better?
A:
These are technically the same thing the difference is just in the syntax. You can create your object and all of it's properties at the same time, add the properties latter, or include some at creation time and then add others latter. It it's the flexibility of JavaScript objects.
One powerful aspect of this is that you can create an object in your program and then allow your users or application flow to add or remove the properties in dynamically latter through functions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java 2D array problem
I want to assign some value in a 2D array.
I have 2 attributes called product and price.
iPad 999.9
iPod 123.4
iPhone 432.1
In 1-D array, I know how to assign the product value.
String[] product = {"iPad", "iPod", "iPhone"};
However, in 2D array, if I assign like this:
String[][] array = new String[3][1];
array[0][1] = "iPad";
How can I assign the float number into the array?
Also, I have a question for sorting.
Since I declare the type of 2D array as String.
Can I sort the float price using this array?
Or I need to declare another array to do the sorting?
Thank
A:
You will save yourself lots of trouble, if you use objects instead of arrays to store products. E.g.,
class Product {
String name;
double price;
}
(add access modifiers, setters/getters and constructors if necessary)
Now you can access array of products easily without type conversions.
Product[] array = new Product[3];
array[0] = new Product();
array[0].name = "iPad";
array[0].price = 123.4;
Or, if you add constructor,
Product[] array = {
new Product("iPad", 123.4),
new Product("iPod", 234.5),
new Product("iPhone", 345.6)
};
To allow sorting, you can implement Comparable interface and then call Arrays.sort(myProductArray):
class Product implements Comparable<Product> {
String name;
double price;
public int compareTo(Product p) {
return ((Double) price).compareTo(p.price);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I open a folder in Windows Explorer?
I don't need any kind of interface. I just need the program to be an .exe file that opens a directory (eg. F:).
What kind of template would I use in C#? Would something other than Visual Studio work better? Would a different process entirely work better?
A:
In C# you can do just that:
Process.Start(@"c:\users\");
This line will throw Win32Exception when folder doesn't exists. If you'll use Process.Start("explorer.exe", @"C:\folder\"); it will just opened another folder (if the one you specified doesn't exists).
So if you want to open the folder ONLY when it exists, you should do:
try
{
Process.Start(@"c:\users22222\");
}
catch (Win32Exception win32Exception)
{
//The system cannot find the file specified...
Console.WriteLine(win32Exception.Message);
}
A:
Create a batch file , for example open.bat
And write this line
%SystemRoot%\explorer.exe "folder path"
If you really want to do it in C#
class Program
{
static void Main(string[] args)
{
Process.Start("explorer.exe", @"C:\...");
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Does scikit-learn have forward selection/stepwise regression algorithm?
I'm working on the problem with too many features and training my models takes way too long. I implemented forward selection algorithm to choose features.
However, I was wondering does scikit-learn have forward selection/stepwise regression algorithm?
A:
No, sklearn doesn't seem to have a forward selection algorithm. However, it does provide recursive feature elimination, which is a greedy feature elimination algorithm similar to sequential backward selection. See the documentation here:
http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html
A:
Scikit-learn indeed does not support stepwise regression. That's because what is commonly known as 'stepwise regression' is an algorithm based on p-values of coefficients of linear regression, and scikit-learn deliberately avoids inferential approach to model learning (significance testing etc). Moreover, pure OLS is only one of numerous regression algorithms, and from the scikit-learn point of view it is neither very important, nor one of the best.
There are, however, some pieces of advice for those who still need a good way for feature selection with linear models:
Use inherently sparse models like ElasticNet or Lasso.
Normalize your features with StandardScaler, and then order your features just by model.coef_. For perfectly independent covariates it is equivalent to sorting by p-values. The class sklearn.feature_selection.RFE will do it for you, and RFECV will even evaluate the optimal number of features.
Use an implementation of forward selection by adjusted $R^2$ that works with statsmodels.
Do brute-force forward or backward selection to maximize your favorite metric on cross-validation (it could take approximately quadratic time in number of covariates). A scikit-learn compatible mlxtend package supports this approach for any estimator and any metric.
If you still want vanilla stepwise regression, it is easier to base it on statsmodels, since this package calculates p-values for you. A basic forward-backward selection could look like this:
```
from sklearn.datasets import load_boston
import pandas as pd
import numpy as np
import statsmodels.api as sm
data = load_boston()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = data.target
def stepwise_selection(X, y,
initial_list=[],
threshold_in=0.01,
threshold_out = 0.05,
verbose=True):
""" Perform a forward-backward feature selection
based on p-value from statsmodels.api.OLS
Arguments:
X - pandas.DataFrame with candidate features
y - list-like with the target
initial_list - list of features to start with (column names of X)
threshold_in - include a feature if its p-value < threshold_in
threshold_out - exclude a feature if its p-value > threshold_out
verbose - whether to print the sequence of inclusions and exclusions
Returns: list of selected features
Always set threshold_in < threshold_out to avoid infinite looping.
See https://en.wikipedia.org/wiki/Stepwise_regression for the details
"""
included = list(initial_list)
while True:
changed=False
# forward step
excluded = list(set(X.columns)-set(included))
new_pval = pd.Series(index=excluded)
for new_column in excluded:
model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included+[new_column]]))).fit()
new_pval[new_column] = model.pvalues[new_column]
best_pval = new_pval.min()
if best_pval < threshold_in:
best_feature = new_pval.argmin()
included.append(best_feature)
changed=True
if verbose:
print('Add {:30} with p-value {:.6}'.format(best_feature, best_pval))
# backward step
model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included]))).fit()
# use all coefs except intercept
pvalues = model.pvalues.iloc[1:]
worst_pval = pvalues.max() # null if pvalues is empty
if worst_pval > threshold_out:
changed=True
worst_feature = pvalues.argmax()
included.remove(worst_feature)
if verbose:
print('Drop {:30} with p-value {:.6}'.format(worst_feature, worst_pval))
if not changed:
break
return included
result = stepwise_selection(X, y)
print('resulting features:')
print(result)
This example would print the following output:
Add LSTAT with p-value 5.0811e-88
Add RM with p-value 3.47226e-27
Add PTRATIO with p-value 1.64466e-14
Add DIS with p-value 1.66847e-05
Add NOX with p-value 5.48815e-08
Add CHAS with p-value 0.000265473
Add B with p-value 0.000771946
Add ZN with p-value 0.00465162
resulting features:
['LSTAT', 'RM', 'PTRATIO', 'DIS', 'NOX', 'CHAS', 'B', 'ZN']
A:
Sklearn DOES have a forward selection algorithm, although it isn't called that in scikit-learn. The feature selection method called F_regression in scikit-learn will sequentially include features that improve the model the most, until there are K features in the model (K is an input).
It starts by regression the labels on each feature individually, and then observing which feature improved the model the most using the F-statistic. Then it incorporates the winning feature into the model. Then it iterates through the remaining features to find the next feature which improves the model the most, again using the F-statistic or F test. It does this until there are K features in the model.
Notice that the remaining features that are correlated to features incorporated into the model will probably not be selected, since they do not correlate with the residuals (although they might correlate well with the labels). This helps guard against multi-collinearity.
| {
"pile_set_name": "StackExchange"
} |
Q:
recursively mix strings
I'm trying to link two string together recursively, but not getting the expected results:
For the two strings "abcd" and "xyz" - expected output should be "axbyczd":
def strr(str1, str2):
def recstr(str1, str2, prn):
if str1 == '':
return str2
if str2 == '':
return str1
else:
return prn + recstr(str1[:len(str1)-len(prn)],str2[:len(str2)-len(prn)],prn)
return recstr(str1, str2, '')
print strr("abcdef","12345")
A:
When you ran out of characters in either string, you returned the other string without concatenating it to a running accumulator. Look at what I do when s1 or s2 is empty.
Also, in your recursive case, you have a very complex slicing of s1 and s2. You should really only need to slice s1[1:] and s2[1:]
This should do it
def recstr(s1, s2, answer=''):
if not s1:
return answer+s2
if not s2:
return answer+s1
return recstr(s1[1:], s2[1:], answer+s1[0]+s2[0])
In [15]: s1,s2 = 'abcd', 'xyz'
In [16]: print recstr(s1,s2)
axbyczd
Of course, a much cleaner way to do this would be to use itertools.izip_longest and itertools.chain.from_iterable:
In [23]: zips = itertools.izip_longest(s1,s2, fillvalue='')
In [24]: ''.join(itertools.chain.from_iterable(zips))
Out[24]: 'axbyczd'
[Thanks @AshwiniChaudhary for pointing out the fillvalue param in izip_longest]
Hope this helps
| {
"pile_set_name": "StackExchange"
} |
Q:
In Diablo 3 how to start single player mode?
What I mean by single player mode is I want to create game and don't allow others to join.
Sometimes there are things I wanna do alone like finding Kanai's cube. Other people keep on wanting to do something else.
I know I can join game. There's an option for that. But how to create game? Single player game?
A:
Single player game in 4 easy steps:
Make sure you are not in a party.
Make sure no one can join the game you make without permission.
Click on game settings to pick your game mode and difficulty level. Make sure it will be a PRIVATE game, not public.
Click on the big Start Game button. If you see join game instead of start game, then go back to step 3 and confirm its a private game.
Bonus step:
Don't invite anyone to your private game. And reject/ignore any join requests you get.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extend the Try Catch functionality C#
I've got an MVC application where I use Try-Catch blocks throughout and I'm looking for an easy way to implement activity/error-logging based on a global boolean field. Does anyone know a way I can 'extend' the functionality of the Try-Catch code in order to add my own activity/error logging without having to go through and touch every block?
For example:
I'd like the the Try to automatically log certain items to my DB such as url, action, ids, parameters, IP info, etc,...
And the Catch to automatically log it's Exception to another table in the DB.
Thoughts? Recommendations?
Thanks,
Peter
A:
Create your custom action filter and decorate controllers or action methods with it.
http://msdn.microsoft.com/en-us/library/dd381609.aspx
public class LoggingFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Trace.Write("(Logging Filter)Action Executing: " +
filterContext.ActionDescriptor.ActionName);
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception != null)
filterContext.HttpContext.Trace.Write("(Logging Filter)Exception thrown");
base.OnActionExecuted(filterContext);
}
}
Then use it
public class HomeController : Controller
{
[LoggingFilter]
public ActionResult Index()
{//...}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Could a fan stopped (too low voltage incoming into it) during long periods become damaged?
Computer fans use to run at 12Volt, but most, as for today, use to allow 9Volt or even less to slow down the fan speed (RPM, Revolutions Per Minute).
In cases of too low voltage, the fan stops, but I can see it "trying to start again". For example: my Tacens 9dB fan stops at about 10 Volts, but to start it again, 10.5Volt is not enough, and the engine tries to move the fan (I can see a small movement as an "attempt" to move) each 1-5 seconds, but it does not succees, so the fan keeps at 0 RPM.
Maybe that "attempt" to move could damage the internal engine of the fan when it last for hours or days?
UPDATE:
Why would I want to stop (some of) my fans:
Less noise when temperatures are low and fans are not needed.
Dust reduction (fans acumulate it).
Less consumption.
A:
A brushless DC fan has four stator coils and a permanent magnet in the rotor. A hall sensor detects which pole of the permanent magnet is facing towards it and it, in turn toggles power between 2 stator coils opposite of eachother, thereby attracting or repelling the permanent magnet and creating a rotational movement.
Whenever a fan cannot rotate because of undervoltage or being mechanically blocked, the same coils will continue to be powered for a prolonged period. Some of this energy is converted into heat, most of it is converted into a constant electromagnetic field.
Whilst not designed for this, chances of a coil melting are slim.
Also, when undervolted, the energy in the coils is low enough to barely attract the rotor, let alone melt.
This website has a page that explains the inner workings of a PC fan.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bluetooth is disabled on Ubuntu 14.04
The bluetooth is disabled on my Ubuntu (Dell vostro Desktop with bluetooth USB adapter).
I plugged the bluetooth USB adapter into another Ubuntu desktop (12.04) and it is recognized instantaneously.
I've installed blueman, bluez, bluetooth support package.
The bluetooth system settings shows the message "bluetooth is disabled" even after I turn it on. Bluetooth status is not shown in the menu bar even though I checked this option.
rfkill list says bluetooth isn't blocked.
lsusb says the dongle is connected.
Bluetooth manager doesn't work... all buttons are grey.
Removing gnome-bluetooth (as some users suggest) not only doesn't fix the problem but also removes ubuntu-desktop, causing my system settings to be missing among other consequences.
Bluetooth option is not shown in the BIOS. Do I need to install a driver maybe? Does it exist?
All I want is to be able to connect my Apple mouse and keyboard to the PC.
A:
Try this:
sudo hciconfig hci0 reset
A:
This solved the problem for me.
Terminal output for
rfkill list
0: hci0: Bluetooth
Soft blocked: no
Hard blocked: no
1: asus-wlan: Wireless LAN
Soft blocked: no
Hard blocked: no
2: asus-bluetooth: Bluetooth
Soft blocked: no
Hard blocked: no
3: phy0: Wireless LAN
Soft blocked: no
Hard blocked: no
After reading several other posts, I found this solution.
Install gksu if not already installed.
sudo apt-get install gksu -y
Then edit /etc/rc.local and enter this line just before the "exit=0" entry.
gksudo gedit /etc/rc.local
In gedit before the last entry, which is "exit=0", enter:
rfkill unblock bluetooth
Then reboot and you should be able to turn on bluetooth, if not already enabled after reboot.
| {
"pile_set_name": "StackExchange"
} |
Q:
Compiler C to Brainfuck (for harassing a professor)?
A professor of mine has said he'll accept homework assignments in any language we'd care to use. I'm on good enough terms that I'd like to mess with him a bit and submit a valid homework assignment using brainfuck, whitespace, or some equally "useful" language.
I have the C-sources for a few simple numerical analysis routines as well as the compiled output and the assembly files they generate.
Does anyone know of a decompiler (or a C->brainfuck translator) that could give me something akin to the "brainfuck source code"?
A:
Just use APL or J.
Unlike BF, they were actually designed to serve a "useful" (and not a "useful as in BF" sense) purpose - and yet can easily make Perl code-golf entries look like novels. (The dedication and mental training to enjoy these languages is currently more than my skill/effort levels.)
If the goal is using a purely esoteric language, I have always enjoyed the look of Piet programs. It looks prettier and is actually able to solve common CS homework problems. Following the links will reveal "Piet assemblers" and other tools. Win.
Happy coding.
A:
For what it's worth, I just wrote a very simple Brainfuck Assembler (inspired by this SO post actually), which assembles readable source code (not C, just something simple and nameless) to BrainFuck. The source-code and compilation/usage instructions can be found here: BrainFuck Assembler.
Edit: The project has recently been updated under a new name: BrainFix.
| {
"pile_set_name": "StackExchange"
} |
Q:
GCC/XCode speedup suggestions?
I have a stock mac-mini server (2.53GHz, 4GB, 5400RPM drive) which I use for iphone development. I am working on a smallish app. The compilation seems to be taking longer and longer (now about 20min). The app is about 20 small files totaling 4000 lines. It links to C++/Boost.
What suggestions do you have to speed up the compilation process? Cheaper will be better.
A:
As others have noted, that's way in excess of what you should be expecting, so it suggests a problem somewhere. Try toggling distributed builds -- depending on your setup it may improve things or slow them down (for a while we had a situation where one machine was servicing everyone else's builds but not its own). If you have a 1Gb network then you may get a bit of extra performance from distributed builds (especially if you have a couple of spare macminis). Also enable precompiled headers, and put both boost and cocoa headers in it.
If things are still slow then it's worth running activity monitor to ensure that you don't have some other process interfering, or even Instruments to get some more detailed information. You could find that you're trying to compile files on a network drive for instance, which will certainly slow things down. Also inside Xcode try running the option to preprocess a file and see what's in the file contents (available via right-click) to check that you're not compiling in loads of extra code.
Also with boost, try slimming it down to find only the bits you need. The bcp tool that comes in the distribution will copy only the packages you ask it to, plus all the dependencies, so you're not building stuff you won't use.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I remove the 'jar' task in gradle build?
When I use the code below, a file of jar will generate after gradle build.
apply plugin 'java'
Is there any settings won't generate the file of jar??
I can write a custom plugins,but the code below was wrong.
dependencies {
compile project(':crm.common')
testCompile group: 'junit', name: 'junit', version: '4.12'
}
I want find a way that donot generate the file of jar.
And can run compile in dependencies.
Is there any way can do that???
A:
You can do that by 2 ways:
explicitly exclude the jar task from execution:
gradle build -x jar
disable the jar task in build.gradle:
apply plugin: 'java'
jar.enabled = false
| {
"pile_set_name": "StackExchange"
} |
Q:
How to view the list of c library functions in Linux?
I'm a newbie in Linux programming. I found that the way to view the list of system calls in Linux via command-line is: man syscalls
But now I want to view the list of c library functions, how can I do that? Which command will help me list the c library functions? And another question, where are system calls and c library functions manual pages located? Thank you.
A:
System calls man pages are located in the section 2 of the man pages, see intro(2), and their list in syscalls(2)
Library functions man pages are located in the section 3 of the man pages, see intro(3). There are many of them (and most of them use some syscalls, but some don't need any syscalls e.g. round(3)).
And some useful Glibc specific functions don't have man pages, for example argp functions.
As Elliot Frisch commented, see Gnu libc documentation.
BTW, you could use something else than GNU libc, for instance musl libc.
You should also read Advanced Linux Programming and some pthread tutorial.
Read also the Posix opengroup documentation.
At last, Linux also have many very widely used libraries, like ncurses and gnu readline for terminal I/O, and GTK or Qt for graphical user interfaces above X11 (both having a foundational library : Gobject+Glib for GTK, and QtCore for Qt, which is useful by itself outside of any GUI programs).
And freecode, sourceforge, github and many other places mention many free software libraries, most of them being developed on Linux. For instance libonion is a useful library giving you HTTP server abilities.
For databases, see mariadb, mongodb, postgresql, gdbm, sqlite etc... (and jansson for JSON textual serialization)
BTW, your Linux distribution should give you a lot of development packages too. On Debian more than 200 packages match lib*dev package name (and some libraries have a development package named differently).
There are several good books about Linux programming, see this...
Be aware that Linux is mostly free-software friendly. Give attention to software licenses and their compatibility.
If possible, make your own Linux software project a free software, e.g. by publishing it with a license like e.g. GPLv3 (early, even barely working, in alpha stage...) on some site like github or gitorious or sourceforge etc... You could get useful feedback.
You might consider coding in C++11 (which can use C or C++ libraries easily). Notice that C++11 is really different from previous versions of the C++ standard. If you do, be sure to use a recent compiler, like GCC 4.8. You could even consider customizing GCC with MELT if your software is complex enough to worth the effort.
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaFX ListView basic app
I am newbie in JavaFX and i wanted to try something to begin with.. So i created simple ListView, but when i tried to run the program, instead of 4 listView items (Cat, Dog, Mouse, Horse) There is only submit button in rigt top corner.
Can someone help me out what i did wrong? Thanks for any advice!
package main;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.scene.control.ListView;
public class Main extends Application {
Stage window;
Scene scene;
Button button;
ListView<String> listView;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("Try listView");
button = new Button("Submit");
listView = new ListView<>();
listView.getItems().addAll("Cat", "Dog", "Mouse", "Horse");
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
button.setOnAction(e -> buttonClicked());
VBox layout = new VBox(10);
layout.setPadding(new Insets(20, 20, 20, 20));
layout.getChildren().addAll(button);
scene = new Scene(layout, 300, 250);
window.setScene(scene);
window.show();
}
private void buttonClicked() {
String message = "";
ObservableList<String> movies;
movies = listView.getSelectionModel().getSelectedItems();
for (String m: movies) {
message += m + "/n";
}
System.out.println(message);
}
}
A:
When you create your scene, you are only adding the Button to it. Change the following line of code:
layout.getChildren().addAll(listView, button);
By doing this, you will add the ListView followed by the Button.
| {
"pile_set_name": "StackExchange"
} |
Q:
Failed to implement a search widget
I'm trying to implement a search widget in my app . I found a useful tutorial from here.
My Activity A
But my app crashed.
Activity A
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.create_menu, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.add: // create new file
View menuItemView = findViewById(R.id.add);
PopupMenu po = new PopupMenu(HomePage.this, menuItemView); //for drop-down menu
po.getMenuInflater().inflate(R.menu.popup_menu, po.getMenu());
po.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// Toast.makeText(MainActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
if ("Create New File".equals(item.getTitle())) {
Intent intent = new Intent(HomePage.this, Information.class); // go to Information class
startActivity(intent);
} else if ("Edit File".equals(item.getTitle())) {
Intent intent = new Intent(HomePage.this, Edit.class);
startActivity(intent);
}
return true;
}
});
po.show(); //showing popup menu
}
return super.onOptionsItemSelected(item);
}
searchable in xml folder
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="Search by date" />
create_menu
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/search"
android:title="Search by date"
android:icon="@mipmap/search"
app:showAsAction="collapseActionView|ifRoom"
android:actionViewClass="android.widget.SearchView" />
<item
android:icon="@mipmap/menu"
android:id="@+id/add"
android:orderInCategory="100"
android:title="Main Menu"
app:showAsAction="always" />
</menu>
declare this in mainfest
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable" />
Error LogCat
01-18 18:31:09.298 9215-9215/com.example.project.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.myapplication, PID: 9215
java.lang.NullPointerException
at com.example.project.myapplication.GUI.HomePage.onCreateOptionsMenu(HomePage.java:104)
at android.app.Activity.onCreatePanelMenu(Activity.java:2646)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:298)
at android.support.v7.internal.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallback
This is the line where error pointed to searchView.setSearchableInfo(
A:
You should use support SearchView's support version:
<item android:id="@+id/action_search"
android:title="@string/search_title"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView" />
And you'd add in Manifest.xml the proper Intent Filter
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
| {
"pile_set_name": "StackExchange"
} |
Q:
Split CSV file in records and save as a csv file format - Apache NIFI
What I want to do is the following...
I want to divide the input file into registers, convert each record into a
file and leave all the files in a directory.
My .csv file has the following structure:
ERP,J,JACKSON,8388 SOUTH CALIFORNIA ST.,TUCSON,AZ,85708,267-3352,,ALLENTON,MI,48002,810,710-0470,369-98-6555,462-11-4610,1953-05-00,F,
ERP,FRANK,DIETSCH,5064 E METAIRIE AVE.,BRANDSVILLA,MO,65687,252-5592,1176 E THAYER ST.,COLUMBIA,MO,65215,557,291-9571,217-38-5525,129-10-0407,1/13/35,M,
As you can see it doesn't have Header row.
Here is my flow.
My problem is that when the Split Proccessor divides my csv into flows with 400 lines, it isn't save in my output directory.
It's first time using NIFI, sorry.
A:
Make sure your RecordReader controller service is configured correctly(delimiter..etc) to read the incoming flowfile.
Records per split value as 1
You need to use UpdateAttribute processor before PutFile processor to change the filename to unique value (like UUID) unless if you are configured PutFile processor Conflict Resolution strategy as Ignore
The reason behind changing filename is SplitRecord processor is going to have same filename for all the splitted flowfiles.
Flow:
I tried your case and flow worked as expected, Use this template for your reference and upload to your NiFi instance, Make changes as per your requirements.
| {
"pile_set_name": "StackExchange"
} |
Q:
Strip multiple tags with strip_tags()
I am trying to strip html tags from my msg string.
I have the following string that contains user input :
$msg="<a href="#">Hello world</a> ! <b>Welcome to venga club</b> .<br><li>We are here to entertain you....</li>";
I know it's simple to strip those tags with regex and preg_replace, but I want to do this using strip_tags() if possible.
I tried the following code
echo strip_tags("<a><b><li><br>",$msg);
but the result i get is black, is there something wrong with the function?
Any help is much appriciated.
Thanks
A:
like @u_mulder has advised - sometimes it is indeed worth to spare some additional time on reading the manual (evening reading etc.) :)
function strip_tags ($str, $allowable_tags = null)
accepts first argument as the input string and second argument as allowable tags. Opposite of how it is written in your case.
http://php.net/manual/en/function.strip-tags.php
so you should put it for example like this:
$msg='<a href="#">Hello world</a> ! <b>Welcome to venga club</b> .<br><li>We are here to entertain you....</li>';
echo strip_tags($msg, '<a>');
| {
"pile_set_name": "StackExchange"
} |
Q:
Wanting to avoid vulgarity; alternatives for "a d--k move"
I have heard the slang phrase dick move in contexts like this:
"Please don't do that prank to him. That'd be a dick move from you."
"Look at those drawings of Bob! Do you know who made them? That's a dick move!"
I understand what the phrase means, but what other colloquial expressions could I use to replace the slang dick move? I want to avoid swear words and convey the same sentiment in a way that is would be regarded as more polite and less offensive.
A:
Saying something is not cool captures the same sentiment. It’s fairly flexible:
Don’t prank him. That would not be cool.
Don’t prank him. That’s not cool.
You could also tell someone not to be that guy.[examples]
Don’t prank him. You don’t want to be that guy.
A:
You could say something along the lines of "that's a rude move".
Rude could stand in for Dick
| {
"pile_set_name": "StackExchange"
} |
Q:
In Amazon Mechanical Turk, Batch HITs remain in mTurk website UI Manager after approving HITs with API
I am currently creating a Batch Project via the Amazon Mechanical Turk website (http://requester.mturk.com). After all the HITs have been completed, I download the CSV and approve or reject the hits.
I am then iterating through the CSV and using the mTurk API to call ApproveAssignment or RejectAssignment on the AssignmentId for each row.
When looking as a Worker (in which I completed my own HITs for testing), I see that HITs have been properly approved or rejected. However when looking as the requester it appears that none of the assignments have been approved or denied and the batch project looks like it is still waiting to be reviewed.
Any thoughts? Any help would be greatly appreciated.
Thanks!
A:
This is a known issue. Once you operate on a HIT via the API, the batch interface no long works correctly.
The Manage HITs Individually page should still be updated correctly, though.
| {
"pile_set_name": "StackExchange"
} |
Q:
Scaling SharePoint Fast Search
I'm about to start a project using the FAST Search Server and would like to know something about how we can scale the Search Server.
Can we setup multiple search server application pools or how does this work?
Thanks
A:
With FAST Search you are going to have a separate set of servers dedicated to document processing, indexing and other components. The configuration options are very flexible so you'll need to come up with the proper architecture based on your specific requirements for content freshness, query throughput, index size and redundancy. Your SharePoint application servers will only be responsible for crawling SharePoint sites. The topic is too broad for a short answer like this but there's plenty of information available on TechNet. Here's a good starting point: Plan search topology (FAST Search Server 2010 for SharePoint)
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I restrict EditText to take emojis
I am developing an application where I want my edittext should take Name only. I have tried using android:inputType="textCapSentences" but it seems like its not working. My edittext is still taking the emojis.
So, Is there any way i can restrict any special character or emojis input in edit text in android.
If anyone have idea,Please reply.
Thanks in advance.
A:
you can use emoji filter as code below
mEditText.setFilters(new InputFilter[]{EMOJI_FILTER});
public static InputFilter EMOJI_FILTER = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
boolean keepOriginal = true;
StringBuilder sb = new StringBuilder(end - start);
for (int index = start; index < end; index++) {
int type = Character.getType(source.charAt(index));
if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) {
return "";
}
char c = source.charAt(index);
if (isCharAllowed(c))
sb.append(c);
else
keepOriginal = false;
}
if (keepOriginal)
return null;
else {
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(sb);
TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
return sp;
} else {
return sb;
}
}
}
};
private static boolean isCharAllowed(char c) {
return Character.isLetterOrDigit(c) || Character.isSpaceChar(c);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Given an element in a quotient group $G/H$, find an element with the same order in $G$
Problem
A finite abelian group $G$ has an element $g$ of order $n$, which generates the subgroup $H = \langle g \rangle$. Let $\gamma$ be an element of order $m$ in $G/H$. Show that there exists an element $x \in G$ such that $\lvert x \rvert = \lvert \gamma \rvert = m$.
I copied my instructor's solution, but I missed the last part, and I can't proceed from what's on my notebook.
Suppose that $x_0 \in G$ such that $\overline{x_0} = \gamma$. Since $\lvert \gamma \rvert = m$, $x_0^m \in H = \langle g \rangle$, and we denote $x_0^m = g^k$. Divide $k$ by $m$ to get $k = mq + r$ with $r \in \{0,\dots,m-1\}$.
\begin{align}
x_0^m &= g^k = g^{mq + r} \\
g^r &= x_0^m g^{-mq} = \left(x_0 g^{-q} \right)^m
\end{align}
We want to show $r=0$.
Let $x' = x_0 g^{-q}$. Observe that $\overline{\mathstrut x'}=\overline{\mathstrut x_0}=\gamma$ and $m \mid \lvert x' \rvert$ because $$e = x'^{\mathstrut \lvert x' \rvert} = x_0^{\mathstrut \lvert x' \rvert} \underbrace{g^{\mathstrut -q \lvert x' \rvert}}_{\in H}.$$
$$\therefore \lvert (x')^m \rvert = \frac{\lvert x' \rvert}{\gcd(m,\lvert x' \rvert)} = \frac{\lvert x' \rvert}{m}$$
I don't know how to continue with this.
A:
This argument seems overly complicated (and the conditions overly strict).
Claim. Let $G$ be a finite group and $H\lhd G$ a normal subgroup. Let $\gamma\in H$ be an element of order $m$. Then $G$ has an element $x$ of order $m$.
Proof. Let $\pi\colon G\to G/H$ denote the canonical projection. Pick $x_0\in G$ with $\pi({x_0})=\gamma$. Then $\langle x_0\rangle$ is a cyclic group with $\pi(\langle x_0\rangle)=\langle \gamma\rangle$, hence is a cyclic group of order divisible by $m$. We know that such a cyclic group contains an element of order $m$. $\square$
| {
"pile_set_name": "StackExchange"
} |
Q:
Can somebody please explain IOS line authentication?
I'm trying to understand a config on one of our Cisco routers (teaching myself iOS) and have run into a problem with one line.
Can somebody please explain the "line enable" piece of the command below and check the rest of my information to ensure it is correct?
aaa authentication login default group tacacs+ local line enable
---
# Creates an authentication list that specifies the types of authentication methods allowed.
# aaa authentication login = command to authenticate users who want exec (enable) access into the access server (tty, vty, console, and aux).
## default = the named list is the the default one (in this case the default one is default)
# There are three authentication methods:
## TACACS+
## local
## line
# All users are authenticated using the tacacs+ server (the first method). If the TACACS+ server doesn't respond, then the router's local database is used (the second method). The local authentication, define the username and password::
## username xxx password yyy
# Because we are using the list default in the aaa authentication login command, login authentication is automatically applied for all login connections (such as tty, vty, console, and aux).
A:
line and enable are additional methods of authentication that will be attempted after failure of the previous methods in the list.
line authentication uses a password that's defined in your line configs, so it can vary based on your connection method. enable authentication simply uses the enable password defined in the enable password command.
Here's a reference of the methods available for the authentication list:
(config)#aaa authentication login default ?
cache Use Cached-group
enable Use enable password for authentication.
group Use Server-group
krb5 Use Kerberos 5 authentication.
krb5-telnet Allow logins only if already authenticated via Kerberos V
Telnet.
line Use line password for authentication.
local Use local username authentication.
local-case Use case-sensitive local username authentication.
none NO authentication.
| {
"pile_set_name": "StackExchange"
} |
Q:
Accessing one database from another
I have two databases where one table in one database has around 6 million records and other table from other database has around 6 thousand records. I need to fetch all the matching records from the table with 6 million records.
Is there any way other than DB link?
A:
There are a few ways to do this with Informatica... my preference is to extract the 6000 rows from db 1, load into a table in a private schema on db 2 and with visibility of the table with 6M rows. That way when you run your query the join will help to optimise the source qualifier and everything will be gravy so long as you have correct indexes defined on the join condition fields
The alternate is to query the 6000 row table in your source qualifier and lookup the matching rows against the 6 million row table using a lookup transformation configured to return multiple rows for multiple matches. If you can either cache the 6M records without a sweat or handle 6000 queries to the db with little time hit then try this but multireturn lookup is a bit more finicky than stsndard lookup so I'd avoid as the next fella probably wont get it
| {
"pile_set_name": "StackExchange"
} |
Q:
Ubuntu Server on-line manual incomplete
I've realized that man in Ubuntu Server (Bionic) is incomplete if compared with Ubuntu Desktop (Bionic) version.
I searched for some system calls like fork using the command man 2 fork and it return No manual entry for fork in section 2.
This doesn't happen on Ubuntu Desktop version.
What I would have to do for get a complete version of the manual on Ubuntu Server?
A:
Try sudo apt install manpages-dev
The manpages-dev package includes over 2000 additional manpages...including fork.
| {
"pile_set_name": "StackExchange"
} |
Q:
Django extra_views, ModelFormSetView doesn't save the data
I have two problems, i have a flat table with settings in my db, structure is:
setting: char
value: char
It shows the form just fine, but:
First Problem: It shows an empty field combination at the end.
Second problem: It doesn't save the data, no error, no redirect to the success page, nothing.
my views.py:
class UpdateSettings(ModelFormSetView):
model = Settings
fields = ['setting', 'value']
template_name = 'settings.html'
success_url = '/shows'
my settings.html:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<div class="row">
<div class="col-6">
{{ form.setting|as_crispy_field }}
</div>
<div class="col-6">
{{ form.value|as_crispy_field }}
</div>
</div>
{% endfor %}
<div class="form-group form-actions">
<button class="btn btn-success">Change</button>
</div>
</form>
{% endblock %}
A:
Your first problem: By default the django modelformset_factory (which the view uses in the background) creates one extra empty form. To avoid this add the factory_kwargs to your view
class UpdateSettings(ModelFormSetView):
model = Settings
fields = ['setting', 'value']
template_name = 'settings.html'
success_url = '/shows'
factory_kwargs = {'extra': 0}
Your second problem: I saw the formset is throwing an error because the 'id' field is required. Add the 'id' to your template:
<div class="row">
<div class="col-6">
{{ form.id }}
{{ form.setting|as_crispy_field }}
</div>
<div class="col-6">
{{ form.value|as_crispy_field }}
</div>
</div>
i don't think 'id' needs to be added to the 'fields' in your view as it is added by default
| {
"pile_set_name": "StackExchange"
} |
Q:
Site hacked, looking for security advice
Possible Duplicate:
My server's been hacked EMERGENCY
Last weekend my company's site was hacked.
They did the nicest thing of doing that on a Friday evening so we only noticed the attack on Monday morning.. The funny thing is that we switched from Windows to Linux recently because it was supposed to be more stable and secure. Go figure. And yes, we got us blacklisted on Firefox and Chrome.
Since I am not a Linux expert, I am looking for advice on how to avoid problems like this in the future. What steps do you take to protect your systems? It seems we had weak passwords, but shouldn't Linux block the account after a few failed logins? They tried more than 20 combinations...
In addition to that, I am looking for a tool (or service) similar to pingdom but applied to security. If my site is ever hacked, alert me. Is that such a thing? A Hacking monitor? :)
Another thing, how do you notify your clients about such issues? Do you just ignore and hope no one noticed? Email explaining what happened?
*posting as anonymous to avoid more bad exposure to my company, which is bad already...
A:
An operating system is not "stable and secure". A properly configured and well-administered infrastructure can be made more secure than one that isn't, but security isn't a boolean. You can't "buy security" or "install security" by using a particular product / technology.
You're not a "Linux expert", so it makes sense that you need to hire / contract with someone who can configure your servers well, from a security perspective. It's not something you can do one and "be done". Patches are being released all the time for newly found vulnerabilities and bugs. If you don't have an employee who has the job of keeping up you really need to consider subscribing to some type of "managed" service to maintain your server computers. This is an ongoing concern, and needs to be factored into the budget / TCO of the system as a whole.
There are "hacking monitors", to some extent. Intrusion detection systems (IDS), intrusion prevention systems (IPS), etc, fill that niche. It's an arms race, though. You can't just purchase an off-the-shelf IDS/IPS product, pay somebody to put it in, then sit back and feel smugly secure. Just like keeping operating system software and application software patched, the "hacking monitor" infrastructure must be kept up to date, too.
You need to talk to a lawyer. You may have clients located in places where you are bound to disclose such occurrances by law. Even if you're not, it sure seems slimy to me not to let your clients know if their data was placed at risk. There's the damage to "your good name" now in disclosing the hack, but there's a multiplicity of that damage if it comes out later that you tried to cover it up-- especially if you're breaking the law by doing it.
Practical Stuff:
Your hacked machine(s) are trash. They need to be reloaded from a known-good backup or, better yet, reloaded from clean OS binaries and re-populated with data. This is like "malware cleanup" except worse, because your adversary is much more likely a thinking being instead of a dumb piece of software (though you may have been hacked by a 'bot). The chance that there are "back doors" in your servers is real.
The data on the server computers should be considered to have been disclosed to the public. Even if it's not now, it could be.
Any credentials to other computers stored on the hacked computers are public. Start getting those passwords to other computers changed NOW and make sure that the other computers are intact. (Does anybody user Tripwire anymore? That'd sure be nice in this occasion...)
You've got a mess. Handle it well and you will come out better. Handle it poorly and, next time, you may not have a company.
In the future, you should be using strong authentication and encrypted management protocols (SSH, public-key based authentication). I've already suggested that you get a "Linux expert", even if it's just on contract, to get you started down the right track. I can't encourage that enough. You'll get to see, with this breach, how that would have "paid for itself".
All the common stuff applies:
Don't run services you don't need to.
Disable default credentials.
Follow the principle of least privilege.
Have tested, offline, and off-site backups.
Know your legal requirements re: breach disclosure.
Keep your systems / applications updated.
A:
It seems we had weak passwords...
...we switched from Windows to Linux recently because it was supposed to be more stable and secure. Go figure.
Weak passwords are platform independent.
Linux is more flexible than Windows in many scenarios, and thus can be made more secure when those certain situations arise. Switching from Windows to Linux for no real reason, especially when you're unfamiliar with the environment, is a bad call. If you run an internet-facing server and don't understand how the services on that server work, whether it be Windows, Solaris, RHEL, or BSD, you're asking for trouble.
As for how to tell your clients, if any of their data was exposed or even POTENTIALLY exposed, AT ALL, call them ASAP. No email, no hope it goes away. Use your phone that's sitting on your desk.
Besides legal repercussions, you were providing a service to them that they were undoubtedly using to provide services for others in some way. You owe it to them to disclose any potential breach of data so they can adjust their workflow accordingly and notify anyone else downstream from them that it may affect.
A:
Linux like any platform is only as secure as the people who administrate the systems. If you were more experienced with Windows then moving to Linux probably wasn't the best idea. You can setup Windows to be just as secure as Linux provided that you take the correct steps to secure the environment which includes firewalls between the public internet and your internal network, and secure VPNs for connecting from your home to the internal network.
Depending on the level of the breach will determine what you tell your customers. If no customer data was taken then you can give your customers just some basic information about what happened. However if Customer data was accessed you now have some state notification laws to deal with depending on the state that your company is in, and the states your customers are in.
| {
"pile_set_name": "StackExchange"
} |
Q:
Validation of default parameters with `inputParser` class
The inputParser class in Matlab is very useful to synthetically check arguments passed by users when calling some function. For instance:
function [] = TestValidation(varargin)
%[
p = inputParser();
p.addParameter('Toto', 'Hello', @isnumeric);
p.parse(varargin{:});
%]
end
Will raise an error if user attempt to assign a non numeric value to the parameter Toto (e.g. TestValidation('Toto', 'Hello') ==> raises an error because Hello is not a numeric).
Anyhow calling above function without parameters (i.e. TestValidation()), there is no error raised even if default value for Toto is a string (i.e. Hello).
Is there a simple way to force inputParser to validate also for default values or can it be done only manually and a posteriori ?
A:
It's a class, create a subclass which implements the functionality you want:
classdef myInputParser<inputParser
methods
function addParamValue(obj,name,default,fcn,varargin)
assert(fcn(default));
addParamValue@inputParser(obj,name,default,fcn,varargin{:});
end
end
end
.
>> p = myInputParser();
>> p.addParamValue('Toto', 'Hello', @isnumeric);
Error using myInputParser/addParamValue
(line 4)
Assertion failed.
| {
"pile_set_name": "StackExchange"
} |
Q:
How create a custom form in django with database values
model.py
class Venue(models.Model):
venue_Name = models.CharField(max_length=100)
place = models.CharField(max_length=50)
rent = models.IntegerField()
parking_area = models.IntegerField()
class Decoration(models.Model):
rate = models.IntegerField()
I have printed the values in database as radio buttons what i want to do is that i want to get the total sum i.e venue.rent + decoration.rate and print it in another page What shoud i give in form action I'm not that familiar with forms.
html
<form action="{% %}" method="post">
{% for venue in venues %}
<input type="radio" name=venue value=venue.rent />{{ venue.venue_Name}}
{% endfor %}
{% for decoration in decorations %}
<input type="radio" name=decor value=decoration.rate />{{ decoration.rating }}
{% endfor %}
<input type="submit" value=" " />
</form>
what should i write in view and urls to get the sum
A:
You can use Django's form for validation and parsing. For that you would set up a form like so:
forms.py
from django import forms
class TotalSumForm(forms.Form):
venue = forms.ModelChoiceField(queryset=Venue.objects.all(), required=True)
decoration = forms.ModelChoiceField(
queryset=Decoration.objects.all(), required=True)
def get_total(self):
# send email using the self.cleaned_data dictionary
return self.cleaned_data['venue'].rent +\
self.cleaned_data['decoration'].rate
And then using a class based view, add the result to context upon submission.
views.py
from myapp.forms import TotalSumForm(
from django.views.generic.edit import FormView
class TotalCost(FormView):
template_name = 'your_template.html'
form_class = TotalSumForm
success_url = '/thanks/'
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
total_result = form.get_total()
# return back to your_template.html with the total in context
return self.render_to_response(self.get_context_data(
form=form, total=total_result))
The urls are pretty simple:
urls.py
from django.conf.urls import patterns, url
import myapp.views
urlpatterns = patterns(
'',
url(r'^total_calc/$', myapp.views.TotalCost.as_view(), name='calculate_total'),
)
Your html could be modified like so
your_template.html
<html>
<body>
<h1>TEST SUCCESFULL!</h1>
{% if total %}
<p>Total cost for venue and decoration: {{ total }}</p>
{% endif %}
<form action="{% url 'calculate_total' %}" method="post">
{{ form.as_p }}
<input type="submit" value="Calculate Total" />
</form>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
The mechanics of creating a White Walker
We saw a few episodes ago:
Leaf creating a White Walker with what looks to be a Dragonglass dagger. It was unclear from that scene whether the stabbing itself initiates the transformation or if there are other rites being performed to create it.
However, given that both Dragonglass and Valyrian Steel are capable of destroying a White Walker, I wonder if both can also be used to create them. It seems unlikely, but am curious whether anyone can find any other evidence for an answer.
My hunch is that Valyrian Steel cannot create a White Walker because it is regularly used in combat against humans. The reason I find it unlikely is that in combat over the last 1000 years in Westeros, not a single killing created a White Walker, but the number of stabs to the heart from Valyrian Steel surely was >0.
It also seems that Dragonglass quickly fell out of use after the last long winter, due to its current scarcity in Westerosi arsenals. It also seems that even if they were used in human to human combat, they never led to the conversion of a human to White Walker much like Valyrian Steel.
So is it safe to say that:
only the Children of the Forest are capable of creating White Walkers? Is that due to other rites/magic or simply the knowledge and ownership of dragonglass that gives them this ability?
A:
We don't know. Neither the show or the books go in depth regarding magical acts. All we know is that magic of the Children of the Forest is involved. But Valerian steel was not involved or mentioned or hinted that it was involved.
Everything the main characters know is from first hand experience fighting the White Walkers, and some rumor and legend from the First Men. Nothing concrete.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get sum of delta values per row
I have a table with a field containing a time delta.
The rows are guaranteed to be in temporal order, that means the row with id 1 represents an event which took place before the one represented in row 2.
Now I want to do a query which returns me the absolute timestamp for every row.
Example data:
id timestamp_delta
1 0
2 22
3 5
4 10
I know the absolute timestamp of the first entry. Let's assume it's 100.
Thus the resulting table I want to create with a query would be:
id timestamp_absolute
1 100
2 122
3 127
4 137
Looks simple, but I'm quite stuck with this task.
What I can do is read the delta of row n-1 by having the table in the from clause twice
select *
from badtable t1, badtable t2
where t2.id = t1.id-1
since I can rely on the order. However I'm not sure how to go from here. Is it possible to somehow just increment the value with each row?
Even if a solution would result in O(N2) runtime behaviour by calculating the sum from the beginning for every row, that would be acceptable.
I guess it's not the way we should store this data. The reason why we chose to use delta was to reduce the amount of data to be transferred from mobile apps (worth it, even if just a few percent saving), for convenience just writing it to the server DB as is.
I'm curious to see how simple or complicated the best solution is going to be...
In case it matters, it's a MySQL DB.
A:
You could do it with a self join like so: (freehand)
SELECT t1.id, SUM(t2.timestamp_delta) + 100
FROM badtable t1 JOIN badtable t2 ON t2.id <= t1.id
GROUP BY t1.id
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I copy a file as a "Standard User" in Vista (ie "An Administrative Choice Application") by prompting user for admin credentials?
I have what the UAC Development Guides refer to as a "Administrative Choice Application." If you're familiar with what this is skip to the next section.
Background:
I want to let a "Standard" user have the ability to select/deselect a Run On Startup option in the preferences for my application.
Since my application is per machine (not per user), what needs to happen is it will either need to Delete or Copy a shortcut file into the Start Menu/Programs/Startup folder which will require administrative access to perform this operation.
So, what i'd like is for the "User Account Control credential prompt" to appear and that way if the user has an admin account also they can put in the credentials. This is apparently how applications are supposed to be designed to keep the user from having to switch to another account each time they need to do something administrative.
Excerpt from MSDN documentation:
An Administrative Choice Application
An Elevated Process or COM Object
The initial application launches without requiring elevation. Those items in the user interface that would require an administrative access token are decorated with a shield icon as identification. This decoration indicates to the user that using that feature will require administrator approval. When the application detects that one of these buttons has been selected, it has the following two choices.
The application launches a second program using ShellExecute() to perform the administrative task. This second program would be marked with a requestedExecutionLevel of requireAdministrator, thus causing the user to be prompted for approval. This second program would be running with a full administrative access token and would be able to perform the desired task.
-OR-
The application launches a COM object using CreateElevatedComObject(). This API would launch the COM object with a full administrative access token following approval and this COM object would be able to perform the desired task.
I just need to copy a file... seems excessive to fork a new process using ShellExecute() and I don't know enough about COM to know if I could use it to copy a file. I am hoping someone can post some code which provides a way to copy the file and ideally also explain how to decorate a MenuItem with the "sheild decorator".
Notes:
I have looked at the UAC Demo provided by microsoft which is referenced in several StackOverflow posts such as (Request Windows Vista UAC elevation if path is protected?) on topics related to permissions. The code only has an example of the calling a separate process.
A:
I ended up going in a different direction. I had my installer create a startup shortcut in the All Users/Startup folder that passes an argument to the application "startup".
When the application started I would check for the existence of the arg[0].equals("startup") and then check if Settings1.Default.RunOnStartup == true.
If both conditions were true I'd exit the application immediately. When the application is started without that argument (ie the Start Menu Program Group), the application loaded normally.
The RunOnStartup setting is a user scoped setting so each user can change without effecting others.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regular Expression Phone Number Validation
I wrote this regular expression for the Lebanese phone number basically it should start with
00961 or +961 which is the international code then the area code which
could be either any digit from 0 to 9 or cellular code "70" or "76" or
"79" then a 6 digit number exactly
I have coded the following reg ex without the 6 digit part :
^(([0][0]|[+])([9][6][1])([0-9]{1}|[7][0]|[7][1]|[7][6]|[7][8]))$
when i want to add code to ensure only 6 digits more are allowed to the expression:
^(([0][0]|[+])([9][6][1])([0-9]{1}|[7][0]|[7][1]|[7][6]|[7][8])([0-9]{6}))$
It Seems to accept 5 or 6 digits not 6 digits exactly
i am having difficulty finding whats wrong
A:
use this regex ((00)|(\+))961((\d)|(7[0168]))\d{6}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is subclassing NSNotification the right route if I want to add typed properties?
I am trying to subclass NSNotification.
Apple's docs for NSNotificationstate the following:
NSNotification is a class cluster with no instance variables. As such,
you must subclass NSNotification and override the primitive methods
name, object, and userInfo. You can choose any designated initializer
you like, but be sure that your initializer does not call
NSNotification’s implementation of init (via [super init]).
NSNotification is not meant to be instantiated directly, and its init
method raises an exception.
But this isn't clear to me. Should I create an initializer like this?
-(id)initWithObject:(id)object
{
return self;
}
A:
Subclassing NSNotification is an atypical operation. I think I've only seen it done once or twice in the past few years.
If you're looking to pass things along with the notification, that's what the userInfo property is for. If you don't like accessing things through the userInfo directly, you could use a category to simplify access:
@interface NSNotification (EasyAccess)
@property (nonatomic, readonly) NSString *foo;
@property (nonatomic, readonly) NSNumber *bar;
@end
@implementation NSNotification (EasyAccess)
- (NSString *)foo {
return [[self userInfo] objectForKey:@"foo"];
}
- (NSNumber *)bar {
return [[self userInfo] objectForKey:@"bar"];
}
@end
You can also use this approach to simplify NSNotification creation. For example, your category could also include:
+ (id)myNotificationWithFoo:(NSString *)foo bar:(NSString *)bar object:(id)object {
NSDictionary *d = [NSDictionary dictionaryWithObjectsForKeys:foo, @"foo", bar, @"bar", nil];
return [self notificationWithName:@"MyNotification" object:object userInfo:d];
}
If, for some strange reason, you'd need the properties to be mutable, then you'd need to use associative references to accomplish that:
#import <objc/runtime.h>
static const char FooKey;
static const char BarKey;
...
- (NSString *)foo {
return (NSString *)objc_getAssociatedObject(self, &FooKey);
}
- (void)setFoo:(NSString *)foo {
objc_setAssociatedObject(self, &FooKey, foo, OBJC_ASSOCIATION_RETAIN);
}
- (NSNumber *)bar {
return (NSNumber *)objc_getAssociatedObject(self, &BarKey);
}
- (void)setBar:(NSNumber *)bar {
objc_setAssociatedObject(self, &BarKey, bar, OBJC_ASSOCIATION_RETAIN);
}
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails 3 - Delayed_Job
I'm working to learn how to user delayed_job on my rails 3 + heroku app.
I currently have the following which emails on a request (not delayed job) but it works!
UserMailer.conversation_notification(record.commentable, participant, record, @comments).deliver
I updated that to this to start using delayed_job:
Delayed::Job.enqueue UserMailer.conversation_notification(record.commentable, participant, record, @comments).deliver
But that error'd with: "ArgumentError (Cannot enqueue items which do not respond to perform):"
I also tried:
UserMailer.delay.conversation_notification(record.commentable, participant, record, @comments)
But that error'd with:
NoMethodError (undefined method `delay' for UserMailer:Class):
Any delayed_job guru's out there? Thanks
A:
From the docs https://github.com/collectiveidea/delayed_job
Your second method was correct which removes the .deliver method:
UserMailer.delay.conversation_notification(record.commentable, participant, record, @comments)
If you are getting an undefined method delay did you add DelayedJob to the Gemfile?
gem "delayed_job"
Since including the delayed_job will add the "delay" method to everything.
| {
"pile_set_name": "StackExchange"
} |
Q:
AWS CloudFormation Outputs: Exporting AZ's
Creating a layered stack set in cloudformation. Network Stack and App Stack
Just need the syntax to Output and Export two Availability Zones that are captured when a cfn user chooses them in the network template parameters dialogue.
eg, a user chooses two AZ's in a region via the usual mechanism.
AZoneNames:
Type: 'List<AWS::EC2::AvailabilityZone::Name>'
Description: Availability Zones (choose two zones)
That captures the az's, and i assume, cfn indexes them [0,1] to an array in the background. That part works.
So I need to output the two az's and export them for the app stack but not sure how. I've attempted with the below snippet but it doesnt work
StackAvailabilityZone1:
Description: The first az that was chosen at network stack creation
Value: !Ref AvailabilityZone 0
Export:
Name: !Sub 'AZ1'
I'm sure its probably staring me in the face. Thanks so much for any ideas.
A:
You can try the following, using Select:
StackAvailabilityZone1:
Description: The first az that was chosen at network stack creation
Value: !Select [0, !Ref AZoneNames]
Export:
Name: AZ1
| {
"pile_set_name": "StackExchange"
} |
Q:
Draw (shapes) to a texture/sprite in libGDX
In my libGDX game I have several sprites that share the same texture. Now I want to "manually" draw onto some of the sprites (i.e. I want to change some of the pixels in some of the sprites).
How can I modify a texture that is shared amongst seveal sprites without affecting other sprites?
I guess I need to copy the texture before I set it to the sprite?
A:
You can use custom shader to customize sprite texture.
Before drawing the sprite with spriteBatch, simply say:
spriteBatch.begin();
spriteBatch.useShader(shaderProgram1);
sprite1.draw(...);
spriteBatch.useShader(shaderProgram);
sprite2.draw(...);
...
spriteBatch.end();
If you aren't familiar with the shaders you can check this link:
https://github.com/libgdx/libgdx/wiki/Shaders
Also there is option to use frame buffer object, for texture customization, but I think if those texture difference aren't that huge, this is the best solution if you are looking for best performances.
Hope that this gives you an idea.
| {
"pile_set_name": "StackExchange"
} |
Q:
Installed Win7 SDK. Can't find winDbg
I installed everything including the debugging tools. I've looked through the Microsoft SDK folder and couldn't find anything that resembled winDbg or an installer for it.
Anyone?
Edit: I'm trying to use a dump file to figure out why I had a BSOD. Will this site give me the same information as winDbg? http://www.osronline.com/page.cfm?name=analyze
Edit 2: I think the sdk did not install correctly. So I'm working on that now. I'm pretty sure what the sdk I downloaded included debugging tools(winDbg). http://www.microsoft.com/en-us/download/confirmation.aspx?id=8279
Edit 3: Installed the sdk correctly and all is well.
A:
I uninstalled the 2010 C++ x86 and x64 redistributables. This allowed me to install the SDK completely along with the redistributables I just uninstalled. I found winDbg here: C:\Program Files\Debugging Tools for Windows (x64).
This can be closed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Three.js, moving a partical along an EllipseCurve
I know questions related to my problem have been asked and answered before but three.js changed a lot in the last couple years and I'm having trouble finding what I need in the currently available examples.
I have an elliptical curve that I'd like to run particles along. My code runs without error but it doesn't actually move the particle anywhere. What am I missing?
var t = 0;
var curve = new THREE.EllipseCurve( .37, .15, .35, .25, 150, 450, false, 0 );
var points = curve.getPoints( 50 );
var curveGeometry = new THREE.BufferGeometry().setFromPoints( points );
var particleGeometry = new THREE.Geometry();
var particleMap = new THREE.TextureLoader().load( "/img/spark.png" );
var vertex = new THREE.Vector3();
vertex.x = points[0].x;
vertex.y = points[0].y;
vertex.z = 0;
particleGeometry.vertices.push(vertex);
particleMaterial = new THREE.PointsMaterial({
size: .05,
map: particleMap,
blending: THREE.AdditiveBlending,
depthTest: false,
transparent : true
});
particles = new THREE.Points( particleGeometry, particleMaterial );
scene.add(particles);
animate();
function animate() {
if (t <= 1) {
particles.position = curveGeometry.getPointAt(t)
t += 0.005
} else {
t = 0;
}
requestAnimationFrame( animate );
render();
}
function render() {
renderer.render( scene, camera );
}
A:
Just a rough concept of how you can do it, using THREE.Geometry():
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 50);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setClearColor(0x404040);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
var grid = new THREE.GridHelper(40, 40, "white", "gray");
grid.rotation.x = Math.PI * -0.5;
scene.add(grid);
var curve = new THREE.EllipseCurve(0, 0, 20, 20, 0, Math.PI * 2, false, 0);
// using of .getPoints(division) will give you a set of points of division + 1
// so, let's get the points manually :)
var count = 10;
var inc = 1 / count;
var pointAt = 0;
var points = [];
for (let i = 0; i < count; i++) {
let point = curve.getPoint(pointAt); // get a point of THREE.Vector2()
point.z = 0; // geometry needs points of x, y, z; so add z
point.pointAt = pointAt; // save position along the curve in a custom property
points.push(point);
pointAt += inc; // increment position along the curve for next point
}
var pointsGeom = new THREE.Geometry();
pointsGeom.vertices = points;
console.log(points);
var pointsObj = new THREE.Points(pointsGeom, new THREE.PointsMaterial({
size: 1,
color: "aqua"
}));
scene.add(pointsObj);
var clock = new THREE.Clock();
var time = 0;
render();
function render() {
requestAnimationFrame(render);
time = clock.getDelta();
points.forEach(p => {
p.pointAt = (p.pointAt + time * 0.1) % 1; // it always will be from 0 to 1
curve.getPoint(p.pointAt, p); //re-using of the current point
});
pointsGeom.verticesNeedUpdate = true;
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Install app to user profile
I have an application in facebook. And I want to add the ability for installing this app on the user's personal timeline.
What is to be done in the application?
I tried to found any answer in the documentation (for example http://developers.facebook.com/docs/appsonfacebook/pagetabs/ ). I found a way to install an app to the fan page only.
But I need the ability to install app to the user's personal profile.
A:
"Tabs" (in the way you can build them for pages) are not supported on user-profiles since more than 2 years!
The only way to have an application-tile on a users profile (like shown on the screenshot below) is by publishing Open Graph-actions through the app.
However, these are not "Tabs" in the sense that you have an iframe which you can build to your needs. They simply display the Open Grap-aggregations defined in the app-dashboard:
Also, these Timeline-aggregations seem to be quite buggy since quite a while, so I wouldn't recommend relying to much on them:
https://developers.facebook.com/bugs/434970296563783
| {
"pile_set_name": "StackExchange"
} |
Q:
When should I use a class and when should I use a function?
When is a class more useful to use than a function? Is there any hard or fast rule that I should know about? Is it language dependent? I'm intending on writing a script for Python which will parse different types of json data, and my gut feeling is that I should use a class to do this, versus a function.
A:
You should use a class when your routine needs to save state. Otherwise a function will suffice.
A:
First of all, I think that isn't language-dependent (if the language permit you to define classes and function as well).
As a general rule I can tell you that a Class wrap into itself a behaviour. So, if you have a certain type of service that you have to implement (with, i.e. different functions) a class is what you're lookin' for.
Moreover classes (say object that is more correct) has state and you can instantiate more occurrences of a class (so different objects with different states).
Not less important, a class can be inearthed: so you can overwrite a specific behaviour of your function only with small changes.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I update a list data_relation in Python Eve
I have a model 'users' and a schema for it, which includes a one-to-many relation back to users:
'followers': {
'type': 'list',
'schema': {
'type': 'objectid',
'data_relation': {
'resource': 'users'
}
}
},
I am trying to update the list of followers. I tried sending PATCH request to the /users/545c7dccb505970bbf0e5ad1 endpoint with a 'followers' key and a list of objectids but it doesn't work. Also tried sending a PUT request to /users/545c7dccb505970bbf0e5ad1/followers/ but no luck.
So how do I add an object to this list with Python Eve REST API?
GET /users/545c7dccb505970bbf0e5ad1/
{
"_updated": "Fri, 07 Nov 2014 08:07:40 GMT",
"public_key": "test",
"_etag": "256d6da738a0f39929d40d1c868e1f67661460be",
"_links": {
"self": {
"href": "/users/545c7dccb505970bbf0e5ad1",
"title": "User"
},
"parent": {
"href": "",
"title": "home"
},
"collection": {
"href": "/users",
"title": "users"
}
},
"active": false,
"_created": "Fri, 07 Nov 2014 08:07:40 GMT",
"_id": "545c7dccb505970bbf0e5ad1"
}
PATCH /users/545c7dccb505970bbf0e5ad1
{
"_status": "ERR",
"_error": {
"message": "You don't have the permission to access the requested resource. It is either read-protected or not readable by the server.",
"code": 403
}
}
PUT /users/545c7dccb505970bbf0e5ad1/followers
{
"_status": "ERR",
"_error": {
"message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.",
"code": 404
}
}
A:
doesn't work is awfully broad... however at a guess you need to send your _etag token the server returned when fetching or creating the user... this is required to prevent updating from an out of date model
| {
"pile_set_name": "StackExchange"
} |
Q:
Compare user input with values stored in vector
This is my program thus far. It compiles but gets stuck and crashes on the last part. I want to repeat user's string input and replace any bad words found in the string with "****". Most likely my error is in find_Poop_inSentence. "Debug Assertion failed. vector subscript out of range"
void find_Poop_inSentence(vector<string> & v1, vector<string> & v2, string sub);
int main()
{
cout << "Howdy partner, tell me some words you don't take kindly to.\n";
vector<string>bad_words;
string word;
while (cin >> word)
{
cin.ignore();
bad_words.push_back(word);
if (word == "exit")
break;
}
cout << "Ok partner, got it!\n";
cout << "Now say something and I'll repeat it back to you. Don't worry, I'll bleep out the words that you don't like.\n";
word = "";
vector<string> random_sentence;
while (cin >> word)
{
cin.ignore();
random_sentence.push_back(word);
if (cin.get() == '\n')
break;
}
find_Poop_inSentence(bad_words, random_sentence, "****");
cout << "You said: ";
for (unsigned int i = 0; i < random_sentence.size(); ++i) {
cout << ' ' << random_sentence[i];
}
system("Pause");
return 0;
}
void find_Poop_inSentence(vector<string> & v1, vector<string> & v2, string sub) {
int iterOne;
int iterTwo = 0;
int iteratorMax = v2.size();
for (iterOne = 0; iterOne < iteratorMax; iterTwo++) {
if (v1[iterOne] == v2[iterTwo]) {
v2[iterTwo] == sub;
}
if (iterTwo == iteratorMax ) {
iterOne++;
iterTwo = 0;
}
}
}
A:
Well thanks to my friend Ivan Drago I was able to solve this.
void find_Poop_inSentence(vector<string> & v1, vector<string> & v2, string sub);
int main()
{
cout << "Howdy partner, tell me some words you don't take kindly to.\n";
vector<string>bad_words;
string word;
while (cin >> word)
{
//cin.ignore();
bad_words.push_back(word);
if (word == "exit")
break;
}
cout << "Ok partner, got it!\n";
cout << "Now say something and I'll repeat it back to you. Don't worry, I'll bleep out the words that you don't like.\n";
cout << "Push enter twice when done.\n";
word = "";
vector<string> random_sentence;
while (cin >> word)
{
//cin.ignore();
random_sentence.push_back(word);
if (cin.get() == '\n')
break;
}
find_Poop_inSentence(bad_words, random_sentence, "****");
cout << "You said: ";
for (unsigned int i = 0; i < random_sentence.size(); ++i) {
cout << ' ' << random_sentence[i];
}
system("Pause");
return 0;
}
void find_Poop_inSentence(vector<string> & v1, vector<string> & v2, string sub) {
for (unsigned int i = 0; i < v1.size(); i++) {
for (unsigned int j = 0; j < v2.size(); j++) {
if (v1[i] == v2[j]) {
v2[j] = sub;
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.