text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Dell PowerEdge 1950 strange reboot
I have Dell PowerEdge 1950 with debian which reboot without reason, and after reboot BIOS write that "previous shutdown was with error press f1 for continue".
First of all, is it possible switch of this "f1 for continue"?
Its remote server and I hate this.
And I can not explain - why its rebooted. There is part of my logs:
Sep 7 11:48:11 kernel: [182893.472177] virbr0: port 8(vnet7) entered forwarding state
Sep 7 11:48:11 kernel: [182893.484451] libvirtd: page allocation failure: order:4, mode:0x2000d0
Sep 7 11:48:11 kernel: [182893.484456] CPU: 0 PID: 2427 Comm: libvirtd Not tainted 3.10-2-amd64 #1 Debian 3.10.7-1
Sep 7 11:48:11 kernel: [182893.484458] Hardware name: Dell Inc. PowerEdge 1950/0DT097, BIOS 2.7.0 10/30/2010
Sep 7 11:48:11 kernel: [182893.484461] 0000000000000000 ffffffff810c4af9 ffff88012fff9b08 ffff88012fff8d80
Sep 7 11:48:11 kernel: [182893.484466] 0000000000000000 0000000000000000 ffff880100000002 ffffffff810d4f89
Sep 7 11:48:11 kernel: [182893.484469] 0000000000000010 fffffffffffffff0 000000000000001e 0000000000000000
Sep 7 11:48:11 kernel: [182893.484473] Call Trace:
Sep 7 11:48:11 kernel: [182893.484482] [<ffffffff810c4af9>] ? warn_alloc_failed+0x118/0x12c
Sep 7 11:48:11 kernel: [182893.484487] [<ffffffff810d4f89>] ? next_online_pgdat+0x1c/0x3a
Sep 7 11:48:11 kernel: [182893.484491] [<ffffffff810c7469>] ? __alloc_pages_nodemask+0x206/0x78e
Sep 7 11:48:11 kernel: [182893.484496] [<ffffffff810f90dc>] ? kmem_getpages+0x53/0x122
Sep 7 11:48:11 kernel: [182893.484499] [<ffffffff810f997c>] ? fallback_alloc+0x123/0x1e5
Sep 7 11:48:11 kernel: [182893.484502] [<ffffffff810f9efa>] ? kmem_cache_alloc_trace+0x7c/0xcc
Sep 7 11:48:11 kernel: [182893.484510] [<ffffffffa0543fcc>] ? vhost_net_open+0x1f/0x17d [vhost_net]
Sep 7 11:48:11 kernel: [182893.484515] [<ffffffff8126a54e>] ? misc_open+0x117/0x17a
Sep 7 11:48:11 kernel: [182893.484519] [<ffffffff8110cd6c>] ? chrdev_open+0x11c/0x140
Sep 7 11:48:11 kernel: [182893.484522] [<ffffffff8110cc50>] ? cdev_put+0x19/0x19
Sep 7 11:48:11 kernel: [182893.484526] [<ffffffff8110815b>] ? do_dentry_open+0x16d/0x20f
Sep 7 11:48:11 kernel: [182893.484529] [<ffffffff81108227>] ? finish_open+0x2a/0x33
Sep 7 11:48:11 kernel: [182893.484533] [<ffffffff811146d7>] ? do_last+0x864/0xa0c
Sep 7 11:48:11 kernel: [182893.484536] [<ffffffff8111219f>] ? __inode_permission+0x57/0x95
Sep 7 11:48:11 kernel: [182893.484539] [<ffffffff81114941>] ? path_openat+0xc2/0x327
Sep 7 11:48:11 kernel: [182893.484543] [<ffffffff81114e49>] ? do_filp_open+0x2a/0x6e
Sep 7 11:48:11 kernel: [182893.484546] [<ffffffff810fa414>] ? kmem_cache_alloc+0x8c/0xfd
Sep 7 11:48:11 kernel: [182893.484550] [<ffffffff8111dcce>] ? __alloc_fd+0xcc/0xdb
Sep 7 11:48:11 kernel: [182893.484553] [<ffffffff81108a99>] ? do_sys_open+0x5c/0xe0
Sep 7 11:48:11 kernel: [182893.484557] [<ffffffff8138ade9>] ? system_call_fastpath+0x16/0x1b
Sep 7 11:48:11 kernel: [182893.484559] Mem-Info:
Sep 7 11:48:11 kernel: [182893.484561] Node 0 DMA per-cpu:
Sep 7 11:48:11 kernel: [182893.484564] CPU 0: hi: 0, btch: 1 usd: 0
Sep 7 11:48:11 kernel: [182893.484566] CPU 1: hi: 0, btch: 1 usd: 0
Sep 7 11:48:11 kernel: [182893.484568] CPU 2: hi: 0, btch: 1 usd: 0
Sep 7 11:48:11 kernel: [182893.484569] CPU 3: hi: 0, btch: 1 usd: 0
Sep 7 11:48:11 kernel: [182893.484571] Node 0 DMA32 per-cpu:
Sep 7 11:48:11 kernel: [182893.484573] CPU 0: hi: 186, btch: 31 usd: 0
Sep 7 11:48:11 kernel: [182893.484575] CPU 1: hi: 186, btch: 31 usd: 0
Sep 7 11:48:11 kernel: [182893.484577] CPU 2: hi: 186, btch: 31 usd: 0
Sep 7 11:48:11 kernel: [182893.484579] CPU 3: hi: 186, btch: 31 usd: 0
Sep 7 11:48:11 kernel: [182893.484581] Node 0 Normal per-cpu:
Sep 7 11:48:11 kernel: [182893.484583] CPU 0: hi: 186, btch: 31 usd: 0
Sep 7 11:48:11 kernel: [182893.484585] CPU 1: hi: 186, btch: 31 usd: 0
Sep 7 11:48:11 kernel: [182893.484587] CPU 2: hi: 186, btch: 31 usd: 2
Sep 7 11:48:11 kernel: [182893.484589] CPU 3: hi: 186, btch: 31 usd: 0
Sep 7 11:48:11 kernel: [182893.484594] active_anon:423230 inactive_anon:137000 isolated_anon:0
Sep 7 11:48:11 kernel: [182893.484594] active_file:169377 inactive_file:162749 isolated_file:0
Sep 7 11:48:11 kernel: [182893.484594] unevictable:0 dirty:7 writeback:0 unstable:0
Sep 7 11:48:11 kernel: [182893.484594] free:57651 slab_reclaimable:16563 slab_unreclaimable:9296
Sep 7 11:48:11 kernel: [182893.484594] mapped:2985 shmem:145 pagetables:3918 bounce:0
Sep 7 11:48:11 kernel: [182893.484594] free_cma:0
Sep 7 11:48:11 kernel: [182893.484599] Node 0 DMA free:15908kB min:264kB low:328kB high:396kB active_anon:0kB inactive_anon:0kB active_file:0kB inactive_file:0kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:15996kB managed:15908kB mlocked:0kB dirty:0kB writeback:0kB mapped:0kB shmem:0kB slab_reclaimable:0kB slab_unreclaimable:0kB kernel_stack:0kB pagetables:0kB unstable:0kB bounce:0kB free_cma:0kB writeback_tmp:0kB pages_scanned:0 all_unreclaimable? yes
Sep 7 11:48:11 kernel: [182893.484607] lowmem_reserve[]: 0 3231 3940 3940
Sep 7 11:48:11 kernel: [182893.484610] Node 0 DMA32 free:188268kB min:55212kB low:69012kB high:82816kB active_anon:1429476kB inactive_anon:284516kB active_file:658168kB inactive_file:631332kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:3386688kB managed:3309356kB mlocked:0kB dirty:16kB writeback:0kB mapped:6836kB shmem:220kB slab_reclaimable:53080kB slab_unreclaimable:12744kB kernel_stack:1024kB pagetables:7692kB unstable:0kB bounce:0kB free_cma:0kB writeback_tmp:0kB pages_scanned:0 all_unreclaimable? no
Sep 7 11:48:11 kernel: [182893.484618] lowmem_reserve[]: 0 0 708 708
Sep 7 11:48:11 kernel: [182893.484621] Node 0 Normal free:26428kB min:12100kB low:15124kB high:18148kB active_anon:263444kB inactive_anon:263484kB active_file:19340kB inactive_file:19664kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:786432kB managed:725380kB mlocked:0kB dirty:12kB writeback:0kB mapped:5104kB shmem:360kB slab_reclaimable:13172kB slab_unreclaimable:24440kB kernel_stack:1400kB pagetables:7980kB unstable:0kB bounce:0kB free_cma:0kB writeback_tmp:0kB pages_scanned:0 all_unreclaimable? no
Sep 7 11:48:11 kernel: [182893.484629] lowmem_reserve[]: 0 0 0 0
Sep 7 11:48:11 kernel: [182893.484632] Node 0 DMA: 1*4kB (U) 0*8kB 0*16kB 1*32kB (U) 2*64kB (U) 1*128kB (U) 1*256kB (U) 0*512kB 1*1024kB (U) 1*2048kB (R) 3*4096kB (M) = 15908kB
Sep 7 11:48:11 kernel: [182893.484645] Node 0 DMA32: 12519*4kB (UEM) 12482*8kB (UEM) 2152*16kB (UM) 3*32kB (U) 0*64kB 0*128kB 0*256kB 0*512kB 0*1024kB 0*2048kB 1*4096kB (R) = 188556kB
Sep 7 11:48:11 kernel: [182893.484659] Node 0 Normal: 5894*4kB (UM) 108*8kB (UM) 1*16kB (R) 2*32kB (R) 0*64kB 0*128kB 1*256kB (R) 1*512kB (R) 0*1024kB 1*2048kB (R) 0*4096kB = 27336kB
Sep 7 11:48:11 kernel: [182893.484684] Node 0 hugepages_total=0 hugepages_free=0 hugepages_surp=0 hugepages_size=2048kB
Sep 7 11:48:11 kernel: [182893.484685] 345767 total pagecache pages
Sep 7 11:48:11 kernel: [182893.484688] 13606 pages in swap cache
Sep 7 11:48:11 kernel: [182893.484690] Swap cache stats: add 110606, delete 97000, find 86650/91247
Sep 7 11:48:11 kernel: [182893.484692] Free swap = 2779960kB
Sep 7 11:48:11 kernel: [182893.484693] Total swap = 2928636kB
Sep 7 11:48:11 kernel: [182893.504936] 1048575 pages RAM
Sep 7 11:48:11 kernel: [182893.504939] 34669 pages reserved
Sep 7 11:48:11 kernel: [182893.504940] 1385978 pages shared
Sep 7 11:48:11 kernel: [182893.504941] 629752 pages non-shared
Sep 7 11:48:11 kernel: [182893.504944] kmem_getpages: 150006 callbacks suppressed
Sep 7 11:48:11 kernel: [182893.504946] SLAB: Unable to allocate memory on node 0 (gfp=0xd0)
Sep 7 11:48:11 kernel: [182893.504949] cache: kmalloc-65536, object size: 65536, order: 4
Sep 7 11:48:11 kernel: [182893.504953] node 0: slabs: 13/13, objs: 13/13, free: 0
Sep 7 11:52:49 kernel: [183171.325360] kvm: sending ioctl 5326 to a partition!
Sep 7 11:52:49 kernel: [183171.325374] kvm: sending ioctl 80200204 to a partition!
What is faulted? Memory allocation?
I have some kvm virtual machines on this host , but its sums of memory less then on hosts, and I have a lot of free swap.
UPD:
new log, now with SMP string:
Sep 10 17:03:54 kernel: [83522.369641] Hardware name: Dell Inc.
PowerEdge 1950/0DT097, BIOS 2.7.0 10/30/2010
Sep 10 17:03:54 kernel: [83522.369644] 0000000000000000
ffffffffa0352060 0000000000000000 00000001087ef000 Sep 10 17:03:54
kernel: [83522.369649] ffff8800c6440080 0000000000000000
0000000000000000 ffff8800c6440080 Sep 10 17:03:54 kernel:
[83522.369652] 0000000000000000 0000000000000001 ffffffffa034b051
0000000100000008 Sep 10 17:03:54 kernel: [83522.369656] Call Trace:
Sep 10 17:03:54 kernel: [83522.369703] [] ?
kvm_mmu_load+0x315/0x33b [kvm] Sep 10 17:03:54 kernel:
[83522.369716] [] ?
kvm_arch_vcpu_ioctl_run+0x8b4/0xe9f [kvm] Sep 10 17:03:54 kernel:
[83522.369723] [] ? vmx_vcpu_load+0x28/0x14e
[kvm_intel] Sep 10 17:03:54 kernel: [83522.369728]
[] ? paravirt_write_msr+0xb/0xe [kvm_intel]
Sep 10 17:03:54 kernel: [83522.369736] [] ?
kvm_vcpu_ioctl+0x116/0x48b [kvm] Sep 10 17:03:54 kernel:
[83522.369743] [] ? do_futex+0xd1/0x7b5
Sep 10 17:03:54 kernel: [83522.369748] [] ?
do_sync_readv_writev+0x76/0x76 Sep 10 17:03:54 kernel:
[83522.369752] [] ? vfs_ioctl+0x1b/0x25
Sep 10 17:03:54 kernel: [83522.369755] [] ?
do_vfs_ioctl+0x3e8/0x42a Sep 10 17:03:54 kernel:
[83522.369759] [] ? finish_task_switch+0x48/0xaa
Sep 10 17:03:54 kernel: [83522.369764] [] ?
__schedule+0x4dc/0x532 Sep 10 17:03:54 kernel: [83522.369767] [] ? SyS_ioctl+0x4e/0x79
Sep 10 17:03:54 kernel: [83522.369771] [] ?
system_call_fastpath+0x16/0x1b Sep 11 12:10:19 kernel:
[152307.503781] BUG: unable to handle kernel NULL pointer dereference
at 000000000000021c
Sep 11 12:10:19 kernel: [152307.503946] IP: []
tag_get+0x2/0xd Sep 11 12:10:19 kernel:
[152307.504038] PGD 0-
Sep 11 12:10:19 kernel: [152307.504081] Oops: 0000 [#1] SMP-
UPD:
Screenshot from one of debian virtual machine inside kvm:
After that real server was frozen, and rebooted with power
A:
Yes, you can switch off that F1 in the BIOS-security-settings.
But you should only do so if you are sure why and what you are doing.
This is a sign for a hardware problem that needs to be fixed.
Try to download a current OMSA-live-CD from Dell and look at omsa to find what is actually wrong with your machine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IIS, single UC cert, multiple sites and host headers. How does it all work together?
Let me start off my saying, IIS is not a strong point of mine. I had asked THIS question here, because i was trying to use 2 different certs on different sites. Scratch all that now, there is a new configuration.
I've purchased a UC cert, and given it all the necessary domains that i need. Here is my new question, I have 2 sites in IIS that both need to use the same cert, is this even possible? What do i need to do to make both sites work? Is there a 'host-headers for dummies' out there?
EDIT: I should mention that one of the sites is my Exchange 2007 site, and the other is a SharePoint site.
A:
To do this you need to use SSL host headers.
The first thing to do is to setup all your sites in IIS for normal HTTP, so set them up, set them all to listen on the same IP with different host headers. I assume you have already done this with at least one site, as you have got your certificate already. Setup your certificate on one of your sites as you would do normally.
Next you need to setup SSL host headers on the other site, to do so run this command from the command prompt, in the C:\Inetpub\AdminScripts folder:
cscript.exe adsutil.vbs set /w3svc/<site identifier>/SecureBindings ":443:<host header>"
Replacing site identifier with your site ID that can be seen in IIS, and host header with the actual host header for this site.
This will then create an SSL host header for that site, that will use the certificate from the first site.
If you want a more detail explanation look here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Append does not work when I try to code in Javascript OOP style
I am learning the concepts of programming in javascript OOP style and I need a little help:
First, a simple html form:
<form>
<select id="jobRole"></select>
</form>
Next, I write the "Question" class:
var Question = function() {
this.masterQ = function (id1) {
this.id1 = jQuery(id1);
this.id1.append('<option value="">test</option>');
};
}
Now I instantiate the question class, making a new object
var q = new Question();
And now I call the masterQ method:
q.masterQ('#jobRole');
But, I have no idea why test isn't appended onto the select.
Any ideas?
Thank you!
A:
I just try it and the code works -> http://jsfiddle.net/HxhH2/1/
Are you sure that you included jquery in your page
<script src="pathtojquery.js"></script>
Or you maybe execute the code before to get the dropdown on the page. It will be good to wrap your logic into
$(document).ready(function() {
// your code here
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sites page Office 365
Is there a way to modifiy this page (Sites in Office 365 that shows you the sites you are following, the suggested sites and the promoted sites)?
I can't see an option like Edit page or something like that for this page
A:
If I understand the problem correctly, what you wanted is to manage the promoted sites and sites you are following.
For promoted sites, only administrators can manage it. It is global to all users. In the administrator view, you will find the boxes(sites) to be editable.
For sites you are following, you can un-follow sites by clicking on Stop Following button or go to the site and click Unfollow (located on the upper right corner of the site). Similarly, for sites that you want to follow, simply navigate to the site and click Follow.
This link will give you a more detailed guide for managing promoted links. On the other hand, this link demonstrates on how to follow or stop following sites. I believe there is no way wherein you can manage the sites in a tabular (like a list) manner.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laravel How to return variables from php file to blade template
I have created a file localization.php and i defined some variable like:
localization.php
<?php
$color = 'red';
$background = 'orange';
?>
now i included the localization.php file in all my blade templates like:
@include('localization')
and here in template i want to echo the variables which i mentioned in localiztion.php
{{$color}} //when i use this it show error 'undefined variable'
can you guys please help me to fix this
A:
"i want to use this localization file in all view i have some genereic variables and i want to include this in all blade templates "
the best way to do this is put it on constants. in directory config>>constants.php
<?php
return
[
'ToBeReturn' => [
'color' => 'red',
'background' => 'orange']
];
then at your controller you can return it
public function index()
{
return view('index')
->with('color',config('constants.ToBeReturn.color')
->with('background',config('constants.ToBeReturn.background'));
}
now on your view you can view it as
{{ $color }}
{{ $background }}
do a
php artisan config:cache
This is the standard the MVC laravel follows. Putting variable in a view is not good. so since you want a localize variable, put it on constants.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getline doesn't work as expected
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int order[5];
string carorder[5];
int smallest=999999, where;
string carname[5];
float carprice[5];
cout << "Enter car names then prices: ";
cout << endl;
for(int i=0; i < 5; i++){
cin >> carname[i];
//getline(cin, carname[i]); can't do this -- why?
cout << endl;
cin >> carprice[i];
cout << endl;
}
//BAD ALGORITHM//
for(int m=0; m<5; m++){
for(int j=0; j < 5; j++){
if(carprice[j] < smallest){
smallest = carprice[j];
where = j;
}
}
order[m] = smallest;
carorder[m] = carname[where];
carprice[where] = 999999;
smallest = 999999;
}
//////////////////////////
for(int w=0; w<5; w++){
cout << endl << "The car: " << carname[w] << " and price: " << order[w];
}
//////////////////////////
return 0;
}
I'm doing an exercise in c++ and it's supposed to take a car and its price, then return the prices in order from lowest to highest. The challenge is to use the algorithm given by the professor, so please don't mind that part (I think it's bad algorithm). I need to know why can't I use getline(cin, carname[i]); and cin >> carname[i]; works fine. I also tried using cin.clear(); and cin.ignore(); before the getline, still doesn't work. Any help is appreciated.
A:
Formatted input, i.e., using operator>>(), will skip leading whitespace. In addition, it will stop when a character is received which doesn't fit the format. For example, when reading a float, the input will read a number and stop upon the first whitespace received. For example, it will stop right before a newline used to enter the current value.
Unformatted input, e.g., using std::getline(), won't skip leading whitespace. Instead, it will happily read whatever character is waiting to be read. For example, if the next character is a newline, std::getline() will happily stop reading right there!
Generally, when switching from formatted to unformatted input, you want to get rid of some of the whitespace. For example, you can skip all leading whitespace with the std::ws manipulator:
std::getline(std::cin >> std::ws, carname[i]);
Your inputs go entirely unchecked: not checking the result before using it is generally a bad idea! You should probably test the stream state at some point and possible restore it to good state, asking for correctly formatted data.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to create a new consumer group in kafka
I am running kafka locally following instructions on quick start guide here,
and then I defined my consumer group configuration in config/consumer.properties so that my consumer can pick messages from the defined group.id
Running the following command,
bin/kafka-consumer-groups.sh --list --bootstrap-server localhost:9092
results in,
test-consumer-group <-- group.id defined in conf/consumer.properties
console-consumer-67807 <-- when connecting to kafka via kafka-console-consumer.sh
I am able to connect to kafka via a python based consumer that is configured to use the provide group.id i.e test-consumer-group
First of all, I am not able to understand how/when kafka creates consumer groups. It seems it loads the conf/consumer.properties at some point of time and additionally it implicitly creates consumer-group (in my case console-consumer-67807) when connecting via kafka-console-consumer.sh.
How can I explicitly create my own consumer group, lets say my-created-consumer-group ?
A:
Each Kafka Consumer will have a Consumer Group. The consumer group is configurable for each individual consumer.
It seems it loads the conf/consumer.properties at some point of time and additionally it implicitly creates consumer-group (in my case console-consumer-67807) when connecting via kafka-console-consumer.sh
If you do not tell your console consumer to actually make use of that file it will not be taken into consideration.
There are the following alternatives to provide the name of a consumer group:
Console Consumer with property file (--consumer.config)
This is how the file config/consumer.properties should look like
# consumer group id
group.id=my-created-consumer-group
And this is how you would then ensure that the console-consumer takes this group.id into consideration:
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test-topic --from-beginning --consumer.config /path/to/config/consumer.properties
Console consumer with --group
For console consumers the consumer group gets created automatically with prefix "console-consumer" and suffix something like a PID, unless you provide your own consumer group by adding --group:
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test-topic --from-beginning --group my-created-consumer-group
Standard code-based consumer API
When using the standard JAVA/Scala/... Consumer API you could provide the Consumer Group through the properties:
Properties settings = new Properties();
settings.put(ConsumerConfig.GROUP_ID_CONFIG, "basic-consumer");
// set more properties
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(settings)) {
consumer.subscribe(Arrays.asList("test-topic")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
When did Clarke become pregnant in the TV series 'The 100'?
In the earlier episodes Clarke is shown to have sex with Finn and Bellamy. But in the later series Clarke is shown as lesbian. In season 4 last episode Clarke is shown having a girl.
So when did Clarke become pregnant?
A:
She didn't !
The child is her adopted daughter.
Shamelessly copied from MY OWN answer at SF&F
There's no specific indication that Maddie is Clarke's daugher (barring advanced aging) since she is clearly more than 6 years old (less pregnancy time).
Jason Rothenburg, producer of The 100...
We wanted a reveal that Clarke survived and that her Nightblood kicked in, and she's now essentially — or so we think for the first couple of minutes of that final pop-out at the end — the lone survivor on the planet. Her friends... we know they made it to space, but she doesn't know whether or not they made it. We also know there's a group of 1200 led by Octavia (Marie Avgeropoulos) in the bunker, but Clarke is the lone survivor on the planet. And then we reveal she's found Maddy, this Nightblood child. Clearly, there's a maternal connection between the two of them when we reveal her in the end.
...
They have been together for years when we first see them. She's been with Maddy alone for a number of years; longer than she was ever on the ground with anybody. So it's going to be a very powerful bond and a huge part of season five.
Hollywood Reporter
Found does not indicate a daughter at least not a birth-daughter.
Indeed...at another interview...Rothenberg confirms
The mother-daughter vibe that you pick up on in that scene is real. (It’s not her biological child; I think it’s fairly obvious that the kid is too old for that.) But she is a nightblood. Clarke was alone until she found Madi. When we find them together in [episode] 413, they have been together already for a number of years and are relying on each other and surviving together.
EW.com
In season 5, it is revealed that Madi is from Shadow Valley, and Clarke finds her as a young child. They rely on each other to survive.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can i use linq to make a console application in C# for counting vowel in a sentence
I am trying make a program to count the number of vowels in a sentence but looks like it could be easily implemented with Linq. But have no idea about this.
Please help me or provide some link.
Thanks,
A:
That's definitely easy. You're just taking each letter in turn, and seeing if it's in one of another set. Fortunately, string implements IEnumerable<char>, so taking each character in turn is really natural with LINQ.
The Enumerable.Count method has an overload accepting a predicate - it returns the number of items in the sequence which match the predicate. Then you've just got to work out a predicate meaning "is this character a vowel". Using string.Contains(char) is the easiest way here.
This will do it:
int count = sentence.Count(c => "AEIOUaeiou".Contains(c));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iPhone midi implementation
i want to synchronize my app to an external midi clock. does anyone know of any code base to do this on the iphone?
i dont want to generate midi events i just want to respond to timing information
A:
Since iOS v4, an iPhone or iPad can join an OS X CoreMIDI network over Wi-Fi, or connect directly to a MIDI interface using USB.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Contact form emails; from, reply-to, ...?
We are developing a contact form for a SaaS application; each instance of our application will have a contact form to contact the instance owner.
Our first version sends email from a generic SaaS email address (i.e. [email protected]) to the owner of the instance (i.e. [email protected]).
This works, but of course if [email protected] replies to the email, the answer gets sent to [email protected] . I'm wondering what's the best practice here:
Setting the from: message to the email address filled out in the contact form would enable replies to be sent easily to the person who sent the contact form- but then, we cannot tell people to add [email protected] to their whitelist to avoid spam filtering
Setting the reply-to header seems better, but I'm wary that some clients will misinterpret reply-to
Including an explanatory text in the message seems inconvenient, but workable
Allowing instance owners to read contact forms through their admin panel seems too much work (but completely spamfilter-proof, albeit inconvenient)
I'm leaning towards 2. Thoughts?
Alex
A:
I'd definitely go for option 2 . From-Header / Envelope-From should make it clear that the message originated at your service (and allow proper bounce handling etc) . I'm not aware of any current mail clients that cannot handle reply-to header correctly. to be on the safe side you could mix in option 3 and clearly state that the message was sent from address [email protected] via your webform.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
why does accessing C++ string class through string.h work?
In the C++ program below, I include the string.h file and I successfully instantiate the C++ string class in it and call one of its member functions: size().
#include <iostream>
#include <string.h>
using namespace std;
int main( )
{
string s = "Hello";
cout << "String: " << s << endl;
cout << "Size of string: " << s.size() << endl;
cin.get();
return 0;
}
The output is:
String: Hello
Size of string: 5
I am using Dev-C++ 4.9.9.2
My question: doesn't the string.h file just provide the functions for manipulating C strings? It doesn't include the definition of the C++ string class right? So, how is it that I am able to access the C++ string class without using #include <string>? My understanding is that the string.h file is the C strings library file and <string> includes the C++ string library file. Is this not right?
Thanks!
A:
This is because std::string is defined though one of the files included in the <iostream> header. The streams provide support for input and output of strings, so they need to include a string header in order to define the corresponding >> and << operations.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are considered as Test Environment apart from windows, Mac , Linux?
What are considered as Test Environment apart from windows, Mac , Linux?
Chrome, diff Browsers classified as environment?
A:
According to ISTQB glossary, it is:
An environment containing hardware, instrumentation, simulators, software tools, and other support elements needed to conduct a test.
A:
"Environments" is really too generic a term.
I would consider using the terms:
Operating System of the server.
Usually one of:
Windows
OSX
Linux
Operating System of the Client Computer.
Usually one of:
Windows
Max
Linux
Client Browser
Usually one of:
Chrome (all OS's)
Firefox (all OS's)
Internet Explorer (Windows only)
Safari (Mac only)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
java recurison - Need help for solving backtracking Knight's Tour
I am working on the Knight's Tour problem.
In my program the user can select a number n equal to 3 or higher. The number will determine the table's size by n*n in a two-dimensional array. Then the knight will start it's tour based on the starting points given by the user as long as they are higher or equal to 0.
My problem comes when the knight has come to a dead end (as of turn number 12 in the visualization table in the output).
I want to somehow track it's movements so that I can block the dead end, go back a step and try from there. I've figured out that I might need a three-dimensional array so that I can save all the turn numbers in each square. But then again I need an ArrayList witch isn't static. Any suggestions will be appreciated. Here's my code:
package knightsTour;
import java.util.Scanner;
import java.util.ArrayList;
public class KnightsTour
{
private static int turns = 0;
private static ArrayList<String> moves = new ArrayList<String>();
private static int squares;
private static int table[][];
private static boolean takeTour(int x, int y) {
// Checks if all squares is used. If true, algorithm will stop
if (checkIfFinished())
return true;
table[x][y] = ++turns;
// 2 Left, 1 Down
if (x > 1 && y < squares -1 && table[x-2][y+1] == 0)
{
moves.add("X: " + x + ", Y: " + y + ". Moving 2 Left, 1 Down. Turn: " + turns);
if (takeTour(x-2, y+1))
{
return true;
}
else
{
return false;
}
}
// 2 Left, 1 Up
if (x > 1 && y > 0 && table[x-2][y-1] == 0)
{
moves.add("X: " + x + ", Y: " + y + ". Moving 2 Left, 1 Up. Turn: " + turns);
if (takeTour(x-2, y-1))
{
return true;
}
else
{
return false;
}
}
// 2 Up, 1 Left
if (y > 1 && x > 0 && table[x-1][y-2] == 0)
{
moves.add("X: " + x + ", Y: " + y + ". Moving 2 Up, 1 Left. Turn: " + turns);
if (takeTour(x-1, y-2))
{
return true;
}
else
{
return false;
}
}
// 2 Up, 1 Right
if (y > 1 && x < squares -1 && table[x+1][y-2] == 0)
{
moves.add("X: " + x + ", Y: " + y + ". Moving 2 Up, 1 Right. Turn: " + turns);
if (takeTour(x+1, y-2))
{
return true;
}
else
{
return false;
}
}
// 2 Right, 1 Up
if (x < squares -2 && y > 0 && table[x+2][y-1] == 0)
{
moves.add("X: " + x + ", Y: " + y + ". Moving 2 Right, 1 Up. Turn: " + turns);
if (takeTour(x+2, y-1))
{
return true;
}
else
{
return false;
}
}
// 2 Right, 1 Down
if (x < squares -2 && y < squares -1 && table[x+2][y+1] == 0)
{
moves.add("X: " + x + ", Y: " + y + ". Moving 2 Right, 1 Down. Turn: " + turns);
if (takeTour(x+2, y+1))
{
return true;
}
else
{
return false;
}
}
// 2 Down, 1 Right
if (y < squares -2 && x < squares-1 && table[x+1][y+2] == 0)
{
moves.add("X: " + x + ", Y: " + y + ". Moving 2 Down, 1 Right. Turn: " + turns);
if (takeTour(x+1, y+2))
{
return true;
}
else
{
return false;
}
}
// 2 Down, 1 Left
if (y < squares -2 && x > 0 && table[x-1][y+2] == 0)
{
moves.add("X: " + x + ", Y: " + y + ". Moving 2 Down, 1 Left. Turn: " + turns);
if (takeTour(x-1, y+2))
{
return true;
}
else
{
return false;
}
}
/*
I need some code here before it gives up searching
*/
// If we'd tried every single paths
// and we still end up here, there's no solution
return false;
}
// Checks if all squares is used
private static boolean checkIfFinished()
{
for (int i = 0; i < squares; i++)
{
for (int j = 0; j < squares; j++)
{
if (table[i][j] == 0)
return false;
}
}
return true;
}
// Made this to save code from 3 duplicates
private static void invalidNumber()
{
System.out.println("Invalid number! Killing proccess");
System.exit(0);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Number of squares: ");
squares = Integer.parseInt(sc.nextLine());
if (squares < 3 )
invalidNumber();
System.out.println("Note: Start values is from 0 -> n-1"
+ "\n0,0 is at top left side");
System.out.print("X start value: ");
int x = Integer.parseInt(sc.nextLine());
if (x < 0 || x > squares -1)
invalidNumber();
System.out.print("Y start value: ");
int y = Integer.parseInt(sc.nextLine());
if (y < 0 || y > squares -1)
invalidNumber();
sc.close();
table = new int[squares][squares];
boolean tourComplete = takeTour(x, y);
for (String s : moves)
{
System.out.println(s);
}
if (!tourComplete)
System.out.println("Did not find any way to complete Knights Tour!");
// Print the table with the move-numbers
for (int i = 0; i < squares; i++)
{
for (int j = 0; j < squares; j++)
{
System.out.printf("%4d", table[j][i]);
}
System.out.println();
}
}
}
My output for a 4*4 table looks like this:
Number of squares: 4
Note: Start values is from 0 -> n-1
0,0 is at top left side
X start value: 0
Y start value: 0
X: 0, Y: 0. Moving 2 Right, 1 Down. Turn: 1
X: 2, Y: 1. Moving 2 Left, 1 Down. Turn: 2
X: 0, Y: 2. Moving 2 Up, 1 Right. Turn: 3
X: 1, Y: 0. Moving 2 Right, 1 Down. Turn: 4
X: 3, Y: 1. Moving 2 Left, 1 Down. Turn: 5
X: 1, Y: 2. Moving 2 Up, 1 Right. Turn: 6
X: 2, Y: 0. Moving 2 Left, 1 Down. Turn: 7
X: 0, Y: 1. Moving 2 Right, 1 Down. Turn: 8
X: 2, Y: 2. Moving 2 Left, 1 Down. Turn: 9
X: 0, Y: 3. Moving 2 Up, 1 Right. Turn: 10
X: 1, Y: 1. Moving 2 Right, 1 Up. Turn: 11
Did not find any way to complete Knights Tour!
1 4 7 12
8 11 2 5
3 6 9 0
10 0 0 0
A:
When trying different possibilities on BackTracking you need to check them all in every recursion step. In the code you provide in a single step you only try one possibility and then return. Doing this you are not able to explore all the possibilities.
My suggestion is to change the function arguments to accept the current position (x,y) and a boolean array for the positions that have been previously visited. If you need to construct the path of the final valid solution, I also suggest to add the step count (the number of steps you have done) and a int array to store which position has been visited in which step.
Next I provide a solution which is not the most efficient. In fact, you can try to prune the backtracking possibilities to avoid the recurssion explosion (cpu efficiency) and you can try to avoid some copies of the matrixes (memory efficiency).
package knightsTour;
import java.util.Scanner;
public class KnightsTour {
private static final int[] MOVE_X = new int[] { -2, -2, -1, -1, +1, +1, +2, +2 };
private static final int[] MOVE_Y = new int[] { +1, -1, +2, -2, +2, -2, +1, -1 };
private final int SQUARES;
private final int INIT_X;
private final int INIT_Y;
private int[][] path;
public KnightsTour(int squares, int x, int y) {
this.SQUARES = squares;
this.INIT_X = x;
this.INIT_Y = y;
}
public int[][] getPath() {
return this.path;
}
public boolean takeTour() {
boolean[][] visited = new boolean[this.SQUARES][this.SQUARES];
for (int i = 0; i < this.SQUARES; ++i) {
for (int j = 0; j < this.SQUARES; ++j) {
visited[i][j] = false;
}
}
visited[this.INIT_X][this.INIT_Y] = true;
this.path = new int[this.SQUARES][this.SQUARES];
return takeTourBT(this.INIT_X, this.INIT_Y, 0, visited, this.path);
}
private boolean takeTourBT(int posX, int posY, int step, boolean[][] visited, int[][] path) {
debug(step, visited);
if (checkIfFinished(visited)) {
return true;
}
// Increase the step count
++step;
// Try recursively (cut when a branch success)
boolean success = false;
for (int i = 0; i < MOVE_X.length && !success; ++i) {
int nextX = posX + MOVE_X[i];
int nextY = posY + MOVE_Y[i];
if (nextX >= 0 && nextX < this.SQUARES && nextY >= 0 && nextY < this.SQUARES && !visited[nextX][nextY]) {
// Next position is valid and has not been visited
// Mark position
visited[nextX][nextY] = true;
// Call
boolean branchSuccess = takeTourBT(nextX, nextY, step, visited, path);
if (branchSuccess) {
// We are comming back from the good solution, mark the path
path[nextX][nextY] = step;
}
success = success | branchSuccess;
// Unmark the position for next try
visited[nextX][nextY] = false;
}
}
return success;
}
// Adds some verbose for debugging
private void debug(int step, boolean[][] visited) {
System.out.println("*********************** STEP " + String.valueOf(step) + " ***********************");
for (int i = 0; i < this.SQUARES; ++i) {
for (int j = 0; j < this.SQUARES; ++j) {
if (visited[i][j]) {
System.out.print("X ");
} else {
System.out.print(". ");
}
}
System.out.println("");
}
System.out.println("*******************************************************");
}
// Checks if all squares is used
private boolean checkIfFinished(boolean[][] visited) {
for (int i = 0; i < this.SQUARES; ++i) {
for (int j = 0; j < this.SQUARES; ++j) {
if (!visited[i][j]) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
// Process arguments
int squares = 0;
int x = 0;
int y = 0;
try (Scanner sc = new Scanner(System.in)) {
System.out.print("Number of squares: ");
squares = Integer.parseInt(sc.nextLine());
if (squares < 3) {
throw new Exception("[ERROR] Invalid number of squares");
}
System.out.println("Note: Start values is from 0 -> n-1" + "\n0,0 is at top left side");
System.out.print("X start value: ");
x = Integer.parseInt(sc.nextLine());
if (x < 0 || x > squares - 1) {
throw new Exception("[ERROR] Invalid start x position");
}
System.out.print("Y start value: ");
y = Integer.parseInt(sc.nextLine());
if (y < 0 || y > squares - 1) {
throw new Exception("[ERROR] Invalid start y position");
}
} catch (Exception e) {
// Error occurred, exit
System.err.println("Killing process");
System.exit(1);
}
// Initialize the KnightsTour
KnightsTour kt = new KnightsTour(squares, x, y);
// Make the tour
boolean success = kt.takeTour();
// Post process
if (success) {
System.out.println("The tour was sucessfull!");
} else {
System.out.println("Did not find any way to complete Knights Tour!");
}
int[][] path = kt.getPath();
for (int i = 0; i < path.length; ++i) {
for (int j = 0; j < path[i].length; ++j) {
String stepSTR = (path[i][j] < 10) ? "0" + String.valueOf(path[i][j]) : String.valueOf(path[i][j]);
System.out.print(stepSTR + " ");
}
System.out.println("");
}
}
}
Try this code with size 5 and start position (0,0).
Notice that:
You can enable/disable the debug iteration by commenting the debug call
I compacted the way you perform the moves with 2 arrays to avoid replications but for the sake of clarity you can unroll it again.
On each recursion step, before going depth, we check if we can perform moves, we mark the next position and proceed. On the way back, we unmark the position, check whether the move reached a successfull step or not and reconstruct the good solution if needed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OutOfMemory exception on Exception.ToString()
Below is some logging output from a .NET application.
Error in MainFunction.
Message: Exception of type 'System.OutOfMemoryException' was thrown.
InnerException:
StackTrace: at System.Text.StringBuilder.ToString()
at System.Diagnostics.StackTrace.ToString(TraceFormat traceFormat)
at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Exception.GetStackTrace(Boolean needFileInfo)
at System.Exception.ToString(Boolean needFileLineInfo)
at System.Exception.ToString()
[the rest of the trace is removed]
Which corresponds to the following line of application code. The following is in a catch block, and returns the string to the method that actually throws:
private void MainFunction()
{
...
try
{
string doc = CreateXMLDocument(); // <- Out of Memory throws here
}
catch (Exception ex)
{
CoreLogging("Error in MainFunction.", ex);
}
}
private string CreateXMLDocument()
{
try
{
//Some basic and well constrained XML document creation:
...
}
catch (Exception ex)
{
return "Exception message: " + ex.ToString(); // <- This is the last line of the trace
}
}
What should I make of this? Clearly Exception.Message should be used instead of Exception.ToString(), but I'd still like to understand this. Does
at System.Text.StringBuilder.ToString()
at System.Diagnostics.StackTrace.ToString(TraceFormat traceFormat)
mean that the stack trace of the exception in CreateXMLDocument was so mammoth caused OutOfMemory? I'm curious to see how that would occur as there's definitely no circular calls in CreateXMLDocument, which is the only thing I can think of that could cause an enormous stack trace.
Has anyone else encountered a similar situation?
A:
I little bit of guessing:
1) CLR rises a OutOfMemoryException. 2) You catch this exception and call .ToString on it
3) ToString() tries to allocate memory to the stack trace but... there is no memory and another OutOfMemoryException is rised.
In the comments you said that the XML documents have a few hundreds of kbytes, this could be a/the problem if your server run on 32bits, because of the fragmentation of the LOH.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
kendoAutoComplete shows [object object] when clicked on template or item
This code return the result below in snaps.
How to populate text field with FirstName and LastName when click on template instead of [object object] ?
function forAutoComplete(FieldName){
var autoCompleteUsers = $("#employees").kendoAutoComplete({
minLength: 1,
dataTextField: FieldName,
template: '<div style="border-bottom: 1px solid DARKGRAY; padding:10px 0; clear:both;">' +
'<img style="float:left; margin-right:20px;" width=\"127\" height=\"127\" src=\"<?php echo base_url() ?>/user_uploads/employee_images/${data.Photo}\" alt=\"${data.Photo}\"/>'+
'<div style="display: inline-block;"><p>${ data.FileNo}</p>' +
'<h3>${ data.FirstName } ${ data.LastName }</h3></div>'+
'<div style="clear: both; "></div></div>',
dataSource: {
serverFiltering: true,
transport: {
read: {
type: "GET",
dataType: "json",
contentType:'application/json; charset=utf-8',
url: "<?php echo base_url() ?>index.php/hr_management/manage_hr/search_employee/",
data: function (arg){
return {FieldName : autoCompleteUsers.data("kendoAutoComplete").value()};
}
}
}
},
height: 300,
change: onChangeAutoComplete
});
}
A:
The problem is likely to be related with the value that you set for dataTextField.
Doing some-sort-of-reverse-engineering, I guess that the JSON data that you return is something like:
[
{data: { FileNo: "0001", FirstName: "OnaBai", LastName: "it's me", Photo: "https://si0.twimg.com/profile_images/2648375258/7f7e451f0de1eb467fe35f4f481d7bf7_bigger.jpeg" } },
{data: { FileNo: "0002", FirstName: "Burke", LastName: "Holland", Photo: "https://si0.twimg.com/profile_images/3342899483/51e933d69222ce8ad8cd14e655116959.jpeg" } },
{data: { FileNo: "0003", FirstName: "Todd", LastName: "Anglin", Photo: "https://si0.twimg.com/profile_images/1478082886/todd-anglin-close-up_illustrated.png" } }
]
If so, you should be defining it as data.FirstName.
If you are defining it as:
[
{ FileNo: "0001", FirstName: "OnaBai", LastName: "it's me", Photo: "https://si0.twimg.com/profile_images/2648375258/7f7e451f0de1eb467fe35f4f481d7bf7_bigger.jpeg" },
{ FileNo: "0002", FirstName: "Burke", LastName: "Holland", Photo: "https://si0.twimg.com/profile_images/3342899483/51e933d69222ce8ad8cd14e655116959.jpeg" },
{ FileNo: "0003", FirstName: "Todd", LastName: "Anglin", Photo: "https://si0.twimg.com/profile_images/1478082886/todd-anglin-close-up_illustrated.png" }
]
Then it should be just FirstName.
Example of the first approach in here while second in here
If you define dataTextField: "data", and use the first approach for your JSON then you get the [object Object]. See it here
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get the value between two asterisk in excel?
How to get the value between two asterisk in excel?
for example:
I have these: TXI*GS*346.32*13*SP*ON*3***103634408RT0001
I only want to get the value 346.32
i these data like this for A1:A20 how can i replace them all using VBA?
A:
Sub extractFirstNumber()
Set objRegEx = CreateObject("vbscript.regexp")
' Match numbers of the form 123 or 123.45
objRegEx.Pattern = "\d+(\.\d*)?"
' Iterate over the first 20 rows in first column
For i = 1 To 20
Set objMatch = objRegEx.Execute(Cells(i, 1).Value)
If objMatch.Count = 1 Then
' If there is a match, replace the cell value
Cells(i, 1).Value = objMatch(0)
End If
Next i
End Sub
Edit
Sub extractFirstAndThirdNumber()
Set objRegEx = CreateObject("vbscript.regexp")
' Match numbers of the form 123 or 123.45 between asteriks
objRegEx.Pattern = "\*(\d+(\.\d*)?)"
objRegEx.Global = True
' Iterate over the first 20 rows in first column
For i = 1 To 20
Set objMatch = objRegEx.Execute(Cells(i, 1).Value)
If objMatch.Count >= 2 Then
' If there is a match, replace the cell value
'Cells(i, 1).Value = objMatch(0)
Cells(i, 3).Value = objMatch(0).SubMatches(0)
Cells(i, 4).Value = objMatch(2).SubMatches(0)
End If
Next i
End Sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
R: How to calculate the number of locations nearby a spatial point?
I have a data frame containing a number of projects + their start date + their coordinates(long/lat) and I have a data frame containing a number of (fictional) respondents + the date they were surveyed + their coordinates:
respond_id<- c(1:5)
survey_year<- c(2007, 2005, 2008, 2004, 2005)
lat_1<- c(53.780928, 54.025200, 53.931432, 53.881048, 54.083359)
long_1<- c(9.614991, 9.349862, 9.473498, 10.685581, 10.026894)
project_id<- c(1111:1114)
year_start<- c(2007, 2007, 2006, 2008)
lat_2<- c(54.022881, 54.022881, 53.931753, 53.750523)
long_2<- c(9.381104, 9.381104, 9.505700, 9.666336)
survey<- data.frame(respond_id, survey_year, lat_1, long_1)
projects<- data.frame(project_id, year_start, lat_2, long_2)
Now, I want to create a new variable survey$project_nearby that counts the amount of projects located nearby (here: 5km) the respondents. So the data frame survey should look somewhat like this (other results possible):
> survey
respond_id survey_year lat_1 long_1 projects_nearby
1 1 2007 53.780928 9.614991 0
2 2 2005 54.025200 9.349862 0
3 3 2008 53.931432 9.473498 1
4 4 2004 53.881048 10.685581 0
5 5 2005 54.083359 10.026894 0
Special attention needs to be paid to the start years of the projects and the year the surveys were conducted: If a respondent was asked in 2007, but the project nearby was completed in 2008, this project naturally does not count as project nearby.
I thought of creating a distance matrix and then just counting the number of rows containing a distance smaller than 5km... but I don't know how to create this distance matrix. And maybe a for loop would be easier?
Could anyone help me or give me a hint, what would be the code for doing this?
EDIT: I edited the expected values of survey$projects_nearby. Now these values should match with actual amount of projects located nearby the respective respondents.
A:
You can use the sp package to find the distances, and then just count the number that are nearby. That is,
library(sp)
survey.loc <- matrix(as.numeric(as.character(unlist(survey[, 3:4]))), ncol = 2)
project.loc <- matrix(as.numeric(as.character(unlist(projects[, 3:4]))), ncol = 2)
distances <- spDists(survey.loc, project.loc, longlat = TRUE)
survey$project_nearby <- apply(distances, 1, function(x) sum(x<5))
I hope this helps!
EDIT:
My apologies for not considering the date.
library(sp)
survey.loc <- matrix(as.numeric(as.character(unlist(survey[, 3:4]))), ncol = 2)
project.loc <- matrix(as.numeric(as.character(unlist(projects[, 3:4]))), ncol = 2)
distances <- spDists(survey.loc, project.loc, longlat = TRUE)
year.diff <- sapply(projects$year_start, function(x) survey$survey_year-x)
year.diff <- ifelse(year.diff < 0, Inf, 1)
survey$project_nearby <- apply(year.diff*distances, 1, function(x) sum(x<5))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add author images to blog articles on a Voog site?
I have a blog on my Voog website (http://voog.com). It’s currently in construction but we’re adding some content before launching it, and I need to add images to the authors. Until now, I’ve been the only one posting the articles and I managed to hardcode my image next to my name and timestamp:
<img class="author-image" src="{{ images_path }}/my-profile-image.jpg">
But now we have multiple people posting the articles and I need a better solution. Can I build this solution on elements? How?
A:
A workaround can be like this:
title - author's name
image - author's image
email - author's e-mail
For example:
<img src="/photos/{{ article.author.firstname }}.jpg">
or a more advanced example:
<img src="/photos/{{ article.author.firstname }}{{ article.author.lastname }}.jpg">
All you need to do is update the first and last name on the editor's profile (https://youtu.be/-RXnoyrsXU0), upload the image to your files menu with the correct name and the system will recognize it.
If this is not the exact solution you're looking for, then yes, it's possible to create an element-based system but this requires site-specific examples and needs to be built on multiple pages. Do get in contact with Voog for this solution!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use keras for binary classification?
I need simple example about how to use keras model. It is not clear for me what difference between model.evaluate and model.predict.
I want to create model for binary classification. Lets say I have images of cats and dogs, train model and can use it to predict which animal on given photo. Maybe there is some good into or tutorials. I read anything in first five pages in google, but found only complex level tutorials and discussions.
A:
To make things short:
model.evaluate evaluates a pair (X,Y) and returns the loss (and all other metrics configured for the model). This is for testing your model on a vaildation or test set.
model.predict predicts the outcome given an input X. This if for predicting the class from an input image for example.
This, among other things, is also clearly documented in the linked documentation.
You can find a lot of example models for Keras in the git repository (keras/examples) or on the Keras website (here and here).
For binary classification you could use this model for example:
model = Sequential()
model.add(Dense(300, init='uniform'))
model.add(Activation('relu'))
model.add(Dense(2, init='uniform'))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.02))
model.fit(X, Y)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Set collection preserving insertion order
I need a collection that behaves as Set and preserves order of element insertion.
Is there one or I'll have to implement it myself?
What would the best implementation be?
A:
It doesn't exist in .NET, but you can emulate it using a List and the Distinct LINQ extension method, which should preserve the order of the underlying List.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Commercial vs Open source CMS and load balancing
I need an open source alternative to something like Sitefinity where load balancing is vitally important for a client's site.
Upon doing a quick Google search it looks like Joomla is able to handle load balancing but I also wanted to find out if anyone else knows of a rock solid open source CMS capable of handling high traffic in a load balanced scenario.
Many thanks!
A:
For scaling CMS sites, it's often a case of compatibility with 3rd party tools.
My recent experience has been with Drupal, but the tools are the same for other *AMP based tools (ie. PHP/Apache/MySQL based), like most open source CMS's are.
The real key thing to determine for you will be the compatibility of each CMS with these standard tools for getting the scalability happening. That is almost more important than the specific scalability features of the CMS itself, which are pretty much the same in most modern CMS's (aggressive caching and so on).
The typical pieces of the puzzle for Linux are the following. You should evaluate which of these pieces matter to you and which will work with the CMS you choose.
Varnish: This HTTP reverse proxy will sit in front of your main webserver and efficiently serve up anonymous page requests where it can. If you have a site with lots of anonymous (not logged in) traffic, then Varnish will pretty much give you the same performance you'd get if your site was static HTML pages. The catch: Your CMS must cooperate with Varnish, either through an add-on module or direct knowledge of how to behave behind one of these proxies. Anonymous pages must be served up without any unique cookies on them, or Varnish cannot do its thing.
Memcached: This in-memory object cache is used as an alternative to cache tables in your SQL database. As we all know, memory access is 1000 times faster than disk access, so it stands to reason that if you keep these cached bits in memory, instead of having to use the database and spin the disks to run queries.. that your site will be very fast. It also stands to reason you need enough RAM to hold extra copies of stuff in memory.
Caching in the CMS: All modern CMS's try do to this as well as they can, it's the key to performance. The achilles heel of all modern CMS's is that you can't really cache logged in data very well (ie. a dashboard that has different stuff to say for each user). So if your users are all logged in, say for a community site or something, then neither this nor the two items above is going to help all that much.
CDN: When CMS people throw around "use a CDN" they mean a couple things. One is what it sounds like, host stuff like static files on a content delivery network provided by Google or Amazon or someone, and things will load faster. But the other thing it means is to set up multiple parallel DNS names to load content off. Your browser will load 6 things at once max from a single domain. If you make: a.example.com, b.example.com, c.example.com, d.example.com, e.example.com, and then if your CMS supports this CDN technique, then a browser could download 30 things at once instead of 6 - it could grab 6 items (.css files, .js files, images, whatever) off each of a., b., c., d., and e.example.com. This speeds sites up, but again your CMS has to support it (built-in or through some kind of add on module)
Database replication? This is always prickly if you are talking about doing it in MySQL. Regardless of database, replication is a tough problem to solve, especially if it has to be 2-way replication (each side has to read and write). If you do everything above perfectly, and buy the best hardware you can, and stick the database on its own high performance server with no other services on it, and a nice fast raid-10 array say with 6 disks to get yourself really awesome disk performance........ then you could probably go a long way with a single master database. (it would definitely be a wise idea to replicate to a backup machine if you had all your eggs in one basket like that). Anyway, by this point you are in standard database replication land... Your CMS might support having multiple database entries, but it's largely more a question of "how do you cluster" rather than "what CMS are you clustering". I'd be surprised if any of the modern alternatives wouldn't allow you to set more than one database hostname for clustering, and you could always do it in DNS by round-robin'ing the hostname of your DNS server. Again though, not related to your choice of CMS really.
And to end this all of, and to answer your question, I of course recommend Drupal as a rock solid scalable CMS. Is it easy to scale it so it runs a site like examiner.com or whitehouse.gov or a university site with hundreds if not thousands of sub sites and millions of nodes? Heck no! Nor will that challenge be easy in any CMS you choose.. but you should also be able to choose any modern popular CMS and make it work fast, if you address all of the above.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can PHP 5.5.5 load Phar files from OPcache?
The version of PHP in use is 5.5.5 and I know this version of PHP can store precompiled script bytecode in shared memory, as mentioned in the following page:
http://php.net/manual/en/intro.opcache.php
I also know OPcache can compile files as mentioned in the following page:
http://php.net/manual/en/function.opcache-compile-file.php
Which would be great if this worked with Phar files. However, I can't tell whether PHP is loading my Phar files from bytecode in shared memory or not. I can't use the opcache_is_script_cached function to test because this is not available in PHP 5.5.5, the function is only available in PHP 5.6 and newer.
Could someone please clarify if this works or not, or at least explain to me how I can find out?
A:
Yes it does. I won't go through the whole thing, but there is logic in ext/opcache/ZendAccelerator.c
|
{
"pile_set_name": "StackExchange"
}
|
Q:
FindByIdentity failing with PricipalOperationException in ASP.NET webapp
I'm struggling with an issue in utilizing System.DirectoryServices.AccountManagement in my internal web application. The error is not very descriptive, but here's what's going on:
When I attempt to validate that a provided user id exists in the AD, I do so with the following code:
private bool IsWindowsIDValid(string strWindowsID)
{
var context = new PrincipalContext(ContextType.Domain, "DOMAINSERVER", "DC=DOMAINNAME,DC=net");
var userPrincipal = UserPrincipal.FindByIdentity(context, strWindowsID);
return (userPrincipal != null);
}
However, an exception is throw at the second line, where FindByIdentity is called. Here are the exception details:
Message:
"An operations error occurred."
Stack trace:
at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInit()
at System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit()
at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize()
at System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx()
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate)
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, String identityValue)
at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue)
at *****.IsWindowsIDValid(String strWindowsID) in *****.ascx.cs:line 193
This same error occurs if I attempt to examine the ConnectedServer property of the PrincipalContext as well. However, I can attempt to validate credentials against the context (using context.ValidateCredentials()), and it will pass just fine.
Any ideas as to what may be going on? I can run this code just fine in a stand alone console script on my machine - this is occurring in my local development environment, inside VisualStudio, when I attempt to debug the webapp. Is this a permissions issue or something else perhaps? I'm pretty lost at this point.
I appreciate any help!
-Patrick
A:
An old question, but I had this same error. For me, the problem is that PrincipalContext doesn't work without a username and password in its constructor... I get the exact same error message whenever I call any method or property of the UserPrincipal (or on the PrincipalContext for that matter).
If you specify a username and password of a domain user with Active Directory permissions to the container you're specifying, the call to FindByIdentity should succeed:
var context = new PrincipalContext(ContextType.Domain, "DOMAINSERVER",
"DC=DOMAINNAME,DC=net", userName, pw);
var userPrincipal = UserPrincipal.FindByIdentity(context, strWindowsID);
For me, this isn't a solution, because I won't have those two parameters. But that's why you're getting the error you're getting.
According to Microsoft's help, doing it your way should run under the credentials of the calling process... but no matter who I'm running under (and I've verified the impersonation) calls to a UserPrincipal object without specifying a username and pw on its PrincipalContext just won't work.
Hope that belatedly helps,
James
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NativeScript ANDROID_HOME missing
When I run tns run android or tns doctor I get an error that the ANDROID_HOME environment variable is not set. Yet it's clearly set. Mac OSX Sierra 10.12.3.
bash-3.2$ tns run android
The ANDROID_HOME environment variable is not set or it points to a non-existent directory. You will not be able to perform any build-related operations for Android.
bash-3.2$ $ANDROID_HOME
bash: /Users/rlangton/Library/Android/sdk: is a directory
bash-3.2$
A:
If you're using bash then you need to update the ~/.bash_profile file.
In my case, I'm using ZSH so I needed to edit ~/.zshrc file.
nano ~/.zshrc
Add the export line below:
if [ -f /Users/{myusername}/.tnsrc ]; then
source /Users/{myusername}/.tnsrc
export ANDROID_HOME=/Users/{myusername}/Library/Android/sdk
fi
Ctrl + O to save, Ctrl + Z to exit. Restart the terminal. Now echo $ANDROID_HOME shows the correct path every time.
A:
Open/create .profile like this
vim ~/.profile
add the following lines to the end of the .profile file.
export ANDROID_HOME=${HOME}/Library/Android/sdk
load the profile using the command
source ~/.profile
You should have it working I guess. This is what I did to get this configured.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
object is not saved in array
I have the following code that parses json into custom objects, parsing works fine i have a problem with saving the objects.
-(void)handleCities:(NSNotification *)notification
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"_getInitialData" object:nil];
if(![notification object])
{
NSLog(@"Something went wrong");
return;
}
// Convert data to a dictionary
NSMutableDictionary * data = [NSJSONSerialization JSONObjectWithData:(NSMutableData *) [notification object] options:NSJSONReadingMutableContainers error:nil];
// Loop over all the data
if([data objectForKey:@"data"] != (id)kCFBooleanFalse)
{
for(int i = 0; i < [[[data objectForKey:@"data"] objectForKey:@"cities"] count]; i++)
{
CityObject * object = [[CityObject alloc] init];
// Loop over all the properties
for(NSString * key in [[[data objectForKey:@"data"] objectForKey:@"cities" ] objectAtIndex:i])
{
NSString * _key = key;
if([object._remap objectForKey:key])
{
NSString * value = [object._remap objectForKey:_key];
NSLog(@"Notice [%@] Remapping \"%@\" to \"%@\"", self.class, _key, value);
_key = value;
}
// Save the value for easy access
NSString * value = [[[[data objectForKey:@"data"] objectForKey:@"cities" ] objectAtIndex:i] objectForKey:_key];
// Does the value have a value
if((id)value == [NSNull null])
{
value = @"";
}
// Set the value for key
[object setValue:value forKey:_key];
}
NSMutableDictionary * set = [[[data objectForKey:@"data"] objectForKey:@"cities"] objectAtIndex:i];
int count = (int)[[set objectForKey:@"categories"] count];
for(int b = 0; b < count; b++)
{
CategoryObject * category = [[CategoryObject alloc] init];
for(NSString * key in [[set objectForKey:@"categories"] objectAtIndex:b])
{
NSString * value = [[[set objectForKey:@"categories"] objectAtIndex:b] objectForKey:key];
if((id)value == [NSNull null])
{
value = @"";
}
[category setValue:value forKey:key];
}
NSLog(@"Category %@",category.class);
NSLog(@"Object : %@",object.class);
NSLog(@"Object Categories : %@",object.categories.class);
// i can print the category object fine here
[object.categories addObject:(CategoryObject *)category];
}
[self.cities addObject:object];
}
}
CityObject * city = [self.cities objectAtIndex:0];
CategoryObject * category = [city.categories objectAtIndex:0];
NSLog(@"Category Name : %@", category.name);
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"_getInitialData" object:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"getInitialData" object:nil];
}
CityObject.h
#import <Foundation/Foundation.h>
#import "Object.h"
@interface CityObject : Object
@property (nonatomic, strong) NSString * name;
@property (nonatomic, strong) NSString * id;
@property (nonatomic, strong) NSString * state;
@property (nonatomic, strong) NSString * image;
@property (nonatomic, strong) NSString * term_order;
@property (nonatomic, strong) NSMutableArray * categories;
@property (nonatomic, strong) NSMutableDictionary * _remap;
@end
CityObject.m
#import "CityObject.h"
@implementation CityObject
-(id)init
{
if(self = [super init])
{
self._remap = [[NSMutableDictionary alloc] init];
self.categories = [[NSMutableArray alloc] init];
[self._remap setObject:@"state" forKey:@"new_city"];
}
return self;
}
@end
CategoryObject.h
#import <Foundation/Foundation.h>
#import "Object.h"
@interface CategoryObject : Object
@property (nonatomic, strong) NSString * name;
@property (nonatomic, strong) NSString * icon;
@property (nonatomic, strong) NSString * id;
@end
Before i add the CategoryObject to my array i can retrieve the values without a problem it is when i NSLog at the end i cannot get the values / objects out of the array's.
What am i doing wrong since it works great when i add the CityObjects but not when i "parse" the categories. I can read them fine before i add them to the object.categories
Error / Output
-[__NSDictionaryM name]: unrecognized selector sent to instance 0x7a482760
2015-03-24 09:21:05.649 10things[16968:337325] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryM name]: unrecognized selector sent to instance 0x7a482760'
A:
Problem solved, i did not have a strong pointer to the model, the Dictionary was magically being replaced to a NSMutableDictionary Once i had a strong handle everything worked properly. (thanks for the code feedback)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cocoon fields are not affected by JS
I'm using cocoon to create quotes for my users. A Quote has_many Expense Categories, and each Expense Category has many Expenses
I added some JS, so that everytime my user changes the value of an expense, it updates the total price in another input, but this doesn't work with the newly created inputs.
I made sure they all had the same classes (.expense .price-input)
I tried with this little piece of code:
$('.expense .price-input').keyup(function () {
alert('OK');
});
When I type something in the existing inputs, OK is displayed. When I create an expense, typing something in the newly created input won't trigger it. Is there something to initialize?
A:
Events are bound to the fields during the initial page loading, which means dynamically added fields won't be bound.
You can however add such an event binding to a parent that exists when the page is loaded, such as document, and pass the selector as an argument to the function.
$(document).on('keyup', '.expense .price-input', function(){
alert('OK');
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rewriting WITH statements into subquery statements in SQL?
I have the following two relations:
Game(id, name, year)
Devs(pid, gid, role)
Where Game.id is a primary key, and where Devs.gid is a foreign key to Game.id.
In a previous post I made here, another user was kind enough to help me out in creating a query that finds all games made with the most developers making that game. His answer used a WITH statement, and I am not very familiar with these as I'm only a few weeks into learning SQL. Here's the working query:
WITH GamesDevs (GameName, DevsCount)
AS
(
SELECT Game.name AS GameName, count(DISTINCT Devs.pid) AS DevsCount
FROM Game, Devs
WHERE Devs.gid=Game.id
GROUP BY Devs.gid, Game.name
)
SELECT * FROM GamesDevs WHERE GamesDevs.DevsCount = (SELECT MAX(DevsCount) FROM GamesDevs)
For the sole purpose of getting more familiar with SQL, I am trying to rewrite this query using a subquery instead of a WITH statement. I've been using this Oracle documentation to help me figure it out. I tried rewriting the query like this:
SELECT *
FROM (SELECT Game.name AS GameName, count(DISTINCT Devs.pid) AS DevsCount
FROM Game, Devs
WHERE Devs.gid=Game.id
GROUP BY Devs.gid, Game.name) GamesDevs
WHERE GamesDevs.DevsCount = (SELECT MAX(DevsCount) FROM GamesDevs)
As far as I can tell, these two queries should be identical. However, when I try running the second query, I get the error
Msg 207, Level 16, State 1, Line 6 Invalid column name 'DevsCount'.
Does anyone know why I might be getting this error, or why these two queries wouldn't be identical?
A:
You will need to duplicate that subquery in last from clause like:
SELECT *
FROM (SELECT Game.name AS GameName, count(DISTINCT Devs.pid) AS DevsCount
FROM Game, Devs
WHERE Devs.gid=Game.id
GROUP BY Devs.gid, Game.name) GamesDevs
WHERE GamesDevs.DevsCount = (SELECT MAX(DevsCount) FROM (SELECT Game.name AS GameName, count(DISTINCT Devs.pid) AS DevsCount
FROM Game
INNER JOIN Devs ON Devs.gid=Game.id
GROUP BY Devs.gid, Game.name))
But better do it like:
SELECT TOP 1 WITH TIES Game.name AS GameName, count(DISTINCT Devs.pid) AS DevsCount
FROM Game
INNER JOIN Devs ON Devs.gid=Game.id
GROUP BY Devs.gid, Game.name
ORDER BY DevsCount DESC
|
{
"pile_set_name": "StackExchange"
}
|
Q:
check answer and remove UIButton (Objective-C)
I have a series of questions and answers that it's loads randomly,each question have 3 choice, in one of my question I have just true and false,
my questions is how can I set my if statement, That if my answer is true or false don't show the last buttons,
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSString *qOne = @"Question 1";
NSString *qTwo = @"Question 2";
NSString *qThree = @"Question 3";
NSString *qFour = @"Question 4";
NSString *answerOne = @"Après le souper";
NSString *answerTwo = @"1";
NSString *answerThree = @" Holstein";
NSString *answerFour = @" yes";
NSString *answer2One = @"Après un exercice physique";
NSString *answer2Two = @" 2";
NSString *answer2Three = @" Jersey";
NSString *answer2Four = @" No";
NSString *answer3One = @"Avant un exercice physique";
NSString *answer3Two = @" 4";
NSString *answer3Three = @" Canadienne";
I want to remove this part
NSString *answer3Four = @" ";
NSString *correctOne = @"Après un exercice physique";
NSString *correctTwo = @" 4";
NSString *correctThree = @" Yes";
NSString *correctFour = @" 14";
answerComments = [[NSArray alloc] initWithObjects: answerOne, answerTwo, answerThree, answerFour, nil];
answer2Comments = [[NSArray alloc] initWithObjects: answer2One, answer2Two, answer2Three, answer2Four, nil];
answer3Comments = [[NSArray alloc] initWithObjects: answer3One, answer3Two, answer3Three, answer3Four,nil];
qComments = [[NSArray alloc] initWithObjects:qOne, qTwo, qThree, qFour, nil];
correctComments = [[NSArray alloc] initWithObjects: correctOne, correctTwo, correctThree, correctFour, nil];
// A random string is selected and assigned to artist.
int rand = arc4random()%4;
NSString *artist = [qComments objectAtIndex:rand];
firstAnswer = [answerComments objectAtIndex:rand];
secondAnswer = [answer2Comments objectAtIndex:rand];
threeAnswer = [answer3Comments objectAtIndex:rand];
correct = [correctComments objectAtIndex:rand];
NSLog (@"%@",correct);
// Here's the problematic code:
[question setText:(artist)];
[question setFont:[UIFont fontWithName:@"HelveticaRoundedLTStd-Bd" size:42]];
question.adjustsFontSizeToFitWidth = NO;
question.numberOfLines = 0;
[test setTitle:(firstAnswer) forState:UIControlStateNormal];
[test setBackgroundImage:[UIImage imageNamed:@"activeBtn.png"] forState:UIControlStateHighlighted];
[ansONE setTitle:(secondAnswer) forState:UIControlStateNormal];
[ansONE setBackgroundImage:[UIImage imageNamed:@"activeBtn.png"] forState:UIControlStateHighlighted];
ansTWO = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[ansTWO addTarget:self
action:@selector(ansTWO:)
forControlEvents:UIControlEventTouchDown];
[ansTWO setTitle:(threeAnswer) forState:UIControlStateNormal];
[ansTWO setBackgroundImage:[UIImage imageNamed:@"activeBtn.png"] forState:UIControlStateHighlighted];
ansTWO.titleLabel.font = [UIFont fontWithName:@"HelveticaRoundedLTStd-Bd" size:24];
[ansTWO setTitleColor:[UIColor colorWithRed:21/255.0 green:119/255.0 blue:183/255.0 alpha:.77] forState:UIControlStateNormal];
ansTWO.titleLabel.textAlignment = UITextAlignmentCenter;
[ansTWO setTag:2];
UIImage *buttonImage = [UIImage imageNamed:@"quizBtn.png"];
[ansTWO setBackgroundImage:buttonImage forState:UIControlStateNormal];
ansTWO.frame = CGRectMake(243, 586,549, 56);
[self.view addSubview:ansTWO];
}
A:
Assuming that you know how to interpret the answer to be TRUE or FALSE you can have some if statement like this:
//1st Option
if(answer){
button.hidden = YES;
//hide or unhide other buttons
}
//2 Option
if(answer){
[button removeFromSuperView];
//add or remove other buttons
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Automatically open new query in adjacent window
When I open a new query (File > New > Query with Current Connection) it opens in the same window as the Object Explorer. I have to then drag it over to put it in a window next to the Object Explorer..
How do I get it to automagically get it to open the window next to the Object Explorer?
A:
It's not the editor that's wrong, but the Object Explorer. i.e. Your object explorer is in the main pane rather than the side pane.
Click and drag the object explorer pane to the left docking point.
After this it should remain to the left of any query windows which you open (always in the main pane).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
UItableView reloadData does not set the cell display properties properly
I have a table view, and I am reloading its contents dynamically, for reloading the table contents I am using the following code:
[agendaTable reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
This works fine, but the problem is I am setting the alpha properties of the table cells in the following manner:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if([cell isKindOfClass:[AgendaItemBlank class]])
cell.backgroundColor = [UIColor clearColor];
else if([cell isKindOfClass:[AgendaItem class]])
{
cell.backgroundColor = [UIColor whiteColor];
[cell setAlpha:0.82];
//set the corner radius so that there is a rounded effect
[cell.layer setBorderWidth:0.5];
[cell.layer setCornerRadius:9.0];
[cell.layer setBorderColor:[UIColor redColor].CGColor];
[cell.layer setMasksToBounds:YES];
//set a different color for the selected background
UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor redColor]];
[bgColorView.layer setCornerRadius:9.0];
[cell setSelectedBackgroundView:bgColorView];
[bgColorView release];
}
}
The combination of these lead to the fact that after the reload, the table cells initially become opaque, all the properties take effect but not the alpha property.
The cells regain their alpha property when they are scrolled up and down (basically when they are redrawn).
I have also tried setting the alpha within - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath, but that does not have any effect.
A:
try
[cell setBackgroundColor:[UIColor colorWithRed:1 green:0 blue:0 alpha:0.82]];
[cell.textLabel setBackgroundColor:[UIColor clearColor]];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A Catholic uncertain of the trinity
I struggle with my church's (Catholic Church's) teaching of the Trinity. I have no doubt that Jesus is the Son of God sent to bring us to the Father and to atone for the sin that separates us from the Father. But I am uncertain that Jesus is God, and in fact tend to believe he's not. I love him and revere him and believe he sits at the right hand of the Father, but have troubles with things he said that would suggest he isn't God:
I'll give just one or two from the RSVCE:
Mark 10, 17-18: 17 And as he was setting out on his journey, a man ran up and knelt before him, and asked him, “Good Teacher, what must I do to inherit eternal life?” 18 And Jesus said to him, “Why do you call me good? No one is good but God alone.
John 20, 16-17: 16 Jesus said to her, “Mary.” She turned and said to him in Hebrew, “Rab-bo′ni!” (which means Teacher). 17 Jesus said to her, “Do not hold me, for I have not yet ascended to the Father; but go to my brethren and say to them, I am ascending to my Father and your Father, to my God and your God.”
Now I know the first chapter of John "In the beginning was the word, and the word was with God and the word was God...the word became flesh and dwelt among us..."
But here's my thing, the last Gospel (John 1) says that the "word was in the world, and the world was made by him, and the world knew him not" before speaking of the word becoming flesh. This seems to me to be presenting scripture as the Word too. The Old Testament, as the Word, was an account of God's divine plan through which all was created. And so I believe that Jesus, as the incarnation of the word, is God in the sense that scripture is God, and not in a literal sense. I have to reconcile the last Gospel and Jesus' constant assertions that place the Father above himself "the father is greater than I" and the quotes I provided (Trinitarian teaching is that the "three persons of God are co-equal). I can only reconcile the Last Gospel with Jesus' words if I come to the conclusion that the Messiah is the Son of God, and brings God to the world, as scripture does, but is not literally YHWH. Can you help me understand how Jesus' words reconcile with a belief in the Trinity?
A:
Orthodox explanations of this apparant paradox centre on drawing a subtle distinction between the attributes manifested by the incarnated Christ versus the inherant attributes of the glorified eternal Son of God. According to the creeds, they are one and the same person - there is no distinction in their essential nature - however, the scriptures tell us:
5 Have this mind among yourselves, which was in Christ Jesus, 6 who, though he was in the form of God, did not count equality with God a thing to be grasped, 7 but emptied himself, taking the form of a servant, being born in the likeness of men. 8 And being found in human form he humbled himself and became obedient unto death, even death on a cross. - Philippians 2:5-8 RSVCE
The key to the dilemma is the nature of this emptying process: We need to understand that during the incarnation there was a voluntary limitation by the Son, in order that he be
...not a high priest who is unable to sympathize with our weaknesses, but one who in every respect has been tempted as we are, yet without sinning. - Hebrews 4:15 RSVCE
This doesn't mean that he stopped being God in terms of the essence of his nature, but he did voluntarily limit the expression of His divine attributes in order to fully identify with humanity and to suffer and die as the lamb of God who takes away the sin of the world. A direct example of His mindset to refuse the exercise of his power is seen in:
"53 Do you think that I cannot appeal to my Father, and he will at once send me more than twelve legions of angels? 54 But how then should the scriptures be fulfilled, that it must be so?” - Matthew 26:53-54 RSVCE
(cf. also Matthew 4:3-4 & John 2:3-4) One of the consequences of this is that Jesus could say in truth "the father is greater than I" during his incarnation; however the Philippians passage goes on to say:
9 Therefore God has highly exalted him and bestowed on him the name which is above every name, 10 that at the name of Jesus every knee should bow, in heaven and on earth and under the earth, 11 and every tongue confess that Jesus Christ is Lord, to the glory of God the Father. - Philippians 2:9-11 RSVCE
Which very much brings us back to the co-equality of the Persons of the Trinity.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In block-diagonal computation of the determinant, do the block sizes need to be equal?
For a block-diagonal matrix with, for simplicity, blocks of sizes 4,3,2, I would like to claim that the determinant of this matrix is just the det(4x4 block)*det(3x3 block)*det(2x2 block), basically thinking of the blocks as scalars instead. Is this claim true?
Perhaps it is not true, because the result, det(AB) = det(A)det(B), would force the block sizes to be equal.
But, I wonder whether there is a more general result that does not force the blocks sizes to be equal.
Thanks,
A:
We want to show that
$$\det\pmatrix{A&0&0\\0&B&0\\0&0&C}\; = \det(A)det(B)\det(C)$$
where $A,B,C$ are square matrices but of not necessarily the same dimensions.
We can use the result in Block Matrix Determinant to proof the result "inductively". There it is shown that
$$\det\pmatrix{A&0\\0&D}\; = \det(A)det(D)$$
We can fit this problem into that one by letting
$$D = \pmatrix{B&0\\0&C}$$
But also by that problem
$$\det\pmatrix{B&0\\0&C}\; = \det(B)det(C)$$
So $$\det\pmatrix{A&0&0\\0&B&0\\0&0&C}\; = \det(A)det(D) = \det(A)\det(B)\det(C)$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
FLEX, Actionscript: how can I invoke a CustomEvent?
I've created a custom MouseEvent in Flex:
package {
import flash.events.MouseEvent;
public class CustomMouseEvent extends MouseEvent {
public var tags:Array = new Array();
public function CustomMouseEvent(type:String, tags:Array) {
super(type, true);
this.tags = tags;
}
}
}
Now I would like to understand how to pass the parameter tags from both Actionscript and MXML:
From actionscript I'm trying something like this, but it doesn't work:
newTag.addEventListener(MouseEvent.MOUSE_UP, dispatchEvent(new CustomMouseEvent(MouseEvent.MOUSE_UP,[newTag.name])));
From MXML i'm doing this and it doesn't work as well:
<mx:LinkButton click="dispatchEvent(new CustomMouseEvent(MouseEvent.MOUSE_UP, bookmarksRepeater.currentItem.tags))" />
thanks
A:
Try wrapping the callback code in a function:
newTag.addEventListener(MouseEvent.MOUSE_UP, function(e:MouseEvent):void {
dispatchEvent(new CustomMouseEvent(MouseEvent.MOUSE_UP, [e.currentTarget.name]));
});
I think the issue with the MXML code is that you are using a repeater and trying to get the currentItem after the repeating has finished. Try this instead:
<mx:LinkButton click="dispatchEvent(new CustomMouseEvent(MouseEvent.MOUSE_UP, event.currentTarget.getRepeaterItem().tags))" />
Hope that helps.
Update
Since you are creating the newTag object in a loop, you'll get better memory usage by just using a named function as the event listener.
newTag.addEventListener(MouseEvent.MOUSE_UP, onTagClick);
...
protected function onTagClick(e:MouseEvent):void {
dispatchEvent(new CustomMouseEvent(MouseEvent.MOUSE_UP, [e.currentTarget.name]));
}
That way you only create one event listener, rather than n listeners that do that exact same thing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ask user to change their password after their password expires, but not during their session
Currently, the logic for my application is that, when the user's password expires after for example, 30 days, a user will be redirected to the Change Password screen even if they were in the middle of doing something. This is wrong. The user should only be prompted to change their password on the next login.
I have created a CheckAfterLoginFilter which extends OncePerRequestFilter where the logic resides. However, this is filtered on EVERY request so that user logs out in mid session. I am not sure how I can implement the desired logic in here if it's even possible.
My login form jsp uses j_security_check. My first thought was to move the logic from CheckAfterLoginFilter into the LoginController but j_security_check seems to redirect to it's own thing which I have no idea about or where to find.
Some help would be much appreciated!
Thanks
A:
As you are using Spring Security, I'd assume you have already configured authenticationManager, and your UserEntity implements UserDetails.
My suggestion would be to provide custom authentication failure handler and override isCredentialsNonExpired() in your UserEntity.
Here is an example (with java based configurations).
Custom authentication failure provider
@Bean
public AuthenticationFailureHandler customAuthenticationFailureHandler() {
ExceptionMappingAuthenticationFailureHandler exceptionMappingAuthenticationFailureHandler =
new ExceptionMappingAuthenticationFailureHandler();
Map<Object, Object> map = new HashMap<>();
map.put(
"org.springframework.security.authentication.CredentialsExpiredException",
"/resetPassword.html"
);
exceptionMappingAuthenticationFailureHandler.setExceptionMappings(map);
exceptionMappingAuthenticationFailureHandler.setRedirectStrategy(
new RedirectStrategy() {
@Override
public void sendRedirect(
HttpServletRequest request, HttpServletResponse response, String url
) throws IOException {
response.sendRedirect(request.getContextPath() + url);
}
}
);
return exceptionMappingAuthenticationFailureHandler;
}
XML way
<bean id="customAuthenticationFailureHandler" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.security.authentication.CredentialsExpiredException">/change_password_page</prop>
</props>
</property>
<property name="defaultFailureUrl" value="/resetPassword"/>
</bean>
and in your security.xml
<security:form-login ... authentication-failure-handler-ref="customAuthenticationFailureHandler">
And finally in your UserEntity
@Override
public boolean isCredentialsNonExpired() {
if (// check password is expired or not) {
return false;
}
return true;
}
So when password expires, failure handler will redirect to your desired page.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Accessing data from an API response is iOS app
I have this iOS app I am working on and when I make a call to the API, I get this kind of data set back:
{
"finished_on" = 1414499584;
id = 4370760;
ip = "1.1.1.1";
mode = 1;
name = asdasdasdasd1;
remaining = 420;
score = 0;
"simulation_block" = 0;
"simulation_id" = 0;
"simulation_type" = 0;
"started_on" = 1414499583;
status = "-1";
step = 1;
total = 5;
}
The API call uses this:
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:req];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
And the response is coming from [responseObject description].
This all works and works everywhere else in my app. No problem there. Just confused on how I can work with this data for some reason.
Can anyone tell me how I can access parts of this data? For example, I'm wanting to pull out the "name". When I inspect the data in XCode, it's telling me it is a NSObject. And I've tried converting that down to a JSON string and other ways, but I'm having no luck.
A:
You're using the description directive, which outputs an NSString representation of the data contained by that object. You need to access the actual contents of the object returned into responseObject with something akin to:
responseObject[@"name"];
... but the implementation depends on exactly how AFNetworking is returning your responseObject.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to show a Tab if mouse pointer axis in a particular location using jQuery?
I have an anchor tag
<li><a href="#inline_content1" class="inline1" ></a></li>
and dynamically insert to two <p> tags into the anchor tag
<p>Tab1</p>
and
<p> Tab2</p>
Now code shows following:
<li>
<a href="#inline_content1" class="inline1" >
<p>Tab1</p>
<p> Tab2</p>
</a>
</li>
If the user clicks on the anchor tag, there is shows a popup. That popup has two tabs, I want to show the Tab1 on the popup if somebody click on the <p>Tab1</p> and vice versa.
$('.toggle_social_media ul li a').click(function (e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
});
if ((x < 399) && (x > 400)) {
$('#tab2').show();
}
else {
$('#tab1').show();
}
I used mouse pointer click event to find the axis of the <p> tags but unfortunately its not working. Can anybody help me.
Thanks
A:
You can use the target which is clicked and specify the tabs with a data-attribute:
jQuery
$('.toggle_social_media ul li a').click(function (e) {
e.preventDefault();
var rel = $(e.target).data('rel');
$('#' + rel).show();
});
Or if you can't change the html-markup you can use
var text = $(e.target).text();
var rel = text.toLowerCase();
for referencing the tab instead.
HTML
<div class="toggle_social_media">
<ul>
<li>
<a href="#inline_content1" class="inline1">
<p data-rel="tab1">Tab1</p>
<p data-rel="tab2"> Tab2</p>
</a>
</li>
</ul>
</div>
Demo
Reference
.target
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java : Using Javamail to read email
I've been working on a program, that's suppose to use javamail, to read through an inbox, and if an email contains a specific String, it should be opened.
First off, this is my first time trying to use this javamail api - I'm pretty sure that my properties are all messed up - Can anyone give me at tip on correctly setting up properties for javamail?
Secondly, it seems like i can connect via the API, but if I try to search for subjects AND the subject is null, I get a null pointer exception - If I however don't try to match the subject with "Ordretest", I get no nullpointer - Any tips would be a great help :)
package vildereMail;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.search.FromTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
public class vildereMail {
public boolean match(Message message) {
try {
if (message.getSubject().contains("Ordretest")) {
System.out.println("match found");
return true;
}
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
};
public static void main(String[] args) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
props.put("mail.imap-mail.outlook.com.ssl.enable", "true");
props.put("mail.pop3.host", "outlook.com");
props.put("mail.pop3.port", "995");
props.put("mail.pop3.starttls.enable", "true");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap-mail.outlook.com", "[email protected]", "MyPassword");
session.setDebug(true);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
SearchTerm sender = new FromTerm(new InternetAddress("[email protected]"));
Message[] messages = inbox.search(sender);
System.out.println(messages);
for (int i = 0 ; i < messages.length ; i++) {
System.out.println(messages[i].getSubject());
if (messages[i].getSubject().equals(null)) {
System.out.println("null in subject");
break;
}
else if (messages[i].getSubject().contains("Ordretest")){
System.out.println("1 match found");
}
else {
System.out.println("no match");
}
}
System.out.println("no more messages");
store.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}
}
A:
Without knowing on which line you get the NPE (Null Pointer Exception) I guess it occurs here:
if (messages[i].getSubject().equals(null))
If getSubject() returns null and you try to do .equals() it will throw a NPE (because you try to invoke a method).
So try to rewrite it to (assuming your message object can't be null):
if (messages[i].getSubject() == null)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to get java codes after using react native bulid a complete app?
In react native android JS code will be translated to java code, so can
I have some way to get this code?I searched android's fold, but can not find. Can u give me some advises?
A:
That is not how react native works. Your javascript code is not compiled or translated to java or ObjectiveC/Swift. It stays as javascript itself.
All of your javascript code, written in many files, gets minified and bundled into one single javascript file. Usually this file is main.jsbundle. This javascript code then runs on a separate thread in the device, and it sends messages to a native thread to create Views and other components on the native side.
This communication between native and javascript side happens through the react native bridge. Also, it is the bridge that delegates all the user interactions to the javascript side so that your business logic can handle them.
tldr: Javascript code does not get compiled to java, but stays as javascript itself.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Choose between `Apply` and `Map`
Even though this might be too general question(or not answerable), I want to get some advice here. I apologize in advance if it is not a relevant question.
I frequently have to process large list of data(nested) and have to apply a function to each element. For example, consider the following simplified contrived example.
Given a list,
dat = {RandomReal[], RandomReal[]} & /@ Range@(10^6);
I want to apply a function. There might be several ways to achieve the same behavior, especially I usually find Map and Apply are good ways to go, i.e.,
{t, d} = #[[1]]/#[[2]] & /@ dat // Timing;
{t2, d2} = #1/#2 & @@@ dat // Timing;
{t3, d3} = Divide @@@ dat // Timing;
In this particular example, there exists a built-in function Divide, so I added the third one as a reference.
The times spent in each line in my machine were {t, t2, t3} == {0.500000, 6.187500, 1.875000}. Therefore, using Map might be the most efficient way in this case.
However, in my real world codes, there are some cases that the version of Apply is much faster, and thus I usually tend to try several versions and choose the best one when the performance really matters. But it would be very nice if I could get a hunch on which one is better in advance. Is there any general guideline for this problem?
A:
Odd that this question had no answers until today. Anyway, the performance of various methods, unsurprisingly, depends on the details of their applications. Generally speaking there are several layers of possible performance levels in Mathematica including optimized C libraries, sometimes with automatic parallelism, functions compiled within Mathematica either manually or automatically, operations fully internal to the pattern-matching engine, and high level rule-based expression transformation. (This is by no means an exhaustive list.) The more efficient a layer you are able to apply to your program, the faster it will run.
The high level rule language is highly flexible but not generally fast. An example:
dat = RandomReal[1, {1*^6, 2}];
Replace[dat, {a_, b_} :> Divide[a, b], {1}] // Timing // First // AbsoluteTiming
{0.612035, 0.592804}
This is (or should be) effectively equivalent to this Map application, though Map is slower for a reason I do not understand:
divide[{a_, b_}] := Divide[a, b]
divide /@ dat // AbsoluteTiming // First // Timing
{1.014007, 1.020058}
Both methods above require both a pattern matching operation and application of Divide for each pair of numbers. Using Apply at level one and Divide avoids the first operation and is faster:
Divide @@@ dat // AbsoluteTiming // First // Timing
{0.405603, 0.401023}
This, still requires a separate high level evaluation for each pair of numbers however. But Map has a possible trick in store: automatic compilation. For this to be applicable, the data need to be packed or packable and the function must be compilable. In this case dat is both packable and packed, as output by RandomReal, but divide is not automatically compilable. If instead we use:
divide2 = Divide[#[[1]], #[[2]]] &;
divide2 /@ dat // AbsoluteTiming // First // Timing
{0.093601, 0.098006}
This is automatically compilable and we see an order of magnitude improvement. Here, there is only the initial high level evaluation of Map with its automatic compilation, then all the pairs are processed in lower-level code. This, at least by default, is running in the Mathematica virtual machine, rather than low level C code, so it is not yet optimal. Divide is (presumably) written in C but if it is to be fast, we need to avoid repeated high level evaluation of the function and instead pass it all the data at once. It bears the Listable attribute and is specifically optimized for this case. To do that, we can use Transpose as mentioned in the comments, below the question:
Divide @@ Transpose[dat] // AbsoluteTiming // First // Timing
{0., 0.022001}
This is so fast, we need larger data to get an accurate estimate:
big = RandomReal[1, {1*^8, 2}];
(big2 = Transpose[big]) // AbsoluteTiming // First // Timing
Divide @@ big2 // AbsoluteTiming // First // Timing
{0.358802, 0.428024}
{0.249602, 0.589034}
This is another order of magnitude faster than the auto-compiled Map operation. We can see the breakdown in the time between Transpose and Divide operations. There is very little high-level evaluation here; nearly all of the computation is done at the compiled library level. This is enabled by packed input to functions specifically optimized to handle it. (Apply in @@ dat unpacks but only one level; Divide is still given two packed lists as input.)
In each of the examples above, I used Divide rather than / for consistency due to this issue:
Why are numeric division and subtraction not handled better in Mathematica?
A:
The problem isn't choosing whether Map, Apply, etc., are faster, but how to decide how much work you're asking Mathematica to do. I like the following method:
Trace shows you every detail of every step of a calculation; if you apply Trace to each of your calculations, you'll see that there are simply more steps required for some methods than the others. So:
dat = {{a, b}, {c, d}, {e, f}}
Trace[#[[1]]/#[[2]] & /@ dat]
(*
{(#1[[1]]/#1[[2]] &)[{a, b}], (#1[[1]]/#1[[2]] &)[{c,
d}], (#1[[1]]/#1[[2]] &)[{e, f}]} etc ...
*)
The output from Trace quickly gets impenetrable, so I use ByteCount as a rough and ready way of estimating how complex it is --- ByteCount is one way of counting how many steps there were, and how complicated they were.
So, combining the steps:
dat = {{a, b}, {c, d}, {e, f}}
ByteCount@Trace[#[[1]]/#[[2]] & /@ dat] (* 9600 bytes *)
ByteCount@Trace[#1/#2 & @@@ dat] (* 4800 bytes *)
ByteCount@Trace[Divide @@@ dat] (* 2672 bytes *)
You can also try the same exercise with the other versions of "dat" you'll see that the amount of time to complete a calculation is loosely related to the size of Trace.
dat = {RandomReal[], RandomReal[]} & /@ Range@(10^6);
ByteCount@Trace[#[[1]]/#[[2]] & /@ dat] (* 40 001 264 bytes *)
ByteCount@Trace[#1/#2 & @@@ dat] (* 1 648 001 304 bytes *)
ByteCount@Trace[Divide @@@ dat] (* 416 001 000 bytes *)
Note that the first method is very efficient when working on the packed array. If you "unpack" the array, the first method loses its efficiency:
dat = {RandomReal[], RandomReal[]} & /@ Range@(10^6);
dat[[1, 1]] = {1, 1};
ByteCount@Trace[#[[1]]/#[[2]] & /@ dat] (* 3 152 003 128 bytes *)
p.s. never ever forget Transpose... for packed data, this is the fastest method:
With[{t = Transpose[dat]}, t[[1]]/t[[2]]]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Install 32- or 64-bit Crystal Reports runtime on 64-bit server?
To run, our VB.NET application needs the runtime files Crystal Reports, developer version for Microsoft Visual Studio. (Support Pack SP8)
We are installing our application on Windows Server 2012 R2 64-bit.
The target CPU of our VB.NET app is x86.
Do we install the 32bit MSI or the 64 bit runtime?
[For the list of Crystal Report installation files, see http://scn.sap.com/docs/DOC-7824]
A:
You should know. Is your application 32 bit or 64 bit? You can set this up for VB.NET.... and.... 64 bit makes maybe little sense for most apps (that is the reason there is no 64 bit office in wide use - ms recommends against the use of it unless there is a need, like HUUUUUGH excel sheets).
As you say:
The target CPU of our VB.NET app is x86.
That says you hav a 32 bit application. So you need the 32 bit runtime.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Modulo and infinity, why is $x\bmod\infty$ equal to $x$ for binary operations on integers and $x \in \Bbb Z$?
Disclaimer: I am a programmer and my mathematical skills are those of Discrete Mathematics as taught at universities. I am interested in the mathematical background of how we can define $x\bmod\infty$, to understand essentially why, in programming language design we make the choices the way we do.
I believe in mathematics you call this the binary modulo operation, where the operator returns the remainder of integer division.
I thought it's such a simply question that I was surprised I couldn't find the answer at Math SE, so perhaps it isn't a mathematical question to begin with. A little background: yesterday we had a discussion at the XSLT 3.0 WG about a certain edge case and its expected outcome, and we seemed to remember that $x\bmod\infty = x$. But none of us was quick to find this definitively described anywhere.
Essentially, I am wondering about the reason why:
$$x\bmod\infty = x$$
With my limited skilss, I deduct that, in $x\bmod y$, as soon as $y$ gets bigger than $x$ it will always return $x$, so this should also be true for infinity, right? In other words, I think that:
$$\lim_{n\to\infty}x\bmod n = x, x \in \Bbb Z$$
And while we are at it, would this hold too?
$$x\bmod-\infty = x$$
$$0\bmod\infty = 0$$
$$0\bmod-\infty = 0$$
$$\infty\bmod\infty = \infty$$
$$-\infty\bmod\infty = -\infty$$
$$\infty\bmod-\infty = \infty$$
$$-\infty\bmod-\infty = -\infty$$
And the following seems logical, though I haven't found it definitively either:
$$\infty \bmod x = NaN$$
$$-\infty \bmod x = NaN$$
A:
I don't know what these values are in other fields, but from a simple point of view, it's right to study infinity as a limit concept, namely that we look at the value of the function as it's argument tend to infinity, and the define the quantity at infinity as the limit.
Note : $\mod x$ returns a value between $0$ and $|x|-1$.
Simply in that spirit,
$x \mod \infty = \lim_{y \to \infty} (x \mod y) = \lim_{y \to \infty} x = x$.
$x \mod -\infty = \lim_{y \to -\infty} (x \mod y) = \lim_{y \to -\infty} x = x$.
$0 \mod \infty = 0$, putting $x=0$ above.
$0 \mod -\infty = 0$, putting $x=0$ above.
$\infty \mod \infty $ cannot be defined, as if we were studying the value $x \mod y$ as $x,y \to \infty$, then we cannot say anything definitive about the limit. Speaking specifically, for all natural numbers $n$, there exist large enough numbers $x$ and $y$ such that $n \equiv x \mod y$. So by uniqueness of limit we would be right not to define this limit.
The subsequent infinite moduli are also undefinable for the reasons mentioned above.
As for the last two:
$\infty \mod x = \lim_{y \to \infty} y \mod x$. For any $n \leq x$, there exists a large enough $y$ such that $y \mod x = n$. Hence, we have that this limit is also not definable by uniqueness of limit. Similarly, the other limit is also not definable, unless $x=1/-1$, when we can say that the limit is zero.
I am not saying that these are correct. However, most concepts dealing with infinity either add it to the space, resulting in a compactification, or approach it as a limit, giving rise to these kind of results. Now, it is up to some one else to see how the definition of moduli would change under compactification by infinity, but this is what should be obtained by just analysis.
A:
Let's consider $x\bmod t$, for $t>0$; one of the used definitions for real $t>0$ is
$$
x\bmod t=x-t\left\lfloor\frac{x}{t}\right\rfloor
$$
If $0\le x<t$, we have $0\le x/t<1$, so $\lfloor x/t\rfloor=0$ and $x\bmod t=x$.
If $-t<x<0$, we have $-1<x/t<0$, so $\lfloor x/t\rfloor=0=-1$ and
$$
x\bmod t=x+t
$$
Thus you see that the definition $x\bmod\infty=x$ would only be reasonable for $x\ge0$.
However, if you use “truncated division”, the definition $x\bmod\infty=x$ would also be reasonable for $x<0$.
See Modulo operation on Wikipedia for the different definitions of the mod operation. You'll also see that different programming languages use different conventions. In any case the definition $x\bmod \infty=x$ for $x\ge0$ fits any of the conventions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Custom Table Model not working
I wrote a custom table model. The goal of it is to bind values to a list. This list is used throughout the application. If a change is made in the table, anywhere else in the application that change is also reflected. My problem is, my table JTable does not display the rows.
This is my first custom table model, so I am not sure if I am missing something.
The table is created with this code:
public CBTable(List<T> elements, Class<T> classType) {
super(new BindingTableModel(elements));
this.tableModel = (BindingTableModel<T>) getModel();
this.classType = classType;
setBindings();
repaint();
}
An example of setBindings is this:
@Override
protected void setBindings() {
addBinding(ProfessionalDelegate.DELEGAGE_PROPERTY_TYPE,
"Type",
String.class,
false);
addBinding(ProfessionalDelegate.ENTITY_PROPERTY_NAME,
"Name",
String.class,
true);
...
And the actual model itself is this:
public class BindingTableModel<T> extends AbstractTableModel implements TableModel {
private List<T> elements;
private List<BindingTableModelInfo> bindingInfo;
private Map<Point, Object> valueMap;
public BindingTableModel(List<T> elements) {
this.elements = elements;
this.bindingInfo = new ArrayList<>();
valueMap = new HashMap<>();
bind();
for(int i = 0; i < getRowCount(); i++){
fireTableRowsInserted(i, i);
}
fireTableStructureChanged();
}
public void addBindingInfo(String propertyName, String columnName, Class colClass, boolean isEditable) {
bindingInfo.add(new BindingTableModelInfo(propertyName,
columnName,
colClass,
isEditable));
}
private void bind() {
for (int col = 0; col < getColumnCount(); col++) {
for (int row = 0; row < getRowCount(); row++) {
getValueAt(row, col);//this will init the map
}
}
}
public void addElement(T element){
elements.add(element);
}
public List<T> getElements(){
return elements;
}
public void removeElement(T element){
int index = elements.indexOf(element);
elements.remove(element);
fireTableRowsDeleted(index, index);
}
@Override
public int getRowCount() {
return elements.size();
}
@Override
public int getColumnCount() {
return bindingInfo.size();
}
@Override
public String getColumnName(int i) {
return bindingInfo.get(i).getColumnName();
}
@Override
public Class<?> getColumnClass(int i) {
return bindingInfo.get(i).getColumnClass();
}
@Override
public boolean isCellEditable(int row, int col) {
return bindingInfo.get(col).isIsEditable();
}
@Override
public Object getValueAt(int row, int col) {
Point point = new Point(row, col);
if (valueMap.containsKey(point)) {
return valueMap.get(point);
}
String property = bindingInfo.get(col).getProperty();
Class classType = bindingInfo.get(col).getColumnClass();
T element = elements.get(row);
Object retVal = Pojo.getValueByName(classType, element, property);
valueMap.put(point, retVal);
return retVal;
}
@Override
public void setValueAt(Object value, int row, int col) {
Point point = new Point(row, col);
if (valueMap.containsKey(point)) {
Object oldValue = valueMap.get(point);
if (oldValue != null && oldValue.equals(value)) {
return;
}
}
String property = bindingInfo.get(col).getProperty();
Class classType = bindingInfo.get(col).getColumnClass();
T element = elements.get(row);
Pojo.setValueByName(classType, element, property, value);
}
}
A:
Be certain to fireTableCellUpdated() or another appropriate event; this is typically done in your implementation of setValueAt():
@Override
public void setValueAt(Object value, int row, int col) {
…
fireTableCellUpdated(row, col);
}
Complete examples are seen here and here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do you say "I also have lots of news to tell you" in German
Could anyone tell me how you would say "I also have lots (of news) to tell you" in German, when speaking to friends who you haven't seen in quite a long time?
A:
You could say
"Ich habe Dir viel zu erzählen."
or, if you want to emphasize the importance of your news:
"Ich muß Dir ganz viel erzählen."
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JQUERY Append issue when working with when the has inner DIV Structures
Ok, so here goes:
I am having a not so odd JQUERY issues. At least I think I am. My base HTML code is a fancy <DIV> <UL> <LI> structure (shown below). Each LI has it's own inner DIV structure though as well.
These are all styles using the Flexslider solution (a few years old). It works great when I just use it inline, but I am trying to convert this to JQUERY using a SP List.
A quick note: This is O365 SP not On-Prem
Some background on what works:
The list data from SharePoint is arriving just fine and when I do simple JQUERY .HTML(myHtml) it displays on the page properly.
The base Flexslider works just fine when I just use inline code without JQUERY for dummy testing.
What does not work is when I try to apply the data to the <LI> structure using either .HTML(myHtml) or .APPEND(myHTML). My guess it is because the <LI> structure has multiple inner DIV and somehow I have the append logic wrong for that.
Here is what the HTML should look like (with Sample Data)
<div class="page-content-wrapper">
<div class="flexslider carousel">
<ul class="slides">
<li>
<div class="fleximage lcol">
<a href="#"><img src="/DoingGood.jpg" alt="" /></a>
</div>
<div class="flexcaption rcol">
<div class="headline">TITLE!</div>
<div class="teaser">BLURB</div>
</div>
</li>
</ul>
</div>
</div>
The above code works when inserted just like that into the page. The problem occurs when I try to use the JQUERY below.
function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '<li><div class=\"fleximage lcol\"><img src=\"' + oListItem.get_item('ImageURL') + '\"></div> <div class=\"flexcaption rcol\"> <div class=\"headline\">' + oListItem.get_item('Title')+'</div> <div class=\"teaser\"> ' + oListItem.get_item('Blurb') + '</div> </div></li> ';
}
alert(listItemInfo);
$(".slides").html(listItemInfo);
}
Essentially I get NO output when using this. The ALERT shows me my data , as expected. I am guessing it is because of the structure of '''DIV''' tags in the LI and I need a different output approach?
Here is a sample output from the ALERT Message for the listItemInfo variable:
<li>
<div class="fleximage lcol"><img src="./Lexington/SiteCollectionDocuments/DoingGood.jpg"/></div>
<div class="flexcaption rcol">
<div class="headline">Test Stephen!</div>
<div class="teaser"> test</div>
</div>
</li>
<li>
<div class="fleximage lcol"><img src="./Lexington/SiteCollectionDocuments/DoingGood.jpg"/>
</div>
<div class="flexcaption rcol">
<div class="headline">Test 3 Steve</div>
<div class="teaser"> Tesst 4</div>
</div>
</li>```
A:
Test demo which works in my online environment.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/flexslider/2.7.2/jquery.flexslider-min.js"></script>
<link rel="stylesheet"
type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/flexslider/2.7.2/flexslider.min.css" />
<script type="text/javascript">
$(function () {
ExecuteOrDelayUntilScriptLoaded(myfunction, "sp.js");
});
function myfunction() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('Slider');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
'<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '<li><div class=\"fleximage lcol\"><img src=\"' + oListItem.get_item('ImageURL').get_url() + '\"></div> <div class=\"flexcaption rcol\"> <div class=\"headline\">' + oListItem.get_item('Title') + '</div> <div class=\"teaser\"> ' + oListItem.get_item('Blurb') + '</div> </div></li> ';
}
//alert(listItemInfo);
$(".slides").html(listItemInfo);
$('.flexslider').flexslider({
animation: "slide",
rtl: true,
start: function (slider) {
$('body').removeClass('loading');
}
})
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
<div class="page-content-wrapper">
<div class="flexslider" style="direction:rtl">
<ul class="slides"></ul>
</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to Search and Match 2 input fields values in Json file and if match found return 3rd Key Value from same json object
I have a 2 inputs fields where the user will enter Pickup and Delivery area name.When user finish with 2nd input (delivery or pickup - no sequence) I want to initiate a process where both input values are searched from JSON file and if the match for both inputs is found show relevant price. I am able to capture values on both inputs but I need a method to compare them to JSON file and on successful match show price. a method defined in constructor giving me all the objects in Json file.
NOTE. FIND MATCH PROCESS WILL NOT START WITH CLICK, Rather it will start with (change) of value.
Template
<div class="form-group">
<input class="form-control" id="pickupSuburb" (change)="onSelectedSuburb($event)" placeholder=" Pickup Suburb Here" [(ngModel)]="pickupSuburb" >
</div>
<div class="form-group">
<input list="suburb" class="form-control" id="deliverySuburb" (change)="onSelectedSuburb($event)" placeholder=" Delivery Suburb Here" [(ngModel)]="deliverySuburb" >
</div>
Component
import {Component, OnInit, ElementRef } from '@angular/core';
import 'rxjs/add/operator/map'
import { FormControl } from '@angular/forms';
import {Http} from '@angular/http';
@Component({
selector: 'app-sending',
templateUrl: './sending.component.html',
styleUrls: ['./sending.component.css'],
providers: [SuburbsService, AutoCompleteSuburbs, CapitalizePipe ],
})
export class SendingComponent implements OnInit {
priceList = [];
constructor(private elm: ElementRef, private http: Http) {
http.get('./assets/zoneRates.json').subscribe(response => {
this.priceList = response.json();
})
}
ngOnInit () {}
public onSelectedSuburb(event) {
const pickupArray = this.elm.nativeElement.querySelector('#pickupSuburb').value.slice(1).slice(-3);
const deliveryArray = this.elm.nativeElement.querySelector('#deliverySuburb').value.slice(1).slice(-3);}
Json Sample
[{
"pickup": "SYD",
"delivery": "QC4",
"weight": "25",
"price": "6.25"
}, {
"pickup": "SYD",
"delivery": "QC6",
"weight": "25",
"price": "6.25"
}, {
"pickup": "SYD",
"delivery": "QC7",
"weight": "25",
"price": "6.25"
}, {
"pickup": "SYD",
"delivery": "ADL",
"weight": "25",
"price": "6.25"
}]
A:
You can use the OnChanges lifecycle hook and search through the array of products using array.prototype.find. I don't see anywhere that you declare the form so I'm assuming you're using reactive forms. I suggest switching to dynamic forms (https://angular.io/guide/dynamic-form) as it will make getting the values easier.
My answer is going to assume you make this switch and have both pickupInput and deliveryAreaInput properties declared in your component which are bound to the associated inputs on your form. If you need to stick with reactiveForms you'll have to get these values some other way.
export class sendingComponent implements onChanges, onInit {
private pickupInput: FormControl = new FormControl('', Validators.required); // You may need different validation than this.
private deliveryAreaInput: FormControl = new FormControl('', Validators.required); // again your validation may differ.
/**
* Checks if either pickupInput or deliveryAreaInput are in the changes object.
* If either key is included pass both values to the searchJson method and store the response in a match property
* If match is truthy show the price
* @param {SimpleChanges} changes
*/
ngOnChanges(changes: SimpleChanges) {
if (changes.pickupInput || changes.delieveryAreaInput) {
const match: any = this.searchJson(this.pickupInput.value, this.deliveryAreaInput.value);
if (match) {
this.showPrice = true; // Use this with an ngIf in your template
}
}
}
/**
* Use Array.prototype.find to search through the priceList array for any products that have a matching pickup and delivery area.
* Array.prototype.find returns either the matching value or undefined if no matches are found.
* @param {string} pickup
* @param {string} deliveryArea
* @return {?} either the matching value or undefined
*/
private searchJson(pickUp: string, deliveryArea: string): any {
return this.priceList.find(price => {
return price.pickup === pickUp && price.delivery === deliveryArea;
});
}
}
I would be concerned about doing this search on change though. This is going to cause the entire product catalog to be searched on each key press, which if the catalog is long will be noticeably slow. A better solution would be to introduce a button or do the search on focus out instead of changes (although that will require the user to focus out obviously).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
If statement not working Unity C#
EDIT: Yeah, I have been coding in python lately and iv mixed up the syntax between the two languages. Thanks for the improvement tips.
My goal is to get the if statements working and output the corresponding normal, medium and hard. Eventhough GameDifficulty is set to 2, it outputs hard instead of medium. I have noticed that it just outputs the last if statement bit. Its really weird.
I define GameDifficulty as 2. When i run the script, Text11 becomes "hard" instead of Medium. I have no idea why this happens.
Thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class DifficultyDisplayOnWinScreen : MonoBehaviour {
public int GameDifficulty;
public GameObject Text11;
public string diffi;
void Start ()
{
//GameDifficulty = DifficultyChooser.DifficultyNumber;
GameDifficulty = 2;
}
void Update ()
{
//GameDifficulty = DifficultyChooser.DifficultyNumber;
if (GameDifficulty == 3);
{
Text11.GetComponent<Text> ().text = "Normal";
}
if (GameDifficulty == 2);
{
Text11.GetComponent<Text> ().text = "Medium";
}
if (GameDifficulty == 1);
{
Text11.GetComponent<Text> ().text = "Hard";
}
}
}
A:
Remove the ; after the if-conditions:
if (GameDifficulty == 3)
{
Text11.GetComponent<Text>().text = "Normal";
}
if (GameDifficulty == 2)
{
Text11.GetComponent<Text>().text = "Medium";
}
if (GameDifficulty == 1)
{
Text11.GetComponent<Text>().text = "Hard";
}
Explanation: the ; ends the if statement, making it an empty statement. This is because one-line if statements are allowed in C#, and the ; determines where they end.
A:
EDIT: I didn't even notice the ;s, yeah remove semicolons and it should work.
if (GameDifficulty == 3)
{
Text11.GetComponent<Text>().text = "Normal";
}
if (GameDifficulty == 2)
{
Text11.GetComponent<Text>().text = "Medium";
}
if (GameDifficulty == 1) //if there is only 3 difficulties in this line you can use just else
{
Text11.GetComponent<Text>().text = "Hard";
}
Or use if/else
if (GameDifficulty == 3)
{
Text11.GetComponent<Text>().text = "Normal";
}
else if (GameDifficulty == 2)
{
Text11.GetComponent<Text>().text = "Medium";
}
else if (GameDifficulty == 1) //if there is only 3 difficulties in this line you can use just else
{
Text11.GetComponent<Text>().text = "Hard";
}
and in this case better use switch/case:
switch(GameDifficulty)
{
case 1:
Text11.GetComponent<Text>().text = "Hard";
break;
case 2:
Text11.GetComponent<Text>().text = "Medium";
break;
case 3:
Text11.GetComponent<Text>().text = "Normal";
break;
}
or you can have a dictionary of difficulties for example:
Dictionary<int, string> difficulties = new Dictionary<int, string>()
{
{1, "Hard" },
{2, "Medium" },
{3, "Normal" }
};
and use it like:
Text11.GetComponent<Text>().text = difficulties[GameDifficulty];
Or enum (there is tons of ways to make it more readable and simple, so I will end my examples with this one)
enum Difficulties
{
Hard = 1,
Medium = 2,
Normal = 3
}
usage:
Text11.GetComponent<Text>().text = ((Difficulties)GameDifficulty).ToString();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Has the birth certificate recently uploaded to whitehouse.gov been digitally altered?
http://www.whitehouse.gov/sites/default/files/rss_viewer/birth-certificate-long-form.pdf
This is the one. I tried asking in my normal channels (hacker news, IRC) but am getting bombarded with accusations of being a Birther.
I am definitely not. Someone showed me there are seperate layers for the text and the rest of the document, and also that the font didn't make sense.
I am just hoping you could find evidence one way or another.
A:
It looks to me like the scanner that was used to make the PDF split the image into several layers during construction of the PDF in order to reduce the file size while maintaining sharp text. If we look side-by-side at some writing that was not separated into a separate layer and some text that was, we can clearly see the effect (note that I have moved the writing around to get a good side-by-side example):
This is a very common feature of scanners that produce PDFs, since your documents tend to look horrible otherwise (or are huge). Here's an example taken from my local copier (again with text moved next to writing that was not recognized as requiring hi-res):
Thus, the existence of multiple layers in no way is evidence that the document is not authentic. This is the standard way for scanners/copiers to handle scanned-document-to-PDF conversions.
Upon review of the document, I can't find an instance of the font "not making sense". Looks like a typewriter to me, and the same one used for the whole document (complete with artifacts that I recall seeing before, like partially shifted caps).
Edit: this site shows all the layers (thanks to geoff for finding it). You can verify them for yourself by loading the PDF into a vector graphics tool like Adobe Illustrator or Inkscape and ungrouping the pieces.
Another edit: This site presents the same conclusion (thanks to fred for finding it), albeit without a clear demonstration, and with some technical inaccuracies.
A:
This video: http://www.youtube.com/watch?v=XcWQw2AAIho does a great job of showing how this is an artifact of the scanning and compression process.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
handle authentication exception with symfony2
I'd like simply return an apropriate message like return new Response('authentication faild'); to my client throught an API but it doesn't behave as it suppose to be as in the following code
try{
$token = $this->get('security.authentication.manager')
->authenticate(new UsernamePasswordToken($username, $password, 'main'));
$this->get('security.context')->setToken($token);
}
catch (BadCredentialsException $e){
return new Response('authentication faild', 403);
}
The error returned is the html/css ... code of the login form
A:
Look at this:
<?php
namespace YourBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class CatchErrorsEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return ["kernel.exception" => ['catchException', 200]];
}
/**
* @param GetResponseForExceptionEvent $evt
*/
public function catchException(GetResponseForExceptionEvent $evt)
{
$request = $evt->getRequest()->getRequestFormat('json');
if($request != 'json') {
return;
}
$response = $evt->getResponse() ?: new Response();
$evt->stopPropagation(); // stop the other listener to redirect to login
$evt->setResponse($response);
}
}
This listener will catch the exception and you can send a response your desired way. In this example only if the request is a json request.
Don't forget to register the subscriber as a service:
<service class="YourBundle\EventListener\CatchErrorsEventSubscriber" id="your_bundle.catch_error_event_subscriber">
<tag name="kernel.event_subscriber"/>
</service>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java unreachable catch block compiler error
Why in Java can we catch an Exception even if it is not thrown, but we can't catch it's subclass (except for "unchecked" RuntimeExceptions and it subclasses). Example code:
class Test {
public static void main(String[] args) {
try {
// do nothing
} catch (Exception e) {
// OK
}
try {
// do nothing
} catch (IOException e) {
// COMPILER ERROR: Unreachable catch block for IOException.
//This exception is never thrown from the try statement body
}
}
}
Any ideas?
A:
A RuntimeException could be thrown by any code. In other words, the compiler can't easily predict what kind of code can throw it. A RuntimeException can be caught by a catch(Exception e) block.
IOException, however, is a checked exception - only method calls which are declared to throw it can do so. The compiler can be (reasonably) confident that it can't possible occur unless there are method calls which are declared to throw it.
The Java compiler simply doesn't consider the "there's no code at all within the try block" situation - it always allows you to catch unchecked exceptions, as in all reasonable scenarios there will be code which could potentially throw an unchecked exception.
From section 14.21 of the JLS:
A catch block C is reachable iff both of the following are true:
Some expression or throw statement in the try block is reachable and can throw an exception whose type is assignable to the parameter of the catch clause C. (An expression is considered reachable iff the innermost statement containing it is reachable.)
There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.
Arguably the compiler should realize that there are no expressions within the try block in your first case... it looks like this is still an unreachable catch clause, to me.
EDIT: As noted in comments, section 14.20 contains this:
It is a compile-time error if a catch clause catches checked exception type E1 but there exists no checked exception type E2 such that all of the following hold:
E2 <: E1
The try block corresponding to the catch clause can throw E2
No preceding catch block of the immediately enclosing try statement catches E2 or a supertype of E2.
unless E1 is the class Exception.
So it looks like that's what you're actually running foul of, but the spec isn't as clear as it could be in terms of unreachable catch blocks in 14.21.
A:
IO Exceptions can only be caught if the compiler predicts that there might be something in the code that throws IOException. So you are getting a warning that IO exception is never thrown from the try statement body (since there is nothing in the body of try).
A:
Because for checked exceptions the method that is throwing them, must explicitly state this fact by 'throws' keyword, thus if a block doesn't have the 'throws IOException' in your case, the compiler has the information it is impossible for an IOException to be thrown, so the whatever you do after catching, it would be unreachable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Select a specific time between set interval into TimePickerDialog
Hey I want to implement time selection functionality in TimePickerDialog. User can select any time between 3PM to 6PM. Other times are not allowed to select. How can I do this functionality?
A:
You could try overriding the onTimeChanged(TimePicker view, int hourOfDay, int minute) method and doing your validation there.
The other option would be to handle it in the TimePickerDialog.OnTimeSetListener listener but this only occurs after the dialog is closed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do python-request sessions detect when a page automatically refreshes?
I've recently been experimenting with using the request module in Python for webscraping and have a question about when a site automatically refreshes. For example, if I sent a request to a website and had to wait in a queue because the website had too many people trying to access it at once, how would the requests session handle eventually being redirected to the site?
Would I be able to do something like:
import requests, time
s = requests.Session()
r = s.get('www.example.com')
passed = 0
while passed == 0:
if 'passed' in r.text:
print('passed queue!')
passed = 1
else:
print('still in queue')
time.sleep(60)
Or would I have to do another GET request in order to determine if I passed the queue or not and do something like:
import requests, time
s = requests.Session()
r = s.get('http://www.example.com')
passed = 0
while passed == 0:
if 'passed' in r.text:
print('passed queue!')
passed = 1
else:
print('still in queue')
time.sleep(60)
r = s.get('http://www.example.com')
A:
Requests doesn't interpret the response beyond handling the Location header for redirects. If the page uses a <meta> tag or JavaScript to perform the refresh, you'll have to handle it.
If you want to act like a real browser at the expense of speed and higher resource utilization, use a headless browser like Selenium.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does the expansion symbol of From the Vault: Transform mean?
What does the expansion symbol of From the Vault: Transform depicts? Looks like feathers in a circle to me.
MTG Gamepedia says:
"The cards use their original transformation symbols. However, the
expansion symbol is uniquely mirrored in color on the cards' back
sides."
And Wikipedia lists it as
unrevealed
in the Expansion Symbol column at List of Magic: The Gathering Sets article
A:
The quote is merely referring to the fact the expansion symbols colours on the front are inverted on the back. The standard is for expansion symbols to be the same regardless of what side they are printed on, so this difference in colour makes the set symbol unique.
I suspect that the symbol is supposed to be the back of a werewolf in front of a moon. Though the expansion only contains one werewolf, werewolves are a core part of the transform mechanic and featured heavily in the mechanics debut during Innistrad.
Front (Orange background, Black lines):
Back (Black background, Orange lines):
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to trigger an action by clicking the option item of a select element (Vue.js)?
List of options as JS object:
options: [{
text: this.$t('analytics.pastDays', { days: 7 }),
value: 7
}, {
text: this.$t('analytics.pastDays', { days: 28 }),
value: 28
}, {
text: this.$t('analytics.pastDays', { days: 360 }),
value: 360
}, {
text: this.$t('analytics.customDate'),
value: 7,
method: () => { console.log('Worked') }
}],
Select element:
<select
class="i-select"
v-model="value"
@change="onChange($event)">
<option
v-for="option in options"
:value="option.value"
@click.stop.prevent="option.method($event)">
{{ option.text }}
</option>
</select>
Right know the console logs never logs.
How to make it so that the analytics.CustomDate options triggers its method?
A:
I think click event on option will not work, we can utilize its change event, (not sure option element is not respecting onclick)
you can check workaround in this snippet
var yourOptions = [{
text: 'analytics.pastDays',
value: 7,
method: function() { console.log('this one is selected (7).') }
}, {
text: 'analytics.pastDays',
value: 28
}, {
text: 'analytics.pastDays',
value: 360,
method: function() { console.log('this one is selected (360).') }
}, {
text: 'analytics.customDate',
value: 70,
method: function() { console.log('this one is selected (70).') }
}];
var vm = new Vue({
el: '#app',
data: {
options: yourOptions,
value:''
},
mounted: function() {
},
methods: {
onChange: function(value) {
var selected = yourOptions.filter(function(obj) {
return obj.value == value
})
if(selected.length > 0) {
selected.forEach(function(option){ if(option.method) { option.method(); } })
}
}
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>VueJS</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>
<div id="app">
<select
class="i-select"
v-model="value"
@change="onChange(value)">
<option
v-for="option in options"
:value="option.value"
>
{{ option.text }}
</option>
</select>
</div>
</body>
</html>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there any way to enable the bash to search subdirectory to find a executable?
I have just built some software on my computer and installed them. After a short period of time, I found files under /usr/local/bin hard to manage because I can't tell which software does each file belong, thus it'll be hard for me to uninstall them or change them(probably their name).
In order to do this, I think the most convenient way is to put softwares in separate directory under /usr/local/, but just doing that isn't enough for bash to work.
The first solution I thought of is adding wildcard /usr/local/*/bin to the PATH variable in .bashrc. But it didn't work.
The second solution I thought of is using overlayfs. But I think that's too much for this, and will incur extra overhead.
So is there any way to do this?
My computer is Debian 9.4, linux kernel 4.9, gcc 6.3.
A:
Software which isn't installed by regular means often goes in /opt.
To make the commands available in bash you can add the directory with the executables to the path without wildcards (which somehow means one entry for each software you add).
Another solution is to add a short startup script or a soft link to the executable in your ~/bin (your ~/bin is usually included in the path if it exists).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does the phrase "point-blank" mean in "she refused point-blank to join in"?
So she refused point-blank to join in.
What does the expression point-blank mean in this context? Could you give me some more examples of situations where this phrase could be used?
A:
There's an interesting discussion of the origins of the expression here:
http://www.wordwizard.com/phpbb3/viewtopic.php?f=7&t=22750
Usually used of a gun, it has become a metaphor for manner.
POINT BLANK adjective; adverb
[1591] Aimed straight at the mark or target without allowing for the drop in a projectile's course [due to gravity], firing straight at the target – point blank –one may hit the target if one is close enough.
[1598] (figurative): Without hesitation, deliberation, or equivocation; plainly, bluntly, directly, frankly; abruptly or rudely: She told him point-blank that he was not welcome.
A:
It is an expression used to say that someone very bluntly did something with emphasis. Usually when used it means that there was some historical context involving the action in that the person doing something point-blank could/should have been expected to do that. Often there is a connotation of hostility or at the very least conveying that you do not want to be questioned about your actions.
Usage:
I told my husband point-blank if he hits me one more time that I am leaving.
"Dad can I borrow your Porsche?" Dad replies, "Steve, point-blank no!"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
really don't know how to set function in order to recognize whether cell is selected or not
class ViewController: UICollectionViewController {
var selectedRow : Int?
let data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier : "MyCell")
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CollectionViewCell
cell.Label.text = String(data[indexPath.row])
return cell
}}
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var Label: UILabel!
@IBOutlet weak var button: UIButton!
@IBAction func buttonPressed(_ sender: UIButton) {
if Label.textColor == .red{
Label.textColor = .black
} else if Label.textColor == .black{
Label.textColor = .red
}}
public override func awakeFromNib() {
super.awakeFromNib()}}
I want to recognize whether cell is selected or not.
but I really don't know where in I have to use what function.
many people are saying using setSelected function but I think there is no such function.
I'm beginner so I don't know well.
what I want to is make "if I select one of that number then that cell's textColor turn red.
and then I select another cell. then that cell's textColor turn red and original one turn black again."
what function I have to use and where I have to use function.
A:
There are so many ways to do it, I prefer the below way.
Change: 1
You need to add buttonPressed method into UIViewController
Change: 2
You need to add code for UILabel text color into cellForItemAt.
Full code:
class ViewController: UICollectionViewController {
var selectedRow : Int?
let data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier : "MyCell")
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CollectionViewCell
cell.button.tag = indexPath.item
cell.button.addTarget(self, action:#selector(buttonPressed(_:)) , for: .touchUpInside)
cell.Label.text = String(data[indexPath.row])
if selectedRow == indexPath.item{
cell.Label.textColor = .black
}else{
cell.Label.textColor = .red
}
return cell
}
@objc func buttonPressed(_ sender: UIButton) {
if selectedRow == sender.tag{
selectedRow = nil
}else{
selectedRow = sender.tag
}
collectionView.reloadData()
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Implementing Twisted style local multiple deferred callbacks in Celery
I am quite new to using Celery and was wondering how TWSITED type multiple deferred callbacks can be implemented in Celery
MY TWISTED CODE uses perspective broker and is as follows. I have a Handler (server) which handles some events and returns the result. The Dispatcher (Client) prints the result returned using a deferred callback.
Handler.py (Server)
from twisted.application import service, internet
from twisted.internet import reactor, task
from twisted.spread import pb
from Dispatcher import Event
from Dispatcher import CopyEvent
class ReceiverEvent(pb.RemoteCopy, Event):
pass
pb.setUnjellyableForClass(CopyEvent, ReceiverEvent)
class Handler(pb.Root):
def remote_eventEnqueue(self, pond):
d = task.deferLater(reactor,5,handle_event,sender=self)
return d
def handle_event(sender):
print "Do Something"
return "did something"
if __name__ == '__main__':
h=Handler()
reactor.listenTCP(8739, pb.PBServerFactory(h))
reactor.run()
Now the Dispatcher.py (Client)
from twisted.spread import pb, jelly
from twisted.python import log
from twisted.internet import reactor
from Event import Event
class CopyEvent(Event, pb.Copyable):
pass
class Dispatcher:
def __init__(self, event):
self.event = event
def dispatch_event(self, remote):
d = remote.callRemote("eventEnqueue", self.event)
d.addCallback(self.printMessage)
def printMessage(self, text):
print text
def main():
from Handler import CopyEvent
event = CopyEvent()
d = Dispatcher(event)
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8739, factory)
deferred = factory.getRootObject()
deferred.addCallback(d.dispatch_event)
reactor.run()
if __name__ == '__main__':
main()
I tried implementing this in Celery.
Handler.py (Server)
from celery import Celery
app=Celery('tasks',backend='amqp',broker='amqp://guest@localhost//')
@app.task
def handle_event():
print "Do Something"
return "did something"
Dispatcher.py (Client)
from Handler import handle_event
from datetime import datetime
def print_message(text):
print text
t=handle_event.apply_async(countdown=10,link=print_message.s('Done')) ##HOWTO?
My exact question is how can one implement deferred callbacks TWISTED style on local functions like print_message in Celery. When handle_Event method is finished it returns result on which I would like to have another callback method (print_message) which is LOCAL
Any other possible Design workflow to do this in Celery?
Thanks
JR
A:
Ok, so finally figured it out. It is not quite possible to add callbacks directly in the Celery client like the Twisted style. But Celery supports task monitoring functionality, that enables the client to monitor different kinds of worker events and add callbacks on it.
A simple task monitor (Task_Monitor.py) would look something like this. (Details can be found in Celery real processing documentation http://docs.celeryproject.org/en/latest/userguide/monitoring.html#real-time-processing)
Task_Monitor.py
from celery import Celery
def task_monitor(app):
state = app.events.State()
def announce_completed_tasks(event):
state.event(event)
task = state.tasks.get(event['uuid'])
print('TASK SUCCEEDED: %s[%s] %s' % (task.name, task.uuid, task.info(), ))
with app.connection() as connection:
recv = app.events.Receiver(connection, handlers={'task-succeeded': announce_completed_tasks})
recv.capture(limit=None, timeout=None, wakeup=True)
if __name__ == '__main__':
app = Celery(broker='amqp://guest@REMOTEHOST//')
task_monitor(app)
Task_Monitor.py has to be run as a separate process (client side). Besides the Celery application (server side) needs to be configured using
app.conf.CELERY_SEND_EVENTS = TRUE
or using -E option while running celery
so that it sends events in order for worker to be monitored.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HtmlUnit, trying to get 2 forms, get exception at second form
Currently using HtmlUnit.
Getting first login page is no problem, succesfully logging in, getting next page, "clicking" the link to get the "MyDetails" page.
After getting "MyDetails" page, i want to get the same way as im getting the first login form.
Why i need to get the form is that i want to change the password, and the fields are in a form.
When im trying to get the second form, it gives me exception as follows:
com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[form] attributeName=[name] attributeValue=[form2]
Gives exception at this line of code:
HtmlForm form2 = page3.getFormByName("form2");
Note: the first form name is "form1" & second form name is "form2".
Is this a problem with HtmlUnit?
Code:
try {
WebClient webclient = new WebClient(BrowserVersion.FIREFOX_3_6);
HtmlPage page1 = webclient.getPage("http://www.highveld.mobi/pages/clubvip/login.aspx");
HtmlForm form = page1.getFormByName("form1");
HtmlSubmitInput buttonLogin = form.getInputByName("cmdLogin");
HtmlTextInput cellLogin = form.getInputByName("txtCellNumber");
HtmlPasswordInput passLogin = form.getInputByName("txtLoginPassword");
cellLogin.setValueAttribute(change);
passLogin.setValueAttribute(oldPass);
HtmlPage page2 = buttonLogin.click();
HtmlAnchor link = page2.getAnchorByHref("updateprofile.aspx");
HtmlPage page3 = link.click();
System.out.println(page3.getUrl());
HtmlForm form2 = page3.getFormByName("form2");
HtmlPasswordInput pass = form2.getInputByName("txtPassword");
HtmlPasswordInput passConfirm = form2.getInputByName("txtConfirmPassword");
HtmlSubmitInput button = form2.getInputByName("cmdUpdate");
pass.setValueAttribute(newPass);
passConfirm.setValueAttribute(newPass);
HtmlPage page4 = button.click();
}
A:
First of all, please update to HtmlUnit 2.9 in case you are using an old version.
Secondly, replace this with this:
System.out.println(page3.getUrl());
HtmlForm form2 = page3.getFormByName("form2");
With this:
System.out.println(page3.getUrl());
System.out.println(page3.asXml());
HtmlForm form2 = page3.getFormByName("form2");
And check for the existance of the form2 element, which I'm pretty sure it shouldn't be there as it is throwing a ElementNotFoundException.
I usually use XPath instead of getFormByName, you can give it a try too.
Hope this helps!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python Beautiful Soup Scraping & Parsing
There is a Java Script page I am attempting to scrape with BeautifulSoup
bb2_addLoadEvent(function() {
for ( i=0; i < document.forms.length; i++ ) {
if (document.forms[i].method == 'post') {
var myElement = document.createElement('input');
myElement.setAttribute('type', 'hidden');
myElement.name = 'bb2_screener_';
myElement.value = '1568090530 122.44.202.205 122.44.202.205';
document.forms[i].appendChild(myElement);
}
I would like to obtain the value of "myElement.value", but I am not familiar with how to do so( If it is even possible with BeautifulSoup)
Ive tried :
soup = BeautifulSoup(a.text, 'html.parser')
h = soup.find('type') ...('div') ... ('input') ... even ('var')
print(soup)
and NO Luck :(
Is there a way of obtaining the value? If so how?
A:
It would help to know more about the myElement.value across different pages. You might get away with a simple character set and lead string as shown in regex below. I would like to tighten it up but would need more examples ..... perhaps those number lengths are fixed and repeating ? ..... then something like p = re.compile(r"myElement\.value = '(\d{10}(?:(\s\d{3}\.\d{2}\.\d{3}\.\d{3}){2}))';") <= then take group 1.
import re
s = '''bb2_addLoadEvent(function() {
for ( i=0; i < document.forms.length; i++ ) {
if (document.forms[i].method == 'post') {
var myElement = document.createElement('input');
myElement.setAttribute('type', 'hidden');
myElement.name = 'bb2_screener_';
myElement.value = '1568090530 122.44.202.205 122.44.202.205';
document.forms[i].appendChild(myElement);
}'''
p = re.compile(r"myElement\.value = '([\d\s\.]+)';")
print(p.findall(s)[0])
@SIM also kindly proposed:
p = re.compile(r"value[^']+'([^']*)'"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can a full batch gradient descent point not to a minimum for a convex function?
Let's say that we have a three dimentional convex function with a minimum marked by a red dot. Can a full batch gradient in a blue point not directed to a red dot as drawn below?
Actually this question is about Andrew Ng's lection Gradient Descent With Momentum (C2W2L06). He said: "If you take one iteration of gradient descent either batch or mini-batch gradient descent maybe you end up heading [toward blue arrow]". Is it really possible for a full batch gradient?
A:
Yes. Gradient descent heads towards the direction of steepest descent (or an approximation of it, in the case of SGD).
Recall that the direction of steepest descent is always perpendicular to the level curves (in this case the ellipses) of the loss function. So the blue arrow makes a lot of sense.
It is definitely not the case the gradient will always point directly towards/away from the minimum.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the best choice for an outgoing mail server?
I am creating a web application that will send out emails to provide users with a registration email when they first login to the website. Eventually we will send out monthly emails showing new features available on the site to our users.
My concern is that the outgoing registration and other emails will be marked as spam and I don't want that to happen. Besides making sure the content of the emails is acceptable, what is the best way to run the outgoing server and avoid being labeled spam?
Choices:
Create a Google Apps account for the domain and send from there. We currently do this on our other domain.
Add an email option to the domain via GoDaddy.com which provides our DNS entry.
Run our own email server on one of our Amazon EC2 instances.
Other?
This is not a duplucate of How to send emails and avoid them being classified as spam? because this question more specifically asks about the choice of the originating server.
A:
You haven't given us much info to go on. If someone chooses the best solution for you, that would be mostly chance.
There is a lot of learning to do to set up a mail server from scratch for yourself. It's easy to get something going, but there's a lot of pitfalls which you'll likely learn over time as you recognise your initial mistakes. That said, a mail server that handles outgoing email only, without high volume, is a relatively simple case.
The main points are:
Make sure all your DNS is set up right. Eg PTR record for your mail server and matching A record.
Set up DKIM signing.
Set up DPF to verify that your mail server is OK to send from your domain.
Set up DMARC so you find out if something is wrong with the above.
Make sure you're processing bounce messages properly so that you don't keep on sending to bad addresses. This is not simple, so don't go reinventing the wheel.
Behave yourself. Your mail-server's reputation is important to protect.
EDIT:
It's a couple of years later now, and these days my operations are about half and half between running my own relays and using services like mandrillapp and sendgrid. Commonly where I build a relay, it's a purpose built one which relays all mail through a given account at one of these services, saving local apps from having to handle the authentication process and credential storage of those services.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
what is the difference between popen() and system() in C
I want to execute a binary within my C code. Which is better to execute with? popen() or system()
EDIT: I tried to use system, but the process executing seems to get stuck in the end and does not return to my code.
Any suggestions on what to do?
Thanks
A:
popen() gives you control over the process's input or output file streams. system() doesn't. If you don't need to access the process's I/O, you can use system() for simplicity.
system() is in C89 and C99; popen() is Posix only (though the Windows API also has one).
Both functions invoke some form of a shell to execute the command (e.g. /bin/sh on Linux, and probably cmd.exe on Windows). If you want to execute an executable file directly and you are on Posix, you can also look at the exec*-family of functions in conjuction with fork() (since exec() replaces the current process).
A:
Use popen if you want to run a shell command and want the parent process to be able to talk to the child. (It hooks the child's input or output up to the stream you get back.) Otherwise, prefer the exec family of functions (likely in conjunction with fork); exec'd processes inherit most open file descriptors (including stdin, stdout, and stderr), so you can hook input and output up to whatever you like...plus, there are fewer security implications.
system is generally best avoided unless you have to run shell commands. It spawns a shell to run the command, and the shell can parse the command any way it likes. In particular, certain environment variables (like $IFS and/or $PATH) can be modified in such a way as to cause the parent to execute programs you never intended it to. Although popen appears to do the same thing, it at least provides functionality that makes it worthwhile in the general case.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
¿Cómo limito el template al grupo del usuario?
Necesito limitar parte del template a los usuarios miembros de un grupo.
Sería algo similar a lo siguiente, pero para el grupo del usuario:
{% if request.user.is_authenticated %}
A:
Puedes encontrar los grupos en:
{{ request.user.groups }}
Una manera muy rapida si sabes que los usuarios solo tendrán un grupo podria ser:
{% if 'grupo' == request.user.groups.all.0.name %}
parte restringida
{% endif %}
Si es un poco mas complejo que eso, te recomeindo crearte una templatetag para preguntar en la template. (eso o lo llevas en una variable desde back)
Creas un fichero user_tags.py en tu proyecto debajo de nombreapp/templatetags
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django import template
register = template.Library()
@register.filter('has_group')
def has_group(user, group_name):
"""
Verifica se este usuário pertence a un grupo
"""
groups = user.groups.all().values_list('name', flat=True)
return True if group_name in groups else False
Y en la template lo usas:
{% load user_tags %}
{% if request.user|has_group:"Administradores"%}
parte restringida
{% endif %}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should we prefer organic lemon and orange peels?
In many recipes, when it comes to add some lemon (or orange) zests, the authors advise to choose an organic fruit, because of the pesticides.
I know there is no proof that non-organic fruits and vegetables are more dangerous than organic ones, but I saw that UK Food Safe Agency seems to make a distinction between fruits that are going to be peeled off and the others, when it comes to testing the pesticide residues:
You don't need to wash or peel fruit and vegetables that would not ordinarily be peeled before consumption (for example apples) because of pesticide residues, as no assumption is made that such foods are peeled when deciding whether a pesticide can be approved for use or setting a legal limit (maximum residue level, MRL).
Then, should we prefer organic lemons or oranges, when we want to use their skin in food?
Note: I know there have been many questions here about organic vs non-organic food and safety, but my question is about this peculiar case.
Edit: Changed "no evidence" to "no proof". It seems a better choice of word.
A:
The intended meaning of the quote you supplied is surely that if the outside of layer of a fruit or vegetable is commonly consumed then this would be taken in to account when setting a maximum residue level (MRL).
Zest of lemon and orange is commonly consumed and therefore those fruits must reasonably be included in the Food Standards Agency's claims about setting an appropriate MRL.
And indeed, Annex 1 on page 4 of this PDF, which is an annex to COMMISSION REGULATION (EU) No 752/2014
of 24 June 2014, says that the MRL for citrus fruit applies to "Whole product after removal of stems".
This case isn't peculiar and citrus zest is safe (if you accept the Food Standards Agency's claims).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is this map lambda function taking too much time when applied on pandas dataframe?
I want to copy each row from df_source to df_target that matches a simple condition (value of its col1 doesn't exist in a given list of values).
I'm trying to accomplish this by doing the following:
df_target = df_source[df_source['Col1'].map(lambda x: x not in id_list)].copy()
Keep in mind len(id_list) = 300000, that contains string identifiers of the shape HF1D2R.
The dataframe df_source also contains 300000 rows and 11 columns of type strings and integers.
This takes over 10 minutes to complete, what's the issue here ?
A:
Use isin with ~ for inverse boolean mask:
df_target = df_source[~df_source['Col1'].isin(id_list)].copy()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NSDate filtering cases
I am using a transient attribute to distribute core data objects in table view sections.
The transient attribute is called sectionIdentifier and it is defined depending on an attribute called todoDueDate.
I need to filter the objects in a way that all must be included in one of following groups, and only in one:
1. sectionIdentier = 0, **OVERDUE** , todoDueDate < today
2. sectionIdentier = 1, **TODAY** , todoDueDate = today
3. sectionIdentier = 2, **TOMORROW** , todoDueDate >today AND todoDueDate= = tomorrow
4. sectionIdentier = 3, **UPCOMING** , todoDueDate > today AND todoDueDate!=tomorrow
With my current code, I am able to filter the objects for the cases 1,2 and 4(I have to discard here objects for tomorrow). I have tried several ways to filter the objects for the case 3, but no success.
I kindly ask you to help me filtering for case 3.
Here is my current code:
-(NSString *)sectionIdentifier{
[self willAccessValueForKey:@"sectionIdentifier"];
NSString *tmp = [self primitiveValueForKey:@"sectionIdentifier"];
[self didAccessValueForKey:@"sectionIdentifier"];
if (!tmp){
NSDate *date = self.todoDueDate;
NSDate *todayDate = [NSDate date];
NSLog(@"date= %@",date);
NSLog(@"todayDate = %@",todayDate);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger comps = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit);
NSDateComponents *date1Components = [calendar components:comps fromDate:date];
NSDateComponents *date2Components = [calendar components:comps fromDate:todayDate];
date = [calendar dateFromComponents:date1Components];
todayDate = [calendar dateFromComponents:date2Components];
if([date
compare:todayDate] == NSOrderedAscending) {
tmp = @"0";//OVERDUE
}
if([date
compare:todayDate] == NSOrderedDescending) {
tmp = @"3";//UPCOMING BUT NOT TOMORROW(PENDING THIS PART)
}
if ([date
compare:todayDate] == NSOrderedSame) {
tmp = @"1";//TODAY
}
//TOMORROW COMES HERE
NSLog(@"Tmp= %@",tmp);
[self setPrimitiveValue:tmp forKey:@"sectionIdentifier"];
}
return tmp;
}
Here is my updated code:
-(NSString *)sectionIdentifier{
[self willAccessValueForKey:@"sectionIdentifier"];
NSString *tmp = [self primitiveValueForKey:@"sectionIdentifier"];
[self didAccessValueForKey:@"sectionIdentifier"];
if (!tmp){
NSDate *today = [NSDate date];
NSDate *date = self.todoDueDate;
NSCalendar *calendar;
NSInteger daysAfterToday = [calendar components:NSDayCalendarUnit
fromDate:today toDate:date options:0].day;
// NSString *section;
if (daysAfterToday < 0) {
tmp = @"0";
} else if (daysAfterToday == 0) {
tmp = @"1";
} else if (daysAfterToday == 1) {
tmp = @"2";
} else {
tmp = @"3";
}
NSLog(@"TODAY = %@", today);
NSLog(@"DATE = %@", date);
NSLog(@"DAYS AFTER TODAY = %ld",(long)daysAfterToday);
NSLog(@"Tmp= %@",tmp);
[self setPrimitiveValue:tmp forKey:@"sectionIdentifier"];
}
return tmp;
}
And here the logging results:
2014-01-17 22:35:53.576 To-Do Pro Light[4124:a0b] TODAY = 2014-01-18 05:35:53 +0000
2014-01-17 22:35:53.619 To-Do Pro Light[4124:a0b] DATE = 2014-01-13 04:08:32 +0000
2014-01-17 22:35:53.656 To-Do Pro Light[4124:a0b] DAYS AFTER TODAY = 0
2014-01-17 22:35:53.664 To-Do Pro Light[4124:a0b] Tmp= 1
2014-01-17 22:35:53.739 To-Do Pro Light[4124:a0b] TODAY = 2014-01-18 05:35:53 +0000
2014-01-17 22:35:53.743 To-Do Pro Light[4124:a0b] DATE = 2014-01-18 04:13:39 +0000
2014-01-17 22:35:53.748 To-Do Pro Light[4124:a0b] DAYS AFTER TODAY = 0
2014-01-17 22:35:53.752 To-Do Pro Light[4124:a0b] Tmp= 1
2014-01-17 22:35:53.757 To-Do Pro Light[4124:a0b] TODAY = 2014-01-18 05:35:53 +0000
2014-01-17 22:35:53.762 To-Do Pro Light[4124:a0b] DATE = 2014-01-19 04:16:14 +0000
2014-01-17 22:35:53.766 To-Do Pro Light[4124:a0b] DAYS AFTER TODAY = 0
2014-01-17 22:35:53.770 To-Do Pro Light[4124:a0b] Tmp= 1
2014-01-17 22:35:53.776 To-Do Pro Light[4124:a0b] TODAY = 2014-01-18 05:35:53 +0000
2014-01-17 22:35:53.779 To-Do Pro Light[4124:a0b] DATE = 2014-01-25 04:11:34 +0000
2014-01-17 22:35:53.825 To-Do Pro Light[4124:a0b] DAYS AFTER TODAY = 0
2014-01-17 22:35:53.831 To-Do Pro Light[4124:a0b] Tmp= 1
A:
Just ask the calendar to compute the number of days from today to the due date, and check that number:
NSInteger daysAfterToday = [calendar components:NSDayCalendarUnit
fromDate:today toDate:date options:0].day;
NSString *section;
if (daysAfterToday < 0) {
section = @"0";
} else if (daysAfterToday == 0) {
section = @"1";
} else if (daysAfterToday == 1) {
section = @"2";
} else {
section = @"3";
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mocha cannot compile Typescript code on Windows
For my nodejs module I wrote a few unit tests using Mocha and Chai. They run fine on macOS, but fail to compile on Windows, with this compiler error:
D:\projects\antlr4-graps>npm test
> [email protected] test D:\projects\antlr4-graps
> mocha --compilers ts:ts-node/register,tsx:ts-node/register
D:\projects\antlr4-graps\node_modules\ts-node\src\index.ts:312
throw new TSError(formatDiagnostics(diagnosticList, cwd, ts, lineOffset))
^
TSError: ⨯ Unable to compile TypeScript
test\test.ts (17,1): Cannot find name 'describe'. (2304)
The code that fails to compile is:
describe('antlr4-graps', function () {
which is totally valid code (the full version of that file is on Github). I double checked that mocha and chai are installed as local node modules, including their TS equivalents (@type/chai and @type/mocha).
How can I fix the compilation?
A:
You must import Mocha in your test file. I've reproduced a project with the description you gave of what you have installed and here I just need to add:
import "mocha";
at the start of a test file so that describe and its siblings become defined in the global space.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Run multiple .sh scripts from one .sh script? CentOS
How can I run multiple .sh scripts from one .sh script and run them all in separate terminals? I already have
/root/A.sh & /root/B.sh & /root/C.sh
The issue is it runs all of these in the same terminal at the same time, and without the &'s, it runs them when the previous one is finished running, how can I make them all startup at the same time in separate terminals?
A:
Here is one way leveraging gnome terminal tabbing capability :
gnome-terminal \
--tab-with-profile=Default --title=A.sh --command="/root/A.sh" \
--tab-with-profile=Default --title=B.sh --command="/root/B.sh" \
--tab-with-profile=Default --title=C.sh --command="/root/C.sh"&
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Remove Symbols Using Selenium Scraper (Python)
Below is a selenium web scraper that loops through the different tabs of this website page, selects the "export data" button, downloads the data, adds a "yearid" column, then loads the data into a MySQL table.
import sys
import pandas as pd
import os
import time
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from sqlalchemy import create_engine
button_text_to_url_type = {
'dashboard': 8,
'standard': 0,
'advanced': 1,
'batted_ball': 2,
'win_probability': 3,
'pitch_type': 4,
'pitch_values': 7,
'plate_discipline': 5,
'value': 6
}
download_dir = os.getcwd()
profile = FirefoxProfile("C:/Users/PATHTOFIREFOX")
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 'text/csv')
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", download_dir)
profile.set_preference("browser.download.folderList", 2)
driver = webdriver.Firefox(firefox_profile=profile)
today = datetime.today()
for button_text, url_type in button_text_to_url_type.items():
default_filepath = os.path.join(download_dir, 'Fangraphs Leaderboard.csv')
desired_filepath = os.path.join(download_dir,
'{}_{}_{}_Leaderboard_{}.csv'.format(today.year, today.month, today.day,
button_text))
driver.get(
"https://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=0&type={}&season=2018&month=0&season1=2018&ind=0&team=&rost=&age=&filter=&players=".format(
url_type))
driver.find_element_by_link_text('Export Data').click()
if os.path.isfile(default_filepath):
os.rename(default_filepath, desired_filepath)
print('Renamed file {} to {}'.format(default_filepath, desired_filepath))
else:
sys.exit('Error, unable to locate file at {}'.format(default_filepath))
df = pd.read_csv(desired_filepath)
df.str.replace('%', '')
df["yearid"] = datetime.today().year
df.to_csv(desired_filepath)
engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
.format(user="walker",
pw="password",
db="data"))
df.to_sql(con=engine, name='fg_test_hitting_{}'.format(button_text), if_exists='replace')
time.sleep(10)
driver.quit()
The scraper works perfectly, however, when I download the data, some columns download data with a % sign after an integer (i.e., 25%) which throws off my data types in MySQL. I have tried using df.str.replace('%','') and df.replace('%',''), but both have been unsuccessful. When scraping the data into a Pandas data frame, is it possible to alter the columns that contain the % symbol so that it just shows the integer? Should I be incorporating this into my loop or can I just add a line of code after I've established a Pandas data frame? Thanks in advance!
A:
df.replace doesn't do inplace replacements. It returns the modified dataframe
So replace this
df.str.replace('%', '')
by
df = df.replace('%', '', regex=True)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How is "ought" used in this King James Bible verse?
There's a use of the word "ought" from the Bible I don't understand.
I've highlighted the relevant word:
Acts 4:32
And the multitude of them that believed were of one heart and of one soul: neither said any of them that ought of the things which he possessed was his own; but they had all things common.
King James Version
I've checked dictionaries and I can't find a meaning of "ought" that makes sense to me within this passage.
A:
'Ought' is an archaic spelling of 'aught', which is another old word meaning 'anything' or 'any'.
So the meaning is:
None of the believers considered that any of the things they owned were theirs.
This is born out by more modern translations of the passage. E.g.
All the believers were one in heart and mind. No one claimed that
any of their possessions was their own, but they shared everything they had. (New International Version).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to compute the min-cost joint assignment to a variable set when checking the cost of a single joint assignment is high?
I want to compute the min-cost joint assignment to a set of variables. I have 50 variables, and each can take on 5 different values. So, there are 550 (a huge number) possible joint assignments. Finding a good one can be hard!
Now, the problem is that computing the cost of any assignment takes about 15-20 minutes. Finding an approximation to the min-cost assignment is also okay, doesn't have to be the global solution. But with this large computational load, what is a logical approach to finding a low-cost joint assignment?
A:
In general, if the costs of different assignments are completely arbitrary, there may be no better solution than a brute force search through the assignment space. Any improvements on that will have to come from exploiting some statistical structure in the costs that gives us a better-than-random chance of picking low-cost assignments to try.
Assuming that the costs of similar assignments are at least somewhat correlated, I'd give some variant of shotgun hill climbing a try. Alternatively, depending on the shape of the cost landscape, simulated annealing or genetic algorithms might work better, but I'd try hill climbing first just to get a baseline to compare against.
Of course, this all depends on what the cost landscape looks like. Without more detail on how the costs are calculated, you're unlikely to get very specific answers. If you don't even know what the cost landscape looks like yourself, well, then you'll just have to experiment with different search heuristics and see what works best.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Content is not responsive on Mobile devices (Bootstrap)
I'm working on a project but, I need help with making an element responsive. The text in the box will come over the image when you resize the browser. Do I have to add a class to the HTML of the item or to the css (the text can't be removed on the resized views). As you can see in the images. Normal look & Resized look
This is the HTML:
<div class="col-md-9">
<div class="item">
<div class="row">
<div class="col-md-3">
<a><img src="../images/pimg.png"></a>
</div> <!-- End Image -->
<div class="col-md-6">
<h4 class="item-name">Item1</h4>
<p class="item-desc">This is an item's description. Feel free to edit me :)
<a href="" class="btn btn-rounded btn-default btn-framed btn-small">Learn More</a>
</div>
<div class="col-md-3">
</div>
</div>
</div> <!-- End Middle -->
</div>
CSS (Item):
.item {
-moz-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.07);
-webkit-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.07);
box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.07);
background-color: #fff;
display: block;
}
.item:hover {
-moz-box-shadow: 1px 10px 15px rgba(0, 0, 0, 0.12);
-webkit-box-shadow: 1px 10px 15px rgba(0, 0, 0, 0.12);
box-shadow: 1px 10px 15px rgba(0, 0, 0, 0.12);
color: #000;
}
.item-name {
padding-left: 15px;
padding-top: 10px;
}
.item-desc {
padding-left: 15px;
font-size: 14px;
color: #A4A4A4;
}
CSS (button):
.btn {
-moz-transition: 0.3s ease;
-webkit-transition: 0.3s ease;
transition: 0.3s ease;
border: none;
outline: none !important;
font-weight: bold;
padding: 4px 12px 6px 12px;
}
.btn.btn-rounded {
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
}
.btn.btn-framed {
background-color: transparent;
border-style: solid;
border-width: 2px;
}
.btn.btn-framed.btn-default {
border-color: rgba(31, 31, 31, 0.2);
color: #1f1f1f;
}
.btn.btn-framed.btn-default:hover {
border-color: #03B01D;
}
.btn.btn-framed.btn-small {
-moz-border-radius: 14px;
-webkit-border-radius: 14px;
border-radius: 14px;
font-size: 10px;
font-weight: bold;
text-transform: uppercase;
padding: 4px 10px;
}
A:
You can use .img-fluid class for making image responsive:
<img src="../images/pimg.png" class="img-fluid">
Or fluid columns:
<div class="col-md-9">
<div class="item">
<div class="row">
<div class="col-md col-md-auto">
<a><img src="../images/pimg.png" width="150px" height="215px"></a>
</div> <!-- End Image -->
<div class="col-md">
<h4 class="item-name">Item1</h4>
<p class="item-desc">This is an item's description. Feel free to edit me :)
<a href="" class="btn btn-rounded btn-default btn-framed btn-small">Learn More</a>
</div>
</div>
</div> <!-- End Middle -->
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to tune spark executor number, cores and executor memory?
Where do you start to tune the above mentioned params. Do we start with executor memory and get number of executors, or we start with cores and get the executor number. I followed the link. However got a high level idea, but still not sure how or where to start and arrive to a final conclusion.
A:
The following answer covers the 3 main aspects mentioned in title - number of executors, executor memory and number of cores. There may be other parameters like driver memory and others which I did not address as of this answer, but would like to add in near future.
Case 1 Hardware - 6 Nodes, and Each node 16 cores, 64 GB RAM
Each executor is a JVM instance. So we can have multiple executors in a single Node
First 1 core and 1 GB is needed for OS and Hadoop Daemons, so available are 15 cores, 63 GB RAM for each node
Start with how to choose number of cores:
Number of cores = Concurrent tasks as executor can run
So we might think, more concurrent tasks for each executor will give better performance. But research shows that
any application with more than 5 concurrent tasks, would lead to bad show. So stick this to 5.
This number came from the ability of executor and not from how many cores a system has. So the number 5 stays same
even if you have double(32) cores in the CPU.
Number of executors:
Coming back to next step, with 5 as cores per executor, and 15 as total available cores in one Node(CPU) - we come to
3 executors per node.
So with 6 nodes, and 3 executors per node - we get 18 executors. Out of 18 we need 1 executor (java process) for AM in YARN we get 17 executors
This 17 is the number we give to spark using --num-executors while running from spark-submit shell command
Memory for each executor:
From above step, we have 3 executors per node. And available RAM is 63 GB
So memory for each executor is 63/3 = 21GB.
However small overhead memory is also needed to determine the full memory request to YARN for each executor.
Formula for that over head is max(384, .07 * spark.executor.memory)
Calculating that overhead - .07 * 21 (Here 21 is calculated as above 63/3)
= 1.47
Since 1.47 GB > 384 MB, the over head is 1.47.
Take the above from each 21 above => 21 - 1.47 ~ 19 GB
So executor memory - 19 GB
Final numbers - Executors - 17, Cores 5, Executor Memory - 19 GB
Case 2 Hardware : Same 6 Node, 32 Cores, 64 GB
5 is same for good concurrency
Number of executors for each node = 32/5 ~ 6
So total executors = 6 * 6 Nodes = 36. Then final number is 36 - 1 for AM = 35
Executor memory is : 6 executors for each node. 63/6 ~ 10 . Over head is .07 * 10 = 700 MB. So rounding to 1GB as over head, we get 10-1 = 9 GB
Final numbers - Executors - 35, Cores 5, Executor Memory - 9 GB
Case 3
The above scenarios start with accepting number of cores as fixed and moving to # of executors and memory.
Now for first case, if we think we dont need 19 GB, and just 10 GB is sufficient, then following are the numbers:
cores 5
# of executors for each node = 3
At this stage, this would lead to 21, and then 19 as per our first calculation. But since we thought 10 is ok (assume little overhead), then we cant switch # of executors
per node to 6 (like 63/10). Becase with 6 executors per node and 5 cores it comes down to 30 cores per node, when we only have 16 cores. So we also need to change number of
cores for each executor.
So calculating again,
The magic number 5 comes to 3 (any number less than or equal to 5). So with 3 cores, and 15 available cores - we get 5 executors per node. So (5*6 -1) = 29 executors
So memory is 63/5 ~ 12. Over head is 12*.07=.84
So executor memory is 12 - 1 GB = 11 GB
Final Numbers are 29 executors, 3 cores, executor memory is 11 GB
Dynamic Allocation:
Note : Upper bound for the number of executors if dynamic allocation is enabled. So this says that spark application can eat away all the resources if needed. So in
a cluster where you have other applications are running and they also need cores to run the tasks, please make sure you do it at cluster level. I mean you can allocate
specific number of cores for YARN based on user access. So you can create spark_user may be and then give cores (min/max) for that user. These limits are for sharing between spark and other applications which run on YARN.
spark.dynamicAllocation.enabled - When this is set to true - We need not mention executors. The reason is below:
The static params number we give at spark-submit is for the entire job duration. However if dynamic allocation comes into picture, there would be different stages like
What to start with :
Initial number of executors (spark.dynamicAllocation.initialExecutors) to start with
How many :
Then based on load (tasks pending) how many to request. This would eventually be the numbers what we give at spark-submit in static way. So once the initial executor numbers are set, we go to min (spark.dynamicAllocation.minExecutors) and max (spark.dynamicAllocation.maxExecutors) numbers.
When to ask or give:
When do we request new executors (spark.dynamicAllocation.schedulerBacklogTimeout) - There have been pending tasks for this much duration. so request. number of executors requested in each round increases exponentially from the previous round. For instance, an application will add 1 executor in the first round, and then 2, 4, 8 and so on executors in the subsequent rounds. At a specific point, the above max comes into picture
when do we give away an executor (spark.dynamicAllocation.executorIdleTimeout) -
Please correct me if I missed anything. The above is my understanding based on the blog i shared in question and some online resources. Thank you.
References:
http://site.clairvoyantsoft.com/understanding-resource-allocation-configurations-spark-application/
http://spark.apache.org/docs/latest/configuration.html#dynamic-allocation
http://spark.apache.org/docs/latest/job-scheduling.html#resource-allocation-policy
A:
Also, it depends on your use case, an important config parameter is:
spark.memory.fraction(Fraction of (heap space - 300MB) used for execution and storage) from http://spark.apache.org/docs/latest/configuration.html#memory-management.
If you dont use cache/persist, set it to 0.1 so you have all the memory for your program.
If you use cache/persist, you can check the memory taken by:
sc.getExecutorMemoryStatus.map(a => (a._2._1 - a._2._2)/(1024.0*1024*1024)).sum
Do you read data from HDFS or from HTTP?
Again, a tuning depend on your use case.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Securing the hardware of my computer against remote exploits
How can I secure the BIOS, video card, network card, PCI, etc. of the computer against remote exploit? I have heard that it is possible to remotely exploit a computer using vulnerabilities in these hardware devices, and that a compromise that occurs in this way may be hard to detect or remove.
So, how can I protect the hardware of my computer against remote exploits when connected to the Internet?
A:
There have been vulnerabilities caused in how the operating system uses hardware. For instance there have been vulnerabilities in systems using Intel processors, although this vulnerability was fixed in the operating system, just about every OS had to be fixed.
Drivers are usually the culprit. Recently there was a privilege escalation vulnerability with nvidia's Linux driver.
There have also been vulnerabilities in wireless devices. The most famous being the OSX Remote Code Execution vulnerability using malformed 802.11 frames.
Vulnerabilities in drivers are absolutely no different any other vulnerability (other than the fact that they are very uncommon and the payload usually runs in kernel-land). To defend your self, make sure your system is updated regularly. Disable hardware that you are not using, (Like NFC on your phone!)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Crash log analysis
I have a customer who has submitted to me about ten crash logs, and I have symbolized the logs in XCode. I just have no idea what this means. Please help me analyze this crash log:
Incident Identifier: 0E7CF1DF-B79C-4AE1-9FB3-7F13D916C844
CrashReporter Key: 0d530a5efc7ff5fff35f75efe047862f1e3ec068
Hardware Model: iPad1,1
Process: MyStocks [292]
Path: /var/mobile/Applications/B120B24C-1B9A-4077-AED3-1364779DBB84/MyStocks.app/MyStocks
Identifier: MyStocks
Version: ??? (???)
Code Type: ARM (Native)
Parent Process: launchd [1]
Date/Time: 2011-05-28 12:12:41.766 -0400
OS Version: iPhone OS 4.3.3 (8J3)
Report Version: 104
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x00000000, 0x00000000
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x32fa3a1c __pthread_kill + 8
1 libsystem_c.dylib 0x362063b4 pthread_kill + 52
2 libsystem_c.dylib 0x361febf8 abort + 72
3 libstdc++.6.dylib 0x30e7da64 __gnu_cxx::__verbose_terminate_handler() + 376
4 libobjc.A.dylib 0x32dcb06c _objc_terminate + 104
5 libstdc++.6.dylib 0x30e7be36 __cxxabiv1::__terminate(void (*)()) + 46
6 libstdc++.6.dylib 0x30e7be8a std::terminate() + 10
7 libstdc++.6.dylib 0x30e7bf5a __cxa_throw + 78
8 libobjc.A.dylib 0x32dc9c84 objc_exception_throw + 64
9 CoreFoundation 0x30adc1b8 -[NSObject(NSObject) doesNotRecognizeSelector:] + 96
10 CoreFoundation 0x30adb642 ___forwarding___ + 502
11 CoreFoundation 0x30a52178 _CF_forwarding_prep_0 + 40
12 MyStocks 0x0000cd28 +[YahooFinanceAPI stockIsValid:] (YahooFinanceAPI.m:31)
13 MyStocks 0x0000bb20 -[StockText check] (StockText.m:51)
14 Foundation 0x35e0f7c6 __NSFireTimer + 130
15 CoreFoundation 0x30aafa40 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 8
16 CoreFoundation 0x30ab1ec4 __CFRunLoopDoTimer + 844
17 CoreFoundation 0x30ab283e __CFRunLoopRun + 1082
18 CoreFoundation 0x30a42ebc CFRunLoopRunSpecific + 224
19 CoreFoundation 0x30a42dc4 CFRunLoopRunInMode + 52
20 GraphicsServices 0x36188418 0x36184000 + 17432
21 GraphicsServices 0x361884c4 0x36184000 + 17604
22 UIKit 0x30f5ed62 -[UIApplication _run] + 398
23 UIKit 0x30f5c800 UIApplicationMain + 664
24 MyStocks 0x00002c88 main (main.m:14)
25 MyStocks 0x00002c08 start + 44
Thread 1 name: Dispatch queue: com.apple.libdispatch-manager
Thread 1:
0 libsystem_kernel.dylib 0x32fa4fbc kevent + 24
1 libdispatch.dylib 0x32fcf032 _dispatch_mgr_invoke + 706
2 libdispatch.dylib 0x32fd003a _dispatch_queue_invoke + 86
3 libdispatch.dylib 0x32fcf5ea _dispatch_worker_thread2 + 186
4 libsystem_c.dylib 0x3620758a _pthread_wqthread + 258
5 libsystem_c.dylib 0x36207bbc start_wqthread + 0
Thread 2 name: WebThread
Thread 2:
0 libsystem_kernel.dylib 0x32fa1c00 mach_msg_trap + 20
1 libsystem_kernel.dylib 0x32fa1758 mach_msg + 44
2 CoreFoundation 0x30ab02b8 __CFRunLoopServiceMachPort + 88
3 CoreFoundation 0x30ab2562 __CFRunLoopRun + 350
4 CoreFoundation 0x30a42ebc CFRunLoopRunSpecific + 224
5 CoreFoundation 0x30a42dc4 CFRunLoopRunInMode + 52
6 WebCore 0x336c827e RunWebThread(void*) + 382
7 libsystem_c.dylib 0x3620630a _pthread_start + 242
8 libsystem_c.dylib 0x36207bb4 thread_start + 0
Thread 3:
0 libsystem_kernel.dylib 0x32fa1c00 mach_msg_trap + 20
1 libsystem_kernel.dylib 0x32fa1758 mach_msg + 44
2 CoreFoundation 0x30ab02b8 __CFRunLoopServiceMachPort + 88
3 CoreFoundation 0x30ab2562 __CFRunLoopRun + 350
4 CoreFoundation 0x30a42ebc CFRunLoopRunSpecific + 224
5 CoreFoundation 0x30a42dc4 CFRunLoopRunInMode + 52
6 Foundation 0x35da97f6 +[NSURLConnection(NSURLConnectionReallyInternal) _resourceLoadLoop:] + 206
7 Foundation 0x35d9c382 -[NSThread main] + 38
8 Foundation 0x35e0e5c6 __NSThread__main__ + 966
9 libsystem_c.dylib 0x3620630a _pthread_start + 242
10 libsystem_c.dylib 0x36207bb4 thread_start + 0
Thread 4 name: com.apple.CFSocket.private
Thread 4:
0 libsystem_kernel.dylib 0x32fa3c60 __select + 20
1 CoreFoundation 0x30ab58f2 __CFSocketManager + 582
2 libsystem_c.dylib 0x3620630a _pthread_start + 242
3 libsystem_c.dylib 0x36207bb4 thread_start + 0
Thread 5:
0 libsystem_kernel.dylib 0x32fa43ec __workq_kernreturn + 8
1 libsystem_c.dylib 0x362076d8 _pthread_wqthread + 592
2 libsystem_c.dylib 0x36207bbc start_wqthread + 0
Thread 0 crashed with ARM Thread State:
r0: 0x00000000 r1: 0x00000000 r2: 0x00000001 r3: 0x00000000
r4: 0x3fb8e48c r5: 0x00000006 r6: 0x002e46ec r7: 0x2fdfe7f8
r8: 0x00245f70 r9: 0x00000065 r10: 0x3f646b98 r11: 0x00000000
ip: 0x00000148 sp: 0x2fdfe7ec lr: 0x368d23bb pc: 0x337e1a1c
cpsr: 0x00000010
Binary Images:
0x1000 - 0xf2fff +MyStocks armv7 <5a9bc2940092fcb19620e8be465b8847> /var/mobile/Applications/B120B24C-1B9A-4077-AED3-1364779DBB84/MyStocks.app/MyStocks
0x2fe00000 - 0x2fe25fff dyld armv7 <bb9bfc7d242331d29a79adf7ef7aaa18> /usr/lib/dyld
0x30e06000 - 0x310f3fff libLAPACK.dylib armv7 <b855d60dac01310495453bddfd004f0d> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libLAPACK.dylib
0x31140000 - 0x31145fff liblaunch.dylib armv7 <f5ccc8234aea3ebd9a88bd37f0fa23ae> /usr/lib/system/liblaunch.dylib
0x3145a000 - 0x3145bfff libsystem_network.dylib armv7 <39bf0f48bd8539169a77f8f61cdcd4c9> /usr/lib/system/libsystem_network.dylib
0x31706000 - 0x31706fff libdnsinfo.dylib armv7 <21415179ffa03f949fa8cc851c6c31c7> /usr/lib/system/libdnsinfo.dylib
0x31716000 - 0x31723fff libbsm.0.dylib armv7 <0a1e2bb78d5138419ecad8ba0fe42fdd> /usr/lib/libbsm.0.dylib
0x31724000 - 0x31725fff libsystem_blocks.dylib armv7 <ccc041df3de73eafb7a59e74cdb1702b> /usr/lib/system/libsystem_blocks.dylib
0x31797000 - 0x317d9fff CoreAudio armv7 <c972fd5f8e89333ca680b9a33587f896> /System/Library/Frameworks/CoreAudio.framework/CoreAudio
0x31a71000 - 0x31a71fff Accelerate armv7 <7d5ad465049136afaa1f0d89aac600bc> /System/Library/Frameworks/Accelerate.framework/Accelerate
0x31bae000 - 0x31c57fff libxml2.2.dylib armv7 <5538d3f2c7d83b88b06168488fe6326b> /usr/lib/libxml2.2.dylib
0x31c58000 - 0x31c63fff libz.1.dylib armv7 <ac706bee36593dc683fd5a96a389d72e> /usr/lib/libz.1.dylib
0x31db6000 - 0x31e75fff CFNetwork armv7 <b09e0d53de9f3bc8bde494780f3cdd4f> /System/Library/Frameworks/CFNetwork.framework/CFNetwork
0x31e76000 - 0x31e78fff libgcc_s.1.dylib armv7 <a2631ac302f4310dae8367939e16b7c2> /usr/lib/libgcc_s.1.dylib
0x31e79000 - 0x31e96fff libsystem_info.dylib armv7 <48016be86e3f3cd9aeee1c6590e1ac6f> /usr/lib/system/libsystem_info.dylib
0x3219d000 - 0x321a1fff libGFXShared.dylib armv7 <a0772a32cd8b3b9194bb0c29807c1c5b> /System/Library/Frameworks/OpenGLES.framework/libGFXShared.dylib
0x321b0000 - 0x3220ffff libBLAS.dylib armv7 <0b36b2272aa33a8c9aa22d99c89d7189> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libBLAS.dylib
0x322de000 - 0x322ecfff OpenGLES armv7 <5a76beaeaa013f0cbf16e5cb154598ab> /System/Library/Frameworks/OpenGLES.framework/OpenGLES
0x32348000 - 0x3234ffff libbz2.1.0.dylib armv7 <0a082e1d475432959ba93aa3dbf7fb31> /usr/lib/libbz2.1.0.dylib
0x32350000 - 0x3295bfff WebCore armv7 <07941e59d0a33f94802c16c76238fddf> /System/Library/PrivateFrameworks/WebCore.framework/WebCore
0x32a50000 - 0x32a7ffff SystemConfiguration armv7 <1d73b8a159363f96bb9c039655c5eae6> /System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration
0x32c4c000 - 0x32d39fff libiconv.2.dylib armv7 <f4146ce07e3031ea8a81fa5516fd77d0> /usr/lib/libiconv.2.dylib
0x32d49000 - 0x32d4dfff libcache.dylib armv7 <d2f7fd2a352b3cd59c564be34b53cf80> /usr/lib/system/libcache.dylib
0x32d4e000 - 0x32d53fff MobileKeyBag armv7 <8c35c090bc373cb181fc26b961b8dba5> /System/Library/PrivateFrameworks/MobileKeyBag.framework/MobileKeyBag
0x32d54000 - 0x32d54fff vecLib armv7 <0c60cd0a60f43d2791d36cb357d30e3c> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/vecLib
0x32d7f000 - 0x32d82fff libmacho.dylib armv7 <43311c113a9d3182b7d007129819f029> /usr/lib/system/libmacho.dylib
0x32eac000 - 0x33239fff UIKit armv7 <c271b78464d93cb7bf28c6e49df293ba> /System/Library/Frameworks/UIKit.framework/UIKit
0x3323a000 - 0x3323dfff IOSurface armv7 <ad50e71624583d06b891344d832f9b08> /System/Library/PrivateFrameworks/IOSurface.framework/IOSurface
0x332b5000 - 0x3339afff CoreFoundation armv7 <a8444f997111304c9571b3ff974b769c> /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
0x333e6000 - 0x33425fff libSystem.B.dylib armv7 <33dcf9a403ae3fd5971d6030ada2fcab> /usr/lib/libSystem.B.dylib
0x3342f000 - 0x33431fff libAccessibility.dylib armv7 <d55f1553d14831a2a5435ae27ef75ef4> /usr/lib/libAccessibility.dylib
0x33485000 - 0x33487fff IOMobileFramebuffer armv7 <683f321680763e519d61541170ba2133> /System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer
0x334ce000 - 0x3357ffff WebKit armv7 <eb9a0d69c64b3127b2bffd71641add3b> /System/Library/PrivateFrameworks/WebKit.framework/WebKit
0x335e1000 - 0x33702fff CoreGraphics armv7 <65f6c8701b563542820a26b0dfc4f6a4> /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics
0x33771000 - 0x33771fff libsystem_sandbox.dylib armv7 <f47c01d627853b328e088b3fdd08e87d> /usr/lib/system/libsystem_sandbox.dylib
0x3377a000 - 0x337cffff libvDSP.dylib armv7 <0221caba81a235c5a896a835e2aac047> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libvDSP.dylib
0x337d0000 - 0x337e7fff libsystem_kernel.dylib armv7 <a06ec84e53bf32098b63c0caebdb45b6> /usr/lib/system/libsystem_kernel.dylib
0x3392a000 - 0x3392bfff libdyld.dylib armv7 <41a7b5e5d9983449ab33affed0f635ad> /usr/lib/system/libdyld.dylib
0x33a3b000 - 0x33a70fff AddressBook armv7 <3f2071a77bc134cd82065eef90d4082f> /System/Library/Frameworks/AddressBook.framework/AddressBook
0x33a84000 - 0x33b9efff libicucore.A.dylib armv7 <bada0c2725bb31a483d5adf9aaf1f8df> /usr/lib/libicucore.A.dylib
0x33cdf000 - 0x33d1bfff libGLImage.dylib armv7 <9d97699e44ee3651ba4ac37e5adec35b> /System/Library/Frameworks/OpenGLES.framework/libGLImage.dylib
0x33e2d000 - 0x33e9cfff ProofReader armv7 <6d843c6aecdd37ae84baa40af8ad7e65> /System/Library/PrivateFrameworks/ProofReader.framework/ProofReader
0x33e9d000 - 0x33ea6fff CoreVideo armv7 <ea847e6dba2d36b1826b255c73b39539> /System/Library/Frameworks/CoreVideo.framework/CoreVideo
0x33fb0000 - 0x33fbdfff libdispatch.dylib armv7 <9a0511ad5ebc3db898f1f49ed1a73d34> /usr/lib/system/libdispatch.dylib
0x340a5000 - 0x340d8fff AppSupport armv7 <0217468bd9f839229a47910b7816b3d5> /System/Library/PrivateFrameworks/AppSupport.framework/AppSupport
0x340dc000 - 0x35b2afff TextInput armv7 <f242acc046073c1598195dd26fd8ad6f> /System/Library/PrivateFrameworks/TextInput.framework/TextInput
0x35b2b000 - 0x35b2bfff libCVMSPluginSupport.dylib armv7 <42d8aa2a31843a6e8bfff745644a7ba5> /System/Library/Frameworks/OpenGLES.framework/libCVMSPluginSupport.dylib
0x35b2c000 - 0x35c4bfff Foundation armv7 <09ff368178c5321c9715b9c8d491d53f> /System/Library/Frameworks/Foundation.framework/Foundation
0x35c61000 - 0x35c67fff liblockdown.dylib armv7 <14c89b7346433c1f8675f454531f6ca3> /usr/lib/liblockdown.dylib
0x35d27000 - 0x35debfff libobjc.A.dylib armv7 <6b51e76fde9f381bb7b3bc5badbfee3a> /usr/lib/libobjc.A.dylib
0x35dec000 - 0x35e24fff IOKit armv7 <80ae313ad69d3363935c88e51a11862d> /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit
0x35e25000 - 0x35f51fff libmecabra.dylib armv7 <113de5f9858c32b8b158bfdc68042a97> /usr/lib/libmecabra.dylib
0x35f72000 - 0x35f91fff Bom armv7 <b178e3efb4d733c694bd5a55e57a314f> /System/Library/PrivateFrameworks/Bom.framework/Bom
0x3615c000 - 0x36168fff SpringBoardServices armv7 <c68262667ac8397a949ce4e92dfec7db> /System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices
0x36184000 - 0x36190fff GraphicsServices armv7 <ff78a9636e933f0dbd222f8d26209788> /System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
0x3654e000 - 0x36552fff AssetsLibraryServices armv7 <e1cbfe599c96369ca4bdb0dd99d3cd9f> /System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices
0x36561000 - 0x365abfff libstdc++.6.dylib armv7 <b2cac408951c3f3c9ba3cf563e54ce81> /usr/lib/libstdc++.6.dylib
0x3661a000 - 0x3662ffff libresolv.9.dylib armv7 <e92cfbb83f7b330db19181e797bb3f7b> /usr/lib/libresolv.9.dylib
0x367ef000 - 0x3689efff QuartzCore armv7 <ef9632c9781f3101916b65e9faae1579> /System/Library/Frameworks/QuartzCore.framework/QuartzCore
0x3689f000 - 0x36920fff libsystem_c.dylib armv7 <a7077267b6743ed3bbdd86d4380c75d9> /usr/lib/system/libsystem_c.dylib
0x3698b000 - 0x3698cfff libremovefile.dylib armv7 <e8858a499d663e6a9e3c188521273cc1> /usr/lib/system/libremovefile.dylib
0x369f7000 - 0x369f8fff TextInput_fr armv7 <df896624a716399f877087d35f6c6d86> /System/Library/TextInput/TextInput_fr.bundle/TextInput_fr
0x36bfd000 - 0x36c02fff libnotify.dylib armv7 <9d7198e91de9386a9e5ea43608a66a57> /usr/lib/system/libnotify.dylib
0x36c09000 - 0x36c4ffff CoreTelephony armv7 <af7d1e770e5a3ffd8834a57fb5d40557> /System/Library/Frameworks/CoreTelephony.framework/CoreTelephony
0x36cbb000 - 0x36cf3fff libCGFreetype.A.dylib armv7 <ccea634795153164a681f0f311f4461d> /System/Library/Frameworks/CoreGraphics.framework/Resources/libCGFreetype.A.dylib
0x36cf4000 - 0x36cf5fff CoreSurface armv7 <7b83cd757da73e6e826693c29296d3fa> /System/Library/PrivateFrameworks/CoreSurface.framework/CoreSurface
0x36d0d000 - 0x36da2fff ImageIO armv7 <d520e3241d1130e8ac1375ee0f2c1095> /System/Library/Frameworks/ImageIO.framework/ImageIO
0x36ded000 - 0x36df4fff AggregateDictionary armv7 <ab9777b39e8e3026ad64dc90323cad7e> /System/Library/PrivateFrameworks/AggregateDictionary.framework/AggregateDictionary
0x36e84000 - 0x36eadfff MobileCoreServices armv7 <57fef84bdc17301d8bf53ba0fb967fe6> /System/Library/Frameworks/MobileCoreServices.framework/MobileCoreServices
0x36efd000 - 0x37001fff JavaScriptCore armv7 <61a94142e2d23dafa2964190dd46e9e3> /System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore
0x37002000 - 0x37039fff Security armv7 <6599f42a910b3b31a0e1d98c883d61cb> /System/Library/Frameworks/Security.framework/Security
0x37058000 - 0x37071fff libRIP.A.dylib armv7 <4825c3e392983aba947eca06555e4480> /System/Library/Frameworks/CoreGraphics.framework/Resources/libRIP.A.dylib
0x3716a000 - 0x3716ffff libsystem_dnssd.dylib armv7 <c7cfe523e2d73521abc01587313ef730> /usr/lib/system/libsystem_dnssd.dylib
0x371ba000 - 0x371bcfff MobileInstallation armv7 <94b6d6c5d9883175af26764567528127> /System/Library/PrivateFrameworks/MobileInstallation.framework/MobileInstallation
0x37297000 - 0x372e8fff libsqlite3.dylib armv7 <8a41cc6a6d9332308bc415d27577fd24> /usr/lib/libsqlite3.dylib
0x3734c000 - 0x374a0fff AudioToolbox armv7 <6619c8c13f8d328e923e797fa8d0df23> /System/Library/Frameworks/AudioToolbox.framework/AudioToolbox
0x374a4000 - 0x374c4fff PrintKit armv7 <e5a01ca9083a36afacc08611a398e2ad> /System/Library/PrivateFrameworks/PrintKit.framework/PrintKit
0x374c5000 - 0x374cafff libcopyfile.dylib armv7 <e57c2b9054b831d9a37119baaa4947cb> /usr/lib/system/libcopyfile.dylib
0x37539000 - 0x37576fff CoreText armv7 <fb6a72faec2330c4b2cd33c2e9c59588> /System/Library/Frameworks/CoreText.framework/CoreText
A:
I bet two bucks on a missing method at YahooFinanceAPI:31 +[YahooFinanceAPI stockIsValid:].
A:
The culprit appears to be here:
64 9 CoreFoundation 0x30adc1b8 -[NSObject(NSObject) doesNotRecognizeSelector:]
96 10 CoreFoundation 0x30adb642 __forwarding
502 11 CoreFoundation 0x30a52178 _CF_forwarding_prep_0
40 12 MyStocks 0x0000cd28 +[YahooFinanceAPI stockIsValid:] (YahooFinanceAPI.m:31)
Like Jano said, possibly a missing method (if that's the case, there should be a warning somewhere).
Either that, or maybe you're accessing an invalid pointer (something you "over released"?).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Play! framework referential integrity contraint on delete
I created some Model object to represent a company with several clients, and an invoice object that consists of a company and client combination and several invoice lines. I have created the following Model objects:
@Entity
public class Company extends Model {
@OneToMany(mappedBy="company")
public Set<Client> clients;
}
@Entity
public class Client extends Model {
@ManyToOne
public Company company;
}
@Entity
public class Invoice extends Model {
@ManyToOne
public Company company;
@ManyToOne
public Client client;
@OneToMany(mappedBy="invoice", cascade=CascadeType.ALL)
public Set<InvoiceLine> invoiceLines;
}
@Entity
public class InvoiceLine extends Model {
@ManyToOne
public Invoice invoice;
}
The test:
@Test
public void testModels() {
Client client = createClient();
Company company = createCompany();
company.clients = new HashSet<Client>();
company.clients.add(client);
company.save();
Invoice invoice = createInvoice(client, company);
InvoiceLine invoiceLine1 = createInvoiceLine(invoice);
InvoiceLine invoiceLine2 = createInvoiceLine(invoice);
Set<InvoiceLine> invoiceLines = new HashSet<InvoiceLine>();
invoiceLines.add(invoiceLine1);
invoiceLines.add(invoiceLine2);
invoice.invoiceLines = invoiceLines;
invoice.save();
Company retrievedCompany = Company.find("byName", company.name).first();
assertNotNull(retrievedCompany);
assertEquals(1, retrievedCompany.clients.size());
assertEquals(2, InvoiceLine.count());
assertEquals(1, Invoice.deleteAll());
assertNull(Invoice.all());
assertNull(InvoiceLine.all());
}
When running a test that creates an invoice with two invoice lines, and try to delete this invoice, I get the following error:
org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation:
"FK3004B0A1F4110EF6: PUBLIC.INVOICELINE FOREIGN KEY(INVOICE_ID) REFERENCES >PUBLIC.INVOICE(ID)";
SQL statement: delete from Invoice [23003-149]
What am I doing wrong?
A:
Have you tried this with invoice.delete()? The problem is that deleteAll() doesn't cascade the delete operation.
deleteAll() uses a javax.persistence.Query internally, while delete() uses the EntityManager's remove() method. The cascading in JPA is handled by JPA and not by the database, and JPA does not cascade bulk deletes like the one executed by deleteAll().
Check this link for more info on bulk delete/update.
Also: adding the InvoiceLine entities to Invoice is redundant if you are already setting Invoice as the parent in createInvoiceLine(). Just do invoice.refresh() before executing the asserts.
Maybe the following unit test clears things up.
The Parent1 is like your Invoice. While Child1 is like your InvoiceLine.
import java.util.*;
import javax.persistence.*;
import org.junit.*;
import play.test.*;
import models.*;
public class Parent1Test extends UnitTest {
public Parent1 p;
public Child1 c1;
public Child1 c2;
public Child1 c3;
@Before
public void setUp() {
Fixtures.deleteAllModels();
p = new Parent1();
c1 = new Child1();
c2 = new Child1();
c3 = new Child1();
}
public void byAddingParentToChilds() {
c1.parent = p;
c2.parent = p;
c3.parent = p;
c1.save();
c2.save();
c3.save();
p.refresh();
}
@Test
public void testByAddingParentToChilds() {
byAddingParentToChilds();
assertEquals(p.id, c1.parent.id);
assertEquals(3, Child1.count());
}
public void byAddingChildsToParent() {
p.childs = new ArrayList<Child1>();
p.childs.add(c1);
p.childs.add(c2);
p.childs.add(c3);
p.save();
}
@Test
public void testByAddingChildsToParent() {
// By adding childs
byAddingChildsToParent();
c1.refresh();
assertEquals(3, Child1.count());
// This will be null, because you added the childs to the
// parent while the childs are the owning side of the
// relation.
assertNull(c1.parent);
}
@Test
public void testDeletingAfterAddingParentToChilds() {
byAddingParentToChilds();
p.delete();
assertEquals(0, Parent1.count());
assertEquals(0, Child1.count());
}
@Test
public void testDeletingAfterAddingChildsToParent() {
byAddingChildsToParent();
p.delete();
assertEquals(0, Parent1.count());
assertEquals(0, Child1.count());
}
@Test(expected=PersistenceException.class)
public void testDeleteAllAfterAddingParentToChilds() {
byAddingParentToChilds();
// The cascading doesn't work for deleteAll() so this line
// will throw an exception because the child elements still
// reference the parent.
assertEquals(1, Parent1.deleteAll());
}
@Test
public void testDeleteAllAfterAddingChildsToParent() {
byAddingChildsToParent();
assertEquals(1, Parent1.deleteAll());
assertEquals(0, Parent1.count());
// Again the cascading doesn't work for deleteAll()
assertEquals(3, Child1.count());
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery notifications, first not showing
I am using AJAX extensively and my PHP based notification system was not sufficient.
I have this function:
<script>
function user_notify($string, $class){
if($class == null){
$class = 'error';
}
$('<div class="' + $class + '"><div class="notification-text">' + $string + '</div></div>').hide().appendTo('#system-notifications').fadeIn('slow');
}
function DeleteTask(SpanName, TaskId){
if (confirm("Are you sure you want to delete this task?")) {
var curDateTime = new Date(); //For IE
var status = document.getElementById('status');
var poststr = "uniqueID=" + curDateTime.getTime() ;
var SpanName = SpanName;
if(SpanName == 'project_todos_complete'){
var showCompleted = 1;
} else {
var showCompleted = 0;
}
//alert (SpanName);
makePOSTRequest('http://*****webdesigns.com/project_manager/include/ajax/global.php?action=delete_task&showCompleted=' + showCompleted + '&id=' + TaskId, poststr, SpanName);
}
if(ajax_status == 4){
user_notify('Task deleted.', 'success');
ajax_status = null;
}
}
</script>
I have a global javascript variable that holds the readyState. If 4 is a response from the server, we can assume the AJAX was successful (I know, not neccessarily the cgi/php is execute if any). So I store that, and within the function that called the AJAX post, if the readyState is 4, I call the user_notify function.
It works beautifully with one exception: the first action that should trigger a notification does not. All consecutive actions successfully generate a message. It's not a specific action that doesn't work, just the first one.
The html:
<body>
<div id="system-notifications"></div>
<div class="wrapper">...</div>
What am I missing here?
UPDATE:
I am in the process of moving legacy javascript/Ajax calls to jQuery/Ajax. Everything works except one aspect: the targeted div does not 'refresh' with the return data from the .ajax jQuery call. The notification pops up (the first time and all consecutive times), the php executes (refreshing the page verfies this), but the div does not update with the html that the PHP script generates.
$('form#addToDoForm').submit(function(){
var project_id = $('#addToDoForm input[name=project_id]');
var assigned_id = $('#addToDoForm input[name=assigned_user_id]');
var description = $('#addToDoForm textarea[name=description]');
var responsible_id = $('#addToDoForm input[name=responsible_user_id :selected]');
alert(responsible_id.val());
return false;
var due = $('#addToDoForm input[name=due]');
var result_div = 'project_todos_' + project_id;
var query_string = 'action=add_to_do&id=' + project_id;
var ajax_url = 'http://avwebdesigns.com/basecamp/include/ajax/global.php?' + query_string;
var successMessage = '<b>' + description.val() + '</b> added.';
var data =
'project_id=' + project_id.val() +
'&assigned_user_id=' + assigned_id.val() +
'&responsible_user_id=' + responsible_id.val() +
'&description=' + encodeURIComponent(description.val()) +
'&due=' + encodeURIComponent(due.val()); // encodeURIComponent()
$.ajax({
type: 'POST',
url: ajax_url,
data: data,
cache: false,
success: function(data){
$('#'+result_div).html(data); // $('#'+result_div).html(data.returnValue);
user_notify(successMessage, 'success');
},
error:function(data){
$('#'+result_div).html(data);
user_notify(failureMessage, 'error');
}
});
return false;
});
Any ideas?
A:
You are missing the non-blocking characteristics of an AJAX call probably. I can't really tell what makePOSTRequest does, but judging from your design I assume you expect it to be synchronous where it probably is not. Due to the asynchronous nature of an AJAX call, you need to pass a callback function to the call that is called when the AJAX request completes.
What probably happens in your case is that makePOSTRequest immediately returns and because the first request hasn't finished yet, ajax_status will not be 4 yet. Then, by the time the second request is sent, your first will have completed and your global variable will have been set to 4, so this time it works and this is also the cause why it works in all subsequent attempts.
This shows another flaw in your design: it's actually a very bad idea to capture the status of an AJAX request in a global variable. These requests are potentially sent in a concurrent fashion so you would have several requests that share one and the same variable - this calls for a 'race condition'. Have a look at the examples in the Ajax section of the jQuery documentation to see how to handle this correctly with the help of a callback function.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Elements in View Controller Disappear When Clicking or Tapping Them
I am developing an app on XCode using Swift 2 and have run into an error with my UI. I have placed a UILabel, UITextView, and UITextField on the View Controller of interest.
Before inputting the UITextField, everything worked fine. I inserted the text field and assigned the proper constraints and when simulating the app, clicking on the text field will cause all of the UI elements to disappear or the alpha to go instantaneously to zero (I'm not sure which of the two is actually happening).
I'm not receiving any feedback via the console and the app itself does not crash.
Here is my code:
//Declare the following UI objects to be manipulated
@IBOutlet weak var labelOneTitle: UILabel!
@IBOutlet weak var textDescription: UITextView!
@IBOutlet weak var fieldInput: UITextField!
override func viewDidLayoutSubviews() {
//Set UI object alphas to zero prior to loading the view
labelOneTitle.alpha = 0
textDescription.alpha = 0
fieldInput.alpha = 0
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
UIView.animateWithDuration(2) { () -> Void in
self.labelOneTitle.alpha = 1
}
UIView.animateWithDuration(3) { () -> Void in
self.textDescription.alpha = 1
}
UIView.animateWithDuration(3) { () -> Void in
self.fieldInput.alpha = 1
}
}
A:
It might be the UIViewController.viewDidLayoutSubviews rechecking all the constraints and reconfiguring the view as per the the class reference:
When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls this method. However, this method being called does not indicate that the individual layouts of the view's subviews have been adjusted. Each subview is responsible for adjusting its own layout.
Your view controller can override this method to make changes after
the view lays out its subviews. The default implementation of this
method does nothing.
When you click on the UITextField the keyboard appears (Probably) and thus recalling the method to set the alpha of all your UI Elements to 0.
If you'd move setting the alpha's to 0 to the viewDidLoad() than the problem might go away.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Developing via Remote Desktop
Has anybody any successful remarks about having a team working via Remote Desktop?
In many workplaces, we put end users via Citrix and the applications on a central, powerful server. Sometimes the clients are in the same building as the server, but often, they are remote.
There could be some huge benefits for me to put my developers on Windows XP or Vista instances running on a couple servers with Hyper-V.
I'm worried that RDP/RDC via the internet would be too slow for somebody to be able to develop efficiently.
I'm sure I can hear plenty of bad things about it... are there any people out there that have had success?
A:
I have seen a situation where the attempt was made to do this with a sattelite office. It was done for a java development team using various java IDE tools. The result wasn't regarded as a success, and the company brought the team back into a central London office at considerable expense.
For someone doing this on a day-in day-out basis on interactive software, the result isn't really very pleasant. For something that mainly uses text-based tools such as vim and unix command line tools, it works somewhat better. At one point I had XVNC going over a 128 Kbit DSL link (of a type that was prevalent in New Zealand at the time) and could do work on an Oracle-based data warehouse at a remote location quite readily. The level of interactivity required by the tooling made them much less sensitive to the slow link than a Windows-based IDE.
So, I'll invoke the 'it depends' argument with some qualifications:
I would not recommend it for a modern IDE, and certainly not for something heavily graphical like Dreamweaver, BI Development Studio or Informatica.
For a textual environment like traditional unix development tools it could probably be made to work quite well. These user interfaces are much less sensitive to latency than a direct-manipulation user interface.
I'm something of a believer in the 'best tools' principle. Going out of your way to give a second-rate user interface to a development team will give off negative signals. The cost saving from doing this is likely to be minimal and it will annoy some of your team members. Even if it can be made to work reasonably well you are still making a value statement by doing this. Weigh the cost saving against the cost of replacing one or more of your key development staff.
A:
If you're not worried about the latency on audio and fast-moving imagery and you're not developing anything dependent on 3D hardware, you'll likely be fine.
I've never used it in a team environment, but I use my laptop RDP'd into my workstation all day and love it.
A:
We connect to our development environments using RDP and locally the performance is great. It slows a bit over VPN, but is still acceptably responsive.
Turn off all the windows animation functionality, desktop background, etc. and that will help considerably.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why bother down voting?
When I think of the alternatives to down voting, I wonder if there is any reason to down vote anything.
If one encounters abusive or spam-like posts one can flag them.
If one thinks a question is inappropriate one can vote to close it.
If one thinks something is incorrect one can post a comment or an answer clarifying what one thinks is correct.
So I don't see why I should down vote anything going forward. Is there any reason to use the down vote that isn't covered by flagging, voting to close, making a comment or writing an answer?
A:
From the help center [bolded mine]:
Voting up a question or answer signals to the rest of the community that a post is interesting, well-researched, and useful, while voting down a post signals the opposite: that the post contains wrong information, is poorly researched, or fails to communicate information. The more that people vote on a post, the more certain future visitors can be of the quality of information contained within that post – not to mention that upvotes are a great way to thank the author of a good post for the time and effort put into writing it!
So while you are correct in stating that there are other means to evaluate the quality of a post, some of them are not immediately visible to other (esp. low-rep) users (like e.g. a flag). Voting down is giving an overt signal to others that there is something wrong with the post. It changes the position of an answer and does not make it look like it was e.g. just as legitimate as another answer just posted.
So while you mention moderation tools, the voting system is first and foremost a tool to signal the quality of a post. Well, it should be - there are a number of exceptions especially in those questions that make it into the "Hot Network Questions".
In other words: The idea is that it is in the responsibility of the community to do both - helping the moderators in moderating the community with whatever tools the reputation threshold is granting and voting according to the quality of the post.
Bonus: A post rapidly voted down is immediately made invisible for all but the highest rep users and is automatically put on the moderators' task list. In other words: Some guys doing this for a hobby [us moderators] do not have to actively intervene and invest time for the post to disappear.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CSS text starts a new line in float left
I'm getting little problem in arranging my elements while using css float left command it floats to the left and repeat the same thing on the next line but when any title with image is bigger the next entry goes to the next line and leaving space behind it which is really annoying for me
Here is my CSS
#main {
width:100%;
margin-top:55px;
margin-left:45px;
margin-right:35px;
}
#body {
float:left;
margin-left:14px;
margin-right:24px;
alignment-adjust:central;
margin-top:14px;
}
#tablealign {
text-align:center;
margin-top:20px;
}
#text {
color:#333;
text-decoration:none;
font-size:12px;
margin-top:12px;
text-align:center;
}
#image{
margin-left:5px;
alignment-adjust:central;
text-align:center;
}
HTML example code [Note I am using php for this]
<center><div id="body"><div id="tablealign"><a href="Videos.php?ID=345"><img id="image" src=https://i1.ytimg.com/vi/8IpPx1vdJV8/maxresdefault.jpg width=200 height=150></a></div><div id="text"><a href="Videos.php?ID=345">GTA IV Lag Fix on Windows 7 -<br />
YouTube</a></div></div></center>
It appears like this
A:
you need add to your #text id in css:
max-height:30px;
overflow:hidden;
this is an example : http://jsfiddle.net/pL79v/1/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Detect changes in a property after the value is changed
I'm currently working in a project with Qt QML and I have a type that has a property (holds a JavaScript Object), and its reference changes constantly.
What I want to do is to detect the changes in this property and compare with a cached one.
I took a look into Qt Property Binding, but the callback function is executed before the change occurs and the property gets the value of the return of the callback. I want something to be executed after that (the property change), because I need to have the property dataset updated before emitting the signals (in the code the signals are emitted with kind of reflection thing, in the forEach callback).
What I've done so far:
Item {
id: root
property var dataset
Component.onCompleted: {
dataset = Qt.binding(function(){
return MediaWatcherHelper.formatDataset(internals.metadata);
// I want this code to execute after the binding occurs, but I obviously can't execute things after the return.
MediaWatcherHelper.detectChanges(root.dataset, internals.cache)
.forEach(it => root[`${it}Change`](dataset[it]));
internals.cache = root.dataset; // And update the cache
});
}
signal trackIdChange(string trackId)
signal albumChange(string album)
signal artistChange(var artist)
signal titleChange(string title)
signal urlChange(url url)
}
A:
You always can keep the previous value and update it accordingly.
property int myCurrentValue: 10
property int myLastValue: myCurrentValue
onMyCurrentValueChanged: {
console.log("current: " + myCurrentValue + ", last:" + myLastValue)
myLastValue = myCurrentValue;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Select all checkbox get selected by default when I don't have any records
I am getting problem by getting my select all button checked when there are no records.
Below is my code:
<input type="checkbox" ng-model="selectAll" ng-model-options="{getterSetter: true}"/>
var getAllSelected= function () {
var selectedItems = $scope.items.filter(function (item) {
return item.selected;
});
return selectedItems.length === $scope.items.length;
}
var setAllSelected = function (value) {
angular.forEach($scope.items, function (item) {
item.selected = value;
});
}
$scope.selectAll = function (value) {
if (value !== undefined) {
return setAllSelected(value);
} else {
return getAllSelected();
}
}
So problem is below condition is getting true when I don't have records in my $scope.items:
return selectedItems.length === $scope.items.length;
A:
I have tried your code with below snippet:
var app = angular.module('app', [])
.controller('ctrl', ['$scope', function($scope) {
$scope.value = false;
$scope.items = [{},{}];
var getAllSelected= function () {
var selectedItems = $scope.items.filter(function (item) {
return item.selected;
});
return $scope.items.length != 0 && selectedItems.length === $scope.items.length;
}
var setAllSelected = function (value) {
console.log(value);
angular.forEach($scope.items, function (item) {
item.selected = value;
});
}
$scope.selectAll = function (value) {
console.log(value);
if (value !== undefined) {
return setAllSelected(value);
} else {
return getAllSelected();
}
}
}]);
and
<input type="checkbox" ng-model="selectAll" ng-model-options="{getterSetter: true}"/>
and it is working fine..
you can check here: https://plnkr.co/edit/oUjNQGI363SJPMeaWA6A?p=preview
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mouse Enter & Mouse Leave on a form
I have a form with child controls.
I want when user move mouse over the form, the form will be closed.
So I catch mouse enter and move leave on the form. But if I move mouse on any controls in form, mouse leave event will be also caught.
Please help me to solve this problem. Thanks.
UPDATE:
When the cursor's position is on the form's caption region (this region is called non-client region). I move mouse out of this region, I can't receive the WM_MOUSELEAVE message as well as WM_NCMOUSELEAVE. Please help me in this problem. I want to receive a message when move mouse out of this region. Thanks.
A:
Essentially you want to check if the cursor is in the scope of the control. Here is the solution:
(1) Add a Panel in the form which is the same size as your Form, and move all controls in the form to the panel. It's easy to change: open MyForm.designer.cs, add the panel, and change all statements like this.Controls.Add(myLabel); to this.myPanel.Controls.Add(myLabel);.
(2) Deal with MouseEnter and MouseLeave events of the panel you added.
myPanel.MouseEnter += (sender, e) =>
{
//enter
};
myPanel.MouseLeave += (sender, e) =>
{
if (Cursor.Position.X < myPanel.Location.X
|| Cursor.Position.Y < myPanel.Location.Y
|| Cursor.Position.X > myPanel.Location.X + myPanel.Width
|| Cursor.Position.Y > myPanel.Location.Y + myPanel.Height)
{
//out of scope
}
};
(3) Why not use Form in step 2? Why do we need a Panel with the same size? Try it yourself. The narrow border of the form will make you crazy.
(4) You can make the if statements in step 2 to an extension method, which is helpful to furthur usage.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the cut-off frequency of a moving average filter?
I need to design a moving average filter that has a cut-off frequency of 7.8 Hz. I have used moving average filters before, but as far as I'm aware, the only parameter that can be fed in is the number of points to be averaged... How can this relate to a cut-off frequency?
The inverse of 7.8 Hz is ~130 ms, and I'm working with data that are sampled at 1000 Hz. Does this imply that I ought to be using a moving average filter window size of 130 samples, or is there something else that I'm missing here?
A:
The moving average filter (sometimes known colloquially as a boxcar filter) has a rectangular impulse response:
$$
h[n] = \frac{1}{N}\sum_{k=0}^{N-1} \delta[n-k]
$$
Or, stated differently:
$$
h[n] = \begin{cases}
\frac{1}{N}, && 0 \le n < N \\
0, && \text{otherwise}
\end{cases}
$$
Remembering that a discrete-time system's frequency response is equal to the discrete-time Fourier transform of its impulse response, we can calculate it as follows:
$$
\begin{align}
H(\omega) &= \sum_{n=-\infty}^{\infty} x[n] e^{-j\omega n} \\
&= \frac{1}{N}\sum_{n=0}^{N-1} e^{-j\omega n}
\end{align}
$$
To simplify this, we can use the known formula for the sum of the first $N$ terms of a geometric series:
$$
\sum_{n=0}^{N-1} e^{-j\omega n} = \frac{1-e^{-j \omega N}}{1 - e^{-j\omega}}
$$
What we're most interested in for your case is the magnitude response of the filter, $|H(\omega)|$. Using a couple simple manipulations, we can get that in an easier-to-comprehend form:
$$
\begin{align}
H(\omega) &= \frac{1}{N}\sum_{n=0}^{N-1} e^{-j\omega n} \\
&= \frac{1}{N} \frac{1-e^{-j \omega N}}{1 - e^{-j\omega}} \\
&= \frac{1}{N} \frac{e^{-j \omega N/2}}{e^{-j \omega/2}} \frac{e^{j\omega N/2} - e^{-j\omega N/2}}{e^{j\omega /2} - e^{-j\omega /2}}
\end{align}
$$
This may not look any easier to understand. However, due to Euler's identity, recall that:
$$
\sin(\omega) = \frac{e^{j\omega} - e^{-j\omega}}{j2}
$$
Therefore, we can write the above as:
$$
\begin{align}
H(\omega) &= \frac{1}{N} \frac{e^{-j \omega N/2}}{e^{-j \omega/2}} \frac{j2 \sin\left(\frac{\omega N}{2}\right)}{j2 \sin\left(\frac{\omega}{2}\right)} \\
&= \frac{1}{N} \frac{e^{-j \omega N/2}}{e^{-j \omega/2}} \frac{\sin\left(\frac{\omega N}{2}\right)}{\sin\left(\frac{\omega}{2}\right)}
\end{align}
$$
As I stated before, what you're really concerned about is the magnitude of the frequency response. So, we can take the magnitude of the above to simplify it further:
$$
|H(\omega)| = \frac{1}{N} \left|\frac{\sin\left(\frac{\omega N}{2}\right)}{\sin\left(\frac{\omega}{2}\right)}\right|
$$
Note: We are able to drop the exponential terms out because they don't affect the magnitude of the result; $|e^{j\omega}| = 1$ for all values of $\omega$. Since $|xy| = |x||y|$ for any two finite complex numbers $x$ and $y$, we can conclude that the presence of the exponential terms don't affect the overall magnitude response (instead, they affect the system's phase response).
The resulting function inside the magnitude brackets is a form of a Dirichlet kernel. It is sometimes called a periodic sinc function, because it resembles the sinc function somewhat in appearance, but is periodic instead.
Anyway, since the definition of cutoff frequency is somewhat underspecified (-3 dB point? -6 dB point? first sidelobe null?), you can use the above equation to solve for whatever you need. Specifically, you can do the following:
Set $|H(\omega)|$ to the value corresponding to the filter response that you want at the cutoff frequency.
Set $\omega$ equal to the cutoff frequency. To map a continuous-time frequency to the discrete-time domain, remember that $\omega = 2\pi \frac{f}{f_s}$, where $f_s$ is your sample rate.
Find the value of $N$ that gives you the best agreement between the left and right hand sides of the equation. That should be the length of your moving average.
A:
If $N$ is the length of the moving average, then an approximate cut-off frequency $F_{co}$ (valid for $N >= 2$) in normalized frequency $F=f/fs$ is:
$F_{co} = \frac {0.442947} {\sqrt{N^2-1}}$
The inverse of this is
$N = \frac {\sqrt{0.196202 + F_{co}^2}}{F_{co}}$
This formula is asymptotically correct for large N, and has about 2% error for N=2, and less than 0.5% for N>=4.
P.S.: After two years, here finally what was the approach followed.
The result was based on approximating the MA amplitude spectrum around $f=0$ as a parabola (2nd order Series) according to
$MA(\Omega) = \frac {Sin(\Omega∗N/2)}{Sin(\Omega/2)}$
$MA(\Omega) \approx 1+(\frac{1}{24}-\frac{N^2}{24})\Omega^2$
which can be made more exact near the zero crossing of $MA(\Omega)-\frac{\sqrt2}{2}$ by multiplying $\Omega$ by a coefficient
$\alpha=0.95264$
obtaining
$MA(\Omega) \approx 1+0.907523(\frac{1}{24}-\frac{N^2}{24})\Omega^2$
The solution of $MA(\Omega)-\frac{\sqrt2}{2}=0$ gives the results above, where $2\pi F_{co}=\Omega_{co}$.
All of the above relates to the -3dB cut off frequency, the subject of this post.
Sometimes though it is interesting to obtain an attenuation profile in stop-band which is comparable with that of a 1st order IIR Low Pass Filter (single pole LPF) with a given -3dB cut off frequency (such a LPF is also called leaky integrator, having a pole not exactly at DC but near to it).
In fact both the MA and the 1st order IIR LPF have -20dB/decade slope in the stop band (one needs a larger N than the one used in the figure, N=32, to see this), but whereas MA has spectral nulls at $F=k/N$ and a $1/f$ evelope, the IIR filter only has a $1/f$ profile.
$H_{IIR} = \frac{1-Exp(-\Omega_{co})}{1-Exp(-\Omega_{co})*Exp(j \Omega)}$
If one wants to obtain an MA filter with similar noise filtering capabilities as this IIR filter, and matches the 3dB cut off frequencies to be the same, upon comparing the two spectra, he would realize that the stop band ripple of the MA filter ends up ~3dB below that of the IIR filter.
In order to get the same stop-band ripple (i.e. same noise power attenuation) as the IIR filter the formulas can be modified as follows:
$F_{co,IIR} = \frac {0.32} {\sqrt{N^2-1}}$
$N = \frac {\sqrt{0.1024 + F_{co,IIR}^2}}{F_{co,IIR}}$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Возможно ли с помощью функции содержащей цикл изменить содержимое списка? (Python 3.8)
Упражнение
Напишите функцию make_great(), которая изменяет список фокусников, добавляя к имени каждого фокусника приставку «Great» . Убедитесь в том, что список был успешно изменен.
Код
name_magicians = ['Harry Houdini', 'David Copperfield', 'Apollo Robbins', 'David Devant', 'Shin Lim', 'David Blaine']
def make_great(names):
for i in names:
i = "Great " + i
make_great(name_magicians)
print(name_magicians)
Ожидаемый результат:
['Great Harry Houdini', 'Great David Copperfield', 'Great Apollo Robbins', 'Great David Devant', 'Great Shin Lim', 'Great David Blaine']
Фактический результат:
['Harry Houdini', 'David Copperfield', 'Apollo Robbins', 'David Devant', 'Shin Lim', 'David Blaine']
Заранее спасибо за объяснение моей ошибки! Всем добра!
A:
Варианта решения вашей задачи два:
Список можно изменять напрямую, обращаясь к его индексам
name_magicians = ['Harry Houdini', 'David Copperfield', 'Apollo Robbins', 'David Devant', 'Shin Lim', 'David Blaine']
def make_great(names):
for i, e in enumerate(names):
names[i] = "Great " + e
make_great(name_magicians)
print(name_magicians)
Если нужно изменять список с заранее известным наименованием, можно обратиться к нему, как к глобальной переменной (это довольно костыльное решение, от которого лучше отказаться)
name_magicians = ['Harry Houdini', 'David Copperfield', 'Apollo Robbins', 'David Devant', 'Shin Lim', 'David Blaine']
def make_great():
global name_magicians
for i, e in enumerate(name_magicians):
name_magicians[i] = "Great " + e
make_great()
print(name_magicians)
Оба решения дают результат:
['Great Harry Houdini', 'Great David Copperfield', 'Great Apollo Robbins', 'Great David Devant', 'Great Shin Lim', 'Great David Blaine']
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Update UITableViewCell from another View
I have a tableview filled with custom cells. In every cell there are two buttons and if I press the first one I navigate to another view, lets call it secondview.
On my secondview there is one button which has the same functionality as the second button on my cell from the previous tableview. When I press the button on my secondview I hide it, but I also want to hide the second button on my cell.
But attention! I only want to hide the second button on this particular cell where I pressed the first button, not all of them!
How can I do that?
Thanks in advance!
A:
You should pass the first view as a delegate to the second view and when the change is made in the second you will call the first view's hideSecondButton or whatever mwthod you make. Anyway, your problem's keyword is delegate.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rubocop: Ignore all cops that are boilerplate from a new rails app
When I run rubocop in my app directory, I get a long list of cops that stem from the default boiler-plate rails app which I just generated.
I don't want rubocop to look at these files since I'm not the author of the files and I don't want to mess around with them.
I see that I can add files to the Exclude: section with rubocop/config/default.yml but I'm not sure what configs and files I should be adding to properly ignore the built in files while not ignoring the files I create.
A:
You can run rubocop --auto-gen-config and this will create a todo file for you which you can disable all the cops in. Then you can selectively turn the ones you want back on. Alternatively you can create a boiler plate rails app and run rubocop and those will be the files you need to add the excludes list.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find the Inverse of this function: $y= \frac{1-\sqrt{x}}{1+\sqrt{x}}$
$y= \frac{1-\sqrt{x}}{1+\sqrt{x}}$
I multiplied both sides by the denominator. However, I am stuck at that point. Help?
A:
$$
y(1+\sqrt{x}) = 1-\sqrt{x} \implies (1+y)\sqrt{x} = 1-y\implies \sqrt{x} = \frac{1-y}{1+y}
$$
so
$$
x = \left(\frac{1-y}{1+y}\right)^2
$$
A:
The square root might be a little daunting, so let's get rid of it... $u = \sqrt{x}$:
$$\begin{split}
y &= \frac{1-u}{1+u} \\
y(1+u) &= 1-u \\
(y+1)u &= 1 - y \\
u &= \frac{1-y}{1+y} \\
x &= \left(\frac{1-y}{1+y}\right)^2
\end{split}$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Read text file using stream reader and display each line in specific format?
I am coding for simple c# where I have to read from text file and display it in text box in format: Lastname, Firstname : EID “department” “designation”. The text file has data in format- EID,Firstname,Lastname,department,designation. Using readline memeber of streamreader class, and split into an array.
if(obj.ShowDialog() == DialogResult.OK)
{
filename = obj.FileName;
textBox1.Text = "";
string[] newline;
StreamReader reader = new StreamReader(filename, true);
while (reader.EndOfStream == false)
{
newline = reader.ReadLine().Split(',');
textBox1.Text = textBox1.Text + newline[1] + ", " + newline[2] + ": " + newline[0] + '"' + newline[3] + '"' +" " + '"' + newline[4] + '"'+"\n";
}
reader.Close();
}
A:
You want a check on the length of the newline array:
if ( newline.Length >= 5 ) textBox1.Text = textBox1.Text + newline[1] + ", " + newline[2] + ": " + newline[0] + '"' + newline[3] + '"' +" " + '"' + newline[4] + '"'+"\n";
I also recommend you study up on using a "using" statement on your StreamReader, since its a disposable resource. That will ensure the file gets closed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WCF Console Application Stand-Alone/Standalone Service
Okay. I'm having some conceptual issues with a WCF service i want to create. In short, I need to create a stand-alone Windows service that provides me with remoting functionality (replacing a .NET 1.1 remoting application).
Some general concepts as I currently understand them:
I can do this by first creating a console app that provides the WCF hosting functionality.
I would then deploy this console app as a service via the "create a service" mechanism available for .NET (using the IDE it's pretty simple -- this part is not difficult).
Edit: It might be better just to create a Windows Service and open the service host on the OnStart() and close it in the OnStop(). I will probably do this, but one of the things I'm finding confusing is that some of the examples I'm looking at talk about writing a simple console app versus this mechanism....
Here's the current situation. We have an interface, I'll call it IData which implements our calls to the SQL server. Currently, we implement IData in a class I'll call RemData which has our basic Execute_Query and Execute_NonQuery methods.
Therefore, IData looks like:
[ServiceContract()]
public Interface IData
{
[OperationContract()]
int Execute_Query( parameter list....); // parameter list shouldn't be important here I hope.
[OperationContract()]
int Execute_NonQuery( parameter list....);
}
Note how in my interface definitions, I added the attributes for the WCF stuff (Service Contract and OperationContract). This is central to one of my questions below.
RemData implements IData. We build it sepearately as a DLL.
Now, I need to implment the WCF so I create a console app and include a reference to the DLL containing the definition for my interface IData and a reference to the DLL for RemData (yes, they are in two separate assemblies for me).
Here's the tricky part for me. I need to implment the service, so I'm thinking I can do it in this way. First I modify the RemData class and add System.ServiceModel as a reference and then decorate the class with the [ServiceBehavior()] attribute and then add the [OperationBehavior()] attributes to each of the methods matching my Interface.
Is this a good plan of attack?
If I do this plan, do I then decorate the class with the [ServiceBehavior()] attribute and then each method in the class with the [OperationBehavior()] attribute? Do I even need the OperationBehavior attribute at all? I'm pretty sure I need the ServiceBehavior attribute, though.
These would then more or less match the ServiceContract and OperationContract attributes on the interface, right?
What if I have multiple overloaded Execute_Query() and Execute_NonQuery() methods in the original (which I do). I know how to define them in the interface using the Name parameter in the OperationContract attribute:
[ServiceContract()]
public Interface IData
{
[OperationContract(Name="Execute_QueryA")]
int Execute_Query( parameter list....); // parameter list shouldn't be important here I hope.
[OperationContract(Name="Execute_NonQueryA")]
int Execute_NonQuery( parameter list....);
[OperationContract(Name="Execute_QueryB")]
int Execute_Query( parameter list....); // parameter list shouldn't be important here I hope.
[OperationContract(Name="Execute_NonQueryB")]
int Execute_NonQuery( parameter list....);
}
But, what do I do for the actual implementation? Do I just leave the [OperationBehavior()] execute as it stands and not add any parameters to it? There doesn't seem to be a name parameter.
I'd appreciate any thoughts on this or links to good articles because I'm not finding a whole lot of useful information that goes beyond the basic "Hey, I created a single call WCF service hosted in IIS ..."
Thank you.
A:
Your plan is fine, but you probably don't need to decorate each method implementation with [OperationBehavior] unless they're doing something special.
Your overloads will need to have unique parameters, though, or else you must give them different names, eg:
[OperationContract()]
int Execute_NonQueryA( parameter list );
[OperationContract()]
int Execute_NonQueryB( parameter list);
The name attribute of OperationContract is not meant to enable multiple overrides of methods that have the same C# signature, it's only meant to rename the method from the perspective of the caller.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Did DB Cooper's aircraft land safely with the aft stairs open?
I've never seen a 727's aft stairs open, but presumably, based on an Wikipedia image and common sense, they do reach the ground when the aircraft is on the ground. Furthermore, (as I understand it), airliners land with a positive pitch, which means that assuming a level runway, the rear of the aircraft will touch down first. However, this suggests that if the aft stairs of the 727 were open during landing, they would impact the ground during landing and, given the pitch, do more than scrape the ground and cause damage to the aircraft.
However, DB Cooper's jump left the aft stairs open, and (as far as I can tell) it seems that the landing was uneventful besides the stress of having a hijacker potentially on board (although it's quite understandable if no one made any record of it, given there were slightly more important things to deal with).
If DB Cooper's flight did land without damage, why is that—did the 727's aft stairs not fully touch the ground? If the stairs did impact the ground, was there sufficient damage to require repairs?
(I meant this question to be more about the 727 than DB Cooper, but since his was the only landing with stairs open, there wasn't much room for speaking in general terms).
A:
I do not think they landed with the airstairs down: The airstairs are powered to get them back up since they are heavy, and this feature can be operated from inside the aircraft as well.
The following answer is of Yahoo answers and while I can't confirm is accuracy, it sounds very plausible:
There are 2 control handles for the airstairs on a B727, one under a
panel on the lower fuselage right beside the stair forward hinge
point, and one at the top of the stairs behind a panel on the left
side which can only be accessed when the rear cabin door is open.
Because the cabin door can only be opened when the aircraft is
unpressurized, this usually would prevent its actuation in flight.
However, after the D B Cooper hijacking a device was added referred to
as an anti-hijack vane that would swing over when the aircraft was in
flight and prevent the door opening. To close the door either an
electric hydraulic pump has to be turned on in the cockpit, or a hand
pump beside the lower control operated while either handle is held to
the close position. The door will free fall open without hydraulic
pressure, but the support arms may have to be pushed to an overcenter
position.
Assuming that the air stairs were deployed, it may be that the force of the airflow passing by would have been sufficient to spare the stairs from a tailstrike. The stairs have a large surface area and moving at perhaps around 100 knots when the nosewheel touches down would still generate a considerable force to push them into the fuselage.
The term deployed may also suggest that the airstairs may have been damaged and uable to retract the whole way, leaving it halfway stuck but still out of tailstrike range.
The aircraft was empty at the time which would have helped in either situation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to skip a record with awk
I have a large number of files in a log-directory, whose names were time-stamped (in this case with date +%b[...]).
I want to write a POSIX compliant one-liner that will:
either
skip lines output from ls -ltc that have 2 fields or less (as
seen by awk) and do not contain the regexp constant /Jul/
or
skip the first line output by ls -ltc and any line not matching /Jul/.
The result is the same for my purpose as only the first line consists of two fields (as seen by awk).
I tried:
> ll -tc | rm $(awk --posix 'NF > 2 && !/Jul/ {print $NF;}')
> ll -tc | rm $(awk --posix 'NF > 2 !/Jul/ {print $NF;}')
Both have bad syntax because a condition on NF apparently does not coexist nicely with a regexp matching condition the way ls | awk '/foo/ && /bar/'would for instance.
Can sb give me pointers on how to either skip any arbitrary record and/or apply the arithmetic condition on NF and the regexp pattern matching at the same time ? I did look around but could not find the documented syntax I am looking for...
A:
Either
awk 'NF<=2 || /Jul/ {next} {print}'
or
awk 'NR==1 || /Jul/ {next} {print}'
or, inverting the logic to shorten the commands, either
awk 'NF>2 && !/Jul/ {print}'
or
awk 'NR!=1 && !/Jul/ {print}'
~$ cat input
first line
Gen second third
Feb second third
Mar second third
Apr second third
May second third
Jun second third
Jul second third
Aug second third
Sep second third
Oct second third
Nov second third
Dec second third
~$ awk 'NF<=2 || /Jul/ {next} {print}' input
Gen second third
Feb second third
Mar second third
Apr second third
May second third
Jun second third
Aug second third
Sep second third
Oct second third
Nov second third
Dec second third
~$ awk 'NR==1 || /Jul/ {next} {print}' input
Gen second third
Feb second third
Mar second third
Apr second third
May second third
Jun second third
Aug second third
Sep second third
Oct second third
Nov second third
Dec second third
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What happens to orphaned/killed async AJAX WebMethod or PageMethod calls?
What happens behind the scenes if I make an AJAX PageMethod or WebMethod call from, say, "Default.aspx" and then I quickly navigate away to a different page, say, "Settings.aspx" before the initial PageMethod has returned?
What kind of housekeeping, if any, takes place on either the browser or the ASP.NET back end?
In other words, where do abandoned AJAX PageMethod calls go to die...and what is their funeral like?
A:
There's no magic here. You made a request. The server presumably received the request. Most likely, it will act upon the request and send a response.
Of course, if the connection has been closed, the server will receive an error when it sends the response, but it will deal with that common occurence.
I don't know whether or not the browser will close any connections created in one top-level window when you destroy it in order to navigate to another document. I suspect it will, depending on the browser.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I reformat value_counts() analysis in Pandas for large number of columns
I have dataset that consist of hundreds of column, and thousands of row
In [119]:
df.columns
Out[119]:
Index(['column 1', 'column2',
...
'column 100'],
dtype='object', name='var_name')
Usually I did value_counts() for every single column to see the distribution.
In [121]:
a = df['column1'].value_counts()
In [122]:
a
Out[122]:
1 77494
2 5389
0 2016
3 878
Name: column 1, dtype: int64
But for this dataframe, if I did this for every columns, this will make my notebook very messy, how to automate this? Is there any function that help?
If you have other information, all my data is int64, but I hope the best answer can give solution that works in every cases. I want to make the solution answer in pandas dataframe.
Based on @MaxU suggestion, this is my version of simplified dataframe
df
id column1 column2 column3
1 3 1 7
2 3 2 8
3 2 3 7
4 2 1 8
5 1 2 7
and my expected output is:
column 1 count
1 1
2 2
3 2
column 2 count
1 2
2 2
3 1
column 3 count
7 3
8 2
3 1
A:
I'd do it this way:
In [83]: df.drop('id',1).apply(lambda c: c.value_counts().to_dict())
Out[83]:
column1 {3: 2, 2: 2, 1: 1}
column2 {2: 2, 1: 2, 3: 1}
column3 {7: 3, 8: 2}
dtype: object
or:
In [84]: for c in df.drop('id',1):
...: print(df[c].value_counts())
...:
3 2
2 2
1 1
Name: column1, dtype: int64 # <----- column name
2 2
1 2
3 1
Name: column2, dtype: int64
7 3
8 2
Name: column3, dtype: int64
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to insert values into a list in python.. with a few extra conditions
hi i have a list of tuples like this:
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]
and i wish to append each individual tuple to a dictionary as the dictionarys key.
i want the format to look like this.
dict = {"wealth-gain": value, "gain-burnt": value ......}
how would i create a loop that will go through each tuple in the bigrams list and append it to the dictionary?
Heres what i have
For word in bigrams:
dict[(0+"-"+1) = dict
basicaly i want to take each tuple and add a "-" in between each word in the tuple then append that to a dictionary?
Any ideas how to do this?
Also if the bigram that is going to be appended to the dictionary matches a bigram that is already in the dictionary i would not like to add that bigram to the dictionary. Rather i would like to increment the value of the bigram already in the dictionary.
Any ideas how to do that?
Thanks.
A:
You can use the join method:
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]
dict_ = {}
for tup in bigrams:
k = '-'.join(tup)
dict_[k] = data.setdefault(k,0) + 1
or express the initialization with a generator:
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]
dict_ = dict(('-'.join(tup), 0) for tup in bigrams)
A:
How about:
d = {}
val = 0
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]
for word in bigrams:
s = '-'.join(word)
if s in d:
d[s] += 1
else:
d[s] = val
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to move around a player in a curved tunnel?
In a scenario where the player moves freely along the walls of a tunnel (like this), what is the best way to move the player along the walls of the tunnel?
I'm using Unity3d game engine. I've tried to remove all gravity and apply relative downward force on the object on every tick. Pressing right or left key applies relative force on the x-axis. But the player object will not rotate along with the walls of the tunnel and hence wont climb. I can calculate tangent to the center of the circle inside the tunnel and rotate the player myself but that wont work with curved tunnels.
A:
You could do a Physics.Raycastin the down direction of the player. The normal of the RaycastHit this gives you, can then be used to determine the new orientation of the player. Then to "stick" the player to the surface, the new position can be calculated from the hit point, the surface normal and the desired distance from the surface.
For smoother results, do this twice, once a bit left of the player and once a bit to the right, then average.
This should work even when the tunnel cross section is not circular, should you choose so at some point.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Bind a collection inside a collection in WPF combobox
ObservableCollection<A> work = new ObservableCollection<A>();
Class A
{
int a;
int b;
observablecollection<string> c;
}
I need to bind" work" as the Itemsource of combobox and selectedItem as A. But I need to display the strings(c) of class A in the combobox. How will I display the strings C in the combobox. Any idea.?
A:
well if you need each ComboBoxItem to display a collection of strings, use an ItemsControl in the ItemTemplate of ComboBox.
<ComboBox ItemsSource="{Binding work}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text={Binding a} />
<TextBlock Text={Binding b} />
<ItemsControl ItemsSource="{Binding c}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to use an #if directive with a template non-type argument? (Vector all-in-one class)
I am creating a Vector class and instead of creating separate classes for Vector2, Vector3 and Vector4 I want to make an all-in-one class. My problem is that I want to define certain properties depending on the size of the vector. For example, a vector of size 2 will have an x and y component, but not a z component.
I'm attempting to use the #if directive to check the non-type template argument (SIZE) to create properties depending on the size of the vector. I did some research and I don't think it's possible this way. I'm wondering if anyone has an idea about how to achieve want I want?
template <typename T, int SIZE>
class Vector
{
public:
union
{
struct
{
#if SIZE == 2
T x, y;
#endif
#if SIZE == 3
T z;
#endif
#if SIZE == 4
T w;
#endif
};
T data[SIZE];
};
};
I want to be able to create and access a Vector like so:
Vector<int, 2> vec2;
vec2.x;
Vector<int, 3> vec3;
vec3.z;
Any feedback is appreciated!
EDIT:
After reviewing the comments I came up with a nifty solution... Hopefully it works for me. I created a templated class:
template <typename T, unsigned int SIZE> class _vec;
This deals with the data (components) of the vector and contains the behaviour. Then I made another templated class that will sort of specialise _vec like so:
template <typename T, unsigned int SIZE> class Vector : public _vec<T, SIZE>;
This is a vector of any size. Now I can specialise that for Vector2, Vector3 and Vector4:
template <typename T> class Vector<T, 2> : public _vec<T, 2>;
template <typename T>
using Vector2 = Vector<T, 2>;
I'll let you know how HORRIBLE this will turn out... ;P
EDIT 2: It worked, but didn't work out... :(
A:
No, this is not possible.
In the phases of translation, the preprocessing phase comes before the template instantiation phase. So in this case, you will end up having none of the variables defined in the template Vector because SIZE is not defined at the preprocessing phase.
As per the C++ standard, [cpp.cond]/9:
After all replacements due to macro expansion and evaluations of defined-macro-expressions and has-include-expressions have been performed, all remaining identifiers and keywords, except for true and false, are replaced with the pp-number 0, and then each preprocessing token is converted into a token.
So the value of SIZE here will be 0 and thus none of the conditions of the conditional inclusions are met.
You can instead specialize your template to have different variables for different instantiations.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.