text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Using jQuery, how to specify with the `.attr` method, the second of two html classes?
When using jQuery and are using the .attr method as follows:
$(document).ready(function(){
$('.class1').click(function(){
id = $(this).attr('.class2');
});
});
Say I have the following HTML for the above function:
<div class="class1 $class2"></div>
The second class is attributed at runtime, so I have 10 divs, each with class1, but several with class2. Then I wish to use the jQuery function at the top, so that whenever I click on any of the divs, it applies the specific class2 of that div, to the variable ID.
I hope this makes more sense.
A:
Since your class2 comes from your PHP code, you seem to hit the usecase of data-attributes.
With data-attributes you can easily have some extra data (often used for javascript purposes) on your HTML elements without having to use special classes or ids for that.
It works like that:
<span data-hero="batman">I'm a Bat!</span>
Where in your Javascript (using jQuery) you get the value of it by simply doing:
$('span').data('hero');
Refer to the MDN and the jQuery documentation for further information.
| {
"pile_set_name": "StackExchange"
} |
Q:
Exchange: give access to a mailbox, but disallow moving/deleting folders
Using exchange is it possible to give a user access to a mailbox so that they can move and delete mails but not move and delete folders? A solution that requires a change to every folder in the account is fine as there are only a few dozen and they do not change very often.
What I am trying to avoid is users dragging folders around or deleting them by accident when they are working in a shared support mailbox.
A:
EDIT:
Sorry about that.
HopelessNoob, thanks for flagging.
PFDavAdmin cannot be used in Exchange 2010Sp1 or later.
For Ex2010 you need ExFolders
You can download it from here
http://gallery.technet.microsoft.com/office/Exchange-2010-SP1-ExFolders-e6bfd405
Installation:
You need to extract it to your Exchange Bin directory c:\program
files\microsoft\exchange\v14\bin
Also, you need to add the registry entries which came in the zip (double-click and add it to
registry)
Before you work on a mailbox folder
a) Open EMC
b) Drill down to
Recipient Config > Mailboxes
Right click on the mailbox > manage full access permission
and give Full Access Permission to the logged in service account you are using.
Open ExFolders from \bin
Connect to GC / Connect to Database folder.
Expand the left tree and drill down to the mailbox.
Select Top of Information Store,
RightClick on the folder you would need to give permission to and search for the username from the list.
Select the user as Contributor, and select appropriate Delete Permissions (Own/All).
Ensure that you do not make them Folder Owner.
Screenshot here
hth
PREVIOUS Answer > Wrong.
You can use PFDavAdmin to do this in Exchange 2010 and prior versions.
http://www.msexchange.org/articles/PFDavAdmin-tool-Part1.html
| {
"pile_set_name": "StackExchange"
} |
Q:
How to enable the Hp QuickPlay buttons?
I have an Hp pavilion dv2000 and it has a pretty nice blue buttons over the keyboard, some are for multimedia (which work perfectly), and other two are for launch a DVD application and a multimedia center on Windows, however, those doesn't work for anything on Ubuntu, because they are not even recognized as keyboard buttons.
So how can I activate them?
A:
If you are running an old version of Ubuntu (9.xx?) then you should try upgrading.
If you are on Ubuntu 10.04 and up, go the System>Preferences>Keyboard Shortcuts, and add new short cuts for your multimedia keys (they will almost definitely be detected). In fact, they may already exist, but not be assigned to launch any applications.
As for the volume/play/pause/stop buttons (I believe you have those, if it is a dv2000) you should be able to use those out of the box in most recent versions of Ubuntu (even most older versions). If you are not able to use those buttons in particular, then you should report a bug (but only if you are using a supported version of Ubuntu; which means 10.04 and up).
If you are not sure they are being detected, run xev in a terminal and press the keys. You will see their key codes on the terminal if they are working. If you don't, then something is wrong with your system either physically or in the software.
There is a program that might help you (though I no longer have it installed, and thus can no longer provide screenshots).
It is called Keytouch-editor, and it helped me in the past with a similar issue (since then Ubuntu supports my QuickPlay button and all the other buttons just fine). Install Keytouch-editor is pretty straight forward and you should be able to learn it quickly.
You can find it in the software center, or install it from the command line with sudo apt-get install keytouch-editor.
Once you have it installed, and have run it, you can assign your Quickplay buttons to launch the media programs (or anything else for that matter) of your choice. Keytouch-editor makes it very simple.
| {
"pile_set_name": "StackExchange"
} |
Q:
Programmatically grant Permissions without using policy file
How to programmatically grant AllPermissions to an RMI application without using policy file?
UPDATE:
After some researching, I have written this custom Policy Class and installed it via Policy.setPolicy(new MyPolicy()).
Now I get the following error:
invalid permission: (java.io.FilePermission
\C:\eclipse\plugins\org.eclipse.osgi_3.7.0.v20110613.jar read
class MyPolicy extends Policy {
@Override
public PermissionCollection getPermissions(CodeSource codesource) {
return (new AllPermission()).newPermissionCollection();
}
}
A:
Based on @EJP's advice, I have debugged using -Djava.security.debug=access and found all the needed permissions in a policy file :
grant { permission java.net.SocketPermission "*:1024-", "connect,
resolve"; };
grant { permission java.util.PropertyPermission "*", "read, write";
};
grant { permission java.io.FilePermission "<>", "read";
};
But because I didn't want to create a policy file, I found a way to replicate this programmatically by extending java.security.Policy class and setting the policy at the startup of my application using Policy.setPolicy(new MinimalPolicy());
public class MinimalPolicy extends Policy {
private static PermissionCollection perms;
public MinimalPolicy() {
super();
if (perms == null) {
perms = new MyPermissionCollection();
addPermissions();
}
}
@Override
public PermissionCollection getPermissions(CodeSource codesource) {
return perms;
}
private void addPermissions() {
SocketPermission socketPermission = new SocketPermission("*:1024-", "connect, resolve");
PropertyPermission propertyPermission = new PropertyPermission("*", "read, write");
FilePermission filePermission = new FilePermission("<<ALL FILES>>", "read");
perms.add(socketPermission);
perms.add(propertyPermission);
perms.add(filePermission);
}
}
class MyPermissionCollection extends PermissionCollection {
private static final long serialVersionUID = 614300921365729272L;
ArrayList<Permission> perms = new ArrayList<Permission>();
public void add(Permission p) {
perms.add(p);
}
public boolean implies(Permission p) {
for (Iterator<Permission> i = perms.iterator(); i.hasNext();) {
if (((Permission) i.next()).implies(p)) {
return true;
}
}
return false;
}
public Enumeration<Permission> elements() {
return Collections.enumeration(perms);
}
public boolean isReadOnly() {
return false;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
recursive view using lookup tables with ambiguous joins
I don't even know how to title this question but I hope this makes sense.
I have three tables:
A table of users and their details
A table of groups and its details
A table of groups with the lookup ID of its members which are either from the users or groups table
The 3rd table has two columns:
A group ID which matches a row in the groups (2nd) table
A member ID which matches a row in either the users (1st) or groups (2nd) table
Notes:
The IDs of users and groups table are unique against each other. For example, if a user has ID = 1 then no other user, nor any group, will have the same ID.
A group can have either a user or another group as a member.
I need to dump a view of the 3rd table, fully expanding all members of each group, including the nested groups, dump the group path, and handle infinite loops. Hopefully this example makes it clear:
1. users
| ID | user_name |
|----|-----------|
| 1 | one |
| 2 | two |
| 3 | three |
| 4 | four |
| 5 | five |
2. groups
| ID | group_name |
|----|------------|
| 6 | six |
| 7 | seven |
| 8 | eight |
| 9 | nine |
| 10 | ten |
3. group members
| group_ID | member_ID |
|----------|-----------|
| 6 | 1 |
| 6 | 2 |
| 6 | 3 |
| 7 | 4 |
| 7 | 5 |
| 8 | 1 |
| 8 | 9 |
| 8 | 10 |
| 9 | 5 |
| 10 | 1 |
| 10 | 8 |
4. output/result
| group_ID | user_ID | user_name | group_path
|----------|---------|-------------|------------
| 6 | 1 | one | six
| 6 | 2 | two | six
| 6 | 3 | three | six
| 7 | 4 | four | seven
| 7 | 5 | five | seven
| 8 | 1 | one | eight
| 8 | 5 | five | eight > nine
| 8 | 1 | one | eight > ten
| 8 | | [recursive] | eight > ten > eight
| 9 | 5 | five | nine
| 10 | 1 | one | ten
| 10 | 1 | one | ten > eight
| 10 | 5 | five | ten > eight > nine
| 10 | | [recursive] | ten > eight > ten
A:
Here's an answer and a live demo
;with cte as
(
select id,name=user_name, type='U' from users
union
select id, name=group_name, type='G' from groups
)
, cte2 as
(
select
user_id=c.id,
user_name=c.name,
group_Id=g.group_ID,
group_path= cast(c2.name as nvarchar(max))
from cte c
left join [group members] g
on g.member_id=c.id and type='U'
left join cte c2
on c2.type='G' and c2.id=g.group_ID
union all
select
user_id=user_id,
user_name=user_name,
group_Id=g.group_ID,
group_path= concat(c2.name,'>',c.group_path)
from cte2 c
join [group members] g
on g.member_id=c.group_Id
join cte c2
on g.group_ID=c2.id and c2.type='G'
where c.group_path not like '%'+c2.name+'%'
)
select
group_id,
user_id,
user_name,
group_path
from cte2
where group_id is not null
union all
select
group_id=g.group_ID,
user_id= NULL,
user_name='[recursive]',
group_path=concat(c2.name,'>',c.group_path)
from cte2 c
join [group members] g
on g.member_id=c.group_Id
join cte c2
on g.group_ID=c2.id and c2.type='G'
where c.group_path like '%'+c2.name+'%'
order by group_id,user_id
| {
"pile_set_name": "StackExchange"
} |
Q:
VerticalLayout with footer?
I'm looking for a way to create a footer in my VerticalLayout.
There are some way to create footer with VerticalLayout ?
Any idea ?
A:
A simple solution. André Schild has already given a valuable input.
VerticalLayout vlMain = new VerticalLayout();
vlMain.setSizeFull();
HorizontalLayout hlFooter = new HorizontalLayout();
hlFooter.setHeight("50px"); // if you want you can define a height.
hlFooter.addComponent(new Label("Test1")); // adding a simple component. You might want to set alignment for that component
vlMain.addComponent(mainComponent);
vlMain.setExpandRatio(mainComponent, 1.0f); // "give" the main component the maximum available space
vlMain.addComponent(hlFooter);
| {
"pile_set_name": "StackExchange"
} |
Q:
Is three.js ObjectLoader capable of loading textures?
three.js version 0.0.70, blender version 2.73a
I have a scene exported from blender to three.js json format using new io_three (not io_three_mesh) exporter.
I'm able to import the scene into three.js using ObjectLoader:
var objectLoader = new THREE.ObjectLoader();
objectLoader.load('assets/models/exportedScene.json', function(imported) {
scene.add(imported);
});
Unfortunatelly, no texture is applied to an object, only the material.
As I see from exportedScene.json file, there is an info about texture in file:
"images": [{
"url": "blue.jpg",
"uuid": "DFE5BBBF-601B-48EA-9C05-B9CB9C07D92E",
"type": "Geometry",
"name": "blue.jpg"
}],
"materials": [{
"color": 200962,
"specular": 5066061,
"shininess": 8,
"ambient": 200962,
"depthTest": true,
"depthWrite": true,
"name": "partitionMat",
"emissive": 0,
"uuid": "A705A33F-68C1-489C-A702-89A0140247AB",
"blending": "NormalBlending",
"vertexColors": false,
"map": "73277351-6CCF-4E84-A9F0-D275A101D842",
"type": "MeshPhongMaterial"
}],
"textures": [{
"minFilter": "LinearMipMapLinearFilter",
"wrap": ["RepeatWrapping","RepeatWrapping"],
"magFilter": "LinearFilter",
"mapping": "UVMapping",
"image": "DFE5BBBF-601B-48EA-9C05-B9CB9C07D92E",
"repeat": [1,1],
"name": "carpetTexture",
"anisotropy": 1.0,
"uuid": "73277351-6CCF-4E84-A9F0-D275A101D842",
"type": "Geometry"
}],
But as I said before, no texture is applied.
I tried placing texture file near the html with js script, but it didn't work.
Maybe my initial approach is incorrect and I should import textures similar to http://threejs.org/examples/webgl_loader_obj.html? However, this one is about using ObjLoader (not ObjectLoader), and I'm not sure if it's correct.
A:
Check out the dev branch. There have been recent commits for texture support for the upcoming r71 release.
| {
"pile_set_name": "StackExchange"
} |
Q:
Begin and monitor progress on long running SQL queries via ajax
Is it possible to start a query that will take a significant amount of time and monitor progress from the UI via Ajax?
I considered starting the process as a "run once" job that is scheduled to run immediately. I could store the results in a temporary table for quick retrieval once it's complete. I could also log the run time of the report and average that out, to guestimate the running time for the progress bar.
I use Microsoft SQL 2005 at the moment, but I'm willing to other DBMS such as SQL 2008, MySQL, etc if necessary.
A:
One idea, if the long running job populates another table.
You have a 2nd database connection to monitor how many rows are processed out of the source rows, and show a simple "x rows processed" every few second
SELECT COUNT(*) FROM TargetTable WITH (NOLOCK)
If you have a source table too:
SELECT COUNT(*) FROM SourceTable WITH (NOLOCK)
..then you can use "x of y rows processed"
Basically, you have to use a 2nd connection to monitor the first. However, you also need something to measure...
| {
"pile_set_name": "StackExchange"
} |
Q:
Monkey patching operator overloads behaves differently in Python2 vs Python3
Consider the following code:
class Foo:
def __mul__(self,other):
return other/0
x = Foo()
x.__mul__ = lambda other:other*0.5
print(x.__mul__(5))
print(x*5)
In Python2 (with from future import print), this outputs
2.5
2.5
In Python3, this outputs
2.5
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-1-36322c94fe3a> in <module>()
5 x.__mul__ = lambda other:other*0.5
6 print(x.__mul__(5))
----> 7 print(x*5)
<ipython-input-1-36322c94fe3a> in __mul__(self, other)
1 class Foo:
2 def __mul__(self,other):
----> 3 return other/0
4 x = Foo()
5 x.__mul__ = lambda other:other*0.5
ZeroDivisionError: division by zero
I ran into this situation when I was trying to implement a type that supported a subset of algebraic operations. For one instance, I needed to modify the multiplication function for laziness: some computation must be deferred until the instance is multiplied with another variable. The monkey patch worked in Python 2, but I noticed it failed in 3.
Why does this happen?
Is there any way to get more flexible operator overloading in Python3?
A:
That is not a monkeypatch.
This would have been a monkeypatch:
class Foo:
def __mul__(self, other):
return other / 0
Foo.__mul__ = lambda self,other: other * 0.5
x = Foo()
x*9 # prints 4.5
What was done with x.__mul__ = lambda other:other*0.5 was creating a __mul__ attribute on the x instance.
Then, it was expected that x*5 would call x.__mul__(5). And it did, in Python 2.
In Python 3, it called Foo.__mul__(x, 5), so the attribute was not used.
Python 2 would have done the same as Python 3, but it did not because Foo was created as an old-style class.
This code would be equivalent for Python 2 and Python 3:
class Foo(object):
def __mul__(self,other):
return other/0
x = Foo()
x.__mul__ = lambda other:other*0.5
print(x.__mul__(5))
print(x*5)
That will raise an exception. Note the (object).
| {
"pile_set_name": "StackExchange"
} |
Q:
Does "for line in file" work with binary files in Python?
One of the answers for this question says that the following is a good way to read a large binary file without reading the whole thing into memory first:
with open(image_filename, 'rb') as content:
for line in content:
#do anything you want
I thought the whole point of specifying 'rb' is that the line endings are ignored, therefore how could for line in content work?
Is this the most "Pythonic" way to read a large binary file or is there a better way?
A:
I would write a simple helper function to read in the chunks you want:
def read_in_chunks(infile, chunk_size=1024):
while True:
chunk = infile.read(chunk_size)
if chunk:
yield chunk
else:
# The chunk was empty, which means we're at the end
# of the file
return
The use as you would for line in file like so:
with open(fn. 'rb') as f:
for chunk in read_in_chunks(f):
# do you stuff on that chunk...
BTW: I asked THIS question 5 years ago and this is a variant of an answer at that time...
You can also do:
from collections import partial
with open(fn,'rb') as f:
for chunk in iter(functools.partial(f.read, numBytes),''):
A:
for line in fh will split at new lines regardless of how you open the file
often with binary files you consume them in chunks
CHUNK_SIZE=1024
for chunk in iter(lambda:fh.read(CHUNK_SIZE),""):
do_something(chunk)
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript audio object addEventListener canplaythrough not working on IPAD Chrome
I have two functions in JavaScript. Its working fine on Windows 7 Chrome but loadedAudio_chrome function is not being fired on IPAD.
function preloadAudio_chrome(url)
{
try
{
var audio = new Audio();
audio.addEventListener('canplaythrough', loadedAudio_chrome, false);
//audio.src = filePath;
} catch (e) {
alert(e.message);
}
}
function loadedAudio_chrome()
{
//alert('not firing this alert on IPAD');
}
A:
You seem to be missing audio.load() from your snippet, try adding that as shown below and it should work.
function preloadAudio_chrome(url)
{
try
{
var audio = new Audio();
audio.addEventListener('canplaythrough', loadedAudio_chrome, false);
// EDIT HERE ADD audio.load();
audio.load();
} catch (e) {
alert(e.message);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
É possível melhorar essa parte do codigo?
Estou precisando melhorar uma parte do código.
Meu problema é que está muito repetitivo esse if e else, o ruim é que terei mais coisas repetitivas por conta que são diferentes jogos.
Consigo melhorar essa parte do código por algo mais legível ou até mesmo menor?
public Double valuesGames(String game){
if (game.equals(constantes.getGameDiadeSorte())){
//Valores referente a Dia de Sorte
if (getNumbersBalls().size() <= 7){
value = constantes.getAmountDiaDeSorte();
}else if (getNumbersBalls().size() == 8){
value = constantes.getAmountDiaDeSorte() + 3;
}else if (getNumbersBalls().size() == 9){
value = constantes.getAmountDiaDeSorte() + 4;
}else if (getNumbersBalls().size() == 10){
value = constantes.getAmountDiaDeSorte() + 5;
}else if (getNumbersBalls().size() == 11){
value = constantes.getAmountDiaDeSorte() + 6;
}else if (getNumbersBalls().size() == 12){
value = constantes.getAmountDiaDeSorte() + 7;
}else if (getNumbersBalls().size() == 13){
value = constantes.getAmountDiaDeSorte() + 10;
}else if (getNumbersBalls().size() == 14){
value = constantes.getAmountDiaDeSorte() + 11;
}else if (getNumbersBalls().size() == 15){
value = constantes.getAmountDiaDeSorte() + 15;
}
} else if (game.equals(constantes.getGameQuina())){
//Valores referente a QUINA
if (getNumbersBalls().size() <= 5){
value = constantes.getAmountQuina();
}else if (getNumbersBalls().size() == 6){
value = constantes.getAmountQuina() * 3;
}else if (getNumbersBalls().size() == 7){
value = constantes.getAmountQuina() * 4;
}else if (getNumbersBalls().size() == 8){
value = constantes.getAmountQuina() * 5;
}else if (getNumbersBalls().size() == 9){
value = constantes.getAmountQuina() * 6;
}else if (getNumbersBalls().size() == 10){
value = constantes.getAmountQuina() * 7;
}else if (getNumbersBalls().size() == 11){
value = constantes.getAmountQuina() * 8;
}else if (getNumbersBalls().size() == 12){
value = constantes.getAmountQuina() * 9;
}else if (getNumbersBalls().size() == 13){
value = constantes.getAmountQuina() * 10;
}else if (getNumbersBalls().size() == 14){
value = constantes.getAmountQuina() * 11;
}else if (getNumbersBalls().size() == 15){
value = constantes.getAmountQuina() * 12;
}
}else if (game.equals(constantes.getGameMega())){
//Valores referente a MEGA-SENA
if (getNumbersBalls().size() <= 6){
value = constantes.getAmountMega();
}else if (getNumbersBalls().size() == 7){
value = constantes.getAmountMega() * 3;
}else if (getNumbersBalls().size() == 8){
value = constantes.getAmountMega() * 4;
}else if (getNumbersBalls().size() == 9){
value = constantes.getAmountMega() * 5;
}else if (getNumbersBalls().size() == 10){
value = constantes.getAmountMega() * 6;
}else if (getNumbersBalls().size() == 11){
value = constantes.getAmountMega() * 7;
}else if (getNumbersBalls().size() == 12){
value = constantes.getAmountMega() * 8;
}else if (getNumbersBalls().size() == 13){
value = constantes.getAmountMega() * 9;
}else if (getNumbersBalls().size() == 14){
value = constantes.getAmountMega() * 10;
}else if (getNumbersBalls().size() == 15){
value = constantes.getAmountMega() * 11;
}
}
return value;
}
A:
Você pode trocar performance por código mais enxuto. Existe um padrão aí e você pode generalizar tudo o que está neste padrão. Se fosse um padrão totalmente regular poderia resolver com matemática simples, mas existe uma exceção que é a primeira verificação e os valores que são usados para somar ou multiplicar precisam constar em uma tabela. Confira se eu não comi bola em alguma coisa ou se o código original não tem problemas, por exemplo o que deveria fazer se o número for maior que estes verificados. Reforço que isto ficará mais lento, não muito, mas ficará:
int[] somadoresDiaDeSorte = new int[] { 3, 4, 5, 6, 7, 10, 11, 15 };
int[] multiplicadoresQuina = new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
int[] multiplicadoresMega = new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 11 };
if (game.equals(constantes.getGameDiadeSorte())) {
if (getNumbersBalls().size() <= 7) value = constantes.getAmountDiaDeSorte();
else {
for (int i = 0; i < i < multiplicadoresDiaDeSorte.length; i++) {
if (getNumbersBalls().size() == i + 8) {
value = constantes.getAmountDiaDeSorte() + somadoresDiaDeSorte[i];
break;
}
}
}
if (game.equals(constantes.getGameQuina())) {
if (getNumbersBalls().size() <= 5) value = constantes.getAmountQuina();
else {
for (int i = 0; i < i < multiplicadoresQuina.length; i++) {
if (getNumbersBalls().size() == i + 6) {
value = constantes.getAmountQuina() + multiplicadoresQuina[i];
break;
}
}
}
}
if (game.equals(constantes.getGameMega())) {
if (getNumbersBalls().size() <= 6) value = constantes.getAmountMega();
else {
for (int i = 0; i < i < multiplicadoresMega.length; i++) {
if (getNumbersBalls().size() == i + 7) {
value = constantes.getAmountMega() + multiplicadoresMega[i];
break;
}
}
}
}
Coloquei no GitHub para referência futura.
Dá pra generalizar um pouco mais e fazer com que os três virem um só, mas acho que começa parametrizar demais para códigos normais. Precisaria ter um motivo muito forte para fazer isto, envolveria lambda (para estabelecer quais os métodos devem ser usados para pegar o dado ser comparado e a quantidade do elementos de cada operação) e só para escrever menos código não acho que fica legal, e tem um número que precisaria ser parametrizado também, mas dei as dicas se quiser fazer.
| {
"pile_set_name": "StackExchange"
} |
Q:
get alphabat instead of word jquery ajax
I wan't to get string instead of word. how can i do this.
php file code
<?php
$countries = array("Afghanistan", "Albania");
$response=array("countries"=>$countries);
echo json_encode($response);
?>
html file
$(document).ready(function(){
$("button").click(function(
$.ajax({
type:'GET',
url:'./countries.php',
data:{countries:true},
cache:false,
async:false,
success:function(data){
var str="";
for(i=0;i<data.length;i++)
{$("tbody.new").append("<tr><td>" + data[i] + "</td><td></td> <tr>");}
result is like this a f g a every word is separate line
A:
You haven't specified the accepted data type in ajax options object. That's why you are getting a json string instead of parced json data.
Change your code as shown below:
$(document).ready(function(){
$("button").click(function(
$.ajax({
type:'GET',
url:'./countries.php',
data:{countries:true},
dataType: 'json',
cache:false,
async: true,
success:function(data){
var str = "";
for (i = 0; i < data["countries"].length; i++){
$("tbody.new").append("<tr><td>" + data["countries"][i] + "</td><td></td><tr>");
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Key Binding not working, action not performed
I'm just trying to learn how the key binders work, and it seems I've misunderstood something from the Java tutorials. This is the code:
public class KeyBinder {
public static void main(String[] args) {
//making frame and label to update when "g" key is pressed.
JLabel keybinderTestLabel;
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(300,75);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
keybinderTestLabel = new JLabel("Press the 'g' key to test the key binder.");
mainFrame.add(keybinderTestLabel);
Action gPressed = new AbstractAction(){
@Override
public void actionPerformed(ActionEvent e) {
keybinderTestLabel.setText("Key Binding Successful.");
System.out.println("Key Binding Successful.");
//Testing to see if the key binding was successful.
}
};
keybinderTestLabel.getInputMap().put(KeyStroke.getKeyStroke("g"), "gPressed");
keybinderTestLabel.getActionMap().put("gPressed", gPressed);
/*
* from my understanding, these two lines map the KeyStroke event of the g key
* to the action name "gpressed", then map the action name "gpressed" to the action
* gpressed.
*
*/
}
}
From what I understand, I mapped the g keystroke to the action name "gPressed", then mapped that to the action gPressed. For some reason though, when I run the program, pressing the g key does not update the text label. What's the issue here? is the "g" keystroke not actually mapped to the g key on the keyboard?
A:
So, from the JavaDocs
public final InputMap getInputMap()
Returns the InputMap that is used
when the component has focus. This is convenience method for
getInputMap(WHEN_FOCUSED).
Since JLabel is not focusable, this will never work, instead, you need to supply a different focus condition, for example...
keybinderTestLabel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). //...
Also, and this is a personal preference... KeyStroke.getKeyStroke("g") using KeyStroke.getKeyStroke like this can be problematic as the String you supply needs be very precise in it's meaning, and I can never remember exactly how it should work (and it's not overly documented).
If the first suggestion fails to fix the issue, also try using KeyStroke.getKeyStroke(KeyEvent.VK_G, 0) instead
| {
"pile_set_name": "StackExchange"
} |
Q:
Is CF 6.1 compatible with IIS7?
Is it advisable to install CF 6.1 on IIS 7 or is it compatible with IIS7 to begin with?
I did a J2EE Multiserver type installation of CF 6.1 and specified IIS as web server but without any luck, I am getting the following error:
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. Detailed Error Information
Module IIS Web Core
Notification MapRequestHandler
Handler StaticFile
Error Code 0x80070002
Requested URL http://127.0.0.1:80/CFIDE/administrator/index.cfm
Physical Path C:\inetpub\wwwroot\CFIDE\administrator\index.cfm
Logon Method Anonymous
Logon User Anonymous
A:
Try running the web server configuration tool - I believe the Windows executable is wsconfig.exe. From there its fairly intuitive on how to proceed.
Also, try following the instructions here, http://www.communitymx.com/content/article.cfm?page=1&cid=224AA . I know its for CF 7, but it may work with Cf 6.1.
| {
"pile_set_name": "StackExchange"
} |
Q:
Access-specifiers are not foolproof?
If I've a class like this,
class Sample
{
private:
int X;
};
Then we cannot access X from outside, so this is illegal,
Sample s;
s.X = 10; // error - private access
But we can make it accessible without editing the class! All we need to do is this,
#define private public //note this define!
class Sample
{
private:
int X;
};
//outside code
Sample s;
s.X = 10; //no error!
Working code at ideone : http://www.ideone.com/FaGpZ
That means, we can change the access-specifiers by defining such macros just before the class definition, or before #include <headerfile.h>,
#define public private //make public private
//or
#define protected private //make protected private
//or
#define so on
Isn't it a problem with C++ (Macros/access-specifiers/whatever)?
Anyway, the point of this topic is:
Using macros, we can easily violate encapsulation. Access-specifiers are not foolproof! Am I right?
A:
First of all, it's illegal to do that. private is a keyword, and you can't use it as an identifier in a macro; your program would be ill-formed.
But in any case, it's not a problem with macro's at all. It's with the fool who used them in a silly manner. :) (They're there to help you be safe, they're not there to help you be safe and block all access to them no matter what you try. C++ protects against Murphy, not Machiavelli.)
Note that you can access privates in a well-formed and well-defined manner, as demonstrated here. Again, this isn't a problem with the language, it's just not the job of the language to do more than necessary to keep prying hands out.
A:
But we can make it accessible without editing the class! All we need to do is this,
Technically, all you've shown is that "we can turn a legal program into Undefined Behavior" without editing one specific class.
That's hardly news. You can also turn it into undefined behavior just by adding a line such as this to the end of main():
int i = 0;
i = ++i;
Access specifiers in C++ are not a security feature They do not safeguard against hacking attempts, and they do not safeguard against people willfully trying to introduce bugs into you code.
They simply allow the compiler to help you maintain certain class invariants. They allow the compiler to inform you if you accidentally try to access a private member as if it were public. All you've shown is that "if I specifically try to break my program, I can". That, hopefully, should be a surprise to absolutely no one.
As @Gman said, redefining keywords in the C++ language is undefined behavior. It may seem to work on your compiler, but it is no longer a well-defined C++ program, and the compiler could in principle do anything it likes.
A:
But we can make it accessible without editing the class
Not without editing the source file containing the class though.
Yes, macros let you shoot yourself in the foot. This is hardly news... but this is a particularly non-troubling example of it, as to "violate encapsulation" you have to force the class to either define the bone-headed macro itself, or include a header file which does so.
To put it another way: can you see this being an issue in real, responsible software development?
| {
"pile_set_name": "StackExchange"
} |
Q:
Is Ezekiel a reluctant prophet?
Many of God's servants in the Old Testament are reluctant—Moses, Gideon, Saul (eventually defunct), Jonah and Jeremiah spring to mind. Moses protests five times in the course of Exodus 2-3:
11But Moses protested to God, “Who am I to appear before Pharaoh? Who am I to lead the people of Israel out of Egypt?”
13But Moses protested, “If I go to the people of Israel and tell them, ‘The God of your ancestors has sent me to you,’ they will ask me, ‘What is his name?’ Then what should I tell them?”
1But Moses protested again, “What if they won’t believe me or listen to me? What if they say, ‘The Lord never appeared to you’?”
10But Moses pleaded with the Lord, “O Lord, I’m not very good with words. I never have been, and I’m not now, even though you have spoken to me. I get tongue-tied, and my words get tangled.”
13But Moses again pleaded, “Lord, please! Send anyone else.”
Jeremiah expresses reluctance at his commissioning (1:6):
"Lord Yahweh," I said, "I can't speak for you! I'm too young!"
and a complaint later on (20:7-18).
In contrast, Ezekiel does not make a single verbal protest of his call. Does this mean he was a willing prophet? What evidence do we have in the commissioning of Ezekiel (chapters 1-3) for his reluctance or willingness?
A:
His Silence does not Necessarily Indicate Willingness
Ezekiel is not as expressive of his emotions and states of mind as some of the other prophets, so his lack of protest does not necessary mean that he was a willing prophet. In the introduction to his commentary on the book, Daniel Block writes,
Ironically, although the oracles are presented in autobiographical narrative style, occasions when the prophet actually admits the reader into his mind are rare.
The eating of the scroll could be a mechanical obedience, and not one that reflected the state of his heart on the matter.
First Argument For Reluctance: Repetitive Calling
After all, God is quite repetitive in his call to Ezekiel—so much so that after commissioning him once, he leaves him alone for a weak and then commissions him again. This points to tacit resistance in the heart of the prophet.
Rebuttal: Repetition a Significant Theme in Ezekiel
But as in much of the Old Testament, Ezekiel, under the hand of God, makes much use of repetition in the book. Not a rote repetition (nor is God's commissioning of him a rote repetition), but a repetition that drives home and furthers the previous pronouncements on the topic. Moreover, for such a difficult task, a confirmation of calling must have been encouraging.
Second Argument For Reluctance: The Week of Bitterness
Daniel Block comments on the week in which Ezekiel sat stunned and bitter,
Ezekiel is infuriated by the divine imposition on his life and the implications of Yahweh's commission for him... The prophet does indeed share some of the hardened disposition of his compatriots.
Thus, not only is Ezekiel resistant, but he is resistant for a week in spite of the fact that Yahweh's hand is strongly upon him.
Rebuttal: Spiritual Bitterness
But the foregoing conclusion is completely uncalled for. The bitterness and rage needn't have been against Yahweh. Rather the bitterness arises from the opposition he is to receive; the rage against the rebellion of his people. God never asks his servants to treat a hard task as if it was not hard. The rejoicing he requires does not exclude intense grief, and rage is not necessarily ungodly. In fact, profound sorrow and wrath are both displayed clearly in the ministry of Christ Jesus. The experience Ezekiel has undergone is profoundly emotionally disturbing; this does not mean he is in rebellion to Yahweh himself. He is stunned by the glory of Yahweh; is is not only upset, but amazed, and there is no reason to suppose that the two emotions are in conflict. Isaiah, too, who does not resist his call but springs to it eagerly, expresses deep grief at his mission. Ezekiel's amazement and anger are both godly.
First Argument Against Reluctance: The Power of the Spirit
This conclusion seems irresistible when it is considered how thoroughly he was under the power of God. As Block says at multiple times in his commentary, Ezekiel is a man "totally possessed of the Spirit of God." This is evidently one of the crucial things that happens at his commissioning; as he is commanded to do something, he is empowered to so do. This is visualized when he is commanded to stand up by the voice and the Spirit lifts him and sets him on his feet. Moreover, in his week of bitterness he notes that the hand of Yahweh was strongly upon him. What does this mean but that his soul was being directed by the Spirit of God in an unusual and powerful way? Surely the conclusion that the Spirit works on Ezekiel from some external manner, or in purely physical ways, must be resisted. If Ezekiel is possessed of the Spirit, his disposition must be submissive—regardless of what it may have been before the theophany.
Second Argument Against Reluctance: The Theophany
Indeed, the theophany itself argues of his willingness. Neither Moses, nor Gideon, nor Jeremiah, nor Jonah, nor any other servant of God in the Old Testament save Isaiah, had a theophany to compare with Ezekiel's. But Isaiah also is a willing prophet ("Lord, how long must I do this?" is clearly sadness, not resistance). How could a prophet have a vision of the grandeur and excellence of Ezekiel 1 and yet resist the Spirit of God for a week? Of what account is it then to see the appearance of the likeness of the glory of Yahweh?
Who Cares?
I conclude that Ezekiel was made pliable to God's will by his Spirit-aided apprehension of the vision of the glory of God and so was not a reluctant prophet. But why bother to speak at such length on an apparently arcane subject? Several reasons, already alluded to, can be adduced in closing as for the importance of this point.
Maintaining a right understanding of the power of the Spirit of God and his mode of operation in softening hearts.
Understanding the irresistible transformation worked by a clear vision of the glory of God.
Seeing more fully the typology between Ezekiel and the Son of Man he prefigures.
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular sourcing textarea from file
I am trying to load text file config1100.txt to textarea (on initial page load), see below. Also tried http://localhost:3000/data/config1100.txt (file is avail), no success so far.
<p><textarea ng-src="data/config1100.txt" type="text" id="textarea" model="myTextArea" cols="80" rows="10" >
</textarea></p>
A:
like this irom:
var app = angular.module("angularApp", []);
app.controller("myConfigGenCtrl", function($scope, customService)
{
customService.getData().then(function(response)
{
$scope.myTextArea = response.data; //-- scope.myTextArea is your ng-model on your text area
});
});
app.service('customService',function($http)
{
this.getData = function()
{
return $http.get('localhost:3000/data/config1100.txt');
};
});
also, your text area attribute model should be ng-model
| {
"pile_set_name": "StackExchange"
} |
Q:
Implementing map on a tree using fold
I am trying to implement a map using fold. I could do so in Haskell
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show)
foldTree :: Tree a -> b -> (b -> a -> b -> b) -> b
foldTree EmptyTree d _ = d
foldTree (Node a l r) d f = f (foldTree l d f) a (foldTree r d f)
mapTree :: Tree a -> ( a -> b) -> Tree b
mapTree tree f = foldTree tree EmptyTree (\l n r -> Node (f n) l r)
However when I tried to port it to Scala, I am a bit stuck
sealed trait Tree[+A]
case object EmptyTree extends Tree[Nothing]
case class Node[A](value: A , left: Tree[A], right: Tree[A]) extends Tree[A]
def fold[A, B](t:Tree[A] , z:B)(f:(B,A,B) => B) : B = t match {
case EmptyTree => z
case Node(x,l,r) => f ( fold( l , z )(f) , x , fold( r , z )(f) )
}
def map(tree:Tree[Int])(f:Int=>Int) : Tree[Int] = fold(tree , EmptyTree)((l,x,r) => Node(f(x),l,r))
The compiler complains that it is expecting an EmptyTree in function I pass to fold.
fold(tree , EmptyTree)((l,x,r) => Node(f(x),l,r))
The return type for the Map is Tree so I would have expected this to work. Any suggestions ?
A:
Try to write your last line as
def map(tree:Tree[Int])(f:Int=>Int) : Tree[Int] = fold(tree , EmptyTree:Tree[Int])((l,x,r) => Node(f(x),l,r))
Scala's type inference is very limited compared to haskell, in this case it tries to infere type of fold from it's arguments left to right, and incorectly decides that result type of fold should be EmptyTree and not the Tree[Int]. Usually adding auxilary constructor to the companion object of the parent type helps in this situation a bit, for instance in the Option object there's a constructor
def empty[A]: Option[A]
which returns the parent type.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the significance of the second property in the sheafification of a pre-sheaf?
Let $\mathcal{F}$ be a pre-sheaf on $X$. It seems that if we let $\mathcal{F}^+(U)$ to be the set of all maps $U \rightarrow \cup_{p \in U} \mathcal{F}_p$, where $\mathcal{F}_p$ is the stalk of $\mathcal{F}$ at p with the single requirement that $s(p) \in \mathcal{F}_p$, then we have a sheaf on $X$. Where exactly does the second requirement in the sheafification comes into play?
Edited: The second requirement is that any map $s:U\rightarrow \cup_{p \in U} \mathcal{F}_p$ satisfies the following property: for any point $p \in U$ there exists a neighborhood $V \subseteq U$ of $p$ and $t \in \mathcal{F}(V)$ such that for any
$q \in V$ we have $t_q=s(q)$, where $t_q$ is the germ of $t$ at $p$.
A:
Indeed $\mathcal{F}^+$ is a sheaf on $X$.
However it has absurdly large sets of sections: since there is no constraint on the choice of $s(p)$ when $p$ varies, essentially all links with $\mathcal F$ are dissolved.
It has however one redeeming feature: it serves as a huge container for the correct sheafification $\mathcal F^{sh}$ of $\mathcal F$.
Indeed by definition $\mathcal F^{sh}(U)\subset \mathcal F^+(U)$ consists of those $s\in \mathcal{F}^+(U)$ such that locally near each $p_0\in U$ there exists $t\in \mathcal F(V)$ ($p_0\in V\subset U$) with $s(p)=t_p$ for all $p\in V$.
The second axiom for sheaves is then automatically satisfied for $\mathcal F^{sh}$.
Moreover the construction immediately yields a morphism of presheaves $\mathcal F\to \mathcal F^{sh}$ which is injective iff the first axiom for sheaves is verified for the presheaf $\mathcal F$.
To sum up visually, we have canonical morphisms of presheaves : $$\mathcal{F}\to \mathcal F^{sh} \hookrightarrow \mathcal{F}^+$$ (and the last two presheaves are sheaves).
A:
A very optional complement
For the sake of completeness and for the record, I'd like to analyze the nature of the functor (from presheaves to sheaves) $\mathcal F\to \mathcal F^+$ on an example and show that it is subtler than one might think.
Let $X$ be a topological space, $\mathcal C$ be the sheaf of real-valued continuous functions on $X$ and $\mathcal Disc $ the sheaf of all real-valued functions, maybe discontinuous: $\mathcal Disc (U)=\mathbb R^U$.
We have a morphism of sheaves $\mathcal C^+\to \mathcal Disc$ given by
$$\mathcal C^+(U)\to \mathcal Disc ( U): s\mapsto \tilde s \text { where} \;\tilde s(x)=(s(x))(x)$$
The strange but logical notation $(s(x))(x)$ means that $s(x)=f_x\in \mathcal C_x$ is the germ at $x$ of some continuous function $f$ defined near $x$ and that you then take the value $f(x)=f_x(x)$ of that function at $x$ and obtain the real number $\tilde s(x)$.
It is then true that for every $U\subset X$ the map $\mathcal C^+(U)\to \mathcal Disc ( U)$ is surjective [take germs of constant functions in the domain], so that a fortiori the morphism of sheaves $\mathcal C^+\to \mathcal Disc $ is surjective.
But the morphism of sheaves $\mathcal C^+\to \mathcal Disc $ is not injective, because the morphism $\mathcal C(X)\to \mathcal Disc ( X)$ (for example) is not injective.
Indeed choose $x_0\in X$ and take for $s\in \mathcal C^+(X)$ the collection of germs $s(x)=0_x$ for $x\neq x_0$ and $s(x_0)=g_{x_0}$ where $g$ is a non-zero continuous function (defined near $x_0$) satisfying $g(x_0)=0$.
Then $\tilde s=0\in \mathcal Disc ( X)$ although $s\neq 0\in \mathcal C^+(X)$
If you start with the sheaf $\mathcal C_b$ of locally bounded continuous functions on $X$, you will find $\mathcal C_b^+=\mathcal C^+$ and the same analysis applies .
Conclusion
You may forget all the details above and just remember that $\mathcal C^+$ is not the sheaf $\mathcal Disc$ of arbitrary [and possibly very discontinuous] functions on $X$, but an even much more horrible sheaf !
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ Char errors
So I'm trying to take the second to first character from Expresie which is a char array and copy it into a char variable, and then use the strcat function to place that variable at the end of another char array Stiva. this is the code:
int SHIFT(char Expresie[], char Stiva[], int x)
{
char a=Expresie[0];
strcat(Stiva,a);
And this is how they are defined in main:
int main()
{
char Expresie[100];
char Stiva[100];
The problem is that when i run it it says : invalid conversion from 'char' to 'const char*'
A:
strcat appends strings, not characters - it wants a pointer to the first character of a "C string", not a single char.
The simplest way to do this is to add the character directly at the end yourself (assuming that there is room, of course):
int SHIFT(char Expresie[], char Stiva[], int x)
{
char a=Expresie[0];
size_t length = strlen(Stiva);
Stiva[length] = a;
Stiva[length+1] = 0;
// ...
| {
"pile_set_name": "StackExchange"
} |
Q:
How get latest commit from gocd and detect did it change some specific folder?
I'm using gocd continious delivery tool + git. My project consists of many subprojects. I don't want to rebuild all subprojects on each commit and thus created one pipeline for each subproject. I know, that for each pipeline, say for project1, I have to choose appropriate working dir and run smth like that:
get git commit which triggered gocd build.
detect whether
changes in that commit contain project1 folder
if changes in
whole project also affected project1 folder run custom build command
for project1.
How may I get commit from gocd which triggered current build? Is it simply git's latest commit or not? I thing latest commit is not safe option in case of many concurrent commits, that's why I want to get it directly from gocd - I hope it stores it for each build trigger event. How detect commit affects on folder in bash?
A:
As you said, you are using a different pipeline for each sub project.
For a quick hack, you can use the "Blacklist" field when adding a material. It basically says the pipeline, not to trigger(start building) when these files(entered in the Blacklist field) are changed in the commit.
I know, it is a bit tricky, but if you don't change your sub-poject folders more often, this can solve your problem.
Hope this helps :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Programmatically create an ng-show value in ng-repeat
I have the following:
<div class="row" ng-repeat="item in items " ng-cloak>
<div ng-show="unique{{$index}}" class="ng-hide">
<button ng-click="remove('{{$index}})">Remove</button>
</div>
I want to create a unique value for every div item repeated,like so:
<div ng-show="unique1" class="ng-hide">
<button ng-click="remove('unique1')">Remove</button>
<div ng-show="unique2" class="ng-hide">
<button ng-click="remove('unique2')">Remove</button>
so that in my controller I can have an action, in this case remove(), that will toggle that attribute.
scope.remove = function(uniqueAttribute) {
$scope[uniqueAttribute] = false;
}
I was able to generate the html using $index but that code does not work and I am sure not sure how to go about accomplishing this.
A:
You can add a new field called show to each object and then you can eliminate all logic relating to the $index.
<div ng-app ng-controller="Ctrl">
<div class="row" ng-repeat="item in items" ng-cloak>
<div ng-show="item.show">
<button ng-click="remove(item)">Remove</button>
</div>
</div>
</div>
function Ctrl($scope) {
$scope.items = [{
item1: 1,
show: true
}, {
item1: 2,
show: true
}, {
item1: 3,
show: false
}];
$scope.remove = function (item) {
item.show = false;
}
}
DEMO
A:
Most attributes in Angular are either evaluated or interpolated. Evaluation is like a restricted form of eval(), interpolation is when the double curly braces get filled in. It looks like you're expecting the ng-show to be interpolated then evaluated, but none of the built-in directives do this. They do one or the other but not both. For ng-show specifically it just does evaluation, so your curly braces pass through literally. This would be an invalid expression.
My suggestion is this: Since ng-repeat creates a new scope for each repeated item, you can just do this:
<div class="row" ng-repeat="item in items" ng-cloak>
<div ng-show="!hide" class="ng-hide">
<button ng-click="hide = true">Remove</button>
</div>
Of course, why keep a bunch of hidden items around. Why not have ng-click="remove(item)" and a remove function that removes from items? Then the ng-repeat updates naturally.
$scope.remove = function(item) {
var index = this.items.indexOf(item);
if (index != -1) {
this.items.splice(index);
}
};
Or something like that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find two $2 \times 2$ matrices $A$ and $B$ with the same rank, determinant,...but they are not similar.
Question:
Find two $2 \times 2$ matrices $A$ and $B$ with the same rank, determinant, trace and characteristic polynomial, but they are not similar to each other.
My thought:
I come up with two matrices:
$A=\begin{pmatrix}
0 &1 \\
0 &0
\end{pmatrix}$ and $B=\begin{pmatrix}
0 &0 \\
1 &0
\end{pmatrix}.$
It is easy to check that they have same rank, determinant, trace and characteristic polynomial. However, my question is I do not know how to prove two matrices are similar or not.
I have learnt the converse in my textbook, i.e. If two matrices are similar, they have the same determinant, characteristic polynomial,etc.
I have also known that (but I do now know the proof), we can check by using Jordan form of two matrices. I do not know if this claim is correct:
"If two matrices have the same Jordan form, they are similar to each other."
Yet, go back to the question, is it a quick way to prove? Thank you in advance.
A:
Try $A = \begin{bmatrix} 2 & 1 \\ 0 & 2 \end{bmatrix}$ and $B = \begin{bmatrix} 2 & 0 \\ 0 & 2 \end{bmatrix}$. They are both rank 2.
A:
Your matrices are similar, related by $\begin{pmatrix}0&1\\1&0\end{pmatrix}$.
By inspection, what each of your matrices do is kill one basis vector while turning the other into the first one. That's intuitively similar, so to transform one to the other all we have to do is swap the basis vectors which is what $\begin{pmatrix}0&1\\1&0\end{pmatrix}$ does.
Hint. The rank (if full), determinant, trace, and characteristic polynomial of a triangular matrix depends only on the diagonal elements.
| {
"pile_set_name": "StackExchange"
} |
Q:
fullcalendar loaded with ajax symfony2 doctrine2
this my function in controller
public function loadcalendarAction() {
$eventsloaded = $this->container->get('calendarbundle.serviceloadcalendar')->loadCalendar();
$response = new JsonResponse();
//dump($eventsloaded);
//die();
$response->setData(array('events' => $eventsloaded));
return $response;
}
the $eventsloaded is an array of 2 events in my database its OK .. but $response is empty i don't know why ..
and this my calendar_setting.js
$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2016-01-12',
lang: 'ar-tn',
buttonIcons: false, // show the prev/next text
weekNumbers: true,
editable: true,
eventLimit: true, // allow "more" link when too many events
dayClick: function () {
alert('a day has been clicked!');
},
events: Routing.generate('loadcalendar')
});
});
if the response not empty all the events will be displayed in the events:
A:
Look at this questions' answer. You need either to use some external bundle (such as JMSSerializerBundle) to serialize entity, to pass it to json response, or implement something like toArray() method in your entity which will return an array of needed data from entity, after that you could do smth like:
$responseData = [];
foreach ($eventsloaded as $i => $event) {
$responseData[$i] = $event->toArray();
}
return new JsonResponse($responseData);
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - Scipy: multivariate_normal - select the right subsets of input
Any help that pushes me towards the right solution is greatly appreciated...
I am trying to do a classification in two steps:
1.) Calculate mu, sigma, and pi on the training set.
2.) Create a test routine, that takes
- mu, sigma, pi
- an array of Feature IDs
- testx and testy.
Part 1.) works. It returns
- mu # shape 4,13
- sigma # shape 4,13,13
- pi # shape 4,
def fit_generative_model(x,y):
k = 3 # labels 1,2,...,k
d = (x.shape)[1] # number of features
mu = np.zeros((k+1,d))
sigma = np.zeros((k+1,d,d))
pi = np.zeros(k+1)
for label in range(1,k+1):
indices = (y == label)
mu[label] = np.mean(x[indices,:], axis=0)
sigma[label] = np.cov(x[indices,:], rowvar=0, bias=1)
pi[label] = float(sum(indices))/float(len(y))
return mu, sigma, pi
Part 2.) does not work, as I seem to be unable to select the right subsets of mu and sigma
def test_model(mu, sigma, pi, features, tx, ty):
mu, sigma, pi = fit_generative_model(trainx,trainy)
# set the variables
k = 3 # Labels 1,2,...,k
nt = len(testy)
score = np.zeros((nt,k+1))
covar = sigma
for i in range(0,nt):
for label in range(1,k+1):
score[i,label] = np.log(pi[label]) + \
multivariate_normal.logpdf(testx[i,features], mean=mu[label,:], cov=covar[label,:,:])
predictions = np.argmax(score[:,1:4], axis=1) + 1
errors = np.sum(predictions != testy)
return errors
It should return the number of mistakes made by the generative model on the test data when restricted to the specified features.
A:
Try this. It should work.
mean=mu[label,features], cov=covar[label,features,features]
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you do a Google Home call?
I am aware that you can do Alexa calling: we've even had numerous questions about it. Is it possible to do something similar with the Google Home? If so, how would it be done?
Particularly, I want to know if it is possible to call a friend who has another Google Home and if so, how it would be done.
A:
Answer to your main question:
I want to know if it is possible to call a friend who has another Google Home
is no, you cannot do that exactly. In the link by @Bence Kaulics in comments it is said you can call outbound (to a phone) but inbound calls are not possible. That means the destination cannot be another Google Home but only owners phone.
Making an outbound call is as easy as saying Hello Google, call NN, where NN is one of your contact or a phone number.
At the moment though 911 calls aren't possible. Another issue is that for normal user your number is not shown to the responding phone, which may feel embarrassing.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't add NPM libraries with Netbeans
I'm trying to use Netbeans IDE to libraries to a project with npm, but the dialog seems to display corrupted characters, almost like there's a character set mismatch.
Is this issue with my configuration or a Netbeans bug?
This happens with a brand new JS project as well as existing ones.
Netbeans 8.2 on Windows 10
npm 4.2.0
A:
First notice please, that this solution will modify the package.json in your source-folder. So, after you add a package, close the window (ignore the error-msgs) and open the package.json in the source-folder to fix the json-syntax manualy.
Exemplary:
"dependencies": {"electron ||||":"2.0.5 ||||",}
to:
"dependencies": {"electron": "2.0.5"}
(Need a bit knowing about JSON-Syntax maybe)
After saving the package.json go to the project-property-tool. You will see the correct package in the overview. You will have to still update the package and press OK.
I hope my instructions helps.
Regards
//Sunny
| {
"pile_set_name": "StackExchange"
} |
Q:
Delphi 2010 inlining useless?
What is the go with inlining functions or procedures in Delphi (specifically v2010 here, but I had the same issue with Turbo Delphi)?
There is some discalimer in the help about it may not always inline a function because of "certain criteria" whatever that means.
But I have found that generally inlining functions (even very simple ones that have 3 or 4 lines of code) slows down code rather than speeds it up.
A great idea would be a compiler option to "inline everything". I don't care if my exe grows by 50% or so to get it working faster.
Is there a way I can force Delphi to really inline code even if it is not decided to be inlinded by the compiler? That would really help. Otherwise you need to do "manual inlining" of replicating the procedure code throughout multiple areas of your code with remarks like "//inlining failed here, so if you change the next 5 lines, change them in the other 8 duplicate spots this code exists"
Any tips here?
A:
There's a compiler option for automatic inlining of short routines. In Project Options, under Delphi Compiler -> Compiling -> Code Generation, turn "Code inlining control" to Auto. Be aware, though, that this should only be on a release build, since inlined code is difficult to debug.
Also, you said that you don't mind making your program larger as long as it gets faster, but that often inlining makes it slower. You should be aware that that might be related. The larger your compiled code is, the more instruction cache misses you'll have, which slows down execution.
If you really want to speed your program up, run it through a profiler. I recommend Sampling Profiler, which is free, is made to work with Delphi code (including 2010) and doesn't slow down your execution. It'll show you a detailed report of what code you're actually spending the most time executing. Once you've found that, you can focus on the bottlenecks and try to optimize them.
A:
Inlining can make things slower in some cases. The inlined function may increase the number of CPU registers required for local variables. If there aren't enough registers available variables will be located in memory instead, which makes it slower.
If the function isn't inlined it will have (almost) all CPU registers available.
I've found that's it's typically not a good idea to inline functions containing loops. They will use a couple of variables which are likely to end up in memory, making the inlined code slower.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find more about a method from rubydoc: Gem::Dependency#pretty_print
I am going through the source code of Gem::Dependency#pretty_print method. I don't understand what argument q is.
def pretty_print q # :nodoc:
q.group 1, 'Gem::Dependency.new(', ')' do
q.pp name
q.text ','
q.breakable
q.pp requirement
q.text ','
q.breakable
q.pp type
end
end
My question is, what do I do next from here. I searched pretty_print in their Github repo. They do not have any specs nor any function which uses this method. How can I know what it takes as input q? They have defined this method for several other objects.
Background and more details:
I am working on a script which reads Gemfile and shows each mentioned Gem with its description. Whenever I am going through the code of any new project which has a long list of Gems, it is difficult to go through each Gem's website and see what the Gem does.
From rubydoc I found how Bundler parses the Gemfile. And came across this method: Bundler::Dsl#evaluate
def self.evaluate(gemfile, lockfile, unlock)
builder = new
builder.eval_gemfile(gemfile)
builder.to_definition(lockfile, unlock)
end
Here also it is not mentioned what should be passed as gemfile, lockfile, unlock. I searched for the method evaluate in their Git repo. I found the spec and I learned that I could pass "Gemfile", nil, true as the argument.
I mentioned the flow so that if I can get any comments on it and improve.
A:
pretty_print method is going to be used by pp.
By defining pretty_print we can customize the output of pp as per their documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Modal jQuery ou Bootstrap que receba e-mail e nome, exibido automaticamente ao carregar a página
Tentei o seguinte codigo, mas não está funcionando
<script type="text/javascript">
$(document).ready(function() {
$('#myModal').modal('show');
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="myModal" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
Conteudo
</div>
</div>
</div>
A:
O problema é que você está chamando o jquery.min.js depois do código.
Tente isso:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="CAMINHO_DO_BOOTSTRAP.MIN.JS_AQUI"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myModal').modal('show');
});
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Grab all links from a page
I want to grab all links (href) from a page.
This is my actual code:
preg_match_all('/href=.([^"\' ]+)/i', $content, $anchor);
But this grabs only domains and subdomains (like name.name.ex or name.ex) but doesn't grab custom URLs like name.ex/name/name.php.
Can anyone please help with the regular expression?
A:
I advise against use of regular expression for this. I suggest that you use DOM to parse and get your results.
Below is an example for this using DOM and XPath
$html = '<a href="name.ex/name/name.php">text</a>
<a href="foo.com">foobar</a>';
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//a') as $link) {
$links[] = $link->getAttribute('href');
}
print_r($links);
See Working demo
| {
"pile_set_name": "StackExchange"
} |
Q:
h:panelGrid with embedded h:graphicImage not displaying correctly
My question regards the display of h:graphicImage within a h:panelGrid
<h:panelGrid border="0" cellspacing="0" cellpadding="0" >
<h:graphicImage height="63" width="270" value="images/NewAOnly.PNG" />
<h:graphicImage height="60" width="270" value="images/NewABottom.PNG" />
</h:panelGrid>
The top .PNG file is 270 x 63 with no border area. The bottom .PNG is 270 x 60 with no border area.
My question is, with border="0", cellspacing="0" and cellpadding="0", why do the two images not sit one on top of the other with no space between them?
A:
This will happen when you use a strict doctype. Long story short, check the article on Mozilla Developer Network: Images, Tables, and Mysterious Gaps. As to the doctype, you can fix this by using a quirks or transitional doctype (as a quick test, remove the DOCTYPE line altogether). This is however not recommended these days.
If you're absolutely positive that the table is the right tool for your concrete functional requirement of displaying images this way and e.g. a div is for some dubious reason absolutely not an option (and you're fully aware of the importance of "Semantic HTML"), then you can fix this by making the images in table cells block level elements.
td img {
display: block;
}
Please note that this problem is completely unrelated to JSF. JSF is in the context of this question merely a HTML code generator.
| {
"pile_set_name": "StackExchange"
} |
Q:
Lenz' law versus $-\frac{d\Omega}{dt}$
I am preparing for an exam, on one problem my answer differ from the solution.
The current $i(t)=I_0e^{-\alpha t}$ runs in a long straight conductor along $\hat z$.
Point A,B,C,D forms a triangle.
A and B is at $L \hat x$ with a very small separation in $\hat z$ with a resistance R between.
C and D is at $2L \hat x$ with a separation in $\hat z$ of $2L$.
The question is: What is the induced current in the triangle.
I calculated the flux $\Omega$ correctly, but my answer differ on the direction of the current.
I took $V_{ind}=-\frac{d\Omega}{dt}$, since $i(t)$ is decreasing, the magnetic flux passing through ABCDA is decreasing, and so (to my understanding) it is reasonable that $i_{ABCD}=\frac{V_{ind}}{R}$ will run clockwise (using right-hand notation).
However, in the solution to the problem they too use $V_{ind}=-\frac{d\Omega}{dt}$ but then "magically" on the next line remove the minus sign and says that according to Lenz law the current opposes the magnetic flux that caused the current and so will run counter-clockwise.
I would be thankful for an intuitive understanding for why it is opposing the magnetic flux that caused the current and not opposing the change in the magnetic flux?
Thanks.
A:
Actually, it does oppose the change in the magnetic flux causing it. If the magnetic field from the source is increasing in some direction, the magnetic field from the induced current decreases in the same direction to oppose the increase, for example. The induced current opposing the change causing it ensures that the cause must supply energy to the system to increase the induced current, so guaranteeing conservation of energy.
The magnetic field from the wire points towards $\hat y$ and is decreasing, which means the magnetic field has to increase in the same direction from the induced current. Therefore the current runs clockwise around the loop.
The negative sign in Lenz's law is needed when using the right hand rule to find the direction of the induced emf: The thumb points in the direction of the applied magnetic field, and the curled fingers point around the direction of the induced emf. In your example, the thumb points towards $\hat y$ and the fingers curl in a clockwise sense. The magnetic field decreasing cancles the minus sign so the direction is the same as the fingers - clockwise.
| {
"pile_set_name": "StackExchange"
} |
Q:
Will there be any copyright issue if we use an existing product's name?
In software industry, while naming a new app or a product, will there be any copyright issue if we use an existing name?
A:
The term in your question, "use an existing name", is pretty broad.
Do you propose to say, "Compatible with Microsoft Lync"?
Or will you actually name your product "Lync"?
The first option is likely safe. The second one looks like a Trademark infringement more than a copyright issue. And "Lync" is distinctive enough, you probably won't win.
However, if you propose to name your product "Messenger", you're slightly better off because "messenger" is a generic term in the English Language, even if Facebook adopted it for their product.
The major criteria would be if your chosen name is likely to cause confusion with Facebook's product.
A:
The names of software programs and apps, like the titles of books and movies, are not protected by copyright. However, they are often protected as trademarks. If a new product uses the name of an existing product, or part of it, or a significantly similar term, or a visual symbol such as a logo, such that a reasonable person might be falsely led to believe that the new thing is made by, endorsed by, approved by, sponsored by, or in some way affiliated with the makers of the existing thing, that might well be trademark infringement. If a reasonable person might be confused about the source, approval, or endorsement, that could also be infringement. It will only be infringement if the name (or symbol) of the existing product is protected as a trademark.
The rules for obtaining protection are different in different countries. In some countries, merely using a name or logo in commerce will grant at least some protection. In other countries, some sort of official registration is required for any protection to apply.
It is generally permitted to refer to another product by its name for purposes of comparison or review or similar reference, provided that no "passing off" a product as being from or affiliated with the makers of the other product is being done, and no confusion is probable. This is known as nominative use. For example:
Compatible with Acme Corp's WordMaker.
50% faster than Acme Corp's WordMaker.
Half the price of Acme Corp's WordMaker.
would all be permissible. A prominent disclaimer, such as "This product made by Zebra Corp, and is in no way sponsored by, endorsed by, or affiliated with Acme Corp. "WordMaker" is a trademark of Acme Corp." helps to make sure that no reasonable person would be confused.
Note also that use of a name out side of commerce, that is in no way connected with selling or advertising a product or service is generally not subject to trademark protect. But again, the law on this varies in different countries.
Note also that a name or other mark that is not distinctive will receive little or no protection. I could open a shop called "David's Best Pizza", but I would probably not win a trademark suit against a shop called 'Tom's Best Pizza", as "Best Pizza" is not very distinctive.
Note also that trademarks are generally protected only in the industry and geographic region where they are used. A product called "Dolphin Pizza" sold in New York would likely be protected in New York, and perhaps New Jersey, but probably not in California. And that trademark probably would not be able to prevent someone from using "Dolphin" as the name of a line of pools, or showers, or computers. However, at least in the US, "Famous" marks which are widely recognized get wider protection. The mark "IBM" might be protected even in industries that IBM has never marketed any product in, for example.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add HTML element inside JS variable
var $document = $(document);
var selector = '[data-rangeslider]';
var $element = $(selector);
// For ie8 support
var textContent = ('textContent' in document) ? 'textContent' : 'innerText';
// Example functionality to demonstrate a value feedback
function valueOutput(element) {
var value = element.value;
var output = element.parentNode.getElementsByTagName('output')[0] || element.parentNode.parentNode.getElementsByTagName('output')[0];
output[textContent] = value + 'mm';
}
$document.on('input', 'input[type="range"], ' + selector, function(e) {
valueOutput(e.target);
});
in the line output[textContent] = value + 'mm'; I need the output as value + '<span class="classname">mm</span>'
I tried most of the things and did a lot of research but no luck so far.
This might be something very simple but I am too new to JavaScript so couldn't figure it out.
A:
You should change this line:
output[textContent] = value + 'mm';
to:
output.innerHTML = value + '<span>mm</span>';
Also, you could remove the IE8 fallback, as it will not be necessary. All browsers have support for innerHTML.
In your code you are assigning the node text and not the node HTML as you should.
You can read more about the difference between innerText and innerHTML here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can't consecutive irrational numbers be treated mathematically as limits?
I'm a relative newcomer to these stackexchange websites, and this post will serve as my introduction to the Mathematics stackexchange site.
After perusing some of the related questions, I found these to be the most relevant to my question: 1) Why can't you count real numbers this way?, 2) Why there is not the next real number?, 3) Proof that the real numbers are countable: Help with why this is wrong, and 4) Why does the Dedekind Cut work well enough to define the Reals? .
In related question #1), the concept of an "index" with regard to the un/countability of the set of real numbers was mentioned. I have encountered that term before in past discussions regarding the countability of transfinite ordinal sets (in other math forum websites), but I'm not sure what it means.
In any case, I understand the "real-number line" to be composed of the set of rational numbers (whose cardinality is $\aleph_0$) which have sets of "gaps" between them, each of which is filled in by a set of irrational numbers (whose cardinality is $\aleph_1$). My "understanding" is that there are no "gaps" between any two consecutive irrational numbers, and likewise, no "gaps" between a rational number and the irrational numbers that immediately precede and follow it. If all of this is true, then given some number $n$ (rational or irrational), why can't I write the next consecutive irrational number that immediately follows n as $\lim_{t\to\infty}n+10^{-t}$.
A:
You asked specifically
why can't I write the next consecutive irrational number that immediately follows n as $\lim_{t\to\infty}n+10^{-t}$.
This $\lim_{t\to \infty}$ notation is a mathematical term of art; it has a specific meaning, and it simply doesn't mean what you think it does. You have the idea that it means $n$ plus some tiny tiny number that is smaller than every other number. But it doesn't mean that, because there is no such thing as a tiny tiny number that is smaller than every other number. What you have written is actually a complicated way of writing the number $n$, nothing more.
I sympathize with your desire to invent a tiny tiny number that is smaller than every other number, because it sounds plausible, and almost everyone tries to do it at some point. But on closer investigation, the idea turns out to be incoherent, and this is why there is no notation for that tiny tiny number.
Consider this analogy: the phrase “the biggest purple hat in my closet” sounds reasonable, and there is no obvious reason why such a thing doesn't exist. But in fact there is no such thing as the biggest purple hat in my closet, although you have to know a bit about the contents of my closet to know this. (I don't have any purple hats.)
Similarly, there is no such thing as the number that is the next bigger real number after $n$, although you have to know a little bit about real numbers to realize this. For suppose there were such a number; let us call it $y$. Then let $\epsilon = y - n$. Since $y$ is bigger than $n$, the number $\epsilon$ is positive. But then $\frac\epsilon2$ is positive also, although smaller than $\epsilon$, so we have $0 < \frac\epsilon2 < \epsilon$. Then adding $n$ to each part of that inequality, we get $$n < n+\frac\epsilon2 < n+\epsilon = y$$ which shows that $n+\frac\epsilon2$ is between $n$ and $y$, and therefore that $y$ was not the next number bigger than $n$. But this argument works for any possible number $y$ that you could invent, so the whole idea of a number $y$ that is the next bigger number after $n$ has to be scrapped.
I'm not sure this answers your question, but your question is based on several basic (but very common) misunderstandings of how numbers work, so I hope this helps clear up some of it. But the question posed by the title of your question, “Why can't consecutive irrational numbers…” can be answered without even reading the whole thing; the answer is “because there is no such thing as consecutive irrational numbers.”
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails: Advantages of storing session in database?
I'm just wondering why storing session in database? Is there any advantage to storing session in database?
A:
The advantage to the database or memcached is that session data cannot be tampered with on the client side and that you can store a larger amount of data than you would with cookies (4kB).
If your session is stored in cookies or the database and the web service is restarted then the session data is not lost. It may only be lost if it is stored in memcached.
If the server is load balanced then the session data is passed to the web server that is serving the request, so this is not an issue with cookies, database, or memcached sessions.
The advantage of cookies over memcached or the database is that the client stores the session data, so the server is not responsible for it.
Keep in mind that either way cookies will be passed to and from the client because a session reference still needs to be maintained.
A:
The two reasons I can think of are that:
1) If the web service is restarted, the session data is not lost
2) In a load balanced environment, the session data is stored in a central location, meaning any server can serve the request and have access to the session data.
A:
There are at least three reasons I can think of. If you save the session in the DB you can:
access it easily on any Rails instance you execute. So if you have more than one machine, you don't have to worry about distributing the session data.
You don't have the 4kb session limit session that only aplies when using cookie session store. Although you are not supposed to use the session to store objects, you may that functionality some day.
When using and RDBM (and not Memcached, or any other non persisted storage) you don't have to worry about loosing session data.
| {
"pile_set_name": "StackExchange"
} |
Q:
ERR_SSL_PROTOCOL_ERROR in chrome 39 and 40 but works in chrome 36.Help fix in chrome 39
I am able to access a URL in Chrome 36 and IE8 but in Chrome 39 or 40 or Firefox 35 it throws the error:
Unable to make a secure connection to the server. This may be a
problem with the server, or it may be requiring a client
authentication certificate that you don't have.
Error code: ERR_SSL_PROTOCOL_ERROR}.
It seems that it is an issue related to the SSL certificate. How can I fix this?
A:
Google announced that they would begin removing support for SHA-1 cryptographic hash algorithm beginning with Chrome 39. According to Google:
HTTPS sites whose certificate chains use SHA-1 and are valid past 1 January 2017 will no longer appear to be fully trustworthy in Chrome’s user interface.
There are several sites which can provide detailed analysis of your SSL certificate chain, such as Qualys SSL Labs' SSL Test.
Google Chrome does have a highly risky command-line option --ignore-certificate-errors which might bypass certain certificate errors. Be aware that ignoring certificate errors puts all of your SSL traffic at risk of being eavesdropped on.
It's also possible that this is a new bug. Google switched from using OpenSSL library to it's own "BoringSSL" library in Chrome 38. To report a bug in Chrome visit chrome://help/ and click "Report an issue".
| {
"pile_set_name": "StackExchange"
} |
Q:
Ensuring that "finally" runs on same thread when thread terminates
Here's a puzzle for you guys. I have a multithreaded program in which some threads work with managed resources like locks and semaphores. Some of the lock release primitives can only be performed from the same thread on which the lock acquire was done.
So here's my puzzle: I wrap these kinds of operations: try { lock-acquire... do something } finally { lock-release }, but sometimes when my threads terminate, the finally clauses are performed by the .NET garbage collection thread and not by my thread. (The specific case actually involves the Dispose of an object allocated in a "using" statement; see below for details)
This is a little tricky to demo; I see it all the time in Isis2, and I've figured out that this is happening by checking the thread-ids in the acquire and finalize blocks. But I don't have a 3-line demo for you, and I am sorry about that. I know it would make it easier to provide help.
Is there a way I can delay termination for a thread until all pending finalize blocks associated with that thread have executed?
---- Details added for Mark ----
What I'm really doing involves a fairly elaborate self-instrumenting locking package that has various locking abstractions (bounded buffers, barriers, normal locks, etc) with thread priorities and designed to self-detect deadlocks, priority inversions, very slow lock grants and other problems. My code is complex enough and threaded enough so that I needed this to debug it.
An example of my basic style of construct is this:
LockObject myLock = new LockObject("AnIsis2Lock");
...
using(new LockAndElevate(myLock)) { stuff }
A LockObject is a self-monitoring lock... a LockAndElevate makes note that I locked it (in this case) and later tracks the dispose, when I unlock it. So I'm exploiting the fact that using should dispose of the new object when the block completes -- even if it throws an exception.
What I'm seeing is that fairly often, threads terminate and yet the using dispose events haven't actually occurred; they run later, on some other thread. This only happens when one of my threads terminates; in normal execution, the whole thing works like a charm.
So since using translates to try... finally, my question was posted in terms of finally clauses.
A:
So as of now, here's my best answer to my own question, based mostly on experience debugging the behavior of Isis2.
If threads don't terminate, "using(x = new something()) { }" (which maps to "try { x= new something(); ...} finally { x.dispose }") works precisely as you would expect: the dispose occurs when the code block is exited.
But exceptions disrupt the control flow. So if your thread throws an IsisException, or something down in "something" does so, control passes to the catch for that exception. This the case I'm dealing with, and my catch handler is higher on the stack. C#/.NET faces a choice: does it catch the IsisException first, or does it do the dispose first? In this case I'm fairly certain the system systematically does the IsisException first. As a result, the finalizer for the allocated object "x" has not yet executed but is runable and needs to be called soon.
[NB: For those who are curious, the Using statement ends by calling Dispose, but the recommended behavior, per the documentation, is to have a finalizer ~something() { this.Dispose; } just to cover all possible code paths. Dispose might then be called more than once and you should keep a flag, locked against concurrency, and dispose your managed resources only on the first call to Dispose.]
Now the key problem is that the finalizer apparently might not run before your thread has a chance to terminate in this case of a caught exception that terminates your thread; if not, C# will dispose of the object by calling dispose on a GC finalizer thread. As a result if, as in my code, x.Dispose() unlocks something an error can occur: a lock acquire/release must occur in the same thread on .NET. So that's a source of potential bugs for you and for me! It seems that calling GC.WaitForFinalizers in my exception handler helps in this case. Less clear to me is whether this is a true guarantee that bad things won't occur.
A further serious mistake in my own code was that I had erroneously been catching ThreadAbortException in a few threads, due to an old misunderstanding about how those work. Don't do this. I can see now that it causes serious problems for .NET. Just don't use Thread.Abort, ever.
So on the basis of this understanding, I've modified Isis2 and it works nicely now; when my threads terminate the finalizers do appear to run correctly, dispose does seem to happen before the thread exits (and hence before its id can be reused, which was causing me confusion), and all is good for the world. Those who work with threads, priorities, and self-managed locks/barriers/bounded buffers and semaphores should be cautious: there are dragons lurking here!
| {
"pile_set_name": "StackExchange"
} |
Q:
Consolidate excel workbooks data to csv file from folder using power shell
In a folder i have around 20 excel workbooks,each workbook having MIS for upload excel sheet i want to consolidate all data from each workbook from MIS for upload excel sheet to new csv file using powershell
below is the code which i have tried.But i want Browse for a Folder method.
#Get a list of files to copy from
$Files = GCI 'C:\Users\r.shishodia\Desktop\May 2018' | ?{$_.Extension -Match "xlsx?"} | select -ExpandProperty FullName
#Launch Excel, and make it do as its told (supress confirmations)
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $True
$Excel.DisplayAlerts = $False
#Open up a new workbook
$Dest = $Excel.Workbooks.Add()
#Loop through files, opening each, selecting the Used range, and only grabbing the first 6 columns of it. Then find next available row on the destination worksheet and paste the data
ForEach($File in $Files[0..20]){
$Source = $Excel.Workbooks.Open($File,$true,$true)
If(($Dest.ActiveSheet.UsedRange.Count -eq 1) -and ([String]::IsNullOrEmpty($Dest.ActiveSheet.Range("A1").Value2))){ #If there is only 1 used cell and it is blank select A1
$Source.WorkSheets.item("MIS for Upload").Activate()
[void]$source.ActiveSheet.Range("A1","R$(($Source.ActiveSheet.UsedRange.Rows|Select -Last 1).Row)").Copy()
[void]$Dest.Activate()
[void]$Dest.ActiveSheet.Range("A1").Select()
}Else{ #If there is data go to the next empty row and select Column A
$Source.WorkSheets.item("MIS for Upload").Activate()
[void]$source.ActiveSheet.Range("A2","R$(($Source.ActiveSheet.UsedRange.Rows|Select -Last 1).Row)").Copy()
[void]$Dest.Activate()
[void]$Dest.ActiveSheet.Range("A$(($Dest.ActiveSheet.UsedRange.Rows|Select -last 1).row+1)").Select()
}
[void]$Dest.ActiveSheet.Paste()
$Source.Close()
}
$Dest.SaveAs("C:\Users\r.shishodia\Desktop\Book2.xlsx",51)
$Dest.close()
$Excel.Quit()
A:
For this purpose you could use ImportExcel module - installation guide included in repo README.
Once you install this module you can easily use Import-Excel cmdlet like this:
$Files = GCI 'C:\Users\r.shishodia\Desktop\May 2018' | ?{$_.Extension -Match "xlsx?"} | select -ExpandProperty FullName
$Temp = @()
ForEach ($File in $Files[0..20]) { # or 19 if you want to have exactly 20 files imported
$Temp += Import-Excel -Path $File -WorksheetName 'MIS for Upload' `
| Select Property0, Property1, Property2, Property3, Property4, Property5
}
To export (you wrote CSV but your destination file format says xlsx):
$Temp | Export-Excel 'C:\Users\r.shishodia\Desktop\Book2.xlsx'
or
$Temp | Export-Csv 'C:\Users\r.shishodia\Desktop\Book2.csv'
| {
"pile_set_name": "StackExchange"
} |
Q:
Scripting changes to multiple excel workbooks
I've trying to make large changes to a number of excel workbooks(over 20). Each workbook contains about 16 separate sheets, and I want to write a script that will loop through each workbook and the sheets contains inside and write/modify the cells that I need. I need to keep all string validation, macros, and formatting. All the workbooks are in 2007 format.
I've already looked at python excel libaries and PHPexcel, but macros, buttons, formulas, string validation, and formatting and not kept when the new workbook is written. Is there an easy way to do this, or will I have to open up each workbook individually and commit the changes. I'm trying to avoid creating a macro in VBscript and having to open up each workbook separately to commit the changes I need.
A:
I avoid working with multiple workbooks like the plague it's a pain, if this is an ongoing requirement then I would suggest looking back to your workbook design and seeing if you can consolidate back to one workbook. I often see workbooks each saved month by month when they should have one workbook with one sheet with raw data where each row represents a month, then another sheet for display which looks up the raw data chosen by the user. Thats a very big generalisation and you could well be in a totally different situation.
If its a once off - and I know its not what you wanted but I think you would be best to loop through the workbooks using VBA. Something like (untested):
Excel 2003:
Sub AdjustMultipleFiles()
Dim lCount As Long
Dim wbLoopBook As Workbook
Dim wsLoopSheet As Worksheet
With Application
.ScreenUpdating = False: .DisplayAlerts = False: .EnableEvents = False
End With
With Application.FileSearch
.NewSearch
'// Change path to suit
.LookIn = "C:\MyDocuments"
'// ALL Excel files
.FileType = msoFileTypeExcelWorkbooks
'// Uncomment if file naming convention needed
'.Filename = "Book*.xls"
'// Check for workbooks
If .Execute > 0 Then
'// Loop through all.
For lCount = 1 To .FoundFiles.Count
'// Open Workbook x and Set a Workbook variable to it
Set wbLoopBook = Workbooks.Open(Filename:=.FoundFiles(lCount), UpdateLinks:=0)
'// Loop through all worksheets
For Each wsLoopSheet In wbLoopBook.Worksheets
'//Update your worksheets here...
Next wsLoopSheet
'// Close Workbook & Save
wbLoopBook.Close SaveChanges:=True
'// Release object variable
Set wbLoopBook = Nothing
Next lCount
End If
End With
With Application
.ScreenUpdating = True: .DisplayAlerts = True: .EnableEvents = True
End With
End Sub
For EXCEL 2007+:
Sub AdjustMultipleFiles()
Dim sFileName As String
Dim wbLoopBook As Workbook
Dim wsLoopSheet As Worksheet
With Application
.ScreenUpdating = False: .DisplayAlerts = False: .EnableEvents = False
End With
'// Change path to suit
ChDir "C:\Documents"
'// ALL Excel 2007 files
sFileName = Dir("*.xlsx")
Do While sFileName <> ""
'// Open Workbook x and Set a Workbook variable to it
Set wbLoopBook = Workbooks.Open(Filename:=sFileName, UpdateLinks:=0)
'// Loop through all worksheets
For Each wsLoopSheet In wbLoopBook.Worksheets
'//Update your worksheets here...
Next wsLoopSheet
'// Close Workbook & Save
wbLoopBook.Close SaveChanges:=True
'// Release object variable
Set wbLoopBook = Nothing
'//Next File
sFileName = Dir
'//End Loop
Loop
With Application
.ScreenUpdating = True: .DisplayAlerts = True: .EnableEvents = True
End With
End Sub
Excel 2007 + (FileSystemObject - LateBinding)
Sub AdjustMultipleFiles()
Dim wbLoopBook As Workbook
Dim wsLoopSheet As Worksheet
With Application
.ScreenUpdating = False: .DisplayAlerts = False: .EnableEvents = False
End With
With CreateObject("Scripting.FileSystemObject")
'// Change path to suit
For Each File In .GetFolder("C:\Documents").Files
'// ALL Excel 2007 files
If .GetExtensionName(File) = "xlsx" Then
'// Open Workbook x and Set a Workbook variable to it
Set wbLoopBook = Workbooks.Open(Filename:=File.Path, UpdateLinks:=0)
'// Loop through all worksheets
For Each wsLoopSheet In wbLoopBook.Worksheets
'//Update your worksheets here...
Next wsLoopSheet
'// Close Workbook & Save
wbLoopBook.Close SaveChanges:=True
'// Release object variable
Set wbLoopBook = Nothing
End If
Next File
End With
With Application
.ScreenUpdating = True: .DisplayAlerts = True: .EnableEvents = True
End With
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
What are these stamps in my passport after I was advised to divert via the UK but didn't have a visa?
I am from Myanmar. I was on my way to Venice from Brussels while holding Schengen visa (single entry). I bought a British Airways ticket to fly from Brussels to Venice. Unfortunately, on that day, all BA flights from Brussels were canceled. British Airway's customer service centre told me to go to from Brussels to London by train, where I could catch my flight to Venice. I took a taxi to Bruxelles-Midi train station and bought a ticket to London. A Brussels immigration officer inspected and approved my passport.
Then I had to to through UK Border Immigration. There, they said I can't enter to get my flight. Although I explained the situation with the airline and made clear of my destination (I already reserved my hotels in Venice, Switzerland and France as described in my travel itinerary), they detained me for some hours and also took my fingerprints on paper and photo.
They asked questions concerned about my finances and gave me a refusal letter for not having a transit visa. So I had to re-enter Brussels where the immigration officer put the below stamp in my passport. As I had a single entry Schengen visa, I had to buy another airline ticket to Venice and complete my Europe trip.
What do the stamps below mean on my passport?
Can they affect me and, if so, how and why, when I apply for another Schengen visa?
A:
The first stamp means that your exit from the Schengen area was cancelled. This is a good thing, since if you had been allowed to exit the Schengen area, you would not have been able to fly from the UK to Italy.
The second stamp means that you were refused entry into the UK. You will have to report this if you're ever asked whether you were refused entry. If you explain the circumstances, the refusal is not likely to have much of a negative impact. The key points are:
you were in the Schengen area with a single-entry visa
your flight from Belgium to Italy was cancelled
the airline instructed you to travel by way of the UK
neither the airline nor you realized that you lacked the necessary visas for that itinerary
the UK immigration officer therefore refused entry into the UK
| {
"pile_set_name": "StackExchange"
} |
Q:
wwwroot serving pages not MVC6
I am currently working on an Asp.Net 5 / mvc 6 app. I was running the beta5 release and updated to beta7. I have noticed my index page is loading from the wwwroot directory (I started the app with an index page in the wwwroot and am now using mvc, making the index in the wwwroot redundant)
All of my mvc views were loading correctly prior to the update to beta7, I ideally do not want to go back to beta5.
I have included mvc in the Startup.cs
app.UseMvc(config =>
{
config.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",//optional id
defaults: new { controller = "App", action = "Index" }
);
});
Project.json
"dependencies": {
"Microsoft.AspNet.Mvc": "6.0.0-beta7",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta7",
"Microsoft.AspNet.Server.IIS": "1.0.0-beta7",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta7",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta7",
"Microsoft.Framework.Configuration.FileExtensions": "1.0.0-beta8",
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
},
A:
So after upgrading to beta8 and running dnvm upgrade this has resolved my issue. I believe my configuration was not entirely in line. Thanks to meligy & juergen-gutsch for their answers, very useful to know.
| {
"pile_set_name": "StackExchange"
} |
Q:
Moodle standard_end_of_body function location?
I'm trying to customize the rendering of the standard_end_of_body(), but I can't seem to find the proper function.
I found the abstract function in /lib/outputrenderers.php, but not the actual theme implementation. In the code it is mentioned that it should be in the theme renderer, so I checked into every renderer, as well as the themes mine is based in (bootstrap and Elegance), but so far, nada.
So I'm very much open to any suggestions!
Thanks
A:
In /theme/yourtheme/renderers/php
add this
class theme_yourtheme_core_renderer extends core_renderer {
public function standard_end_of_body_html() {
// Optionally add the parent html.
$output = parent::standard_end_of_body_html();
$output .= 'my stuff';
return ($output);
}
alternatively, you can also add footer html to the setting additionalhtmlfooter
via site admin -> appearance -> additional html
or direct to /admin/settings.php?section=additionalhtml
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting a few values out of dictionary with default different than None (Python)
I don't quite like this: Accessing python dict with multiple key lookup string
So:
In [113]: d = {'a':1, 'b':2}
In [114]: va, vb = map(d.get, ['a', 'b'])
In [115]: va, vb
Out[115]: (1, 2)
But:
In [116]: va, vb = map(d.get, ['a', 'X'])
In [117]: va, vb
Out[117]: (1, None)
What if one needs a default different than None?
I could use lambda:
In [118]: va, vb = map(lambda x: d.get(x) or 'MyDefault', ['a', 'c'])
In [119]: va, vb
Out[119]: (1, 'MyDefault')
But that's kind of convoluted and not very economic tradeoff for writing 2 d.get(key, 'MyDefault') calls.
Anything better (short of obvious solution of writing trivial utility function for that)? Esp. in Python 3?
A:
Use collections.defaultdict:
>>> from collections import defaultdict
>>> d = defaultdict(lambda: 'MyDefault', {'a':1, 'b':2})
>>> d['c']
'MyDefault'
>>> map(d.get, ['a', 'c'])
[1, None]
>>> map(d.__getitem__, ['a', 'c'])
[1, 'MyDefault']
| {
"pile_set_name": "StackExchange"
} |
Q:
Group time-series observations dynamically in R
I have time-series data of five days, formatted as xts object. The data is generated as:
library(xts)
Sys.setenv(TZ="Asia/Kolkata")
seq <- timeBasedSeq('2015-06-01/2015-06-05 23')
z <- xts(1:length(seq),seq)
Now, I want to group the data with similar timestamps (only H:M:S), dynamically in a for loop and then perform required operation on each group. Here, I am facing two problems:
How should I run for loop over xts time indices. I mean to say, can I traverse using minutes of xts object?
How should I group the observations with similar time stamps and perform the required operation. For example, find all the observations at 11 A.M. of all 5 days and compute regression coefficients. Is there any defined function to group time-series observations dynamically?
In all these operations, I don't want to lose xts index.
A:
You could split your data by HH:MM:SS, then loop over the resulting list.
# convert to factor because split.xts will pass f to endpoints() if f is character
# (even if it's more than one element). split.zoo is called if f is factor.
y <- split(z, factor(format(index(z), "%H%M%S")))
# loop over each time group
l <- lapply(y, FUN)
# combine results
x <- do.call(rbind, l)
| {
"pile_set_name": "StackExchange"
} |
Q:
android app crash when i call EditText
The application crashes when I call EDITTEXT.
layout
<EditText
android:id="@+id/T_Price"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@+id/B_LessMoney"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp"
android:text="@string/Price"
android:visibility="visible" />
Main
EditText mPrice = (EditText) findViewById(R.id.T_Price);
and this the report
E/AndroidRuntime: FATAL EXCEPTION: main
Process: budgetreport.com.budgetreport, PID: 2791
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{budgetreport.com.budgetreport/budgetreport.com.budgetreport.Report}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2488)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1499)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:117)
at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:149)
at android.support.v7.app.AppCompatDelegateImplV11.(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:54)
at android.support.v7.app.AppCompatDelegateImplV23.(AppCompatDelegateImplV23.java:31)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:200)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at budgetreport.com.budgetreport.Report.(Report.java:21)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1072)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2478)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1499)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
I/Process: Sending signal. PID: 2791 SIG: 9
Application terminated.
A:
You are calling findViewById before Activity's onCreate method (in the constructor?).
What you should do is to initialize it in the Activity's onCreate:
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
mPrice = (EditText) findViewById(R.id.T_Price);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting Float to a String in Ruby
Sometimes when I try to print a Float in rails, I get an error like this:
TypeError at /delivery_requests/33/edit
no implicit conversion of Float into String
on the line:
= this_is_a_float
I know I can just add .to_s to the float, but why is this not done by default?
A:
This is because you're using a Float in place where a String is expected like the following example:
"Value = " + 1.2 # => no implicit conversion of Float into String
To fix this you must explicitly convert the Float into a String
"Value = " + 1.2.to_s # => Value = 1.2
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Map on IOS 6
I have an application that uses maps. In iOS 5 and below, it used Google Maps, but the same application running in iOS 6 shows Apple Maps. However, Apple Maps has some inaccuracies. Is it possible to use Google Maps on my iOS 6 application instead, and if so, how?
A:
Google has an official SDK available at, https://developers.google.com/maps/documentation/ios/
| {
"pile_set_name": "StackExchange"
} |
Q:
Change date() to central time
I have figured out how to get the time using date('g:i a', time()) to output on the chat i'm making. It outputs something like 7:54 pm. The promlem is that I am in the Central Timezone and it is 8:54 my time. I tried using date('g' + 1 + ':i a', time()) but that didn't work. Any Ideas?
Thanks
A:
Use DateTime() with DateTimeZone():
$date = new DateTime(null, new DateTimeZone(date_default_timezone_get()));
$date->setTimeZone(new DateTimeZone('America/Chicago'));
echo $date->format('g:i a');
I use date_default_timezone_get() to get the current time zone and then change it using DateTime::setTimeZone()
| {
"pile_set_name": "StackExchange"
} |
Q:
Benefits of calling hasOwnProperty as a direct static reference with the call method, as opposed to calling it as an object instance method
In numerous JavaScript sources, I have seen a preference of calling Object.prototype.hasOwnProperty from a static reference as in the following example:
var hasOwnProp = Object.prototype.hasOwnProperty;
//...
if ( hasOwnProp.call(myObj, 'prop') ) {
doSomethingWith(myObj);
}
Why is it preferred over calling an object instance's hasOwnProperty method:
//...
if ( myObj.hasOwnProperty('prop') ) {
doSomethingWith(myObj);
}
A:
Because you can make an object that looks like this:
var obj = {
hasOwnProperty: function () {
throw new Error("you are ugly");
}
};
ie. you can accidentally, or intentionally redefine the function.
Source on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty#hasOwnProperty_as_a_property
| {
"pile_set_name": "StackExchange"
} |
Q:
Why this angular $http.put parameter won't get passed?
I am facing a very weird case in my angularjs app. In a factory, the following code works properly:
$http.put(apiBase + 'delete?id='+orderId);
Which obviously connects to an api to perform a PUT operation (it is called "delete" here but it actually only updates a flag in the record).
But the same code, when written this way, does not work:
$http.put(apiBase + 'delete', {
params: {
id: orderId
}
}
);
Which is funny, because I am using the exact same syntax in some other factories to hit similar APIs and they work!
A:
When using $http.put, you don't need to wrap your data in the config object. You can pass the data object directly, and then omit the third parameter:
$http.put(apiBase + 'delete', { id: orderId });
Your other factories probably work with the syntax stated in your question because you are making $http.get or $http.delete requests.
I have found that this slightly-different API for the various "shortcut" methods to be confusing enough that I almost think it's better to avoid them altogether. You can see the differences from the documentation where get and delete have two parameters:
get(url, [config]);
delete(url, [config]);
and most of the other shortcut methods have three:
post(url, data, [config]);
put(url, data, [config]);
Note that the [config] object is defined further up on that documentation page, which is where it defines that "params" property:
params – {Object.} – Map of strings or objects which
will be serialized with the paramSerializer and appended as GET
parameters.
| {
"pile_set_name": "StackExchange"
} |
Q:
'GOverlay is undefined' javascript error in IE 7, in spite of having loaded the Google Maps API
Despite loading the Google Maps API, via this url:
http://maps.gstatic.com/intl/en_ALL/mapfiles/276b/maps2.api/main.js
I'm getting the above error.
Why is it that when I download that URL in my browser and do a find for 'GOverlay' I'm getting zero matches?
Have Google removed this from their API or something, causing all my code to break?
A:
GOverlay is an essential part of the Google Maps API implementation, see the V2 documentation for GOverlay here.
The reason for you not finding "GOverlay" when searching through the Javascript file you provided is simply that the Google Maps API consists of several Javascript files, not all of the code is in main.js. Additionally the code is obfuscated which could mean the build GOverlay by concatenating some crazy strings.
On a basic note: Why do you want to use some static JS file? The offical way to use the Google Maps API is using a key, which you have to obtain by registering with your Google account. So actually the URL you should be using is:
http://maps.google.com/maps?file=api&v=2&key=abcdefg
Or use the AJAX loader as seen on the Google Maps V2 documentation here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding Loose / Tight Coupling in the "Real World"
I wont say what "community" because I want a non-biased explanation, but let's say you're building a reusable module and that module requires 3+ dependent modules and removing 1 of them causes a breaking error not only in your app as a whole which uses this module, but the module itself.
From my understanding (which must be wrong) a loosely coupled modular system will not break by simply removing one module. The app should still run but without that "feature" / module and the module itself shouldn't causes everything to not run simply because a dependent module doesn't exist.
Is this wrong? If so, if modules are still dependent to the point of everything not working whats the difference between tight/loose coupling?
A:
Not quite --- removing the module could well break the system. The idea behind loosely coupled systems is that swapping in a completely different module will work just fine so long as the new module conforms to the same interface requirements as the old one. If it were tightly coupled, the surrounding code would make presumptions about the internals and would start to fail if a new module was introduced.
A:
Loose coupling is essentially the indirect dependency between module on how they can evolve.
Generally, when there is a tightly coupled systems different modules/objects have a very specific behaviors that assumes that behavior of the peripheral objects. Such objects are linked/coupled to other modules behaviors and they cannot be re-used in isolation or in any other context.
Such modules even though responsible for individual functionality cannot evolve independently or cannot evolve
An example:
Let's say you have 3 objects
Shape (a model object) and Canvas (a UI element).
Now
Assume that a method shape.draw(Canvas) will draw an object on the plane that is supplied by the plane of the canvas.
Now, sometimes windows are partially covered and are resized. In such cases,
the above method might just do something like this.
shape::draw(Canvas) {
Rect.WindowLeft = Canvas.GetWindowRect.getLeftOffset();
Rect.LeftPixel = Canvas.GetWindowRect.pixels() + Rect.WindowLeft;
.... // like this get all co-ordinates.
draw_instance(Rect); // This will draw the actual shape.
}
Basically, here the draw function picks up the rectangle where things needs to be drawn. This is easy to understand (people might call this simple) code. However, this is extremely coupled code.
Imagine the situation:
What if the canvas's mechanism of holding windows is no longer a rectangle?
what if there are additional offsets that Canvas keeps which is private?
What if some other application wants the same shape but no longer has a GUI window (for example, it is creating images and saving in files).
The root cause of the problem is that object shape knows and hence tightly coupled with Canvas.
What is desirable that a pixel set is given to shape where it writes; the shape should not have (even implicit) knowledge about where the pixels are actually written.
| {
"pile_set_name": "StackExchange"
} |
Q:
Как определить разрешение экрана?
Товарищи, как с помощью jQuery определить разрешение экрана и в зависимости от результата подгрузить нужный файл на PHP?
A:
Возможно. Вот таким образом:
ScreenWidth = screen.width;
ScreenHeight = screen.height;
alert(ScreenWidth+'x'+ScreenHeight);
| {
"pile_set_name": "StackExchange"
} |
Q:
Hardening OSX 10.11
I'm following the instruction, on hardentheworld.org to harden my OS X 10.11.
When I send the following command:
sudo defaults write /System/Library/LaunchDaemons/com.apple.mDNSResponder ProgramArguments -array-add "-NoMulticastAdvertisements"
I obtain:
Could not write /System/Library/LaunchDaemons/com.apple.mDNSResponder; exiting
My question is why this error happens and how to solve it?
A:
System Integrity Protection (SIP.) It locks up a variety of files to prevent malicious software from modifying it including /System. You can temporarily disable SIP, modify your files, then turn it back on if you want to have the maximum protection.
| {
"pile_set_name": "StackExchange"
} |
Q:
List all computers in active directory
Im wondering how to get a list of all computers / machines / pc from active directory?
(Trying to make this page a search engine bait, will reply myself. If someone has a better reply il accept that )
A:
If you have a very big domain, or your domain has limits configured on how how many items can be returned per search, you might have to use paging.
using System.DirectoryServices; //add to references
public static List<string> GetComputers()
{
List<string> ComputerNames = new List<string>();
DirectoryEntry entry = new DirectoryEntry("LDAP://YourActiveDirectoryDomain.no");
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(objectClass=computer)");
mySearcher.SizeLimit = int.MaxValue;
mySearcher.PageSize = int.MaxValue;
foreach(SearchResult resEnt in mySearcher.FindAll())
{
//"CN=SGSVG007DC"
string ComputerName = resEnt.GetDirectoryEntry().Name;
if (ComputerName.StartsWith("CN="))
ComputerName = ComputerName.Remove(0,"CN=".Length);
ComputerNames.Add(ComputerName);
}
mySearcher.Dispose();
entry.Dispose();
return ComputerNames;
}
A:
What EKS suggested is correct, but is performing a little bit slow.
The reason for that is the call to GetDirectoryEntry() on each result. This creates a DirectoryEntry object, which is only needed if you need to modify the active directory (AD) object. It's OK if your query would return a single object, but when listing all object in AD, this greatly degrades performance.
If you only need to query AD, its better to just use the Properties collection of the result object. This will improve performance of the code several times.
This is explained in documentation for SearchResult class:
Instances of the SearchResult class are very similar to instances of
DirectoryEntry class. The crucial difference is that the
DirectoryEntry class retrieves its information from the Active
Directory Domain Services hierarchy each time a new object is
accessed, whereas the data for SearchResult is already available in
the SearchResultCollection, where it gets returned from a query that
is performed with the DirectorySearcher class.
Here is an example on how to use the Properties collection:
public static List<string> GetComputers()
{
List<string> computerNames = new List<string>();
using (DirectoryEntry entry = new DirectoryEntry("LDAP://YourActiveDirectoryDomain.no")) {
using (DirectorySearcher mySearcher = new DirectorySearcher(entry)) {
mySearcher.Filter = ("(objectClass=computer)");
// No size limit, reads all objects
mySearcher.SizeLimit = 0;
// Read data in pages of 250 objects. Make sure this value is below the limit configured in your AD domain (if there is a limit)
mySearcher.PageSize = 250;
// Let searcher know which properties are going to be used, and only load those
mySearcher.PropertiesToLoad.Add("name");
foreach(SearchResult resEnt in mySearcher.FindAll())
{
// Note: Properties can contain multiple values.
if (resEnt.Properties["name"].Count > 0)
{
string computerName = (string)resEnt.Properties["name"][0];
computerNames.Add(computerName);
}
}
}
}
return computerNames;
}
Documentation for SearchResult.Properties
Note that properties can have multiple values, that is why we use Properties["name"].Count to check the number of values.
To improve things even further, use the PropertiesToLoad collection to let the searcher know what properties you are going to use in advance. This allows the searcher to only read the data that is actually going to be used.
Note that the DirectoryEntry and DirectorySearcher objects should
be properly disposed in order to release all resources used. Its best
done with a using clause.
| {
"pile_set_name": "StackExchange"
} |
Q:
KeyBinding (Enter) on textbox doesn't update model
I try execute command AddTodoCommand when I press enter in text box:
<TextBox x:Name="TbTodo" Text="{Binding TodoTask.Text, Mode=TwoWay}" >
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding AddTodoCommand}" />
</TextBox.InputBindings>
</TextBox>
Method execute properly but property TodoTask.Text is null.
When I click button with this command model have value:
<Button x:Name="BtnAdd" Command="{Binding AddTodoCommand}" Content="Button"
I think before button is pressed textbox change focus and update binding.
How update model after enter?
A:
the default UpdateSourceTrigger for TextBox.Text is LostFocus. thats why you cant see the "new" value in your TodoTask.Text. one way to solve this issue would be to change the UpdateSourceTrigger to PropertyChanged
| {
"pile_set_name": "StackExchange"
} |
Q:
Parse Windows log files to pull out usernames and tally pages printed in Perl
I am attempting to write a log parser in Perl. I want to output a list of all the users' tally of the number of pages printed.
The logs are exported as a tab delimited text file. There are several columns of information but everything significant is in the last column. The significant portion looks like this:
Document 34, Microsoft Word - Q5_Springc_2013 owned by USERNAME on COMPUTERHOSTNAME was printed on PRINTER through port PORT. Size in bytes: 42096. Pages printed: 4. No user action is required.
#!/usr/bin/perl
use warnings;
#use strict;
print "Export the \"Printed to...\" logs from Event Viewer for the desired printer as a .txt and place it in the same directory as this script!\n";
print "Enter the text file name: ";
my $infile = <STDIN>;
if ($infile eq "\n"){
print "No filename entered! Exiting!";
exit 0;
}
chomp $infile;
print "Reading from file $infile\n";
open INFILE, "<$infile" or die "File does not exist!";
my %report;
while(<INFILE>){
if (/ by (\S+) on .* printed: (\d+)/s) {
$report{$1} += $2;
}
}
print "$_ $report{$_}\n" for (keys %report);
close INFILE or die $!;
I have tried to pull unique names out of the usernames array and tally the prints but I have failed to get any father than this. I have tried to use a hash instead and use a key/value scheme by adding the next value to the old one if the key exists but haven't had any luck. Could anyone help me figure out where to go from here?
I forgot to mention, the output i'm going for is something like this:
USER 45
USER2 12
USER3 120
A:
Here's a quick way to tally up the sums for each user:
my %hash;
while (<>) {
if (/ by (\S+) on .* printed: (\d+)/s) {
$hash{$1} += $2;
}
}
The keys of the hash are unique, so it will be a list of users.
On a related note:
If you're opening a file, it doesn't matter if you prepend the current directory name to the file name. Perl understands that if you want to open file.txt, it first looks in the current directory.
$i = $i + 1 also known as $i += 1, or $i++
Use lexical file handles and three argument open: open my $fh, "<", $file or die $!
Your entire program can be replaced by my 6 lines of code, assuming you give a file name as argument.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is this grassy houseplant?
I have this type of grassy houseplant. I think it might be a Ponytail Palm, but it seems to be slightly different. I want to put them outside on the porch my cats frequent, but they go crazy chomping at them so I'm afraid they will get sick. I need to identify the plant.
A:
This plant looks like a pencil cactus or milkbush. If that is a pencil cactus, the plant is toxic to dogs and cats. If a person contacts the white, milky, latex sap of the plant, it can cause an anaphylactic reaction.
Please do not let your cats, or any pet, chew on this plant.
Pencil Cactus
| {
"pile_set_name": "StackExchange"
} |
Q:
How do websites convert latex files to pdf?
Whenever a researcher submits his paper to a journal website he/she does so by uploading a latex file plus some figures in the format of eps, and after clicking on the submit button the files are converted to one pdf file. Does anyone know how they do that?
Is there a .js file that does that and is pdf.js capable of doing this?
A:
i imagine it's done server-side (after the files have been transmitted to the server) using typical latex-to-pdf workflow tools (e.g., the pdflatex command or similar). i imagine it's theoretically possible to write a javascript library to do it client-side in the browser though i haven't come across anything like that.
Edit: cool! as posted in Jaromanda X's comment above, there is in fact a JavaScript library for this. shows what i know. :p
| {
"pile_set_name": "StackExchange"
} |
Q:
Can putting a one year old baby in a playschool for around 7 hours, daily, cause any psychological issues to the baby?
I and my partner both work in software companies. There are only two of us living together.
So, if we put the baby in a playschool for around 7 hours, daily, after he is one year old, can it cause any psychological issues to baby?
By psychological issues, I mean:
1. Detachment from parents.
2. Aggressive behavior.
3. Being stubborn.
etc.
A:
Having worked in a nursery for several years, I can say that it is very common for parents to have their child or children come "full-time"- that is 7-8 hours a day, 5 days a week. Sometimes from as young as 3 months. Mostly, this was not the parents' ideal plan, but bills need to be paid, so sometimes circumstances must dictate.
In my experience, what tends to happen is that the child will soon adjust to the new routine, and learn to enjoy it. They may even start nagging in the morning to be taken to nursery, because they know it is part of their routine. It's easy to forget, but nurseries are places designed to entertain, educate and stimulate children. Plus, they learn social interaction skills with other children, that are difficult to replicate at home.
So, in my opinion, there certainly is no risk of "damaging" the child psychologically. Speaking now, as a parent, I would say that the bigger psychological effect is on the parent, who feels they are not spending as much time with their child as they would like. What you (we) must remember is that we are not abandonning our child- we are putting them in a safe and caring environment, so we can go out and earn to money to give them a good life.
I should add that I have observed the phenomenon of children "playing up" for their parents after a long day at nursery. This is probably a mixture of tiredness, and (some suggest) "punishing" their parents for leaving them at nursery all day. Not all children do this, and I don't think it is fair to read too much into it.
Lastly, I want to say that the children who found nursery most traumatic were the ones who only came "occasionally". I distinctly remember one little boy (aged 3) who came on average only one afternoon a month. For almost a year, that afternoon was spent in tears. Whereas the children who came regularly settled very quickly and enjoyed it.
A:
I agree with Rory and Urbycoz.
My son has been in daycare since he was about 5 months old, first with a friend of my wife who was a stay-at-home-mom with 3 girls of her own not yet in school, and then with a professional home daycare run by a wonderful woman who is responsible for 6-7 children full-time during the day.
Aside from my son having an early fascination with blonde girls (the mother and all three girls in the first home were blonde), the experiences we've had with daycare have been overwhelmingly positive, despite our concerns.
When we first started, almost all of the children were older than my son. However, with the supervised interactions, the older children provided models from which my son was able to quickly learn how to interact with other children.
Now there are several younger children, and my son has learned the rudiments of age appropriate interactions (he is much gentler with littler children, and knows that it is better to give hugs to an infant or younger toddler than it is to try and play "tag", even though "tag" is one of his favorite games with the older children).
We've seen absolutely no sign of detachment from us. Our son is very affectionate, friendly, and one of the happiest children I've ever met (granted, I'm biased, but quite honestly, he smiles and laughs at least 95% of his waking time). He doesn't get upset when I drop him off in the mornings (so long as he gets his hug goodbye!), and is always happy to see me when I pick him up in the afternoon (although if he's in the middle of doing something with the other kids, he may not be quite ready to stop what he's doing just because I showed up).
He talks quite happily about going to play with his friends in daycare, although he gives equal weight to the other friends and relatives his age that he sees outside of daycare.
We have no problems leaving him with relatives that he knows (his grandparents) at times when we need a babysitter, and rarely cries when we leave (and on those occasions, it doesn't last more than 3 minutes after we're out of sight).
As for being stubborn... well, our son is stubborn, there's no doubt about that, but I do have to question any assumption that daycare is the cause, or even a contributing factor.
The issue he's most stubborn about is eating, and trying new foods. However, in daycare, he eats literally anything that the daycare provider gives to him, and apparently without complaint. For us, it has become a game to try and avoid eating anything new with us, but we're getting past that. However, if our daycare provider hadn't told us repeatedly how readily he eats a huge assortment of foods, we likely would not have pushed so hard for him to eat a varied diet for us, as well, and we would probably have caved in to accepting that our son was just a "picky eater".
So, to address your three main concerns:
1. Does he show detachment from his parents? Absolutely not!
2. Does he show aggressive behavior? Absolutely not! In fact, his cousin, who is exclusively cared for by his stay-at-home-mother, is far, far more aggressive than my son, and his parents attribute it to not having any experience playing with younger children.
3. Is he stubborn? Yes, but daycare has actually provided us tools to help deal with that stubbornness slightly better than we might have without it, and I don't see any reason to blame daycare for the stubbornness in the first place (how many 2 year olds aren't stubborn, anyway?).
A:
My kids have been in and out of daycares at various ages throughout their lives. My son started daycare when he was 6 weeks old and continued there until he was almost 2 1/2 years old when I resigned from my teaching job and became a SAHM when my daughter was born. Shortly after my daughter was born, I enrolled my son in a mothers-day-out program which met 2 days a week from 9 am to 2 pm. When we finally moved for my husband's job when my son was 3, he and my daughter were at home with me full-time until he was 3 1/2 when I put them both back in daycare part-time (3 days a week). When I finally found a job, they both went into daycare full-time again. So...we've done it all. My daughter was at home full-time with me from the time she was born until she was just over a year old.
My daughter took to daycare immediately at 1 1/2. She enjoys it thoroughly. That doesn't mean she doesn't have her bad days, but those occur whether a child is home all the time or a daycare child. My son had a more difficult time adjusting to daycare after we pulled him out and put him back in. Now that he's back into the swing of things, he loves it.
Compared to their cousins (4 of whom are mostly stay-at-home kids and all around the same ages as my kids), they are better socially adjusted and more independent. My two nephews are MUCH more aggressive than my son is and they only recently (within the past year or so) started attending any form of daycare and that is part-time. Up until then, they were cared for in the home by a nanny. My nieces, while not aggressive, are VERY attached to their mother. In fact, my SIL has never been able to put them in any form of daycare because they simply scream and cry for her the whole time she's gone. When my SIL or BIL cannot be there to care for them, they have a series of nannies that fill in as needed.
My two kids and my final niece (who is the same age as my daughter) have all attended daycare on a fairly regular basis, and none of us feel that our child(ren) suffer(s) any kind of attachment issues. I like to work and I am a better parent when I work. I'm miserable as a stay-at-home-mom. My husband and I go out of our way to make sure that the time that we spend with our kids is good, quality time. We play, we read books, we go places, we visit our family that lives out of state. Our kids are happy, well-adjusted, social little people who are happy to see me when I pick them up from daycare everyday and tell me about their day. But when we're at home, it's not like they start asking for Miss Limor or Miss Keila if they're sad, hurt, unhappy, tired, or sick. They still want Mommy and Daddy.
As for stubbornness, my kids are just stubborn. My daughter was stubborn before she ever started daycare.
Truthfully, daycare is initially harder on the parent than it is the child. Your child might cry when you drop him/her off for the first couple of weeks until they figure everything out. It's a lot for a little brain to take in: a new figurehead, a new routine, new food (probably), perhaps a new naptime, new other little people milling around all the time. Once they get into the swing of things, though, that should go away. You, as a parent, will suffer from feelings of guilt and worry that your child will feel abandoned.
Go visit any daycare you're considering putting your child in to. Talk with the teachers, the director, other parents. Observe the children. Do they appear happy? Are their needs attended to promptly by their teachers and caregivers? If your state/country/whatever does it, check into the daycare's credentials. This is usually available online these days. Have they had any recent complaints? What were those complaints? Were the complaints resolved and how? Drop in unannounced so you can see how the daycare is run when they don't know you're coming. This will help you make a better decision about where you want to place your child and help you feel more confident about the decision you've made.
Your biggest concern after you put your child in daycare is going to be illness. Your child is going to be sick with something a lot. Between Halloween and Christmas last year, my daughter had hand, foot, and mouth disease, roseola, and RSV. This is just how things go. Kids bring illnesses to school and pass them around--especially in the 1-2 years age group where they just put everything in their mouths. After about the first year, though, your child will suddenly have the immune system of a bull. My son rarely if ever gets sick with anything more serious than the occasional cold. My daughter hasn't really been sick in months now.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find which event called the listener in Node.js
There is only one listener attached to several events like this:
// emitter is an instance of events.EventEmitter..
emitter.on('event1', listener);
emitter.on('event2', listener);
emitter.on('event3', listener);
emitter.on('event4', listener);
function listener() {
// I need to find which event was emitted and as a result, this listener was called.
}
Please note that arguments.callee.caller.name won't work in Node, since events.EventEmitter.on method calls an anonymous function and therefore the callee.caller has no name!
Thanks!
A:
I would just make an intermediary "function" for each listener if I really need to know who called it:
For example:
emitter.on('event1', function(){
//something special with this event
listener();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails Best Practice: Constants for model ids, or find_by or where queries?
I have a situation where I need to make a best practice decision which will affect a large part of my system. There are many different has_many through: relationships that I will be querying often to see if a specific item exists and is attached to another item.
class User
has_many :user_skills
has_many :skills, through: :user_skills
end
class Skill
has_many :user_skills
has_many :users, through: :user_skills
end
class UserSkill
belongs_to :skill
belongs_to :user
end
There will be thousands of users in the system that can be combined with any amount of skills, of which there are about 200+. I'm trying to figure out what is the fastest, most efficient way to query a user to find out if he/she possesses a specific skill. I'm leaning toward Constants because the IDs will obviously be different in dev, test, and production, and it would be nice to only have to load them up once instead of searching for a non-indexed name every time.
1. #find_by (:name)
@user.skills.find_by(name: 'Ruby-on-Rails').present?
2. #where ('name...')
@user.skills.where("name = 'Ruby-on_rails'").present?
3. Constant + #find_by (:id)
constants would be set dynamically on application load using #const_set so there would be over 200 constants always stored
RUBY_ON_RAILS = 41
RUBY = 42
PHP = 45
@user.skills.find_by(id: RUBY_ON_RAILS).present?
4. Constant + #pluck (:id)
same constants as above
@user.skills.pluck(:id).include?(RUBY_ON_RAILS)
5. ???
any better way that I have't thought of
A:
There is a better way to do this:
@user.skills.exists?(name: 'Ruby-on-Rails')
It also works on a relation:
@user.skills.where(name: 'Ruby-on-Rails').exists?
| {
"pile_set_name": "StackExchange"
} |
Q:
Installed Python 3.6 using 'Conda install', unable to run old 2.7 python programs
I have Anaconda 2.7 python installed on my mac book, I wanted to try Python 3.6, so installed the package .. tried the following, Python 3.6 seems to be installed now, but Im unable to run my old 2.7 python scripts.
Kindly help me in restoring my Python environment, I want 2.7, 3.6 version to co-exists, I should be able to switch easily between these 2 versions.
$ conda create --name python3.6 python=3.6
$ source activate python3.6
$ unset PYTHONPATH
$ python pyplot2.py
Traceback (most recent call last): File "pyplot2.py",
line 2, in <module>
import pandas as pd ModuleNotFoundError: No module named 'pandas'
A:
As the ModuleNotFoundError tells you, there is no module named 'pandas' installed. So you have to install it first. You can see all your installed packages with conda list. You shouldn't see it there. To install it just enter conda install pandas and it should work.
If you would like to have all the packages in your Python 3.6 version, that you also had in your 2.7 version you can look here
| {
"pile_set_name": "StackExchange"
} |
Q:
benefits of using interfaces in fflib service layer
I am looking at the fflib-apex-common-samplecode, and I see that the AccountsSelector uses an interface IAccountsSelector, see below:
public class AccountsSelector extends fflib_SObjectSelector implements IAccountsSelector
{
public static IAccountsSelector newInstance()
{
return (IAccountsSelector) Application.Selector.newInstance(Account.SObjectType);
}
// ...
}
Source
Which are the benefits of using the interface IAccountsSelector? Why not just using:
public class AccountsSelector extends fflib_SObjectSelector
{
public static AccountsSelector newInstance()
{
return Application.Selector.newInstance(Account.SObjectType);
}
// ...
}
A:
It was implemented with interfaces to allow dependency injection (for example, for mocking). This way you can create other classes that implement the interfaces and use them (inject them) in runtime. For example, you can use mock classes when executing unit tests to create more pure unit tests.
https://quirkyapex.com/2017/12/03/fflib-application-structure/
| {
"pile_set_name": "StackExchange"
} |
Q:
How to debug AJAX (PHP) code that calls SQL statements?
I'm not sure if this is a duplicate of another question, but I have a small PHP file that calls some SQL INSERT and DELETE for an image tagging system. Most of the time both insertions and deletes work, but on some occasions the insertions don't work.
Is there a way to view why the SQL statements failed to execute, something similar to when you use SQL functions in Python or Java, and if it fails, it tells you why (example: duplicate key insertion, unterminated quote etc...)?
A:
There are two things I can think of off the top of my head, and one thing that I stole from amitchhajer:
pg_last_error will tell you the last error in your session. This is awesome for obvious reasons, and you're going to want to log the error to a text file on disk in case the issue is something like the DB going down. If you try to store the error in the DB, you might have some HILARIOUS* hi-jinks in the process of figuring out why.
Log every query to this text file, even the successful ones. Find out if the issue affects identical operations (an issue with your DB or connection, again) or certain queries every time (issue with your app.)
If you have access to the guts of your server (or your shared hosting is good,) enable and examine the database's query log. This won't help if there's a network issue between the app and server, though.
But if I had to guess, I would imagine that when the app fails it's getting weird input. Nine times out of ten the input isn't getting escaped properly or - since you're using PHP, which murders variables as a matter of routine during type conversions - it's being set to FALSE or NULL or something and the system is generating a broken query like INSERT INTO wizards (hats, cloaks, spell_count) VALUES ('Wizard Hat', 'Robes', );
*not actually hilarious
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Apiglity provide a buil-in error handling and logging?
I'm working on an API project and have to decide over the error handling and logging strategy/concept. So as first step I want to check, whether Apigility provides its own logging functionality.
If I see it correctly, Apigility only provides a minimal error handling for REST specific errors (Apigility documentation -> Error Reporting). That's it. So, only a limited error handling and no logging. Right? But maybe it's wrong and I have just not found the functionality I need. So, is an error handling mechanism provided? Is a logging mechanism provided in Apigility?
A:
It handles error rendering if you use ApiProblem objects to encapsulate your errors.
It doesn't handle logging out of the box, you'll have to add your application's logging strategy yourself.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to test a Cloudflare App with Worker before submitting?
After clicking “Add app” on the /apps/developer/app-creator page if I click “Save draft” I am given a message “You are not authorized to create apps with workers.”
Is there a way I can create an App that contains a worker for testing on my own domains? How do I become authorized to create an app with a worker? Is it possible to have an App that is only a worker and no client side javascript?
A:
You can only test installing an app with a worker if you have been accepted into the beta. You can apply for the beta here: https://www.cloudflare.com/products/cloudflare-workers/#otherways
Yes, it is possible to just have workers installed on no client-side javascript. Just omit the "resources" node
| {
"pile_set_name": "StackExchange"
} |
Q:
Get a value using regex in php?
How can I get price 1.199,00 from below html using preg_match_all?
`<h4><span class="price_label">Preis: </span>1.199,00 Euro (inkl. 19% MwSt.)</h4>`
Code
<?php
$pattern = '#'.$regex.'#';
preg_match_all($pattern, $data, $price);
print_r(price);
?>
A:
This would be a simple example:
<?php
$subject = '<h4><span class="price_label">Preis: </span>1.199,00 Euro (inkl. 19% MwSt.)</h4>';
$pattern = '|<span[^>]+class="price_label".*>[^<]+</span>([0-9.,]+)\s*.*$|';
preg_match($pattern, $subject, $tokens);
var_dump($tokens[1]);
The output obviously is:
string(8) "1.199,00"
Note however that it is questionable to use regular expressions to parse HTML markup or extract values from it. Such solutions tend to be picky, so not robust against minor modifications of the markup. It is far better to use a DOM parser.
| {
"pile_set_name": "StackExchange"
} |
Q:
Actionscript 3 - ESC making application to go out of fullscreen mode
So, how do I make it so that so when I got my application at StageDisplayState.FULL_SCREEN, it wont make it StageDisplayState.NORMAL on pressing esc? like if I want to make an in-movie pop-up menu, which appears on esc that includes all the options like exit and fullscreen or not -settings?
A:
If you are making a web based swf then there is no way to stop the escape key from quitting full screen mode, because of the security problems associated with not being able to leave a full screen movie. However if you are making an AIR application then there might be some work arounds that I am unsure of.
More in depth explanation
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple script - execute command on selected file
I want to make a script that will execute .jar file on selected file. Later I will add that script to right-click menu via the tool Nautilus Actions or just place it into nautilus-scripts folder. I have a problem creating script.
When I am in a usual console screen and want to execute this jar file on any other file, I use this syntax
myfile.jar ./someotherfile.xml
and the jar file will write the output to the console screen.
So I created a file script.sh, added lines in it
#!/bin/bash
/home/username/myfile.jar $1
But it does not output anything. I know I am doing something wrong. Please help.
To sum, I need a script that will use selected file as a parameter, open the gnome-terminal, inside that terminal it will start JAR file and pass it the selected file.
I am confident that this is a very simple procedure, but I am total newbie with shell scripting.
A:
You might also go for
!/bin/sh
gnome-terminal -x java -jar /home/askmoo/myfile.jar "$1"
in order to first open gnome terminal and then execute your java application in it. This way you would be able to get output printed out to the terminal.
| {
"pile_set_name": "StackExchange"
} |
Q:
CakePHP2でAWSのS3プラグインを使用しているのですがアップロードがうまくいきません。
お世話になっております。
ご回答ありがとうございます。
現在、ご紹介いただいた https://github.com/robmcvey/cakephp-amazon-s3 のプラグインを使用しているのですが、
Error: Call to a member function put() on null
File: /var/www/html/cakephp-2.6.4/app/Controller/UploadsController.php
Line: 25
という、エラーが発生しています。 $AmazonS3->put('/*****/files/'); の部分です。
Readmeの通りに記述しましたがうまくいかないのですが、記述の仕方がまちがっているのでしょうか?
よろしくお願いいたします。
public function add() {
if ($this->request->is('post')) {
$tmp = $this->request->data['Upload']['file']['tmp_name'];
if(is_uploaded_file($tmp)) {
$filename = basename($this->request->data['Upload']['file']['name']);
$file = WWW_ROOT.'files'.DS.$filename;
// S3にファイル保存
$AmazonS3->put('/*****/files/'); // *****はパケット名、filesは作成したフォルダ
if (move_uploaded_file($tmp, $file)) {
$this->Upload->create();
$this->request->data['Upload']['filename'] = $filename;
if ($this->Upload->saveAll($this->request->data)) {
$this->Session->setFlash(__('アップロードしました。'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('アップロードできませんでした。'));
A:
$AmazonS3が作成されていません。
READMEをもう一度よく読んでみましょう。
App::uses('AmazonS3', 'AmazonS3.Lib');
$AmazonS3 = new AmazonS3(array('{access key}', '{secret key}', '{bucket name}'));
とあるはずです。
| {
"pile_set_name": "StackExchange"
} |
Q:
Restrict function parameters to certain enum values
Here's my first attempt -
#include <iostream>
using namespace std;
enum class props {
left, right
};
template<typename T>
auto allowLeftOnly(T p) -> decltype((p==props::left), void())
{
cout << "Wow!";
}
int main() {
props p1 = props::left;
props p2 = props::right;
allowLeftOnly(p1);
// allowLeftOnly(p2); // should fail to compile
}
What I want from allowLeftOnly function is to accept only props::left or others that I explicitly specify as parameters and fail to compile for others. Is that possible?
A:
No, it is not possible. Values of p1 and p2 are run-time properties, not compile time properties, hence the compiler does not "know" their values at compile-time.
You can make them known at compile-time by using constexpr, and pass them as template arguments instead, e.g.:
#include <iostream>
#include <type_traits>
enum class props {
left, right
};
template <props v>
typename std::enable_if<v == props::left, void>::type allowLeftOnly()
{ std::cout << "Wow!\n"; }
int main() {
constexpr auto p1 = props::left;
constexpr auto p2 = props::right;
allowLeftOnly<p1>();
allowLeftOnly<p2>(); // Fails to compile
}
A:
You can change p in to a template parameter and then use std::enable_if, like this:
template <props p> // p is now a template parameter
std::enable_if_t<p == props::left> // We only allow p == props::left, return type is implicitly void
allowLeftOnly() // No 'normal' parameters anymore
{
std::cout << "Wow!";
}
int main()
{
constexpr props p1 = props::left;
constexpr props p2 = props::right;
allowLeftOnly<p1>();
// allowLeftOnly<p2>(); // Fails to compile
}
For p1 and p2 the constexpr keyword ensures we can use the variables as template parameters.
If you later want another return type, e.g., int then use:
std::enable_if_t<p == props::left, int>
| {
"pile_set_name": "StackExchange"
} |
Q:
superdev mode not loading module
Hello I'm upgrading my gwt from 2.4.0 to 2.7.0 with gxt 2.3.1a. Everything was looking alright ultil I try to debug the application. I start the debug using superdev mode without any problems aparently. Here is the end of my debug start.
"
[INFO] Unification traversed 108163 fields and methods and 8186 types. 8146 are considered part of the current module and 8146 had all of their fields and methods traversed.
[INFO] Compiling 1 permutation
[INFO] Compiling permutation 0...
[INFO] Linking per-type JS with 8130 new types.
[INFO] prelink JS size = 26317582
[INFO] prelink sourcemap = 26317582 bytes and 534648 lines
[INFO] postlink JS size = 26027857
[INFO] postlink sourcemap = 26027857 bytes and 528723 lines
[INFO] Source Maps Enabled
[INFO] Compile of permutations succeeded
[INFO] Compilation succeeded -- 128,510s
[INFO] Linking into C:\Users\ALEXAN~1.RIS\AppData\Local\Temp\gwt-codeserver-3435183735990420589.tmp\br.com.webb.ria.Application\compile-2\war\br.com.webb.ria.Application; Writing extras to C:\Users\ALEXAN~1.RIS\AppData\Local\Temp\gwt-codeserver-3435183735990420589.tmp\br.com.webb.ria.Application\compile-2\extras\br.com.webb.ria.Application
[INFO] Link succeeded
[INFO] Linking succeeded -- 11,742s
[INFO] 147,211s total -- Compile completed
"
After I start the remote debug I get the normal gray window of gwt debug plugin. Everything is processed without any errors. When I copy the generated link on my browser I get the following message.
"Compiling br.com.webb.ria.Application" My gwt module.
The problem is that after the message vanishes I get nothing but the plain html. The module is not loaded on screen and I can't see my application.
I've tried using the "Dev Mode On" button from my bookmark, nothing happens. I tried to stop using "Dev Mode Off" and then clicking on "Dev Mode On" again, nothing happens.
I also tried enabling https support and <set-property name="user.agent" value="safari" />. Nothing seems to help. Any ideas?
A:
Unlike convencional debug mode, superdev mode requires a full compilation before debuging to work. If you are using maven and face the same problem, perform a mvn clean package before trying to debug.
| {
"pile_set_name": "StackExchange"
} |
Q:
dataframe multiply some columns with a series
I have a dataframe df1 where the index is a DatetimeIndex and there are 5 columns, col1, col2, col3, col4, col5.
I have another df2 which has an almost equal datetimeindex (some days of df1 may be missing from df1), and a single 'Value' column.
I would like to multiply df1 in-place by the Value from df2 when the dates are the same. But not for all columns col1...col5, only col1...col4
I can see it is possible to multiply col1*Value, then col2*Value and so on... and make up a new dataframe to replace df1.
Is there a more efficient way?
A:
You an achieve this, by reindexing the second dataframe so they are the same shape, and then using the dataframe operator mul:
Create two data frames with datetime series. The second one using only business days to make sure we have gaps between the two. Set the dates as indices.
import pandas as pd
# first frame
rng1 = pd.date_range('1/1/2011', periods=90, freq='D')
df1 = pd.DataFrame({'value':range(1,91),'date':rng1})
df1.set_index('date', inplace =True)
# second frame with a business day date index
rng2 = pd.date_range('1/1/2011', periods=90, freq='B')
df2 = pd.DataFrame({'date':rng2})
df2['value_to_multiply'] = range(1-91)
df2.set_index('date', inplace =True)
reindex the second frame with the index from the first. Df1 will now have gaps for non-business days filled with the first previous valid observation.
# reindex the second dataframe to match the first
df2 =df2.reindex(index= df1.index, method = 'ffill')
Multiple df2 by df1['value_to_multiply_by']:
# multiple filling nans with 1 to avoid propagating nans
# nans can still exists if there are no valid previous observations such as at the beginning of a dataframe
df1.mul(df2['value_to_multiply_by'].fillna(1), axis=0)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get iPhone SDK 2.2.1 for Xcode 3.2?
After my upgrade to Snow Leopard and Xcode 3.2 (which I really regret a lot!!), Xcode lost all the SDK's. I'm one of those old-fashioned idiots who still want to develop for 2.2.1. But Apple does not offer me an old SDK download.
Now I was clever and made tons of time machine backups. But: What's the preferred way to get iPhone SDK 2.2.1 running with Xcode 3.2? Some guys said that's generally possible. I do hope so because I still don't believe in all those "faked" stats, and besided that, my app doesn't benefit from 3.x additional features so I would not want to constrain my market just for that lazyness.
Any idea?
A:
Regardless of whether or not you're targeting iPhone OS 3.0 or not using any 3.0 specific features, you should always compile your app against the latest SDKs to benefit from bug fixes and performance improvements.
You can compile against the 3.0 SDK and set the iPhone OS Deployment Target to 2.2.1 and still cater for users who are using 2.2.1.
You may find that some methods have been deprecated, but that doesn't stop you from using them until you're ready to move on.
A:
Get the 3.1 final sdk, it has the 2.2.1 sdk in it. On disk its usual location is:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.1.sdk
Also included is 3.0 and 3.1.
A:
XCode 3.2 should have the prior iPhone SDKs available, just make sure you are setting your project's Base SDK setting to "iPhone OS 2.2.1". (Right-click on your top-level project icon in the Groups & Files browser in XCode and choose "Get Info", then go to the Build tab.)
| {
"pile_set_name": "StackExchange"
} |
Q:
ArrayList in ArrayList in C#?
I want to have an ArrayList in an ArrayList. This is how I did it:
ArrayList arraylist1 = new ArrayList();
ArrayList arraylist2 = new ArrayList();
arraylist2.Items.Add("test1");
arraylist2.Items.Add("test2");
arraylist1.Items.Add(arraylist2);
Now how can I call the arraylist?
I tried it this way:
arraylist1[0][0].ToString()
arraylist1[0][1].ToString()
It didn't work. Does anyone have any other ideas?
Thanks.
A:
This way using Generic List<string> and List<List<string>> types found in System.Collections.Generic-namespace:
var listOfStrings = new List<string>();
listOfStrings.Add("test1");
listOfStrings.Add("test2");
var listOfStringLists = new List<List<string>>();
listOfStringLists.Add(listOfStrings);
Console.WriteLine(listOfStringLists[0][0]);
Console.WriteLine(listOfStringLists[0][1]);
| {
"pile_set_name": "StackExchange"
} |
Q:
Canvas Object is null when app is launched in run mode and object has value when run on debug mode
Im using canvas object to set drawbitmap to set wallpaper change it
based > on user selected interval. Canvas object is null when app is
launched in run mode and in debug mode its not null. below is my code
very strange behaviour
public MyWallpaperEngine() {
mImagesArray = new int[] {R.drawable.one,R.drawable.two,R.drawable.three,
R.drawable.four,R.drawable.five,R.drawable.six,
R.drawable.seven,R.drawable.eight,R.drawable.nine,
R.drawable.ten};
myTimertask = new TimerTask() {
@Override
public void run() {
System.out.println("TIMER SCHEDULED INSIDE RUN");
drawFrame();
incrementCounter();
}
};
myTimer.schedule(myTimertask,startInterval,WALLPAPER_DURATION);
}
private void incrementCounter() {
mImagesArrayIndex++;
if (mImagesArrayIndex >= mImagesArray.length) {
mImagesArrayIndex = 0;
}
}
private void drawFrame() {
System.out.println("inside draw frame");
SurfaceHolder holder = getSurfaceHolder();
System.out.println("holder Object "+holder);
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
System.out.println("Canvas Object "+canvas);
if (canvas != null) {
System.out.println("inside draw image");
drawImage(canvas);
}
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
private void drawImage(Canvas canvas)
{
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray[mImagesArrayIndex]);
Bitmap b=Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), true);
canvas.drawBitmap(b, 0,0, null);
}
A:
When is your drawImage method called ? (From the activity/fragment lifecyle).
The reason you are not able to receive in run time, might be because your view is not yet completely drawn on the screen, where you canvas object is placed.
You canvas is not null in debug mode, since debug mode is slower and it gets sufficient time to get drawn.
Make sure you follow the activity/ fragment lifecycle.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to segment an id based on daily device usage for each day
Objective: I would like to segment Ids based on their device type usage per day. If an Id uses solely pc then 'pc'. If only mobile, then 'mobile'. If at least 1 mobile and 1 pc then 'both'.
Sample data:
CREATE TABLE #test1 (
dates DATE
,id INT
,device CHAR(30)
)
INSERT INTO #test1
VALUES
('2018-01-01', 123, 'pc')
,('2018-01-01', 123, 'pc')
,('2018-01-01', 123, 'mobile')
,('2018-01-01', 123, 'mobile')
,('2018-01-01', 800, 'mobile')
,('2018-01-01', 800, 'mobile')
,('2018-01-01', 800, 'mobile')
,('2018-01-01', 500, 'pc')
,('2018-01-01', 500, 'pc')
,('2018-01-02', 123, 'mobile')
This is what i tried so far but to no avail:
SELECT DISTINCT dates
, id
,CASE
WHEN device = 'pc' AND device = 'mobile' THEN 'Both'
WHEN device = 'pc' THEN 'pc'
ELSE 'mobile'
END AS x
FROM #test1
My output should look like this:
+------------+-----+--------+
| dates | id | x |
+------------+-----+--------+
| 2018-01-01 | 123 | both |
| 2018-01-01 | 800 | mobile |
| 2018-01-01 | 500 | pc |
| 2018-01-02 | 123 | mobile |
+------------+-----+--------+
A:
CASE expression eventuate once per row so it doesn't work the way that you write so, you can use use exists :
select distinct t.dates, t.id,
(case when exists (select 1 from #test1 t1 where t1.dates = t.dates and t1.id = t.id and t1.device <> t.device)
then 'both'
else t.device
end) as x
from #test1 t;
A:
You need to group by dates, id and count the distinct values of device:
SELECT dates
, id
,CASE COUNT(DISTINCT device)
WHEN 1 THEN MAX(device)
WHEN 2 THEN 'both'
END AS x
FROM #test1
GROUP BY dates, id
See the demo
| {
"pile_set_name": "StackExchange"
} |
Q:
How to bind multiple nested properties in WPF
Here is my problem, I have the following data structure:
public class Job : INotifyPropertyChanged {
public StateEnum State {
get { return this.state; }
private set {
this.state = value;
this.OnPropertyChanged();
}
}
}
public class MainWindow : Window, INotifyPropertyChanged
public List<Job> Jobs {
get { return this.jobs; }
private set {
this.jobs = value;
this.OnPropertyChanged();
}
}
}
I want to display a global state summary of the jobs in the main window.
I first tried to make a data binding on the Jobs list, then use a custom IValueConverter to display the global state. Problem: It is not refreshed when the job states change (since it is bind to the collection and not the states).
ProgressState="{Binding Jobs, Converter={StaticResource JobsToProgressState}, ElementName=MainWindow}"
So I was trying to find a solution where I can bind all the nested properties of the jobs to a IMultiValueConverter. I did not find any syntax to make this work.
Is it possible to do something like that?
EDIT:
I want to do something like
ProgressState="{Binding Jobs[*].State, Converter={StaticResource JobsToProgressState}, ElementName=MainWindow}"
And retrieve an array containing all job states (StateEnum[]) in the JobsToProgressState converter.
A:
The problem is that OnPropertyChanged is not fired when a record of an IList changes. You need to delegate the OnPropertyChanged of the Job up to your Jobs-List.
This rough implementation will do what you want.
public class Job : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
public StateEnum State {
get { return this.state; }
private set {
this.state = value;
this.OnPropertyChanged();
}
}
}
public class MainWindow : Window, INotifyPropertyChanged
public List<Job> Jobs {
get { return this.jobs; }
private set {
this.jobs = value;
foreach(var job in this.jobs)
{
job.PropertyChanged += job_PropertyChanged;
}
}
}
private void job_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
this.OnPropertyChanged("Jobs");
}
}
Don't forget to unwire your event registrations when you don't need them any more.
| {
"pile_set_name": "StackExchange"
} |
Q:
Print an integer tensor in binary
I have a tensor of type tf.int32
I would like to use tf.Print but I need the result to be in binary.
Is this even possible?
It is for debugging.
Example:
constant = tf.constant(5)
#magic
tf.Print(constant) # prints 101
A:
You can use tf.py_function:
x = tf.placeholder(tf.int32)
bin_op = tf.py_function(lambda dec: bin(int(dec))[2:], [x], tf.string)
bin_op.eval(feed_dict={x: 5}) # '101'
But note that tf.py_function creates a node in the graph. So if you want to print many tensors, you can wrap them with tf.py_function before tf.Print, but doing this in a loop may cause bloating.
| {
"pile_set_name": "StackExchange"
} |
Q:
Background image on top (Using CSS)
I have this image that I want to display on top of my product images when you HOVER on them.
This is what i'm using:
.centerBoxContentsFeatured img:hover {
background-image:url('http://i47.tinypic.com/vz2oj.gif');
}
It does work but it's being display behind the product image instead of on top of it. I tried absolute positioning and z-index but nothing seems to work.
http://www.pazzle.co.uk - trying to apply on the images on the main page. <<
EDIT:
#featuredProducts.centerBoxWrapper {
position: relative;
}
#featuredProducts.centerBoxWrapper:hover:before {
content: '';
width: 187px;
height: 179px;;
position: absolute;
top: 0;
left: 0;
background-image:url('http://i47.tinypic.com/vz2oj.gif');
}
A:
a {
display: block;
position: relative;
width: 100px;
height: 100px;
}
a:hover:before {
content: '';
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background-image:url('http://i47.tinypic.com/vz2oj.gif');
}
Demo
Use a pseudo element.
A:
It's doing exactly what it's supposed to do. It's a background, so it will appear behind the container's content.
What you have to do here is to overlay a div over the image you're hovering.
I think this is possible a with a pure CSS solution, but it might be easier with some JavaScript.
See this question: on hover overlay image in CSS
| {
"pile_set_name": "StackExchange"
} |
Q:
Выделение элемента изображения при наведении
Здравствуйте.
Подскажите, как лучше и быстрее реализовать такую идею. Есть изображение - на ней изображена строительная техника. Нужно, чтобы при наведении на камаз, например, он подсвечивался и вылезала подсказка. Вроде нужно area использовать, а можно как-то поскорее это реализовать, а то сложно карту изображения создавать, объекты не простые.
A:
http://jsfiddle.net/yv43qa5c/
http://jsfiddle.net/g8Lpuroj/
| {
"pile_set_name": "StackExchange"
} |
Q:
qTip and .Live() data
In Short,
I am currently showing a list of results... and then I place a filter on the results and pulls another list of results, using the .live() within jQuery.
Not my problem comes when i'm using qTip. Which currently runs somewhat like this... without all the details.
$('.contact').each(function() {
$(this).qtip({
// These are my options within here
});
});
This if my code for filtering my results using the .live() feature.
$('.filterContacts').live('click', function(){
var filterId = $(this).attr('id');
$.ajax({
url: 'classes/class.Post.php?a=filterContacts',
dataType: 'html',
data: {
filter: filterId
},
success: function (responseText) {
$(".contacts").html(responseText);
},
error: function() {
alert("Oops... Looks like we're having some difficulties.");
}
});
return false;
});
So now my qTip doesn't like to work on my filtered results... is there anything that I am able to do? Any help would be appreciative!
UPDATE:
.contacts is a div that surrounds all of the .contact divs.
IE:
<div class="contacts">
<div class="contact">FistName, LastName</div>
<div class="contact">FistName, LastName</div>
<div class="contact">FistName, LastName</div>
</div>
A:
you should execute your code in the success block.
$('.filterContacts').live('click', function(){
var filterId = $(this).attr('id');
$.ajax({
url: 'classes/class.Post.php?a=filterContacts',
dataType: 'html',
data: {
filter: filterId
},
success: function (responseText) {
$(".contacts").html(responseText);
// call your each function here...
$('.contact').each(function() {
$(this).qtip({
// These are my options within here
});
});
},
error: function() {
alert("Oops... Looks like we're having some difficulties.");
}
});
return false;
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Outlook 2010 Add-in throws error message
I'm using Visual Studio 2013 and am trying to create an Outlook 2010 Add-in, and found an MSDN article on how to set up a rudimentary add-in at this url: http://msdn.microsoft.com/en-us/library/cc668191.aspx. So far my code is exactly like in the article, no changes at all, and when I try to run in debug mode I get the following error:
Outlook experienced a serious problem with the add-in. If you have
seen this message multiple times, you should disable this add-in and
check to see if an update is available. Do you want to disable this
add-in?
Here is a copy of the code in the ThisAddIn.cs file:
public partial class ThisAddIn
{
private Outlook.Inspectors inspectors;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
inspectors = this.Application.Inspectors;
inspectors.NewInspector +=
new Microsoft.Office.Interop.Outlook.InspectorsEvents_NewInspectorEventHandler(Inspectors_NewInspector);
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
void Inspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
{
Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;
if (mailItem != null)
{
if (mailItem.EntryID == null)
{
mailItem.Subject = "Added Text";
mailItem.Body = "Added Text to Body";
}
}
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
I've been searching for posts on this problem, but have had no luck, can anyone help with this?
A:
It turned out that Microsoft's EMET version 4.0 was causing this problem. The solution turned out to be disable the "Export Address Table Filtering" for Outlook in EMET, or to upgrade EMET to EMET version 5.1.
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS/Objective-C - How do I send multiple NSURLSessionDataTask requests without losing initial session?
I am currently working on a project in an iOS programming course. As part of a class project I am working to make a particular portion work successfully.
I am using an NSAlert dialog to supply my login and password to fetch my enrolled classes in an HTML string.
My college maintains students' enrolled class schedule on the college information system from which I can log in and see my classes.
I want to log in to the college webpage that has a page called submit.asp to process POST requests sent from a login form. On an actual browser, when I submit my credentials, and after some the server processes and redirects to another page I am able to navigate to my class schedule page with no problem.
- (BOOL) loginToStudentPortal: (NSString *) ID : (NSString *) pin
{
NSString *submitUrl = @"https://eweb4.laccd.edu/Common/submit.asp";
NSString *scheduleUrl = @"https://eweb4.laccd.edu/WebStudent/validate.asp";
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURL *URL = [NSURL URLWithString:submitUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
NSString * submitParams = [NSString stringWithFormat:@"ssn1=%@&ssn2=&pin=%@REDIRECT/WebStudent/validate.asp", ID, pin];
NSString * submitParams2 = [NSString stringWithFormat:@"HOLDER=Y"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[submitParams dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"%@", error);
} else {
//Here I Try to initiate a second dataTaskWithRequest to the next URL
//But there is no way to jump to the destination page without losing the session
//NSString *receivedData = [[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding];
//NSLog(@"%@ %@", response, receivedData);
}];
[dataTask resume];
return YES;
}
However, when I run the initial request from the iPhone simulator in XCode 5, I can not get the session preserved after the first request.
Is it correct to attempt to initiate a follow on dataTask request in the else block of the main completionHandler?
Secondly, do I need to do make sure manually that I follow any redirects from the server?
A:
I was able to resolve the issue and finally get to the destination page.
My initial attempt was a start, but I continued to investigate the behavior further and it seems that one reason I was not able to proceed was that I was debugging and I think the timeout was occurring.
When I ran the program and removed all breakpoints the program would output the correct HTML.
More importantly, I made sure that the exact chain of events was reproduced in my function. I added all the dataTasks required within the completion handlers.
I was eventually able to retrieve the HTML string containing the desired information.
It turns out the session is managed by the method I was using. Probably I had a session timeout which is why I posed the initial question.
| {
"pile_set_name": "StackExchange"
} |
Q:
LoginActivity Crashes during login
Don't no what's the problem,It's just every time i enter username and password
dialog box shows Attempting Login and app just crashes.
Server used:Wamp
Below are the codes used.
Any help would be appreciable.Thanks in advance.
LoginActivity.java:
package com.sam.kiet;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Vaibhav on 10/2/2015.
*/
public class LoginActivity extends Activity implements View.OnClickListener {
private EditText user, pass;
private Button bLogin;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.43.1/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
bLogin = (Button) findViewById(R.id.Blogin);
bLogin.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.Blogin:
new AttemptLogin().execute();
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
//boolean failure = false;
private String username,password;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
username = user.getText().toString();
password = pass.getText().toString();
}
@Override
protected String doInBackground(String... args) {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
Log.d("Login attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Intent main_activity = new Intent(LoginActivity.this, MainActivity.class);
finish();
startActivity(main_activity);
return json.getString(TAG_MESSAGE);
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String message) {
super.onPostExecute(message);
pDialog.dismiss();
if (message != null){
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
}
}
}
}
JasonParsor.java:
package com.sam.kiet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSON Object.
return jObj;
}
}
Login.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context=".LoginActivity"
>
<!-- Login progress -->
<ProgressBar
android:id="@+id/login_progress" style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone"
/>
<ScrollView
android:id="@+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:id="@+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<AutoCompleteTextView
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:inputType="text"
android:maxLines="1"
android:singleLine="true" />
<EditText android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:imeActionId="@+id/login"
android:imeActionLabel="Login"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
<Button
android:id="@+id/Blogin"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Login"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Logcat(error):
10-12 09:02:22.084 1804-1819/com.sam.kiet E/Buffer Error﹕ Error converting
result java.lang.NullPointerException: lock == null
10-12 09:02:22.084 1804-1819/com.sam.kiet E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
10-12 09:02:22.094 1804-1819/com.sam.kiet E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: com.sam.kiet, PID: 1804
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:92)
at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:60)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
10-12 09:02:23.744 1804-1804/com.sam.kiet E/WindowManager﹕ android.view.WindowLeaked: Activity com.sam.kiet.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1402280 V.E..... R......D 0,0-1026,288} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.sam.kiet.LoginActivity$AttemptLogin.onPreExecute(LoginActivity.java:71)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.sam.kiet.LoginActivity.onClick(LoginActivity.java:53)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
New LOGCAT:
10-12 10:40:56.083 5644-5658/com.sam.kiet E/JSON Parser﹕ Error parsing data org.json.JSONException: Value success of type java.lang.String cannot be converted to JSONObject
10-12 10:40:56.093 5644-5658/com.sam.kiet E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: com.sam.kiet, PID: 5644
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:85)
at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:60)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
10-12 10:40:58.003 5644-5644/com.sam.kiet E/WindowManager﹕ android.view.WindowLeaked: Activity com.sam.kiet.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1401ef8 V.E..... R......D 0,0-1026,288} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.sam.kiet.LoginActivity$AttemptLogin.onPreExecute(LoginActivity.java:71)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.sam.kiet.LoginActivity.onClick(LoginActivity.java:53)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
A:
ok I think you get the NullPointer because of this:
if(method == "POST"){
change it to
if("POST".equals(method)){
you compare the object reference and not the values with ==.
That's the reason why the method makeHttpRequest returns null.
of course you have to change this too:
}else if(method == "GET"){
A:
This part of your code
Intent main_activity = new Intent(LoginActivity.this, MainActivity.class);
finish();
startActivity(main_activity);
return json.getString(TAG_MESSAGE);
You create the Intent then you finish() the activity , then you run startActivity() and finally return.
The logic order is wrong, try this approach:
class AttemptLogin extends AsyncTask<String, String, JSONObject> {
//boolean failure = false;
private String username,password;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
username = user.getText().toString();
password = pass.getText().toString();
}
@Override
protected JSONObject doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
Log.d("Login attempt", json.toString());
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
pDialog.dismiss();
if (json != null){
try {
int success = json.getInt(TAG_SUCCESS);
String message = json.getString(TAG_MESSAGE);
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Toast.makeText(LoginActivity.this,"Login successful" + message, Toast.LENGTH_LONG).show();
Intent main_activity = new Intent(LoginActivity.this, MainActivity.class);
startActivity(main_activity);
finish();//only at the end!!!
} else {
Toast.makeText(LoginActivity.this, "Login failed = " + message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Repeat widget n time in Row
I am getting n as integer number from API. Then based on this n I need to add widget n number of times in Row. I am not getting correct way to implement this.
I am adding screenshot to explain what I need to achieve with this.
That rupee icons I need to repeat number of times in Row.
A:
Create a method.
List<Text> _myWidget(int count) {
return List.generate(count, (i) => Text("*")).toList(); // replace * with your rupee or use Icon instead
}
Use it in Row for instance like this.
Row(children: _myWidget(10));
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding columns for mean and sd of rows in R
I have following data frame:
> ddf
aa bb cc dd
1 1 2 3 4
2 5 6 7 8
3 9 10 11 12
>
>
> dput(ddf)
structure(list(aa = c(1L, 5L, 9L), bb = c(2L, 6L, 10L), cc = c(3L,
7L, 11L), dd = c(4L, 8L, 12L)), .Names = c("aa", "bb", "cc",
"dd"), class = "data.frame", row.names = c(NA, -3L))
>
I want to add mean and sd columns (mean and sd for each row) but following does not work:
ddf$mean = mean(ddf[,1:4])
Warning message:
In mean.default(ddf[, 1:4]) :
argument is not numeric or logical: returning NA
> ddf$sd = sd(ddf[,1:4])
Error in is.data.frame(x) :
(list) object cannot be coerced to type 'double'
>
> ddf
aa bb cc dd mean
1 1 2 3 4 NA
2 5 6 7 8 NA
3 9 10 11 12 NA
How can I add columns for mean and sd (for each row)? Thanks for your help.
A:
If you want to get mean for each column, you can use rowMeans(). For SD, I used apply() here.
ddf$Rmean <- rowMeans(ddf)
ddf$SD <- apply(ddf[1:4], 1, sd)
# aa bb cc dd Rmean SD
#1 1 2 3 4 2.5 1.290994
#2 5 6 7 8 6.5 1.290994
#3 9 10 11 12 10.5 1.290994
A:
I would write a function for this. That way you can add to it later if need be, and you don't need to write na.rm = TRUE multiple times.
foo <- function(x, digits = 3L, ...) {
x <- c(x, recursive = TRUE, use.names = FALSE)
res <- c(mean = mean(x, ...), sd = sd(x, ...),
median = median(x, ...), max = max(x, ...))
round(res, digits)
}
cbind(ddf, t(apply(ddf, 1, foo, na.rm = TRUE)))
# aa bb cc dd mean sd median max
# 1 1 2 3 4 2.5 1.291 2.5 4
# 2 5 6 7 8 6.5 1.291 6.5 8
# 3 9 10 11 12 10.5 1.291 10.5 12
| {
"pile_set_name": "StackExchange"
} |
Q:
Design decisions about computational hardware for small mechatronics project
I've recently started learning electronics/mechatronics. As part of my studies, I've been reading about devices such as RaspberryPi, Arduino, etc, and I'm interested in experimenting with such devices.
I have what would, I guess, be considered a "design" question. Let's say I wanted to undertake a small robotics project. Furthermore, let's assume that I wanted this small project to just be something that remains connected (via usb, say) to a computer. In terms of the electronics involved here, how would I go about making design decisions about whether such a device would require a microcontroller (such as Arduino), a self-contained computer (such as Raspberry Pi), or whether no such separate computational hardware is required, since it is connected to the computer (and the computer can do all the computational stuff itself)? Specifically, what I'm actually asking is a beginner technical question: Does such a robotic device, as described, require having some separate, additional computational device, such as an Arduino or Raspberry Pi, in order to operate (since this might be required to interface with the computer, or something), or are such devices superfluous if it is connected directly to the computer already (that is, the computer can somehow (through the more "primitive" (for lack of a better term) circuit board elements) directly interface with, and control, the robotics device? Furthermore, if the latter is the correct answer, then is there any situation in which, despite being connected directly to the computer, that it would be a good design decision to also include one of these separate pieces of computational hardware in the device (say, for computationally intensive tasks (although, it is connected directly to the (much more powerful) computer, so I'm not sure that this would make any sense))?
I'm not sure if this would get covered later at some point in my textbooks, so I thought that I might as well ask now, just in case it never gets covered and I forget.
This probably heavily relates to "control systems" or "control engineering", but I am very new to all of this, so I'm not yet familiar with all of the specifics of hardware.
I would greatly appreciate it if people would please take the time to clarify this.
A:
This question honestly is too broad. You have these criteria:
Suitability of peripherals
Suitability of processing power
Ease of software development
Ease of hardware development
3 and 4 completely dwarf the other two criteria so much when starting out. When starting, just always assume you need a microcontroller in some form until you know for a fact from experience that you need something more.
Arduinos are pre-packaged microcontrollers with software crutches. An RPI is a pre-packaged application processor with an OS. An RPI is an advanced piece of hardware that you have no chance (or money) of building something similar from scratch on your own.
With an Arduino, you are eased into the software side (software crutches in the form of the Arduino programming language/environment) and the bare minimum on the hardware side so you can at least graduate onto bare microcontrollers and re-use the knowledge. You cannot do the same with an RPI because the hardware is too advanced.
| {
"pile_set_name": "StackExchange"
} |
Q:
SharePoint 2010 My Sites versus custom code for Social Networking / Micro-Blogging
What kind of features does the upcoming SharePoint 2010 have in regards to functionality that is like those found in:
FriendFeed, Twitter, Google Wave?
Flickr or Digg (tagging and voting)?
How much of this do you get "for free" with SP 2010 or would you still have to code it all yourself? Any one know what that have added to My Sites? Anything really too difficult for a 2 person senior dev team to code up in 6 weeks?
I'm trying to get a good sense of this before I weight in at some future discussions at work.
A:
Blog posts relating to this from SPC '09:
SharePoint 2010 My Sites, social networking architectural
SPC: Overview of Social Computing in SharePoint 2010
MySite and Social Networking Architecture
There will be tagging and rating so there's a chance custom development won't be required for what you need.
I strongly recommend signing up for the SP2010 beta which will be released late November and have a look yourself if at all possible. (Make note of the system requirements and I understand 8GB of RAM is required for a production server - you may be able to get away with less if you can put up with disk thrashing.)
Also keep an eye on the SharePoint 2010 section of SharePointDevWiki.
| {
"pile_set_name": "StackExchange"
} |
Q:
Solving $3x^2 - 4x -2 = 0$ by completing the square
I can't understand the solution from the textbook (Stroud & Booth's "Engineering Mathematics" on a problem that involves solving a quadratic equation by completing the square.
The equation is this:
$$
\begin{align}
3x^2 - 4x -2 = 0 \\
3x^2 - 4x = 2
\end{align}
$$
Now, divide both sides by three:
$$x^2 - \frac{4}{3}x = \frac{2}{3}$$
Next, the authors add to both sides the square of the coefficient of $x$, completing the square on the LHS:
$$x^2 - \frac{4}{3}x + \left(\frac{2}{3}\right)^2 = \frac{2}{3} + \left(\frac{2}{3}\right)^2$$
Now, the next two steps (especially the second step) baffle me. I understand the right-hand side of the first quation (how they get the value of $\frac{10}{9}$), but the last step is a complete mystery to me:
$$
\begin{align}
x^2 - \frac{4}{3}x + \frac{4}{9} = \frac{10}{9} \\
\left(x - \frac{2}{3}\right)^2 = \frac{10}{9}
\end{align}
$$
Can anyone please explain how they went from the first step to the second step?
A:
Try going backward; expand the square $(x-\tfrac{2}{3})^2$ to find that
$$\left(x-\frac{2}{3}\right)^2=\left(x-\frac{2}{3}\right)\left(x-\frac{2}{3}\right)=x^2-\frac43x+\frac49.$$
A:
Well, $(x-a)^2=(x-a)(x-a)=x^2-2ax+a^2$ with $a=\frac{2}{3}$ gives the last line.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why Does $\mathbf{Set}$ Have Equalizers for All Pairs of Arrows?
From pg. 113 of Categories for the Working Mathematician:
Problem: This seems to imply that $\mathbf{Set}$ has equalizers for all pairs of arrows. But how could this be so? Consider $A = \{0\}$ and $B=\{1,2\}$ with $f,g: A \rightarrow B$ s.t. $f(0) = 1$ and $g(0) = 2$. Then there couldn't be an $e: E \rightarrow A$ s.t. $fe = ge$ for any set $E$. Doesn't this then mean that $f$ and $g$ don't have an equalizer?
A:
The equalizer of your $f$ and $g$ is the (unique) empty map $\varnothing\to\{0\}$.
In general, to construct an equalizer in $\mathbf{Set}$ for $f,g:X\to Y$, take the identity injection
$$ \{ x\in X\mid f(x)=g(x) \} \to X $$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Optionally Protect a Resource with Custom Dropwizard Filter
I'm using Dropwizard 0.9.2 and I want to create a resource that requires no authentication for GET and requires basic authentication for POST.
I have tried
@Path("/protectedPing")
@Produces(MediaType.TEXT_PLAIN)
public class ProtectedPing {
@GET
public String everybody() {
return "pingpong";
}
@PermitAll
@POST
public String authenticated(){
return "secret pingpong";
}
with
CachingAuthenticator<BasicCredentials, User> ca = new CachingAuthenticator<>(environment.metrics(), ldapAuthenticator, cbSpec);
AdminAuthorizer authorizer = new AdminAuthorizer();
BasicCredentialAuthFilter<User> bcaf = new BasicCredentialAuthFilter.Builder<User>().setAuthenticator(ca).setRealm("test-oauth").setAuthorizer(authorizer).buildAuthFilter();
environment.jersey().register(bcaf);
environment.jersey().register(RolesAllowedDynamicFeature.class);
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
environment.jersey().register(new ProtectedPing());
This seems to result in all requests to "/protectedPing" requiring basic auth.
In Dropwizard 0.9.2 the documentation says to create a custom filter if I have a resource that is optionally protected. I'm assuming I need to do that, but I don't know where to start, or if that I what I actually need to do.
A:
this is more of a jersey problem than a dropwizard problem. You can have a look here: https://jersey.java.net/documentation/latest/filters-and-interceptors.html
Essentially what you want is:
Create an annotation that indicates that you want to test for authentication (e.g. @AuthenticatePost)
Create the resource and annotate the correct method with @AuthenticatePost
Create your authentication filter (probably kind of like what you did above).
In the dynamic feature, test for the annotation to be present on the passed in resource. This will hold true for post, false for get. Then register the AuthenticationFilter directly on the resource method instead of globally on the resource.
This would be a semi-complete example of how I would solve this:
public class MyDynamicFeature implements DynamicFeature {
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
if(resourceInfo.getResourceMethod().getAnnotation(AuthenticateMe.class) != null ) {
context.register(MyAuthFilter.class);
}
}
public class MyAuthFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// do authentication here
}
}
public @interface AuthenticateMe {
}
@Path("myPath")
public class MyResource {
@GET
public String get() {
return "get-method";
}
@POST
@AuthenticateMe
public String post() {
return "post-method";
}
}
}
Note, the DynamicFeature checks that the Authenticate Annotation is present, before registering the authentication with the feature context.
I hope that helps,
let me know if you have any questions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does MVC3 automatically dispose of current instance of database object?
does MVC automatically dispose of the database context I instantiate in a controller or anywhere else or does it persist?
Do I need to use using or can I not worry about that?
A:
If you are talking about an EF data context, the answer is no, ASP.NET MVC, doesn't dispose it automatically but you shouldn't be worried about disposing it as Stephen Walther explains in his blog post. And here's a similar answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
At checkout: I don't need [?] bag
Like some others, at the checkout of a local store the cashier asked me:
Do you need a bag?
As I already had my own, I answered "No, thanks." However, I would like to be a bit more talkative next time, but I don't know with which word to fill in the blank in following sentence:
No, I don't need bag, thank you!
I don't know if it's a bag, no bag, any bag ...
A:
The correct phrase here is "no, I don't need a bag."
"I don't need no bag" is something you might hear sometimes -- double negatives ("do not need no bag") are technically incorrect, but used by many native speakers anyway.
"I don't need any bags" means exactly the same thing (in this context) as "I don't need a bag," and is the most obvious answer had the cashier asked "do you need any bags?"
"I don't need any bag" means something slightly different. It's grammatically correct, and would be understood fine, but it actually implies that you don't need bags in general. Saying "I don't need any bag" implies that you don't need a bag ever, in all of life.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP Select dropdown Option value array
I'm trying to make my select dropdown filter on results by row if that makes any sense!
Essentially I have a table and there's 5 rows in it, each with different date - each row has a dropdown with a list of users that are available to work on that date. I have all the users showing correctly and I have it where it filters a user that can't work that day - the only issue is that it only seems to do it for the first result.
So for example;
User A can't work 10/06/2019 & 11/06/2019 - User A won't show in the dropdown for row dated 10/06/2019, but will show in row dated 11/06/2019.
User B can work on all dates on the table so will show in all dropdowns.
I've tried modifying my array and my query, tried using a counter too but not getting anywhere!
if ($available_date == $stk_date) {
$query = "SELECT * FROM user_master WHERE id NOT IN (SELECT UM.id FROM user_master UM JOIN bookings B ON B.id_item = UM.id JOIN stocktakes S ON B.the_date = S.stk_date)";
$result = mysqli_query($connect, $query);
//$row = mysqli_fetch_array($result);
if ($result) {
while ($row = mysqli_fetch_array($result)){
echo "<option value=$row[first_name]>$row[first_name] $row[last_name]</option>'";
}
}
}
else {
$query = "SELECT * FROM user_master";
$result = mysqli_query($connect, $query);
//$row = mysqli_fetch_array($result);
if ($result) {
while ($row = mysqli_fetch_array($result)){
echo "<option value=$row[first_name]>$row[first_name] $row[last_name]</option>'";
}
}
}
echo "</select></td>";
*For some reason my code isn't including my first echo, it's just the id name of the select which is supervisor_id_1
Any ideas on where I'm going wrong?
Update:
Removed update as it's a different question.
A:
In both your IF and ELSE you have a
$row = mysqli_fetch_array($result);
that is reading the first row from your resultset, but you are not using in your output. Just remove those 2 lines, see code below for annotations
if ($available_date == $stk_date) {
$query = "SELECT * FROM user_master
WHERE id NOT IN (
SELECT UM.id
FROM user_master UM
JOIN bookings B ON B.id_item = UM.id
JOIN stocktakes S ON B.the_date = S.stk_date)";
$result = mysqli_query($connect, $query);
// remove, its just throwing your first result away
//$row = mysqli_fetch_array($result);
if ($result) {
while ($row = mysqli_fetch_array($result)){
echo "<option value=$row[first_name]>$row[first_name] $row[last_name]</option>'";
}
}
} else {
$query = "SELECT * FROM user_master";
$result = mysqli_query($connect, $query);
// remove, its just throwing your first result away
//$row = mysqli_fetch_array($result);
if ($result) {
while ($row = mysqli_fetch_array($result)){
echo "<option value=$row[first_name]>$row[first_name] $row[last_name]</option>'";
}
}
}
echo "</select></td>";
| {
"pile_set_name": "StackExchange"
} |
Q:
start or stop a cloudera manager management service using python API
I am trying to use Cloud era manager python API for starting and stopping the cluster.
IS it possible to stop the management roles also using this API?
IF can you let me know the commands or the documentation page?
Thanks
A:
Here's an example on how to stop Management Services using the python CM API
# CM API in python
from cm_api.api_client import ApiResource
api = ApiResource("cm-host.cloudera.com")
mgmt = api.get_cloudera_manager().get_service()
# stop the Mamagement Services
mgmt.stop()
# start the Management Services
mgmt.start()
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.