text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
How can I speed up this sql query with substring?
Is there a way to speed up this working query?
I have 4 tables in my database (Area, APeriod, Data, Item). They are setup as follows [column_name (with example)]:
Area [area_code (A102)] [Area_name (Philadelphia-Wilmington-Atlantic City, PA-NJ-DE-MD]
APeriod [period (M01)] [period_abbr (JAN)] [period_name (January)]
Item [item_code (701322)] [item_name (spaghetti and macaroni, per lb. 453.6 gm)]
Data [series_id] [year (1995)] [period (M01)] [value (0.235)] [footnote_codes]
Query Description - Determine the price ratio per pound of steak sirloin [703611] to wine, red and white table (all sizes, any origin; per 1 liter) [702311] in the Miami-FT. Lauderdale area aggregated by month and separately aggregated by years from 1995 to present.
Query Code:
SELECT main.year, APeriod.period_name, steak.value AS Steak, wine.value AS Wine, steak.value/wine.value AS Ratio
FROM
(SELECT DISTINCT year, period FROM Data) main
INNER JOIN APeriod ON main.period = APeriod.period
LEFT OUTER JOIN Data steak ON steak.series_id ='APU0100703611' AND main.year=steak.year AND main.period=steak.period
LEFT OUTER JOIN Data wine ON wine.series_id ='APU0400720311' AND main.year=wine.year AND main.period=wine.period
ORDER BY main.year, main.period
This query works but it takes the MySQL server on average 129 seconds to run this query (which i'm told is ridiculously long).
Example of return
[Showing rows 0 - 24 (209 total, Query took 137.6224 seconds.) [year: 1995 - 1997]
year period_name Steak Wine Ratio
1995 January 3.593 NULL NULL
1995 February3.510 NULL NULL
1995 March 3.708 NULL NULL
1995 April 3.747 NULL NULL
1995 May 3.462 NULL NULL
1995 June 3.742 NULL NULL
1995 July 3.686 4.661 0.7908174
1995 August 3.823 3.978 0.9610357
1995 Septemb 3.625 4.580 0.7914847
1995 October 3.795 4.042 0.9388916
1995 November3.509 4.760 0.7371849
1995 December3.315 4.056 0.8173077
(couldn't insert image properly, sorry)
I tried taking the substring and creating a view to help speed things up but encountered other errors which leads me to believe that I did something wrong as I am new to sql. Is there a way to speed this up? If so, please show me. Thanks in advance.
A:
This is your query:
SELECT main.year, APeriod.period_name, steak.value AS Steak, wine.value AS Wine,
steak.value/wine.value AS Ratio
FROM (SELECT DISTINCT year, period FROM Data) main INNER JOIN
APeriod
ON main.period = APeriod.period LEFT OUTER JOIN
Data steak
ON steak.series_id ='APU0100703611' AND
main.year=steak.year AND
main.period=steak.period LEFT OUTER JOIN
Data wine
ON wine.series_id ='APU0400720311' AND
main.year=wine.year AND
main.period=wine.period
ORDER BY main.year, main.period;
Indexes should be a big help. I would suggest:
create index idx_data_year_period_series on data(year, period, seies);
create index idx_aperiod_period on aperiod(period);
The second of these (on aperiod.period) already exists if aperiod.period is declared either as a primary key or unique.
| {
"pile_set_name": "StackExchange"
} |
Q:
Should Git workspace automatically adjust to the content of a specific branch?
Git checkout/pull doesn’t remove directories?
I'm kind of new to git and slowly learning various parts of it.
So forinstance I have a branch
Master with FolderA
I have later from Master created a branch
Dev and added FolderB
So Dev as result have FolderA and FolderB
now when I do git branch master, I'm assuming folder B should be deleted.
But I see FolderB as unstaged folder in master, as I understand it should be removed.
Further more, if I go ahead, when in branch Dev deleting FolderA, when changing branch
to master and back to Dev FolderA appears unstaged in branch Dev.
So why is git not deleting these folders? should I always do some sort of clean command like git clean -f -d?
Or what am I missing?
My real scenario is much more complicated however this simple example should cover the problem I'm experiencing at a larger scale.
Just to be clear:
This questions is about content of the branch, it is not concerned with folders only. However the answer is similar to another question pointed out here, but the questions is different.
A:
Although Git manages the files within your folders, it doesn't delete the folder itself when switching to a branch where the folder isn't needed. Don't worry about it, you're not missing anything.
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ delete pointer
#include <iostream>
#include <string>
using namespace std;
int main() {
string* pstr2 = new string;
cout << "pointer pstr2: " << pstr2 << endl;
delete pstr2;
cout << "pointer pstr2 after deletion: " << pstr2 << endl;
string* pstr = new string;
pstr->push_back('a');
cout << "pointer pstr: " << pstr << endl;
cout << "*pstr: " << *pstr << endl;
delete pstr;
cout << "pointer pstr after deletion: " << pstr << endl;
cout << "*pstr after deletion: " << *pstr << endl;
return 0;
}
The output is as follows:
pointer pstr2: 0x7ffe00404d10
pointer pstr2 after deletion: 0x7ffe00404d10
pointer pstr: 0x7ffe00404d10
*pstr: a
pointer pstr after deletion: 0x7ffe00404d10
*pstr after deletion: a
Questions:
I know there is a practice to set dynamic pointer to NULL after deleting the pointer. But why does pstr2 still have valid address?
Deleting pointer pstr frees the memory, i.e., "a". But why does *pstr still have valid content as "a"?
Why does pstr and pstr2 have the same allocated address? I have run the code for several times.
A:
I know there is a practice to set dynamic pointer to NULL after deleting the pointer. But why does pstr2 still have valid address?
It doesn't have a "valid" address. By deleting the memory at that address you invalidated it. The address does not change but the memory that was allocated to that address has been unassigned and may be overwritten/removed at any time.
Deleting pointer pstr frees the memory, i.e., "a". But why does *pstr still have valid content as "a"?
The content is not "valid" it just happens to not have changed. There is no guarantee of that. Deleting the memory does not necessarily change its contents. It may just mark it as available to another variable.
Why does pstr and pstr2 have the same allocated address? I have run the code for several times.
That's just a coincidence. Its not guaranteed to always be the same. If it is its an artifact of the way the memory allocation functions works for that speific compiler implementation.
| {
"pile_set_name": "StackExchange"
} |
Q:
WSO2 ESB alters the wsdl
I have a backend service which I configure as a proxy service in WSO2 ESB.
The ESB exposes slightly different wsdl, which is also valid and works as expected.
The problem is I can't use my old stubs with the ESB wsdl because of the changed structure. I want to create the service in such a way that the wsdl from ESB is EXACTLY the same as my endpoint service.
Is such approch poissible or do I need to generate again the stubs (this would require a lot of effort in my case)?
EDIT: The difference in the WSDL between endpoint and esb wsdl
1. For example my endpoint has following tags
<xs:element name=", - Endpoint
<xsd:element name= - ESB
2. Another difference is:
<wsdl:service name="CasesServiceService"> - Endpoint
<wsdl:service name="CasesService"> - ESB
3. Port names:
<wsdl:port name="CasesServiceHttpSoap11Endpoint" binding="tns:CasesServiceSoap11Binding">
<wsdl:port binding="tns:CasesServiceServiceSoapBinding" name="CasesServicePort">
A:
In order to make WSO2 ESB keep the same WSDL contract with the exact same services / ports names, you can edit the Apache Synapse configuration file for your proxy service directly. Just click on "Source View" in the WSO2 ESB interface and add the following parameters to the <proxy> node:
<parameter name="useOriginalwsdl">true</parameter>
<parameter name="modifyUserWSDLPortAddress">true</parameter>
This will make it use the original WSDL and modify only the port address so it points to the bus.
The relevant documentation is here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to display image label in second Tkinter frame
I am trying to build a simple gui using Tkinter. The application involves a smaller secondary frame opening up over the primary one upon pressing a button. This secondary frame must contain an image. Image labels appear easily on the primary frame, but on the secondary frame, the image label appears as an empty box the size of the image, with whatever background colour I set.
Here's how I'm doing it:
#send diagram page
def send_diagram():
send_diagram_frame=tk.Frame(frame, bg="#D4BAEC")
send_diagram_frame.place(relx=0.5, rely=0.5, relheight=0.7, relwidth=0.7, anchor="center")
send_diagram_entry_working_image=Image.open('/home/raghav/RemEdi/design/assets/generic_page_entry.png')
send_diagram_entry_image=ImageTk.PhotoImage(send_diagram_entry_working_image)
send_diagram_entry_label=tk.Label(send_diagram_frame, image=send_diagram_entry_image)
send_diagram_entry_label.place(relx=0.5, rely=0.5, anchor="center")
return
As visible, send_diagram() is the command for the button.
I have tried adding another smaller frame inside the secondary frame to contain the image, but that did not work either.
Any help would be greatly helpful. Thanks!
A:
You are creating the new image inside a function, with it's own local namespace. When the function ends the reference to the image will be garbage collected.
You can fix this by saving a reference to the image in the Label widget. Put this line in the function after the image is created:
send_diagram_entry_label.image = send_diagram_entry_image
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript subclass object not retaining properties / methods of base class
function Man(name){
this.name = name || 'John';
}
Man.prototype.getName = function(){
return this.name;
}
function Emp(id){
this.id = id;
}
Emp.prototype = Object.create(Man.prototype);
Emp.prototype.display = function(){
return this.id;
}
//Testing
var emp = new Emp(100);
emp.id ; // 100
emp.display() //100
However,
emp.name // undefined
emp.getName() // undefined
emp instanceof Man // true, proves inheritance
Why do emp.name and emp.getName() come as undefined
A:
Why do emp.name and emp.getName() come as undefined
Because you are never applying Man to the new Emp instance. You also have to call the parent constructor in the child constructor:
function Emp(id){
Man.call(this); // call parent constructor
this.id = id;
}
With ECMAScript 6 classes, you would have to call super:
class Emp extends Man {
constructor(id) {
super();
this.id = id;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
.net Libraries not showing on Mac OSX El Capital 10.11.6
I have Visual Studio Community for Mac v7.33 installed so I can create a C# application. Using Homebrew I installed openssl 1.0.2. I also installed .net Core SDK 1.1.7 (x64) for Mac, yet I cannot access the System.Windows.Forms library to create a simple button. What am I missing here? How do I access the standard .net libraries or is it a different process for a Mac?
A:
There is no .net core version of windows.forms. The closest you will find to windows forms on a mac is to create a new project and look under other --> .net --> Gtk# 2.0 project
| {
"pile_set_name": "StackExchange"
} |
Q:
Besides macros, are there any other metaprogramming techniques?
Possible Duplicate:
Programming languages with a Lisp-like syntax extension mechanism
I'm making a programming language, and, having spent some time in Lisp/Scheme, I feel that my language should be malleable. Should I use macros, or is there something else I might/should use? Is malleable syntax even a good idea? Is it perhaps too powerful a concept?
In doing some research, I found fexprs. I don't really understand what these are. Help with that in an answer too please.
Is it possible to have a language with macros/something-of-a-similar-nature without having s-expressions?
A:
You might want to take a look at Ruby, which has a great deal of support for metaprogramming. The book Eloquent Ruby covers the language well, with a significant amount of attention to metaprogramming in the later chapters. There is also a book called Metaprogramming Ruby that is well-reviewed, but which I have not personally read yet.
Metaprogramming in Ruby is far more flexible (and powerful . . . and dangerous) than what is provided by .NET's Reflection libraries (since Guy Coder mentioned C# in his answer, I thought this comparison might be useful). In Ruby, you can use hooks to dynamically select which mixin modules you want to add to a class at runtime, use "method_missing" for flexible error handling and delegation, use monkey patching to choose what code to add in dynamically, and get yourself into all kinds of awesomely amazing trouble writing self-modifying code. This makes Ruby a very powerful language for, e.g., writing your own domain-specific language (DSL).
Note: I used a lot of jargon in the second paragraph. My hope is that this will provide people who are interested in more information with search terms for web searches, in case someone wants to know more but isn't ready to buy a book on the topic yet.
| {
"pile_set_name": "StackExchange"
} |
Q:
Linq2sql update each row in a huge table
I have a huge table (over 80M rows) and I created a model from the DB using linq2sql. I loop over the table (all 80M rows) and update each row with several values. I have done the most to optimize the code around the linq2sql code, but it looks like the db.SaveChanges() method hangs on the first update.
My code looks something like this (I`m paraphrasing for readability):
using(MessageListCtx db = new MessageListCtx())
{
foreach(var message in db.MessageList.OrderByDescending(e => e.RecordId))
{
message.hashCode = Hasher.GenerateHash(message.name);
db.SubmitChanges();
}
}
I'm guessing that the issue is that when I call db.SubmitChanges(); all objects in the context are iterated for changes, which takes a while with over 80M objects, but I have no idea how to get around this.
I was thinking about paging the results using a for loop. Something like: db.MessageList.Skip(i).Take(1000). But I`d rather an out-of-the-box solution, if one exists.
Can someone please point me in the right direction?
A:
Forget it
Linq 2sql is not made for batch operations. You really need to move this to a set operated level to get some performance.
No matter what you do, you will get individual update statements so no performance.
I guess the fastest way is to do something like this:
use the foreach without change tracking (ObjectTrackingEnabled = false )
build an in-memory data structure with hashes
use sqlbulkcopy to bulk insert into a staging table (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx)
use an 'old school' update statement to update you large table
And I guess still with this approach you might want to buffer this into 100k records at a time
| {
"pile_set_name": "StackExchange"
} |
Q:
How to build unity project with firebaseUI from android library elegantly
I'm trying to create a game with firebase google and facebook login. I know that it is possible to use firebase with unity, but I don't want to create both login methods separately, when something like FirebaseUI exists.
So I've created android plugin with FirebaseUI authentication. I tested it in new android project and everything works fine. But when I use my plugin in unity, I have to add my own gradle (mainTemplate.gradle) with dependencies for firebaseUI.
Problem is that there is a default value in firebase auth library and when the game is built, values from my library (default_web_client_id etc.) is overwritten by default value.
Almost after week I found a solution, but I hope there is another way.
My solution: Build android library with firebase, copy library (.aar) to Assets/Plugins, export unity project with this library to Idea, then copy the entire file values.xml (that is created from google-services.json) and facebook appId to res folder in exported project. (then build from Idea)
It's working, but by this method, I have default_web_client_id 3 times in project (1x from my library, 1x from FirebaseUI dependency and 1x from copied values.xml, that overrides them). It's not a problem, but I think that it's not necessary.
Is there any more elegant way to work with firebaseUI and android libraries?
mainTemplate (dependency part):
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
def room_version = "1.1.1"
implementation "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version"
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "android.arch.lifecycle:viewmodel:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.firebaseui:firebase-ui-auth:4.3.1'
implementation 'com.facebook.android:facebook-android-sdk:4.41.0'
**DEPS**}
A:
after some more experiments I found that it depends on implementation order, so I moved **DEPS** up and now its working.
So the solution is easy:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
**DEPS**
def room_version = "1.1.1"
implementation "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version"
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "android.arch.lifecycle:viewmodel:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.firebaseui:firebase-ui-auth:4.3.1'
implementation 'com.facebook.android:facebook-android-sdk:4.41.0'
}
Hope that this helps somebody.
| {
"pile_set_name": "StackExchange"
} |
Q:
Explanation of the line 'But you don't really care for music, do you' in "Hallelujah"
In the first verse of Leonard Cohen's "Hallelujah", there are these lines:
Now, I've heard there was a secret chord
That David played and it pleased the Lord
But you don't really care for music, do you?
It goes like this...
I can't figure out what the But you don't really care for music, do you? line is supposed to mean. Who is it addressed to? Why is it relevant in that spot?
A:
The song has many verses, some of which varied in different performances. Even sticking to the "canonical" verses used in the Jeff Buckley version, however, there's demonstrably no one consistent "you" being referred to between verses. This can be shown by the fact that the "you" in the second verse seems to be a composite of Sampson and King David himself, whereas the first verse refers to David in the third person.
Given that, the answer is ambiguous, but the most natural reading to me is to assume the first, third, fourth (and arguably the fifth) verses are all directed to the narrator's lover, who seems to be a somewhat distanced and indifferent figure (with the second verse taking a detour to directly address the subject of the first). The narrator seems to idolize [her], with the first and fourth verses somewhat blasphemously conflating her with God.
Under that reading, we can picture the narrator (Cohen?), a songwriter writing a song for his girlfriend. He pictures himself charming her with his song, like King David pleased the Lord with a "secret chord." But he know that in real life, she's not even a fan of his music, or really any music. There's no secret key to her heart, or at least, not one that he knows (compare the similar themes in Frank Ocean's Songs For Women, which directly references this line).
EDIT: This source indicates that all the best-known verses come from two separate recordings by Cohen, a 1984 version with more religious imagery, and a 1988 version more focused on the relationship with a lover. The Buckley version includes verses from both, although not the single verse shared between versions. It's only the second verse from the first version, however, that clearly addresses someone other than the narrator's lover.
A:
Strictly speaking, this answer duplicates one that @Chris Sunami has already given: the "you" is a woman the singer addresses. But when I came and read his answer, I felt there was still some interest in mine. Like him, I wonder if my answer will strike readers as sacrilegious. I apologize if it is offensive.
The flow of thought in Cohen's lyrics is not logical; it is subjective and psychological. The poet is associating events in the lives of biblical David and Samson with events in his own life.
Passages referring specifically to David include (1) Now, I've heard there was a secret chord / That David played, and it pleased the Lord… The baffled king composing hallelujah; (2) You saw her bathing on the roof / Her beauty and the moonlight overthrew ya; and (3) the title and refrain.
(1) The first passage (Now, I've heard there was a secret chord / That David played, and it pleased the Lord… The baffled king composing hallelujah) refers to the David as a “musician credited for composing many of the psalms contained in the Book of Psalms” (Wikipedia) which does contain the oft-repeated title word.
David is often pictured with a harp or lyre, as in the picture David Playing the Harp by Jan de Bray, 1670.
(2) The second passage (You saw her bathing on the roof / Her beauty and the moonlight overthrew ya) refers to the story of David and Bathsheba, which appears in 2 Samuel 11:
2 One evening David got up from his bed and walked around on the roof
of the palace. From the roof he saw a woman bathing. The woman was
very beautiful, 3 and David sent someone to find out about her. The
man said, “She is Bathsheba, the daughter of Eliam and the wife of
Uriah the Hittite.” 4 Then David sent messengers to get her. She came
to him, and he slept with her. (Now she was purifying herself from her
monthly uncleanness.) Then she went back home. 5 The woman conceived
and sent word to David, saying, “I am pregnant.”
(3) And the third, the title and refrain, are a word used many times through the book of Psalms and often left untranslated in English versions. (It sometimes appears consecutively, but not in as many consecutive statements as in Cohen’s song. That’s more typical of spirituals.)
Passages referring specifically to Samson include (4) She tied you to a kitchen chair / She broke your throne, and she cut your hair. This relates to the way that Delilah betrayed Samson in Judges 16:
4 Sometime later, he [Samson] fell in love with… Delilah. 5 The rulers
of the Philistines went to her and said, “See if you can lure him into
showing you the secret of his great strength and how we can overpower
him so we may tie him up and subdue him. Each one of us will give you
eleven hundred shekels of silver.” 6 So Delilah said to Samson, “Tell
me the secret of your great strength and how you can be tied up and
subdued.” 7 Samson answered her, “If anyone ties me with seven fresh
bowstrings that have not been dried, I’ll become as weak as any other
man.” 8 Then the rulers of the Philistines brought her seven fresh
bowstrings that had not been dried, and she tied him with them. 9 With
men hidden in the room, she called to him, “Samson, the Philistines
are upon you!” But he snapped the bowstrings as easily as a piece of
string snaps when it comes close to a flame. So the secret of his
strength was not discovered… 15 Then she said to him, “How can you
say, ‘I love you,’ when you won’t confide in me? This is the third
time you have made a fool of me and haven’t told me the secret of your
great strength.” 16 With such nagging she prodded him day after day
until he was sick to death of it. 17 So he told her everything. “No
razor has ever been used on my head,” he said, “because I have been a
Nazirite dedicated to God from my mother’s womb. If my head were
shaved, my strength would leave me, and I would become as weak as any
other man.” 18 When Delilah saw that he had told her everything, she
sent word to the rulers of the Philistines, “Come back once more; he
has told me everything.” So the rulers of the Philistines returned
with the silver in their hands. 19 After putting him to sleep on her
lap, she called for someone to shave off the seven braids of his hair,
and so began to subdue him. And his strength left him. 20 Then she
called, “Samson, the Philistines are upon you!” He awoke from his
sleep and thought, “I’ll go out as before and shake myself free.” But
he did not know that the Lord had left him. 21 Then the Philistines
seized him, gouged out his eyes and took him down to Gaza. Binding him
with bronze shackles, they set him to grinding grain in the prison. 22
But the hair on his head began to grow again after it had been shaved.
The biblical figures loved G-d and wished to serve Him; but they were merely men, with weakness and failure in their nature, and they failed in crucial ways suggested in the lyrics -- David with Bathsheba, Samson with Delilah. Yet through it all (in Cohen's version) they repeated the title of the song, which is the Hebrew word for "praise G-d." Serving G-d remained the meaning of their lives, and in that sense they remain loyal despite their failings. They remain hopeful that G-d will accept that which is good in them.
Similarly the poet loves the woman he addresses and wishes to serve her; but he is merely a man, with weakness and failure in his nature, and he failed in crucial ways. (The nature of this failure is perhaps suggested by the fact that David's and Samson's failures were with women.) Yet through it all the poet repeated the title of the song. Serving the woman he loves remained the meaning of his life, and in that way he remain loyal despite his failings and hopeful that she will accept that which is good in him.
The line you ask about is one of the points of transition in the song. The poet says that while David was able to serve his G-d with music, the poet is not able to serve his love with music because she does not like music. This is of course ironic if we think of the poet as Cohen himself, whose occupation is music and who is even at this moment addressing the woman with a song.
I did my best, it wasn't much
I couldn't feel, so I tried to touch
I've told the truth, I didn't come to fool you
And even though it all went wrong
I'll stand before the lord of song
With nothing on my tongue but hallelujah
| {
"pile_set_name": "StackExchange"
} |
Q:
javascript variables to html?
here is the case:
ive got 2 lists on my website. country and region. when the user first enter the options are ALL and ALL. then he picks a country and a region. and i use jquery bbq to hash the url with different variables for remembering the unique ajax rendered pages. for example:
webpage#country=1®ion=3
webpage#country=2®ion=3
now i want the user to be able to send this url to another person and the browser will display the same html select lists.
so i came up with a solution:
first i grab the hash with jquery and turn them into cookies.
then i've got the following html code:
<select>
<?php
while($row = mysqli_fetch_assoc($countries))
{
if($row['id'] == $_COOKIE['country'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else
{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
?>
</select>
this will show the option that the user had picked from the list. and the same things goes for the region select list.
but the problem is that it doesnt work in firefox. and in safari its too slow to be shown. the cookies are created after the html is shown. so i have to refresh the page a second time.
it just seems like its not a very good solution. and i dont want the html to render all the options and then afterwards change to the picked option with jquery. then the user sees the lists suddenly change and its ugly.
what are my options here? i think this issue has crossed a lot of ajax programmers mind.
(the site got more than 2 lists so i really want this to work)
A:
I don't think cookies are moving you in the right direction. Cookies are for remembering something AFTER the first visit. Not before.
No matter what, if you code this on the client side using javascript or anything else, some one will have a connection/browser slow enough that they will see the options load one way and then get switched. It sounds more like you want the server to dynamically generate the options list. Make it so the generated links are
webpage?country=1®ion=3
webpage?country=2®ion=3
Then the server knows what was pre-selected and can generate the initial version with the right values pre-selected. But if the user comes in without passing in values for country/region, then just generate the page as you normally would.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is this knee pain when going downhill?
I can hike uphill practically all day. However as very soon after I start a descent, pain builds on the outside of my knee. What is causing this and can I do anything to prevent/mitigate it (other than Ibuprofen)?
Edit: I talked to my doc and the location of the pain is very important in the cause. Note that this is pain on the outside (side) of the knee specifically, as opposed to pain in the knee or below/under the kneecap.
A:
Talked to my doc today during a visit for something else. It's Iliotibial Band Syndrome. The band of connective tissue that runs along the outside of the knee becomes irritated and inflamed. It's often caused by over-pronation and poor gait which is exacerbated on the weight bearing leg (not the landing leg) when going downhill. Once injured, the only good solution is rest and anti-inflammatory medication while it heals.
There are specific exercises and stretches that will work to prevent the injury. Specifically you have to stretch the band itself and build the muscles above the knee
Pain from excess force on the downhill would usually present below or in the kneecap, not to the side.
A:
In addition to the suggestions above, regular use of walking or trekking poles are a great help in alleviating knee and hip problems.
A:
I have experienced the same when trail running.
I can pretty consistently reproduce the symptoms on downhill stretches when running distances that are much longer than my regular runs, when starting to hit the trails again after not running for a while, and when running downhill at a faster pace than I would run uphill.
The following is my hypothesis, meaning I don't have any published facts to back this up:
When going uphill we are fighting gravety in a pretty static way. It is not likely that we would go any faster or for longer distances than our muscle-mass permits.
When going downhill on the other hand, we have momentum that our muscles have to slow down. Fightling gravety becomes less static and more dynamic, especially with steeper slopes and higher speeds. We can keep going even when our muscles are fatiguing, and we can go faster than our muscles can effectively slow down, which passes the stress of slowing down on to our skeletal system (mainly our joints.) This can be compounded by heavy heal-striking (less cushioning by our muscles) and a heavy pack (providing a larger mass, which increases the momentum.)
My advice would be to take downhill stretches at a much slower pace (on my trail runs I am MUCH slower going downhill than uphill!), avoid steep slopes until you build up the specific muscles you use for descending, don't take as much stuff when moving on steep terrain and transition to a midd-foot-strike when you notice your knee is hurting (a word of caution: practice this! If you are a heavy heel-striker this can be very tiring for your calfs and you can damage your achilles-tendon if you don't strengthen it first.)
I take this kind of pain pretty seriously. To me it is a sign that even though I have the conditioning, I am missing the muscles to do what I am doing when my knees hurt.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can Perl's "exists" modify data structure values?
I have a nested hash table that looks like this:
my %myhash = (
"val1" => {
"A/B.c" => {
"funct1" => 1
}
},
"val2" => {
"C/D.c" => {
"funct2" => 1
}
}
)
My objective with this data structure is to produce different values based on whether certain hash tables exist. For example,
sub mysub
{
my $val = shift;
my $file = shift;
my $funct = shift;
if (exists $myhash{$val}{$file}{$funct}) {
return "return1";
}
if (exists $myhash{$val}{$file}) {
return "return2";
}
return "return3";
}
The behavior I'm encountering is as follows. I have an instance in time when
my $val = "val1";
my $file = "C/D.c";
my $funct = "funct3";
At this point in time, the return value I get "return2". These are my observations with the Perl debugger:
Break at first "if" in mysub
Print p $proxToBugs{"val1"}{"C/D.c"} ==> Returns blank line. Okay. Continue and this "if" is skipped.
Continue and break at the second "if" in mysub
Print p $proxToBugs{"val1"}{"C/D.c"} ==> Returns "HASH(0x...)". WTF moment. Function returns "return2".
This tells me that running the first if modified the data structure, which allows the second if to pass when in fact it shouldn't. The function I'm running is identical to the function shown above; this one is just sanitized. Anyone has an explanation for me? :)
A:
Yes. This is because of autovivification. See the bottom of the exists documentation:
Although the mostly deeply nested array or hash will not spring into existence just because its existence was tested, any intervening ones [autovivified arrays or hashes] will [spring into existance]. Thus $ref->{"A"} and $ref->{"A"}->{"B"} will spring into existence due to the existence test for the $key element above. This happens anywhere the arrow operator is used...
Where "...test for the $key element above..." refers to:
if (exists $ref->{A}->{B}->{$key}) { }
if (exists $hash{A}{B}{$key}) { } # same idea, implicit arrow
Happy coding.
A:
As pst rightly points out, this is autovivification. There are at least two ways to avoid it. The first (and most common in my experience) is to test at each level:
if (
exists $h{a} and
exists $h{a}{b} and
exists $h{a}{b}{c}
) {
...
}
The short-circuit nature of and causes the second and third calls to exists to not be executed if the earlier levels don't exist.
A more recent solution is the autovivification pragma (available from CPAN):
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
$Data::Dumper::Useqq = 1;
{
my %h;
if (exists $h{a}{b}{c}) {
print "impossible, it is empty\n";
}
print Dumper \%h;
}
{
no autovivification;
my %h;
if (exists $h{a}{b}{c}) {
print "impossible, it is empty\n";
}
print Dumper \%h;
}
A third method that ysth mentions in the comments has the benefits of being in core (like the first example) and of not repeating the exists function call; however, I believe it does so at the expense of readability:
if (exists ${ ${ $h{a} || {} }{b} || {} }{c}) {
...
}
It works by replacing any level that doesn't exist with a hashref to take the autovivification. These hashrefs will be discarded after the if statement is done executing. Again we see the value of short-circuiting logic.
Of course, all three of these methods makes an assumption about the data the hash is expected to hold, a more robust method includes calls to ref or reftype depending on how you want to treat objects (there is a third option that takes into account classes that overload the hash indexing operator, but I can't remember its name):
if (
exists $h{a} and
ref $h{a} eq ref {} and
exists $h{a} and
ref $h{a}{b} eq ref {} and
exists $h{a}{b}{c}
) {
...
}
In the comments, pst asked if something like myExists($ref,"a","b","c") exists. I am certain there is a module in CPAN that does something like that, but I am not aware of it. There are too many edge cases for me to find that useful, but a simple implementation would be:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
sub safe_exists {
my ($ref, @keys) = @_;
for my $k (@keys) {
return 0 unless ref $ref eq ref {} and exists $ref->{$k};
$ref = $ref->{$k};
}
return 1;
}
my %h = (
a => {
b => {
c => 5,
},
},
);
unless (safe_exists \%h, qw/x y z/) {
print "x/y/z doesn't exist\n";
}
unless (safe_exists \%h, qw/a b c d/) {
print "a/b/c/d doesn't exist\n";
}
if (safe_exists \%h, qw/a b c/) {
print "a/b/c does exist\n";
}
print Dumper \%h;
A:
If you want to turn off autovivification, you can do that lexically with the autovivification pragma:
{
no autovivification;
if( exists $hash{A}{B}{$key} ) { ... }
}
I wrote more about this at The Effective Perler as Turn off autovivification when you don’t want it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Positive cumulative sum of difference
I have a water reservoir with input and output rates. I want to determine when the input is exceeding the output by a certain constant. To accomplish this, I need to cumulatively sum all cases where the inflow exceeds the outflow. Thus, I've written this function:
def pos_diff_cum_sum(flow_in: np.ndarray, flow_out: np.ndarray) -> np.ndarray:
sums = []
cum_sum = 0
diff = list(flow_in - flow_out)
for dd in diff:
cum_sum += dd
if cum_sum < 0:
cum_sum = 0
sums.append(cum_sum)
return np.array(sums)
It sums up the periods where the inflow exceeds the outflow while ignoring periods where the opposite is true. Basically, numpy.cumsum with a corner case.
Tests with plots
t_steps = 9
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(4, 8))
in_flow = np.linspace(1., 0., t_steps)
out_flow = np.linspace(0., 1., t_steps)
ax1.plot(in_flow, label="in")
ax1.plot(out_flow, label="out")
ax1.legend()
pos_diff = pos_diff_cum_sum(in_flow, out_flow)
ax2.plot(pos_diff)
pos_diff
# => array([1. , 1.75, 2.25, 2.5 , 2.5 , 2.25, 1.75, 1. , 0. ])
t_steps = 9
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(4, 8))
in_flow = np.linspace(0., 1., t_steps)
out_flow = np.linspace(1., 0., t_steps)
ax1.plot(in_flow, label="in")
ax1.plot(out_flow, label="out")
ax1.legend()
pos_diff = pos_diff_cum_sum(in_flow, out_flow)
ax2.plot(pos_diff)
pos_diff
# => array([0. , 0. , 0. , 0. , 0. , 0.25, 0.75, 1.5 , 2.5 ])
This code isn't vectorized, but it's going to be called very frequently, so is there some way I should speed it up? Is there any way to make this more elegant?
A:
You can use np.cumsum and np.minimum.accumulate (which I found from this post).
Another way to look at what you want is you want the cumsum.
If the value goes below zero then you want to subtract a value to get it to zero, this value is itself. This means that you just need a running minimum. This is as you've subtracted the value from an earlier value so the effect propagates in your version but not in np.cumsum.
You also want to start this minumum from 0.
def pos_diff_cum_sum(flow_in, flow_out):
delta = np.cumsum(flow_in - flow_out)
return delta - np.minimum.accumulate(np.append([0], delta))[1:]
For reference below.
def fn(in_, out):
delta = np.cumsum(np.array(in_) - np.array(out))
print(delta)
output = delta - np.minimum.accumulate(np.append([0], delta))[1:]
print(np.minimum.accumulate(np.append([0], delta))[1:])
print(output)
If you have an input that only increases then you can just use use np.cumsum:
>>> fn([1, 1, 1, 1, 1], [0, 0, 0, 0, 0])
[1 2 3 4 5]
[0 0 0 0 0]
[1 2 3 4 5]
However if the number goes negative you must subtract all values after it goes negative by that value. This is as the single -= affects the rest of the input in the OP:
>>> fn([1, 0, 0, 0, 0], [0, 1, 1, 0, 0])
[ 1 0 -1 -1 -1]
[ 0 0 -1 -1 -1]
[1 0 0 0 0]
This means you must subtract them even if the value becomes positive again:
>>> fn([1, 0, 0, 1, 1], [0, 1, 1, 0, 0])
[ 1 0 -1 0 1]
[ 0 0 -1 -1 -1]
[1 0 0 1 2]
If more numbers go negative then you have to decrease by these amounts too:
>>> fn([1, 0, 0, 0, 0], [0, 1, 1, 1, 1])
[ 1 0 -1 -2 -3]
[ 0 0 -1 -2 -3]
[1 0 0 0 0]
This allows the value to go positive again if it needs to:
>>> fn([1, 0, 0, 0, 1], [0, 1, 1, 1, 0])
[ 1 0 -1 -2 -1]
[ 0 0 -1 -2 -2]
[1 0 0 0 1]
| {
"pile_set_name": "StackExchange"
} |
Q:
Minus Parameter in expression of report
I have this expression into my report
=Parameters!DimTiempoAnio.Value(0)
When I execute report it returns:
[Dim_Tiempo_].[Anio].&[2016]
I want to minus 1 to 2016 so I just do:
=Parameters!DimTiempoAnio.Value(0) -1
But it throws me an error and it just don´t specify why, can someone help me how can I achieve this?
A:
In not entirely convinced that this is the best way to do it.. but here is one that might work
=replace(Parameters!DimTiempoAnio.Value,right(Parameters!DimTiempoAnio.Value,5),(cstr(cint(left(right(Parameters!DimTiempoAnio.Value, 5),4)) -1)))+"]"
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular JS: IE Error: 10 $digest() iterations reached. Aborting
I'm new to Angular and I'm stuck with a issue relating IE.
Here is the IE Error that I'm getting.
Webpage error details
User Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Timestamp: Thu, 13 Dec 2012 04:00:46 UTC
Message: 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: function $locationWatch() {\n var oldUrl = $browser.url();\n\n if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t defaultPrevented) {\n\t $location.$$parse(oldUrl);\n\t } else {\n\t $browser.url($location.absUrl(), $location.$$replace);\n\t $location.$$replace = false;\n\t afterLocationChange(oldUrl);\n\t }\n\t});\n }\n\n return changeCounter;\n }; newVal: 7; oldVal: 6"],["fn: function $locationWatch() {\n var oldUrl = $browser.url();\n\n if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t defaultPrevented) {\n\t $location.$$parse(oldUrl);\n\t } else {\n\t $browser.url($location.absUrl(), $location.$$replace);\n\t $location.$$replace = false;\n\t afterLocationChange(oldUrl);\n\t }\n\t});\n }\n\n return changeCounter;\n }; newVal: 8; oldVal: 7"],["fn: function $locationWatch() {\n var oldUrl = $browser.url();\n\n if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t defaultPrevented) {\n\t $location.$$parse(oldUrl);\n\t } else {\n\t $browser.url($location.absUrl(), $location.$$replace);\n\t $location.$$replace = false;\n\t afterLocationChange(oldUrl);\n\t }\n\t});\n }\n\n return changeCounter;\n }; newVal: 9; oldVal: 8"],["fn: function $locationWatch() {\n var oldUrl = $browser.url();\n\n if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t defaultPrevented) {\n\t $location.$$parse(oldUrl);\n\t } else {\n\t $browser.url($location.absUrl(), $location.$$replace);\n\t $location.$$replace = false;\n\t afterLocationChange(oldUrl);\n\t }\n\t});\n }\n\n return changeCounter;\n }; newVal: 10; oldVal: 9"],["fn: function $locationWatch() {\n var oldUrl = $browser.url();\n\n if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t defaultPrevented) {\n\t $location.$$parse(oldUrl);\n\t } else {\n\t $browser.url($location.absUrl(), $location.$$replace);\n\t $location.$$replace = false;\n\t afterLocationChange(oldUrl);\n\t }\n\t});\n }\n\n return changeCounter;\n }; newVal: 11; oldVal: 10"]]
Line: 7859
Char: 6
Code: 0
URI: http://localhost:8080/__assets__/lib/angular/angular.js
This is not happening in any other browser but IE 8 and IE 9.
I have a watch looking at a content filtering object which includes a location filter.
My question with this is why doesn't it happen on any other browser but IE and what should I do to get rid of this. Thanks in advance.
A:
Tiago Roldão is definitely right. I had exact the same issue. After debug, I realized in my code I have
location.hash = "#/app/" + id;
which causes the infinitely loop issue. After some research, I found this
$location.path("/apps/" + id);
which solves my issue perfectly.
A:
I had the same issue with error which looked the same. Chrome\FF worked fine, but IE failed. I've clicked on some links in my app and sometimes got this error and sometimes not.
1) In my view I had few links which looked like this:
<a href="#" ng-click="addIP(ip)">Add some IP</a>
2) Click handler for those links added new object into IpRanges collection like this:
$scope.IpRanges.push(ip);
3) Collection itself was binded on view by ng-repeat, and I thought that somehow IE could not handle this situation well - probably order of binding\adding\applying events wasn't incorrect or else... Also after click on links I had # symbol added to url, and sometimes it blinked, and then I've got an error. So I removed href attribute and everything worked fine:
<a href="" ng-click="addCurrentIP()">Add as allowed IP</a>
Probably it's better to use spans or divs for similar situations.
A:
I had the same issue using AngularJS v1.2.13 in IE9, IE10, when calling $window.history.back() (especially in Windows Phone).
It seems the root cause is that $window.history.back() in IE changes the href right before the $locationWatch() is fired hence oldUrl would contain the new Url and that throws off the angular into an infinite $digest.
The immediate work around is to replace the calls to $window.history.back() with the following:
setTimeout(function ()
{
$window.history.back();
}, 0);
| {
"pile_set_name": "StackExchange"
} |
Q:
No decoration on links in CSS
Example page,
Accompanying CSS
Should be a fairly basic issue but for some reason I can't figure it out.
Basically I want the links in my navbar to have no underline or colour change and remain white.
Any idea where I'm going wrong?
A:
It's because you're selecting the main .links element, but not the actual a elements inside. This should do the trick:
.links a {
text-decoration: none;
color: white;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
calling a php function from Javascript same file
Possible Duplicate:
Calling PHP Function within Javascript
I have a small JavaScript code in a php file. This JavaScript code runs some logic and in the end should call a php function which is defined in the same php file. How can I do this ? any guidance ?
A:
you can use ajax for that and call this same file. because php function will not initialize from javascript.
| {
"pile_set_name": "StackExchange"
} |
Q:
symbol lookup error: ./executableName: undefined symbol: _ZN18QXmlDefaultHandlerC2Ev
I am trying to run an executable on Linux Mint 16 x64 that was compiled for Ubuntu 12 x64.
The executable uses Qt 5.1.1 dynamically during runtime. I get the error:
loaded the dummy plugin
loaded the Linux plugin
updating server status
./executableName: symbol lookup error: ./executableName: undefined symbol: _ZN18QXmlDefaultHandlerC2Ev
When I run
ldd executableName | grep "not found"
searching for missing dependencies I get no result; all dynamic dependencies seem to be found, but the undefined symbol error above persists.
Thoughts?
A:
A quick help:
$ echo _ZN18QXmlDefaultHandlerC2Ev|c++filt
QXmlDefaultHandler::QXmlDefaultHandler()
Thus, you don't have a constructor for QXmlDefaultHandler. Googling for that we can found here, that at least Qt-4.8 and Qt-5.3 contains this library.
I think, there is some type of incompatibility between your actual running Qt library and between for which the executable was compiled for. My suggestion were to recompile that executable from source, but on your mint.
It is not impossible, that porting the source package from ubuntu will be a little bit hard for you, in this case I suggest a simple upstream source recompilation (or even binary download, if there is one).
A:
You can't run Ubuntu binaries on Mint like that; binaries are generally not binary-compatible between distributions. Can you find a Mint build? If not, you'll have to build it yourself.
| {
"pile_set_name": "StackExchange"
} |
Q:
MATLAB: Compute mean over a huge array
I need to compute the mean of all columns over a huge array wherby I must replace all numbers that are less than zero with zero in the first place. Using my toy example, it will become obvious that these computation takes quite an amount of time.
tmp = -5 + 10 * rand(5000,100000);
tmp(tmp<0) = 0;
result = mean(tmp);
I am wondering whether there might be a better way in order to gain some speed?
A:
Finding values in arrays and then replacing them is a very expensive operation. Instead, do the following:
% slooooooow
tic
tmp(tmp<0)=0;
mean(tmp);
toc
% faaaaaaaaaast
tic
tmp=max(tmp,0);
mean(tmp);
toc
In my PC , this reports:
Elapsed time is 5.940434 seconds.
Elapsed time is 0.358057 seconds.
Remember that if you expect a single mean value, you should call mean(tmp(:))
| {
"pile_set_name": "StackExchange"
} |
Q:
MockitoJUnitRunner is deprecated
I'm trying to make a unit test with @InjectMocks and @Mock.
@RunWith(MockitoJUnitRunner.class)
public class ProblemDefinitionTest {
@InjectMocks
ProblemDefinition problemDefinition;
@Mock
Matrix matrixMock;
@Test
public void sanityCheck() {
Assert.assertNotNull(problemDefinition);
Assert.assertNotNull(matrixMock);
}
}
When I don't include the @RunWith annotation, the test fails. But
The type MockitoJUnitRunner is deprecated
I'm using Mockito 2.6.9. How should I go about this?
A:
org.mockito.runners.MockitoJUnitRunner is now indeed deprecated, you are supposed to use org.mockito.junit.MockitoJUnitRunner instead. As you can see only the package name has changed, the simple name of the class is still MockitoJUnitRunner.
Excerpt from the javadoc of org.mockito.runners.MockitoJUnitRunner:
Moved to MockitoJUnitRunner, this class will be removed with
Mockito 3
A:
You can try this:
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
Because you add @Before annotation, Your mock objects can be new and recorded many times, and in all test you can give objects new properties. But, if you want one time record behavior for mock object please add @BeforeCLass
A:
There is also a @Rule option:
@Rule
public MockitoRule rule = MockitoJUnit.rule();
Or in Kotlin:
@get:Rule
var rule = MockitoJUnit.rule()
| {
"pile_set_name": "StackExchange"
} |
Q:
Some questions about the performance of PHP Objects
Right now since I am new to using Objects in PHP I feel like in my head, I think of a PHP object as being something big and bulky. This makes me want to use them less often, I feel Like I am taking really simple code and really over-complicating it by putting it into objects.
If I have a database, cache, session, core, and user object and I need to access them pretty much inside of each other and in other non-mentioned classes, I have decided to store all these inside a registry object. So with my limited knowledge of how objects work, it would almost seem to me that by passing a registry object into a simple object is something really big. Like a registry is holding those 5 objects inside of it. Is this wrong? Is the registy really only passing in a reference to where these objects are in memory? Or am I really passing in a really BIG object into all my objects?
Sorry if this makes no sense at all, hopefully it does. I am just trying to get a better understanding of how they work in relation to performance.
A:
In PHP5, all objects are passed by reference by default. In simple terms, a reference simply "points to" the actual object or variable's location in memory (be careful with terminology, as "pointers" are something quite different functionally from PHP's "references", but they are conceptually very similar).
When you pass objects around by reference, you are simply passing around very tiny memory indicators. The objects themselves are not moved... they remain constant in memory, and aren't moved around or rewritten or anything. This includes when you put objects inside other objects... the references are simply adjusted.
The advantages that OO design and programming confer to your code usually far outweigh the minor overhead that comes with managing objects. Rest assured that the PHP interpreter does it's best to optimally manage objects, and you're not incurring any more overhead by passing objects around than you would by passing references to integers or strings. Reference overhead is very minimal.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can gmock mock static methods of Java classes? Alternative?
I could not get it to work. It's like the method is not mocked.
Are there alternative groovy testing frameworks that work better to mock static Java methods?
Update 02/Mar/2011: Adding code:
I am actually trying to mock the Scala XML.loadXml (I am trying Groovy for unit testing) class:
This is my test case:
// ContentManagementGatewayTest.groovy
class ContentManagementGatewayTest extends GMockTestCase
{
void testGetFileList()
{
// Preparing mocks code will go here, see below
play {
GetFileGateway gateway = new GetFileGateway();
gateway.getData();
}
}
}
// GetFileGateway.scala
class GetFileGateway {
def getData()
{
// ...
val xmlData = XML.loadData("file1.txt");
}
}
I tried testing using both gmock and metaClass:
// metaClass:
XML.metaClass.'static'.loadFile = {file ->
return "test"
}
// gmock:
def xmlMock = mock(XML)
xmlMock.static.loadFile().returns(stream.getText())
A:
You can do this using Groovy (metaprogramming), you don't need any additional libraries. Here's a (stupid) example, that overrides Collections.max such that it always returns 42. Run this code in the Groovy console to test it.
// Replace the max method with one that always returns 42
Collections.metaClass.static.max = {Collection coll ->
return 42
}
// Test it out, if the replacement has been successful, the assertion will pass
def list = [1, 2, 3]
assert 42 == Collections.max(list)
Update
You mentioned in a comment that my suggestion didn't work. Here's another example that corresponds to the code you've shown in your question. I've tested it in the Groovy console and it works for me. If it doesn't work for you, tell me how your testing differs from mine.
Math.metaClass.static.random = {-> 0.5}
assert 0.5 == Math.random()
A:
Scala doesn't have static methods, so it is no wonder you couldn't mock one -- it doesn't exist.
The method loadXml to which you refer is found on the XML object. You can get that object from Java with scala.XML$.MODULE$, but, since objects are singleton, its class is final.
Alas, loadXML is defined on the class XMLLoader, which the object XML extends, not on the object XML itself. So you can simply do a normal mock of XMLLoader. It will lack a few methods, but perhaps it will do all you need.
| {
"pile_set_name": "StackExchange"
} |
Q:
problems instantiating a root in a Binary tree
I have a problem. I have made the following program because I wanted to create a binary tree node, have the instantiater create a bunch of tree nodes, and then have the counter count the nodes and the leaves. My problem is this: I keep getting a null pointer exception when I invoke BTNode(null,null,null). Further: I have to put null in for those values, the node by definition points to other nodes, and when you instantiate the root there's no other nodes for the right and left to point to, so it has to be null. This, for some reason, completely screws with java, and it throws a null pointer exception. Why: I have no clue, I never even reference those values before declaring new BTNodes and assigning them as left and right. Furthermore, it doesn't even get past the constructor!
Please help!
public class binarytree {
static int nodeCounter=0;
static int leafCounter=0;
public static class BTNode{
char c;
BTNode left;
BTNode right;
public BTNode(Character d, BTNode left1, BTNode right1){
c=d;left=left1;right=right1;}
}
public static void Instantiator(BTNode root){
int counter=10;
Instantiator1(root,counter);
}
public static void Instantiator1(BTNode root,int counter){
if (counter<=0){
return;}
BTNode a=new BTNode(null,null,null);
BTNode b=new BTNode(null,null,null);
root.left=a;
root.right=b;
counter--;
Instantiator1(a,counter);
Instantiator1(b,counter);
}
public static int Testleaf(BTNode n){
if(n.left==null && n.right==null)
return 1;
else return 0;
}
public static int Testnode(BTNode n){
if(!(n.left==null && n.right==null))
return 1;
else return 0;
}
public static void printNodesandLeaves(BTNode root){
counter(root);
System.out.println("Nodes are"+nodeCounter);
System.out.println("leaves are"+leafCounter);
}
public static void counter(BTNode r){
nodeCounter+=Testnode(r);
leafCounter+=Testleaf(r);
if (!(r.left==null))
counter(r.left);
if (!(r.right==null))
counter(r.right);}
public static void main(String[] args){
BTNode root=new BTNode(null,null,null);
Instantiator(root);
printNodesandLeaves(root);
}}
A:
You are getting a NullPointerException when auto-unboxing (Character) null to a char.
Your constructor
public BTNode(Character d, BTNode left1, BTNode right1){
c=d;left=left1;right=right1;
}
takes a Character and assigns it to
char c;
this is technically legal because of autoboxing but when d is null it is equivalent to
c = ((Character) null).charValue()
which results in a NullPointerException.
You shouldn't use Character unnecessarily, so I would rework the calls to the constructor to
BTNode((char) 0, null, null)
and changes the signature of BTNode to take a char instead of a Character, but you could also change c=d; to
c = d != null ? d.charValue() : (char) 0;
| {
"pile_set_name": "StackExchange"
} |
Q:
"Similarity" of two vectors
Imagine I have three vectors
v1 = [1,1]
v2 = [.9,.9]
v3 = [.1,.1]
I want to see how closely related two vectors are in both Magnitude and Direction
So consider a hypothetical "similarity" function
sim(v1,v2) > sim(v1,v3).
sim(a,b) will return a value from 0 to 1
I figure i need to weight the importance for both Magnitude and Direction, so for now consider that both Magnitude and Direction are weighted equally.
What would a good approach to this problem be?
A:
The usual approach to measure dissimilarity is to use a norm of the difference. For example, if we use the Euclidean norm, we have
$$
\lVert v_1-v_2\lVert=\sqrt{(1-0.9)^2+(1-0.9)^2}=0.1\sqrt{2}
$$
and
$$
\lVert v_1-v_3\lVert=\sqrt{(1-0.1)^2+(1-0.1)^2}=0.9\sqrt{2},
$$
and since $\lVert v_1-v_3\lVert>\lVert v_1-v_2\lVert$ we see that $v_1$ is more dissimilar to $v_3$ than to $v_2$.
Now, if you want to have a measure of similarity instead, and have this value lie between zero and one, you could for instance consider exponentials $e^{-\lVert v_1-v_2\lVert}$ and $e^{-\lVert v_1-v_3\lVert}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android - customized keyboard key and action
If you own Android phone you are no doubt have noticed how in the certain apps the keyboard layout can change from the standard issue to digits-only or to have .com or .net special buttons based on the text field input type (e.g. phone number). So I have 2 questions:
how to trigger this customization? I suspect it has to do with EditText format
Can this be taken even further if I want to add some custom buttons to inject a specific pattern? Say I would have an AND button which when pressed will add all uppercase " AND " surrounded by spaces to the text field. Can this be done?
What I'm not asking is how to capture some key combination in onKeyPress event and then populate text field with a pattern - I pretty much know how to do that already.
A:
It is controlled by the android:inputType XML attribute (or the setInputType() method).
For info on the available options see the pages for the XML attribute or the object's method.
As an example, the following XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:text="example text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone" />
</LinearLayout>
will give you this layout:
whereas changing the inputType to textEmailAddress will give you this:
You can customize the "action" button as explained here, but I don't believe there's any way to do full customization of keyboards at this time, but I could be wrong.
| {
"pile_set_name": "StackExchange"
} |
Q:
Funding opportunities for non-european people going to Europe for a PhD in TCS
There are two chinese students who would like to come to Spain to pursue a PhD in TCS in our group. I know of course the funding possibilities in my country but wonder if you know any European and non-European and Chinese funding calls or opportunities for doing PhD.
An extension of this questions; is it there around any funding/grant stack exchange site or which ones do you use to track grants?
A:
Never having worked or studied in Spain, I can not really help with local information. However, as I mentioned in the comments, the most obvious source for such funding in European universities (aside from internal university or departmental sources and local research councils) would be funding from the European Research Council. The ERC has many different kinds of grants, including training networks and personal grants, which can often be used to fund overseas students from. Additionally, the European Commission offers funding for postgraduates and postdocs via Marie Curie actions.
Further, there is the China Scholarship Council which also offers support for students wishing to study abroad.
Then there are the industry scholarships: Google, IBM, Microsoft, etc.
If either of the students is female, then there are more options (see Google's Anita Borg scholarship, etc.).
Lastly, many European countries have bilateral agreements with China or Chinese institutions which may be another potential source of funding.
A:
Recently, a new Sino-Danish institute was announced, Center for the Theory of Interactive Computation(CTIC). From what I've read, I got the impression that Chinese students are welcome to visit Denmark for their PhD and vice versa.
You will probably be aware of the Erasmus Programme, however I am not sure if Chinese students can apply to it directly, they can certainly do once they join a European university as students and spend a seimester visiting another university.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to subfilter a jquery object which is a subset of $(this)
I've read the documentation over and over and I can't get why this doesn't work:
From inside a function, calling the following:
alert($(this).parent().parent().html());
returns something looking like this:
<div class="something1">
<div class="whereThisStarted">stuff</div>
</div>
<div class="something2">stuff</div>
<div class="somethingSpecial">stuff</div>
<div class="something4">stuff</div>
I want to get "somethingSpecial". It would seem to me that either of the following should work but they both return null.
alert($(this).parent().parent().children(".somethingSpecial").html());
alert($(this).parent().parent().filter("div.somethingSpecial").html());
What's wrong with this?
Thanks
A:
if you really must do it the way you want and not how TStamper showed, try this:
alert($(this).parent().parent().find("div.somethingSpecial").html());
| {
"pile_set_name": "StackExchange"
} |
Q:
numpy package not defined when importing function from another .py file
In my master file I have:
import matplotlib.pyplot as plt
import seaborn
import numpy as np
import time
import sys
sys.path.append("C:/.../python check/createsplit")
import createsplit
data='MJexample'
X,Y,N,Ntr=create_training_data(data)
where I am calling create_training_data function from createsplit.py file which is:
import numpy as np
import scipy.io
def create_training_data(data_type):
"""
creates training data
"""
if data_type=='MJexample':
N=300
Ntr = 150
X=np.linspace(0,1,N)
X = np.array([X,X*X,np.linspace(5,10,N),np.sin(X),np.cos(X),np.sin(X)*np.cos(X)]).T
fac=40
Y=np.array([np.sin(fac*x)*np.cos(fac*x**2) for x in X[:,0]])[:,None]
_X=X
_Y=Y
return _X,_Y,N,Ntr
However running my original file results in error: NameError: global name 'np' is not defined for some reason I do not understand. I assume I am importing the functions in a wrong way but I don't really understand what would be wrong.
A:
I think this issue raises just because of a wrong call of the function. Try
X, Y, N, Ntr = createsplit.create_training_data(data)
instead, and it should work.
| {
"pile_set_name": "StackExchange"
} |
Q:
SparkSQL split using Regex
I'm trying to split a line into an array using a regular expression.
My line contains an apache log and I'm looking to split using sql.
I tried split and array function, but nothing.
Select split('10.10.10.10 - - [08/Sep/2015:00:00:03 +0000] "GET /index.html HTTP/1.1" 206 - - "Apache-HttpClient" -', '^([^ ]+) ([^ ]+) ([^ ]+) \[([^\]]+)\] "([^"]+)" \d+ - - "([^"]+)".*')
;
I'm expecting an array with 6 elements
Thanks
A:
SPLIT function, as you can guess, splits string on a pattern. Since pattern string you provide matches a whole input there is nothing to return. Hence an empty array.
import org.apache.spark.sql.functions.{regexp_extract, array}
val pattern = """^([^ ]+) ([^ ]+) ([^ ]+) \[([^\]]+)\] "([^"]+)" \d+ - - "([^"]+)".*"""
val df = sc.parallelize(Seq((
1L, """10.10.10.10 - - [08/Sep/2015:00:00:03 +0000] "GET /index.html HTTP/1.1" 206 - - "Apache-HttpClient" -"""
))).toDF("id", "log")
What you need here is regex_extract:
val exprs = (1 to 6).map(i => regexp_extract($"log", pattern, i).alias(s"_$i"))
df.select(exprs:_*).show
// +-----------+---+---+--------------------+--------------------+-----------------+
// | _1| _2| _3| _4| _5| _6|
// +-----------+---+---+--------------------+--------------------+-----------------+
// |10.10.10.10| -| -|08/Sep/2015:00:00...|GET /index.html H...|Apache-HttpClient|
// +-----------+---+---+--------------------+--------------------+-----------------+
or for example an UDF:
val extractFromLog = udf({
val ip = new Regex(pattern)
(s: String) => s match {
// Lets ignore some fields for simplicity
case ip(ip, _, _, ts, request, client) =>
Some(Array(ip, ts, request, client))
case _ => None
}
})
df.select(extractFromLog($"log"))
| {
"pile_set_name": "StackExchange"
} |
Q:
angular watch object not in scope
I have a service in which values can change from outside Angular:
angularApp.service('WebSocketService', function() {
var serviceAlarms = [];
var iteration = 0;
this.renderMessages = function(alarms, socket) {
if (! angular.equals(serviceAlarms, alarms)) {
serviceAlarms = alarms;
iteration++;
}
};
this.getAlarms = function () {
return serviceAlarms;
};
this.iteration = function () {
return iteration;
};
this.socket = initSocketIO(this);
});
The initSocketIO function makes callbacks to this services renderMessages() function and serviceAlarms variable gets changed on a steady basis.
Now i am trying to watch for changes in this service like so:
controllers.controller('overviewController', ['$scope', 'WebSocketService', function ($scope, WebSocketService) {
$scope.$watch(
function () {
return WebSocketService.iteration();
},
function(newValue, oldValue) {
$scope.alarms = WebSocketService.getAlarms();
},
true
);
}]);
to no avail. The second function provided to $watch never gets executed except on controller initialization.
I have tried with and without true as third parameter.
A:
You should use $rootScope.$watch (not $scope.$watch)
| {
"pile_set_name": "StackExchange"
} |
Q:
Given C is a code of length n. Containing M code-words with a distance d
I'm studying for my exam and came across this question below.
I don't understand how to get $d$. I get $C$ is a code of length $n$.
Containing $M$ code-words with a distance $d$.
$(n,M,d)$
But how do I get $d$ below?
Give one (5,4,d) code in … as below …
Z^(5) base 2.
C={
0,0,0,1,0
0,1,1,0,1
1,0,1,1,0
1,1,0,1,1
}
A:
The distance of the code word is the minimum number of bit flips that transforms one codeword into another. It's just the minimum of all possible hamming distances between the codes.
Also you can define the weight of a codeword to be the distance from the zero vector.
For your code it looks like $d = 2$.
| {
"pile_set_name": "StackExchange"
} |
Q:
File Open Dialog Box With Password
I am using below codes but there another password 456 also to be tried on fail. Can you please guide how to do that.
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xls", 1
.Show
fullpath = .SelectedItems.Item(1)
End With
If InStr(fullpath, ".xls") = 0 Then
Exit Sub
End If
Workbooks.Open fullpath, ReadOnly:=False, Password:="123"
Rows("2:" & Rows.Count).ClearContents
Range("A2").Select
End Sub```
A:
Test if the first password try was successful, if not try the other password.
Dim OpenWb As Workbook
On Error Resume Next 'if Workbooks.Open errors hide these messages
Set OpenWb = Workbooks.Open(fullpath, ReadOnly:=False, Password:="123")
If OpenWb Is Nothing Then 'if first faild try second
Set OpenWb = Workbooks.Open(fullpath, ReadOnly:=False, Password:="456")
End If
On Error Goto 0 'always re-enable error reporting!
If OpenWb Is Nothing Then
MsgBox "Both passwords were wrong"
Exit Sub 'cancel here
Else
With OpenWb.Worksheets(1)
.Rows("2:" & .Rows.Count).ClearContents
.Range("A2").Select
End With
End If
| {
"pile_set_name": "StackExchange"
} |
Q:
c++11: what is its gc interface, and how to implement?
I was watching Bjarne Stroustrup's talk "The Essence of C++".
In 44:26 he mentioned "C++11 specifies a GC Interface".
May I ask what is the interface, and how to implement it?
Any more detailed good introduction online, or some sample codes to demonstrate it pls?
A:
Stroustrup extends this discussion in his C++ FAQ, the thing is that GC usage is optional, library vendors are free to implement one or not :
Garbage collection (automatic recycling of unreferenced regions of
memory) is optional in C++; that is, a garbage collector is not a
compulsory part of an implementation. However, C++11 provides a
definition of what a GC can do if one is used and an ABI (Application
Binary Interface) to help control its actions.
The rules for pointers and lifetimes are expressed in terms of "safely
derived pointer" (3.7.4.3); roughly: "pointer to something allocated
by new or to a sub-object thereof."
to ordinary mortals: [...]
The functions in the C++ standard supporting this (the "interface" to which Stroustrup is referring to) are :
std::declare_reachable
std::undeclare_reachable
std::declare_no_pointers
std::undeclare_no_pointers
These functions are presented in the N2670 proposal :
Its purpose is to support both garbage collected implementations and
reachability-based leak detectors. This is done by giving undefined
behavior to programs that "hide a pointer" by, for example, xor-ing it
with another value, and then later turn it back into an ordinary
pointer and dereference it. Such programs may currently produce
incorrect results with conservative garbage collectors, since an
object referenced only by such a "hidden pointer" may be prematurely
collected. For the same reason, reachability-based leak detectors may
erroneously report that such programs leak memory.
Either your implementation supports "strict pointer safety" in which case implementing a GC is possible, or it has a "relaxed pointer safety" (by default), in which case it is not. You can determine that by looking at the result of std::get_pointer_safety(), if available.
I don't know of any actual standard C++ GC implementation, but at least the standard is preparing the ground for it to happen.
A:
In addition to the good answer by quantdev, which I've upvoted, I wanted to provide a little more information here (which would not fit in a comment).
Here is a C++11 conforming program which demonstrates whether or not an implementation supports the GC interface:
#include <iostream>
#include <memory>
int
main()
{
#ifdef __STDCPP_STRICT_POINTER_SAFETY__
std::cout << __STDCPP_STRICT_POINTER_SAFETY__ << '\n';
#endif
switch (std::get_pointer_safety())
{
case std::pointer_safety::relaxed:
std::cout << "relaxed\n";
break;
case std::pointer_safety::preferred:
std::cout << "preferred\n";
break;
case std::pointer_safety::strict:
std::cout << "strict\n";
break;
}
}
An output of:
relaxed
means that the implementation has a trivial implementation which does nothing at all.
libc++ outputs:
relaxed
VS-2015 outputs:
relaxed
gcc 5.0 outputs:
prog.cc: In function 'int main()':
prog.cc:10:13: error: 'get_pointer_safety' is not a member of 'std'
switch (std::get_pointer_safety())
^
| {
"pile_set_name": "StackExchange"
} |
Q:
with using enter key from the key Board instead of the mouse click using java
i'm trying to make enter key react instead of the mouse click.
i have no idea how to do that using java.
here is the code and the output.
import java.util.Random;
import javax.swing.*;
import java.util.Arrays;
import java.text.DecimalFormat;
import java.awt.event.*;
import java.awt.*;
public class PayRate extends JFrame
{
private JPanel panel;
private JLabel rateLabel;
private JLabel hoursLabel;
private JLabel payLabel;
private JTextField rateTextField;
private JTextField hoursTextField;
private JTextField payTextField;
private JButton calcButton;
private JButton clearButton;
private final int WINDOW_WIDTH = 350;
private final int WINDOW_HEIGHT = 160;
public PayRate()
{
setTitle("PAY RATE");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel()
{
rateLabel = new JLabel("RATE");
hoursLabel = new JLabel("HOUR");
payLabel = new JLabel("");
rateTextField = new JTextField(8);
hoursTextField = new JTextField(8);
payTextField = new JTextField(27);
calcButton = new JButton("CALCULATE PAY");
clearButton = new JButton(" CLEAR ");
calcButton.addActionListener(new CalcButtonListener());
clearButton.addActionListener(new clearButtonListener());
getRootPane().setDefaultButton(calcButton); // make the enter key react instead of mouse click
//calcButton.setMnemonic(KeyEvent.VK_E); // make (ALT + E) response as an enter key
panel = new JPanel();
payTextField.setBackground(Color.ORANGE);
rateTextField.setBackground(Color.LIGHT_GRAY); // Set the Background of rateTextField to LIGHT_GRAY
hoursTextField.setBackground(Color.LIGHT_GRAY);// Set the Background of hoursTextField to LIGHT_GRAY
calcButton.setBackground(Color.GREEN); // Set the background of CalcButton to GREEN
rateLabel.setForeground(Color.BLUE); // set the Foreground of rate label to blue
hoursLabel.setForeground(Color.BLUE); // set the Foreground of hours label to blue
payLabel.setForeground(Color.BLUE); // set the Foreground of pay label to blue
panel.setBackground(Color.PINK);// Set the background of the panel to yellow
panel.add(rateLabel); // Add rate label to the panel
panel.add(rateTextField); // add rate text field to the panel
panel.add(hoursLabel); // add hour label to the panel
panel.add(hoursTextField); // add hours text field to the panel
panel.add(calcButton); // add calculate button to the panel
panel.add(payLabel); // add the pay label to the panel
panel.add(payTextField); // add pay text field to the panel
panel.add(clearButton);
}
private class CalcButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double rt ;
String input;
String display ="";
String output = " Your total pay for this week is: ";
double hrs;
double sum = 0;
DecimalFormat formatter = new DecimalFormat("#0.00");
input = rateTextField.getText();
rt = Double.parseDouble(input);
input = hoursTextField.getText();
hrs = Double.parseDouble(input);
sum = hrs * rt;
display = display + output.toUpperCase() + formatter.format(sum);
payTextField.setText(display);
}
}
private class clearButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
payTextField.setText("");
hoursTextField.setText("");
rateTextField.setText("");
}
}
public static void main(String[] args)
{
new PayRate();
}
}
Here is the output.
I Want the the calculate pay button to react to enter key instead of clicking on it using the mouse.
Thank You in advance.
A:
Option 1: make the JButton of interest the default button for your JFrame's JRootPane:
calcButton = new JButton("CALCULATE PAY");
calcButton.addActionListener(new CalcButtonListener());
getRootPane().setDefaultButton(calcButton); // **** add this line ****
Option 2: add the same ActionListener to your JTextFields:
CalcButtonListener calcListener = new CalcButtonListener();
calcButton.addActionListener(calcListener);
rateTextField.addActionListener(calcListener);
payTextField.addActionListener(calcListener);
Edit
You ask in comment:
what if i want another key (such as space key) to react as the enter key? is that possible?
Answer:
A JButton is already wired to respond to space key press if the button has the focus. Otherwise, 1) set the button's mnemonic to respond to an alt-key combination, or 2) use key bindings to bind the button to any key or key combination.
An example of a mnemonic:
calcButton.setMnemonic(KeyEvent.VK_C);
If you add this to your program, you'll see that the first "C" in the button's text is underlined. Your button will also respond to alt-c presses.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set BindingExpression.Status to Active programmatically?
I am transfering FrameworkElement from StackPanel on WPF Page to programmatically created StackPanel. At a certain point I need to refresh bindings and get property values.
At this point FrameworkElement.DataContext has correct value and BindingExpression.Status==BindingStatus.Unattached for all binding expressions. I execute BindingExpression.UpdateTarget, but property values are empty.
I found source code for BindingExpression.UpdateTarget():
public override void UpdateTarget()
{
if (Status == BindingStatus.Detached)
throw new InvalidOperationException(SR.Get(SRID.BindingExpressionIsDetached));
if (Worker != null)
{
Worker.RefreshValue(); // calls TransferValue
}
}
Worker gets instance in internal override void BindingExpression.Activate(). Also inside Activate() BindingExpression.Status set to BindingStatus.Active.
How can I programmatically initiate execution for BindingExpression.Activate() and make UpdateTarget after that?
Update
Solution here (thanks, Olli):
public void UpdateAllBindingTargets( DependencyObject obj)
{
FrameworkElement visualBlock = obj as FrameworkElement;
if (visualBlock==null)
return;
if (visualBlock.DataContext==null)
return;
Object objDataContext = visualBlock.DataContext;
IEnumerable<KeyValuePair<DependencyProperty, BindingExpression>> allElementBinding = GetAllBindings(obj);
foreach (KeyValuePair<DependencyProperty, BindingExpression> bindingInfo in allElementBinding)
{
BindingOperations.ClearBinding(obj, bindingInfo.Key);
Binding myBinding = new Binding(bindingInfo.Value.ParentBinding.Path.Path);
myBinding.Source = objDataContext;
visualBlock.SetBinding(bindingInfo.Key, myBinding);
BindingOperations.GetBindingExpression(visualBlock, bindingInfo.Key).UpdateTarget();
}
}
where getting all bindings for object:
public IEnumerable<KeyValuePair<DependencyProperty, BindingExpression>> GetAllBindings( DependencyObject obj)
{
var stack = new Stack<DependencyObject>();
stack.Push(obj);
while (stack.Count > 0)
{
var cur = stack.Pop();
var lve = cur.GetLocalValueEnumerator();
while (lve.MoveNext())
if (BindingOperations.IsDataBound(cur, lve.Current.Property))
{
KeyValuePair<DependencyProperty,BindingExpression> result=new KeyValuePair<DependencyProperty, BindingExpression>(lve.Current.Property,lve.Current.Value as BindingExpression);
yield return result;
}
int count = VisualTreeHelper.GetChildrenCount(cur);
for (int i = 0; i < count; ++i)
{
var child = VisualTreeHelper.GetChild(cur, i);
if (child is FrameworkElement)
stack.Push(child);
}
}
}
A:
You can programmatically create a new binding, which should do the trick.
http://msdn.microsoft.com/en-us/library/ms752347.aspx#creating_a_binding
Example from the MSDN page
MyData myDataObject = new MyData(DateTime.Now);
Binding myBinding = new Binding("MyDataProperty");
myBinding.Source = myDataObject;
myText.SetBinding(TextBlock.TextProperty, myBinding);
| {
"pile_set_name": "StackExchange"
} |
Q:
Compress a three digit number into a single number
If I have a three digit number like 293 Is there a method to compress it into one digit. Can any three digit number be rewritten into a single digit with some formula and then back to its original form?
A:
No, assuming by three digit number you mean $100\leq n\leq 999$, then there are $999-100+1=900$ three digit numbers. But there are only $10$ single digit numbers (the integers $0$ through $9$). Since sets with different cardinalities can not have a bijection between them, there is no invertible function which maps three digit numbers to single digit numbers.
Of course, if you do not need the map to be invertible, then there are any number of functions you can use. For example
$$f(x)=\left\lfloor\frac{x}{100}\right\rfloor$$
simply maps every three digit number to its first digit (i.e. $f(293)=2$).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to identify dynamic listview row separately to identify which row has been clicked
I am fiddling with a google map tutorial where I have a map populated dynamically with markers of values from a database using JSON. As well as this I have a listview also dynamically populated with the names of each marker from the same database. I am trying to pan to the location of the marker's lat and lon when the the name of the store in the listview is selected.
Eg. The user selects McDonalds in the listview. They are then panned to the McDonald's marker location on the map.
I imagine that the id from each row in the listview should somehow be used to match the lat and lon values in the array and then used the map.panTo() function of the store's lat and long. I am a novice with JSON so unsure of how to do this as it's all dynamic and it's all stuck in a loop.
jQuery for the dynamic listview is posted below.
JS
var file = "getsome.php";
$.post(file, function(data) {
var output = '';
$.each(data, function(index, value){
output += '<li><a href="#" id='+ value.site_id +'" class="latlon">' + value.site_name + '</a></li>';
}); $('#listview-id').html(output).listview().listview('refresh'); }, "json");
getsome.php
require("dbconnect.php");
try {
$DBH = new PDO("mysql:host=$server;dbname=$database;charset=utf8", $username, $password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$STH = $DBH->prepare("SELECT * FROM Site WHERE 1");
$STH->execute();
$result = $STH->fetchAll();
echo json_encode($result);
A:
You can use this method. In the example i grab some data from the Listview item using (closest). While you dynamically populate the listview items you can insert data attributes -- data-whatever="the data" -- eg (data-address="10 maple Street" data-lat="45.6789" data-lng="56.6786") etc
Demo
http://jsfiddle.net/g5tvj3xp/
<ul data-role="listview" id="listview">
<li data-id="row1">Row 1</li>
<li data-id="row2">Row 2</li>
<li data-id="row3">Row 3</li>
<li data-id="row4">Row 4</li>
</ul>
$("#listview").on("click", ">li", function(event, ui) {
var id = $(this).closest("li").attr('data-id');
alert(id)
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Browser Choice with Automation Test in Python
Initially I have def setup() with options to call specific web browsers from another file that have all the information on how to setup the web browser. Remarking out the browser not used.
def setUp(self):
# Choose the Web Browser to test with
operabrowser(self)
# chromebrowser(self)
...
def test_one()
...
def test_two()
...
I am trying to move away from editing the test file each time, I am looking to setup a console input that will call the browser and I have added to def setup().
browser_choice = input ( """Choose your browser
Opera, [Firefox], Chrome or Safari
> """ ).lower ()
if browser_choice == 'opera':
operabrowser()
else chromebrowser()
This works with a single unit test but if there is more than one test in the file it asks each time for a browser choice.
How can I get this option to be asked only once for all tests that will be ran in the test file? I have tried a few other ways of approaching this all unsuccessful.
A:
Tests should be defined as class methods, in your code they appears to be standalone functions not directly related with the class which holds the setUp() method. You just need to modify your code like this:
import unittest
class YouTests(unittest.TestCase):
def setUp(self):
q = 'Choose your browser Opera, [Firefox], Chrome or Safari >'
browser_choice = input (q).lower ()
if browser_choice == 'opera':
operabrowser()
else:
chromebrowser()
def test_one(self):
pass
def test_two(self):
pass
...
If you have multiple classes inheriting from unittest.TestCase and all should use the same browser the browser choice will be best inserted in your global scope. For example:
browser_object = None
...
def operabrowser():
global browser_object
# Init opera object here
def chromebrowser():
global browser_object
# Init chrome object here
...
# Your tests using the browser_object
...
if __name__ == '__main__':
q = 'Choose your browser Opera, [Firefox], Chrome or Safari >'
browser_choice = input (q).lower ()
if browser_choice == 'opera':
operabrowser()
elif browser_choice == 'firefox':
...
else:
chromebrowser()
unittest.main()
| {
"pile_set_name": "StackExchange"
} |
Q:
What are pros and cons of empirical Bayesian methods?
The empirical Bayesian method is a new concept to me. It raises my interest, because it offers a different philosophical and methodological perspective of statistical analysis.
From my limited knowledge, I am not sure if it is useful/powerful, or inferior to alternative methods, and if it is worth learning (and to what degree) compared to learning other useful topics in Bayesian analysis?
How do you think about it?
What are pros and cons of empirical Bayesian methods?
A:
So we are clear, the idea is that I have data $Y \sim f(Y \mid \theta)$ and have a prior $\theta \sim \pi(\theta \mid \eta)$. Then the joint is
$$
J(Y, \theta \mid \eta) = f(Y\mid \theta)\pi(\theta\mid \eta)
$$
and the marginal of $Y$ is
$$
m(Y\mid\eta)=\int f(Y\mid\theta) \pi(\theta\mid\eta) \ d\theta.
$$
The empirical Bayes approach, rather than specifying the value of $\eta$ or placing a prior on $\eta$, estimates
$$
\hat \eta = \arg \max_\eta m(Y\mid \eta).
$$
Then, we draw inferences about $\theta$ from the "posterior" $\pi(\theta \mid Y, \hat \eta)$.
This describes parametric empirical Bayes. Maybe someone else can describe the situation for nonparametric empirical Bayes; I haven't dealt with it personally. The primary alternative to EB is to place a prior on $\eta$.
Some Pros
The procedure is, in principle, automatic. No work need to be done in eliciting a prior on $\eta$. Contrast this with choosing $\eta$ according to your prior knowledge about $\theta$, or using a hyperprior $\eta \sim \lambda(\eta \mid \gamma)$ (which will require specifying a value of $\gamma$). Subjectivity is always creeping in with these alternative approaches.
In practice, it can be very annoying to have to specify a prior. It can cause a lot of work on the part of the scientist. Empirical Bayes can shift the workload to the computer.
Related to 1., I've found that this can provide some stabilization of our results. Normally I would try to place a prior on $\eta$, but if my prior is too vague or out of line with the data, I find you can get some strange results. I'm more likely to get a sane answer with empirical Bayes. (Note: This is my personal experience with the models I've worked with; it is easy to imagine EB overfitting for the same reason ML results in overfitting).
Some Cons
It is not always easy to implement. What you can get away with in implementation depends on what problem you are looking at - if you are in an ML setting and are doing some variational approximation for inference you can often do some approximate EB, but if you are doing MCMC it can be quite difficult to implement in a computationally attractive way. Under MCMC you can try to fake things with a stochastic search algorithm, but as far as I know the theory behind this hasn't really been done.
By plugging in fixed point estimate $\hat \eta$ in place of $\eta$ and drawing inference from $\pi(\theta \mid Y, \hat \eta)$ as though we had specified $\hat \eta$ from the beginning, we are neglecting our uncertainty about $\eta$. There are ways to try to fix this, but mostly people just hope that it doesn't make a big difference. But if it really didn't make a difference, why not just put a hyperprior on $\eta$? This is especially suspect because the amount of information in the data about $\eta$ is often quite small.
It isn't clear what exactly we are doing from a statistical perspective. It isn't really Bayesian; at best, it is an approximation to Bayesian analysis. Hypothetically, if there was a prior on $\eta$ and it was tightly concentrated, then EB would be an approximation to fully Bayesian inference, but this typically isn't the case. So what the heck is this procedure doing? It seems to me that if I'm using this I'm usually either being a fake Bayesian or I have some reason to believe that the frequentist properties of the method are good. The principled Bayesian approach would be to put a prior on $\eta$, and this can work better in practice.
Hope that helps. I actually like EB quite a bit as a method for finding procedures and evaluating them according to their frequentist properties when I'm wearing my statistics hat. It gives frequentists a nice tool for constructing methods with "sharing of information" in hierarchical models. Occasionally the properties of EB estimators are provably good (e.g. the Stein shrinkage estimator can be derived from an EB standpoint). In ML, of course, you often just don't really care where procedures come from and just use whatever works.
| {
"pile_set_name": "StackExchange"
} |
Q:
angularJS directive not immediately honoring ng-show/ng-hide
I have the following section of HTML in an angularJS application. The <div/> tag for appointment-list is showing a listing of appointments. This directive is basically just a table.
<div ng-show="loading">Loading...</div>
<div ng-show="!loading && (appointments.length == 0)">No Appointments Found</div>
<div ng-hide="loading || (appointments.length == 0)">Test123</div>
<div ng-hide="loading || (appointments.length == 0)" appointment-list source="appointments" appointment-selected="appointmentSelected(appointment)"></div>
I then have the following in my controller. I am setting a loading variable while things are in-flight, and then I also filter the appointments on the page according to text in a text box.
$scope.$watch('selectedDate', function(newVal, oldVal) {
if (newVal) {
$scope.loading = true;
Appointment.query({year: newVal.getYear()+1900, month: newVal.getMonth()+1, day: newVal.getDate()}, function(data) {
$scope.allAppointments = data;
$scope.appointments = $scope.filterAppointments();
$scope.loading = false;
});
}
});
My issue is that the hiding of the div for my custom directive isn't happening properly. The table should be disappearing exactly along with the "Test123" string and its not. When I go from a selected date with the table populated to a date with nothing on there, the "Test123" will be replace with the loading (therefor its being hidden, and loading being shown) but the table remains until after the loading process is complete at which point the table will disappear
Can someone explain why the delay? Why is the directive not responding exactly like the div above it?
Edit
Here is a plnkr which shows the issue: http://plnkr.co/edit/khxQuaM6sxTx5RszvowX?p=preview
Basically click on the buttons at the top to load the two datasets. I have a timeout in there to simulate some of the think time on the server. Whenever you see "Loading..." the div for the appointmentList table should not be shown since ng-hide will evaluate to true because loading is true, yet is doesn't disappear.
A:
You need to use $parent to access the model loading since the directive appointmentList creates an isolated scope. Make the following change to the last div containing the table and you will achieve the effect you want.
<div ng-hide="$parent.loading || (appointments.length == 0)" appointment-list source="appointments" ... ></div>
You don't need to use $parent to refer to appointments, since you pass this model to the directive. But there is no harm to add $parent like $parent.appointments.length == 0, since you have appointments defined anyway in the parent scope.
Btw, you should also set appointments to be empty in the watcher like this
if (newVal) {
$scope.loading = true;
$scope.appointments = []; //add this
to make the condition appointments.length == 0 useful.
| {
"pile_set_name": "StackExchange"
} |
Q:
Elasticsearch dsl deleting error
I have a problem with deleting items using elasticsearch dsl. When i trying to filter my data it goes easily and something like this works great.
def searchId(fileId):
s = Search().filter('term', fileId=fileId)
# for hit in s:
# print(str(hit.foreignKey))
response=s.execute()
# print(response.hits.total)
return response
Scanning works also :
def scanning():
s = Search()
i = 0
for hit in s.scan():
if hit.domain == 'Messages':
i+=1
print(str(hit.fileId) + " : " + str(hit.domain) + " : " + str(i))
But when i wanna to delete items like this :
def deleteId(fileId):
s = Search().query('match', fileId=fileId)
response = s.delete()
return "Done"
I got an error :
Traceback (most recent call last):
File "", line 1, in
File "/home/o.solop/DataSearchEngine/datasearch/elasticapp/search.py", line 96, in deleteId
response = s.delete()
File "/usr/local/lib/python2.7/dist-packages/elasticsearch_dsl/search.py", line 660, in delete
**self._params
File "/usr/local/lib/python2.7/dist-packages/elasticsearch/client/utils.py", line 73, in _wrapped
return func(*args, params=params, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/elasticsearch/client/__init__.py", line 887, in delete_by_query
raise ValueError("Empty value passed for a required argument.")
ValueError: Empty value passed for a required argument.
A:
I missed an index in the Search constructor. I should do something like:
def deleteId(fileId):
s = Search(index='my_index_name').query('match', fileId=fileId)
response = s.delete()
Elasticsearch-dsl uses the delete_by_query API, as indicated in my error message, which needs to know which index to perform the delete against.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make confirm dialog box after button click
What I'm trying to do is make a confirm dialog box popup when I press to create an item in my view. From what I understand from reading other posts (correct me if I'm wrong) is by using jquery. I'm not very familiar with jquery/javascript so I'm doing my best to understand what I'm doing. The code i found online is this.
<form method="post">
<input id="Create" name="Common" type="submit" value="Create" />
<script type="text/javascript">
$(document).ready(function () {
$("#Create").click(function (e) {
// use whatever confirm box you want here
if (!window.confirm("Are you sure?")) {
e.preventDefault();
}
});
});
How it is right now every time I press the button it fires my POST create method in my controller right away without showing a dialog box. Can someone explain me why that happens and how i can fix it. I have tried adding code where //use whatever confirm box you want here is written but I don't really know what I'm looking for or what it needs to be written there.
Posts i have read
Where i got the above code from
Delete ActionLink with confirm dialog
ASP.NET MVC ActionLink and post method
A:
One way is to use <input type="button" />. Then call submit() for the form.
<form method="post" id="sampleform">
<input id="Create" name="Common" type="button" value="Create" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#Create").click(function (e) {
if (confirm("Are you sure?")) {
console.log('Form is submitting');
$("#sampleform").submit();
} else {
console.log('User clicked no.');
}
});
});
</script>
</form>
If you use ASP.NET MVC, you might want to consider using Html.BeginForm Html Helper.
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { Id = "sampleform"}))
{
<input id="Create" name="Common" type="button" value="Create" />
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script type="text/javascript">
... Same as above
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
dc: how do I pop (and discard) the top number of the stack?
In dc, how do I pop and discard a number from the top of the stack? A stack with three items (1 2 3) should become a stack with two items (2 3). Currently I'm shoving the number onto another stack (Sz) but that seems rather lame.
A:
There are numerous ways to delete the top of the stack but they have side effects. Removing an element without side effects requires you to avoid included side effects.
To remove the top of the stack without a side effect, ensure that the top is a number and then run d!=z. If the stack had [5], this does the following
Start with item to remove. Stack: [5]
Duplicate top of stack. Stack: [5,5]
Pop top 2 and test if they are not equal: 5 != 5 Stack: []
If test passed (which it can't), run z Stack: []
To ensure that the top of stack is a number, I use Z which will calculate the length of a string or the number of digits in a number and push that back. There are other options such as X. Anything that makes a number out of anything will work so that it will be compatible with !=.
So the full answer for copy pasting in all situations is the following:
Zd!=r
I usually stick this in register D (for Drop):
[Zd!=r]sD
and then I can run
lDx
| {
"pile_set_name": "StackExchange"
} |
Q:
Node.js Custom Middleware Using An Object Of Functions
In Express.js, ihave been having problems with making my own middleware. I know that middleware is supposed to be a function, but can the middleware function be inside an array.
For Example:
module.js:
module.exports = {
function1: function(req, res) {
console.log('function1');
//second edit.
I want to return something as well
return 'hello world';
//if i add next(); it wont call the next();
},
function2: function(req, res) {
console.log('function2');
}
}
app.js:
const express = require('express')
, middleware = require('./module')
, app = express();
app.use(middleware.function1);
app.use(middleware.function2);
app.get('/', (req, res) => {
//this is an edit: i want to use some code here like
res.send('Hello World');
middleware.function1();
});
app.listen(8080);
When i Do This, the webpage just doesn't load. Any Help?
A:
You are missing crucial part next function (which is callback to trigger next middleware in the sequence) in defining middleware functions function1 and function2.
Have you seen https://expressjs.com/en/guide/writing-middleware.html ?
In below code, you are not passing req, res to the middleware function.
app.get('/', (req, res) => {
middleware.function1();
});
OR call it directly as below
app.get('/', middleware.function1);
| {
"pile_set_name": "StackExchange"
} |
Q:
How get odd chars from String in C#
I am new to C#. My problem is to take odd chars from a string and get a new string from those odds.
string name = "Filip"; // expected output ="Flp"
I don't want to take, for example,
string result = name.Substring(0, 1) + name.Substring(2, 1) + ... etc.
I need a function for this operation.
A:
Try Linq (you actually want even characters since string is zero-based):
string name = "Filip";
string result = string.Concat(name.Where((c, i) => i % 2 == 0));
In case of good old loop implementation, I suggest building the string with a help of StringBuilder:
StringBuilder sb = new StringBuilder(name.Length / 2 + 1);
for (int i = 0; i < name.Length; i += 2)
sb.Append(name[i]);
string result = sb.ToString();
| {
"pile_set_name": "StackExchange"
} |
Q:
Как сделать так чтобы display: table-cell был адаптивным
Привет всем, дорогие друзья.
Предо мной стоит интересная задача, мне необходимо сделать адаптивность, прописываю max-width для каждого отдельного контейнера, и задаю максим width:100%,
у меня значит <div id="left"> и <div id="right">каждый поделен CSS свойствами на display: table-cell, и если использую display:block то весь, контейнер становится не красивым и не адаптивным.
Как мне быть ?
A:
При отсутствии (на данный момент) кода в вопросе можно ответить только так:
Чтобы сохранялась адаптивность при использовании display: table-cell , у родительского элемента должен стоять display: table.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using django-discover-runner without database
I'm trying to use django-discover-runner to test my app. It's basically a WebService frontend, so it doesn't include a database, and, apparently, django-discover-runner doesn't like that.
Looking in other questions, I've seen that with plain Django, I should inherit from DjangoTestSuiteRunner and set settings.TEST_RUNNER. It works fine. But django-discover-runner uses its own discover_runner.DiscoverRunner class, so I tried this:
from discover_runner import DiscoverRunner
class DBLessTestRunner(DiscoverRunner):
def setup_databases(self):
pass
def teardown_databases(self, *args):
pass
But it doesn't work. I get this error message:
ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
Any idea how to get django-discover-runner working without a DataBase?
A:
In Django 1.6 the standard Django TestCase inherits from TransactionTestCase which attempts to access the database.
To fix the problem in your test class inherit from SimpleTestCase rather then TestCase:
from django.test import SimpleTestCase
class TestViews(SimpleTestCase):
...
You should now be able to run your tests with out setting up the database.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get the previous element of a LinkedHashMap
I need to get the previous element of a LinkedHashMap.
I tried using the ListIterator because it has the previous() method. But the problem is ListIterator needs a List not a set.
ListIterator<Entry<String, Integer>> it = (ListIterator<Entry<String, Integer>>) unitsItems.entrySet().iterator();
I have to transform my entrySet into a list. So I tried this :
List entryList= new ArrayList (unitsItems.entrySet());
ListIterator<Entry<String, Integer>> it = (ListIterator<Entry<String, Integer>>) entryList.iterator();
I got this error:
java.util.ArrayList$Itr cannot be cast to java.util.ListIterator
Can anyone tell me the correct way to transform the set to a list and then use it in ListIterator?
Thank you.
A:
As per request: Since you already have the list entryList you just need to call listIterator() on it to get what you want.
Btw, I'd add the generic type to the list as well: List<Entry<String, Integer>> = new ArrayList<>(unitsItems.entrySet());
| {
"pile_set_name": "StackExchange"
} |
Q:
Overlapping maps
I have two maps that are exactly the same, except of different sizes (the maps are proportional). I place the smaller of the two maps onto the larger, both face up so that the smaller map is completely within the borders of the larger map.
Is there always an overlapping point corresponding to the same geographic place on both maps? Can you show why or why not?
A:
Yes. Here's a simple proof.
The smaller map defines a region within the larger map. You can draw that region on the smaller map too. That region you've just drawn is a smaller version of the map. In this smaller version of map you can draw that same region again, which is an even smaller version of the map. You can repeat this ad infinitum, creating smaller and smaller drawings, until the drawing is infinitely small, i.e. the size of a single point. That point is in the same location on every version of the map, so in particular it is the same point on the two largest maps.
It is essentially the Droste Effect, of an image containing itself.
A:
Yes.
This is a special case of Brouwer's fixed point theorem:
Every continuous function from a convex compact subset K of a Euclidean space to K itself has a fixed point.
The function sending one of your maps to the other is a simple isometry - an enlargement, combined with whatever rotations or translations are described by your positioning of the smaller map on the larger one - so it's definitely continuous. And the maps are presumably rectangular, or at least homeomorphic to closed discs, and therefore convex and compact. Thus, by BFPT there is a fixed point: a point which is in the same place on both maps.
Incidentally, this result can be used to show that if you have a map of a place in the place itself, then there must be a point which has the same location on the map and in real life - in other words, it must be possible to put a You Are Here sign on the map.
| {
"pile_set_name": "StackExchange"
} |
Q:
UPDATE and SELECT from same table in one query
I am trying to count the rows from table1, and depending the rows count to update a certain column. Below is the query I have tried, but am getting an arror saying that temp is not a table.
UPDATE table1 AS t1
INNER JOIN table1 AS temp ON temp.id = t1.id
SET
t1.field1 = (CASE
WHEN (SELECT COUNT(*) FROM temp WHERE temp.field1 = 1) < 100 THEN 1
WHEN (SELECT COUNT(*) FROM temp WHERE temp.field1 = 2) < 100 THEN 2
WHEN (SELECT COUNT(*) FROM temp WHERE temp.field1 = 3) < 100 THEN 3
WHEN (SELECT COUNT(*) FROM temp WHERE temp.field1 = 4) < 100 THEN 4
WHEN (SELECT COUNT(*) FROM temp WHERE temp.field1 = 5) < 100 THEN 5
END)
WHERE t1.id IN(100, 200, 300); --Example data
A:
A couple things:
I would suggest making a temp table of the data in your case
statement, then joining that for an update.
Joining back on the table you're updating does not work.
You have a syntax error in your where clause. You don't need that
equals sign before IN.
Try:
DROP TABLE IF EXISTS temp_table1;
CREATE TEMPORARY TABLE temp_table1 AS
SELECT field1,count(*) as field_count FROM table1 group by field1;
UPDATE table1 AS t1
LEFT JOIN temp_table1 aa
ON aa.field1= t1.field1
SET t1.field1 = (CASE
WHEN aa.field1 = 1 AND aa.field_count < 100 THEN 1
WHEN aa.field1 = 2 AND aa.field_count < 100 THEN 2
WHEN aa.field1 = 3 AND aa.field_count < 100 THEN 3
WHEN aa.field1 = 4 AND aa.field_count < 100 THEN 4
WHEN aa.field1 = 5 AND aa.field_count < 100 THEN 5 END)
WHERE t1.id IN (100, 200, 300);
| {
"pile_set_name": "StackExchange"
} |
Q:
Resteasy. Class def not found
I'm building rest-client with resteasy and wildfly.
According to stacktrace probably I've got problems with dependecies.
Already done many tries regarding changes scopes, deleting or adding dependencies in pom.xml doesn't give any result except another stacktrace with something not found...
Here is my
stacktrace
Exception in thread "main" java.lang.NoClassDefFoundError: javax/ws/rs/core/GenericType
at groupId.Main.<init>(Main.java:33)
at groupId.Main.main(Main.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: javax.ws.rs.core.GenericType
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
and
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
JBoss, Home of Professional Open Source
Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
contributors by the @authors tag. See the copyright.txt in the
distribution for a full listing of individual contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>restClient</artifactId>
<groupId>groupId</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>rest-client</artifactId>
<packaging>war</packaging>
<name>restClient: WAR Module</name>
<url>http://wildfly.org</url>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<distribution>repo</distribution>
<url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
</license>
</licenses>
<dependencies>
<!-- Dependency on the EJB module so we can use it's services if needed -->
<!--<!– https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxrs –>-->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.1.2.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxrs -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.1.2.Final</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-multipart-provider -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>
<version>3.1.2.Final</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxb-provider -->
<!--<dependency>-->
<!--<groupId>org.jboss.resteasy</groupId>-->
<!--<artifactId>resteasy-jaxb-provider</artifactId>-->
<!--<version>3.1.2.Final</version>-->
<!--<scope>provided</scope>-->
<!--</dependency>-->
<!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxrs -->
<!-- https://mvnrepository.com/artifact/javax.ejb/ejb-api -->
<!-- Import the CDI API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the JSF API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.faces</groupId>
<artifactId>jboss-jsf-api_2.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.ejb/ejb-api -->
<dependency>
<groupId>javax.ejb</groupId>
<artifactId>ejb-api</artifactId>
<version>3.0</version>
</dependency>
<!-- Import the JPA API, we use provided scope as the API is included in JBoss WildFly -->
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<!--<dependency>-->
<!--<groupId>org.postgresql</groupId>-->
<!--<artifactId>postgresql</artifactId>-->
<!--<version>42.1.0</version>-->
<!--</dependency>-->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.jaxrs/jackson-jaxrs-json-provider -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.9.0.pr3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.jaxrs/jackson-jaxrs-xml-provider -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-xml-provider</artifactId>
<version>2.9.0.pr3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<!-- Java EE 7 doesn't require web.xml, Maven needs to catch up! -->
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
A:
According to the stacktrace, you're running a main method in IntelliJ.
All your RESTEasy dependencies are marked as 'provided'. This means the appliation expects the runtime container (e.g. an application server) to provide them. IntelliJ will not provide these dependencies at runtime itself and therefore you're getting the ClassNotFoundException error.
https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html
provided
This is much like compile, but indicates you expect the JDK
or a container to provide the dependency at runtime. For example, when
building a web application for the Java Enterprise Edition, you would
set the dependency on the Servlet API and related Java EE APIs to
scope provided because the web container provides those classes. This
scope is only available on the compilation and test classpath, and is
not transitive.
To test the application in IntelliJ, simply remove the provided scopes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which of phantomjs or webdriver would be easier/more-appropriate for scraping my linkedin account?
I have a personal need to scrape/automate-access-to my linkedin account (copy my contacts, etc), and obviously the site is too ajaxy to just use wget, urllib, etc.
I cannot use the LinkedIn API, as it happens to restrict some use cases I'm interested in.
I am proficient in Python and Javascript. I've used webdriver in the past for small scraping projects, but it was long ago enough that there's probably a similar overhead in re-learning it vs learning phantomjs.
I am not planning to run any kind of high-volume cluster-based scraping operation, this is all going to be running on my local machine at some appropriate rate limit so as not to piss off linkedin. It's mostly just for personal convenience, automation, etc.
I've heard good things about phantomjs, but I'd like to understand what if any advantage it has over webdriver (or vice versa). I guess phantomjs is "headless", meaning it doesn't actually have to run a browser, which I guess makes it easier to write command line scripts or consume fewer resources or some other property that I would love to have explained to me!
I can appreciate the argument that webscraping programs should be javascript, since that's more of a browser-native language, but would love to hear if that's a primary reason why people are using phantomjs (or one of its cousins)
A:
I've used both Selenium and Phantom/Casper in scraping jobs, and also used both in functional testing jobs. If I was going to do what you describe I would choose CasperJS. I would choose CasperJS over PhantomJS because:
Easier to describe the flow of steps. (You have to deal with all the async callbacks when using PhantomJS directly.)
SlimerJS can be swapped in to have it use Gecko (i.e. Firefox), with no additional effort. (I don't think this will matter with LinkedIn, but PhantomJS 1.9.x is based on a fairly old WebKit, so when sites use newer HTML5 features it can sometimes fail.)
Reasons to choose CasperJS over Selenium:
The flow of steps is quite easy to describe in CasperJS.
Selenium feels more like hard work. This might be because PHP is my preferred glue language, and since Selenium 2.0, PHP has been treated as an outsider. But also it has the philosophy of only allowing actions that a user could do in the browser with keyboard and mouse. This is sometimes not flexible enough.
Selenium breaks each time Firefox gets updated, and I have to install the latest version. Irritating. (PhantomJS and SlimerJS have their browser internally, so are cleanly independent of system updates to your desktop browser.)
As you are proficient in both Python and JavaScript, I would say none of the above are killer reasons. It doesn't really matter which you choose, the effort is going to be roughly the same.
| {
"pile_set_name": "StackExchange"
} |
Q:
Flattening Streams produced from multiple JDBC ResultSets, to prevent loading everything in memory
I am given List[String], that I need to group in chunks. For each chunk, I need to run a query (JDBC) that returns a List[String] as a result.
What I'm trying to get to is:
All the results from the different chunks concatenated in one flat list
The final flat list to be a non-strict collection (so as not to load the whole ResultSet in memory)
This is what I've done:
Producing a Stream from a ResultSet, given a List[String] (this is the chunk):
def resultOfChunk(chunk: List[String])(statement: Statement): Stream[String] = {
//..
val resultSet = statement.executeQuery(query)
new Iterator[String] {
def hasNext = resultSet.next()
def next() = resultSet.getString(1)
}.toStream
}
Producing the final list:
val initialList: List[String] = //..
val connection = //..
val statement = connection.createStatement
val streams = for {
chunk <- initialList.grouped(10)
stream = resultOfChunk(chunk)(statement)
} yield stream
val finalList = streams.flatten
statement.close()
connection.close()
(Variable names are intended to prove the concept).
It appears to work, but I'm a bit nervous about:
producing an Iterator[Stream] with a for-comprehension. Is this
something people do?
flattening said Iterator[Stream] (can I assume they do not get evaluated during
the flattening?).
is there any way I can use the final List after I close the connection and statement?
Say, if I need to do operations that last a long time and do not want to keep the connection open during this, what are my options?
does this code actually prevent loading the whole DB ResultSet into memory at once (which was my actual goal) ?
A:
I'll reply one by one:
Sure, why not. You might want to consider flattening in the for-comprehension directly for readability.
val finalList = for {
chunk <- initialList.grouped(10)
result <- resultOfChunk(chunk)(statement)
} yield result
See above for flattening. Yes you can assume they will not get evaluated.
The Iterator cannot be re-used (assuming initialList.grouped(10) gives you an iterator). But you can use a Stream instead of an Iterator and then, yes you can, but:
you will have to make sure it is fully evaluated before you close the connection
this will store all the data in memory
Yes it does
Based on what I've seen, I'd recommend you the following:
val finalList = for {
chunk <- initialList.grouped(10).toStream
result <- resultOfChunk(chunk)(statement)
} yield result
This will give you a Stream[String] that is evaluated as needed (when accessed in sequence). Once it is fully evaluated you may close the database connection and still use it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Question about Android View
First off I'm new to owning an android and trying to develop android apps. I've noticed that sometimes in applications and in the local android apps that sometimes when you a long press or sometimes just tap a menu comes up. This menu isn't like a context menu bc there is no title. Just a white list of options, and in others it seems to be completely custom but once again no Black Bar title on top of it. If anyone knows the name of this view could you let me know. Thanks
A:
You are right ContextMenus are shown on long presses only. Everything else you saw is either a Dialog or a custom view. You define menus like described in the android developer articles:
http://developer.android.com/guide/topics/ui/menus.html
If you want to completely customize some sort of menu you could also just use a Dialog and add every view element you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Autofac to create a factory that can return different SQL engines
I am trying to refactor an existing solution (didn't write it) to use DI and Autofac, and have run into a bit of a problem. The solution in question supports a number of SQL database types (MSSQL, MySQL, PostgreSQL, potentially more.), and the user can have a number of databases of various kinds connected in the app (ie. they may have both an MSSQL and PostgreSQL DB connected). When a DB is connected to the app the type is stored in an enum. When actions are taken on the DBs in question it currently uses the following static factory to return a Datalayer:
public static class DatabaseFactoryController
{
public static IDatalayer GetDatalayer(ConnType databaseType)
{
switch (databaseType)
{
case ConnType.Mssql:
return new MssqlModel());
case ConnType.Postgre:
return new PostgreModel());
case ConnType.MySql:
return new MysqlModel());
default:
throw new ArgumentOutOfRangeException(nameof(databaseType));
}
}
}
Now the problem is that other controllers in the code need to have the proper datalayer injected for the DB the user is currently accessing like eg:
public class SizeController : IDataController
{
private readonly IDatalayer _datalayer;
public SizeController(IDatalayer datalayer)
{
_datalayer = datalayer;
}
public Response<SizeInfo> GetData(IRequest request)
{
<actions taken here using datalayer>
}
}
But how can I wire up Autofac to dynamically inject the right datalayer in the controllers, for the DB chosen for any given call (instantiation of the controller) without going to a ServiceLocator. I'm pretty sure it has to be possible but I'm pretty new to Autofac so maybe that's why I can't seem to make it work based on the documentation. I've tried following this: https://benedict-chan.github.io/blog/2014/08/13/resolving-implementations-at-runtime-in-autofac/
builder.RegisterType<MssqlDatalayer>()
.As<IDatalayer>().Keyed<IDatalayer>(ConnType.Mssql);
builder.RegisterType<PostgreDatalayer>()
.As<IDatalayer>().Keyed<IDatalayer>(ConnType.Postgre);
builder.Register<Func<ConnType, IDatalayer>>(c =>
{
var componentContext = c.Resolve<IComponentContext>();
return (roleName) =>
{
var dataService = componentContext.ResolveKeyed<IDatalayer>(roleName);
return dataService;
};
});
builder.RegisterType<SizeController>().As<IDataController>()
but in that implementation I fail to see how I pick the implementation to inject into the constructor at runtime. Maybe I'm missing something massively obvious, or maybe I need to fundamentally refactor the code. Any input will be valued as I've been stuck on this problem for a while now.
A:
As it shown in the article you used
public class SizeController : IDataController
{
private readonly IDatalayer _datalayer;
public SizeController(Func<ConnType, IDatalayer> dataLayerFactory)
{
_datalayer = dataLayerFactory(ConnType.Mssql);
}
public Response<SizeInfo> GetData(IRequest request)
{
//<actions taken here using datalayer>
_datalayer.SomeIDatalayerMethod();
}
}
Or you can use another one approach
| {
"pile_set_name": "StackExchange"
} |
Q:
extjs - Roweditor not working
I have a gridPanel defined as follows:
Ext.define('Mb.view.winbiz.ExportGrid', {
extend: 'Ext.grid.Panel',
store: 'winbiz.Exports',
plugins: [{ptype: 'rowediting', clicksToMoveEditor: 2, autoCancel: false}],
columns: [
{text: 'Id', dataIndex: 'id'},
{
text: 'Description',
dataIndex: 'description',
flex:1,
editor: {
xtype: 'textfield',
allowBlank: false
}
}
]
});
I have this problem with the rowEditing plugin:
Instead of editing the line on which I double-click, a new row is inserted at the top of the grid, but it does not show the editor fields.
I looked everywhere in the code and compared to a working example based on the doc, but I cannot find what is not correct.
This is how it looks like:
A:
The reason the rowEditor did not work was the following:
I have a custom template. The css needed for the rowEditiong plugin to work was not included.
Once I rebuilt the application with sencha app build the css file was updated and everything worked fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
PGAdmin3 hidden object types
I have scoured the web and PGSQL docs for information on what, to me, is a hidden data type, but have come up short. I am working on an existing database that has functions with return types with preceding double underscores (__some_type). In PGAdmin3, you can optionally display types in your tree view, there I see some recognizable types that are used in various functions and what not, but nowhere do I see these other types. I learned, through PyCharm Full edition, I can connect to a PostgreSQL DB and see all of the types I mention. As well as in the console with "\dT", but not in PGAdmin itself.
Question: What is the deal with types that are preceded with one or two underscores? (__some_type).
Followup: I did find an unverified source describe a convention that restricts users from creating types that start with an underscore, but have not confirmed this from PG sources.
Here is the link to that: https://momjian.us/main/writings/pgsql/aw_pgsql_book/node223.html
And the line I mention is all the way towards the bottom under "NOTES":
Type names cannot begin with the underscore character ("_") and can
only be 31 characters long. This is because Postgres silently creates
an array type for each base type with a name consisting of the base
type's name prepended with an underscore.
Continued searching results:
I have found references to what I speak of, but it does not go into detail about the behavior of such types, or what happens if users violate this 'restriction'.
PG Source from 6.3 docs:
As discussed earlier, Postgres fully supports arrays of base types.
Additionally, Postgres supports arrays of user-defined types as well.
When you define a type, Postgres automatically provides support for
arrays of that type. For historical reasons, the array type has the
same name as the user-defined type with the underscore character _
prepended. Composite types do not need any function defined on them,
since the system already understands what they look like inside.
6.4 Docs on Create Type:
Restrictions
Type names cannot begin with the underscore character ("_") and can
only be 15 characters long. This is because Postgres silently creates
an array type for each base type with a name consisting of the base
type's name prepended with an underscore.
A:
The restriction on underscores in type names no longer applies. Judging by the docs, it was dropped between 8.2 and 8.3.
The fact that these types don't show up in pgAdmin3 looks like a bug. As you can see from the source, it filters out any type with a leading underscore. It's trying to suppress the auto-generated array types, but the query predates release 8.3 (back when this was still a reliable approach), and was never updated to use the new pg_type.typarray column.
Not sure if this issue is present in pgAdmin4. If you want to stick with pgAdmin3, BigSQL are still maintaining a fork, so they're probably your best bet if you want to see this fixed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if a list is part of another list while preserving the list sequence
How to check if a list in python is part of another list with preserving the order. Example:
a = [3, 4, 1, 2, 5]
b = [4, 1, 2]
Answer is True
a = [3, 4, 1, 0, 2, 5]
b = [4, 1, 2]
Answer is False as the order is not matched
A:
This can be solved using python lists equality, comparing the sublists at all positions:
is_b_sublist_of_a = any(b == a[i:i+len(b)] for i in range(len(a)))
The expression a[i:i+len(b)] creates a list at the length of b starting from the ith position. This expression is computed for all positions in a. If any of the comparisons return True, the any expression will be True as well, and False otherwise.
| {
"pile_set_name": "StackExchange"
} |
Q:
Filters collection unavailable on *some* versions of IE9
I've created a Windows Sidebar Gadget which uses the filters collection on HTMLElements, so that I can show transition effects (between photos... the gadget is a photo viewer).
With the latest version of IE9 however, I've discovered that in some cases, the filters collection is not available; and throws an error when access to it is attempted.
Originally, I put this down to some weird problem with IE9 being in Standards mode instead of Quirks by default (as in IE9, Microsoft retired the style.filter property in favour of style.opacity in an attempt to be standards compliant with opacity), however after further debugging, this isn't the case.
In all the following tests, the results came back the same for both gadgets that were throwing errors, and gadgets that weren't:
document.documentMode is 5
document.compatMode is BackCompat
typeof some_html_element.style.filter is string
typeof some_html_element.style.MsFilter is undefined
However, the following test gave different results:
typeof some_html_element.filters is object in unbroken gadgets
typeof some_html_element.filters is unknown in broken gadgets
A selection of useragent strings of broken gadgets are below:
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; BRI/1; .NET CLR 1.1.4322; .NET4.0C)
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; Tablet PC 2.0)
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MATP; InfoPath.2; FunWebProducts; .NET4.0C; yie9)
A selection of useragent strings of working gadgets are below:
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; yie9)
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; MALN; InfoPath.2; .NET4.0C)
Unfortunately, the problem is baffling me so much, I can't even reproduce it on my development machine; so I haven't really got much more information to go on.
Anyone experienced anything like this before/ have any idea what could be causing it?
To ensure I'm making my question(s) clear:
Has anyone experienced this before/ have any idea what could be causing it?
Does anyone know any other variables I could report to the server to try diagnose the cause of the problem futher?
Bounty Edit: Can anyone download the gadget, reproduce the problem, and post detailed information on their Windows Environment (OS version, updates installed), and their IE configuration (version, plugins installed)?
If the gadget is broken, upon clicking any status icon (loading spinner, error icon) displayed in the top left of the gadget whilst hovering over it, you'll see an error saying "Several problems (most noticeably disabled transitions) were introduced when installing Internet Explorer 9. We are actively working on a fix.". You'll notice there aren't any transition effects between photo changes (and several users have reported the title/author/play back control bar has no opacity either).
N.B: Needless to say, cross compatability is not an issue for me. I need the gadget to run in IE7, 8 and 9 and that's it (Windows Sidebar uses a mangled version of the copy of IE installed behind the scenes).
A:
I downloaded the gadget and see no problems. I see the transitions (dissolve) and control bar transparency is also there.
My user agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
I'm running Win7 x64 SP1, IE9 32bit. I do not have many addons, just a few including Shockwave, Kaspersky AV Broswer helpers, MS Office cache handler, WIndows Live Sign In helper.
Based on the broken user agents, the problem seems to be in some variants of IE7. Also if you look at the last one, there is this FunWebProducts in it which tells me that there are other components on the system (addons/activex maybe) which could be interfering.
Not sure but I would suspect windows updates to be a culprit too.
It is hard to say exactly what is causing this issue, but here's few pointers:
IE 7, 8 have problems displaying some png images correctly (alpha channel issues mainly). A workaround to handle this gracefully is this check: if (!/MSIE (5\.5|6|7|8)/.test(navigator.userAgent) || typeof filters == 'unknown') return; which can probably help you in general too.
Does it break on specific images on the broken systems?
Does it break when IE has no addons?
Is anything being logged in Event Logs?
Does the broken system has latest updates?
If possible, use AppSight's Blackbox on one the broken systems. This will give you tons of info as to what is going on in the system. When everything else fails, this program is godsend (from my own personal experience).
Except for the last bullet, everything else are vague pointers. If you can, use Blackbox. Pretty sure you'll be able to find what's causing the issue.
It definitely looks like the code is not the culprit, but a combination of factors/components on those systems that are causing this.
| {
"pile_set_name": "StackExchange"
} |
Q:
how enable SNMP on all Computer remotely?
I need to find the easiest way to install snmp on all computers?
we have Windows Server 2003 with 160 Client.
A:
This answer assumes you want to enable SNMP on either XP or 2003. The Windows source directory, i386, needs to be configured correctly for this to work.
Create a file titled "snmp.txt" that contains the following:
[NetOptionalComponents]
SNMP=1
Run the following command to install the SNMP feature:
sysocmgr.exe /i:%WINDIR%\inf\sysoc.inf /u:"%PATH_TO_FILE%\snmp.txt"
This can be performed remotely via Computer Logon script or with a tool such as psexec.
You can use Group Policy to configure the SNMP settings. In gpmc.msc look under Computer Configuration, Administrative Templates, Network, SNMP to see the available options.
How to add or remove Windows Components by using Sysocmgr.exe
Configure the SNMP Service
| {
"pile_set_name": "StackExchange"
} |
Q:
how to force method to be implemented in concrete subclass from trait
I have a method in my trait
def controller: AnyRef
but my concrete class was not implementing that method and it was still compiling. The compiler doesn't let me add abstract to that method either. How can I create a method in a trait that forces it's implementer to implement it?
thanks,
Dean
A:
The compiler enforces that concrete classes implement all the abstracts methods they inherit from superclasses and traits.
If your class was compiling it meant it wasn't concrete, i.e. it was a trait or an abstract class, and you can't force neither to implement the abstract method.
Of course, as soon as you try to obtain a concrete instance the compiler will raise an error as the method is not implemented.
Practical example in the REPL
scala> trait A { def controller: AnyRef }
defined trait A
scala> trait B extends A
defined trait B
scala> abstract class C extends A
defined class C
scala> class D extends A
<console>:8: error: class D needs to be abstract, since method controller in trait A of type => AnyRef is not defined
class D extends A
scala> new B { }
<console>:10: error: object creation impossible, since method controller in trait A of type => AnyRef is not defined
new B { }
^
scala> new C
<console>:10: error: class C is abstract; cannot be instantiated
new C
| {
"pile_set_name": "StackExchange"
} |
Q:
How to implement HttpMessageHandler in Web API?
In an ASP.NET 4.5 MVC 4 Web API project, I want to add a custom HttpMessageHandler. I've changed WebApiConfig class (in \App_Satrt\WebApiConfig.cs), as follows:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: new MyCustomizedHttpMessageHandler()
);
}
}
Then I developed MyCustomizedHttpMessageHandler:
public class MyCustomizedHttpMessageHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IPrincipal principal = new GenericPrincipal(
new GenericIdentity("myuser"), new string[] { "myrole" });
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
return Task<HttpResponseMessage>.Factory.StartNew(() => request.CreateResponse());
}
}
However, the request to the API (let's say http://mylocalhost.com/api/values), always returns status code 200, without any data. I mean it never gets to ValuesController.cs's 'GET()' method.
What have I missed? How can I implement HttpMessageHandler properly?
PS: Have already read this one: https://stackoverflow.com/a/12030785/538387 , doesn't help me.
A:
Here you are creating a HttpMessageHandler which short circuits the request and doesn't let the request pass through the rest of the pipeline. Instead, you should create a DelegatingHandler.
Also there are 2 kinds of message handler pipelines in Web API. One is a regular pipeline in which all requests for all routes pass through and other where one could have message handlers specific to certain routes only.
Try to create a DelegatingHandler and add it to your HttpConfiguration's list of message handlers:
config.MessageHandlers.Add(new HandlerA())
If you want to add a route specific message handler, then you could do the following:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler:
HttpClientFactory.CreatePipeline(
new HttpControllerDispatcher(config),
new DelegatingHandler[]{new HandlerA()})
);
This Web Api Poster shows the pipeline flow.
A:
To write a custom message handler, you should derive from System.Net.Http.DelegatingHandler
class CustomMessageHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage>
SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IPrincipal principal = new GenericPrincipal(
new GenericIdentity("myuser"), new string[] { "myrole" });
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
return base.SendAsync(request, cancellationToken);
}
}
And call base.SendAsync to send the request to the inner handler.
| {
"pile_set_name": "StackExchange"
} |
Q:
Low Search: find channel entries with relationships to it?
I have a Products channel and an Images channel. The Images has a relationship field to Products (basically: a product can have 0 or more images).
Since most of my products do not have images, I'd like to showcase the products with images over the products without images. Meaning, I'd like to create a page that lists only the products that do have images, random order, and allow users to paginate through them.
In Low Search, is there a way to get a list of products that have images?
Products without images will still be viewable by doing a full text search or getting a list of entries based on the EE category they are associated with.
A:
One way that's currently possible, is to use a SQL Parameter to query the entry IDs that have a relationship. The other would be to create a custom filter.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the purpose of the lab in The Divide?
What exactly happens at the laboratory in The Divide (2011)? Who are the guys at the laboratory and what do they try to achieve?
A:
It doesn't look like it explains the lab
After time passes the shelter's door is broken open and the shelter is
invaded by armed soldiers in biohazard suits; the men's speech is
unintelligible and their allegiance remains ambiguous.
After exploring the lab, Josh runs back into the shelter after being identified at which point the door is welded shut. This leads me to believe that the lab was setup there for some other purpose other than the occupants of the shelter and may have originally burst in because they intended to occupy it for themselves but after finding resistance they retreated, but not without first taking a test subject.
Josh's outfit allows him to explore the lab where he discovers several
unconscious children—including Wendi—in stasis units; their hair
shaved off and their eyes bandaged.
Being in a post-apocalyptic setting, it's possible that the lab was setup to prevent contamination and the children may have been shaved to get rid of radioactive contamination and placed in the stasis tanks to be protected or cleansed.
Or, the lab was setup to perform experiments on people and that's why suits broke into the shelter to begin with. Who knows. But with the reaction to Josh when they see he isn't supposed to be there, they were either there to do harm or he was just mad about his buddies getting attacked in the previous encounter with the shelter inhabitants.
If you examine the final scene after Eva escapes, she finds the city in ruin. So it doesn't seem as if the lab was actually there for malicious purposes or containment (like in Quarantine).
However, the real reason is not revealed to us and is just there to add an element of terror and explain why they just can't walk out the door. It has even less significance when you consider that once the door was welded shut, the lab and suits were forgotten.
There is a lot of ambiguity and confusion as to the purpose of the lab which suggests it wasn't meant to be explained as part of the story line.
| {
"pile_set_name": "StackExchange"
} |
Q:
How could I get a variety of outputs from a shell script?
I'm not sure how to word it (I'm having one of those moments where I forget everything), but I'd like to create a script where it gives me every word possible made up from characters.
For example, if I wanted a variety of "spaces", I could input (s|S)/(p|P)/(A|a|4)/(C|c)/(e|3|E|ε)/(s|S|5|$) into the script, and in return get an output like this:
...
sP4C3s
SpaCe5
spACεS
Sp4C3$
...
So on, so forth. How could I create that?
(Tried searching for this by the way, but couldn't find anything that helped. It's probably me wording it wrong.)
A:
You would use a brace expansion in bash:
echo {s,S}{p,P}{a,A}{c,C}{e,E}{s,S}
spaces spaceS spacEs spacES spaCes spaCeS spaCEs spaCES spAces spAceS spAcEs spAcES spACes spACeS spACEs spACES sPaces sPaceS sPacEs sPacES sPaCes sPaCeS sPaCEs sPaCES sPAces sPAceS sPAcEs sPAcES sPACes sPACeS sPACEs sPACES Spaces SpaceS SpacEs SpacES SpaCes SpaCeS SpaCEs SpaCES SpAces SpAceS SpAcEs SpAcES SpACes SpACeS SpACEs SpACES SPaces SPaceS SPacEs SPacES SPaCes SPaCeS SPaCEs SPaCES SPAces SPAceS SPAcEs SPAcES SPACes SPACeS SPACEs SPACES
If you want the words newline-separated, use
printf "%s\n" {s,S}{p,P}{a,A}{c,C}{e,E}{s,S}
To make this reusable, put it in a function. However, since brace expansion is the first expansion performed by the shell, you can't use variables in it without using eval:
casecombinations() {
local source brace_expr i char
for source in "$@"; do
brace_expr=""
for ((i=0; i<"${#source}"; i++)); do
char="${source:i:1}"
case $char in
[[:alpha:]]) brace_expr+="{${char,},${char^}}";;
*) brace_expr+="\\$char";;
esac
done
eval echo "$brace_expr"
done
}
casecombinations hello world
| {
"pile_set_name": "StackExchange"
} |
Q:
Shadows color for text
I was wondering if you could change the shadow color from the sun? I'm making this for a T-shirt that will be black so I'd like to change the shadow to grey. Thanks!
Now it got foggy...what should I do?
A:
While user2859's answer is correct for changing the color of shadows, the shadows in your image are actually not those kind of shadows (or at least not to BI).
To adjust the color of those shaded parts of the mesh, try tweaking the ambient world color in Properties > World:
| {
"pile_set_name": "StackExchange"
} |
Q:
What resolution (pixels/mm) should I use in SVG for CNC?
I am planning a mechanical 40% keyboard build and are coincidentally on the home stretch of a homemade CNC project.
The only thing the CNC needs to do for the keyboard project is to drill 7*48 holes. So what I need to do now is layout those holes in SVG. Therein lies the question. What resolution should I use for the SVG? I want to space the center of the keyboard switches 19 mm apart. An online pixel to mm converter suggested that 72 pixels is exactly 19.05 mm (which actually is what Cherry MX says should be their spacing).
Now, I do understand that this really doesn't matter, but I am curious as I am new on CNCs and was suspecting that there is a number that will "just work".
EDIT:
For example, if I where to print the template (SVG) on a regular printer, what pixel to mm ratio should I use so that it would come out the size I want?
A:
I found one of those printer things that puts ink on dead trees and tested to print a simple SVG file.
<svg xmlns="http://www.w3.org/2000/svg"
width="400px" height="800px">
<rect x="10" y="10" width="72" height="72" fill="#999999" />
<rect x="10" y="100" width="378" height="378" fill="#999999" />
</svg>
As I suspected 72 pixels came out pretty much exactly 19mm. (72/19.05)*100~=378 came out 100mm.
Given this I am going to assume that 72/19.05 is the de facto best pixel to mm ratio to use for CNC projects.
EDIT:
Found this documentation: http://w3.org/TR/SVG/coords.html#Units
<svg xmlns="http://www.w3.org/2000/svg"
width="400px" height="800px">
<rect x="10" y="10" width="19.05mm" height="19.05mm" fill="#999999" />
<rect x="10" y="100" width="100mm" height="100mm" fill="#999999" />
</svg>
Much simpler to use mm as units right away
| {
"pile_set_name": "StackExchange"
} |
Q:
After appending cells, find min and max of five different categories in a CSV file
Hello everyone I have a question. I just now learning min and max.
I'm having trouble in finding the min and max of five columns for each category
Heres what I have:
I moved a 5 columns of 26 column data from a csv file to a txt file.
for example
the appended cells for .csv are like
state car motorcycle van airplane bike
Maine 35.5 8.1 5.7 21.0% 33.2%
Michigan 47.9 9.1 5.5 20.40% 25.2%
Washington 52.5 1.2 4.6 3.50% 24.7%
Denver 21.8 20.5 5.3 2.90% 30.9%
how do I get the min and max to look like this
min max
car Denver: 21.8 Washington: 52.5
motor Washington: 1.2 Denver: 20.5
van Washington 4.6 Maine: 5.7
airplane Denver 2.90% Maine 21.0%
bike Washington 24.7% Maine 33.2% -
Here is what I have
import csv
import string, re
import operator
output = []
data = []
csv_string = []
data_file = []
try:
with open('data.csv', 'r') as csv_string:
for line in csv_string:
cells = line.split(",")
output.append((cells[0], cells[1], cells[5], cells[7], cells[11], cells[13]))
for lines in output:
#state = cells[0]
zmin = cells[1] #car = cells[1]
ymin = cells[1]
xmin = cells[5] #motor = cells[5]
wmin = cells[5]
vmin = cells[7] #van = cells[7]
zmax = cells[7]
ymax = cells[11] #airplane = cells[11]
xmax = cells[11]
wmax = cells[13] #bike = cells[13]
vmax = cells[13]
if cells[1] < xmin:
zmin = cells[1]
if cells[1] > xmax:
zmax = cells[1]
if cells[5] < ymin:
ymin = cells[5]
if cells[5] > ymax:
ymax = cells[5]
if cells[7] < zmin:
xmin = cells[7]
if cells[7] > zmax:
xmax = cells[7]
if cells[11] < zmin:
wmin = cells[11]
if cells[11] > zmax:
wmax = cells[11]
if cells[13] < zmin:
vmin = cells[13]
if cells[13] > zmax:
vmax = cells[13]
outstring = ' '
for item in output:
for cell in item:
outstring += "{0:<35}".format(cell) #Width/Distance of each row
outstring += "\n"
print(outstring)
print('Min: ',zmin,ymin,xmin,wmin,vmin)
print('Max: ',state,zmax,ymax,xmax,wmax,vmax)
finally:
f.close()
try:
f_write = open('output.txt', 'w') #creates the file
try:
f_write.writelines(outstring)
finally:
f.close()
I'm not sure what I am doing wrong. I been reading min and max but I don't understand how this applies in a .csv file while appending 5 columns.
If anyone can offer some guidance, Thank you for your input.
The program prints wrong numbers
print('Min: ',zmin,ymin,xmin,wmin,vmin)
47.9, 8.1, 5.5, 20.40%, 25.2%
print('Max: ',state,zmax,ymax,xmax,wmax,vmax)
21.8, 9.1, 4.6, 20.40%, 30.9%
A:
Using pandas - a library designed for such data manipulation, the task becomes a lot simpler:
import pandas as pd
c = lambda x: float(x.strip('%'))
df = pd.read_csv(f,sep='\s+', converters = {'bike':c, 'airplane':c})
vehicles = df.columns[1:] #['car', 'motorcycle', 'van', 'airplane', 'bike']
max_v = zip(df['state'][df[vehicles].idxmax().values],
df[vehicles].max().values.astype('|S4'))
min_v = zip(df['state'][df[vehicles].idxmin().values],
df[vehicles].min().values.astype('|S4'))
max_i = [': '.join(tup) for tup in max_v]
min_i = [': '.join(tup) for tup in min_v]
print pd.DataFrame({'min':min_i, 'max':max_i}, index=vehicles)
out:
max min
car Washington: 52.5 Denver: 21.8
motorcycle Denver: 20.5 Washington: 1.2
van Maine: 5.7 Washington: 4.6
airplane Maine: 21.0 Denver: 2.9
bike Maine: 33.2 Washington: 24.7
A:
You can do much of what is needed by using Python's built-in csv module. Here's how to find the minimum and maximum values of a list of fields (or columns) of the data. The contents of sample data.csv file shown only has the fields of interest in it, but could contain all 26 columns of data without affecting the code which only processes the fields who's names appear in the FIELDS list.
import csv
ID = 'state'
FIELDS = ['car', 'motorcycle', 'van', 'airplane', 'bike']
MIN_ID, MIN, MAX_ID, MAX = 0, 1, 2, 3 # indices of data in min_maxes records
with open('data.csv', 'rb') as csv_file:
csv_dict_reader = csv.DictReader(csv_file, delimiter=',')
# initialize min and max values from first row of csv file
row = csv_dict_reader.next()
min_maxes = {field: [row[ID], float(row[field])]*2 for field in FIELDS}
# update min and max values with data from remaining rows of csv file
for row in csv_dict_reader:
for id, value, min_max_rec in (
(row[ID], float(row[field]), min_maxes[field]) for field in FIELDS):
if value < min_max_rec[MIN]:
min_max_rec[MIN_ID] = id
min_max_rec[MIN] = value
if value > min_max_rec[MAX]:
min_max_rec[MAX_ID] = id
min_max_rec[MAX] = value
print ' min max'
for field in FIELDS:
min_max_rec = min_maxes[field]
print '{:10} {:12}{:4.1f} {:12}{:4.1f}'.format(field,
min_max_rec[MIN_ID]+':', min_max_rec[MIN],
min_max_rec[MAX_ID]+':', min_max_rec[MAX])
Input (simplified data.csv file):
state,car,motorcycle,van,airplane,bike
Maine,35.5,8.1,5.7,21.0,33.2
Michigan,47.9,9.1,5.5,20.40,25.2
Washington,52.5,1.2,4.6,3.,24.7
Denver,21.8,20.5,5.3,2.90,30.9
Output:
min max
car Denver: 21.8 Washington: 52.5
motorcycle Washington: 1.2 Denver: 20.5
van Washington: 4.6 Maine: 5.7
airplane Denver: 2.9 Maine: 21.0
bike Washington: 24.7 Maine: 33.2
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Maintain data on listview when action bar back button is clicked
Hello guys I'm having an issue in using the back button of ActionBar. I want to retain the data of my listview when going from Activity A to Activity B. But when I click the back button of Action Bar from Activity B, my previous data was not retained. However, when I click the back button the data was still there. Any ideas why this is happening? I would gladly appreciate your help. Thanks
A:
When you click the Up button on the ActionBar, you must be passing an intent to create a new Activity. What you need to do is check if the Activity already exists or not. If it does, then you need to resume it. Otherwise, create a new one.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
} else {
upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Wordpress - Restrict page by user role - URL Redirect
I am trying to restrict a page for all user roles except "librarian"
I've got a library dashboard on example.com/library-dashboard
When a loogged in user role that is not 'librarian' visits this page, I need to redirect them to example.com/subscription-needed
I am using the following function for this:
function is_corr_user($page_slug) {
// User has to be logged in
if(!is_user_logged_in())
return false;
// All user roles
$roles = wp_get_current_user()->roles;
// For each page check if user has required role
switch($page_slug) {
case "library-dashboard":
return in_array('librarian, administrator', $roles);
default:
return false;
}
}
// Hook to wordpress before load and check if correct user is on page
add_action( 'wp', 'wpse69369_is_correct_user' );
function wpse69369_is_correct_user()
{
global $post;
// Redirect to a custom page if wrong user
if(!is_corr_user($post->post_name)) {
wp_redirect( '/subscription-needed/' );
exit;
}
}
My issue is that this function now redirects all pages to example.com/subscription-needed/ including the homepage and I am getting too many redirects error.
How can I fix this, so the function only works for the given user role librarian on the page example.com/library-dashboard ?
So what I'm trying to achieve is that if librarian & administrator visits example.com/library-dashboard then nothing happens and the page shows as normal.
But If any other user role that is NOT librarian & administrator visits the page example.com/library-dashboard, they should be redirected to example.com/subscription-needed/
A:
This worked for me, which you can use in place of both the is_corr_user() and wpse69369_is_correct_user() functions:
add_action( 'template_redirect', 'librarian_dashboard_redirect' );
function librarian_dashboard_redirect() {
if ( is_user_logged_in() && is_page( 'library-dashboard' ) ) {
$user = wp_get_current_user();
$valid_roles = [ 'administrator', 'librarian' ];
$the_roles = array_intersect( $valid_roles, $user->roles );
// The current user does not have any of the 'valid' roles.
if ( empty( $the_roles ) ) {
wp_redirect( home_url( '/subscription-needed/' ) );
exit;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Update on Weave Merging n lists into single list
This is a follow up to my previous post from 7 months ago. I changed up the algorithm a little. Instead of inserting items into a new list, each item's final place is calculated up front. Sort of like if instead of resizing an array each time I add a new item, I'm sizing it up front and just setting the value of each element. If the place is already occupied, the closest open place is found. This avoids everything getting shifted around as new items are inserted into the list, so every item is as close as possible to it's ideal place in the new list.
Sub TrueShuffle()
' object declarations
Dim xl As Object ' Excel.Application
Dim wb As Object ' Excel.Workbook
Dim destinationWs As Object ' Excel.Worksheet
Dim sourceWs As Object ' Excel.Worksheet
Dim totalsWs As Object ' Excel.Worksheet
' variable declarations
Dim artistName As String
Dim quotient As Double
Dim quotientSum As Double
Dim timeElapsed As Double
Dim pivotRows As Integer
Dim songCount As Integer
Dim artist As Integer
Dim song As Integer
Dim artistSongs As Integer
Dim oldRow As Integer
Dim newRow As Integer
Dim adjustment As Integer
Dim first As Integer
Dim sign As Integer
' start timer and turn off screen updating
timeElapsed = Timer
Application.ScreenUpdating = False
' set xl objects
Set wb = ThisWorkbook
Set totalsWs = wb.Worksheets("Totals")
Set sourceWs = wb.Worksheets("Source")
Set destinationWs = wb.Worksheets("Dest")
' opening operations
songCount = sourceWs.Range("A1").End(xlDown).row - 1 ' total songs in destination sheet
totalsWs.PivotTables("SongCount").ChangePivotCache _
wb.PivotCaches.Create(SourceType:=xlDatabase _
, SourceData:="Source!A1:C" & songCount + 1) ' set pivot data source range
totalsWs.PivotTables("SongCount").RefreshTable ' refresh pivot table
pivotRows = totalsWs.Range("B1").End(xlDown).row ' total rows in pivot table
destinationWs.Cells.Delete ' clear destination sheet
' iterate through each artist in pivot table
For artist = 2 To pivotRows - 1
artistName = totalsWs.Range("A" & artist).Value2
artistSongs = totalsWs.Range("B" & artist).Value2 ' song count for current artist
Select Case artist
Case 2 ' first artist takes first place in destination list
oldRow = sourceWs.Range("A2:A" & songCount + 1).Find(artistName, sourceWs.Range("A" & songCount + 1)).row
sourceWs.Range("A" & oldRow & ":C" & oldRow).Copy destinationWs.Range("A1:C1")
quotient = (songCount - 1) / (artistSongs - 1)
quotientSum = 1
first = 2 ' first song is placed before loop, so start from second song
Case Else
oldRow = songCount + 1 ' set to ensure the search for an artists songs starts from the beginning of the source list
quotient = songCount / artistSongs
quotientSum = (-quotient) / 2 ' offset placement within the list by half the quotient
first = 1
End Select
For song = first To artistSongs
' insert each song into destination sheet by incrementing by the
' artistSongs:songCount quotient and rounding to the nearest integer
quotientSum = quotientSum + quotient
oldRow = sourceWs.Range("A2:A" & songCount + 1).Find(artistName, sourceWs.Range("A" & oldRow)).row
newRow = Round(quotientSum, 0)
On Error Resume Next
' find the closest empty space
adjustment = 1
sign = 1
Do While destinationWs.Range("A" & newRow).Value2 <> 0
newRow = newRow + adjustment
adjustment = (adjustment + sign) * (-1)
sign = sign * (-1)
Loop
On Error GoTo 0
sourceWs.Range("A" & oldRow & ":C" & oldRow).Copy destinationWs.Range("A" & newRow & ":C" & newRow)
Next song
Next artist
' clear objects from memory
Set totalsWs = Nothing
Set sourceWs = Nothing
Set destinationWs = Nothing
Set wb = Nothing
' turn on screen updating and calculate time elapsed
Application.ScreenUpdating = True
timeElapsed = Timer - timeElapsed
MsgBox "TrueShuffled " & songCount & " songs in " & Round(timeElapsed, 2) & " seconds!", , "You Just Got TrueShuffled!"
End Sub
A:
Error Handling (and avoidance)
First, I would either add error handling or replace code that can throw errors with code that can't. For example, on an empty Worksheet this line will throw an overflow error:
songCount = sourceWs.Range("A1").End(xlDown).row - 1 ' total songs in destination sheet
I would personally replace this with a call to .UsedRange:
songCount = sourceWs.UsedRange.Rows.Count
What an error handler will do is let you clean up anything in the environment that had already been changed back to a safe setting. I.e.
Application.ScreenUpdating = False
I generally use a template something like the following:
Option Explicit
Public Sub TrueShuffle()
On Error GoTo ErrorHandler
'... Code here ...
ErrorHandler:
If Err.Number <> 0 Then
MsgBox "Error " & Err.Number & vbCrLf & Err.Description
End If
'Turn screen updating back on.
Application.ScreenUpdating = True
End Sub
Note that I also explicitly declared the scope of the Sub as Public and set Option Explicit, both of which you should be in the habit of doing.
Needless to say, turning error handling off instead of avoiding errors is generally not the best strategy, especially with a while loop between turning it off and turning it back on:
On Error Resume Next
' find the closest empty space
adjustment = 1
sign = 1
Do While destinationWs.Range("A" & newRow).Value2 <> 0
newRow = newRow + adjustment
adjustment = (adjustment + sign) * (-1)
sign = sign * (-1)
Loop
On Error GoTo 0
Let's assume for the sake of argument that the expression that throws the error is this (which is the most likely place you'll get a throw):
destinationWs.Range("A" & newRow).Value2
If the error is caused by newRow being out of bounds (for example 0 or negative), it's possible if not likely that you'll "Resume Next" in an infinite loop.
Other Notes
Remove unused variables:
Dim xl As Object ' Excel.Application is never even set.
Try to avoid declaring variables as "Object" unless you are using late binding or a COM object that doesn't have clean marshalling behavior - use the explicit type declarations:
Dim wb As Workbook, destinationWs As Worksheet, sourceWs As Worksheet
Dim totalsWs As Worksheet
When you declare them as "Object", you are using the IDispatch interface of the object instead of the IUnknown interface, and that carries a ton of overhead as compared to using the registered type definition. There's a really good explanation of the difference here.
Addressing cells with the alphanumeric addresses is really slow - column and row indexes are usually about twice as fast. Interestingly, the string concatenation isn't what slows it down (although it certainly doesn't help) - it's whatever Excel is doing to resolve the address:
Dim cell As Range
Set cell = ActiveSheet.Range("A" & 1) '375 ms over 200000 calls.
Set cell = ActiveSheet.Range("A1") '343 ms over 200000 calls.
Set cell = ActiveSheet.Cells(1, 1) '156 ms over 200000 calls.
Using the Excel .Copy() function will destroy whatever the user has on the clipboard (rather poor form), and can also fail with a runtime error 1004 if another application happens to be reading or writing to it. Since the Ranges are the same size, you can simply assign the values from one to the other. If they aren't the same size, just resize the destination Range and do the same thing:
sourceWs.Range("A" & oldRow & ":C" & oldRow).Copy destinationWs.Range("A" & newRow & ":C" & newRow)
'...becomes...
destinationWs.Range("A" & newRow & ":C" & newRow).Value2 = sourceWs.Range("A" & oldRow & ":C" & oldRow).Value2
Select or switch structures traditionally have another level of indentation for the cases to make them easier to read...
Select Case artist
Case 2
'...
Case Else
'...
End Select
...although in this case, there is no reason to use a select with only 2 cases - If ... Else is much clearer:
If artist = 2 Then
'...
Else
'...
End If
Finally, you shouldn't keep row counters in Integer types. They are only 16 bit and an Excel sheet can have enough rows to overflow them.
Dim newRow As Integer 'Runtime error 6 waiting to happen.
Dim newRow As Long 'Much better.
Sorting Method
While the algorithm that you use looks solid, using it the way you are in Excel VBA completely disregards what Excel is good at - which is handling large amounts of data in tables. You are going to have a hard time finding a VBA routine that performs a sorting function better than the built-in sorts. What you are really after here is a way to provide your own sort criteria, so your focus should be solely on doing that. Pick an unused column, write sort criteria to it, and use it to sort the sheet - it's as simple as that. This is a quick sample as to how I would go about this (error handler omitted because this is already a much longer post than intended). Assumes that the artist is in column A, no headers, and that column E is unused:
'Requires a reference to Microsoft Scripting Runtime
Private Sub FastShuffle()
Dim sheet As Worksheet, length As Long, artistCounts As Dictionary
Dim startTime As Double
startTime = Timer
Set sheet = ActiveSheet
length = sheet.UsedRange.Rows.count
Set artistCounts = New Dictionary
'Pass 1 - get song and artist counts.
Dim artist As String, row As Long
For row = 1 To length
artist = sheet.Cells(row, 1).Value2
If Not artistCounts.Exists(artist) Then
Call artistCounts.Add(artist, 1)
Else
artistCounts(artist) = artistCounts(artist) + 1
End If
Next row
'Pass 2 - write sort criteria to an empty row.
Dim numArtists As Long, last As String, counter As Long
'Need to be sorted for this pass.
Call sheet.UsedRange.Sort(sheet.Columns(1))
For row = 1 To length
'Get the artist to use as the key.
artist = sheet.Cells(row, 1).Value2
'Reset the counter if the artist changed.
If artist <> last Then
counter = 0
last = artist
End If
counter = counter + 1
'Calculate where it falls in the sort.
sheet.Cells(row, 5).Value2 = counter / artistCounts(artist)
Next row
'Now just sort on the criteria column and delete it.
Call sheet.UsedRange.Sort(sheet.Columns(5))
sheet.Columns(5).Delete
Debug.Print "FastShuffled " & length & " songs from " & (UBound(artistCounts.Keys) + 1) _
& " artists in " & Timer - startTime & " seconds."
End Sub
Sample output:
FastShuffled 30000 songs from 190 artists in 1.359375 seconds.
When you approach an Excel VBA problem from within the context of Excel's (and VBA's) strengths and weaknesses, you end up with much more readable and less fragile code. It works with one Worksheet, sorts it in place, doesn't require a pivot table, and doesn't nuke the clipboard. It's also clear what it is doing, concise, and efficient.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ruby: How to create attr_accessor on the fly
I want to know how to create attr_accessor on the fly. Is it possible to do something like:
attr_accessor "@#{key}"
inside the initialize method?
module Mymodule
def initialize(parameters = {})
parameters.each do |key, value|
instance_variable_set("@#{key}", value) unless value.nil?
end
end
end
class Myclass
include Mymodule
end
clazz = Myclass.new attr1: "Arg1", attr2: "Arg2", attr3: "Arg3"
# => #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3">
clazz.attr1
# !> NoMethodError: undefined method `attr1' for #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3">
clazz.attr1="ATTR1"
# !> NoMethodError: undefined method `attr1=' for #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3">
A:
You can define per instance accessors by calling attr_accessor on that instance's singleton class.
class Structy
def initialize(parameters = {})
parameters.each do |key, value|
singleton_class.send :attr_accessor, key
instance_variable_set "@#{key}", value
end
end
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Loading MySQL table into a text file?
It has been answered that how to load data from text file into SQL databases.
However, I did not find any question regarding how to load table into text file.
I am using JDBC and MySQL on my own PC.
How can I load a table into a text file ?
The data should be neatly organized like a matrix in the text file, including column names.
Best regards to the people reading this question.
A:
Are you just trying to export it as a .txt?
IF so you can just do this
SELECT * FROM table
INTO OUTFILE '/.../filelocation.txt'
You have several options of delimiting, line feed, and such. Look at this link for some examples.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can not SET a Value in table using Python?
I'am trying to set values in table, the code run good, i don't got errors, but nothing is done !
I'm using Arcgis10.1, arcpy and Python
This is the code :
import arcpy
import math
import arcview
from arcpy import env
arcpy.env.workspace = "D:/Users/saadiya/Documents/ArcGIS/Default1.gdb"
arcpy.env.overwriteOutput = True
cur = arcpy.UpdateCursor("Join_Dataset")
for row in cur :
SW = row.getValue("RefName_SW")
S = row.getValue("RefName_S")
SE = row.getValue("RefName_SE")
new_s = S
if (SW != S):
new_s = new_s+", "+SW
elif (SE != S):
new_s = new_s+", "+SE
row.setValue("Sud", new_s)
cur.updateRow(row)
print new_s
I got this error :
Traceback (most recent call last):
File "<string>", line 11, in <module>
File "d:\program files (x86)\arcgis\desktop10.1\arcpy\arcpy\arcobjects\arcobjects.py", line 102, in updateRow
return convertArcObjectToPythonObject(self._arc_object.UpdateRow(*gp_fixargs(args)))
RuntimeError: ERROR 999999: Error executing function.
Objects in this class cannot be updated outside an edit session [Join_Dataset]
A:
You've forgotten to add cur.updateRow(row) in the end of the loop, to save changes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Loading text file in MATLAB?
I have a comma separated file with 182 rows and 501 columns, of which 500 columns are of type number (features) while the last column are strings (labels).
Example: 182x501 dimension
1,3,4,6,.........7, ABC
4,5,6,4,.........9, XYZ
3,4,5,3,.........2, ABC
How can I load this file so it will have a data set with a matrix, B, containing the number as my features, and a vector, C, containing the strings as my labels?
d = dataset(B, C);
A:
Build a format specifier for textscan based on the number and types of columns, and have it read the file for you.
nNumberCols = 500;
format = [repmat('%f,', [1 nNumberCols]) '%s'];
fid = fopen(file);
x = textscan(fid, format);
fclose(fid);
B = cat(2, x{1:nNumberCols});
C = x{end};
A:
You could use the textscan function. For example:
fid = fopen('test.dat');
% Read numbers and string into a cell array
data = textscan(fid, '%s %s');
% Then extract the numbers and strings into their own cell arrays
nums = data{1};
str = data{2};
% Convert string of numbers to numbers
for i = 1:length(str)
nums{i} = str2num(nums{i}); %#ok<ST2NM>
end
% Finally, convert cell array of numbers to a matrix
nums = cell2mat(nums);
fclose(fid);
Note that I have made a number of assumptions here, based on the file format you have specified. For example, I assume that there are no spaces after the commas following a number, but that there is a space immediately preceding the string at the end of each line.
To can make the above code more flexible by using a more considered format specifier (the second argument to textscan). See the section Basic Conversion Specifiers in the textscan documentation.
A:
For example, if you have the following data in a file named data.txt:
1,3,4,6,7, ABC
4,5,6,4,9, XYZ
3,4,5,3,2, ABC
you can read it into a matrix B and a cell array C using the code
N = 5; % Number of numeric data to read
fid = fopen('data.txt');
B = []; C = {};
while ~feof(fid) % repeat until end of file is reached
b = fscanf(fid, '%f,', N); % read N numeric data separated by a comma
c = fscanf(fid, '%s', 1); % read a string
B = [B, b];
C = [C, c];
end
C
B
fclose(fid);
to give
C =
'ABC' 'XYZ' 'ABC'
B =
1 4 3
3 5 4
4 6 5
6 4 3
7 9 2
| {
"pile_set_name": "StackExchange"
} |
Q:
Instance of Realm Object subclass is null when init
I'm new to iOS development and swift, and I'm using Realm for my swift project.
First, I create a subclass of Realm Object:
enum EnumA: Int {
case ValueA
case ValueB
}
class ClassA: Object {
var propA: EnumA = EnumA.ValueA
var propB: Double = 0.0
}
Then I have another class:
class ClassB: Object {
var id = 0
var name: String = ""
let aLotOfA = List<ClassA>()
override static func primaryKey() -> String? {
return "id"
}
}
Then I create instance of ClassB somewhere:
class ClassC: NSObject {
static let cManager = ClassC()
func defaultB() -> ClassB {
let instanceA = ClassA()
let instanceB = ClassB()
instanceB.name = "String"
instanceB.aLotOfA.append(instanceA)
return instanceB
}
}
And I have this class:
class ClassD: Object {
let aB: ClassB = ClassC.cManager.defaultB()
}
When I call defaultB(), the first line (let instanceA = ClassA()) makes instanceA null. I keep receiving message in the console like this:
"Object type '(null)' does not match RLMArray type 'ClassA'."
or
"The `ClassD.aB` property must be marked as being optional."
I don't know what's wrong here. Please someone help me, thanks very much.
And my environment:
Mac OS X 10.11.1 + Xcode 7.1
Realm is latest (Just downloaded from realm.io)
Base SDK: iOS 9.1
Deployment Target: iOS 9
A:
As pointed out by zuziaka, you will need to declare all your persisted properties with dynamic var. This doesn't apply for List and RealmOptional properties.
Furthermore Realm doesn't support enums. You will need to declare your property ClassA.propA as Int and use the rawValue to initialize its default value:
class ClassA {
var propA: Int = EnumA.ValueA.rawValue
…
}
To-one relationships must be always marked as optional. That's here the case for the property ClassD.aB.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript keyup call other table value
I have a table like this:
<tbody id="invoice_item">
<tr>
<td><input name='qty[]' type='text' class='form-control form-control-sm qty' value='0'></td>
<td><input name='price[]' type='text' class='form-control form-control-sm price' value='0'></td>
<td><input name='sub_total[]' type='text' class='form-control form-control-sm sub_total' value='0' readonly></td>
</tr>
</tbody>
I want to make Javascript when qty/price change subtotal changed too.
My js:
$("#invoice_item").delegate(".qty","keyup",function(){
var qty = $(this).val();
var price = tr.find(".price").val();
alert(price);
var sub_total = qty * price;
alert(sub_total);
tr.find(".sub_total").html(sub_total);
})
$("#invoice_item").delegate(".price","keyup",function(){
var price = $(this).val();
var qty = tr.find(".qty").val();
alert(qty);
})
It seems the trouble is tr.find(".").val();.
I try to alert it, but no use.. anyone can help? How I can call the other input?
$(this).val(); is no problem.
A:
i solved it,
i must define it by
var tr = $(this).parent().parent();
thanks all!
| {
"pile_set_name": "StackExchange"
} |
Q:
Why the products search bar is not working? Rails 4
I have a simple search bar to find products by name and order the results alphabetical.
-----> products_controller.rb
def index
scope = Product
if params[:search]
scope = scope.search(params[:search])
end
if params[:ordering] && ordering = ORDERS[params[:ordering].to_i]
scope = scope.order(ordering)
end
@products = Product.includes(:current_price).all.stock.order('id DESC')
@product_detail = ProductDetail.new
end
-----> product.rb
class Product < ActiveRecord::Base
has_many :product_details
has_many :prices
has_one :current_price, -> {
where('prices.id = (SELECT MAX(id) FROM prices p2 WHERE product_id = prices.product_id)')
}, class_name: 'Price'
accepts_nested_attributes_for :prices
accepts_nested_attributes_for :product_details
# It returns the products whose names contain one or more words that form the query
def self.search(query)
where(["name LIKE ?", "%#{query}%"])
end
# Returns a count with the available products on stock
def self.stock()
select('products.*, SUM(case when product_statuses.available=true then 1 else 0 end) as count')
.joins('LEFT JOIN `product_details` `product_details` ON `product_details`.`product_id` = `products`.`id`')
.joins('LEFT JOIN `product_statuses` ON `product_statuses`.`id` = `product_details`.`status`')
.group('products.id')
end
end
I don't know, I have a very similar code for my Customers controller and model to do a phonebook and It works.
The only different is the "stock" to calculate how many units are available on the inventory, and It's working good.
I really need help with search bar :( I already reviewed all my code and looks good.
Thanks to everyone
A:
Why is your @product variable not using the scope you already defined. I think it should be @products = scope.includes(:current_price).all.stock.order('products.id DESC')
Add products.id DESC instead of id DESC since the statement may be ambiguous to ActiveRecord. Also you will have to append products. to your orderng params.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to enable laravel5.3 auth to register users after login?
i want to user after login with own credentials,be able to register new users.
i using laravel5.3 and built-in Authentication system.
how to change Authentication system for this feature?
thanks
A:
You don't need to change authentication system for that. You can allow some user to create a new user manually:
public function createNewUser(Request $request)
{
if (auth()->user()->isAdmin()) {
$request->password = bcrypt($request->password);
$user = User::create($request->all());
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Access violation in Entity Framework code accessing SQL Server
We've encountered an access violation on our test machine, in Entity Framework code. I'm wondering if this could potentially be due to a threading bug, or if it's more likely due to hardware issues.
Here is a partial call stack:
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at System.Data.Common.Internal.Materialization.CoordinatorFactory`1..ctor(Int32 depth, Int32 stateSlot, Expression hasData, Expression setKeys, Expression checkKeys, CoordinatorFactory[] nestedCoordinators, Expression element, Expression elementWithErrorHandling, Expression initializeCollection, RecordStateFactory[] recordStateFactories)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeConstructor(IRuntimeMethodInfo method, Object[] args, SignatureStruct& signature, RuntimeType declaringType)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at System.Data.Common.Internal.Materialization.CoordinatorScratchpad.Compile()
This happened in our ASP.NET app on IIS 7 (Server 2008 R2 SP1), using Entity Framework 4 to access SQL Server 2008 R2. I've read about access violations with EF and SQL Server CE, but we are using the full SQL Server. We aren't directly interacting with any native code from our app - no P/Invoke or COM interop.
This has only happened once. Personally I think it's a problem with the machine, not the application... the machine has BSOD'd a couple times before. But I was asked to look into it as a possible bug.
I'll look into setting up DebugDiag to catch this if it happens again. Does anyone have any other suggestions?
Thanks,
Richard
A:
I think you're probably right, I would guess that there was some other code running in the same worker process which caused some memory corruption that resulted in this error.
If there are other applications running in this worker process, you might want to look at separating this application out into a dedicated worker. Other than that I would put it into the "lets just keep an eye out" category.
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing Parameter into function match
I am using the function match for a search engine, so whenever a user types a search-string I take that string and use the match function on an array containing country names, but it doesn't seem to work.
For example if I do :
var string = "algeria";
var res = string.match(/alge/g); //alge is what the user would have typed in the search bar
alert(res);
I get a string res = "alge": //thus verifying that alge exists in algeria
But if I do this, it returns null, why? and how can I make it work?
var regex = "/alge/g";
var string = "algeria";
var res = string.match(regex);
alert(res);
A:
To make a regex from a string, you need to create a RegExp object:
var regex = new RegExp("alge", "g");
(Beware that unless your users will be typing actual regular expressions, you'll need to escape any characters that have special meaning within regular expressions - see Is there a RegExp.escape function in Javascript? for ways to do this.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Find distance of one graph from another in matlab
I have two curves in Matlab.
Curve A:
x1 = [128 192 256 384 512 704 1024 1472 2048 2880 4096 5824 8192 11584 16384 23168];
y1 = [0.62 0.51 0.43 0.35 0.3 0.26 0.22 0.18 0.15 0.13 0.11 0.09 0.08 0.06 0.05 0.05];
Curve B:
x2 = [16 24 32 48 64 88 128 184 256 360 512 728 1024 1448 2048 2896];
y2 = [1.94 1.54 1.33 1.15 0.97 0.86 0.71 0.59 0.5 0.42 0.36 0.3 0.25 0.21 0.18 0.15];
After drawing both curves (x-axis exponentially) in the same plot:
semilogx(x1,y1,'-o')
hold on
semilogx(x2,y2,'-o')
I have found that B curve is above A curve. But I want to shift B to the left so that B curve overlaps A curve. So the question is, what amount (right to left) I need to shift B curve to overlap A curve?
Some clue: Maybe need to count the vertical distance (for all match points) from B to A (interpolation) and square the distance and sum them all up and find the value of Alpha. How can I do it in Matlab?
A:
We can find the desired shift by first finding what values of x2 would move the curve B exactly on top of curve A. This can be achieved by resampling curve A at points corresponding to the y-coordinates of the points in curve B. The following code illustrates this.
Since you plot the x-axis in log-domain, I assume that you want to shift log10(x2). So the x-points on your shifted curve be will be log10(x2) + shift instead of log10(x2 + shift).
% find the subset of y2 which is within the range of y1
idxCommonB = find((y2 <= max(y1)) & (y2 >= min(y1)));
y2c = y2(idxCommonB);
x2c = x2(idxCommonB);
% for each point on curve B, find a new x2 that would move the point on
% curve A
% We use interp1 function for resample the curve. This function requires
% all the points in the domain to be unique. So find the unique elements in
% y1.
[y1_unique,iUnique] = unique(y1);
x2c_desired = interp1(y1_unique, x1(iUnique), y2c, 'linear');
% find the average distance between the desired and given curves
x2_logshift = mean(log10(x2c_desired) - log10(x2c));
% Display the result
fprintf('Required shift in log10(x2) is %f.\n', x2_logshift);
% Required shift in log10(x2) is -0.126954.
% plot to verify the estimate
figure;
plot(log10(x1),y1,'-o')
hold on
plot(log10(x2),y2,'-o')
plot(log10(x2)+x2_logshift,y2,':*')
grid on;
legend({'A', 'B', 'Shifted B'});
set(gca, 'FontSize', 12);
| {
"pile_set_name": "StackExchange"
} |
Q:
Only downloading new folders/files with rsync
I periodically run a rsync command which downloads new files from my remote server.
The files that are downloaded are stored in folders, once I have downloaded them to my local machine I may delete folders (and their contents) that are no longer required.
When I run my rsync command again it will download any new folders as well as the old folders that I have deleted from my local machine which I don't want.
What I would like to do on rsync command is store the folder names in a file (like downloaded.log) and then use this as my exclude file for the next time I run rsync so it will not download these folders again.
I think it would be more efficient to store only the folder names rather than folders and filenames as by skipping the folder you would skip the file anyway.
Could someone explain how I could have the rsync command output the folders names?
Current RSYNC command:
rsync -avz --dry-run remote-host:downloads/ ~/Downloads/
A:
use the --exclude-from=FILE and put the directories you don't want in this file.
For example if you have a dir test with folders a,b and c inside and you want to sync it to a folder test2 but want to ignore folder b and c, you need to create a file like following :
$ cat ignore
/b
/c
and then run the command
rsync -avz --exclude-from=ignore test/ test2/
edit:
To fit to your command
rsync -avz --dry-run --exclude-from=/path/to/ignore-file remote-host:downloads/ ~/Downloads/
and in the file /path/to/ignore-file make a list of contents that are on remote-host in the downloads folders like this.
subfolder1/
subfolder2/
edit2:
To make it automatic you can create a script like that
/home/youruser/scripts/add-to-ignore.sh
#/bin/bash
for filepath in ~/Downloads/*
do
filename=$(basename $filepath)
echo "$filename/" >> /home/youruser/.ignorelist
done
And then run it like that
rsync -avz --dry-run --exclude-from=/path/to/ignore-file remote-host:downloads/ ~/Downloads/ && bash /home/youruser/scripts/add-to-ignore.sh
That should do the trick, and the list will keep the old dirs.
You could also use --log-file and --log-file-format to log what you've just copied in a file and then have a script to remove the beginning of lines, so you could use this file as a source for --exclude-from.
| {
"pile_set_name": "StackExchange"
} |
Q:
Linq mystery error in EF query
I have a UserProfile class
[Key]
public int UserProfileId { get; set; }
public string AppUserId { get; set; }
...code removed for brevity
[Required]
public NotificationMethod NotificationMethod { get; set; }
public List<PrivateMessage> PrivateMessages { get; set; }
public List<Machine> OwnedMachines { get; set; }
public bool IsProfileComplete { get; set; }
public byte[] Avatar { get; set; }
public string AvatarUrl { get; set; }
public string GetFullName()
{
return $"{FirstName} {LastName}";
}
}
I also have a PrivateMessage class
public class PrivateMessage
{
[Key]
public int Id { get; set; }
public int MessageToUserId { get; set; }
public int MessageFromUserId { get; set; }
public DateTime DateSent { get; set; }
public string Message { get; set; }
}
I set up a simple test to pull the user profile out with various includes. The PrivateMessages always errors. Here is a sample method that errors.
public static UserProfile GetUserProfileIncluding(string appUserId)
{
using (RestorationContext)
{
//RestorationContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
return RestorationContext.MemberProfiles.Where(m => m.AppUserId == appUserId)
.Include(m=> m.PrivateMessages)
.FirstOrDefault();
}
}
The error noted is
InnerException {"Invalid column name 'UserProfile_UserProfileId'.\r\nInvalid column name 'UserProfile_UserProfileId'."} System.Exception {System.Data.SqlClient.SqlException}
Which I don't understand, neither table has a column "UserProfile_UserProfileId"
If I use the property OwnedMachines instead of PrivateMessages, it works perfectly fine (well not really, its only pulling in 4 records when there are 6 that match but I can figure that out later).
public static UserProfile GetUserProfileIncluding(string appUserId)
{
using (RestorationContext)
{
return RestorationContext.MemberProfiles.Where(m => m.AppUserId == appUserId)
.Include(m=> m.OwnedMachines)
.FirstOrDefault();
}
}
And you can see below, Machine is set up exactly like PrivateMessage, albeit it has two UserProfiles instead of one
public class Machine
{
[Key]
public int MachineId { get; set; }
public int OwnerProfileId { get; set; }
public int SerialNumber { get; set; }
public string YearofManufacture { get; set; }
public string ModelName { get; set; }
public Manufacturer Manufacturer { get; set; }
public DateTime DateAcquired { get; set; }
}
I've spent far to much time on this now. Does it have something to do with the fact that I have two UserProfile Id int properties in PrivateMessage? (MessageToUserId & MessageFromUserId). I originally had these set as foreign keys with a UserProfile property in there as well like this
[ForeignKey("MessageToProfile")]
public int MessageToUserId { get; set; }
public UserProfile MessageToProfile { get; set; }
[ForeignKey("MessageFromProfile")]
public int MessageFromUserId { get; set; }
public UserProfile MessageFromProfile { get; set; }
But I removed them thinking they may have been the source of the error, but apparently not.
UPDATE:
After a bunch more trial and error, it is apparent that the current method will always err as the method is looking for a navigable property which doesn't exist. Since I have the two int properties in PrivateMessage, when trying to include those in the UserProfile object, I will need to filter then by MessageToUserId and then include them. Not sure how to filter and include.
Using this method should work;
public static UserProfile GetProfileForLoggedInUser(string appUserId)
{
using (RestorationContext)
{
RestorationContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
var profile= RestorationContext.MemberProfiles.Include(m => m.OwnedMachines)
.FirstOrDefault(m => m.AppUserId == appUserId);
var pms = RestorationContext.PrivateMessages.Where(m => m.MessageToUserId == profile.UserProfileId).ToList();
if (profile != null) profile.PrivateMessages = pms;
return profile;
}
}
But it gives the same invalid column error UserProfile_UserProfileID.
Here is the TSql
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[MessageToUserId] AS [MessageToUserId],
[Extent1].[MessageFromUserId] AS [MessageFromUserId],
[Extent1].[DateSent] AS [DateSent],
[Extent1].[Message] AS [Message],
[Extent1].[UserProfile_UserProfileId] AS [UserProfile_UserProfileId]
FROM [RestorationContext].[PrivateMessages] AS [Extent1]
WHERE [Extent1].[MessageToUserId] = @p__linq__0
Since this is just querying the PrivateMessage table WHY is it looking for that UserProfileId, it has nothing to do with this table. Here are the table properties from SSMS
Where is that UserProfileID crap coming from?
A:
Your Machine inclusion works because the Machine class has only one foreign key of UserProfile.
You have 2 foreign keys to the same table in PrivateMessage class, naturally, you would need 2 ICollection navigation properties in your UserProfile class. EntityFramework didn't know which foreign key to use in your PrivateMessage class for loading your ICollection<PrivateMessage> property in your UserProfile class.
public ICollection<PrivateMessage> FromPrivateMessages { get; set; }
public ICollection<PrivateMessage> ToPrivateMessages { get; set; }
In your context class
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PrivateMessage>()
.HasRequired(m => m.MessageFromProfile)
.WithMany(t => t.FromPrivateMessages)
.HasForeignKey(m => m.MessageFromUserId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<PrivateMessage>()
.HasRequired(m => m.MessageToProfile)
.WithMany(t => t.ToPrivateMessages)
.HasForeignKey(m => m.MessageToUserId)
.WillCascadeOnDelete(false);
}
UPDATE
EF uses convention over configuration, and by having navigation properties of UserProfile in your PrivateMessage class will imply a relationship and EF will try to find a foreign key in the form of <Navigation Property Name>_<Primary Key Name of Navigation Property type>, which gives you UserProfile_UserProfileId.
You should be wondering why UserProfile_UserProfileId instead of UserProfile_MessageToUserId or UserProfile_MessageFromUserId at this point. That's because of your foreign key attribute, telling EF to use the UserProfileId property in your UserProfile class.
What you can do now is, remove the foreign key attributes like this
public int MessageToUserId { get; set; }
public UserProfile MessageToProfile { get; set; }
public int MessageFromUserId { get; set; }
public UserProfile MessageFromProfile {get; set; }
and add another ICollection and do the modelBuilder configuration like how I stated before the update.
| {
"pile_set_name": "StackExchange"
} |
Q:
If a custom metadata type is subscriber editable can the subscriber create a record?
Is it possible to deploy a custom metadata type in a managed package with on record that users can edit without the permissions to create any more?
A:
It's not currently possible to do this, although it's on our radar.
The workaround is to filter your queries by NamespacePrefix, so that custom metadata records created outside your namespace don't have an effect on your app.
E.g., instead of
MyType__mdt myRecord = [select DeveloperName, CustomField__c from MyType__mdt];
use
MyType__mdt myRecord = [select DeveloperName, CustomField__c from MyType__mdt where NamespacePrefix='my_namespace'];
| {
"pile_set_name": "StackExchange"
} |
Q:
asp.net mvc and canonical link: bug?
I created a simple CMS in asp.net MVC. Every article has a canonical link, which I want to use in my master page like this:
<link href="<%= Model.CanonicalLink %>" rel="canonical" />
However, when I view the source of this page in Firefox, it shows me:
<link href="../../Views/Shared/%3C%25=%20Model.CanonicalLink%20%25%3E" rel="canonical" />
I must be very stupid, or it is a bug. When I move the
<%= Model.CanonicalLink %>
part out of the <link /> then it shows me the canonical link. So, what is causing this odd behaviour?
A:
This is the ASPX parser stomping on your HTML. Remove the runat="server" from the <head> element in which this <link> is defined.
| {
"pile_set_name": "StackExchange"
} |
Q:
php cannot send posted array elements
I successfully passed following values with AJAX post method to my PHP file
name:John
email:[email protected]
comments:Hello
category_list[]:Books
category_list[]:Documents
The problem is that the following code sends HelloArray instead of HelloBooksDocuments. Could you please help me to find my mistake.
$email = $_POST["email"];
$name = $_POST["name"]);
$comments = $_POST["comments"];
$categories = $_POST["category_list"]; //the problem is here
A:
Replace this line:
$comments= $comments.$categories;
With:
$comments= $comments.implode("", $categories);
The reason is that that variable $categories is an array, and you need to convert it to a string.
This you can do with implode. If you want them separated by a comma, then pass that as the first argument, replacing the empty string "" I have suggested above.
Of course, you can change this, and use another separator of your choice.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get x and y value pairs of pandas in python
I have created a co-occurrence matrix as follows using pandas.
import pandas as pd
import numpy as np
lst = [
['a', 'b'],
['b', 'c', 'd', 'e', 'e'],
['a', 'd', 'e'],
['b', 'e']
]
u = (pd.get_dummies(pd.DataFrame(lst), prefix='', prefix_sep='')
.groupby(level=0, axis=1)
.sum())
v = u.T.dot(u)
v.values[(np.r_[:len(v)], ) * 2] = 0
print(v)
The output is as follows.
a b c d e
a 0 1 0 1 1
b 1 0 1 1 3
c 0 1 0 1 2
d 1 1 1 0 3
e 1 3 2 3 0
I would like to convert the above mentioned dataframe into (x,y) pairs. As you can see the output matrix is symmetric (i.e the upper part from the diagonal and lower part from the diagonal is similar). Therefore, I am happy to only get the (x,y) pairs from one part of them (e.g., only using upper part).
So, in the above matrix the ouput should be (i.e. (x,y) pairs whose value is greater than zero >0);
[('a','b'), ('a', 'd'), ('a','e'), ('b', 'c'), ('b', 'd'), ('b', 'e'),
('c', 'd'), ('c', 'e'), ('d', 'e')]
Is it possible to perform this in pandas?
I am happy to provide more details if needed.
A:
You can try np.where:
arr = np.where(v>=1)
corrs = [(v.index[x], v.columns[y]) for x, y in zip(*arr)]
corrs
[('a', 'b'),
('a', 'd'),
('a', 'e'),
('b', 'a'),
('b', 'c'),
('b', 'd'),
('b', 'e'),
('c', 'b'),
('c', 'd'),
('c', 'e'),
('d', 'a'),
('d', 'b'),
('d', 'c'),
('d', 'e'),
('e', 'a'),
('e', 'b'),
('e', 'c'),
('e', 'd')]
Then you can filter the list:
final_arr = []
for x, y in corrs:
if (y,x) not in final_arr:
final_arr.append((x,y))
final_arr
[('a', 'b'),
('a', 'd'),
('a', 'e'),
('b', 'c'),
('b', 'd'),
('b', 'e'),
('c', 'd'),
('c', 'e'),
('d', 'e')]
A:
This also works:
pd.DataFrame(np.argwhere(v.values>0)).replace({0:'a', 1:'b', 2:'c', 3:'d', 4:'e'}).values
A:
Use numpy.triu for upper triangle matrix, get indices by numpy.nonzero or numpy.where and last zip values of index and columns created by indexing:
i, c = np.nonzero(np.triu(v.values))
#alternative
#i, c = np.where(np.triu(v.values))
L = list(zip(v.index[i], v.columns[c]))
print (L)
[('a', 'b'),
('a', 'd'),
('a', 'e'),
('b', 'c'),
('b', 'd'),
('b', 'e'),
('c', 'd'),
('c', 'e'),
('d', 'e')]
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I reset the startup directory to my HOME in Fish?
In my desktop manager, I have bound fish to a keyboard shortcut Ctrl + ~. On startup, fish opens the directory /usr/lib/lightdm/lightdm. This is quite annoying, because I have no business with lightdm, and I usually work on code in my $HOME directory.
How can I change the directory that fish starts in? I would like to change the startup directory simply to ~/
A:
I had found that the config.fish file that runs at startup had been changing my default working directory.
A misguided attempt at setting my PATH left a list of directories in my config.fish, the first of which was /usr/lib/lightdm/lightdm. Fish automatically assumes directories without a command should be cd`d into, so my shell was cd`ing into that directory at startup.
I removed the stray lines and all is well.
To change your fish startup directory:
add cd /path/to/new/startup/directory to your ~/.config/fish/config.fish file, or create it if it does not exist.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bind Unbind onclick event not working with Ajax
I am having an issue with bind & unbind onClick listener using JQuery Ajax.
How to unbind on click event that it can't be clicked multiple times, but bind it if ajax fails. this is what I have tried so far.
$('#test').on('click', function (e) {
e.preventDefault();
alert('clicked');
$( "#test" ).off( "click");// works fine,remove on click listner
// Ajax function
// done() // Do nothing.
// error() // bind it again so it can be clicked.
});
https://jsfiddle.net/khirad1996/4nLdvq9s/2/
A:
You can disable the button while the call is happening, and re-enable if there is an error!
const fakeAjax = time => new Promise(r => setTimeout(() => r(Math.random() > .5), time))
const button = document.querySelector('button');
button.addEventListener('click', async function() {
this.disabled = true;
error = await fakeAjax(1000);
this.disabled = error;
});
<button>Ajax Call</button>
| {
"pile_set_name": "StackExchange"
} |
Q:
Background image transition on hover
I have html page and I set background image in css rule:
body{ background-image:url("/someurl");}
And i have button, when i hover it I'm change background image. But i do it using JQuery like this
body.css('background-image', 'url(' + initialimageSrc + ')');
I 'd like to have a transition on backgound-image change, but when I use
transition:background-image 2s linear;
It looks very bad. Can any one help?
A:
well, actually, this way of transitioning a background-image only supports fade-in, fade-out, and doesn't really offer any customisability.
my advice is to create a second object, which will fade in and out alternatively.
try to follow the conventions in http://css3.bradshawenterprises.com/cfimg/ - it helped me a lot with that subject.
| {
"pile_set_name": "StackExchange"
} |
Q:
Howto import xls/csv file with unicode charset into php/mysql?
I want to give the user the ability to import a csv file into my php/mysql system, but ran into some problems with encoding when the language is russian which excel only can store in UTF-16 tab-coded tab files.
Right now my database is in latin1, but I will change that to utf-8 as described in question "a-script-to-change-all-tables-and-fields-to-the-utf-8-bin-collation-in-mysql"
But how should I import the file? and store the strings?
Should I for example translate it to html_entitites?
I am using the fgetcsv command to get the data out of the csv file.
My code looks something like this right now.
file_put_contents($tmpfile, str_replace("\t", ";", file_get_contents($tmpfile)));
$filehandle = fopen($tmpfile,'r');
while (($data = fgetcsv($filehandle, 1000, ";")) !== FALSE) {
$values[] = array(
'id' => $data[0],
'type' => $data[1],
'text' => $data[4],
'desc' => $data[5],
'pdf' => $data[7]);
}
As note, if I store the xls file as csv in excel, i special chars are replaced by '_', so the only way I can get the russian chars out of the file, is to store the file in excel as tabbed seperated file in UTF16 format.
A:
Okay, the solution was to export the file from excel to UTF16 unicode text and add the ';' instaid of '\t' and convert from utf16 to utf8.
file_put_contents($tmpfile, str_replace("\t", ";", iconv('UTF-16', 'UTF-8', file_get_contents($tmpfile))));
The table in mysql has to be changed from latin1 to utf8
ALTER TABLE `translation`
CHANGE `text` `text` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
CHANGE `desc` `desc` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL
And then the file could be imported as before.
When I want to export the data from the database to a excel file, the csv-version is not an option. It has to be done in excel's html mode. Where data is corrected by eg. urlencode() or htmlentities()
Here some example code.
<?php
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="export.xls"');
print ('<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<div id="Classeur1_16681" align=center x:publishsource="Excel">
<table x:str border=0 cellpadding=0 cellspacing=0 width=100% style="border-collapse: collapse">');
for($i = 0 ; $i < count($lines) ; $i++) {
print ('<tr><td>');
print implode("</td><td>",$lines[$i]);
print ('</td></tr>');
}
?>
</div>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Парсинг содержимого веб страницы
Стоит задача пропарсить сайт и достать из него изображения.
Использую библиотеки requests и BeautifulSoup.
Проблема в том, что когда я делаю парсинг сайта напрямую, то BeautifulSoup не хочет отображать содержимое списка в котором находятся изображения. Суп показывает, что в списке нет элементов. Есть подозрение, что они подгружаются отдельно, потому что если страницу сохранить на ПК и парсить как локальный файл, то Суп прекрасно находит содержимое списка.
Вопрос в том, как мне все-таки получить содержимое этих списков. Какова технология их получения и какой (какими) библиотеками надо воспользоваться. Спасибо!
Вот этот ресурс:( http://gepur.ru ), к примеру картинки с этой страницы:( http://gepur.ru/product/plate-6916 ). Спасибо!
A:
В ходе изучения запросов и поиска внутри страницы я узнал что список картинок находится внутри страницы, но как объект Javascript, а не как тег HTML, но его очень просто получить, для этого используется простенькая регулярка и парсер JSON.
Привожу весь рабочий код:
import requests
rs = requests.get('http://gepur.ru/product/plate-6916')
html = rs.text
# Ищем строку c описанием модели
import re
match = re.search(r'ProductPage\.init\((.+)\)', html)
if not match:
print('Не получилось вытащить описание модели')
quit()
# Вытаскиваем объект js из параметра функции init
json_text = match.group(1)
# Парсим его как JSON
import json
json_data = json.loads(json_text)
# Вытаскиваем список ссылок на картинки
for url_img_rel in json_data['getImages']['originImg']:
from urllib.parse import urljoin
url_img = urljoin('http://gepur.ru', url_img_rel)
print(url_img)
Консоль:
http://gepur.ru/products/10000/6916/simple/origins/6916_1.jpg
http://gepur.ru/products/10000/6916/simple/origins/6916_2.jpg
http://gepur.ru/products/10000/6916/simple/origins/6916_3.jpg
А для http://gepur.ru/product/plate-6917 в консоли будет:
http://gepur.ru/products/10000/6917/simple/origins/6917_1.jpg
http://gepur.ru/products/10000/6917/simple/origins/6917_2.jpg
http://gepur.ru/products/10000/6917/simple/origins/6917_3.jpg
http://gepur.ru/products/10000/6917/simple/origins/6917_4.jpg
http://gepur.ru/products/10000/6917/simple/origins/6917_5.jpg
http://gepur.ru/products/10000/6917/simple/origins/6917_6.jpg
Есть еще один способ их получить, судя по запросам, нужно после прогрузки в рамке текущей сессии отправить POST запрос на http://gepur.ru/ajax/last-viewed и вернется JSON, похожий на тот, что был на самой странице при ее загрузке (непонятно даже зачем такое сделали, ведь данные уже есть).
Код будет такой:
import requests
session = requests.session()
# Нам нужны куки чтобы второй запрос был удачным
rs = session.get('http://gepur.ru/product/plate-6917')
print(rs)
rs = session.post('http://gepur.ru/ajax/last-viewed', headers={'X-Requested-With': 'XMLHttpRequest'})
print(rs)
# Текст нужно распарсить модулем json как сделано в примере выше
print(rs.text)
| {
"pile_set_name": "StackExchange"
} |
Q:
Select query to retrieve rows with null values
I need to retrieve data from a table even if one of the fields has null value. Here's an example:
Select name, SUM(credit) as credit
From expenses
Where name like 'vendor0%'
and date like '2013%'
Group by name
Order by name asc
This example retrieves name and SUM(credit) only when credit has values. I need to retrieve all from name even if credit has no value at all.
Is this possible?
A:
This example retrieves only "name" and the "SUM(credit)", when the
"credit" has values.
The query you presented will retrieve a row for every present name, even if all associated credit columns are NULL. You get a row with a NULL value for SUM(credit) then. Null values are just ignored by the aggregate function sum():
You only get no row for a particular name if no row for that name exists in the table expenses for the given WHERE expressions.
I am assuming you want
.. only names matching 'vendor0%'
.. but all of those, even if they have no expenses in 2013.
Your query could work like this:
SELECT name, SUM(CASE WHEN date LIKE '2013%' THEN credit END) AS credit
FROM expenses
WHERE name LIKE 'vendor0%'
GROUP BY name
ORDER BY name
CASE defaults to NULL if no ELSE branch is given.
Aside: You shouldn't store date / time values as text. Use an appropriate type, it has many advantages.
And don't use "name" or "date" as identifiers. "name" is not a descriptive name and "date" is a reserved word in standard SQL and a function and base type name in Postgres.
| {
"pile_set_name": "StackExchange"
} |
Q:
frequency count for file column in bash
I have a file with 8 columns using "|" as a delimiter and I want to count the occurence frequency of the words in the 8th column. I tried awk like this
awk -F '{print $8}' | sort | uniq -c $FILE
but I get instead a print of the whole file and I can't understand what I am doing wrong.
EDIT: Now I get printed what I want as below:
1
2307 Internet Explorer
369 Safari
2785 Chrome
316 Opera
4182 Firefox
but I can't understand where this "1" come from
A:
Among other things, you're running uniq on $FILE instead of running awk on $FILE and piping the results to sort then uniq. You meant to write:
awk -F'|' '{print $8}' "$FILE" | sort | uniq -c
but all you need is one command:
awk -F'|' '{cnt[$8]++} END{for (key in cnt) print cnt[key], key}' "$FILE"
wrt I can't understand where this "1" come from - you have 1 empty $8 in your input file. Maybe a blank line. You can find it with:
awk -F'|' '$8~/^[[:space:]]*$/{print NR, "$0=<"$0">, $8=<"$8">"}' "$FILE"
A:
You can just awk to do this:
awk -F '|' '{freq[$8]++} END{for (i in freq) print freq[i], i}' file
This awk command uses | as delimiter and uses an array seen with key as $8. When it finds a key $8 increments the frequency (value) by 1.
Btw you need to add custom delimiter | in your command and use it like this:
awk -F '|' '{print $8}' file | sort | uniq -c
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best way to to store data that the majority of classes in a program use?
To explain, i'm creating a simple game in Java using Swing. The size of the JFrame used is needed in a good deal of my classes. At first i just made a super class to contain the variables, but i am forced to find something different because Java only lets you extend once, and i need to use the super class for different reasons. If that makes sense.
I'm storing multiple instances of the same information in memory.
Variables such as:
JFrame height and width in pixels and tiles
Map height and width in pixels and tiles
"Tile" height and width
Here's some code to paint the picture better:
protected static int SCREEN_WIDTH = 928;//Pixels
protected static int SCREEN_HEIGHT = 672;//Pixels
protected static int TILE_WIDTH = 32;//Pixels
protected static int TILE_HEIGHT = 32;//Pixels
protected int MAP_WIDTH = 1280;//Pixels
protected int MAP_HEIGHT = 1280;//Pixels
protected int MAP_WIDTHtile = MAP_WIDTH / TILE_WIDTH;
protected int MAP_HEIGHTtile = MAP_HEIGHT / TILE_HEIGHT;
protected static int XTILES = SCREEN_WIDTH / TILE_WIDTH;//how many tiles can fit on display x axis;
protected static int YTILES = SCREEN_HEIGHT / TILE_HEIGHT;//how many tiles can fit on display y axis;
protected ArrayList<BufferedImage> images;
protected ArrayList<ArrayList<Integer>> displayArray2;
protected ArrayList<ArrayList<Integer>> mapGlobal2;
protected static int xIndex = 0;
protected static int yIndex = 0;
Almost all of those variables are needed multiple classes throughout my entire program. And i'm declaring it multiple times as a result. I can't help but think i'm implementing this horribly and there has got to be a better way to do it. I also feel as though passing all this information through as parameters to class constructors isn't the best route.
A:
Create a class just for those variables, instantiate it once and pass it around your code.
Make it static if there is only ever one instance.
You might even start adding methods so as to manipulate the data better.. ;-)
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript command insertion HTML
I want to create a JavaScript Command Execution ..
I mean, if I build up a page, with an input method, then, the value of that input method is executed in the JavaScript console, then, the result of that execution should be inserted in an HTML tag as:
HTML:
<input id="commandInsertion"/>
<input type="Submit" onclick="doCommand()">
<p id="result"></p>
JavaScript:
var doCommand = function(x) {
// The command should be something like this
Execute(x); // Imaginary Function
document.getElementById('result').innerHTML = ResultOf(x);
// ResultOf() is also an imaginary function
};
doCommand is a function that executes a command and then, prints it into the document
A:
What I got from your explaining that you need some thing such as the following:
function getInsertedValue() {
var txt = document.getElementById('commandInsertion').value;
updateElem(txt);
}
function updateElem(insertedTxt) {
document.getElementById("updatedTxt").innerHTML = eval(insertedTxt);
}
<div>
<input type="text" id="commandInsertion" />
<span id="updatedTxt"></span>
<input type="Submit" onclick="getInsertedValue()">
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
ImageMagick composite resizes image before composing
I'm using ImageMagick's composite command to compose one smaller image over larger one. The resulting image should be of size of the background image (the larger one). Additionally I want the smaller one to be always of the same size.
Currently I have such a simple invocation:
composite -gravity SouthWest watermark.png photo.jpg photo.jpg
The problem is that I get different sizes of watermark for different photos and I don't know how to set it to be fixed size. I tried -resize, -geometry and -size options but all of them change size of resulting image and not the watermark.
A:
I had a similar problem and tried all sorts of different options with the composite command to try to get it to work. Eventually I had to switch to using the convert command and was able to get it to resize with gravity using:
convert photo.jpg -gravity SouthWest -draw "image Over 0,0,200,200 watermark.png" photo.jpg
The numeric parameters for -draw are left,top,width,height. See http://www.imagemagick.org/script/command-line-options.php?#draw. So this solution no longer uses the composite command but hopefully gives you what you want.
A:
Hurraaay!
I have found the answer from a little note in the ImageMagick manual that says -resize '1x1<' is essentially a no-op (and SHORT-CIRCUIT) for the resize operation.
So, if I have a 1200x1200 image.jpg and I overlay it with a 600x600 copyright.png, using this command:
composite -dissolve 50% -gravity center image.jpg copyright.png result.jpg
my image gets resized to 600x600 as per the copyright.png.
However, if I do the following:
composite -resize '1x1<' -dissolve 50% -gravity center image.jpg copyright.png result.jpg
my output image retains its orginal size of 1200x1200.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.