text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
swift firebase retrieving data error
My if is not working
feelingRef.child("conditions/needsattention").observeEventType(.Value) { (snap: FIRDataSnapshot) in
print((snap.value?.description)!)
if (snap.value?.description)! == 1 {
self.conditionLabel.text = "관심필요"
}
}
when I print snap's value it prints 1 but if is not working!!!
A:
It can be a String type so check with dynamicType of your variable
print(snap.value!.description.dynamicType)
if (snap.value!.description)! == "1" {
self.conditionLabel.text = "관심필요"
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to login the super user(root) in remote host system using pexpect?
How to login the super user(root) in remote host system using pexpect?
user = root user
password = 'pass'
child = pexpect.spawn('ssh %s@%s'%(user,host,))
A:
i will get answer
child = pexpext.spawn('ssh root@host')
| {
"pile_set_name": "StackExchange"
} |
Q:
Best way to using Global Variables in PowerShell?
I want to use variables over PowerShell instances away.
(I know that global variables are not nice)
Is this the best way to define a variable over instances in PowerShell? Other ideas?
($global:variable is not over PowerShell instances away)
[Environment]::SetEnvironmentVariable("TestVariable", "Test value.", "User")
[Environment]::GetEnvironmentVariable("TestVariable","User")
A:
Yes. Other options would be to:
Write/read a hashtable to a settings file using Export/Import-CliXml.
Stash information in the user's registry hive.
But adding a user environment variable is also a good way to go and the way you suggest is what is needed for the environment changes to survive exiting the current PowerShell session.
| {
"pile_set_name": "StackExchange"
} |
Q:
MYSQL - Performance issues when callin a function several times inside a view
I encountered a situation in which I have to call a function several times inside a view. something like:
select a,b,c, GetRefund(a) AS REFUND, d-GetRefund(a) AS Payment_left FROM bla bla bla.
Obviously I can't join the refunds table to this view (or else I'd do it).
It seems the explain plan doesn't consider the function's cause no matter how many times I use them, explain looks the same.
What I'm asking is - does MYSQL optimize this and actually call the function a single time?
is there a better solution for doing this?
Thank you very much!
A:
No. MySQL calls this function twice for each selected row
Is there a better solution? We'd need to know a bit more about your database structure, but something like this should reduce it to one function call per row:
SELECT
a,b,c, REFUND, d-REFUND AS PaymentLeft
FROM (
select a,b,c,d, GetRefund(a) AS REFUND FROM bla bla bla
) AS sq
| {
"pile_set_name": "StackExchange"
} |
Q:
ActiveRecord serialize not working properly with Hash column
I'm trying to store a Hash in a table column, using ActiveRecord's serialize method but I can't make it work. I'm using Rails 4.2.0 and RailsApi 0.3.1
This is my model:
class Agreement < ActiveRecord::Base
serialize :phone_numbers, Hash
end
phone_numbers is a text column like it's required.
Then in the console:
a = Agreement.new(phone_numbers: {"dario" => "12345"})
a.phone_numbers
=> "{\"dario\"=>\"12345\"}" #(Note this is a string, not a Hash as I would expect)
a.phone_numbers["dario"]
=> "dario" #(Not "12345" as I would expect)
Am I missing soemthing?? Thank you!
A:
The behavior you're showing is consistent with the serialize call being wrong, either misnamed column, or missing entirely. Eg. https://gist.github.com/smathy/2f4536d3e59b7a52c855
You're showing the right code in your question, so either you didn't copy-paste that correctly, or perhaps it you haven't restarted your rails console since adding/correcting that serialize call?
| {
"pile_set_name": "StackExchange"
} |
Q:
Border with text
please help to me to make a border with text for my images. I have attached a picture for reference.
A:
Use the rectangle tool (with a stroke and no fill) to create a little box over the image:
Rasterize the layer (Right click on the layer → Rasterize)
Add some text on a new layer
Now use the Rectangular Marquee Tool (M) to select and cut out an area from the bottom of the rectangle (a little larger then your text)
Final result:
Just for fun, some other variations:
If all of your images are the same size, you can create the whole border and merge it into one layer, then just copy the whole layer and paste it on top of every image.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Django: Handling URL with Google App Engine - Post then Get
I have something like this set up:
class CategoryPage (webapp.RequestHandler):
def get(self):
** DO SOMETHING HERE **
def post(self):
** DO SOMETHING HERE **
** RENDER THE SAME AS get(self)
The question is, after I process the posted data, how would I be able to display the same information as the get(self) function?
A:
A redirect, as others suggest, does have some advantage, but it's something of a "heavy" approach. As an alternative, consider refactoring the rendering part into a separate auxiliary method def _Render(self): and just ending both the get and post methods with a call to self.Render().
| {
"pile_set_name": "StackExchange"
} |
Q:
ComboBox in UserControl. setup the data binding
I have a combobox in a user control and i want to data bind it but the only things i have access to in the properties menu of the visual studio 2008 designer view is the data source and display member. Is there a way to setup the usercontrol so i can edit the selected value member in the properties menu too?
[System.ComponentModel.ComplexBindingProperties("DataSource", "DisplayMember")]
public partial class CustomComboBox : UserControl
{
private object dataSource;
private string displayMember;
[AttributeProvider(typeof(IListSource))]
public object DataSource
{
get
{
return this.dataSource;
}
set
{
this.dataSource = value;
}
}
public String DisplayMember
{
get
{
return this.displayMember;
}
set
{
this.displayMember = value;
}
}
public CustomComboBox()
{
InitializeComponent();
}
private void BindComboBox()
{
if (this.dataSource == null || this.displayMember == null)
{
return;
}
Binding binding = new Binding("DataSource", this.dataSource, this.displayMember, true);
Binding binding2 = new Binding("DisplayMember", this.dataSource, this.displayMember, true);
this.comboBox1.DataBindings.Clear();
this.comboBox1.DataBindings.Add(binding);
this.comboBox1.DataBindings.Add(binding2);
}
}
A:
I ended up adding a property for every field i wanted to edit and added [Browsable(true)] above all the properties. This let me edit everything as a text field in the properties menu.
| {
"pile_set_name": "StackExchange"
} |
Q:
Assert module use in nodejs?
Hello everyone I was reading node official documentation, and I've seen the "Assert" module, but don't understand its use, my conclutions up to now are that is like the (try--catch) of some languages, the examples on official documentation are not enough for me to understand the module, could you guys help me please?
A:
These would be used for unit testing.
This module is used for writing unit tests for your applications, you can access it with require('assert').
http://nodejs.org/api/assert.html
The goal of a unit test is to test individual units of your code.
For example, to test a function, you give it the input and know what output to expect. This will isolate that function so you can be sure there is not an error in other parts of your code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Applying an option to all opened files in Vim
I do a vimdiff on 2 files. Now if I want to wrap 2 files then I need to apply :set wrap 2 times to each file separately.
Is there any way I can apply set wrap to both of them simultaneously without running same command twice?
A:
windo does exactly what you want:
:windo set wrap
If you have multiple tabs, there is an equivalent tabdo to handle that case.
:tabdo set wrap
| {
"pile_set_name": "StackExchange"
} |
Q:
Отправка сообщений
Здравствуйте!
Подскажите, пожалуйста, как можно реализовать отправку сообщений, а конкретно по варианту, как в соц сетях: прочитал пользователь или не прочитал его. Если есть какой-нибудь туториал на эту тему, то подкиньте, пожалуйста. Желательно, при помощи jQuery ajax чтобы было. Заранее спасибо!
A:
В таблице БД, в которой сохраняются сообщение, добавляется поле для хранения статуса прочтения. Соответственно, если пользователь сообщение открыл - считаем его прочитанным и обновляем статус. В vk.com сообщение считается прочитанным, если пользователь начал набирать ответ или провел над сообщением курсором.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculating cosine distance between the rows of matrix
I'm trying to calculate cosine distance in python between the rows in matrix and have couple a questions.So I'm creating matrix matr and populating it from the lists, then reshaping it for analysis purposes:
s = []
for i in range(len(a)):
for j in range(len(b_list)):
s.append(a[i].count(b_list[j]))
matr = np.array(s)
d = matr.reshape((22, 254))
The output of d gives me smth like:
array([[0, 0, 0, ..., 0, 0, 0],
[2, 0, 0, ..., 1, 0, 0],
[2, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[1, 0, 0, ..., 0, 0, 0]])
Then I want to use scipy.spatial.distance.cosine package to calculate cosine from first row to every other else in the d matrix.
How can I perform that? Should it be some for loop for that? Not too much experience with matrix and array operations.
So how can I use for loop for second argument (d[1],d[2], and so on) in that construction not to launch it every time:
from scipy.spatial.distance import cosine
x=cosine (d[0], d[6])
A:
You said "calculate cosine from first row to every other else in the d matrix" [sic]. If I understand correctly, you can do that with scipy.spatial.distance.cdist, passing the first row as the first argument and the remaining rows as the second argument:
In [31]: from scipy.spatial.distance import cdist
In [32]: matr = np.random.randint(0, 3, size=(6, 8))
In [33]: matr
Out[33]:
array([[1, 2, 0, 1, 0, 0, 0, 1],
[0, 0, 2, 2, 1, 0, 1, 1],
[2, 0, 2, 1, 1, 2, 0, 2],
[2, 2, 2, 2, 0, 0, 1, 2],
[0, 2, 0, 2, 1, 0, 0, 0],
[0, 0, 0, 1, 2, 2, 2, 2]])
In [34]: cdist(matr[0:1], matr[1:], metric='cosine')
Out[34]: array([[ 0.65811827, 0.5545646 , 0.1752139 , 0.24407105, 0.72499045]])
If it turns out that you want to compute all the pairwise distances in matr, you can use scipy.spatial.distance.pdist.
For example,
In [35]: from scipy.spatial.distance import pdist
In [36]: pdist(matr, metric='cosine')
Out[36]:
array([ 0.65811827, 0.5545646 , 0.1752139 , 0.24407105, 0.72499045,
0.36039785, 0.27625314, 0.49748109, 0.41498206, 0.2799177 ,
0.76429774, 0.37117185, 0.41808563, 0.5765951 , 0.67661917])
Note that the first five values returned by pdist are the same values returned above using cdist.
For further explanation of the return value of pdist, see How does condensed distance matrix work? (pdist)
A:
You can just use a simple for loop with scipy.spatial.distance.cosine:
import scipy.spatial.distance
dists = []
for row in matr:
dists.append(scipy.spatial.distance.cosine(matr[0,:], row))
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ Multi threaded directory scan code
I was looking how to write a multi threaded C++ code for scanning directory and get list of all files underneath. I have written a single threaded code which can do and below the code which can do that.
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>
#include <sys/stat.h> /* for stat() */
using namespace std;
int isDir(string path)
;
/*function... might want it in some class?*/
int getdir (string dir, vector<string> &dirlist, vector<string> &fileList)
{
DIR *dp;
struct dirent *dirp, *dirFp ;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
if (strcmp (dirp->d_name, ".") != 0 && strcmp(dirp->d_name, "..") != 0) {
//dirlist.push_back(string(dirp->d_name));
string Tmp = dir.c_str()+ string("/") + string(dirp->d_name);
if(isDir(Tmp)) {
//if(isDir(string(dir.c_str() + dirp->d_name))) {
dirlist.push_back(Tmp);
getdir(Tmp,dirlist,fileList);
} else {
// cout << "Files :"<<dirp->d_name << endl;
fileList.push_back(string(Tmp));
}
}
}
closedir(dp);
return 0;
}
int isDir(string path)
{
struct stat stat_buf;
stat( path.c_str(), &stat_buf);
int is_dir = S_ISDIR( stat_buf.st_mode);
// cout <<"isDir :Path "<<path.c_str()<<endl;
return ( is_dir ? 1: 0);
}
int main()
{
string dir = string("/test1/mfs");
vector<string> dirlist = vector<string>();
vector<string> fileList = vector<string>();
getdir(dir,dirlist,fileList);
#if 0
for (unsigned int i = 0;i < dirlist.size();i++) {
cout << "Dir LIst" <<dirlist[i] << endl;
//string dirF = dir + "/" + dirlist[i];
//getdir(dirF,fileList);
}
#endif
for (unsigned int i = 0; i < fileList.size(); i++)
cout << "Files :"<<fileList[i]<< endl;
return 0;
}
Now issue is that it is single threaded and I need to scan say about 8000 directories under which file can be present. So I am not getting how to do so as number of directories can vary as it is decided by N dimension matrix.
Any help in this regard will be great. Thanks in advance.
A:
boost::filesystem has directory_iterator and recursive_directory_iterator, the former will get all the contents of a directory but not recurse sub-directories, the latter will also recurse subdirectories.
With regard to thread-safety, you could lock a mutex then copy the results into a std::vector or two vector instances, one for files and one for directories, in which case you will at least have a local snapshot copy.
To actual "freeze" the file-system at that point to stop any process modifying it is not something you can normally do - well you could try setting the file attributes on it to read-only then change it back later but you will need to have permission to do that first.
| {
"pile_set_name": "StackExchange"
} |
Q:
Infinite for loop in golang
I'm new to Golang, but I would expect not to have issues with something as basic as this.
package main
import "fmt"
func main() {
s := make([]int, 0)
s = append(s, 1)
for len(s) != 0 {
j := len(s) - 1
top, s := s[j], s[:j]
fmt.Printf("top = %+v\n", top)
fmt.Printf("s = %+v\n", s)
fmt.Printf("len(s) = %+v\n", len(s))
}
}
This command doesn't exit, it just prints
len(s) = 0
top = 1
s = []
len(s) = 0
top = 1
s = []
len(s) = ^C
I find this stunning; what am I doing wrong? Syntactically, based on https://tour.golang.org/flowcontrol/3, everything seems OK.
A:
When you use :=, you declare new variables. An s is created inside the loop unrelated to the s outside it. Assign instead:
for len(s) != 0 {
j := len(s) - 1
var top int
top, s = s[j], s[:j]
fmt.Printf("top = %+v\n", top)
fmt.Printf("s = %+v\n", s)
fmt.Printf("len(s) = %+v\n", len(s))
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Change every other letters font color? (JavaScript)
I'm trying to create a Christmas user group on my forums, and would like to replace the users name with a green/red pattern using JavaScript. So basically, JavaScript would turn every other letter within a specific CSS class into green, and the others would stay red.
So this is what it looks like now:
<span class="style6">Username</span>
I'd like JavaScript to turn it into something like this:
<span class="style6">
<span class="color_red">U</span>
<span class="color_green">s</span>
<span class="color_red">e</span>
<span class="color_green">r</span>
<span class="color_red">n</span>
<span class="color_green">a</span>
<span class="color_red">m</span>
<span class="color_green">e</span>
</span>
A:
In pure JavaScript without jQuery dependency.
var elements = document.querySelectorAll('.style6');
for(var i=0,l=elements.length;i<l;++i) {
var str = elements[i].textContent;
elements[i].innerHTML = '';
for(var j=0,ll=str.length;j<ll;++j) {
var n = document.createElement('span');
elements[i].appendChild(n);
n.textContent = str[j];
n.style.color = (j % 2) ? 'red' : 'green';
}
}
If you have/need/want to use classes instead of setting the color attribute directly, then swap the following lines
n.style.color = (j % 2) ? 'red' : 'green'; //Swap This
n.classList.add((j % 2) ? 'color_red' : 'color_green'); //With This
Basically, we grab all elements with style6, and then loop through each. For each element we grab the username string and loop through each character. For each character, you create a new span, append it to the element, give it the character, and finally a color.
Let me know if you have any questions.
jsfiddle here
A:
EDIT - sorry, I just saw that you didn't have jQuery tagged on your question. If you can use it, the below should get you close.
var textToChange = $(".style6").text();
for(var i = 0; i < textToChange.length; i++) {
var newSpan = $("<span />")
.text(textToChange[i])
.css("color", i % 2 == 0 ? "green" : "red");
$("#divToAddThisTo").append(newSpan);
}
You'll need to traverse the text, and append a new span with the desired css color set alternately to red or green.
You can access individual characters of a string by indexing it, just like in c#. So if var str = "Adam" then str[0] would equal 'A'
Also, the ? operator is known as the conditional operator, or ternary operator. It simplifies the writing of if else statements, where either branch results in the assignment of the same variable. For example:
var x, y = 1;
x = y == 1 ? "one" : "not one";
Is the same as
if (y == 1)
x = "one";
else
x = "not one";
A:
As long as your <span> doesn't contain any HTML you could do this.
$('.style6').each(function(){
var letters = $(this).text().split('');
$(this).text('');
for(var i = 0; i < letters.length; i++){
if(i % 2 == 0){
$(this).append('<span class="color_red">' + letters[i] + '</span>');
}
else{
$(this).append('<span class="color_green">' + letters[i] + '</span>');
}
}
});
It would be a bit more complicated if your <span> did contain HMTL.
Edit: This is with jQuery BTW. Not sure if that is OK.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to cast entity to set in PostgreSQL
Using Postgres 9.3, I found out that I can perform something like this:
SELECT generate_series(1,10);
But I can't do this:
SELECT (SELECT generate_series(1,10));
Can I somehow cast SELECT result to setof int to use it same as result from generate_series()?
What exactly is happening there why I can use result from function but not from SELECT?
A:
Your first form is a non-standard feature of Postgres. It allows SRF (Set Returning Functions) in the SELECT list, which are expanded to multiple rows:
Is there something like a zip() function in PostgreSQL that combines two arrays?
Note: that's working for functions, not for sub-selects. That's why your second SELECT is simply invalid syntax.
Standard SQL does not have a provision for that at all, so the feature is frowned upon by some and clean alternatives have been provided (thanks to improvements in the SQL standard). It is largely superseded by the LATERAL feature in Postgres 9.3+:
What is the difference between LATERAL and a subquery in PostgreSQL?
The simple form can be replaced by:
SELECT g
FROM generate_series(1,10) g;
Whenever possible move SRF to the FROM clause and treat them like tables - since version 9.3 that's almost always possible.
Note that g serves as table and column alias automatically in the example. g in SELECT g binds to a column name first. More explicit syntax:
SELECT g
FROM generate_series(1,10) AS t(g); -- table_alias(column_alias)
You need to understand the difference between a row, a set of rows (~ a table) and an array. This would give you an array of integer:
SELECT ARRAY(SELECT g FROM generate_series(1,10) g) AS g_arr;
Browse the tags generate-series and set-returning-functions for many related answers with code examples.
| {
"pile_set_name": "StackExchange"
} |
Q:
Presentational js vs. functional js: Separate them? General architecture?
This is a general kind of question.
Very often, I need to write JavaScript for web pages. Keeping in mind best practices, unobtrusive js, etc. I have my JavaScript in separate *.js files. Every page gets its own js file. What's been somewhat bothering me lately, is the mix of presentational code with functional code that I always end up with.
So, for example, I would assign a .click handler to an element. On that click the element must change its appearance and an AJAX call must be made to the server. So, right now, I'd do both of these things inside that .click handler. It might get bulky depending on what needs to be accomplished. When I come back to these blocks of code after not touching them for a week, I often feel like it takes away too much time to trace through all lines of code when I only need to fix something with appearance.
Anyway, any idea on architecture/design for presentational js vs. functional js? Keep them in one file, but break into separate functions? Break them into 2 separate files? Leave them alone?
A:
I would tend to keep them all together that are related regarding the event that kicked them off, but sometimes put a function in to call to do a specific group of things.
Example:
function domyUIstuff(myevent, myselector)
{
// stuff here
};
function domyBehaviorStuff(myevent, myselector)
{
//dostuffhere
};
$(selector).click(function(e)
{
domyUIstuff(e,$(this));
domyBehaviorStuff(e,$(this));
};
Side note: I do keep stuff separate (I do a lot of asp.net stuff) from different user controls - I create a myusercontrol.js file for my myusercontrol.ascx as well as a mypage.js file for my mypage.aspx which tends to cut down on the "noise" when I debug - I put my "generic" functions in the page file that I might call from my controls such as generic ajax message handlers or generic "utility" functions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - match dictionary value within string & print key in string order
I asked a similar question to this earlier on but Im still having a hard time figuring this out. I have the following code:
d = {'k' : '10', 'a' : '20', 'r' : '30', 'p' : '401'}
string = '401203010'
text = ''
for i, j in d.items():
if j in string:
text += i
print(text) #prints karp
desired output: park
the output I get is karp, however I would like the output to be in order of value match in the string, Thanks!
A:
try this maybe?
d = {'k' : '10', 'a' : '20', 'r' : '30', 'p' : '40'}
string = '40203010'
text = ''
keylen = len(''.join(d.keys()))
while len(text) != keylen:
found_val = 0
for i, j in d.items():
jl = len(j)
if string[:jl] == j:
text += i
string = string[jl:]
found_val += 1
if found_val == 0:
break
print(text)
for the sake of clarity, this is really not an algorithm you want to use here. For example one of the downfalls is if it isn't guaranteed that a part of the string will be in the dictionary values then the loop will never end. I don't want to spend the mental resources to fix that potential pitfall because I have some reading to do but perhaps you can figure out a way around it.
edit, never mind that wasn't that difficult but you should test various edge cases.
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.net hyperlink tilde ~ URLs not rendering as expected
Given the following code:
var link = new HyperLink();
link.NavigateUrl = "~/manual/subdir";
This has started rendering on the site as:
<a href="manual/subdir">
And not as:
<a href="/manual/subdir">
As expected. Is there any web.config setting or other setting that changes this behaviour?
A:
Try this:
link.NavigateUrl = Page.ResolveUrl("~/manual/subdir");
It will set navigate url relative to the website root.
| {
"pile_set_name": "StackExchange"
} |
Q:
append values in a dataframe column
Hello I am New to Pandas, and i have a situation in hand where I Have the dataframe
such as below:
and I want to add another column to the dataframe which makes it look like below:
enter image description here
Can someone kindly help. I have tried my ways to convert it into dictionary and print values but that is not giving me the output in this form.
A:
I think need GroupBy.transform for joined values to new column as strings:
df['col 5'] = (df.groupby(['col 1','col 2','col 3'])['col 4']
.transform(lambda x: ','.join(x.astype(str))))
print (df)
col 1 col 2 col 3 col 4 col 5
0 A B C 25 25,22,23,45
1 A B C 22 25,22,23,45
2 A B C 23 25,22,23,45
3 A B C 45 25,22,23,45
4 P Q R 9 9,109,20
5 P Q R 109 9,109,20
6 P Q R 20 9,109,20
If need lists use join:
df = df.join(df.groupby(['col 1','col 2','col 3'])['col 4']
.apply(list).rename('col 5'), on=['col 1','col 2','col 3'])
print (df)
col 1 col 2 col 3 col 4 col 5
0 A B C 25 [25, 22, 23, 45]
1 A B C 22 [25, 22, 23, 45]
2 A B C 23 [25, 22, 23, 45]
3 A B C 45 [25, 22, 23, 45]
4 P Q R 9 [9, 109, 20]
5 P Q R 109 [9, 109, 20]
6 P Q R 20 [9, 109, 20]
| {
"pile_set_name": "StackExchange"
} |
Q:
¿Cómo comparar date en jpql?
Tengo un proyecto web con Java 8, Apache Tomcat y Postgresql 9.3 y necesito comparar los dates, este es el código delo controlador:
public Curso findCursoByFechaInicio(Date inicio) {
EntityManager em = getEntityManager();
try {
Curso p = (Curso) em.createQuery("SELECT c FROM Curso c WHERE c.iniciocurso=" + inicio).getSingleResult();
return p;
} catch (Exception e) {
return null;
} finally {
em.close();
}
}
El iniciocurso es de tipo Date de java.Util.Date y cuando le paso el Date de inicio con los mismos valores de uno que existe en la base de datos (lo compruebo durante el debbug) lanza una excepcion en la consulta.
A:
La query que estas creando es un String normal al que encadenas el "toString" del objeto Date "inicio". Probablemente el resultado del "toString" de este objeto Date no coincida con el formato de la fecha en la BBDD.
Lo mejor para evitar estos casos es dejar la transformación del objeto date al formato de la base de datos al ORM que estés usando.
Puedes probar a construir la query con un parámetro dinámico e informarlo a después.
Query query = em.createQuery("SELECT c FROM Curso WHERE c.iniciocurso= :fechaInicio");
query.setParameter("fechaInicio", fechaInicio);
Curso p = query.getSingleResult();
Al poner ":nombreVariable" el entity manager sabe que es un parámetro que tendrá que manejar.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to assign values to a slice in a pandas data frame
I have to reassign a reassign a column value for specific rows based on state. The data frame I am working with has only two columns, SET VALUE and AMOUNT, with STATE being in the index. I need to change the value of SET VALUE to 'YES' for the 3 customers with the highest value in the AMOUNT column for each state. How can I do this in the pandas framework?
I have attempted to use a for loop on the state in the index and then sort by AMOUNT column values and assign 'YES' to the first three rows in the SET VALUE column.
for state in trial.index:
trial[trial.index == state].sort_values('AMOUNT', ascending = False)['SET VALUE'].iloc[0:3] = 'YES'
print(trial[trial.index == state])
I am expecting the print portion of this loop to include 3 'YES' values but instead all I get are 'NO' values (the default for the column). It is unclear to me why this is happening.
A:
I would advise against repeated index for various reasons. This case being one, as it is harder for you to update the rows. Here's what I would do:
# make STATE a column, and index continuous numbers
df = df.reset_index()
# get the actual indexes of the largest amounts
idx = df.groupby('STATE').AMOUNT.nlargest(3).index.get_level_values(1)
# update
df.loc[idx, 'SET_VALUE'] = 'YES'
| {
"pile_set_name": "StackExchange"
} |
Q:
c: assignment used in calculation
I have a question that I'd love to google but I have no idea on what to ask her/she/it (google :) )
Having found assignments like this in several example codes (this particular one originated here where they copied the code from the Numerical Recipes in C p. 508) on the net.
I tried to understand the usage of the assignment in the following line:
wr = (wtemp = wr) * wpr - wi * wpi + wr;
as far as my own understanding of programming logic goes, I would translate it to
wtemp = wr;
wr = wtemp * wpr - wi * wpi + wr;
is that correct? or should it be wpr * wpr - wi [...]? or something completely different :D?
(according to wikipedia the assignment operator returns a reference to the assignee, which according to the free dictionary - i checked to be sure - is the value which something is being assigned to)
A:
The value of the expression a = b is the value of a after assignment, so:
wr = (wtemp = wr) * wpr - wi * wpi + wr;
is equivalent to:
wtemp = wr;
wr = wtemp * wpr - wi * wpi + wr;
or:
wtemp = wr;
wr = wr * wpr - wi * wpi + wr;
Reference:
6.5.16 Assignment operators
An assignment expression has the value of the left operand after the assignment (...).
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating table in PostgreSQL from R platform by using RPostgreSQL
I am using RPostgreSQL package to connect the db to R. I wanted to update the db with those tables do not exist in db.
Is it possible to create the new table from R in postgresql and update it with upcoming values?
Any suggestion?
Sample of data:
Date&Time temp
1 2007-09-30 00:00:00 -0.1153333
2 2007-09-30 01:00:00 -0.4006667
3 2007-09-30 02:00:00 -0.4493333
4 2007-09-30 03:00:00 -0.7540000
5 2007-09-30 04:00:00 -0.5783333
6 2007-09-30 05:00:00 -0.3280000
A:
We added a number of tests for automatic conversion of types to the package, see the source tarball. In particular, the conversion of SQL Datetime to POSIXct was a prime motivation for me to get the package started (as a GSoC project).
But we may simply not writing back the same way you did here. So if it complains about a missing converter for POSIXct, try converting the POSIXct column(s) to numeric, and then provide a reproducible example on the rpostgresql mailing list (see the code.google.com repo and wiki).
| {
"pile_set_name": "StackExchange"
} |
Q:
DbContext Not Found or A relational store has been configured without specifying either the DbConnection or connection string to use
when using Entity Framework Commands ("7.0.0-beta1").
when running
k ef migration add InitialCreate
i'm getting errors.
[Solution]
i try to move my Class File (where DbContext is created) to main project from separate class library and everything working as expected.
so the real problem is when using DbContext in separate Class Library.
my dbcontext file
public class DbTables : DbContext
{
public DbSet<class_name> class_name_alias { get; set; }
private static bool _created = false;
public DbTables()
{
if (_created)
{
Database.AsRelational().ApplyMigrations();
_created = true;
}
}
protected override void OnConfiguring(DbContextOptions options)
{
options.UseSqlServer(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=app_db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
A:
If you create a DBContext in a class library, to create migration you have to declare the ef command in the project.json of this class library. and run the k ef commmand for this project.
{
"version": "1.0.0-*",
"dependencies": {
"EntityFramework.SqlServer": "7.0.0-beta1",
"EntityFramework.Commands": "7.0.0-beta1"
},
"commands": {
"ef": "EntityFramework.Commands"
},
"frameworks" : {
"aspnet50" : {
"dependencies": {
}
},
"aspnetcore50" : {
"dependencies": {
"System.Runtime": "4.0.20-beta-22231"
}
}
}
}
You must override the on OnConfiguring method to set up a connection string
protected override void OnConfiguring(DbContextOptions options)
{
options.UseSqlServer(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=app_db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Scope of variables executing functions in a subshell
That's what happens when a command is executed in a subshell environment:
The command will run in a copy of the current shell execution environment
"Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes" (quote)
Example:
#!/bin/sh
export TOTO=123
FOO=abc
(mycmd)
In this case mycmd will be able to read TOTO but not FOO, and every changement realized by mycmd to the values of those two variables will not be visible in the current shell.
But what happens when we do the same thing with a function?
Example:
#!/bin/sh
export TOTO=123
FOO=abc
function (){
echo $TOTO
echo $FOO
TOTO=${TOTO}456
FOO=${FOO}def
}
(function)
echo $TOTO
echo $FOO
result:
123
abc
123
abc
Reasonably a function executed in a subshell is not able to alter the contents of the variables defined in the parent shell, on the other hand it is able to read all the variables indiscriminately even if they are not being exported.
Can somebody please explain this behaviour in a better way?
Links to some reference will be very appreciated since I couldn't find anything about it.
A:
What you are observing has nothing to do with functions. Subshells get all the environment, even the un-exported variables. To illustrate, let's define two variables:
$ alpha=123
$ export beta=456
Observe that a subshell has access to both:
$ (echo $alpha $beta)
123 456
If we start a new process, though, it only sees the exported variable:
$ bash -c 'echo $alpha $beta'
456
Documentation
man bash documents subshells as follows:
(list) list is executed in a subshell environment (see COMMAND
EXECUTION ENVIRONMENT below). Variable assignments and builtin
commands that affect the shell's environment do not remain in effect
after the command completes. The return status is the exit status of
list.
If we go look at the "COMMAND EXECUTION ENVIRONMENT", we find that it includes
shell parameters that are set by variable assignment or with set or inherited from the shell's parent in the environment.
In other words, it includes variables whether or not they have been exported.
If we read further, we find that this is in contrast to "a simple command other than a builtin or shell function." Such commands only receive the exported variables.
| {
"pile_set_name": "StackExchange"
} |
Q:
Stack variable and .contains(Object o)
Im having trouble keeping track of nodes in my stack. My nodes contain a 2d int array which contains numbers 0-20 as well as another integer measuring the cost to get to the current node state (2d int array).
currently i cant figure out how to track if my stack contains a node that i wish to skip since it is already in the stack or has been popped before so i avoid repeating the same compares on nodes that have the exact same state + costs.
if q is my stack and n1 is my current node i just popped, why wont
q.contains(n1);
ever return true?
I also tried making an ArrayList which creates a string for every node
Ex
1 2 4
5 3 6
0 7 8
Creates the string "1,2,4,5,3,6,0,7,8,". if i add this string to the array list and i use
aList.contains(stringKey); never returns true?
I think i have to do something with an object because the contains() requires an object to be passed, and im not 100% sure how to do this.
A:
The contains(obj) of any list returns true if it found obj in its list. It checks each object in list with the obj that you have provided with equals() method. So you need to override the equals() method of the object that you are using.
Example :
class MyObj {
int a;
char b;
MyObj(int a, char b) {
this.a = a; this.b = b;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof MyObj){
MyObj myobj = (MyObj) obj;
if(myobj.a == a && myobj.b == b){
return true;
}
}
return false;
}
}
Now it can be used in any List as here :
ArrayList<MyObj> list = new ArrayList<>();
MyObj obj = new MyObj(3, 'b');
list.add(obj);
System.out.println(list.contains(obj));
System.out.println(list.contains(new MyObj(3, 'b')));
Output :
true
true
According to good design pattern we should override hashCode() too when we decides to override equals().
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I say 'people insist on' in the passive voice?
If I have 'read guides where people insist that...' then how do I use that in the passive voice?
'In guides I have read, it is insisted that...'?
'In guides I have read, it is insisted upon that..'?
Or is it something different?
A:
If you really wanted to, you could say it is insisted that and you would have the support of at least one citation from the OED (Oxford English Dictionary). It is insisted upon that, however, has no such support. In any case, both sound very formal and are unlikely to be used in contemporary English.
A:
Here X is the thing insisted. For example, X could be "visitors to Italy must try the delicious local pizzas".
You could say, "There has been insistence that X". Or "That X has been insisted".
And your structure also works, "... it has been insisted that X".
You can prefix or postfix any of my examples with "In guides that I have read", "In some guides", and so on. For example:
In guides that I have read, it has been insisted that X.
It has been insisted that X in guides that I have read.
In some guides, there has been insistence that X.
It is insisted, in some guides, that X.
These are all acceptable, though some are awkward.
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL sort by average of two averages
I am working on a contest site where there are two types of users, normal site members, and judges. Each can use a drag and drop tool to order the entries in a particular contest in the order they choose. When they are done the relevant entry ids are attached a ranking value that can then be used to determine which entry in contest got the highest average score. The winner will actually be determined by the averaging the averages of each group.
What I hope to do is end up with a table showing EACH entry in a particular contest, with the title, and then show 3 values, avg_normal for that entry, avg_judge for that entry, and then those two values added together and divided by two, so the avg_normal and avg_judge each account for 50% of the avg_all. Finally, sort the table by avg_all.
avg_all = ((avg_normal + avg_judge) / 2)
They order entry_ids 1, 2, 3, 4, 5 in order. The ranking value starts at zero so:
entry_id, entry_ranking, author_id
1, 0, 1
2, 1, 1
3, 2, 1
4, 3, 1
5, 4, 1
I'm hoping to determine the averages on a scale of 1-100, so an entry ranking of 0 = 100 points, 1 = 90, 2 = 80, 3 = 70, and anything above 4 = 5 points
Each user is attached to a group in another table, so they are either a normal user, or a judge
I want to be able to write a query that finds
1.) The average NORMAL user vote score
2.) The average JUDGE user vote score
3.) The average of the NORMAL & JUDGE SCORE.
So Normal User average = 93.3333, Judge average = 70, Total Average = 81.66665
Thanks to the answers below, both queries work like a champ.
A:
Please note the following:
I've assumed that there is a field user_type in members which stores either 'NORMAL' or 'JUDGE'
I've removed the join to data and the group by of titles.title because I don't see how they're relevant to your averages.
.
SELECT
t.title,
AVG(CASE WHEN user_type = 'NORMAL' THEN IF (r.ranking_value = '0', 100, 0) + IF (r.ranking_value = '1', 90, 0) + IF (r.ranking_value = '2', 80, 0) + IF (r.ranking_value = '3', 70, 0) + IF (r.ranking_value = '4', 5, 0) END) AS avg_normal,
AVG(CASE WHEN user_type = 'JUDGE' THEN IF (r.ranking_value = '0', 100, 0) + IF (r.ranking_value = '1', 90, 0) + IF (r.ranking_value = '2', 80, 0) + IF (r.ranking_value = '3', 70, 0) + IF (r.ranking_value = '4', 5, 0) END) AS avg_judge,
(AVG(CASE WHEN user_type = 'NORMAL' THEN IF (r.ranking_value = '0', 100, 0) + IF (r.ranking_value = '1', 90, 0) + IF (r.ranking_value = '2', 80, 0) + IF (r.ranking_value = '3', 70, 0) + IF (r.ranking_value = '4', 5, 0) END) +
AVG(CASE WHEN user_type = 'JUDGE' THEN IF (r.ranking_value = '0', 100, 0) + IF (r.ranking_value = '1', 90, 0) + IF (r.ranking_value = '2', 80, 0) + IF (r.ranking_value = '3', 70, 0) + IF (r.ranking_value = '4', 5, 0) END)) / 2 AS avg_all
FROM rankings r
LEFT JOIN titles t
ON r.entry_id = t.entry_id
LEFT JOIN members m
ON t.author_id = m.member_id
WHERE r.contest_id IN ('CONTEST ID NUMBER')
GROUP BY
t.title
ORDER BY
avg_all;
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom arrow key navigation not working properly (one part works)
I have a large HTML table with dynamically added rows.
The table has a standard structure (incl. thead, tbody and tfoot).
Within this table there are editable TDs (which have the class "editable" and contain a contenteditable div) and non-editable TDs (which dont't have the class "editable" and do not contain a div).
I am trying to create a custom arrow key navigation that allows me to jump from one editable TD to next or previous one (like in an Excel table).
To test this I used the below example but this only works partially, i.e. the alerts are shown correctly but I am not able to do anything with the corresponding div (e.g. change its background or add a text etc.).
Can someone tell me what I am doing wrong here ?
My jQuery (in doc ready):
$(document).keydown(function(e){
switch(e.which){
case 37: // left arrow
alert('test left');
$(this).closest('td').prevUntil('td.editable').find('div').text('test');
break;
case 39: // right arrow
alert('test right');
$(this).closest('td').nextUntil('td.editable').find('div').text('test');
break;
default: // exit for other keys
return;
}
e.preventDefault(); // prevent default action
});
My HTML (example row):
<tr>
// ...
<td class="editable"><div contenteditable="true"></div></td> <!-- editable -->
<td class="editable"><div contenteditable="true"></div></td> <!-- editable -->
<td></td> <!-- non-editable -->
<td></td> <!-- non-editable -->
<td class="editable"><div contenteditable="true"></div></td> <!-- editable -->
// ...
</tr>
A:
this in your code refers do document not single element
if you use $(e.target) you can get single element
Also you should use next() function instead of nextUntil()
$(e.target).closest('td').nextAll('td.editable:first').find('div').text('test');
| {
"pile_set_name": "StackExchange"
} |
Q:
Delphi - Keep highlighted selection in RichEdit when focus is lost
I have an TRichEdit.
When I select some text and click on another element, the selection of the selected text disappears.
Is there a way to keep this selection, also when the TRichEdit has los it's focus?
Thanks!
A:
TRichEdit has a property HideSelection which is True by default. If set to False then the selection will still be visible even when the TRichEdit does not have focus.
BTW: the propery HideSelectionexists on other controls as well. It is also very usefull on a TListView or a TTreeView when you are showing details of the selected item in the listview or treeview.
| {
"pile_set_name": "StackExchange"
} |
Q:
Include Core CSS in one particular file in YII
I disabled core css file because it was intercepting with my custom css files:
$cs = Yii::app()->getClientScript();
$cs->scriptMap = array(
'*.css' => false,
);
Now, I need core css files in one view only.
Is there anyway to include those core css files in one view?
A:
You can do it like this
In config/main.php under components section
'clientScript'=>array(
'packages'=>array(
'CoreCss'=>array(
'baseUrl'=> 'css/' ,
'css'=>array('main.css','ie.css','form.css','screen.css','print.css'),
),
),
In any page you want to register this css use below lines..
$cs = Yii::app()->clientScript;
$cs->registerPackage('CoreCss');
may be this things can help you...
| {
"pile_set_name": "StackExchange"
} |
Q:
Optimized linear to sRGB GLSL
I'm currently using a simple implementation of linear to sRGB transform:
float sRGB(float x) {
if (x <= 0.00031308)
return 12.92 * x;
else
return 1.055*pow(x,(1.0 / 2.4) ) - 0.055;
}
vec3 sRGB_v3(vec3 c) {
return vec3(sRGB(c.x),sRGB(c.y),sRGB(c.z));
}
Possibly, that the correction for small values (x <= 0.00031308) will not matter in practice.
I considered to just let ´pow(x, 1.0 / 2.4) but I'm not sure how much impact it will have.
Is there any way to optimize it?
Can be vectorization help?
Can some polynomal fitting be better?
A:
A few days ago, I ran into this when messing around on Shadertoy. I was curious and some solutions to the various problems I faced, so I may as well post what I've made here for you.
Note, however, that I have never benchmarked this and I don't know how fast it works. But I've heard that different drivers/hardware/etc. implement sRGB conversion differently, so I wanted to make my own, correct implementation... And as far as I can tell, I succeeded. It does not use ifs and operates on entire color vectors at a time.
The trick with bvecs was learned from here. He says it won't work on most GLSL ES versions, but it seems to work well in the browsers I've tested (including Chrome on my Pixel). Still something to consider, especially since my uses are pretty limited (just making test images for my desktop, though I did test on my phone too).
I'm sure somebody could make a more optimal version that's just as accurate, especially as I'm very new to GLSL in general. However, since nobody was really giving you actual code (except to suggest x1/2.2 and the like), and my own code seemed to follow the general advice of avoiding branches, I figured I may as well post it.
// Converts a color from linear light gamma to sRGB gamma
vec4 fromLinear(vec4 linearRGB)
{
bvec4 cutoff = lessThan(linearRGB, vec4(0.0031308));
vec4 higher = vec4(1.055)*pow(linearRGB, vec4(1.0/2.4)) - vec4(0.055);
vec4 lower = linearRGB * vec4(12.92);
return mix(higher, lower, cutoff);
}
// Converts a color from sRGB gamma to linear light gamma
vec4 toLinear(vec4 sRGB)
{
bvec4 cutoff = lessThan(sRGB, vec4(0.04045));
vec4 higher = pow((sRGB + vec4(0.055))/vec4(1.055), vec4(2.4));
vec4 lower = sRGB/vec4(12.92);
return mix(higher, lower, cutoff);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Determining sampling rate in OFDM demodulation
I have seen that in OFDM, the sampling rate is much lesser than twice the bandwidth of signal. why is it so? How is sampling rate calculated in OFDM? Does it depend on the modulation type used inside like QAM or BPSK. Does it relate to FFT length by any chance.
A:
It is incorrect to say that the sample rate is "much less" than the bandwidth of the signal. It is true to say that it is a "little less". Even that statement is only true for part of the demodulator.
Demodulators almost always use a sample rate that is higher than the bandwidth for two reasons: to ensure that all of the signal is captured rather than aliased due to Nyquist frequency limitations, and to do some version of early/late gating when syncing with the symbols. It is very common to sample at twice the symbol rate because that is very convenient for capturing the symbols and doing early/late gating.
OFDM is different because of the FFTs/IFFTs built into the signal. There is no advantage for the demodulator to do the FFT at higher than the symbol rate, so they don't. The roll-off in OFDM is very minimal (an example of typical OFDM roll-off is shown below), though, so the sample rate is not much less than the bandwidth. In some schemes, like 802.11a, the outer frequency bins are not used which reduces the bandwidth of the signal relative to the sample rate, meaning that the sample rate will be higher than the bandwidth even when taking into consideration the signal roll-off.
Also, before the demodulator does the FFT it has to eliminate as much carrier offset as it can. This is typically done at a sample rate that is higher than the bandwidth for the same Nyquist reasons as a typical demodulator.
EDIT: I see that I forgot to answer some of your questions. The sample rate for OFDM is exactly equal to the sample rate that the OFDM transmitter used when it inverse FFT'ed the data. No, the sample rate has nothing to do with the modulation types used inside the OFDM symbols (e.g. BPSK or QPSK). No, the sample rate has nothing to do with the FFT length.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display contact form module in a block using drupal 7
Possible Duplicate:
Put Site-Wide Contact Form in a Block
I want to display the contact form in a sidebar of the website. Is it possible? Please help me.
A:
Check this answer which recommends to use Form Block module.
This could also be useful.
| {
"pile_set_name": "StackExchange"
} |
Q:
serialization/deserialization mechanism
Say, I have a class X which has a field value, that is,
class X implements Serializable {
private int value;
// ...
}
Further it has getters and setters not displayed here. This class is serialized.
At the deserialzation, end same class has value field and access specifier is public. Further, this class does not have getters and setters. So, my questions are:
Does deserialization fail in case the access specifier of the field changes OR some or all of the methods go missing in the class at the deserialization end?
What is the mechanism by which fields are assigned their values during deserialization?
A:
Some good links The Java serialization algorithm revealed
1) does deserialization fail in case the access specifier of the field
changes OR some or all of the methods go missing in the class at the
deserialization end ?
Serialization happens using Using Reflection
Java Detects the changes to a class using the
private static final long serialVersionUID
The default involves a hashcode. Serialization creates a single hashcode, of type long, from the following information:
The class name and modifiers
The names of any interfaces the class implements
Descriptions of all methods and constructors except private methods and constructors
Descriptions of all fields except private, static, and private transient
The default behavior for the serialization mechanism is a classic "better safe than sorry" strategy. The serialization mechanism uses the suid, which defaults to an extremely sensitive index, to tell when a class has changed. If so, the serialization mechanism refuses to create instances of the new class using data that was serialized with the old classes.
2) what is the mechanism by which fields are assigned their values
during deserialization ?
A:
The real details can be read in the Java Object Serialization Specification.
To answer your questions:
Serialization has a basic sanity check to see if the serialization ends use the same version of a class: the serialVersionUID member must be equal. Read the section Stream Unique Identifiers to know more about it. Basically, it's a static value which you can either manage yourself by declaring it on your class, or let the compiler generate one for you. If the compiler generates it, ANY change to a class will result in a change of serialVersionUID and hence will make the deserialization fail if the ends do not have exactly the same classes. If you want to avoid this, declare the variable yourself and update it manually when a change to the class' member variables does make classes incompatible.
The Java Virtual Machine does a lot of the magic here, it can access all internal state directly without the need for getters (fields marked transient or static aren't serialized though). Also, while the Serializable interface doesn't specify any methods to implement, there are a number of 'magic methods' which you can declare to influence the serialization process. Read section "The writeObject Method" and onwards to know more. Be aware though that you should use these sparingly as they might confuse any maintenance developers!
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I update kotlin-js-library to 1.1.3 like the kotlin-gradle-plugin has been?
If you look at:
https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/
the current version is 1.1.3 but:
https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-js-library/
is stuck back at 1.0.7. How can I trigger this to update?
A:
The kotlin dev repository has all what you want. just add the repository in build.gradle as below:
buildscript{
repositories{
maven{ url = "https://dl.bintray.com/kotlin/kotlin-dev/" }
}
}
repositories{
maven{ url = "https://dl.bintray.com/kotlin/kotlin-dev/" }
}
and the kotlin-js-library at here: https://dl.bintray.com/kotlin/kotlin-dev/org/jetbrains/kotlin/kotlin-js-library/
| {
"pile_set_name": "StackExchange"
} |
Q:
With Prism, is it possible for two modules to reference different versions of the same assembly?
In my company, different teams are developing different modules of the same product based on WPF. Some modules reference the same assemblies e.g. Log4net, in-house framework, etc...
To minimize the impacts, we would like each team to be able to update the version of the assemblies referenced by its module without forcing other teams to do the same. Is it possible with Prism?
A:
This is possible but has nothing to do with Prism. What you will need to look at is using binding redirects.
Binding redirects allow you to specify that any reference to version X of an assembly should actually use version Y. This way the different teams may update their dependencies separately to one another but when it comes to deploying the application, you may configure the binding redirects to all point to a version of the assembly.
It is often usual to redirect the references to the most recent version of an assembly which has not introduced any breaking changes. Breaking changes could result in exceptions at runtime.
Here is an example of a binding redirect:
<dependentAssembly>
<assemblyIdentity name="OurInHouseLibrary" publicKeyToken="32ab4ba45e0a69a1" culture="en-us" />
<bindingRedirect oldVersion="1.0.0.0-1.0.32.27762" newVersion="1.0.32.27762" />
</dependentAssembly>
This specifies that any reference to the assembly OurInHouseLibrary of versions 1.0.0.0 through to version 1.0.32.27762 should now reference the assembly OurInHouseLibrary at version 1.0.32.27762.
I would suggest against it, but another option is to use the codeBase element to redirect to different assemblies, i.e.:
<dependentAssembly>
<assemblyIdentity name="OurInHouseLibrary" publicKeyToken="32ab4ba45e0a69a1" culture="en-us" />
<codeBase version="1.0.0.0" href="v1.0\OurInHouseLibrary.dll" />
<codeBase version="1.1.0.0" href="v1.1\OurInHouseLibrary.dll" />
</dependentAssembly>
Here is an article from Microsoft explaining why loading multiple versions of the same assembly is a bad thing. One of the main issues is with Type identities, as you will not be able to use the type from one version in place of the type from another (including being unable to cast them).
| {
"pile_set_name": "StackExchange"
} |
Q:
Postgresql - query problem
I have a variable which is in this format 2011-05-13.
I want to make a query that adds one day to this variable and searches for days like this in the database.
I made this query but it doesnt work.
select phone from employee where date like (select date '2011-05-13' + 1) %
Can anyone help?
A:
You need an INTERVAL:
SELECT phone FROM employee WHERE datefield = (date '2011-05-13' + INTERVAL '1 DAY') ;
Edit: Don't use LIKE when you're working with dates, there is no LIKE for a date.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is putting external jars in the JAVA_HOME/lib/ext directory a bad thing?
We have an application which runs in a JRE environment. The application uses some external jars and we have been putting them in the JAVA_HOME/lib/ext folder. This has worked for us for years but recently a new programmer joined our team and seems emphatic that this is some how a bad thing to do. I can't understand why and I'm trying to do some research before I dig further with this developer. Is there something I'm missing here?
A:
Yes - it's a bad thing. Think about it: the application depends on the JRE and some extra jars. What if you update the JRE? Then you have to remember to copy the files into the new JRE. What if you need to set up the application on a new system? You have to copy the application there, and then also remember to copy the external jars into the JRE on that system.
Both those issues wouldn't be an issue at all if you just package the application properly together with the external jars it needs. If you don't see this, then maybe it's not an issue at all. But you should still be grateful for the new guy for sharing his opinion.
A:
In addition to the answer by weiji (packaging and upgrades to new JVM versions), there are other risks.
If you are using security manager in any of your applications, the libraries in ext often have a lot more capability by default - they are treated much like the system libraries. You need to be sure that you can trust, in the sense of enforcing security rules, these classes. Did the authors think through what they were exposing correctly? If these classes do not use access control to change the security context then you don't need to worry about this but do you know if they do or do not (e.g. a method that provides access to a file and uses AccessController, does it ensure that the caller has the right file permissions?)
Can all your applications use the exact same version of the library? What happens when you need to update that library (not just the JVM)? Will you break any of your applications? You will need to retest everything. The libraries in ext are loaded by the extension class loader which, due to parent delegation, has higher precedence than the normal (i.e. CLASSPATH) loader so these are guaranteed to be used by your application and there is no way for an individual application to override the library in ext with a different version.
If you want to share the libraries across your applications, why not instead provide a separate folder of common libraries that applications can be individually configured (CLASSPATH) to reference. Then if you have problems with one application and a library, you can switch to a different version of the libraries or just for that one, put it earlier in the CLASSPATH (if that works, you must test this too as there may be other dependency issues). This will allow you to have more individual control for each application. But then, bundling all the required libraries with your application is the safest as you can retest and roll-out library upgrades to individual applications.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to populate observable with another observable and return observable
I'm working on rxjs project and I am using json-server as database provider. I am stuck at getting one collection that I need to populate with another collection.
I have collection Match and collection Tournament.
Inside collection Match, I have tournamentId only, but my class Match also contains Tournament instance.
class Match{
id:number;
...
tournamentId:number;
tournament: Tournament;
}
class Tournament{
id:number;
...
name:String;
}
I need 2 calls from db. First to get all tournaments, and then to get all matches.
I need to return Match Observable that has been populated with Tournament.
get(): Observable<Match> {
return Observable.create(obs => {
tournamentService.get().pipe(toArray()).subscribe(tournaments => {//tournaments = [torunament1, tournament2]
super.get().pipe(map(x => { let m = new Match(x); m.populateTournament(tournaments); obs.next(m); return m; })).subscribe(() => {
obs.complete();
});
});
});
}
obs.complete() is being called immediately, thus I end up with only one Match in observable that's created.
I'm trying to populate Match with Tournament in map pipe, and also send it as obs.next(m) there. I don't know if that is smart either.
tournamentService.get() and super.get() return Observables of Tournament and unpopulated Match respectively (JS {object} with same attributes).
How do I next() matches one by one and after they are all sent to subscriber call complete()?
A:
You shouldn't create your own observables, there are already existing operators you can use for that. I think mergeMap, switchMap and combineLatest all work here.
You should combine those two observables:
get(): Observable<Match> {
return combineLatest([super.get(), tournamentService.get()]) // Combine both Observables when both emit
.pipe(map(([match, tours])=> { // Destructuring array of emitted values
let m = new Match(match);
m.populateTournament(tours);
return m; // Return match combined with tournaments
}))
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Mocking an external SSO login in RSpec feature specs with Capybara Webkit
My application redirects to an external party for Single-Sign On (SSO).
Once logged in, that external party redirects that user back to my app's callback route.
This is implemented as follows in the controller:
SsoController < ApplicationController
def connect
# do stuff
# Redirect to external party with some params
redirect_to "www.external-party.com?foo=\"bar\""
end
def callback
# Receive response from external party
response = params[:response]
# do stuff
end
end
In my feature specs I'd love to actually have this mocked out so I can test the end-to-end functionality from the user's perspective.
I'm using RSpec + Capybara and I'd like to do model the following flow -
User clicks some button (e.g. "sign in")
That button is tied to the connect action above which redirects to some external party
RSpec mocks a response based on the params sent over and sends a POST request back to my app (callback action)
Further business logic to sign in user and take them to their target
I'm unsure of how to do the 3rd step, particularly with intercepting the call, constructing the response, and POST-ing something back
Thanks!
Edit: A POST request back to my app is preferred, but is not a must-have. If it's a GET request or a redirect, I can configure my app to allow those HTTP verbs on the test environment only.
A:
Rather than attempting to mock this in the app code (which is discouraged in feature specs) the cleanest way to do what you want is using a programmable proxy like puffing billy - https://github.com/oesmith/puffing-billy. That will let you respond to the test browser making a request to "www.external-party.com?foo=\"bar\"" in any way you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Would you at this situation explain the difference between object and objective as a noun?
Would anybody please explain the difference between these?
A government whose object is good for people.
A government whose objective is good for people.
Is there a difference between these two words when they are used as a noun?
These definitions and citations come from the Longman Dictionary, but I can not yet understand the difference between object and objective at such situations. I am so confused yet.
Object: AIM( the purpose of a plan, action, or activity.
Object: the purpose of an action or event.
Objective: the thing that you are working towards and hope to achieve by the end of a course of action.
The object of the game is to score as many points as possible.
Nobody knows the real object of their visit. They are keeping it a secret.
The object of the game is to improve children's math skill.
Longman also says
Do not use object to mean 'the thing you are working towards and hope to achieve'. Use objective: We have not yet achieved our objective (NOT our object).
That appears to mean:
My object is to improve my English as much as possible. (This one is wrong)
My objective is to improve my English as much as possible. (This one is right)
Is my reading correct?
A:
SHORT ANSWER:
In this context the two words mean exactly the same thing. Both are acceptable.
The distinction Longman's draws is difficult to understand; if it means what it appears to mean, it's wrong. I think you may ignore it.
LONGER ANSWER:
What Longman's says is this:
2 AIM [singular] the purpose of a plan, action, or activity [↪ goal, aim]
object of
The object of the game is to improve children's math skills.
My object was to explain the decision simply.
The customer will benefit most, and that is the object of the exercise (=the purpose of what you are doing).
! Do not use object to mean 'the thing you are working towards and hope to achieve'. Use objective: We have not yet achieved our objective (NOT our object).
I cannot understand this distinction. It does not reflect actual use of the two words, either now or in the past.
The distinction which is drawn in use is exactly the opposite:
Object is used both for purposes and for the person or thing which receives an action - the Direct Object of a verb:
okHis object is to win Mary's love. ... The purpose of his actions is to win Mary's love.
okMary is the object of his love. ... =He loves Mary. Mary is the person towards whom he directs his love, the person for whom he feels love.
But objective is used only to name purposes. It is not used to name the person or thing which receives an action.
okHis objective is to win Mary's love. ... The purpose of his actions is to win Mary's love.
∗ Mary is the objective of his love. ... This is not acceptable.
So Longman's is wrong. Both of these are correct:
okMy object is to improve my English as much as possible.
okMy objective is to improve my English as much as possible.
But only one of these is correct, the one with object:
okThe object of my study is English. ... =I study English. What I study is English.
∗ The objective of my study is English. ... This is not acceptable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Keyboard not dismissing when another UITextField is tapped that brings up a picker
I have 2 text fields that I am working with each one when clicked opens up a picker wheel with a toolbar on top that gives the option to dismiss the picker and bring up a keyboard everything works fine unless you dismiss the picker and bring up the keyboard then click the next textfield. I get the keyboard on top with the new pickerview behind it. And the only way to get the keyboard to go away is to click back in the first textfield and click done or anywhere on the screen (not a textfield).
here is my code:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
for (NSUInteger i = 0; i<[self.fieldsArray count]; i++) {
if ([self.fieldsArray objectAtIndex:i] == textField) {
UITextField *input = [self.fieldsArray objectAtIndex:i];
if (input.tag == 3 && !self.overrideDriver) {
[self animatePickDriverForInput:input];
}
if (input.tag == 4 && !self.overrideVehicle) {
[self animatePickVehicleForInput:input];
}
}
}
}
Here are some other methods used:
- (IBAction)textFieldFinished:(id)sender
{
[sender resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
- (void)animatePickDriverForInput:(UITextField *)input
{
if ([self.drivers count] > 0) {
[self.view endEditing:YES];
[self showPickDriver];
} else {
//untested
[input addTarget:self action:@selector(textFieldFinished:)
forControlEvents:UIControlEventEditingDidEndOnExit];
}
}
- (void)animatePickVehicleForInput:(UITextField *)input
{
if ([self.vehicles count] > 0) {
[self.view endEditing:YES];
[self showPickVehicle];
} else {
//untested
[input addTarget:self action:@selector(textFieldFinished:)
forControlEvents:UIControlEventEditingDidEndOnExit];
}
}
- (void)allowManualEntryOfDriver
{
[self.additionalButtonPickerHelper animateDismiss:self.pickDriver];
self.overrideDriver = YES;
[self.driver becomeFirstResponder];
}
- (void)allowManualEntryOfVehicle
{
[self.additionalButtonPickerHelper animateDismiss:self.pickVehicle];
self.overrideVehicle = YES;
[self.vehicle becomeFirstResponder];
}
- (void)showPickVehicle {
self.pickVehicle = [self.additionalButtonPickerHelper createPicker:self.pickVehicle WithTag:2 WithOtherButtonText:@"Add Other Vehicle"];
[self.additionalButtonPickerHelper showPicker:self.pickVehicle WithDoneAction:@selector(dismissVehiclePicker) OrWithOtherAction:@selector(allowManualEntryOfVehicle)];
}
- (void)showPickDriver {
self.pickDriver = [self.additionalButtonPickerHelper createPicker:self.pickDriver WithTag:1 WithOtherButtonText:@"Add Other Driver"];
[self.additionalButtonPickerHelper showPicker:self.pickDriver WithDoneAction:@selector(dismissDriverPicker) OrWithOtherAction:@selector(allowManualEntryOfDriver)];
}
edit:
More code:
- (void)dismissDriverPicker
{
[self.additionalButtonPickerHelper animateDismiss:self.pickDriver];
}
- (void)dismissVehiclePicker
{
[self.additionalButtonPickerHelper animateDismiss:self.pickVehicle];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
This may not be the most efficient way to do this but im new to objective c and looking for a solution that I can understand. Thanks!
edit here is a picture
A:
Also you can try to use property of textField : inputView
The custom input view to display when the text field becomes the first
responder.
So, you can show this view instead of keyboard, and don't handle it manually.
Or:
Wrong behavior for now occur, because keyboard for second textfield is shown also. So you need not only to resign first responder of first field, but also implement:
-(BOOL) textFieldShouldBeginEditing:(UITextField *)field {
return NO;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Images rotated to 90 degree left email attachment iPhone
Well this may be a very easy Question but I'm not getting the answer after searching a lot.
I have one application in which I send the image taken from camera. The path of image captured from camera is stored in database. So in mail attachment code I load image from path and attach like this:
UIImage *myImage = [UIImage imageWithContentsOfFile:ImagePath];
NSData *imageData = UIImagePNGRepresentation(myImage);
[mailer addAttachmentData:imageData mimeType:@"image/png" fileName:@"Spotted"];
but the image is rotated by 90 Degree left every time. Can anyone guide me what am I doing wrong here??
P.S.: NSLog of ImagePath -->
/var/mobile/Applications/4BFB1BD9-DD83-42AF-A2BF-A5E4CC0DEAE3/Documents/459443.png
A:
There has been some discussion on the Apple site about this issue in pictures sent by mail.
| {
"pile_set_name": "StackExchange"
} |
Q:
At a Loss on over Page Peel Plugin Customization
I am trying to install and configure the Page Peel Plugin for a friend on their site. The plugin is from SmartRedFox.com and they're support is non-existent.
I have it installed but for some reason the Page Peel is not displaying. The code is present when I view Source but no image is visible. I've checked through the CSS and can't see the conflict.
Plugin installed here: http://dev.sharepoint-videos.com/ Should be visible in the Banner area which is marked by :
<div id="PagePeel" class="right"></div>
Granted I didn't develop this site so I am not sure why the original author has everything positioned absolute.
A:
CSS was indeed the issue. It works fine on a stock WP installation and I was finally able to track down the conflict with this developed site.
| {
"pile_set_name": "StackExchange"
} |
Q:
Easiest way to replace preinstalled Windows 8 with new hard drive with Windows 7
There are all kinds of questions and answers relevant moving Windows 8 to a new hard drive. I'm not seeing anything quite applicable to my situation.
I have a new, unopened, unbooted notebook with pre-installed Windows 8. I will be replacing the hard drive before ever booting, unless that is not possible for some reason. I want to "downgrade" to Windows 7 Pro, and I want a clean installation. To do so legitimately, I apparently either need to:
Upgrade Windows 8 to Windows 8 Pro using Windows 8 Pro Pack, then downgrade; or
Just install a newly-licensed copy of Windows 7 Pro.
(Let me know if I've missed an option.)
Installation media is likely not a problem, though if I need something vendor-specific that I cannot otherwise download, that could present an issue (Asus notebook, if that matters). If I could, I would just buy the Pro Pack upgrade, swap the hard drive (without ever booting), then install Windows 7 Pro directly on the new hard drive, using the Pro Pack key for activation. Will this work? Are there any activation issues?
Edited to clarify, as some comments and answers indicate confusion:
Here is, ideally, what I want to do:
Before ever powering on the notebook, remove the current hard drive.
Replace this hard drive with a new, blank hard drive.
Install a clean copy of Windows 7 Pro on this new, blank hard drive.
Unless I have no choice to accomplish the end result (a clean install of Win7 Pro on the newly-installed, previously-blank hard drive), I am not wanting to:
Install Windows 7 "over" the current Windows 8 install (after upgrading to Win8 Pro). That would involve using the currenly-installed hard drive. I want to use a new, different hard drive.
Copy the Win8 install to the new hard drive, then install Windows 7 "over" that installation.
Install Windows 7 "over" the current Windows 8 install (after upgrading to Win8 Pro), then copy the installation to the new hard drive.
If I have to use one of those three options, I will, but only if there is no other choice. Please note that this question is not about licensing: I will purchase the necessary license(s) to accomplish this procedure legally (apparently either Win8 Pro Pack or Win7 Pro -- the former currently appears less expensive).
A:
After following some links, I believe I have found my answer.
From Microsoft's "Downgrade Rights FAQ" near the bottom of this page:
Q. Will the downgraded software require product activation? If so, what product key should be used to activate the software?
A. Once the downgraded software is installed, the PC will prompt for a product key in order to activate the software. The product key associated with the original Windows software should be used for activation. If the product key has been previously activated, which is likely if the media came from a prior legally licensed version that has been activated in the past, the software may be unable to activate over the Internet, due to the hardware configuration change when installing this media onto the Windows 8 or Windows 7 system. When this happens, the appropriate local Activation Support phone number will be displayed, and the person performing the downgrade will need to call the Activation Support Line and explain the circumstances to a customer service representative.
Once it is determined that the end user has a valid Windows 8 Pro, Windows 7 Professional, or Windows 7 Ultimate license, the customer service representative will provide a single-use activation code that can be used to activate the software.
This answer strongly suggests that, no matter what, I will end up having to call Activation Support if I want to use my first option, which is to buy Windows 8 Pro Pack but install Windows 7 Pro. While I happen to have a volume licensing agreement, new Windows license keys are not part of my specific agreement, so I will probably just reuse one from a prior installation, get the error, and call the hotline.
The volume licensing agreement does confirm the downgrade rights I am describing, though it appears that any consumer with a valid Win8 Pro license could downgrade to Win7 Pro at this time.
I have MSDN, but I believe use of one of my Win7 keys from MSDN for this purpose may violate my MSDN license, so I'm not going to go that route.
Of course, just buying a new Win7 Pro license would appear also to work, but right now, Win8 Pro Pack appears cheaper. Since I don't mind the activation hassle this time to save a few bucks, I think that is the route I will go. Plus, I will have Win8 Pro available (for that machine only, since the original Win8 is an OEM install) in case I ever decide to go back to that OS or upgrade to a later one that requires a Win8 Pro license.
To summarize, I plan to:
Determine whether Windows 7 drivers are available for the machine, and obtain those drivers.
Purchase a Windows 8 Pro Pack license.
Swap the pre-installed hard drive for a new, blank one. This is because the new drive will be faster and have greater capacity (new drive: hybrid 7200RPM 750GB; old drive: 5400RPM 500GB with unwanted, OEM-installed software).
Turn off Secure Boot.
Install Windows 7 using a USB key specifically set up for a UEFI install (I already have this USB key available). If UEFI does not work, I will simply perform a legacy-mode install from DVD.
Use the activation key from my last Win7 install.
Get the activation error and call Activation Support to get a valid activation code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove subview from other method
I initialize UIVisualEffectView from one method and need to remove it with other method.
func showBlur() {
let blurEffect: UIBlurEffect = UIBlurEffect(style: .Light)
let blurView = UIVisualEffectView(effect: blurEffect)
// ...
}
func destroyBlur {
// i can’t destroy via remove from superview it here, blurView was initialized in showBlur()
}
I’ve tried to initiate blurView not in method but in class… there is problems with init() in UIViewController.
I’ve tried to find that view in view.subViews, but i’ve got no luck.
I’ve tried to set tag to UIView but can’t find that tag lately in subView list.
A:
You can create property to store UIVisualEffectView on the beginning od the class:
var blurView: UIVisualEffectView!
and in showBlur() function, sto the effect in this variable:
let blurEffect: UIBlurEffect = UIBlurEffect(style: .Light)
blurView = UIVisualEffectView(effect: blurEffect)
and in destroyBlur() call:
blurView.removeFromSuperview()
| {
"pile_set_name": "StackExchange"
} |
Q:
ValueError: Unrecognized Mode
Here is my code:
import Image
img = Image.new("RBG",(649,489),(0,0,255))
for x in xrange(649):
for y in xrange(489):
img.putpixel((x,y),(0,255,0))
img.show()
When I try to run this code I get a "ValueError: unrecognized mode", does anyone know why this might happen? Any help will be greatly appreciated. :)
A:
I guess it should be "RGB" instead of "RBG".
| {
"pile_set_name": "StackExchange"
} |
Q:
DevExpress report with mvc and angular js
In my web application,i am using asp.net mvc5 and angular1.5.All views are rendered as partial using ui-view.
I need to integrate DevExpress reporting with mvc5 and angular js.
Does anyone have Idea how i can integrate DevExpress report with mvc5 and angularjs 1.5.
A:
please review the following links for your question, the current solution is to have separate page for the report viewer and you can use iframe to show it inside your app
https://www.devexpress.com/Support/Center/Question/Details/T289424
https://www.devexpress.com/Support/Center/Question/Details/T422061
Happy coding :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Does "the other side of the receipt" sound natural in American English
Kindly, look at the other side of the receipt. You will find a link
through which you can rate our service.
The aim of this sentence is to make a customer pay attention to the link because it is written on the other side of the receipt. Is the sentence correct, polite, and expressing the required meaning?
Is the expression "The other side" accurate? I mean what do you call the golden side of the shown picture? Is it called back, back-side, flip the paper, or something else?
A:
Yes, you can refer to the other side for something which is flat, like a receipt or other piece of paper, which has only one other side, or where there is only one other side of interest.
It is almost never the case, however, that information about the transaction is printed on both sides. It is almost always printed on only one side, and the back is left blank or used for marketing messages, policy statements, coupons, and indeed, in this case the URL for a customer survey. It would be far more customary to refer to the front and back of the receipt.
More importantly (in my opinion), kindly is not much if ever used by native speakers of American English to make requests except in very formal circumstances. Please would be used almost exclusively for customer relations.
Please see the back of this receipt for a link to rate our service.
A:
This is certainly understandable, though I would suggest that it could be made more direct and effective by giving the user a reason to turn over before asking them to.
As currently drafted, you're asking the user to turn over the receipt. They might do that, then wonder why they did if they hadn't read the next sentence.
I would suggest rephrasing the sentence as:
To find a link through which you can rate our service, please turn over this receipt.
Alternatively, if you do want to refer to the back of the receipt and to be as direct as possible, respecting the user's time:
To rate our service, please use the link on the back of this receipt.
If you're attempting to get as many users (customers?) as possible to turn over the receipt, I would recommend trying multiple different messages with different links in a multivariate test.
| {
"pile_set_name": "StackExchange"
} |
Q:
Subquery in doctrine2 notIN Function
I'd like to select members who are not in specific service. I have 3 tables :
membre
service
membre_service (relation between membre and service)
I'm using doctrine 2 and in SQL my query is :
SELECT m.* FROM membre m WHERE m.`id` NOT IN (
SELECT ms.membre_id FROM membre_service ms WHERE ms.service_id != 29
)
In Doctrine, I do :
$qb = $this->_em->createQueryBuilder();
$qb2 = $qb;
$qb2->select('m.id')
->from('Custom\Entity\MembreService', 'ms')
->leftJoin('ms.membre', 'm')
->where('ms.id != ?1')
->setParameter(1, $service);
$qb = $this->_em->createQueryBuilder();
$qb->select('m')
->from('Custom\Entity\Membre', 'm')
->where($qb->expr()->notIn('m.id', $qb2->getDQL())
);
$query = $qb->getQuery();
//$query->useResultCache(true, 1200, __FUNCTION__);
return $query->getResult();
I got the following error :
Semantical Error] line 0, col 123 near 'm WHERE ms.id': Error: 'm' is already defined.
A:
The same alias cannot be defined 2 times in the same query
$qb = $this->_em->createQueryBuilder();
$qb2 = $qb;
$qb2->select('m.id')
->from('Custom\Entity\MembreService', 'ms')
->leftJoin('ms.membre', 'm')
->where('ms.id != ?1');
$qb = $this->_em->createQueryBuilder();
$qb->select('mm')
->from('Custom\Entity\Membre', 'mm')
->where($qb->expr()->notIn('mm.id', $qb2->getDQL())
);
$qb->setParameter(1, $service);
$query = $qb->getQuery();
return $query->getResult();
Ideally you should use many-to-many relation for your entity, in this case your query is going to be much simpler.
A:
Actually if you are using the Symfony2 repository class you could also do the following:
$in = $this->getEntityManager()->getRepository('Custom:MembreService')
->createQueryBuilder('ms')
->select('identity(ms.m)')
->where(ms.id != ?1);
$q = $this->createQueryBuilder('m')
->where($q->expr()->notIn('m.id', $in->getDQL()))
->setParameter(1, $service);
return $q->getQuery()->execute();
A:
You can use (NOT) MEMBER OF:
<?php
$query = $em->createQuery('SELECT m.id FROM Custom\Entity\Membre WHERE :service NOT MEMBER OF m.services');
$query->setParameter('service', $service);
$ids = $query->getResult();
See the documentation for more examples.
| {
"pile_set_name": "StackExchange"
} |
Q:
Not able to find mongoose models after creation
I have created one express app and the database connection .
var app = express();
app.db = mongoose.connect("mongodb://localhost/forcast-db");
var accountSchema = new mongoose.Schema({
accountId:{
type:String,
required:true
}
});
app.db.model('Account', accountSchema);
console.log(app.db.models);
But it is printing a empty object.
used library
"express": "^4.13.4",
"mongoose": "^4.4.7",
Any kind of help will be highly appreciated.
A:
to get all models created with your mongoose connection use app.db.connection.models so your code should be like this:
var app = express();
app.db = mongoose.connect("mongodb://localhost/forcast-db");
var accountSchema = new mongoose.Schema({
accountId:{
type:String,
required:true
}
});
var accountModel= app.db.model('Account', accountSchema);
console.log(app.db.connection.models);
//to create a document from this Account model and save it
var newAccount= new accountModel({accountId:'1111'});
newAccount.save();
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best way to write a function to compute row-wise elements in panda?
I have a base table like:
col1 is a column of independent values, col2 is an aggregate based on Country and Type combo. I want to compute columns col3 through col5 with the following logic:
col3: ratio of an element in col1 to the total of col1
col4: ratio of an element in col1 to the corresponding element in col2
col5: the natural exponent of the product of row-wise elements in col3 and col4
I wrote a function like the below to achieve this:
def calculate(df):
for i in range(len(df)):
df['col3'].loc[i] = df['col1'].loc[i]/sum(df['col1'])
df['col4'].loc[i] = df['col1'].loc[i]/df['col2'].loc[i]
df['col5'].loc[i] = np.exp(df['col3'].loc[i]*df['col4'].loc[i])
return df
This function executes, and gives me the expected results, but the notebook also throws a warning:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
I'm not sure if I'm writing the best function here. Any help would be appreciated! Thanks.
A:
I think apply and loop in pandas is best avoid, so better and faster is use vewctorized solution:
df = pd.DataFrame({'col1':[4,5,4,5,5,4],
'col2':[7,8,9,4,2,3],
'col3':[1,3,5,7,1,0],
'col4':[5,3,6,9,2,4],
'col5':[1,4,3,4,0,4]})
print (df)
col1 col2 col3 col4 col5
0 4 7 1 5 1
1 5 8 3 3 4
2 4 9 5 6 3
3 5 4 7 9 4
4 5 2 1 2 0
5 4 3 0 4 4
df['col3'] = df['col1']/(df['col1']).sum()
df['col4'] = df['col1']/df['col2']
df['col5'] = np.exp(df['col3']*df['col4'])
print (df)
col1 col2 col3 col4 col5
0 4 7 0.148148 0.571429 1.088343
1 5 8 0.185185 0.625000 1.122705
2 4 9 0.148148 0.444444 1.068060
3 5 4 0.185185 1.250000 1.260466
4 5 2 0.185185 2.500000 1.588774
5 4 3 0.148148 1.333333 1.218391
Timings:
df = pd.DataFrame({'col1':[4,5,4,5,5,4],
'col2':[7,8,9,4,2,3],
'col3':[1,3,5,7,1,0],
'col4':[5,3,6,9,2,4],
'col5':[1,4,3,4,0,4]})
#print (df)
#6000 rows
df = pd.concat([df] * 1000, ignore_index=True)
In [211]: %%timeit
...: df['col3'] = df['col1']/(df['col1']).sum()
...: df['col4'] = df['col1']/df['col2']
...: df['col5'] = np.exp(df['col3']*df['col4'])
...:
1.49 ms ± 104 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Unfortunately loop solution is really slow for this sample, so tested in 60 rows DataFrame only:
#60 rows
df = pd.concat([df] * 10, ignore_index=True)
In [3]: %%timeit
...: (calculate(df))
...:
C:\Anaconda3\lib\site-packages\pandas\core\indexing.py:194: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self._setitem_with_indexer(indexer, value)
10.2 s ± 410 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
| {
"pile_set_name": "StackExchange"
} |
Q:
Are Pull Down Resistors too Slow to read Encoder Counts?
I'm planning on using the LPC1768's QEI module for reading a motor's encoder (which has a high resolution - http://encoder.com/literature/datasheet-770.pdf).
I've read some people have hooked up their encoders to the module using pull down resistors [https://os.mbed.com/users/hexley/notebook/qei_hw-interface-implementation-notes/, however, apparently this is only suitable for reading panel encoders turned by humans because the pull down is too slow for high-speed application.
If this is the case, what would be an alternative to using a pull down/up resistor?
Ultimately I'd like to know the best way to hook up an encoder without losing counts.
A:
The first thing to do is to figure what the fastest toggling speed of any of the lines will be. Find the fastest shaft speed you need to handle, then figure out the toggle frequency out of the encoder for that.
Once you know the fastest response time you need, this problem no longer has anything to do with a encoder. It's really about how stiff a pullup or pulldown needs to be to float the line to the released state when it is no longer actively driven to the opposite state. This is mostly a RC time constant calculation.
Let's say you decide that there will be no more than 100 pF of parasitic capacitance on a line, and that the fastest toggle rate is 10 kHz. Each cycle is 100 µs long, so each level is 50 µs long. If you need to decode two of these lines in quadrature, one should be well settled before the other starts to change. Let's say you therefore decide you want each line to settle to 90% within 10 µs.
90% settling happens in 2.3 time constants. One time constant is therefore (10 µs)/2.3 = 4.35 µs. The minimum pullup or pulldown resistance is therefore (4.35 µs)/(100 pF) = 43.5 kΩ. That's actually rather high. Unless this is a particularly low power application where you need to conserve 10s of µA, I'd just use 10 kΩ in this case.
Note that most of these devices have open drain or open collector outputs with a common ground. You would therefore need pullup, not pulldown, resistors. Check the datasheet to make sure you are using the correct polarity. High speed devices usually drive both ways and don't need pullups/pulldowns at all. Again, check the datasheet.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the shorthand for this?
Here's some messy javascript:
$('.menu').mouseover(function () {
$(this).animate({
}, 500, function() {});
}).mouseout(function () {
$(this).animate({
}, 500, function() {});
});
How can I make this smaller, not minify, but isn't there a way to say like "toggle" instead of "mouseover" then "mouseout"?
thx
A:
You're looking for hover()
A:
jQuery .hover() combines .mouseenter() and .mouseleave() into one convenient method. It should also be noted that mouseenter and mouseleave work somewhat differently, and usually much better, than mouseover and mouseout.
$('.menu').hover(
function () {
$(this).animate({
}, 500, function() {});
},
function () {
$(this).animate({
}, 500, function() {});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Better to run 2 sql queries or 1 and deal with duplicate result set?
I have a webpage that has an ID as a GET variable that I need to pull the name, city, and state for that ID (stored in 1 table) as well as any data associated with it (stored in another table).
These are the results of a single query:
SELECT
info.name, info.city, info.state,
data.data1, data.data2, data.data3, data.data4
FROM
data_table data,
info_table info
WHERE
data.id = 12345 AND info.id = data.id
name | city | state | data1 | data2 | data3 | data4
---------------------------------------------------
test | temp | AL | 12 | 9 | 1 | 14
test | temp | AL | 63 | 8 | 1 | 6
test | temp | AL | 46 | 66 | 1 | 723
test | temp | AL | 7 | 5 | 2 | 99
test | temp | AL | 4 | 2 | 3 | 0
test | temp | AL | 2 | 11 | 1 | 1
But the column data for name, city, state are all going to be identical for each row, so I could also do it with two queries and return the 'right' amount of data (but obviously taking twice as long to communicate with the server):
SELECT
info.name, info.city, info.state,
FROM
info_table info
WHERE
info.id = 12345
name | city | state
-------------------
test | temp | AL
...and...
SELECT
data.data1, data.data2, data.data3, data.data4
FROM
data_table data,
WHERE
data.id = 12345
data1 | data2 | data3 | data4
-----------------------------
12 | 9 | 1 | 14
63 | 8 | 1 | 6
46 | 66 | 1 | 723
7 | 5 | 2 | 99
4 | 2 | 3 | 0
2 | 11 | 1 | 1
So, in general, is it necessarily better to use 2 queries and returning the exact amount of data I need? Or because of the (small) size of the data set being returned, just bite the dataset-larger-than-it-needs-to-be bullet and only run a single query?
I'm guessing that every situation varies, and if the total server communication time / 2 > time to transmit extra data, then a single query is better?
A:
Avoid the pitfalls of premature optimization, and just do the single JOIN instead of trying to do your JOIN operations client-side.
If it later turns out that duplicated data is a significant strain, you have better options for addressing the issue besides doing multiple queries.
For example, result sets can be compressed, reducing the the size of repeating data. The CPU overhead for the compression would likely be substantially less than attempting to do JOIN operations client-side.
A:
For a small resultset, where the amount of redundant data is insignificant, use one statement.
One of the "hidden" costs (in terms of the MySQL server) is the overhead for each statement. Each SQL statement has to be sent to the server... MySQL has to parse and prepare each statement. MySQL has to check that a statement is syntactically correct (keywords, commas, etc.), that the statement is semantically correct, that is that the identifiers (table names, column names, function names) are valid, and that the user has permission on all of the objects). After that MySQL can produce an execution plan, evaluating different access paths (full table scan vs. using an index, the join order, and so on.
For a small resultset, it's going to be more efficient (in terms of the MySQL server) to send a single statement and return a few redundant columns, than it is going to be to process two separate statements and preparing and returning two separate result sets.
There's network latency involved in sending the query, and retrieving the resulset. So doing that two times is going to outweigh the cost of doing it just once, and sending a couple hundred bytes of redundant data in the resultset.
On the other hand, if the amount of redundant data is going to be significant, that's going to consume memory and network bandwidth, or, if the execution plan for the query is not as efficient as running two separate queries.... in those cases, running two separate queries is going to be more efficient.
| {
"pile_set_name": "StackExchange"
} |
Q:
powershell or msdeploy
I am running into a situation where I need to find a better approach to deploy web applications (asp.net to iis6..sorry ruby lovers :( and I was curious what some of you have done? I have seen products out there (Anthill?) but I am really looking for a way that my operations team can script a way to grab zip files (packaged code and assemblies), unzip, deploy to a farm. Anyone have any thoughts or solutions that they may be using?
A:
Supposedly, MSDeploy ships with a PowerShell snapin and cmdlets... so you shouldn't have to choose.
IIS Team Blog: web deployment tool and PowerShell
MSDeploy + PowerShell Blog
The bad news is, I can't find that snapin on my system ;)
A:
You mention a tool that Microsoft has in Beta, msdeploy.exe. Is that not a good choice for you?
On IIS6, the state of the art was adsutil.vbs, iisweb.vbs, iisback.vbs, iiscnfg.vbs, and iisext.vbs or learning an arcane script programming model for IIS.
I think msdeploy will be a large step up from wrapping those primitive utils with powershell and other scripts or batch files, with its "syncing" approach.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get values from the form array and form group functions..Angular
https://www.tektutorialshub.com/angular/nested-formarray-example-add-form-fields-dynamically/
the code is from here
export class AppComponent {
title = 'Nested FormArray Example Add Form Fields Dynamically';
empForm:FormGroup;
constructor(private fb:FormBuilder) {
this.empForm=this.fb.group({
employees: this.fb.array([]) ,
})
}
employees(): FormArray {
return this.empForm.get("employees") as FormArray
}
newEmployee(): FormGroup {
return this.fb.group({
firstName: '',
lastName: '',
skills:this.fb.array([])
})
}
addEmployee() {
console.log("Adding a employee");
this.employees().push(this.newEmployee());
}
removeEmployee(empIndex:number) {
this.employees().removeAt(empIndex);
}
employeeSkills(empIndex:number) : FormArray {
return this.employees().at(empIndex).get("skills") as FormArray
}
newSkill(): FormGroup {
return this.fb.group({
skill: '',
exp: '',
})
}
addEmployeeSkill(empIndex:number) {
this.employeeSkills(empIndex).push(this.newSkill());
}
removeEmployeeSkill(empIndex:number,skillIndex:number) {
this.employeeSkills(empIndex).removeAt(skillIndex);
}
onSubmit() {
console.log(this.empForm.value);
}
}
This is template:
<form [formGroup]="empForm" (ngSubmit)="onSubmit()">
<div formArrayName="employees">
<div *ngFor="let employee of employees().controls; let empIndex=index">
<div [formGroupName]="empIndex" style="border: 1px solid blue; padding: 10px; width: 600px; margin: 5px;">
{{empIndex}}
First Name :
<input type="text" formControlName="firstName">
Last Name:
<input type="text" formControlName="lastName">
<button (click)="removeEmployee(empIndex)">Remove</button>
<div formArrayName="skills">
<div *ngFor="let skill of employeeSkills(empIndex).controls; let
skillIndex=index">
<div [formGroupName]="skillIndex">
{{skillIndex}}
Skill :
<input type="text" formControlName="skill">
Exp:
<input type="text" formControlName="exp">
<button (click)="removeEmployeeSkill(empIndex,skillIndex)">Remove</button>
</div>
</div>
<button type="button" (click)="addEmployeeSkill(empIndex)">Add Skill</button>
</div>
</div>
</div>
</div>
<p>
<button type="submit">Submit</button>
</p>
</form>
<p>
<button type="button" (click)="addEmployee()">Add Employee</button>
</p>
so, I need go get values of firstName, lastName from empForm and skill: '',exp: ''from, skills array...
this function is not working for me to get values..
get from_date() {
return this.empForm.get("from_date");
}
....thia is not working..
also not able to take values from skills array
please help
A:
When you submit the form, the structure of this.empForm.value could be described by the following interfaces.
export interface Employee {
firstName: string;
lastName: string;
skills: Skill[];
}
export interface Skill {
exp: string;
skill: string;
}
Where empForm.value could be described by the following structure:
{
employees: Employee[];
}
When you query the empForm on submit, you can get the data as if you're querying a regular object.
onSubmit() {
const firstNames = this.empForm.value.employees.map(x => x.firstName);
const firstEmployeeSkills = this.empForm.employees[0].skills.map(x => x.skill);
// etc
}
As for this.empForm.get("from_date"), you don't have a property on the empForm called from_date, so this won't return anything.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex to determine legal SQL?
Possible Duplicate:
Regular expression to match common SQL syntax?
I am writing some helpers to help generate some very domain-specific sql. In my test-suite it would be nice to add a sanity check to ensure that the results are actually valid SQL. I'm not doing anything particularly fancy and this isn't production code so I think some regex would do but it's still annoyingly difficult to write by hand.
Is anyone willing to share a regex expression that would validate valid SQL at least for the 90% case?
A:
SQL is not a regular language. Use a real validator, such as Mimer.
See also:
Is SQL or even TSQL Turing Complete?
Regular expression to match common SQL syntax?
| {
"pile_set_name": "StackExchange"
} |
Q:
Table View hidden behind large gray box
I have a table view that was properly displaying using the Basic layout. After creating a custom cell, almost the entire table view is now covered by a large gray area. When I click the Add bar button, the table displays the cells properly for a second while the segue switches into the add item view controller. Also, when pressing Cancel from the add item view controller, the table displays properly for a second as it segues back, but then is covered by the gray box again.
Here is my custom cell class:
import UIKit
class ItemTableViewCell: UITableViewCell {
@IBOutlet weak var labelName: UILabel!
@IBOutlet weak var labelPhone: UILabel!
@IBOutlet weak var labelDetail: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
I didn't change anything in the TableViewController other than casting the cell as the custom cell class. What am I missing?
PS: I'm using Xcode 6, Beta 5
A:
Could your custom cell be larger than the rows in your table View? Try setting the row height in the tableviewdatasource and/or then on the custom cell say self.layer.clipsToBounds=true
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I prevent jQuery Template from digging too deeply on a string array in a recursively "reflection" template?
full jsFiddle Example
From what I found out on my last question about $.tmpl, passing an array of strings into a template containing an {{each}} will result in the template going over each string in the array like an array of characters because tmpl implicitly loops over arrays already. Unfortunately, that means, if I am already in a given template and I recursively call that template again on an array of strings (sub-objects work fine), I skip a level of recursion and try to template each string in the array instead of the templating the array itself.
If I am recursively templating an object by {{each}} (reflection, basically), how do I keep that implicit array loop from happening?
HTML
<div class="results"></div>
<script id="reflectTemplate" type="text/x-jquery-tmpl">
<ul>
{{each(i, prop) $data}}
{{if $data.hasOwnProperty(i)}}
<li>
${i}:
{{if $item.shouldDigDeeper(prop)}}
{{tmpl(prop, { shouldDigDeeper: $item.shouldDigDeeper, formatDisplay: $item.formatDisplay }) "#reflectTemplate"}}
{{else}}
${$item.formatDisplay(prop)}
{{/if}}
</li>
{{/if}}
{{/each}}
</ul>
</script>
JavaScript
var data = {
test2: "abc",
test3: [ "abc", "123", "def", "456" ]
},
templateFunctions = {
shouldDigDeeper: function(itemToCheck) {
return null !== itemToCheck && "object" === typeof(itemToCheck);
},
formatDisplay: function(propertyValue) {
var result = propertyValue;
if (null === result) {
result = "null";
}
else if ("string" === typeof (propertyValue)) {
result = "\"" + result + "\"";
}
return result;
}
};
$("#reflectTemplate").tmpl(data, templateFunctions).appendTo($(".results"));
Actual Output
<ul>
<li>test2: "abc" </li>
<li>test3:
<ul>
<li>0: "a" </li>
<li>1: "b" </li>
<li>2: "c" </li>
</ul>
...
<ul>
<li>0: "4" </li>
<li>1: "5" </li>
<li>2: "6" </li>
</ul>
</li>
</ul>
Desired Output
<ul>
<li>test2: "abc" </li>
<li>test3:
<ul>
<li>0: "abc" </li>
...
<li>1: "456" </li>
</ul>
</li>
</ul>
A:
In case @mblase75 is right (read: it isn't possible) and no one else comes up with anything else, here is a workaround I came up with.
jsFiddle example
Since tmpl pre-jumps a level deeper into arrays, I just came up with a system of templates that bounce off each other as an array comes up. One template handles only array items, while allowing nested objects/arrays within it (it seems). The duplication is a bit rough, but it appears to do the job for even crazy nested arrays.
HTML
<div class="results"></div>
<script id="arrayDisplayTemplate" type="text/x-jquery-tmpl">
<li>
{{if null !== $data && "object" === typeof ($data)}}
{{if $data instanceof Array}}
[
<ul>
{{tmpl($data, { formatDisplay: $item.formatDisplay }) "#arrayItemTemplate"}}
</ul>
]
{{else}}
{{tmpl($data, { formatDisplay: $item.formatDisplay }) "#reflectTemplate"}}
{{/if}}
{{else}}
${$item.formatDisplay($data)}
{{/if}}
</li>
</script>
<script id="reflectTemplate" type="text/x-jquery-tmpl">
<ul>
{{each(i, prop) $data}}
{{if $data.hasOwnProperty(i)}}
<li>
${i}:
{{if null !== prop && "object" === typeof (prop)}}
{{if prop instanceof Array}}
[
<ul>
{{tmpl(prop, { formatDisplay: $item.formatDisplay }) "#arrayDisplayTemplate"}}
</ul>
]
{{else}}
{{tmpl(prop, { formatDisplay: $item.formatDisplay }) "#reflectTemplate"}}
{{/if}}
{{else}}
${$item.formatDisplay(prop)}
{{/if}}
</li>
{{/if}}
{{/each}}
</ul>
</script>
JavaScript
var data = {
test1: 123,
test2: { w: [ "some", "string", "array" ], x: 1, y: 2, z: "abc" },
test3: [ "abc", "123", "def", "456" ],
test4: null
},
templateFunctions = {
formatDisplay: function(propertyValue) {
var propertyType = typeof (propertyValue),
result = propertyValue;
if (null === result) {
result = "null";
}
else if ("string" === propertyType) {
result = "\"" + result + "\"";
}
return result;
}
};
$("#reflectTemplate").tmpl(data, templateFunctions).appendTo($(".results"));
| {
"pile_set_name": "StackExchange"
} |
Q:
two Lists to Json Format in python
I have two lists
a=["USA","France","Italy"]
b=["10","5","6"]
I want the end result to be in json like this.
[{"country":"USA","wins":"10"},
{"country":"France","wins":"5"},
{"country":"Italy","wins":"6"},
]
I used zip(a,b) to join two but couldn't name it
A:
Using list comprehension:
>>> [{'country': country, 'wins': wins} for country, wins in zip(a, b)]
[{'country': 'USA', 'wins': '10'},
{'country': 'France', 'wins': '5'},
{'country': 'Italy', 'wins': '6'}]
Use json.dumps to get JSON:
>>> json.dumps(
... [{'country': country, 'wins': wins} for country, wins in zip(a, b)]
... )
'[{"country": "USA", "wins": "10"}, {"country": "France", "wins": "5"}, {"country": "Italy", "wins": "6"}]'
| {
"pile_set_name": "StackExchange"
} |
Q:
Where does hashing take place with a webclient and LDAP
We are currently implementing several web application that requires the user to create a user login that will be authenticated through LDAP calls. The LDAP server and user accounts will be shared by all the applications and the user's credentials will be the same across all applications.
My question is where does the hashing take place in a standard LDAP scenario, on the client side or does the LDAP server take care of it. It was my understanding that the LDAP server takes in a user password, at the time of creation, and hashes it and stores it. (By the by we plan on using salted SHA512 hashing and SSL connections between the client > webserver > LDAp server)
It was my understanding that the hashing operation takes place centrally on the LDAP server, relieving the client of the trouble and avoiding any breakage on the client end to affect other apps.
A:
Modern, professional-quality servers use storage schemes for password attributes (usually userPassword and authPassword) that involve executing the hash on the server. Servers usually append or prepend a unique value (called a salt) to a password, then execute the hash function. The "salt" minimizes the effectiveness of dictionary attacks, that is, dictionaries are more difficult to create for salted, hashed passwords.
SSL (a secure connection) should be used, or a non-secure connection should be promoted using the StartTLS extended request. An encrypted connection should be used so that passwords can be transmitted in the clear with BIND requests. Passwords that are transmitted in the clear over a secure connection can be checked for history and quality by the servers' password policy enforcement mechanisms. For servers that enforce password history and quality checks, passwords should not be transmitted pre-encoded. Therefore, it is not so much the "trouble" to the LDAP client as it is the fact that the server can enforcement organization-wide and agreed-to password quality and history checks in a central location.
see also
LDAP: StartTLS request
LDAP: Programming Practices
| {
"pile_set_name": "StackExchange"
} |
Q:
Joining 2 SQL SELECT result sets into one
I've got 2 select statements, returning data like this:
Select 1
col_a col_b
Select 2
col_a col_c
If I do union, I get something like
col_a col_b
And rows joined. What i need is getting it like this:
col_a col_b col_c
Joined on data in col_a
A:
Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:
SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a
If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.
A:
Use a FULL OUTER JOIN:
select
a.col_a,
a.col_b,
b.col_c
from
(select col_a,col_bfrom tab1) a
join
(select col_a,col_cfrom tab2) b
on a.col_a= b.col_a
| {
"pile_set_name": "StackExchange"
} |
Q:
CGIとして動作させた場合のUnicodeEncodeError
Webサーバーの、CGIで以下のコードを実行するとエンコーディングのエラーになります。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
html_body = """
<!DOCTYOE html>
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Test CAM</title>
</head>
<body>
こんにちは<br>
<form>
<input type="button" value="Button" onclick="button_click()">
</form>
</body>
</html>
"""
print("Content-type: text/html\n")
print(html_body)
エラー内容は
UnicodeEncodeError: 'ascii' codec can't encode characters in position 153-157:
ただし、ファイルは
$ nkf -guess test.py
UTF-8
なので、utf-8のはずです
どうも、リダイレクトの折にエラーになるようで
import sys
sys.setdefaultencoding('utf-8')
を入れて見ましたが、今度は
AttributeError: module 'sys' has no attribute 'setdefaultencoding'
とのエラーになります。
Python3ではどのように対処すれば良いでしょうか?
A:
Windows10のpython3.6ですが、python -m http.server --cgiを実行した場合は文字化けしました。
文字列がShift-JISで送られていましたので、リンク先のようにio.TextIOWrapperを冒頭に記述することで対処出来ました。
OSが違うので直接の回答になるかは分かりませんが、ご参考になれば。
変更前:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
変更後:
# -*- coding: utf-8 -*-
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
| {
"pile_set_name": "StackExchange"
} |
Q:
Arrow function in typescript interface with return type as void
I am trying to write arrow function in my type Script interface as below but getting error "Class 'ToastrService' incorrectly implements interface 'IToastr'."
interface IToastr{
(message:string,title:string):void;
}
@Injectable()
export class ToastrService implements IToastr {
(message:string,title:string):void {
toastr.success(message,title);
}
}
My question is: can we define a function signature in TS interface with return type as void??
I did try searching google as well but did not find any example. Thanks !!
A:
What you are doing seems fine just missing a name for the function (or if this is a constructor then the constructor keyword is missing)
interface IToastr{
toast(message:string,title:string):void;
}
@Injectable()
export class ToastrService implements IToastr {
toast(message:string,title:string):void {
toastr.success(message,title);
}
}
A:
Yes it is possible. Please consult the official typescript for more info.
Example 1:
interface SearchFunc {
(source: string, subString: string): void;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
// do smth
}
Example 2: Solution: You should name your function
interface IToastr{
FuncName(message:string,title:string):void;
}
class ToastrService implements IToastr {
FuncName(message:string,title:string):void {
// toastr.success(message,title);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Casl Vue set ability on reload + in router + after login based on role from async get request
Perhaps I am overlooking something very easy, but I have been looking at this for two days now and I cannot figure it out.
I have an Vue application where I would like to specify what a user can see or where he can go to based on his role. I am using casl-vue for this.
There are two moments I want to set the ability, on loading of the page and after login.
On page load
All works fine when I register the abilities with a synchronous function, like so:
main.js
import { abilitiesPlugin } from '@casl/vue';
import ability from '../config/ability';
Vue.use(abilitiesPlugin, ability);
ability.js
import { AbilityBuilder, Ability } from '@casl/ability';
export default AbilityBuilder.define((can, cannot) => {
const role = 'Admin';
switch (role) {
case 'Admin':
can('manage', 'all');
break;
case 'Author':
can('manage', 'all');
cannot('manage', 'users');
break;
case 'Trainer':
break;
case 'Participant':
cannot('manage', 'all');
break;
default:
cannot('manage', 'all');
};
})
However, when I want to get the role using a function that returns a promise (getCurrentUserRole()), and therefore make the function async like so:
ability.js
export default AbilityBuilder.define(async (can, cannot) => {
const role = await getCurrentUserRole();
switch (role) {
case 'Admin':
can('manage', 'all');
break;
...
default:
cannot('manage', 'all');
};
})
I receive the following error:
"TypeError: ability.on is not a function"
After login
Thankfully, updating the ability rules after login works using this.$ability.update:
const { role } = await someSignInFunction();
this.$ability.update(defineRulesFor(role));
this.$router.push({ name: 'home' });
However, it seems I cannot use this function on page load, because when I put it in App.vue (for example, in beforeCreate() or created()) the page is already loaded before I call ability.update, therefore the ability is updated 'too late'.
Vue router
I would also like to access the ability can method in my Vue Router instance (to control the routes my users can visit), but how do I get access to the ability instance in my router file?
If in any case my problem is not explained well, please let me know!
I am very grateful if anyone can help me with the setup structure.
Dependencies:
casl/ability: ^3.3.0
casl/vue: ^0.5.1
A:
The issue is that if you pass async function inside AbilityBuilder.define then AbilityBuilder.define returns a Promise. It can't magically make async code to be sync :)
So, what you need to do is to create a separate function defineRulesFor(role):
// src/config/rules.js
import { AbilityBuilder } from '@casl/ability'
export default function defineRulesFor(role) {
const { can } = AbilityBuilder.extract()
switch (role) {
case 'Admin':
can('manage', 'all');
break;
case 'Author':
can('manage', 'all');
cannot('manage', 'users');
break;
case 'Trainer':
break;
case 'Participant':
cannot('manage', 'all');
break;
default:
cannot('manage', 'all');
}
}
Then after login:
// inside Login.vue
import defineRulesFor from '../config/rules'
export default {
name: 'LoginPage',
methods: {
async login() {
const response = await axios.post(...)
const user = response.data
this.$ability.update(defineRulesFor(user.role))
}
}
}
And now you have 2 options:
Store user role in local storage and restore it on page reload:
// inside App.vue
import defineRulesFor from './config/rules'
export default {
name: 'App',
created() {
this.$ability.update(defineRulesFor(localStorage.getItem('userRole'))
}
}
Refetch information about user on page reload
// inside App.vue
import defineRulesFor from './config/rules'
export default {
name: 'App',
async created() {
const role = await getCurrentUserRole()
this.$ability.update(defineRulesFor(role))
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
If I transfer 'ONE DOLLAR' into your account, is it a 'FUNDS' transfer or 'FUND'?
Dictionaries don't help me.
fund [countable] -an amount of money that has been saved or has been made available for a particular purpose. and fund [plural] -money that is available to be spent.
Now, if I transfer ONE DOLLAR into your account, is it a fund transfer or funds? And, the sum is not for charity. It's merely a money-transfer which banks in India refer to as fund transfer or funds transfer. They have this option on netbanking sites.
A:
Fund and funds are two different words:
Funds is an indeterminate, uncountable amount of money or currency. (Def.n 2 in OLD.)
A fund is a countable noun meaning a collection of money to be used as payment or capital towards a certain purpose; account is a rough synonym. It offers no indication of how much money has been collected. The plural of this word is funds. (Def. 1 in OLD; def. 3 has the same meaning, just not necessarily about money.)
I've omitted the use of fund as a verb because it's not related to the question at hand.
A fund contains funds. For example:
Accounting needs to know which of our funds (2, plural) provided the revenue for the purchase.
The petty cash fund (2); it didn't cost very much.
Will we have enough funds (1) remaining in that account to buy lunch for everyone?
If we don't, we will have to wait until after our client's funds transfer (1) has gone through.
I'm surprised to hear that Indian English refers to a general movement of money from one account to another as a fund transfer. British, Australian and American English call it a funds transfer or transfer of funds. This makes more sense semantically, because fund transfer seems to imply a change in ownership of the account rather than a movement of money.
For example (ignore the electronic bit, it's not relevant to our discussion and just makes the term easier to search): Cambridge, Dictionary.com, Australian bank. Additionally, Google Books Ngram Viewer and the Corpus of Global Web-Based English both indicate that funds transfer is more popular by a wide margin. GloWbE shows that India prefers funds 67 to 37, though Bangladesh prefers fund 40 to 21, and Ireland is tied with both at 30.
Funds (or fund) describes the type of transfer, and together they form a compound noun. See the linked Cambridge and Dictionary.com definitions above, again ignoring the electronic portions. This noun is countable, but the pluralization applies to transfer. For example:
I processed seventeen funds transfers today.
Regardless of whether fund or funds is the term of choice, it should not be changed based on the amount of money being transferred, because the term never actually specifies a particular quantity of currency. The source or intended purpose of the money is also irrelevant, for the same reason: the term means nothing more than a simple movement of an unspecified quantity of money from one storage space to another.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pass a Value when delete button is clicked
I have a delete button on a gridview for each row that calls gvSiteInfo_RowDeleting(object sender, EventArgs e) when it is clicked. How do I find out the value of the row number of the clicked delete button? I need to have the row number in the delete method where i specify with << NEED ROW NUMBER HERE!! >>
So far I haven't been able to turn up anything searching the web and when i print out the values of sender and e they don't tell me anything useful.
protected void gvSiteInfo_RowDeleting(object sender, EventArgs e)
{
SiteDB site = new SiteDB();
site.SelectedConnectionString = "SQLDEV08";
site.deleteSite(<<<NEED ROW NUMBER HERE!!>>>);
}
<asp:GridView ID="gvSiteInfo" runat="server" AutoGenerateColumns="False" OnSorting="gvSiteInfo_Sorting" width="100%"
AllowSorting="True" OnRowDeleting="gvSiteInfo_RowDeleting" >
<Columns>
<asp:CommandField ButtonType="Button" ShowDeleteButton="True" ShowCancelButton="True" />
<asp:BoundField DataField="prodServer" HeaderText="Production Server"
SortExpression="prodServer" />
<asp:BoundField DataField="prodIP" HeaderText="Production IP Address"
SortExpression="prodIP" />
<asp:BoundField DataField="Priority" HeaderText="Priority"
SortExpression="Priority" />
<asp:BoundField DataField="Platform" HeaderText="Platform"
SortExpression="Platform" />
</Columns>
</asp:GridView>
A:
The RowDeleting event actually takes GridViewDeleteEventArgs, not your standard EventArgs. There is a RowIndex property on the former that will give you the index of the row being deleted.
| {
"pile_set_name": "StackExchange"
} |
Q:
Kafka listener, get all messages
Good day collegues.
I have Kafka project using Spring Kafka what listen a definite topic.
I need one time in a day listen all messages, put them into a collection and find specific message there.
I couldn't understand how to read all messages in one @KafkaListener method.
My class is:
@Component
public class KafkaIntervalListener {
public CountDownLatch intervalLatch = new CountDownLatch(1);
private final SCDFRunnerService scdfRunnerService;
public KafkaIntervalListener(SCDFRunnerService scdfRunnerService) {
this.scdfRunnerService = scdfRunnerService;
}
@KafkaListener(topics = "${kafka.interval-topic}", containerFactory = "intervalEventKafkaListenerContainerFactory")
public void intervalListener(IntervalEvent event) throws UnsupportedEncodingException, JSONException {
System.out.println("Recieved interval message: " + event);
IntervalType type = event.getType();
Instant instant = event.getInterval();
List<IntervalEvent> events = new ArrayList<>();
events.add(event);
events.size();
this.intervalLatch.countDown();
}
}
My events collection always has size = 1;
I tried to use different loops, but then, my collection become filed 530 000 000 times the same message.
UPDATE:
I have found a way to do it with factory.setBatchListener(true); But i need to find launch it with @Scheduled(cron = "${kafka.cron}", zone = "Europe/Moscow"). Right now this method is always is listening. Now iam trying something like this:
@Scheduled(cron = "${kafka.cron}", zone = "Europe/Moscow")
public void run() throws Exception {
kafkaIntervalListener.intervalLatch.await();
}
It doesn't work, in debug mode my breakpoint never works on this site.
A:
The listener container is, by design, message-driven.
For fetching messages on-demand, it's better to use the Kafka Consumer API directly and fetch messages using the poll() method.
| {
"pile_set_name": "StackExchange"
} |
Q:
MSBuild hangs after NUnit is finished
I'm trying to set up a MSBuild with NUnit as unit test driver but the script keeps hanging after NUnit is done. It doesn't seem to finalize its work and let MSBuild get on with its job.
I'm working in .NET 4.0 and using NUnit 2.5.8.
If I run the test manually or using the gui (either VS2010 or NUnit) it works fine but not when called by MSBuild.
I'd appreciate any help with error finding or just a heads up on where to looks for answers.
The manual command looks like this:
C:\....>nunit\nunit-console.exe buildbinaries\YYYY.XXXX.Extractor.Test.IntegrationTest.dll /xml=nunit.xml
and the abbreviated MSBuild:
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- define folders for build output and reports -->
<PropertyGroup>
<BuildPath>buildbinaries\</BuildPath>
<ReportPath>buildreports\</ReportPath>
<ReleaseFolder>release_artefacts\</ReleaseFolder>
<PublishFolder>c:\ZZZ Applications\published builds\</PublishFolder>
<DeploymentFolder>\\seldclq99\ZZZ_Costanza_Dev$\</DeploymentFolder>
</PropertyGroup>
<PropertyGroup>
<!-- specify assemblies that should be included in coverage report -->
<NCoverAssemblyList>YYYY.XXXX.Extractor.Business.dll; YYYY.XXXX.Extractor.Common.dll YYYY.XXXX.Extractor.Configuration.dll YYYY.XXXX.Extractor.DAL.Access.dll YYYY.XXXX.Extractor.DAL.Facade.dll YYYY.XXXX.Extractor.Service.Contracts.dll YYYY.XXXX.Extractor.Service.dll YYYY.XXXX.Extractor.Service.Host.WebHost.dll YYYY.XXXX.Extractor.ServiceGateway.dll</NCoverAssemblyList>
</PropertyGroup>
<!-- define item group for deliverables -->
<ItemGroup>
<Binaries Include="$(BuildPath)/**/*.*" Exclude="$(BuildPath)nunit*" />
</ItemGroup>
<!--
This is the default target that will be executed if MSBuild is not started
with a specific target (this is decided by the DefaultTargets attribute in
the root element of this XML document)
-->
<Target Name="BuildAndTest">
<CallTarget Targets="SetupDirs" />
<CallTarget Targets="Build" />
<CallTarget Targets="UnitAndIntegrationTest" />
<CallTarget Targets="FxCop" />
<CallTarget Targets="CopyToReleaseFolder" />
</Target>
<!-- Setup folders used during the build -->
<Target Name="SetupDirs">
<RemoveDir Directories="$(ReportPath);$(BuildPath);$(ReleaseFolder)" ContinueOnError="true"/>
<MakeDir Directories="$(ReportPath);$(BuildPath);$(ReleaseFolder);$(AssemblyVersionFolder)" ContinueOnError="true"/>
</Target>
<Target Name="Build">
<!-- build the software using msbuild -->
<!-- Build error in the Install build-->
<MSBuild ContinueOnError="true" RebaseOutputs="false" Targets="Clean;Rebuild" Projects="YYYYXXXXExtractor.sln" Properties="Configuration=Release;OutDir=..\$(BuildPath)" />
</Target>
<!--Run the coverage stats-->
<Target Name="UnitAndIntegrationTest">
<Exec Command="nunit\nunit-console.exe buildbinaries\YYYY.XXXX.Extractor.Test.IntegrationTest.dll /xml=$(ReportPath)nunit.xml "/>
<CallTarget Targets="UnitTest" />
</Target>
<Target Name="UnitTest">
<Exec Command="nunit\nunit-console.exe buildbinaries\YYYY.XXXX.Extractor.Test.UnitTest.dll /xml=$(ReportPath)nunit.xml"/>
</Target>
<!-- Run FxCop -->
<!-- The ForceError.bat fires if the xml file is not found... aka an error was found -->
<!-- The quiet command forces an Xml file ONLY if warnings or Errors are found -->
<Target Name="FxCop">
<Exec Command="..\tools\fxcop\FxCopCmd.exe /p:..\FxCopSettings.FxCop /o:$(ReportPath)fxcop.xml" />
<Exec Condition="Exists('$(ReportPath)fxcop.xml')" Command="..\tools\fxcop\FX_Cop_Failed_Rule_Checks.bat" />
<!--STATS: Run again but don't fail and this time run for all rules.-->
<Exec Command="..\tools\fxcop\FxCopCmd.exe /p:..\FxCopSettingsALLRULES.FxCop /o:$(ReportPath)fxCopAllRules.xml" />
</Target >
A:
I had the same problem with NUnit 2.5.8. There is some discussion of this at the nunit site about the test process hanging. I switched to NUnit 2.5.7 and the problem went away.
It looks like this was fixed a couple of weeks ago in 2.5.9.
| {
"pile_set_name": "StackExchange"
} |
Q:
Plot at indexes in pandas Series
I have a pandas Series with some data in it:
In [117]: data1.C_TRQENG
Out[117]:
0 Nm
1 4.85
2 5.339
3 2.552
4 -0.171
5 -0.142
6 1.218
7 -1.133
8 2.188
9 0.88
10 4.316
11 10.06
12 8.925
13 8.262
14 7.627
...
Name: C_TRQENG, Length: 1230, dtype: object
and another Series that has some max values in it from this series
In [115]: data
Out[115]:
915 199.571429
1087 173.339207
984 114.696170
27 90.184324
82 80.805341
Name: C_TRQENG, dtype: float64
In [116]: data.index
Out[116]: Int64Index([915, 1087, 984, 27, 82], dtype='int64')
I would like to plot the original data at these indexes with a window of plus/minus 100 in order to get a glimpse of what is happening at these points. How can I do this with plot()?
A:
Used pandas slicing to create a window for each index, then plotted it
nlarge = pct.nlargest(5)
for ind in nlarge.index:
high = ind + 100
low = ind - 100
window = data.C_TRQENG[low:high]
window = window.convert_objects(convert_numeric=True)
window.plot()
| {
"pile_set_name": "StackExchange"
} |
Q:
What's that? It seems, they were meteoroids but i am not sure, please help!
I guess that thing must be meteoroid!
Strange thing about them was they appear and disappear then appear again!
I think that was meteoroid but why were some of them disappearing and reappearing?
P.S. this process took around 1 minute, and there were nothing any symptoms of meteoroid!(as shown in some YouTube videos)
A:
Meteorites would not suddenly appear at ground level, would not hover, and would not move sideways. Meteorites generally appear as fast-moving pinpoints of white light descending downward from the upper sky, and disappear before they reach ground.
These could be ball lightning, which is known to move up and down, to hover, and to be repelled by buildings and landscape. Ball lightning lasts longer than other types of lightning. Here's a video of ball lightning: https://www.youtube.com/watch?v=D4vV3KxQ16c. You get views of various kinds later in the video.
Or these might be the notorious Min Min lights, if these pictures were taken in Australia.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I create a new partition with mountpoint by splitting an existing partition?
How can I split an existing partition (NTFS) to get space for a new partition and create a mountpoint for it?
A:
You need to boot from a live CD or USB and use gparted to partition your drive. It should be called something like Partition Manager in the System->Administration menu.
Read through this tutorial for gparted - it should tell you everything you need to be able to:
Shrink the partition
Create a new partition in the free space created by this action
You should take a note of the device path of the partition you create (eg. /dev/sda5). To mount this drive you can run this command:
sudo mount -t ext4 /dev/sda5 /path/to/mountpoint
Replace ext4 with the file system type, /dev/sda5 with the device path you noted down and /path/to/mountpoint with the file path you want it to be mounted to.
To permanently mount this partition, you need to edit /etc/fstab. Before you do, make a copy to back it up in case you mess it up somehow. To edit /etc/fstab, press Alt+F2 and enter gksudo gedit /etc/fstab. This will prompt you for your password and then open the file in the text editor.
Once opened, add this line to the end of the file:
/dev/sda5 /home ext4 defaults 0 2
but obviously you need to use your specific information instead. Once you have done this, save and close the file. The partition will now be mounted to the specified path every time you start up the computer.
A:
Install gparted
After installation you can find it under System>>Administration>>Gparted.
Right click and unmount your NTFS partition first.(In my case i have used /dev/sda6)
Select your NTFS partition and then right click on it and then choose Resize/Move.
For example i have maximum size of 39998 MB.
So now i am giving 30000 MB
Now goto Edit and choose Apply all Operations.
After few minutes the opration will get completed.
Now you will see unallocated space of 9.77 GB
Right click on the unalloacated space and select New to create new partition.
Now you are done.
Note:
To learn more about Gparted,you can have a look at this tutorial.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding the limit of a fraction
Find $$lim_{x \to 3} \frac{x^3-27}{x^2-9}$$
What I did is:
\begin{align}
\lim_{x \to 3} \frac{x^3-27}{x^2-9} &= \lim_{x \to 3} \frac{(x-3)^3+9x-27x}{(x-3)(x+3)} = \lim_{x \to 3} \frac{(x-3)^3+9(x-3)}{(x-3)(x+3)} \\
&= \lim_{x \to 3} \frac{(x-3)^3}{(x-3)(x+3)} + \lim_{x \to 3} \frac{9(x-3)}{(x-3)(x+3)} \\
&= \lim_{x \to 3} \frac{(x-3)^2}{(x+3)} + \lim_{x \to 3} \frac{9}{(x+3)} =0 + \frac{9}{6}
\end{align}
Wolfram factor the numerator to $(x-3)(x^2+3x+9)$ is there a quick way to find this?
A:
Wolfram factor the numerator to $(x-3)(x^2+3x+9)$ is there a quick way to find this?
Generally, you have
$$
a^{n+1}-b^{n+1}=(a-b)(a^n+a^{n-1}b+a^{n-2}b^2+\cdots+a^2b^{n-2}+ab^{n-1}+b^n)
$$ (to see this expand the right hand side, then terms telescope).
Then apply it to $a=x$, $b=3$, $n=2$ giving
$$
x^3-27=(x-3)(x^2+3x+9).
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to restrict a Swift generic class function return type to the same class or subclass?
I am extending a base class (one which I do not control) in Swift. I want to provide a class function for creating an instance typed to a subclass. A generic function is required. However, an implementation like the one below does not return the expected subclass type.
class Calculator {
func showKind() { println("regular") }
}
class ScientificCalculator: Calculator {
let model: String = "HP-15C"
override func showKind() { println("scientific") }
}
extension Calculator {
class func create<T:Calculator>() -> T {
let instance = T()
return instance
}
}
let sci: ScientificCalculator = ScientificCalculator.create()
sci.showKind()
The debugger reports T as ScientificCalculator, but sci is Calculator and calling sci.showKind() returns "regular".
Is there a way to achieve the desired result using generics, or is it a bug?
A:
Ok, from the developer forums, if you have control of the base class, you might be able to implement the following work around.
class Calculator {
func showKind() { println("regular") }
required init() {}
}
class ScientificCalculator: Calculator {
let model: String = "HP-15C"
override func showKind() { println("\(model) - Scientific") }
required init() {
super.init()
}
}
extension Calculator {
class func create<T:Calculator>() -> T {
let klass: T.Type = T.self
return klass()
}
}
let sci:ScientificCalculator = ScientificCalculator.create()
sci.showKind()
Unfortunately if you do not have control of the base class, this approach is not possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
Need help changing table array by moving a column in PHP
I have been handed the task of making some changes to a PHP webpage that was coded by someone who has left the company and my Php is exactly exeprt.
The page in question displays a database table in a SQL server that allows you to update values via an update page.
Currently the Update function sits under the 'Action' column at the end of the table and I need to relocate the 'Action' column to the start of the table before the 'Name' column.
When I try to make changes, I break the table array and the 'Update' function no longer works.
Current order of columns are;
Name,
Value,
Details,
Action
The new order of columns attempting to achieve
Action,
Name,
Value,
Details
I have also included the code in question.
Any assistance would be appreciated
Note** It is a Php website running on a Windows box and connecting to a MSSQL Server 2008
$query = sqlsrv_query($conn, 'SELECT * FROM Database_Values ORDER BY Name ASC');
// Did the query fail?
if (!$query) {
die( FormatErrors( sqlsrv_errors() ) );
}
// Dump all field names in result
$field_name = "";
foreach (sqlsrv_field_metadata($query) as $fieldMetadata) {
foreach ($fieldMetadata as $name => $value) {
if ($name == "Name") {
$field_name .= $value . '-';
}
}
}
$field_name = substr_replace($field_name, "", -1);
$names = explode("-", $field_name);
?>
<div style="max-height:610px; overflow:auto;">
<table border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" class="table" width="100%">
<tr>
<?php
foreach ($names as $name) {
?>
<th><?php echo $name; ?></th>
<?php
}
?>
<th>Action</th>
</tr>
<?php
// Fetch the row
while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
//print_r($row);
?>
<tr>
<?php
foreach ($row as $key => $eachrow) {
?>
<td nowrap="nowrap">
<?php echo $eachrow; ?>
</td>
<?php
}
?>
<td nowrap="nowrap">
<?php $groupid = $_SESSION["gid"] ;
if($groupid!='1') {
?>
<a href="javascript:void(0);" title="Permission Restricted" >Update</a>
<?php } else { ?>
<a href="javascript:void(0);" onclick="update('<?php echo $row['CodeName'] ?>');">Update</a>
<?php } ?>
</td>
</tr>
<?php
}
?>
</table>
</div>
A:
All you need to do is change the order of the th and td cells in the html
$query = sqlsrv_query($conn, 'SELECT * FROM Database_Values ORDER BY Name ASC');
// Did the query fail?
if (!$query) {
die( FormatErrors( sqlsrv_errors() ) );
}
// Dump all field names in result
$field_name = "";
foreach (sqlsrv_field_metadata($query) as $fieldMetadata) {
foreach ($fieldMetadata as $name => $value) {
if ($name == "Name") {
$field_name .= $value . '-';
}
}
}
$field_name = substr_replace($field_name, "", -1);
$names = explode("-", $field_name);
?>
<div style="max-height:610px; overflow:auto;">
<table border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" class="table" width="100%">
<tr>
<th>Action</th>
<?php
foreach ($names as $name) {
?>
<th><?php echo $name; ?></th>
<?php
}
?>
</tr>
<?php
// Fetch the row
while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
//print_r($row);
?>
<tr>
<td nowrap="nowrap">
<?php $groupid = $_SESSION["gid"] ;
if($groupid!='1') {
?>
<a href="javascript:void(0);" title="Permission Restricted" >Update</a>
<?php } else { ?>
<a href="javascript:void(0);" onclick="update('<?php echo $row['CodeName'] ?>');">Update</a>
<?php } ?>
</td>
<?php
foreach ($row as $key => $eachrow) {
?>
<td nowrap="nowrap">
<?php echo $eachrow; ?>
</td>
<?php
}
?>
</tr>
<?php
}
?>
</table>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to implement scale-9 (9-slice) for custom background art created for UIButton
What do I need to do programatically in order to use the same background image for UIButton of variable size? (commonly known as 9-slice scaling or scale-9)
A:
I know this is an old thread, but to anyone who stumbles upon this after iOS 5 is released, it should be noted from Apple's documentation that the stretchableImageWithLeftCapWidth:topCapHeight: method is deprecated as of iOS 5:
Deprecated UIImage Methods
Deprecated in iOS 5.0. Deprecated. Use the resizableImageWithCapInsets: instead, specifying cap insets such that the interior is a 1x1 area.
So now that iOS 6 has been announced and will be here soon, anyone developing for iOS 5 and higher should probably take a look at resizableImageWithCapInsets instead, which documentation can be found here:
UIImage Class Reference - resizableImageWithCapInsets
Just thought I'd mention it to help any developers who needed an updated answer to this problem.
A:
Check out:
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
In the UIImage class.
If I understand what you're looking for correctly, this while allow you to use one png to define how your button looks, and it will stretch to any size vertically or horizontally.
| {
"pile_set_name": "StackExchange"
} |
Q:
Почему в javascript шаблонных строках map цикл получается с запятыми?
Есть javascript код
` ${respons.some_array.map((item, index)=>`
<div>${index}</div>
`)}`;
это выражение возвращает код с запятыми
<div>0</div>
,
<div>1</div>
,
<div>2</div>
,
<div>3</div>
,
<div>4</div>
,
<div>5</div>
,
<div>6</div>
,
<div>7</div>
"
После использования join('') запятые убираются
Почему получаются запятые и как на них действует join
A:
Потому что map возвращает массив, который для перевода в строку пропускается через toString, который разделяет элементы массива запятыми.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString
join - метод массива, который возвращает строку, в которой строковые представления элементы массива разделены строкой, которая передана в join как параметр.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
| {
"pile_set_name": "StackExchange"
} |
Q:
Radio buttons checked changing submit text
My site structure consists on an index.php which is styled by a css file. It then includes the following php code in a separate file:
<?php include("globals.php"); ?>
<form action="<?php echo $website.$relative_string;?>" name="subscribe" onsubmit="javascript:return checkEmail(this);" method="post">
<div id="cell8" class="titlecell2"><h3>Email:</h3></div>
<div id="cell9" class="inputcell2">
<input type="text" class="inputfield2" name="email" value="Your Email..." id="email2" maxlength="255" onfocus="this.value='';">
</div>
<div id="cell10" class="textcell3">
<input name="group" type="hidden" id="group[]" value="<?php echo $group; ?>">
<input name="subscribe" id="sub" type="radio" value="true" checked>
</span>Subscribe </p>
</div>
<div id="cell11" class="buttoncell">
<button type="submit" name="Submit2" value="Join" id="submitButton2">
<span>OK</span>
</button>
</div>
<div id="cell8" class="textcell4">
<input type="radio" name="subscribe" id="unsub" value="false">
</span>Un-Subscribe </p>
</div>
</form>
It appears on screen with no problems in the correct layout as my css style sheet. What I would like this to do is when I select the "Subscribe" radio button the submit button text "OK" changes to "Join". When I click on the Unsubscribe button text "OK" or "Join" changes to "Leave".
I tried to make some code from research:
if(document.getElementById('sub').checked) {
document.write("<span>Join</span>"
}
else if(document.getElementById('unsub').checked) {
document.write("<span>Leave</span>)
}
I think this kind of worked in that it changed to Join (replacing the OK line, but obviously didn't update on clicking unsubscribe. I guess it would update on refreshing the page if my default wasn't join. I guess I need to do some form of onclick but then I have no idea how to adjust that span ok bit.
Please help?
Many thanks Chris
A:
Here is a solution in plain JavaScript without jQuery. It avoids the unnecessary overhead.
This should work, but I haven't had a chance to test it:
var sub = document.getElementById('sub'); // Save element to a variable, so you don't have to look for it again
var unsub = document.getElementById('unsub');
var btn = document.getElementById('submitButton2');
sub.onchange = function() //When sub changes
{
if(sub.checked) //If it's checked
{
btn.innerHTML = "<span>Join</span>"; // Set button to Join
}
else // If not..
{
btn.innerHTML = "<span>OK</span>"; // Set button to OK
}
}
unsub.onchange = function() //When unsub changes
{
if(unsub.checked) //If it's checked
{
btn.innerHTML = "<span>Leave</span>"; // Set button to Leave
}
else // If not..
{
btn.innerHTML = "<span>OK</span>"; // Set button to OK
}
}
However, you should not do it like this.
You should combine the two radio buttons into a radio group.
In that case you will listen for radio group to change, get the value of the radio group, set button text according to the value.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is the power set always closed under complementation and unions?
Given a set S, its power set $\mathcal{P}(S)$ always forms a sigma algebra (I read this in Casella & Berger). That is, the power set contains as an element S itself (which the power set clearly does, I have no problems with that), but also:
The power set must be closed under complementation: $$A \in \mathcal{P}(S) \implies A^c \in \mathcal{P}(S),$$
and the power set must be closed under countable unions:
$$A_1, A_2, ... \in \mathcal{P}(S) \implies \bigcup_{i=1}^\infty A_i \in \mathcal{P}(S). $$
However, this was not proven but only shown anecdotally by writing out the power set of the set $S = \{1,2,3\}$. While I certainly believe that this is true (it makes sense intuitively), I am having trouble understanding why it is true, much less proving that it is true. So, why does the power set have these properties?
A:
The complement here is the relative complement in $S$:
$$A^c=S\setminus A=\{s\in S:s\notin A\}\,.$$
By definition this is a subset of $S$ and is therefore an element of $\wp(S)$.
Similarly, if $A_n\in\wp(S)$ for each $n\in\Bbb Z^+$, let $A=\bigcup_{n\in\Bbb Z^+}A_n$. Then $x\in A$ if and only if $x\in A_n$ for some $n\in\Bbb Z^+$: every element of $A$ is an element of at least one $A_n$. And every $A_n$ is a subset of $S$, so every element of an $A_n$ is an element of $S$. Now put the pieces together: every element of $A$ is an element of $S$. That’s exactly what it means to say that $A\subseteq S$, i.e., that $A\in\wp(S)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Noncontext free for quotient
Have such exercise:
Let $L_1=\{a^{2n}b^n|n\geq1\}^*$
and $L_2=\{b^na^n|n\geq 1\}^*b$
Prove, that $L_1, L_2$ are context free, while quotient $L_1/L_2$ is not context-free.
(This is home exercise, which I am not sure what to make of it. 3rd one)
Anyway, proving $L_1, L_2$ are CFL is trivial.
For $L_1$:
S->aaSb|$\epsilon$
For $L_2$
S->Ab
A->bAa|$\epsilon$
So far so good, grammar can be constructed, i.e CFL. Fine.
But quotient.. Lets list few words for $L_1$: $\epsilon$ then: aab, aabaab, aabaabaab, $\dots$ then aaaabb, aaaabbaaaabb, $\dots$ and so on - string under Kleene, which contains twice as much $a$ than $b$
Now about $L_2$ words: b then bab,babab,bababab,$\dots$ then bbaab,bbaabbaab,$\dots$, ie - $(b^na^n)^*b$
But.. Only words in $L_1$ are of format which ends in suffix ...ab are where $n=1$: $aab,aabaab,\dots$, moreover - if we take string from $L_1$, for example $aabaab$, we kinda remove trailing $b$ ($aabaa$), after which we can't really remove anything else, in this particular case we would have to remove suffix $bbaa$, but there is no such suffix in word from $L_1$
So, all in all - quotient, to my understanding is $L_1$, with only difference that there is very last b always removed. And it feels to me like CF, what am I doing wrong?
Edit: According to comment, I have mistake in my thoughts, which is reasonable, we dont have to Kleenize $n$ in each substring.
Ie $aaaabbaab$ for $L_1$ is possible. Ok, now lets look exactly at $aaaabbaab$ - first remove trailing $b$, get $aaaabbaa$. Now $bbaa$ - resulting in $aaaa$.. So all in all, quotient is still $L_1$, which has some arbitrary suffix removed. Still feels CF to me
A:
Work backwards, from right to left.
Try to find which strings of the form $a^*$ belong to $L_1/L_2$. So find matches of strings $w_1\in L_1$ and $w_2\in L_2$ such that at the start only a string of the form $a^*$ sticks out: $w_1= a^k w_2$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysql. Update not null column with null value
mysql> SHOW COLUMNS from users LIKE 'created_at';
+------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| created_at | datetime | NO | | NULL | |
+------------+----------+------+-----+---------+-------+
1 row in set (0.00 sec)
mysql> SHOW VARIABLES LIKE 'innodb_strict_mode';
+--------------------+-------+
| Variable_name | Value |
+--------------------+-------+
| innodb_strict_mode | ON |
+--------------------+-------+
1 row in set (0.00 sec)
mysql> UPDATE `users` SET `created_at` = NULL WHERE `users`.`id` = 200;
Query OK, 1 row affected, 1 warning (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 1
mysql> SELECT `created_at` from `users` WHERE `users`.`id` = 200;
+---------------------+
| created_at |
+---------------------+
| 0000-00-00 00:00:00 |
+---------------------+
1 row in set (0.00 sec)
Is it normal behavior? Just warning.
A:
Yes, it can be normal behavior. It depends on server's SQL Mode. It is possible that database is not in strict mode, and zero-dates are allowed.
See more details on this page - Server SQL Modes: STRICT_ALL_TABLES, STRICT_TRANS_TABLES, NO_ZERO_DATE.
Check current SQL mode using this query -
SHOW VARIABLES WHERE variable_name = 'sql_mode';
| {
"pile_set_name": "StackExchange"
} |
Q:
How to declare Filter attribute globally in Global.asax.cs file
I have implemented one action filter in my MVC project. Now I want to add it globally so that I do not need to write filter attribute just above the action methods. I am using BundleMinifyInlineJsCss nuget package.
I have tried with following code in Global.asax.cs file:
GlobalFilters.Filters.Add(new ReplaceTagsAttribute());
Here is my filter code:
public class ReplaceTagsAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Filter = new BundleAndMinifyResponseFilter(filterContext.HttpContext.Response.Filter);
}
}
I am getting an error: Filtering is not allowed. How can I declare it Globally?
Thanks.
A:
I think adding a null check will work for you.
public class ReplaceTagsAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var response = filterContext.HttpContext.Response;
if (response.Filter == null) return; // <-----
response.Filter = new BundleAndMinifyResponseFilter(response.Filter);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Query using Mysql Update
I have two tables T and T1
T
id p o
1 47 1
2 47 2
3 47 25
T1
id p
1 47
2 48
3 49
I am looking to find a way to get T as the following table
id p o
1 47 1
2 47 2
3 47 0
If T.p in (select T1.p from T1) and the value of the field o is the max then update o
into 0.
I try the following query but it didn't work
Update T
SET T.o=0
WHERE T.P IN (select T1.p from T INNER join select T.p from T ON T.p=T1.p)
AND T.o In (select Max(T.o) from T)
For more details Sqlfiddle
Many thanks in advance .
A:
SQL Fiddle
Update T
SET T.o=0
WHERE T.P IN (select T1.p from t1 )
AND t.o IN (SELECT * FROM(SELECT MAX(t.o) FROM t)x)
| {
"pile_set_name": "StackExchange"
} |
Q:
Notify or callback flask after remote celery worker is completed
I am running celery client(Flask) and worker in two different machines, now once the worker has completed the task, I need to callback a function on client side. Is this possible?
Celery client:-
celery_app=Celery('test_multihost', broker='amqp://test:test@<worker_ip>/test_host', backend='rpc')
result= testMethod1.apply_async((param1, param2,param3), link=testMethod2.s())
@celery_app.task
def testMethod2():
#testMethod2 body.
Celery Worker:-
celery_app=Celery('test_multihost', broker='amqp://test:test@<worker_ip>/test_host', backend='rpc')
@celery_app.task
def testMethod1():
#testMethod1 body
But the problem is the function testMethod2 is getting executed on the celery worker side, not on the client side.
Is there anyway that I can callback the method on client side?
A:
I solved this problem using @after_task_publish from celery signals.
The code snippet is as follows:-
@after_task_publish.connect(sender=<registered_celery_task>)
def testMethod2(sender=None, headers=None, body=None, **kwargs):
#callback body
The testMethod2 will be called after the celery worker is completed on the remote machine.
Here I can access the result of celery worker using headers parameter.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server 2008 - fulltext search not stopping on stop words
I've created a stoplist based on the system's list and I set up my fulltext indexes to use it.
If I run the code select unique_index_id, stoplist_id from sys.fulltext_indexes I can see that all my indexes are using the stoplist with ID 5 which is the one I have created.
When I run the text using the FTS_PARTIAL the result comes correct.
example:
SELECT special_term, display_term
FROM sys.dm_fts_parser
(' "Rua José do Patrocinio nº125, Vila América, Santo André - SP" ', 1046, 5, 0)
The words that I added to the stoplist are shown as noise words. But for some reason when I run my query it brings me the register containing the stopwords too.
For example:
SELECT *
FROM tbEndereco
WHERE CONTAINS (*, '"rua*" or "jose*"')
Brings me the register above as I would expect. Since the word 'rua' should be ignored but 'Jose' would be a match.
But if I searched:
SELECT *
FROM tbEndereco
WHERE CONTAINS (*, '"rua*"')
I would expect no register to be found. Since 'rua' is set to be a stopword.
I'm using Brazilian (Portuguese) as the stoplist language.
So the word "Rua" (that means "Street") should be ignored (as I added it to the stop list). It is recognized as noise by the parser but when I run my query it brings me registers that contain "Rua".
My search is an address search, so it should ignore the words such as "Street", "Avenue", etc.. (in Portuguese of course and which I added them all as well).
This is the query that I'm using to look up the tables.
select DISTINCT(PES.idPessoa)
, PES.Nome
, EN.idEndereco
, EN.idUF
, CID.Nome as Cidade
, EN.Bairro
, EN.Logradouro
, EN.Numero
, EN.Complemento
, EN.CEP
, EN.Lat
, EN.Lng
from tbPessoa PES
INNER JOIN tbAdvogado ADV ON PES.idPessoa = ADV.idPessoa
INNER JOIN tbEndereco EN ON PES.idEmpresa = EN.idEmpresa
LEFT JOIN tbCidade CID ON CID.idCidade = EN.idCidade
where adv.Ativo = 1
and CONTAINS (en.*, '"rua*"')
OR EN.idCidade IN (SELECT idCidade
FROM tbCidade
WHERE CONTAINS (*, '"rua*"'))
OR PES.idPessoa IN (SELECT DISTINCT (ADVC.idPessoa)
FROM tbComarca C
INNER JOIN tbAdvogadoComarca ADVC
ON ADVC.idComarca = C.idComarca
WHERE CONTAINS (Nome, '"rua*"'))
OR PES.idPessoa IN (SELECT OAB.idPessoa
FROM tbAdvogadoOAB OAB
WHERE CONTAINS (NROAB, '"rua*"'))
I tried both FREETEXT and CONTAINS. Using something simpler like WHERE CONTAINS (NROAB, 'rua')) but it also brought me the registers containing "Rua".
I thought my query could have some problem then I tried a simpler query and it also brought me the stop-word "Rua".
SELECT *
FROM tbEndereco
WHERE CONTAINS (*, 'rua')
One thing I noticed is that the words that were native from the system stoplist work just fine. For example, if I try the word "do" (which means "of") it does not bring me any registers.
Example:
SELECT *
FROM tbEndereco
WHERE CONTAINS (*, '"do*"')
I tried to run the command "Start full population" through SSMS in all tables to check whether that was the problem and got nothing.
What am I missing here. This is the first time I work with Fulltext indexes and I may be missing some point setting it up.
Thank you in advance for your support.
Regards,
Cesar.
A:
You have changed your question so I will change my answer and try to explain it a little better.
According to Stopwords and Stoplists:
A stopword can be a word with meaning in a specific language, or it
can be a token that does not have linguistic meaning. For example, in
the English language, words such as "a," "and," "is," and "the" are
left out of the full-text index since they are known to be useless to
a search.
Although it ignores the inclusion of stopwords, the full-text index
does take into account their position. For example, consider the
phrase, "Instructions are applicable to these Adventure Works Cycles
models". The following table depicts the position of the words in the
phrase:
I am not sure why, but I think it only applies when using a phrasal search like:
If you have a line like this:
Teste anything casa
And you query the fulltext as:
SELECT *
FROM Address
WHERE CONTAINS (*, '"teste rua casa"')
The line:
Teste anything casa
Will be returned. In that case, the fulltext will translate your query as something like this:
"Search for 'teste' near any word near 'casa'"
When you query the fulltext using the "or" operator or only search for one word the rule does not apply. I have tested it several times for about 3 months and I never understood why.
EDIT
if you have the line
"Rua José do Patrocinio nº125"
and you query the fulltext
"WHERE CONTAINS (, '"RUA" or "Jose*" or "do*"')"
it will bring the line because it DOES contains at least one of the words you are searching for and not because the word "rua" and "do" are being ignored.
| {
"pile_set_name": "StackExchange"
} |
Q:
Algorithm to get a range of discontinuous values
I am trying to draw a "broken" ellipse via:
PointF p;
List<IntPoint> list;
int res = 1000;
for(int i = 0; i < res; ++i)
{
if(i <= 250) // do nothing
else
{
p.X = h + a * Math.Cos(i/res * Math.PI * 2);
p.Y = k + b * Math.Sin(i/res * Math.PI * 2);
list.Add(p);
}
}
This code will cut the first 1/4 of the ellipse off and store the valid points in list. In this case it is easy to say that the range of valid angle lies from 90 to 360 degrees.
However what if I want to have an ellipse like this (assuming the cutting off point is known):
Now that the angle is not a continuous value (since valid angle is from about 100-360 degrees & 0-70 degrees), is there an algorithm to quantify the range of valid angles? If so, what should the data structure look like?
A:
Angles wrap. so you can treat (100, 360) + (0,70) as (100,360)+(360,430), i.e. it is simply (100,430).
int startAngle = 100;
int endAngle = 430;
PointF p;
List<IntPoint> list;
int res = 1000;
for(int i = startAngle*res/360; i <= endAngle*res/360; ++i)
{
p.X = h + a * Math.Cos(i/res * Math.PI * 2);
p.Y = k + b * Math.Sin(i/res * Math.PI * 2);
list.Add(p);
}
I've left the code close to yours, but unless there is a specific reason, you might want to use floating point rather than int.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a jquery plugin with jquery ui-like parameter acceptance
I am trying to create a plugin very that has similar usage to the jquery ui plugin for dialogs. The usage I am after looks like this
First, to set options for my plugin (with a default action) you could pass in params like this.
$('#myId').dialog({
value1 : 'someValue',
value2 : 'anotherValue',
//...
});
Also, I want to be able to wire-up specific events using "key words". For instance in jquery.UI you can call this to close a dialog
$('#myId').dialog('close');
My question is how do I setup my plugin so that it does one thing if it is being passed in the settings or it does other things depending on the keywords passed in? I tried looking at some of the jquery ui code but I'm not sure I understand what it's doing or even where to start to just pull out this functionality.
A:
Have a look at jQuery Plugins/Authoring, specifically Plugin Methods.
Example:
(function( $ ){
var methods = {
init : function( options ) { /* THIS */ },
show : function( ) { /* IS */ },
hide : function( ) { /* GOOD */ },
update : function( content ) { /* !!! */ }
};
$.fn.tooltip = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
}
};
})( jQuery );
Then...
$('div').tooltip(); // calls the init method
$('div').tooltip({ // calls the init method
foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method
| {
"pile_set_name": "StackExchange"
} |
Q:
A badge that rewards "prophetic" downvoting
How about introducing a badge that rewards downvoting, but only of the sensible kind?
A measure for sensible downvoting would be a high percentage certain number of downvotes on content that has subsequently been
Deleted
Closed (except migrations and duplicates)
Bronze, Silver, and Gold badges would vary in numbers, say
Bronze: cast 50 downvotes on content that was subsequently closed or deleted
This would encourage downvoting (which is great and needed), but of the measurably sensible kind only.
What good actual numbers would be for Bronze, Silver, and Gold would be a separate discussion. Feel free to suggest numbers in your answers, as well as name suggestions (the only I managed to come up with was Whistleblowerand that isn't really accurate. I'm more imagining the old lady calling the council over some abandoned litter in the streets, or broken windows... but in a good way of course.
A:
I disagree. Not all that should be downvoted should be closed, and vice versa.
A question can be very good, well put, well thought-out, but is off-topic, or not constructive.
A question can be valid, but badly formatted, or research wasn't applied to it ("RTFM questions which aren't duplicates"). There's no reason to close, only downvote.
Also
You're encouraging gang-voting, people see a close (4) question and rush to downvote it before it gets closed.
A:
I really don't like this "accuracy percent" idea; you're basically discouraging people from downvoting on bad but not closable posts; there are lots of ways your post can be bad but not outright closable.
It's also often the case that a good answer salvages a poor question, or a poor question is kept around because it's popular. It doesn't make sense that I should have to save up my downvotes only for stuff I know is going to be closed, or be locked out of a badge forever because 50% of my 400 downvotes aren't on closed posts.
Alternately I can see this being useful if it's instead downvote X number, not percent, of posts that go on to be closed. There you keep the idea of "accurate downvotes" without the problems % based badges have (hello Unsung Hero).
A:
I don't like the idea. I downvote questions because they're bad (and it's the only way to fix them), not because I get a badge. Gamification is good and all, but my reasons for downvoting is because something deserves it, not because I'd get a badge. Voting really needs to be a civic thing more than anything else.
| {
"pile_set_name": "StackExchange"
} |
Q:
Git push keeps prompting username and password
Having problem where I git push origin master and it prompts username and password.
I was on same git repo using laptop, it doesn't prompt username and password but when I use it on my desktop it prompts username and password.
Also I have been cloning using https on laptop and it doesn't prompt me username and password when I push it.
A:
You can see this link to cache the credentials:
Caching your GitHub password in Git
| {
"pile_set_name": "StackExchange"
} |
Q:
With jQuery/JavaScript Is it slower to declare variables that will only be used once?
I just want to make sure I understand this basic idea correctly, and no matter how I phrase it, I'm not coming up with completely relevant search results.
This is faster:
function () {
$('#someID').someMethod( $('#someOtherID').data('some-data') );
}
than this:
function () {
var variableOne = $('#someID'),
variableTwo = $('#someIDsomeOtherID').data('some-data');
variableOne.someMethod( variableTwo );
}
is that correct?
I think the question may be "Is declaring variables slower than not declaring variables?" :facepalm:
The particular case where I questioned this is running a similarly constructed function after an AJAX call where some events must be delegated on to the newly loaded elements.
A:
The answer you will benefit from the most is It does not make a difference.
Declaring variables and storing data in them is something you do so that you do not have to query that data more than once. Besides this obvious point, using variables rather than chaining everything into one big expression improves readability and makes your code more manageable.
When it comes to performance, I can't think of any scenario where you should debate declaring a variable or not. If there's even an absolute difference in speed, it would be so small that you should not see this as a reason to not use that variable and just leaving your code to becoming spaghetti.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript, possible to pass undeclared method parameters without eval?
Ok, difficult to understand from the title only. Here is an example. I want a function to refer to a variable that is "injected" automagically, ie:
function abc() {
console.log(myVariable);
}
I have tried with:
with({myVariable: "value"}) { abc() }
but this doesn't work unless abc is declared within the with block, ie:
with({myVariable: "value"}) {
function abc() {
console.log(myVariable);
}
abc(); // This will work
}
So the last piece will work, but is it possible to fake the with statement, or do I have to force the developers to declare their function calls in a with statement?
Basically the call I want to do is:
doSomething({myVariable: "value"}, function() {
console.log(myVariable);
});
Ofcourse, I am aware I could pass this is a one parameter object, but that is not what I am trying to do:
doSomething({myVariable: "value"}, function(M) {
console.log(M.myVariable);
});
Further more, I am trying to avoid using eval:
with({myVariable: "value"}) {
eval(abc.toString())(); // Will also work
}
Is this not supported at at all beyond eval in Javascript?
A:
JavaScript does not provide any straightforward way to achieve the syntax you're looking for. The only way to inject a variable into a Lexical Environment is by using eval (or the very similar Function constructor). Some of the answers to this question suggest this. Some other answers suggest using global variables as a workaround. Each of those solutions have their own caveats, though.
Other than that, your only option is to use a different syntax. The closest you can get to your original syntax is passing a parameter from doSomething to the callback, as Aadit M Shah suggested. Yes, I am aware you said you don't want to do that, but it's either that or an ugly hack...
Original answer (written when I didn't fully understand the question)
Maybe what you're looking for is a closure? Something like this:
var myVariable = "value";
function doSomething() {
console.log(myVariable);
};
doSomething(); // logs "value"
Or maybe this?
function createClosure(myVariable) {
return function() {
console.log(myVariable);
};
}
var closure = createClosure("value");
closure(); // logs "value"
Or even:
var closure = function(myVariable) {
return function() {
console.log(myVariable);
};
}("value");
closure(); // logs "value"
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Factorise these expressions?
I'm dong some Factorisation revision and I'm a bit stuck. I've never done this before and I'm stuck a bit. First of all I know how to do small factorisations and I know you have to find the Highest Common Factor and that it's the opposite of expanding but these expressions are scaring me a bit.
e.g. how would you do this $x^2 + 8x + 16$
or this $9m^2 - 24mn + 16n^2$
A:
Remember, and you must learn it by heart:
$$(a{+}b)^2=a^2+2ab+b^2$$
and
$$(a-b)^2=a^2-2ab+b^2$$
So try to write each of two expressions in one of this two forms
A:
To solve these kinds of exercises all you need to know is
$$
(a+b)^2=a^2+b^2+2ab,\quad (a-b)^2=a^2+b^2-2ab
$$
and then be a little smart.
Suppose we are looking at $9m^2-24mn+16n^2$ and want to write it in one of the above forms. Since there is a minus-sign involved, we should bring it on the form $(a-b)^2$ for some $a$ and $b$ to be determined. Now $9m^2$ should correspond to the $a^2$ term, $16n^2$ should correspond to the $b^2$ term and $-24mn$ corresponds to $-2ab$.
Edit upon OP's now deleted comment: Aligning your expression with the expression we obtain from expanding $(a+b)^2$ we have:
$$
\begin{align}
&a^2\;\;\;+b^2\;\;\;\,-2ab\\
=&9m^2+16n^2-24mn
\end{align}
$$
meaning that you should pick $a$ and $b$ such that $a^2=9m^2$, $b^2=16n^2$ and $-2ab=-24mn$. Which $a$ and $b$ does this correspond to?
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional value bolding or annotation for a barplot
The following query generates a barplot for top tickers:
df2=final_df.groupby(['ticker'])['ticker'].count().rename(columns={'ticker':''}).reset_index().rename(columns={0:'number_tickers_uploaded'}).reset_index(drop=True)
print(df2)
sns.set(style='darkgrid')
plt.title('Top tickers uploaded in the last week')
result = df2.sort_values('number_tickers_uploaded',ascending=False)
sns.barplot(x='ticker', y='number_tickers_uploaded', data=result.head(8), palette='Set2')
This a sample of the data:
ticker number_tickers_uploaded
0 BWM 50
1 IND 25
2 RIA 18
3 X 10
4 Y 6
The resulting barplot lists tickers by number_tickers_uploaded in descending order, but I would like the value to be bolded (either the ticker or the bar itself) and annotated with let's say "Z Fund," if it is equal to x or y .
Thank you!
--Edit--
I know I can annotate like so:
# Annotate with text + Arrow
plt.annotate(
# Label and coordinate
'Z Fund', xy=(25, 50), xytext=(0, 80),
# Custom arrow
arrowprops=dict(facecolor='black', shrink=0.05)
)
But I am trying to annotate conditionally (before you know the position the arrow and annotation should go)- not after seeing the data is plotted
A:
The question is a bit chaotic and I'm having problems understanding what you want to do under which conditions. As far as I understand, the aim is to make the ticklabels bold, add an annotation with an arrow and have an edge on bars for those bars which belong to some special label. The following code does that:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame({"name" : list("ABCDXY"), "value" : [5,6,3,5,7,4]})
result = df.sort_values("value",ascending=False)
ax = sns.barplot(x="name", y="value", data=result, palette='Set2')
for i,t in enumerate(ax.get_xticklabels()):
if t.get_text() in ["X", "Y"]:
## bold ticklabels
t.set_weight("bold")
## bar edges
ax.patches[i].set_edgecolor("k")
ax.patches[i].set_linewidth(2)
## arrow annotations
ax.annotate("Z Fund",(i, ax.patches[i].get_height()),
xytext=(0,30), textcoords='offset points', ha="center",
arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()
| {
"pile_set_name": "StackExchange"
} |
Q:
Time Machine backup to an SMB share Mavericks
I'm following the instructions and scripts detailed in this article, but it's failing on mavericks - the mounted windows drive isn't showing up in the time machine disk selection pane.
Any ideas how to get this working?
http://lifehacker.com/5691649/an-easier-way-to-set-up-time-machine-to-back-up-to-a-networked-windows-computer
(Using Window 7 and the SMB server)
A:
Pulled this from MacRumors:
After you get the sparse bundle created in your desired location, mount the sparse bundle by double clicking it. It should mount just as any other drive or image file will.
Once that is done open up terminal and run this command (leave the quotes in place):
sudo tmutil setdestination "/Volumes/Time Machine Backups/"
Now open up Time Machine and turn it on. You don't have to select your disk, the command in terminal did that for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why Firefox & IE breaks down my div boxes and place underneath each other?
I have 3 div boxes (with fixed width and dynamic height) that are set next to each other. This works fine in Chrome. But in Mozilla and IE, the boxes don't stay same, they break down themselves and sits on top of each other, what I definitely don't want to happen. Even if I minimize the window size (it happens with all browsers) the boxes break down and don't stay in the same row. I want to get rid of this problem. I want that whatever size the window have or what ever browser is used, the boxes shouldn't break down. They must still be able to fit next to each other.
See here
[NOTE/SIDE INFO: I have set the width of my each box 253 px because the max-width of my bosy is set as 1200px, and 253px is estimated so that they all can fit inside 1200px]
This piece of code I am working on:
.HTML:
<div class="box">box1box1box1box1box1<br>
</div>
<div class="box">Box2Box2Box2Box2Box2<br>
</div>
<div class="box">box3box3box3box3box3<br>
</div>
.CSS:
.box {
display:inline-block;
margin-top:100px;
-webkit-box-flex: 1;
-moz-box-flex: 1;
margin-bottom:60px;
margin-left:70px;
padding:15px;
width:253px;
border: 4px solid gray;
border-radius:5px;
}
A:
All you need to do is to put your content in a block-level container element with a width that's wide enough for the elements to not wrap to the next line:
http://jsfiddle.net/o8r97fhf/
HTML:
<div class="container">
<div class="box">box1box1box1box1box1<br /></div>
<div class="box">Box2Box2Box2Box2Box2<br /></div>
<div class="box">box3box3box3box3box3<br /></div>
</div>
CSS:
.container {
width:1161px;
}
.box {
display:inline-block;
margin-top:100px;
-webkit-box-flex: 1;
-moz-box-flex: 1;
margin-bottom:60px;
margin-left:70px;
padding:15px;
width:253px;
border: 4px solid gray;
border-radius:5px;
}
The reason why it is doing this is because the <div class="box" /> elements have "display:inline-block;" - making them act more like an element such as <img /> where it has a height and width, but it is displayed inline, and if there's not enough room on one line, the elements will wrap to the next line.
Another thing you can try with the container <div /> element is to put "white-space: nowrap;" on it instead of specifying a particular width on it.
One thing I do when I'm messing around with CSS like this is, I will put a temporary "background-color:#F0F;" on the container <div /> element so I can see exactly what the dimensions look like, and what is really going on in the page.
| {
"pile_set_name": "StackExchange"
} |
Q:
How Long is the Shelf Life of Refrigerated Eggless Mayonnaise?
I have learned to make mayonnaise using only oil, milk, and lemon juice. If I store this in the refrigerator, how long will it remain safe to eat?
A:
According to the recipe here, Milk Mayonnaise will last about a week in the fridge.
| {
"pile_set_name": "StackExchange"
} |
Q:
Modelica print current time
How can I print the current date and/or time to a file (e.g. log file, or csv file) from Modelica? Do I need external code for this? I was not able to find any example code in the Modelica Standard Library.
A:
https://build.openmodelica.org/Documentation/Modelica.Utilities.Streams.print.html
You would need to add this to your equation or algorithm section:
.Modelica.Utilities.Streams.print(String(time));
For local system time use:
https://build.openmodelica.org/Documentation/Modelica.Utilities.System.getTime.html
model GetTime
Integer ms;
Integer sec;
Integer min;
Integer hour;
Integer mday;
Integer mon;
Integer year;
algorithm
(ms, sec, min, hour, mday, mon, year) := .Modelica.Utilities.System.getTime();
.Modelica.Utilities.Streams.print("ms:" + String(ms) + "\n");
.Modelica.Utilities.Streams.print("sec:" + String(sec) + "\n");
.Modelica.Utilities.Streams.print("min:" + String(min) + "\n");
.Modelica.Utilities.Streams.print("hour:" + String(hour) + "\n");
.Modelica.Utilities.Streams.print("mday:" + String(mday) + "\n");
.Modelica.Utilities.Streams.print("mon:" + String(mon) + "\n");
.Modelica.Utilities.Streams.print("year:" + String(year) + "\n");
end GetTime;
| {
"pile_set_name": "StackExchange"
} |