text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
how to add the database to wx.grid of wxpython?
I have tried to add the database in the following way.
import sys
import sqlite3
# --- constructor
# --------------
self.m_grid1 = wx.grid.Grid( self.m_panel6, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0 )
# Grid
self.m_grid1.CreateGrid( 6, 3 )
called from a button
def Database_View( self, event ):
db = sqlite3.connect("database/Save.db")
cur = db.cursor()
cur.execute("SELECT id,login,password FROM datosurl")
data = cur.fetchall()
if data:
for row, form in enumerate(data):
for column, item in enumerate(form):
#self.m_grid1.SetCellValue(column, row, form[0])
print("row: "+str(row)+" - column - "+str(column)+" - "+str(form[0]))
print("row :"+str(row)+" - column - "+str(column)+" - "+ str(form[1]))
print("row :"+str(row)+" - column - "+str(column)+" - "+ str(form[2]))
column +=1
row +=1
db.close()
As you can see, I've been trying with print, but the goal is the following code:
self.m_grid1.SetCellValue(column, row, form[0])
in form1, I have the following
form('id','apple','english') #and continuously
I know I'm failing in repetitive sentences,Could you help me please? I've stalled
Would it be correct that I have already defined you ?, because my data exceeds the defined value
self.m_grid1.CreateGrid( 6, 3 )
A:
Here is one way of doing it, there are a few, depending on how the database is constructed and accessed.
See onLoadTable which loads the column labels and the data.
import wx
import sqlite3 as sqlite
import wx.grid as gridlib
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,"",size=(900,400))
panel = wx.Panel(self, -1)
self.db = db
self.cursor = self.db.conn.cursor()
result = self.cursor.execute("create table if not exists Data (myindex INTEGER PRIMARY KEY AUTOINCREMENT, id int, login text, password text)");
vbox = wx.BoxSizer(wx.VERTICAL)
self.grid = wx.grid.Grid(panel)
rows = self.cursor.execute('SELECT Count(*) FROM Data')
val = rows.fetchone()
self.db_exists = val[0]
self.grid.CreateGrid(15,20)
self.grid.Scroll(0,0)
self.LoadBtn = wx.Button(panel, -1, "Commit/Load")
self.Bind(wx.EVT_BUTTON, self.onLoad, self.LoadBtn)
vbox.Add(self.LoadBtn)
vbox.Add(self.grid)
panel.SetSizer(vbox)
panel.Fit()
def onLoad(self, event):
if self.db_exists == 0:
for i in range(10):
id = i
login = 'login'+str(i)
password = 'pass'+str(i)
self.cursor.execute("INSERT INTO Data VALUES (NULL,?,?,?);",(id, login, password))
self.db.conn.commit()
self.onLoadTable()
def onLoadTable(self):
self.grid.ClearGrid()
metadata = self.cursor.execute('SELECT * from Data')
labels = []
for i in metadata.description:
labels.append(i[0])
labels = labels[1:]
for i in range(len(labels)):
self.grid.SetColLabelValue(i, labels[i])
logins = self.cursor.execute('SELECT * from Data')
for row in logins:
row_num = row[0]
cells = row[1:]
for i in range(0,len(cells)):
if cells[i] != None and cells[i] != "null":
self.grid.SetCellValue(row_num-1, i, str(cells[i]))
self.Show()
self.db.conn.commit()
class GetDatabase():
def __init__(self):
self.conn = sqlite.connect("logins.db")
if __name__ == "__main__":
db=GetDatabase()
app = wx.App()
frame = MyFrame()
frame.Show()
app.MainLoop()
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Query Grabbing data from two tables
My code right now is this
$extract = mysqli_query($dbc, "SELECT * FROM items");
$numrows = mysqli_num_rows($extract);
while($row = mysqli_fetch_assoc($extract)) {
$id = $row['i_id'];
$iname = $row['i_name'];
echo "<tr><td><a href='capture.php?item_id=$id'>$iname</a></td><td>Incomplete</td></tr>";
}
What i want to do is run a check to see if the item has already been completed.
I have a separate table that contains the information, for instance say that Item 1 has been completed then I would like to be able to change my echo to something like:
echo "<tr><td>$iname</td><td>Complete!</td></tr>";
How would I accomplish this? Would I need to use some form of a join statement?
I want to be able to display all the items in the table but not duplicate them i initially thought that an if statement on the echo to see if item complete then do this else do that
Here are the two tables
Items item_collection
------ ---------------
i_id i_id
i_name complete
caption
image
c_id
g_id
A:
You can use join condition like this (assuming complete is a varchar field)
SELECT a.i_id, a.i_name,
CASE WHEN i_status = '1' THEN 'Complete!' ELSE 'Incomplete' END AS complete_status
FROM items a
LEFT OUTER JOIN item_collection b ON a.i_id = b.i_id
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the reason behind Gita favoring the SAtvika way over others?
Usually people who have read Gita, would say that NishKAma Karma is the way of "Karma yoga".
Numerous verses suggest that, NishkAma Karma is SAtvika way of life. SakAma karma is RAjasika way & Vikarma is TAmasika way. Even attempting to perform Akarma is also sometimes considered TAmasika way.
Now everyone is aware that, The supreme Purusha / Brahman (the ultimate "I/Me") is beyond 3 modes of nature: Sattva, Rajas, Tamas. A person with any predominant quality should have the same right on Moksha.
As discussed in this answer, there is a difference between NishkAma Karma ("Karma Yoga") and NishkarmatA ("Moksha or Jeevan Mukta").
Why can't a person with RAjasika nature do "Karma yoga" with SakAma Karma & attain NishkarmatA?
Similarly, why can't a TAmasika person do "Karma yoga" with Vikarma and attain Moksha?
IMO People like ShishupAla, Hiranyakashipu, RAvana, Kamsa, who probably attained Moksha, were not doing NishkAma Karma.
A:
Because Satva Guna helps in approaching spirituality thought it doesn't lead one to Moksha.
See the nature of three Gunas as described in Bhagavag Gita
14.11 When the illumination that is knowledge radiates in this body through all the doors (of the senses), then one should know that sattva has increased greatly.
14.12 O best of the Bharata dynasty, when rajas becomes predominant, these come into being: avarice, movement, undertaking of actions, unrest and hankering.
14.13 O descendant of the Kuru dynasty, when tamas predominates these surely [i.e. without exception.-M.S.] come into being: non-discrimination and inactivity, inadvertence and delusion.
Also see the next birth according to the dominance of particular Guna while departure:
Satva : attains the taintless worlds of those who know the highest
Rajas : born among people attached to activity
Tamas : birth among the stupid species.
14.18 People who conform to sattva go higher up; those who conform to rajas stay in the middle; those who conform to tamas, who conform to the actions of the lowest ality, go down.
So, it's very obvious that there are very less chances of obtaining true knowledge for the followers of Rajas and Tamas Gunas. Agree that Satva Guna will not lead one to Moksha, for approaching Moksha, one needs to go beyond all three Gunas. As preached in 14.6th verse : "it binds through attachment to happiness and attachment to knowledge." However it is better than Rajas and Tamas as it helps in purifying mind and in becoming eligible for one to obtain the true knowledge.
Q. Why can't a person with RAjasika or TAmasika nature do "Karma yoga" with SakAma Karma & attain Moksha?
As mentioned above, Rajasika or Tamasika mind is not eligible to understand or obtain the right knowledge that is required for Moksha. So, regarding your queries you can consider that Rajasika or Tamasika Sakama Karma Yoga is wrong tool which will never lead one to Moksha and comparatively Satviak Nishkama Karma is preferable (right tool) which can lead one to the Moksha.
| {
"pile_set_name": "StackExchange"
} |
Q:
Deduct from total pool of hours and minutes in Excel
I am trying to have a cell which has a given number of hours and minutes allocated and then add events which deduct from that time and show the total hours and minutes left. For example if I had 240 hours & 40 minutes and took 40 minute appointment and another 36 minute appointment I should be left with 239 hours and 24 minutes. But I am doing something wrong with my excel formula, is there another better way of doing this?
A:
Try something like this
=E3-SUM(E4:E11)
You also need to list your times as hh:mm:ss
E4 should be 00:40:00, E5 should be 00:36:00. They way you have them, it looks
like 40 seconds and 36 seconds (depending on formatting)
Also note that working with days you must multiply by 24 and hours multiply by 60
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel 5.3: Use a array field from a controller in the view for trans()
I have a form, which is sending the data of the form to a controller using POST.
The controller returns the array of data using this line:
return view('pages.result', compact('request'))
The view displays me the correct array with all data, when I use this code in the view:
<?php $input = $request->all(); echo "<pre>"; print_r($input); echo "</pre>"; ?>
Now I want to use the field "name" of the array in a translation. The following line of code...
{{ trans('auth.resultMessage', ['name' => '<?php echo $result['name']; ?>']) }}
...displays this:
{{ trans('auth.resultMessage', ['name' => 'Max']) }}
Unfortunately, it doesn't use the translation text. It should look like this:
Everything worked fine, Max.
I've also tried the following solution, but this ends with the error Parse error: syntax error, unexpected '}', expecting ',' or ')':
{{ trans('auth.resultMessage', ['name' => '{{ Request::input("name") }}']) }}
How can I use the array field in the translation?
A:
If I understood your question correctly, you should just supply the variable without trying to echoing it. Like this, for instance:
{{ trans('auth.resultMessage', ['name' => $request->name]) }}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get logged UserID in asp.net MVC and display it in hidden text box
I can get username using @user.identity.name from table user but i need to get UserID instead of Username. how to do it?. i tried the following code in my controller but it returns 0.
My Controller:
public ActionResult Index()
{
int userId = User.Identity.GetUserId<int>();
User currentUser = db.Users.FirstOrDefault(x => x.UserID == userId);
ViewBag.UID=userId;
return View();
}
My View
<input value="@ViewBag.UID" type="hidden"/>
My Model
[Table("User")]
public partial class User
{
public int UserID { get; set; }
//added by zakerr
public int? DepartmentID { get; set; }
public string Firstname{ get; set; }
public string Lastname { get; set; }
[Required]
[StringLength(50)]
public string Username { get; set; }
[Required]
[StringLength(50, MinimumLength =4)]
[DataType(DataType.Password)]
public string Password { get; set; }
public string UserEmailAddress { get; set; }
[StringLength(50)]
public string Status { get; set; }
}
A:
If this isn't about ASP.NET membership, then you should be using your own method and query to do so as follows: (I guess, you are passing email for the login)
int currentUser = db.Users.Where(x => x.Email == email).Select(x => x.userId);
ViewBag.UID = Convert.ToInt32(userId);
| {
"pile_set_name": "StackExchange"
} |
Q:
Построение единого запроса MYSQL для удаления всех символов, кроме цифр и букв в WordPress
Друзья, помогите разобраться.
При включении кеша на wordpress, адрес типа:
mydomain.com/?p=123 превратился в mydomain.com/Hello-World
Но вот ведь не задача, есть такие ссылки как:
mydomain.com/Hello.-World
mydomain.com/Hello-&-World
при их вводе, сайт выдаёт ошибку.
если удалить все лишние символы типа "." или "&", то всё ок и странички загружаются без проблем
для удаления я искользовал следующий такой запрос:
UPDATE `wp_posts` SET `post_name` = REPLACE( post_name, '.', '' );
UPDATE `wp_posts` SET `post_name` = REPLACE( post_name, '&', '' );
И вот вопрос: как построить запрос так, чтобы удалились все символы, кроме
БУКВ,ЦИФР и ТИРЕ
(одним запросом сразу) ?
Чтоб не строить 50 запросов на удаление.
Спасибо.
A:
create procedure multiremove(charstodelete text)
begin
while length(charstodelete)>0 do
begin
set @onechar = substring(charstodelete,1,1);
set charstodelete = substring(charstodelete,2,length(charstodelete));
set @sql=CONCAT("update wp_posts set post_name=replace(post_name,\'",@onechar,"\',\'\');");
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;
set @sql='';
set @onechar='';
end;
end while;
end;
На sql.ru - подробнее.
При желании можно доработать и передавать процедуре имя таблицы и поля.
| {
"pile_set_name": "StackExchange"
} |
Q:
JList selection, successive items are marked as selected when popup is introduced in-between
I have a JList and JTextArea pair. Based on the selected item on JList, Data will be displayed in JTextArea. But for some data, user inputs are needed, and are collected by a JOptionPane. The problem is when I traverse JList with up and down arrows; having JOptionPane popped up; both successive items are selected. I mean previously selected data is not getting unselected, but only the last data is supposed to be selected. I am popping JOptionPane inside changeTextArea() method and the Code is as follows. Thanks for any help!
private class JListListenerEdit implements ListSelectionListener {
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting() && listEdit.isFocusOwner()) {
Data selection = null;
try {
selection = listEdit.getSelectedValue();
} catch (Exception e) {
}
if (null != selection) {
changeTextArea(selection);
}
}
}
}
public void changeTextAreaEditData(SData selection) {
if (selection.requireInputs()) {
JOptionPane.showMessageDialog(frame,"Provide inputs to process the data.","Inputs Required", JOptionPane.INFORMATION);
this.textAreaEditData.setText(processData(selection.getData()));
} else {
this.textAreaEditData.setText(selection.getData());
}
}
A:
I see that you are checking getValueIsAdjusting() in your ListSelectionListener, as shown here. You might try wrapping the call to changeTextArea() inside an Runnable using invokeLater().
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the temperature during ice melting change?
I did an online test for physics and one of the questions was: Salt was added to ice. Because of it the ice melted. What was happening with temperature DURING the process of melting? The right answer was that temperature was lowering.
Can please someone explain why? I always thought that during melting the temperature is constant and after all ice is melted then the temperature changes.
Thank you very very much
A:
This is called a "Colligative property" - which include depression of the freezing point and elevation of the boiling point (plus 2 others). These properties increase in effect as more solute is added. I believe adding salt to ice only melts it if there is already liquid water present, which there usually is (it might be a very thin coat of water on the ice). This thin layer dissolves some salt, which reduces the freezing point of the liquid water (salt solution), leading to the surrounding ice to melt, which dissolves more salt, melting more ice etc. These properties are more related to the amount of solute, rather than the type of solute (at least in an ideal solution).
Reference
Colligative Properties of Simple Solutions, Frank C. Andrews,
Science 05 Nov 1976: Vol. 194, Issue 4265, pp. 567-571
| {
"pile_set_name": "StackExchange"
} |
Q:
Concrete types - as described by Stroustrup - C++ Programming Language 4th ed
I'm having a hard time with this concept. What is Stroustrup getting at here? What is special about a class whose "representation is part of its definition"? What does a "concrete type" contrast with? (I assume it contrasts with "abstract type", but since, AFAIK, you can't even bring an instance of an abstract type into existence, it seems obvious you couldn't place that on the stack, initialize it, etc.)
Is there such a thing as a class I could instantiate that would NOT fit this description of a "concrete class"? Normally I find BS very easy to follow, but I'm missing the point here.
The basic idea of concrete classes is that they behave “just like
built-in types.” For example, a complex number type and an
infinite-precision integer are much like built-in int, except of
course that they have their own semantics and sets of operations.
Similarly, a vector and a string are much like built-in arrays, except
that they are better behaved (§ 4.2, § 4.3.2, § 4.4.1).
The defining
characteristic of a concrete type is that its representation is part
of its definition. In many important cases, such as a vector, that
representation is only one or more pointers to more data stored
elsewhere, but it is present in each object of a concrete class.... In
particular, it allows us to
• place objects of concrete types on the
stack, in statically allocated memory, and in other objects (§ 6.4.2);
• refer to objects directly (and not just through pointers or
references);
• initialize objects immediately and completely (e.g.,
using constructors; § 2.3.2); and
• copy objects (§ 3.3).
Stroustrup, Bjarne (2013-07-10). The C++ Programming Language (4th
Edition) (Section 16.3 Concrete Classes; Kindle Locations 2373-2386). Pearson Education. Kindle
Edition.
A:
You've pretty much got it right, a concrete type is something that you can create an instance of, while an abstract type is not. For example, consider a typical pedagogical hierarchy such as:
class animal {
virtual void noise() = 0;
}
class dog: public animal {
void noise() { cout << "bark\n"; }
public:
human *master;
}
class cat: public animal {
void noise() { cout << "meow\n"; }
public:
std::vector<human *> slaves;
}
You can create instances of dog or cat because they are concrete, and not abstract. On the other hand, you can't create an instance of an animal, but only hold a pointer (or refernce) to one. For example:
void hungry(animal *a) {
a->noise();
}
In terms that Stroustrup is using, the representation of an animal is not included in the definition of class animal. The representation for a particular kind of animal is described in a subclass, here either dog or cat.
A:
It seems a term used by BS with a meaning which only him is using AFAIK. I'm not sure I understand fully what he intend.
First a citation from the same section:
Such types are called concrete types or concrete classes to distinguish them from abstract classes and classes in class hierarchies.
So for him a a non abstract descendant of an abstract class is not a concrete class (which isn't a nuance I'm used to, the familiar usage for me is that all non abstract classes are concrete), at least if than inheritance is not an implementation detail. His concrete classes seems to be standalone utilities.
Another concrete/abstract dichotomy I'm familiar with is for data structure. An abstract data structure is defined by its operation (say a Dictionary provide look up, insertion, ...) A concrete data structure states how those are provided (an hash table for instance). His insistence that representation is exposed is perhaps related to that (probably due to the influence of the representation on complexity).
Stepanov and McJones in Elements of Programming are using a concept of Regular types. Stroustrup is also using that notion (in section 24.3.1) and I'm not sure what the difference is with the concrete types. Two guesses:
the concrete type is more a notion of intend of usage than strict properties while the concept of Regular is intended to describe properties that a type has to have to be usable in generic contexts.
the notion of regular type is a refinement of the one concrete type and he didn't saw when he introduced it that they should perhaps be unified (the description of concrete types is already present in the second description but seem to have been rewritten).
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery slider inside popup dosen't work
I am trying to program a slider inside a popup box.
I am using Jquery.
The popup works and it pops as i want to.
For the slider I use the Swiper jquery library.
If i test the code inside the popup div by it self the slider works great, but there must be some collision there.
This is the link to what i just described.
http://seveloff.com/test/popup.html
This is the pop-up code:
$(document).ready(function() {
$(window).load(function() {
$("div#slidex").append('<div class="pup disable"><div class="swiper-container"><div class="swiper-wrapper"><div class="swiper-slide"><img src="images/1.jpg" alt="pro group 1"></div><div class="swiper-slide"><img src="images/2.jpg" alt="pro group 2"></div><div class="swiper-slide"><img src="images/3.jpg" alt="pro group 3"></div><div class="swiper-slide"><img src="images/4.jpg" alt="pro group 4"></div></div> <div class="swiper-pagination"></div></div><img id="x" src="http://cmsresources.windowsphone.com/windowsphone/en-us/How-to/wp7/inline/basic-icon-x.png"> </div>');
setTimeout(function() {
$("div.pup").fadeIn(200).addClass("active");
}, 3000);
$('#x').on('click', function() {
$("div.pup").fadeOut(300).addClass("disable");
});
});
});
I don't get any errors at the console.
I must be missing something...
A:
The problem is that you are trying to initialize the swiper when the target elements are not loaded yet. Also, as you are showing div.pup inside a timeout, you should initialize the swiper there.
Other thing you can improve is that you don't need to wait for load the DOM and the contents separately. In this case, waiting just for the DOM is enough.
You code should look like this (jsFiddle):
$(function(){
$("div#slidex").append('<div class="pup disable"><div class="swiper-container"><div class="swiper-wrapper"><div class="swiper-slide"><img src="http://seveloff.com/test/images/1.jpg" alt="pro group 1"></div><div class="swiper-slide"><img src="http://seveloff.com/test/images/2.jpg" alt="pro group 2"></div><div class="swiper-slide"><img src="http://seveloff.com/test/images/3.jpg" alt="pro group 3"></div><div class="swiper-slide"><img src="http://seveloff.com/test/images/4.jpg" alt="pro group 4"></div></div> <div class="swiper-pagination"></div></div><img id="x" src="http://cmsresources.windowsphone.com/windowsphone/en-us/How-to/wp7/inline/basic-icon-x.png"> </div>');
setTimeout(function() {
$("div.pup").fadeIn(200).addClass("active");
new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
slidesPerView: 1,
paginationClickable: true,
spaceBetween: 30,
loop: true,
autoplay: 2500,
autoplayDisableOnInteraction: false,
effect: 'fade'
});
}, 3000);
$('#x').on('click', function() {
$("div.pup").fadeOut(300).addClass("disable");
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Vim - how to store and execute commonly used commands?
If I wanted to process a batch of text files with the same set of commands for example:
:set tw=50
gggqG
Can I save the above and run it with a shortcut command?
A:
If you want to use it only once, use a macro as specified in some of the other answers. If you want to do it more often, you can include the following line in your .vimrc file:
:map \r :set tw=50<CR>gggqG
This will map \r to cause your two lines to be executed whenever you press \r. Of course you can also choose a different shortcut, like <C-R> (Ctrl+R) or <F12> or something.
A:
The following in .vimrc will define a new command Wrap that does what you want.
command! Wrap :set tw=50 | :normal gggqG
Call it with :Wrap
A:
As a very quick start, put this in your .vimrc:
" define the function
" '!' means override function if already defined
" always use uppercase names for your functions
function! DoSomething()
:set tw=50
gggqG
endfunction
" map a keystroke (e.g. F12) in normal mode to call your function
nmap <F12> :call DoSomething()<CR>
note: the formatted code above looks rather horrible, but lines starting with " are comments.
| {
"pile_set_name": "StackExchange"
} |
Q:
Como alterar objetos do URL via JavaScript?
Tenho um sistema de busca no meu site usando o Google Custom Search, e para definir a pesquisa por imagens, é acrescentado no URL: #gsc.tab=1. Como eu crio um sistema em JS que pode ser executado via link que adiciona isso no URL?
A:
Não tenho certeza se é isso que você está buscando, mas esse fragmento que começa com # é chamado de hash e pode ser obtido e alterado assim:
// pega o valor atual
var hashAtual = window.location.hash;
// troca o valor
window.location.hash = 'foo';
// monitora trocas de valor
window.onhashchange = function() {
console.log('hash trocado para ' + window.location.hash);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ValueError + repetition I can't figure out
I am new to programming. I have to write a script for a calculator.
I have two issues with it:
My 3rd prompt to enter a number repeats itself, and I am not sure why.
I get a ValueError instead of the calculation but I can't figure out what I am doing wrong.
This is my code:
def input_number1():
prompt = 'Enter a number\n'
num1 = int(input(prompt))
if num1 <= 0:
print('Error')
input_number1()
else:
return num1
input_number1()
def input_operator():
prompt = 'Enter [1] to add, [2] to substract, [3] to multiply or [4] to divide?\n'
operator = int(input(prompt))
if operator < 1 or operator > 4 :
print('error')
input_operator()
else:
return operator
input_operator()
def input_number2():
prompt = 'Enter a number\n'
num2 = int(input(prompt))
if num2 <= 0 :
print('Error')
input_number2()
else:
return num2
input_number2()
num1 = input_number1()
operator = input_operator()
num2 = input_number2()
def do_calc():
if operator == 1:
print(num1 + num2)
elif operator == 2:
print(num1 - num2)
elif operator == 3:
print(num1 * num2)
else:
print(num1 / num2)
do_calc()
Can someone points me in the right direction please?
A:
The main error here is that you are calling input_number1(), input_operator() and input_number2() after the function definition so they call once after the function is defined and their return value is ignored, then once again to actually store and calculate the result.
And about the ValueError I can't seem to find where that might be, for me the code works fine after fixing the main problem. On what line does the problem happen?
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get arrays returned from laravel foreach instead of a json array?
I'm trying to return an array of values using laravel foreach based on input values.
This is my expected output
[
[
"number": 2567046807891,
"message": "THis is a test",
"sender": "Oasis Agrib"
],
[
"number": 256782248927,
"message": "THis is a test",
"sender": "Oasis Agrib"
]
]
but am getting this instead
[
{
"number": 2567046807891,
"message": "THis is a test",
"sender": "Oasis Agrib"
},
{
"number": 256782248927,
"message": "THis is a test",
"sender": "Oasis Agrib"
}
]
This is what i have tried
$batch = array();
foreach($data as $v){
$phone_number = $v['phonenumber'];
$batch[] = array('number' => $phone_number,'message' => $message, 'sender' => $sender);
}
return $batch;
How can best go about this situation
A:
If you want to use an JSON structure as PHP array, you can use the function json_decode() and set the second flag to true
$json_string = '[
{
"number": 2567046807891,
"message": "THis is a test",
"sender": "Oasis Agrib"
},
{
"number": 256782248927,
"message": "THis is a test",
"sender": "Oasis Agrib"
}
]' ;
$array = json_decode($json_string, true);
You can now use $array as a classic PHP associative array.
| {
"pile_set_name": "StackExchange"
} |
Q:
debian: aptitude install sshfs > Couldn't find any package whose name
Why aptitude don’t found sshfs?
And how can I install sshfs via aptitude? Pleas, without 3rd-Partys.
https://packages.debian.org/en/wheezy/sshfs
I typed this:
root@s18:~# aptitude update
Hit http://security.debian.org wheezy/updates Release.gpg
Hit http://security.debian.org wheezy/updates Release
Hit http://ftp.de.debian.org wheezy Release.gpg
Hit http://security.debian.org wheezy/updates/main Sources
Hit http://ftp.de.debian.org wheezy Release
Hit http://security.debian.org wheezy/updates/contrib Sources
Hit http://security.debian.org wheezy/updates/non-free Sources
Hit http://security.debian.org wheezy/updates/main amd64 Packages
Hit http://ftp.de.debian.org wheezy/main Sources
Hit http://security.debian.org wheezy/updates/contrib amd64 Packages
Hit http://security.debian.org wheezy/updates/non-free amd64 Packages
Hit http://ftp.de.debian.org wheezy/contrib Sources
Hit http://security.debian.org wheezy/updates/contrib Translation-en
Hit http://security.debian.org wheezy/updates/main Translation-en
Hit http://ftp.de.debian.org wheezy/non-free Sources
Hit http://security.debian.org wheezy/updates/non-free Translation-en
Hit http://ftp.de.debian.org wheezy/contrib amd64 Packages
Hit http://ftp.de.debian.org wheezy/non-free amd64 Packages
Hit http://ftp.de.debian.org wheezy/contrib Translation-en
Hit http://ftp.de.debian.org wheezy/non-free Translation-en
root@s18:~# aptitude dist-upgrade
No packages will be installed, upgraded, or removed.
0 packages upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B of archives. After unpacking 0 B will be used.
root@s18:~# aptitude install sshfs
Couldn't find any package whose name or description matched "sshfs"
Couldn't find any package whose name or description matched "sshfs"
No packages will be installed, upgraded, or removed.
0 packages upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B of archives. After unpacking 0 B will be used.
root@s18:~# cat /etc/debian_version
7.5
root@s18:~#
My sources:
root@s18:~# cat /etc/apt/sources.list
deb http://ftp.de.debian.org/debian/ wheezy contrib non-free
deb-src http://ftp.de.debian.org/debian/ wheezy main contrib non-free
deb http://security.debian.org/ wheezy/updates main contrib non-free
deb-src http://security.debian.org/ wheezy/updates main contrib non-free
root@s18:~# ls /etc/apt/sources.list.d/
root@s18:~#
And
root@s18:~# aptitude search sshfs
root@s18:~# apt-cache search sshfs
root@s18:~# apt-get -s install sshfs
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package sshfs
root@s18:~#
A:
Your problem is your primary deb source line:
deb http://ftp.de.debian.org/debian/ wheezy contrib non-free
This pulls in the contrib and non-free respositories of the wheezy version, but not the main repository which is where most of Debian lives. You are however pulling in security updates for main as well; I suppose sshfs just hasn't had anything that warrants a release there since Wheezy was released.
As was found out in comments to the question, adding the main repository solves the problem:
deb http://ftp.de.debian.org/debian/ wheezy main contrib non-free
| {
"pile_set_name": "StackExchange"
} |
Q:
g++ optimization makes the program unable to run
I implemented a path planning algorithm based on D*-Lite. When I do not turn on optimization (-O0), the program can run normally. But when I turn on the optimization level (-O1/2/3), the program cannot be terminated. In Visual Studio, both debug mode and release mode can run normally. In the above cases, the codes are the same.I don’t know how to find the problem, can anyone help me?
class DstarLite {
public:
DstarLite() = delete;
DstarLite(GridStatus* a, GridStatus* b, FILE* fp)
: k_m_(0), start_(a), last_(start_), goal_(b), open_close_(fp) {}
void calculateKey(GridStatus* s);
void updateVertex(GridStatus* u);
void initialize();
void computeShortestPath();
void rePlanning(vector<pair<GridStatus*, int>>& node_change);
GridStatus* getStart();
void setStart(GridStatus* val);
GridStatus* getGoal();
private:
Fib frontier_;
double k_m_;
unordered_map<GridStatus*, handle_t>
heap_map_;
GridStatus* start_;
GridStatus* last_;
GridStatus* goal_;
FILE* open_close_;
};
void DstarLite::calculateKey(GridStatus* s) {
s->f = min(s->g, s->rhs) + heuristic(start_, s) + k_m_;
s->k2 = min(s->g, s->rhs);
}
void DstarLite::initialize() {
fprintf(open_close_, "%d %d\n", start_->x, start_->y);
fprintf(open_close_, "%d %d\n", goal_->x, goal_->y);
goal_->rhs = 0;
calculateKey(goal_);
handle_t hand = frontier_.push(goal_);
heap_map_[goal_] = hand;
}
void DstarLite::updateVertex(GridStatus* u) {
bool heap_in = heap_map_.find(u) != heap_map_.end();
if (u->g != u->rhs && heap_in) {
calculateKey(u);
frontier_.update(heap_map_[u]);
} else if (u->g != u->rhs && !heap_in) {
calculateKey(u);
handle_t hand = frontier_.push(u);
heap_map_[u] = hand;
} else if (u->g == u->rhs && heap_in) {
calculateKey(u);
frontier_.erase(heap_map_[u]);
heap_map_.erase(u);
}
}
void DstarLite::computeShortestPath() {
int count = 0;
while (smaller(frontier_.top(), start_) || !myEqual(start_->rhs, start_->g)) {
count++;
auto u = frontier_.top();
pair<double, double> k_old = {u->f, u->k2};
pair<double, double> k_new;
k_new.first = min(u->g, u->rhs) + heuristic(start_, u) + k_m_;
k_new.second = min(u->g, u->rhs);
if (k_old < k_new) {
calculateKey(u);
frontier_.update(heap_map_[u]);
} else if (myGreater(u->g, u->rhs)) {
u->g = u->rhs;
frontier_.pop();
heap_map_.erase(u);
for (auto s : neighbors(u)) {
if (s->rhs > u->g + cost(u, s)) {
s->next = u;
s->rhs = u->g + cost(u, s);
updateVertex(s);
}
}
} else {
double g_old = u->g;
u->g = kDoubleInfinity;
auto neighbor = neighbors(u);
neighbor.push_back(u);
for (auto s : neighbor) {
if (myEqual(s->rhs, cost(s, u) + g_old)) {
if (!equal(s, goal_)) {
double pp_s = kDoubleInfinity;
for (auto succ : neighbors(s)) {
double dis = succ->g + cost(succ, s);
if (dis < pp_s) {
pp_s = dis;
s->next = succ;
}
}
s->rhs = pp_s;
}
}
updateVertex(s);
}
}
}
cout << "Dstar visited nodes : " << count << endl;
}
void DstarLite::rePlanning(vector<pair<GridStatus*, int>>& node_change) {
k_m_ += heuristic(last_, start_);
last_ = start_;
for (auto change : node_change) {
GridStatus* u = change.first;
int old_threat = u->threat;
int new_threat = change.second;
double c_old;
double c_new;
u->threat = new_threat;
u->rhs += (new_threat - old_threat) * threat_factor;
updateVertex(u);
for (auto v : neighbors(u)) {
u->threat = old_threat;
c_old = cost(v, u);
u->threat = new_threat;
c_new = cost(v, u);
if (c_old > c_new) {
if (v != goal_) {
if (v->rhs > u->g + c_new) {
v->next = u;
v->rhs = u->g + c_new;
}
}
} else if (myEqual(v->rhs, c_old + u->g)) {
if (v != goal_) {
double pp_s = kDoubleInfinity;
for (auto pre : neighbors(v)) {
double dis = pre->g + cost(pre, v);
if (dis < pp_s) {
pp_s = dis;
v->next = pre;
}
}
v->rhs = pp_s;
}
}
updateVertex(v);
}
}
}
GridStatus* DstarLite::getStart() { return start_; }
void DstarLite::setStart(GridStatus* val) { start_ = val; }
GridStatus* DstarLite::getGoal() { return goal_; }
DstarLite dstar(start, goal, open_close);
dstar.initialize();
dstar.computeShortestPath();
Sorry, I think it is difficult to locate the problem in the code, so the code was not shown before. Now I have re-edited the question, but there are a lot of codes, and the main calling part is computeShortest().
A:
As you did not provide any code, we can give you only some general hints to fix such problems.
As a first assumption your code has definitely one or more bugs which causes what we call undefined behaviour UB. As the result is undefined, it can be anything and is often changing behaviour with different optimization levels, compiler versions or platforms.
What you can do:
enable really ALL warnings and fix them all! Look especially for something like "comparison is always...", "use of xxx (sometimes) without initialization", " invalid pointer cast", ...
try to compile on different compilers. You should also try to use gcc and/or clang, even on windows. It is maybe hard in the first time to get the environment for these compilers run on windows plattforms, but it is really worth to do it. Different compilers will give different warnings. Fixing all warnings from all compilers is a really good help!
you should use memory tracers like valgrind. I have not much experience on windows, but I believe there are also such tools, maybe already integrated in your development suite. These tools are really good in finding "of by x" access, access freed memory and such problems.
if you still run into such trouble, static code analyser tools may help. Typically not as much as managers believe, because today's compilers are much better by detecting flaws as expected by dinosaur programmers. The additional findings are often false positives, especially if you use modern C++. Typically you can save the money and take a class for your own education!
Review, Review, Review with other people!
snip the problem small! You should spend most of your development time by setting up good automated unit tests. Check every path, every function in every file. It is good to see at minimum 95% of all branches covered by tests. Typically these tests will also fail if you have UB in your code if you change optimizer levels and or compiler and platforms.
using a debugger can be frustrating. In high optimized code you jump through all and nothing and you may not really see where you are and what is the relation to your code. And if in lower optimizer level the bug is not present, you have not really much chance to see find the underlying problem.
last but not least: "printf debugging". But this may change the behaviour also. In worst case the code will run always if you add a debug output. But it is a chance!
use thread and memory sanitizers from your compiler.
| {
"pile_set_name": "StackExchange"
} |
Q:
POST collection type data from silverlight to aspx page.
I have a problem posting the data from silverlight to the aspx page which is in same domain.
I need to open aspx page in a new tab that needs data of type combination (id, amount) like
3-XX-YY-ZZ, 12
4-XX-YY-ZZ, 20
5-XX-YY-ZZ, 15
etc...[many]
and process it and display.
I tried to do it using querystrings and HtmlPage.PopupWindow(). It works but that would come with size limits.
Please help.
A:
I can access javascript from silverlight application. And this problem was solved by using javascript function from silverlight to post the hidden field data to aspx page.
| {
"pile_set_name": "StackExchange"
} |
Q:
What constitutes proof of relationship/intention to marry for a UK immigration visa?
Being disabled, I don't really have to worry so much about funds or some of the more complicated issues with getting my partner over to the UK (from the USA). But there is one thing that concerns and confuses us: Proof of relationship/intention to marry.
Would it help if we booked the marriage before applying for the visa? We have an arrival date (7th of May), we've considered every other angle we need to, I think (going crazy with that)... But I don't want us to be refused the Visa and this is one question hanging over our heads.
We're going to include letters from ourselves and whatever third parties we can that will serve to explain our relationship, but since we communicate over Skype (we've had calls going 24/7 for over four years, now), we don't have phone records.
Any... Any information (especially from experience) would be helpful. We really want to make this work. Thank you!
A:
You asked if you should get a provisional booking at the Registry Office (from this I assume that your gf is seeking a fiance visa). The answer is yes, it's always a good idea, but its evidential value is close to nil since it costs £35 and anybody can get one.
You asked about how to establish that your relationship is genuine. Since part of the rules for a fiance visa is proof that you met (and that means you met person-to-person in the physical, real-world) I assume that you have met. You will have some hard evidence of this including, passport stamps, hotel and meal receipts, and a few photos together. If you have visited together on multiple occasions, get that hard evidence also. The more the better.
Also, you will have (presumably) evidence of how you met on the net. If not, you will be able to explain it in a way that makes sense to them.
They don't want to see reams and reams of emails, and it can backfire if they read something and take it the wrong way. It can also slow the whole process down if somebody has to read through piles and piles of crap. Having a huge Skype log or similar can lead to the impression that you are addicted to cybersex and the relationship is not physically subsisting or viable. Be careful.
When I was doing casework for clients seeking a fiance visa, I would send the hard evidence I listed above along with a MAX of 3 photos, and 3 emails spaced out over the length of the relationship. I would include a cover letter that explained in detail how the couple met (doing this is critically important). If the couple had progressed to intimacy, I would explain when and where that took place. It's not a requirement, but it's an abrupt end to any questions about genuine relationship. Sham marriages and forced marriages do not have intimacy beforehand.
You asked about getting evidence from third parties, possibly an attestation that the relationship is genuine. It's not appropriate. They will look at it and wonder why you thought it was necessary. It's a poor idea. If the relationship is genuine, there will be a sufficient amount of hard evidence readily available without having to rely upon third parties.
Adding...
If it's a US/UK relationship, they will not worry a lot about if the relationship is genuine or not. The approval rate for family path applicants from the USA is about 98%.
| {
"pile_set_name": "StackExchange"
} |
Q:
Set WordPress permalinks directly in httpd.conf?
Is is possible to configure WordPress permalinks directly in Apache httpd.conf?
I have a server situation (Apache 2.2.3 CentOS PHP5.1.6) where I can't use .htaccess for performance reasons, but can use httpd.conf.
The admin says that mod_rewrite is enabled, but AllowOverride is not, and I can't change those settings.
And I need to restrict the permalinks to just the "blog" directory.
This is what would go in .htaccess but needs to go into httpd.conf:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>
Thanks...
A:
Put this within the container for your site.
<Directory /path/to/blog/>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>
</Directory>
| {
"pile_set_name": "StackExchange"
} |
Q:
Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference
Following is my code for my fragment, i get the above error of null exception
/**
* Created by USer on 09-04-2016.
*/
public class FeaturedFragment extends android.support.v4.app.Fragment {
private List url;
private SliderLayout sliderLayout;
private GridView gridView;
private int firstVisiblepos;
AppnextAPI api;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.featured, container, false);
url = new ArrayList<String>();
url.add("http://192.168.5.51/Wallpapers/Autumn.jpg");
url.add("http://192.168.5.51/Wallpapers/Tree.jpg");
url.add("http://192.168.5.51/Wallpapers/Flower.jpg");
url.add("http://192.168.5.51/Wallpapers/Lion.jpg");
api = new AppnextAPI(getActivity(), "my id");
sliderLayout = (SliderLayout) rootView.findViewById(R.id.slider);
gridView = (GridView) rootView.findViewById(R.id.gridView);
ThemeShowcase theme = new ThemeShowcase();
theme.execute("getThemes");
for (int i = 0; i < url.size(); i++) {
TextSliderView textSliderView = new TextSliderView(getActivity().getApplicationContext());
textSliderView.image((String) url.get(i));
sliderLayout.addSlider(textSliderView);
}
sliderLayout.setDuration(4000);
sliderLayout.setPresetTransformer(SliderLayout.Transformer.Stack);
return rootView;
}
private class ThemeShowcase extends AsyncTask<String, Integer, ArrayList<ThemeModel>> {
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://192.168.5.51/WebApplication/WebService.asmx";
private final String SOAP_ACTION = "http://tempuri.org/";
private String responseString;
private ArrayList model = null;
private ThemeModel dummy;
@Override
protected void onPreExecute() {
super.onPreExecute();
model = new ArrayList<ThemeModel>();
}
@Override
protected ArrayList<ThemeModel> doInBackground(String... params) {
try {
SoapObject request = new SoapObject(NAMESPACE, params[0]);
PropertyInfo sayHelloPI = new PropertyInfo();
sayHelloPI.setName("page");
sayHelloPI.setValue("1");
sayHelloPI.setType(Integer.class);
request.addProperty(sayHelloPI);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION + params[0], envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
responseString = response.toString();
if (!responseString.equalsIgnoreCase("Error occured")) {
JSONArray array = new JSONArray(responseString);
for (int i = 0; i < array.length(); i++) {
JSONObject objct = array.getJSONObject(i);
dummy = new ThemeModel();
dummy.preview = objct.getString("Preview");
dummy.name = objct.getString("Name");
model.add(dummy);
}
}
} catch (Exception e) {
model = null;
return model;
}
return model;
}
@Override
protected void onPostExecute(ArrayList<ThemeModel> model) {
if(model!=null) {
gridView.setAdapter(new ImageAdapter(getActivity().getApplicationContext(), model));
firstVisiblepos = gridView.getFirstVisiblePosition();
}else{
try {
Toast.makeText(getActivity().getApplicationContext(), "Site Unreachable", Toast.LENGTH_LONG).show();
}catch (Exception e){
Log.d("MyApp","exception");
}
}
}
}
}
here's my image adapter
public class ImageAdapter extends BaseAdapter implements View.OnClickListener{
private Context context;
private LayoutInflater inflater;
private ArrayList<ThemeModel> model;
public ImageAdapter(Context context,ArrayList<ThemeModel> model) {
this.inflater = LayoutInflater.from(context);
this.context = context;
this.model = model;
}
@Override
public int getCount() {
return model.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.custom_item,null);
CardView cardView = (CardView)convertView.findViewById(R.id.cardView);
cardView.setOnClickListener(this);
ImageView imageView = (ImageView)convertView.findViewById(R.id.imageView);
final ProgressBar progressBar = (ProgressBar)convertView.findViewById(R.id.progressbar);
TextView textView = (TextView)convertView.findViewById(R.id.contentName);
ImageButton imageButton = (ImageButton)convertView.findViewById(R.id.downloadButton);
textView.setText(model.get(position).getName());
Picasso.with(context).load(model.get(position).getPreview()).into(imageView, new Callback() {
@Override
public void onSuccess() {
progressBar.setVisibility(View.GONE);
}
@Override
public void onError() {
}
});
return convertView;
}
@Override
public void onClick(View v) {
}
}
i keep getting force close on below line
gridView.setAdapter(new ImageAdapter(getActivity().getApplicationContext(), model));
the error is
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference
i have tried using getActivity(),getContext() etc but none of them work
A:
The reason is because when you call getActivity() in the onPostExecute(), the Fragment is already detached from the Activity (for example, when the AsyncTask is executing, user click back button to exit the activity), so getActivity() would be null.
The solution is before getActivity(), check isAdded() is true or not, if not true, that means the fragment is already detached, call to getActivity() will return null.
Remember in the AsyncTask, everywhere before you call getActivity(), you'd better to check isAdded() again, because user may exit the activity at anytime during the AsyncTask is executing.
| {
"pile_set_name": "StackExchange"
} |
Q:
How seriously do we take the finger-inspection in Havdala?
After saying the blessing over fire during Havdala, we do something (customs vary) involving looking at our fingers by the light of the Havdala candle. I'm wondering how seriously we take this part of the ritual. In particular:
If the person making Havdala doesn't do this, is the fire blessing or the Havdala invalidated?
If the people discharging their obligation by observing the Havdala don't do this, do they lose credit for this blessing of for the Havdala?
How certain must the finger-looker be that the light involved is from the Havdala candle? If most of the light cast on the fingers is from electric lights, does that invalidate the finger-looking?
A:
Shulchan Aruch Orach Chaim 298:3-4 says:
The person needs to be close enough to the fire to potentially benefit from it, should he so choose (It is described there as being able to sort money by the light of the torch). The Mishna Berurah there (S"K 13) says that if one who is listening wants to fulfill his obligation, he too must be that close.
Our custom is to look at our fingers and nails to make sure we are close enough to differentiate between them (Mishna Berurah S"K 9, quoting the Tur - see there for other reasons as well).
I understand this to mean that even if we don't look at our nails, as long as we are that close we have fulfilled our obligation.
A:
Based on the answer given in this other question (which matches with what I remembered to be the halacha) - the concept is merely to benefit from the light of the havdala candle.
If one turns off all of the lights in the room before reciting the havdala blessings, and the reciter reads them out of a siddur / bircon (a.k.a "bentscher"), that is also benefiting from the candlelight.
Since I can't find an explicit source which states that those who listen to havdala must benefit from the light, it stands to reason that there is no such requirement.
In normative practice, the listeners are not required to drink the havdala wine. Generally, the reciter pauses from the end of "borei minei b'samim" until all of the listeners have smelled the spices - but it would seem that even this is not essential (lo m'akev) for the listeners.
In summary, my answers to the bullet points are:
No.
No.
The reciter should try to benefit from the candlelight in some way. The listeners need not be concerned about it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a page with just one post?
I am creating a small blog using Flask. But I didn't find any tutorials or information that would solve the following problem: Create a dynamic page with just one post. I want this page to appear only a complete post, that is, coming out of a database. Without showing all at once (using the for repeater)
I already have an automatic redirector that takes you to a dynamic page for each post title, I just need to know how to show just one post on that page instead of several.
@app.route('/<url_post>', methods=['GET'])
def daily_post(url_post):
with sqlite3.connect("sample.db") as connection:
c = connection.cursor()
c.execute("SELECT * FROM posts")
data = c.fetchall()
Page Post.html
{% extends "layout.html" %}
{% block content %}
{% for item in data %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="/home">{{ item[0] }}</a>
<small class="text-muted">{{ item[1] }}</small>
</div>
<p class="article-content">{{ item[2] }}</p>
</div>
</article>
{% endfor %}
{% endblock content %}
I want a dynamic page with only one post (use sqlite3)
A:
The issue is you're grabbing every post from within your posts table and are then passing that result query set into your view to be rendered. This is the problematic code:
c.execute("SELECT * FROM posts")
data = c.fetchall()
Instead you should be filtering your results with a WHERE clause to only extract those records that fulfill a specified condition, i.e. your specific post.
Something along the lines of:
c.execute("SELECT * FROM posts WHERE <table_column_identifier>=?", (url_post))
data = c.fetchall()
Where <table_column_identifier> is the column within your posts table schema uniquely identifying your desired post. I would have to see your table schema definition to give you the exact field, but it's probably something along the lines of id
Note: You can reuse your page post view providing your new route endpoint provides the filtering as described above.
Hopefully that helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
send html + JS in ajax
im using jQuery load() method to send another html to my webpage.
The html being loaded contains Javascript generated HTML.
Im using this function to load the html:
$(document).ready(function(){
$("img#links").click(function(){
$("div#content").load("links.html");
});
});
The links.html contains:
<h1 id="content">Links</h1>
<br>
<script>add_link("http://google.com");</script>
The add_link function generates me a table:
var add_link = function(link) {
document.write("<table border=\"0\" width=\"100%\" height=\"50\" id=\"link\">");
document.write("<tr>");
document.write("<td width=\"50\"><img src=\"img/star.png\" /></td>");
document.write("<td><a href=\"" + link + "\"><div class=\"link\">" + link + "</div></a></td></tr></table>");
}
However, when called instead of writing that js generated code into the webpage, it gets written to a blank page, containing only the table generated by JS.
A:
When you call document.write() after the page loading has completed — definitely the case here — the browser will wipe out the original page. In other words, the browser interprets a call after the page is done to be an implicit request to "start over" with a blank page.
Instead of using document.write(), then, you can use DOM APIs to append new content to the page.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - how to check if weak reference is still available
I am passing some weakrefs from Python into C++ class, but C++ destructors are actively trying to access the ref when the real object is already dead, obviously it crashes...
Is there any Python C/API approach to find out if Python reference is still alive or any other known workaround for this ?
Thanks
A:
From Python C API documentation:
PyObject* PyWeakref_GetObject(PyObject *ref)
Return value: Borrowed reference.
Return the referenced object from a weak reference, ref. If the referent
is no longer live, returns None. New in version 2.2.
A:
If you call PyWeakref_GetObject on the weak reference it should return either Py_None or NULL, I forget which. But you should check if it's returning one of those and that will tell you that the referenced object is no longer alive.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I block linked ads on Google Chrome
Some days back I suddenly got ads in Google Chrome whenever I try to open any page. After searching online how to block ads, I found one adblock extension. I have installed adblock and it was working fine and ads were blocked. But today I am getting linked ads.
What do I mean by linked ads In the first screenshot you can see web applications ,user experience are in blue colors and underlined. If I Mouse over the linked ads (in the screenshot I mouse over on "user experience") then a pop-up comes up showing the ads. You can see I have enabled adblock in the screenshot. Can anybody please tell me why these ads are appearing?
And yes, I have reinstalled Google Chrome and still the same
A:
I am certain that you've got a Chrome Extension that has had a brain transplant.
It probably started out as a good, useful extension. It may still have the functionality you got it for. However, a recent trend is for nefarious advertisers to buy extensions from their developers and take over. Since the extension is already installed no extra permissions are needed to add extra "functionality" to it in the form of injected ads. It's not "malware" in the strictest sense, so anti-virus checkers won't pick up on them.
It was in the tech news quite a bit recently. Ars Technica has a very good writeup about it: Adware vendors buy Chrome Extensions to send ad- and malware-filled updates
Worse actors have gone beyond ads to actual malware.
I had a few Extensions where this happened, including one Extension much beloved (and missed).
You should disable each of your Extensions one-by-one until you find the culprit, then uninstall it with extreme prejudice.
If you're willing to trust another extension there are a couple that purport to find these bad extensions for you.
ExtShield (Lifehacker review)
Extension Defender (Lifehacker review)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to tell whether elaboration has completed at a breakpoint?
When I hit a breakpoint in a VLAB script, how can I find out if I have caused elaboration to finish or not, yet?
My script reaches a statement that raises an error:
Error: (E529) insert module failed: elaboration done
(The command that causes this is vlab.instantiate("stim", "stim"))
So obviously elaboration was unexpectedly (for me) already completed. I need to somehow go back in the process and find out where that happened - so I need some way of asking "is elaboration complete?" at the point where I set breakpoints earlier in the script.
A:
SystemC provides the following function to query the current phase of elaboration or simulation.
sc_status sc_get_status();
It returns either SC_ELABORATION, SC_BEFORE_END_OF_ELABORATION, SC_END_OF_ELABORATION, SC_START_OF_SIMULATION, SC_RUNNING, SC_PAUSED, SC_STOPPED, or SC_END_OF_SIMULATION.
See section 4.5.8 in the SystemC Language Reference Manual for more details. Note that this function was only added in the most recent version of the standard, IEEE Standard 1666-2011.
In VLAB, the SystemC API is available from the sysc Python package, so the following script can be used to test if the current phase is at elaboration:
import sysc
print "Is elaboration phase:", sysc.sc_get_status() == sysc.SC_ELABORATION
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best comparison algorithm for comparing the similarity of arrays?
I am building a program that takes 2 arrays and returns some value showing to what degree they are similar. For example, images with few differences will have a good score, whereas images that are vastly different will have a worse score.
So far the only two algorithms I have come across for this problem are the sum of the squared differences and the normalized correlation.
Both of these will be fairly simple to implement, however I was wondering if there was another algorithm I haven't been able to find that I could use?
Furthermore, which previously mentioned method will be the best? Would be great to know both in terms of their accuracy and efficiency.
Thanks,
A:
Comparing images usually depends on application you are dealing with. Normally distance functions used depends on image descriptor.
Take look at Distance functions
Euclidean Distance
Squared Euclidean Distance
Cosine Distance or Similarity [THIS SHOULD WORK FINE]
Sum of Absolute Differences
Sum of Squared Differences
Correlation Distance
Hellinger Distance
Grid Distance
Manhattan Distance
Chebyshev Distance
statistics distance function
Wasserstein Metric
Mahalanobis Distance
Bray Curtis Distance
Canberra Distance
Binary Distance functions
L0 Norm
Jacard similarity
Hamming Distance
As you are directly comparing images, taking cosine similarity should work for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Assembler. Распознавание эмуляции среды
Некоторые программы(например, антивирусные) эмулируют изолированную среду для PE файлов. Как можно при помощи Assembler распознать такую среду? Идеально было бы кусок кода, но буду вполне доволен и описанием алгоритма. Заранее спасибо.
A:
Если я правильно понял вопрос, то по идее тут подход должен быть комплексным. Универсальным способо определить эмулятор (хотя точнее говорить, это все-таки некая виртуалка), думаю, нельзя. Но при этом вряд ли какие-то программы (антивирусы) будут использовать полностью самостоятельно написанну VM, а это значит, что они используют что-то готовое. Поэтому можно попробовать взять некие типовые способы определения каждой виртуалки поотдельности и последовательно выполнять все проверки
Если говорить про то, какими способами это можно делать, то тут разные варианты: ключи регистра, какие-то особые драйвера, команды, железо и т.д.
Примеры (возможно немного устаревшие) можете посмотреть в статье (даже английский знать не обязательно, чтобы скопипастить): https://www.symantec.com/avcenter/reference/Virtual_Machine_Threats.pdf
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting from double to single
Given 64 bits which represent a number in IEEE 754 double precision format, what is the algorithm for converting them to 32 bits which represent the same number, but in IEEE 754 single precision format (perhaps with loss of precision)?
Also, is there an easy way to perform this conversion in Ada, without having to manipulate the bits?
A:
There is indeed an easy way to do this in Ada (quite similar to the way you would do the same thing in C!):
with Ada.Numerics;
with Ada.Text_IO; use Ada.Text_IO;
procedure Floating_Conversion is
D : constant Long_Float := Ada.Numerics.Pi;
F : Float;
begin
F := Float (D); -- The conversion!
Put_Line ("double:" & Long_Float'Image (D));
Put_Line ("single:" & Float'Image (F));
end Floating_Conversion;
| {
"pile_set_name": "StackExchange"
} |
Q:
How to prove to friend I have solution to puzzle (without revealing it)?
My friend Paul set me this arithmetic puzzle:
To make 21 from the numbers 1, 5, 6, 7. You can use the operations add, subtract, multiply, divide as well as brackets. You must use each number once.
After I solved it myself, I set the puzzle to another friend Ollie. He thinks it's impossible. How can I prove otherwise to Ollie—without revealing the solution? Can it be done without a trusted third party?
Also, how should I show my solution to Paul? I suspect he might not have one himself. If that's the case, I'd rather not tell mine—or at least expose him in the process.
A:
You can use a zero-knowledge proof to demonstrate that you have a solution to a general class of problem. (For example: "I can efficiently find the prime factorization of any number. I won't tell you how I do it, but I'll prove my ability by quickly factorizing any number you throw at me.") However, here, the solution is how you solved the problem; it's tautological to say you can't show how you solved the problem without giving away how you solved the problem.
You could secretly but provably declare your solution via cryptographic commitment. For example, you publish a hash of your solution and then later publish your solution. That allows you to prove that you had the solution for at least as long as the hash has been public. However, it only becomes clear that the secret you committed is a valid solution after you make the secret public. (This approach will allow Paul to compare his (non-)answer with yours -- simply compare hashes, using a standard format -- but it will not prove anything to Ollie.)
For Ollie, you need some way of demonstrating a solution to a different problem that maps onto the actual problem in some provable way. I briefly considered some kind of fully homomorphic encryption, but I don't see how you could homomorphically demonstrate the problem in a way that 1) doesn't allow your friend to decrypt it and 2) still allows your friend to verify the result. For example, consider an attempt at an iterative zero-knowledge proof with a homomorphic scheme that can encrypt (Enc) with a public key and decrypt (Dec) with a private key:
Show your friend Enc(1), Enc(5), Enc(6), and Enc(7) in a random order, and separately show Enc(21). At this point, your friend may stop these steps, demand the private key and verify that you are not lying about the values of the numbers. (This prevents you from using the wrong values, since you'd probably get caught if you played enough times.)
Perform the necessary mathematical operations on the first four encrypted values to produce 21. (This step gives away the necessary operations, which is suboptimal, but it does not reveal which values go with which operations.) At this point we can no longer give your friend the decryption key, or else he will be able to view the entire solution.
Perform a homomorphic equality test of the result from step 2 against the Enc(21) from step 1. This produces an encrypted boolean.
There is no way to allow your friend to decrypt the boolean without also allowing him to decrypt every other value, which would reveal your solution entirely. Therefore, there is no way to verify to your friend the correctness of your solution.
A:
There are only 7680 possible expressions using exactly once each of the four values, and binary operators in a list of four possible binary operators. A number of these expressions are in fact duplicates of each other, since two of the operators (addition and multiplication) are commutative. You can tell Ollie and Paul that they are lazy bastards.
This short number of candidates invalidates most cryptographic endeavours, since a zero-knowledge proof is always relative to a core hard problem: a ZK proof is a proof where you demonstrate that you know a solution without giving to the verifier any information that he could not obtain by himself. Here, trying out all possible solutions is simply too easy, so Ollie and Paul can already gain by themselves all the information that is to be obtained.
(Besides, according to my own computations, there is no solution. Hence, the solution to the puzzle must be some sort of pun or loophole, which by nature evades mathematical analysis.)
Edit: there was a bug in my program (damned silent conversion double to int; no warning from GCC even with -W -Wall). Indeed there is one solution, the one found by @Gudradain (and it is unique). For those interested in such things, here is my horrible program.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert EPS to SVG
I'm looking for a free tool to convert EPS (encapsulated postscript) to SVG (scalable vector graphics).
I am aware that I can convert EPS to PDF with Ghostscript, then import the PDF with Inkscape and save the result as SVG. However, I want a simpler workflow with less tools, basically I want a single button "convert it".
I need that for Windows and offline use. I cannot upload my EPS to an online service.
A:
I think Scribus - an Open Source Desktop Publishing software - should be able to do it. Open an EPS, let it save the converted file into its native format, and export as SVG.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error running Libreoffice 6.0.5. Did ubuntu 18.04 fix itself after I looked up the version number?
I followed these instructions:
How do I install LibreOffice 6 in Ubuntu?
In Terminal, I typed libreoffice. This error appeared:
/usr/lib/libreoffice/program/oosplash: error while loading shared
libraries: libuno_sal.so.3: cannot open shared object file: No such
file or directory
Then the Software Updater opened and I ran an update that fixed the error.
In Terminal, I typed libreoffice and the application ran.
Simultaneously, this error appeared:
func=xmlSecCheckVersionExt:file=xmlsec.c:line=188:obj=unknown:subj=unknown:error=19:invalid
version:mode=abi compatible;expected minor version=2;real minor
version=2;expected subminor version=25;real subminor version=26
At first, I thought there was something wrong, but since it mentioned something about a version, I went back to terminal and typed:
libreoffice --version
LibreOffice 6.0.5.2 00m0(Build:2)
Next, commands
soffice
The application opened without the error. I closed the application
Next, command
libreoffice
The application opened without the error.
Did Ubuntu fix itself after looking up the version number?
A:
Hi i stumbled upon this one:
https://bugs.documentfoundation.org/show_bug.cgi?id=118373
The first part of your question about why the error message changed:
Yes after you did a software update, some previously missing dependencies may have been declared, and thus the library libuno_sal.so.3 was installed.
The second part is a bit more mystery:
My assumption is, that Libreoffice starting from some point in time to at least version 6.0.7-0ubuntu0.18.04.2 was compiled with libxmlsec1 1.2.26 but in Ubuntu 18.04 the current version of libxmlsec1 is still 1.2.25-1build1.
Libreoffice does not load that library on every call, and if your terminal command does not load an ODS for example, you dont see this message.
If you try to open a Calc sheet for example, i assume you will still see this message, until the devs of libreoffice push a solution, to silence the warning, or solve the dependency issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calling sys_read two times [Nasm, Linux]
Twice i try to read character from input, the first time "call getUserAction" works fine, but the main problem is, that the system didn't call the second read func, it just exits. Here is a little part of my code
SECTION .bss
buffer resb 1
SECTION .text
global _start
_start:
...some unuseful and commented code
call getUserAction ;reading 1 byte from console, works fine
...
jmp count
call exit
count:
...
call getUserAction; don't work, just exits from program without err
...commented code to debug
call exit
getUserAction: ;proc to read from console 1 byte
mov eax, 3
mov ebx, 0
mov ecx, buffer
mov edx, 1
int 80h
ret
Also i tried to put code from getUserAction in "count" proc, but it changes nothing.
UPD: Answer on first comment:
After the second "getUserAction":
mov eax, [buffer]
cmp eax, 'u'
je setUsersValues
cmp eax, 'e'
je callFunc
call exit
UPD2: I'm so sorry, here is all code
%define newline 10,0
%define A1 -7
%define A2 3
%define A3 2
%define A4 4
%define A5 2
SECTION .data
labInfo db "============Lab_3============",newline
labInfoLen equ $ - labInfo
mainMenu db "Choose the ex:",newline,\
" r - call count",newline,\
" t - call beep", newline,\
" y - call exit func",newline
mainMenuLen equ $ - mainMenu
funcStr db "Here func func func", newline
funcStrLen equ $ - funcStr
countPromt db "Please,choose the variant of variables value",newline,\
" u - user defined values", newline,\
" e - execerciese defined values", newline,\
"Your choise:"
promtLen equ $ - countPromt
SECTION .bss
buffer resb 1
resultValue resb 1
%macro calculateFunc 5
push eax
push edx
push ecx
mov eax, %1
mov ecx, %2
add eax, ecx
mov ecx, %3
imul ecx
mov ecx, %4
xor edx, edx
idiv ecx
mov ecx, %5
add eax, ecx
mov [resultValue], eax
pop ecx
pop edx
pop eax
%endmacro
SECTION .text
global _start
_start:
;call showPromt
push labInfo
push labInfoLen
call printStr
add esp, 8
;call showVarsList
push mainMenu
push mainMenuLen
call printStr
add esp, 8
call getUserAction
;get get get action
mov eax, [buffer]
cmp eax, 'r'
je count
cmp eax, 't'
je beep
cmp eax, 'y'
je exit
jmp _start
count:
;showFuncInfo
push funcStr
push funcStrLen
call printStr
add esp, 8
;showProposal
push countPromt
push promtLen
call printStr
add esp, 8
call getUserAction
mov eax, [buffer]
cmp eax, 'u'
je setUsersValues
cmp eax, 'e'
je callFunc
call exit
ret
setUsersValues:
nop; add some code later
ret
callFunc:
calculateFunc A1,A2,A3,A4,A5
add byte [resultValue], '0'
push resultValue
push 1
call printStr ; print Result
add esp, 8
ret
printStr:
push ebp
mov ebp, esp
mov eax, 4
mov ebx, 1
mov ecx, [ebp+12]
mov edx, [ebp+8]
int 80h
pop ebp
ret
getUserAction:
mov eax, 3
mov ebx, 0
mov ecx, buffer
mov edx, 1
int 80h
ret
beep:
nop;add some code later
ret
exit:
mov eax, 1
xor ebx, ebx
int 80h
A:
without seeing all the code, your buffer should be at least 2 bytes. the size for both sys_read and sys_write should be 2 not 1.
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I dispose EventRecords from a EventLogReader?
Should dispose be called on the events that come back from the ReadEvent method of EventLogQuery?
var eventLogQuery = new EventLogQuery("application", PathType.LogName) ;
using (var logReader = new EventLogReader(eventLogQuery))
{
var eventInstance = logReader.ReadEvent();
while (eventInstance != null)
{
eventInstance.Dispose(); //Should this be done? Or is this not ours to dispose?
eventInstance = logReader.ReadEvent();
}
}
Should my code call a dispose on eventInstance? Or is that something else's job?
A:
If it implements IDispose, dispose of it before it leaves the scope where it was created -- unless you plan to keep it around for a while for some particular reason. And calling EventLogReader.ReadEvent() is the kind of thing you should presume qualify as creation unless MSDN says otherwise (I checked -- it doesn't).
"Unless you plan to keep it around for a while" is why logReader should be deeply reluctant to dispose of the objects it created for you: It just can't know what you plan to do with them, so it should leave the decision up to you. It's not a bad idea to check MSDN if in doubt, but it would be strange if EventLogReader.Dispose() disposed of the query results as well. If you look at EventLogRecord in MSDN, it doesn't say anything about the subject, so just take IDispose as a suggestion to call Dispose() on the thing when you are done with it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I override "hide and disable all items on the desktop"?
Is it possible to add shortcuts and/or windows components to the desktop if "hide and disable all items on the desktop" is enabled via GPO? For example, if I have a few specific program icons I want to show up and nothing else, what is the best way to accomplish this?
I tried the steps at here and here.
But neither worked. Either the shortcut never showed up or the registry key didnt exist (on either Win7 or S2K8 machine).
A:
Redirecting the desktop to a read-only folder worked nicely.
Also, needed to add the reg entries to [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel]... I only did the ClassicStartMenu/
I also had to add Computer Configuration -> Policies -> Windows Settings -> Security Settings -> File System -> %SYSTEMDRIVE%\Users\Public\Desktop (Users: Deny - List Folder Contents) otherwise icons previously installed by programs available to all users would still show up.
| {
"pile_set_name": "StackExchange"
} |
Q:
Probability in a fixed die
I have that transition matrix is $$\begin{bmatrix}0&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}\\\frac{1}{5}&0&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}\\\frac{1}{5}&\frac{1}{5}&0&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}\\\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&0&\frac{1}{5}&\frac{1}{5}\\\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&0&\frac{1}{5}\\\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&0\end{bmatrix}$$
If I did $P^{(n)}=P^{(n-1)}P$ I get that
$$p_{66}^{(n)}=\frac{1}{5}(p_{61}^{(n-1)}+p_{62}^{(n-1)}+p_{63}^{(n-1)}+p_{64}^{(n-1)}+p_{65}^{(n-1)})$$
A:
That is mistaken. Let's look at the probability distribution of $X_2$ given $X_0=6$.
\begin{align}
& \Pr(X_2 = 6\mid X_0=6) \\[10pt]
= {} & \Pr\Big( \underbrace{(X_1 = 1\ \&\ X_2 = 6)\text{ or }(X_1=2\ \&\ X_2=6)\text{ or }\cdots}_{\text{five disjuncts}}\mid X_0=6\Big) \\[10pt]
= {} & \underbrace{\Pr\Big(X_1 = 1\ \&\ X_2 = 6 \mid X_0=6\Big) + \Pr\Big(X_1 = 2\ \&\ X_2 = 6 \mid X_0=6\Big) + \cdots\quad{}}_{\text{five terms}} \\[10pt]
= {} & \underbrace{\left( \frac 1 5 \right)^2 + \left( \frac 1 5 \right)^2 + \cdots \quad {} }_{\text{five terms}} = \frac 1 5.
\end{align}
And then:
\begin{align}
& \Pr(X_2 = 1\mid X_0=6) \\[10pt]
= {} & \Pr\Big( \underbrace{(X_1 = 2\ \&\ X_2 = 6)\text{ or }(X_1=3\ \&\ X_2=6)\text{ or }\cdots}_{\text{four disjuncts}}\mid X_0=6\Big) \\[10pt]
= {} & 4\left( \frac 1 5 \right)^2 = \frac 4 {25}.
\end{align}
So we get $4/25$ for each of five outcomes and $1/5 = 5/25$ for the other outcome.
However, if we have $n$ instead of $2$, I think I'd express it as an $(n-1)$th power of a Markov chain transition matrix. And maybe it would admit a closed form by solving a recursion. And I say $n-1$ rather than $n$ because the problem as phrased goes from $1$ to $n$ rather than from $0$ to $n$.
The above shows why your first guess was wrong; now let's try to get it right. We have the transition matrix:
$$
P = \begin{bmatrix}0&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}\\\frac{1}{5}&0&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}\\\frac{1}{5}&\frac{1}{5}&0&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}\\\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&0&\frac{1}{5}&\frac{1}{5}\\\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&0&\frac{1}{5}\\\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&\frac{1}{5}&0\end{bmatrix}
$$
When a matrix has a constant diagonal and a constant off-diagonal, then one can use the following trick. Write it as a linear combination of the matrix that projects orthongonally onto the space spanned by $(1,1,1,\ldots,1)^T$ and the matrix of the complement of that projection. The mapping $(a_1,\ldots,a_6) \mapsto (\bar a,\ldots, \bar a)$, where $\bar a = (a_1+\cdots+a_6)/6$, is the first orthongonal projection. The complement is $(a_1,\ldots,a_6) \mapsto (\bar a_1-\bar a,\ldots, a_6 - \bar a)$. Those matrices are therefore
$$
A= \begin{bmatrix} \frac16 & \frac16 & \frac16 & \frac16 & \frac16 & \frac16 & \\
\frac16 & \frac16 & \frac16 & \frac16 & \frac16 & \frac16 \\
\frac16 & \frac16 & \frac16 & \frac16 & \frac16 & \frac16 \\
\frac16 & \frac16 & \frac16 & \frac16 & \frac16 & \frac16 \\
\frac16 & \frac16 & \frac16 & \frac16 & \frac16 & \frac16 \\
\frac16 & \frac16 & \frac16 & \frac16 & \frac16 & \frac16 \end{bmatrix}
\text{ and }B = \begin{bmatrix}\frac56&\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}\\
\frac{-1}{6}&\frac56&\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}\\
\frac{-1}{6}&\frac{-1}{6}&\frac 5 6&\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}\\
\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}&\frac56&\frac{-1}{6}&\frac{-1}{6}\\
\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}&\frac56&\frac{-1}{6}\\
\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}&\frac{-1}{6}&\frac56\end{bmatrix}
$$
We will write $P=\alpha A + \beta B$.
The advantage of this is that we can then exploit the fact that
\begin{align}
A^2 & =A, \tag 1 \\
B^2 & =B, \tag 2 \\
AB =BA & =0. \tag 3
\end{align}
Solving the system, we get $\alpha= -1/5$ and $\beta=1$. Then by $(1)$, $(2)$, and $(3)$ above, we have
$$
P^n= \alpha^n A + \beta^n B.
$$
BTW, this experiment can be done with an ordinary (un-"fixed") die: just discard each outcome that is the same as the previous one.
| {
"pile_set_name": "StackExchange"
} |
Q:
Leak detection simple class
Basic idea is to use a Class, with static methods to add and remove references in a static vector, that keeps track of these references, and check that vector upon exit.
The class is detecting intentional leaks that I create, but maybe you can find a case where it does not detect the leak, that I am not seeing
#include <iostream>
#include <stdexcept>
#include <memory>
#include <vector>
#include <cstdlib> // for REM_LEAKt
#include <algorithm> // for std::remove
void checkLeakStack();
class LeakDbg
{
private:
LeakDbg()
{
/// Constructor will only be called once,
/// since it's a singlton class
std::atexit( checkLeakStack );
}
public:
struct Pair
{
std::string name;
void* ref;
bool operator==( const Pair &other ) const { return ref == other.ref; }
};
static bool locked;
static std::vector<Pair> stack;
static LeakDbg& instance()
{
static LeakDbg INSTANCE;
return INSTANCE;
}
static void addRef(const std::string& nm, void* ptr)
{
stack.push_back(Pair{ nm, ptr });
}
static void remRef(void* ptr)
{
/// If it's not enabled, it means
/// it's OK to remove a ref
if( !LeakDbg::locked ){
Pair search = Pair{"",ptr};
std::vector<Pair> vect;
// std::remove(vect.begin(), vect.end(), search);
stack.erase(std::remove(stack.begin(), stack.end(), search), stack.end());
}
}
};
bool LeakDbg::locked = false;
std::vector<LeakDbg::Pair> LeakDbg::stack = std::vector<LeakDbg::Pair>();
void checkLeakStack()
{
/// Here the stack should be emoty
/// you can print or assert if the stack is not empty
std::cout << "There are " << LeakDbg::stack.size() << " leaks ..." "\n";
for ( LeakDbg::Pair pair : LeakDbg::stack) {
const std::string msg = pair.name + " is leaked";
std::cout << msg << std::endl;
}
}
Add defines
#define ADD_LEAK(msg, ptr) LeakDbg::addRef(msg, ptr);
#define REM_LEAK(ptr) LeakDbg::remRef(ptr);
#define CREATE_LEAK_DET() LeakDbg::instance();
#define LCK_LEAK_DET(st) LeakDbg::locked = st;
// ADD_LEAK -> Add it in a class constructor
// REM_LEAK -> Add it in a class destructor
// CREATE_LEAK_DET -> Call it once to make sure "std::atexit" is called
// LCK_LEAK_DET -> If set to "true", all objects destructed after,
// -> will be considered a leak
Test
struct Test {
Test() {
ADD_LEAK( "Cls", this )
}
~Test() {
REM_LEAK( this )
}
};
int main() {
CREATE_LEAK_DET()
Test *obj1 = new Test();
Test *obj2 = new Test();
Test *obj3 = new Test();
delete obj2;
LCK_LEAK_DET( true )
}
Update 12/12/2019
If anybody is interested, I refactored the code to be reusable and less intrusive. Github
A:
Here are some things that may help you improve your code.
Use the required #includes
The code uses std::string which means that it should #include <string>. It might compile on your machine because some other header includes that file, but you can't count on that, and it could change with the next compiler update.
Use only necessary #includes
The #include <stdexcept> and #include <memory> lines are not necessary and can be safely removed because nothing from those headers appears to be used here.
Avoid C-style macros
I'd advise not using C-style macros like the ones in this code, preferring either inline functions or even lambdas. See ES.31 for details.
Consider thread safety
If multiple threads are using this code, there is likely to be a problem because the single shared instance of the std::vector is not protected by a mutex. I would also recommend renaming the existing locked variable to something like complete or finished to better distinguish what it's doing.
Avoid singletons
A singleton is basically just another way to create global variables, and we don't like global variables much because they make code linkages much harder to see and understand. See I.3 for more on that. In this case, since you already have two global variables, much of the complexity can easily be avoided by simply using a namespace instead of a class. Here's one way to do that which eliminates the need for instance and CREATE_LEAK_DET:
namespace LeakDbg
{
struct Pair
{
std::string name;
void* ref;
bool operator==( const Pair &other ) const { return ref == other.ref; }
};
static bool locked = false;
static std::vector<Pair> stack;
static void addRef(const std::string& nm, void* ptr)
{
stack.emplace_back(Pair{ nm, ptr });
}
static void remRef(void* ptr)
{
if( !LeakDbg::locked ){
stack.erase(std::remove(stack.begin(), stack.end(), Pair{"",ptr}), stack.end());
}
}
void checkLeakStack()
{
std::cout << "There are " << LeakDbg::stack.size() << " leaks ..." "\n";
for ( LeakDbg::Pair pair : LeakDbg::stack) {
std::cout << pair.name << " is leaked\n";
}
}
static const bool registered{std::atexit( checkLeakStack ) == 0};
}
Consider the user
The current code requires that the user explicitly instruments the code, which seems a bit intrusive. Here's an alternative approach the modifies things just slightly, using the Curiously Recurring Template Pattern, or CRTP for short. First we isolate the leak detector bits into a templated class.
template <typename T>
struct LeakDetector {
LeakDetector() {
LeakDbg::addRef(typeid(T).name(), this);
}
~LeakDetector() {
LeakDbg::remRef(this);
}
};
Now to use it is much simpler than before. No ugly macros are required and we only need to add one simple thing to the declaration of the class to be monitored:
struct Test : public LeakDetector<Test>
{
Test() {
}
~Test() {
}
};
An even less intrusive approach might be to override new and delete as outlined in this question.
Consider alternatives
Leak detection is a worthwhile thing to do, since many C++ bugs stem from that kind of error. However, there are already a number of existing approaches to this, some of which may already be installed on your computer. There is, for example the useful valgrind tool. If you're using clang or gcc and have the libasan library installed, you can get a very nice runtime printout. Just compile the code with
g++ -g -fsanitize=address myprogram.cpp -o myprogram
Then at runtime, a memory leak report might look like this:
There are 2 leaks ...
Cls is leaked
Cls is leaked
=================================================================
==71254==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 1 byte(s) in 1 object(s) allocated from:
#0 0x7fe67c2c69d7 in operator new(unsigned long) (/lib64/libasan.so.5+0x10f9d7)
#1 0x4057a6 in main /home/edward/test/memleak/src/main.cpp:97
#2 0x7fe67bcbb1a2 in __libc_start_main (/lib64/libc.so.6+0x271a2)
Direct leak of 1 byte(s) in 1 object(s) allocated from:
#0 0x7fe67c2c69d7 in operator new(unsigned long) (/lib64/libasan.so.5+0x10f9d7)
#1 0x405774 in main /home/edward/test/memleak/src/main.cpp:95
#2 0x7fe67bcbb1a2 in __libc_start_main (/lib64/libc.so.6+0x271a2)
SUMMARY: AddressSanitizer: 2 byte(s) leaked in 2 allocation(s).
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I remove a tag without deleting the docker image itself?
Every time I pull an image, there are two tags pulled. Like this:
centos 6 f07f6ca555a5 4 weeks ago 194.6 MB
centos <none> f07f6ca555a5 4 weeks ago 194.6 MB
How can I remove the later tag only?
$ docker info
Containers: 2
Running: 0
Paused: 0
Stopped: 2
Images: 13
Server Version: 1.12.1
Storage Driver: aufs
Root Dir: /mnt/sda1/var/lib/docker/aufs
Backing Filesystem: extfs
Dirs: 181
Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
Volume: local
Network: bridge overlay host null
Kernel Version: 4.4.17-boot2docker
Operating System: Boot2Docker 1.12.1 (TCL 7.2); HEAD : ef7d0b4 - Thu Aug 18 21:18:06 UTC 2016
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 7.604 GiB
Name: default
ID: WUS6:YHEN:O4U4:6GYZ:ECIX:5KQA:SAYJ:HNPY:RJB4:AEMR:QQCE:777M
Docker Root Dir: /mnt/sda1/var/lib/docker
Debug mode (client): false
Debug mode (server): true
File Descriptors: 14
Goroutines: 23
System Time: 2016-10-10T02:13:57.107136165Z
EventsListeners: 0
Registry: https://index.docker.io/v1/
Labels:
provider=virtualbox
docker rmi $(docker images --filter "dangling=true" -q --no-trunc)
This command is not working for me. Actually they are the same image.
A:
This is actually a 1.11.2 bug, reported in issue 23895 and issue 23503.
It is supposed to be fixed in 1.12.x, with PR 23549: "Do not show empty tags for digest references in output".
When a repository has a tag and digests, show tag for each digest value.
Rows will not be duplicated for the same image name which has both a tag and a digest.
If you still see this in 1.12.1, you should open a new issue, as it might be a regression from 1.12.0.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java ftpclient application doesn't connect
I am new to android and java programing. I write following code to connect to ftp server
public class NewMainActivity extends Activity {
TextView Display;
//declare a public FTP client object.
public FTPClient mFTPClient = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_main);
final TextView Display = (TextView) findViewById(R.id.tvResults);
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect("www.filegenie.com",21);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login("user", "MyPassword");
// Set File Transfer Mode
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
Display.setText("Correct"+ String.valueOf(status)); //return status;
}
}catch(Exception e) {
Display.setText(" Exception message is = "+e.getMessage()+" Reply code = "+mFTPClient.getReplyCode());
}
}
When I run this code I get no specific error but the program didn't execute mFTPClient.connect method and jumps to the 'Exception' part and I get "null" as exception getMessage and "0" as ReplyCode.
I have import all the required files such as
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
I am using eclipse and ADT Build v22.0.1-685705.
I have also included commons-net-3.3, commons-net-3.3-sources and commons-net-examples-3.3 files in the android project's lib, and also included the java files and folders from
commons-net-3.3-src | src | main | java | org | apache | commons | net folder to the Android project's src folder by creating the folders org | apache | commons | net.
I could not figured out what is the problem.
Can any one help me in this regard.
The same server can be accessed with a comercial ftp client.
Thanks in advance.
A:
I've tried your code and it works ok. Based on the response code you're getting I assume the connection to the server has not been even established. Make sure you have granted your app with INTERNET permission in the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
EDIT: From the exception stack trace it's clear, that you're trying to execute this code from a main thread. In Android 3.0 (Honeycomb) or later you're not permitted to execute any network call in UI thread by default. The reason is simple: network call may block for an indefinite amount of time, effectively freezing application UI.
You have two options how to fix it:
Lazy way - Disable therad check for network calls:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll()
.build();
StrictMode.setThreadPolicy(policy);
You can always enable thread checks again using
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build();
StrictMode.setThreadPolicy(policy);
Proper way - execute FTP calls from a background worker thread using AsyncTask. Take a look here for examples and comprehensive explanation about AsyncTasks.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ghost light following main light at point of origin
I have a spotlight in my OpenGL project, the light currently shines down the -z axis like a ceiling light, towards the floor, which is just a big quad.
I currently have a cube at the origin of the light, that follows the light around, so I can see exactly where the light is at all times.
My problem is that there is another brighter spotlight that follows the main light, it starts at the origin, or the bottom left corner of the floor.
I'd like to remove this white light, as I don't know what's causing it, or how to remove it.
I have tried to play around with some of the variables and see their impact, but I've had little to no success.
Any assistance would be greatly appreciated.
The error:
//ceiling light
GLfloat Light_Ambient[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat Light_Diffuse[] = { 0.0f, 0.0f, 0.0f, 1.0f };
GLfloat Light_Position[] = { Sun.X, Sun.Y, Sun.Z, 1.0f };
GLfloat Spot_Direction[] = { 0.0f, 0.0f, -1.0f };
//ambient
GLfloat Light_Ambient1[] = { 0.4f, 0.4f, 0.4f, 1.0f };
GLfloat Light_Diffuse1[] = { 1.0f, 1.0f, 1.0f, 0.0f };
GLfloat Light_Position1[] = { Sun.X, Sun.Y, Sun.Z, 1.0f };
//ceiling light
glLightfv(GL_LIGHT0, GL_AMBIENT, Light_Ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, Light_Diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, Light_Position);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 55);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, Spot_Direction);
glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 5);
glEnable(GL_LIGHT0);
//ambient
glLightfv(GL_LIGHT1, GL_AMBIENT, Light_Ambient1);
glLightfv(GL_LIGHT1, GL_DIFFUSE, Light_Diffuse1);
glLightfv(GL_LIGHT1, GL_POSITION, Light_Position1);
glEnable(GL_LIGHT1);
A:
I changed some things around and I seem to have solved it.
//ceiling light
GLfloat Light_Ambient[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat Light_Diffuse[] = { 0.0f, 0.0f, 0.0f, 1.0f };
GLfloat Light_Position[] = { Sun.X, Sun.Y, Sun.Z, 1.0f };
GLfloat Spot_Direction[] = { 0.0f, 0.0f, -1.0f };
//ambient
GLfloat Light_Ambient1[] = { 0.6f, 0.6f, 0.6f, 1.0f };
GLfloat Light_Diffuse1[] = { 1.0f, 1.0f, 1.0f, 0.0f };
GLfloat Light_Position1[] = { 0, 0, 0, 0.0f };
//ceiling light
glLightfv(GL_LIGHT0, GL_AMBIENT, Light_Ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, Light_Diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, Light_Position);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 55);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, Spot_Direction);
glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 20);
glEnable(GL_LIGHT0);
//ambient
glLightfv(GL_LIGHT1, GL_AMBIENT, Light_Ambient1);
glLightfv(GL_LIGHT1, GL_DIFFUSE, Light_Diffuse1);
glLightfv(GL_LIGHT1, GL_POSITION, Light_Position1);
glEnable(GL_LIGHT1);
UPDATE:
I'm returning to edit this months later simply because I feel that this answer may help a lot of people with OpenGL and this confusion with lights.
If your lights are broken (like mine were) there's actually a good chance there's nothing wrong with your lights at all, but how you're rendering the world. It's worthwhile to remember that opengl looks a little like this:
https://imgur.com/a/saYxy
What I was actually doing wrong, as you can see from my initial question i was convinced that the Z was the Y and the Y was the Z, and vice versa, this broke all of my lighting calculations back then. If your lights look like mine do, there's a good chance that you're confusing your axis, it isn't that hard to do this when moving from 2d to 3D opengl.
| {
"pile_set_name": "StackExchange"
} |
Q:
Inertial and non-inertial reference frames
My book states that:
A reference frame attached to earth is not inertial because it is
revolving around the sun and it is rotating about its own axis.
Don't we need a specified observer's frame to comment on other frames?
If the observer's frame was on Earth won't Earth be inertial?
I have read other answers to questions based on inertial and non-inertial on this site. I just want to clarify if what I am thinking is right.
A:
Don't we need a specified observer's frame to comment on other frames? If the observer's frame was on Earth won't Earth be inertial?
No, being inertial frame is a property of the frame, not a relative state dependent on the observer.
Frame being inertial is an idealization that is never perfectly realized in practice. A real frame may be pronounced to be inertial if the non-inertial effects in the space and time region of interest are negligible.
Thus Earth can be assumed to be inertial frame if we study motion of ping-pong ball in a common table tennis exchange, because any non-inertial effect is negligible compared to effective gravity and aerodynamic forces. But Earth cannot be assumed to be inertial frame if we study motion of a cannon ball moving across long distances (miles) in Earth's atmosphere, because the Coriolis force due to Earth's rotation has measurable manifestations on such long ballistic trajectories.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nested JSON from a input form
I've been looking around for quite some time but I can't seem to find a way how to best create a nested JSON from client side input fields of sorts.
The end JSON i'd like to create should look like:
{
"DiaryEntry": [
{
"Date": "2019.xx.01",
"Time": "14:00",
"ThingsDone": [
{
"Activity": "Walking",
"Duration": "1h"
}
]
},
{
"Date": "2019.xx.02",
"Time": "19:00",
"ThingsDone": [
{
"Activity": "rolling",
"Duration": "24h"
}
]
}
]
}
(This JSON might be with mistakes, but I hope it's understandable).
Would be ideally if someone could give me some pointers on how to manage at least one nested level via an UI where the person could enter information in a form and that would end up as a JSON like that. I'm doing it this way so it seems to be the easiest way how to manage info and let users have as many dynamically generated input fields (E.g, he can make 100 "ThingsDone" inputs)
Open to other suggestions or pointers!
A:
If you want to do it in javascript, here is a way.
var activities = []
var activity = {}
activity.date = "03-21-2019"
activity.time = "14:30"
var task = {}
task.activity = "Walking"
task.duration = "2h"
var tasks = []
tasks.push(task)
activity.thingsDone = tasks
activities.push(activity)
activity = {}
activity.date = "03-21-2019"
activity.time = "14:30"
task = {}
task.activity = "Walking"
task.duration = "2h"
tasks = []
tasks.push(task)
activity.thingsDone = tasks
activities.push(activity)
var jsonObj = {}
jsonObj.diaryEntry = activities;
console.log(jsonObj)
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I check another empire's FTL method?
There are three different methods of FTL:
Warp
Hyperdrive
Wormholes.
It's useful to know what method other empires use, for defense, etc. While it's easy to tell at a glance if they use wormholes (because of the presence of wormhole stations), is there a method to tell apart the others (without keeping a track of their ships)?
A:
As far as I know, you can't, you have to watch the movements of the foreign fleet. But here you have two options:
If you yourself use hyperspace, you can see the hyperspace lanes, if you don't, you can research a technology (hyperspace mapping) allowing you to do so, though it's a rare tech.
Either way, once you can see the lanes, you can easily determine whether an empire uses hyperspace or warp by seeing whether they travel on the lanes or not. Or wormhole, if they don't travel at all, but simply appear.
Another factor is the cooldown time.
Hyperspace and wormhole have a charge-up time before the jump, whereas warp has a cooldown after a jump. When a foreign fleet enters your system and you read something like "warp winddown" in their status window, they use warp. If they are able to move immediately, they use hyperspace or wormhole.
But you can easily distinguish hyperspace from wormhole by the presence of wormhole stations and the fact, that wormhole fleets appear instantly in your system instead of travelling through space.
A:
When you click an enemy fleet, it has an information, then you click on one of the ship to view ship design. There is one slot of FTL engine that allows using it.
Bonus:
How to counter (this assumes that you have free transportation)
Warp Drive: Use space station (combat one) that bring enemy into the station then kill it quickly or at least make them less powerful before warp wind down.
If you're their friend, they won't have much trouble traveling except if they're surrounded.
Hyperspace: If you use hyperspace mapping, you may block their way if you're their foes, and heavily fortify it if you're their friend, then it would be
a pleasure to allow their access or leave this system theirs.
Wormhole: Split your army and no matter where they came from if you can destroy their wormhole station they're stranded. If you're your friend station right might be good or they may never come to help protecting you. Also this wormhole make you can go pass any territory into system with station. If you're wormhole player you might build a strong economy by building everywhere with rich resources and still get connected.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why storing users passwords at all?
I occasionally see questions asking how to safely store user passwords for a web application (using an RDBMS, I'm not talking of Facebook or Twitter). The usual answer is "salt the password, then hash it with a strong algorithm such as TDES or SHA512".
My question is : As an RDBMS user, why should I bother at all with the password storing problematic at all since most engines have a built-in authentication mechanism.
For example, if some user X wants to create an account user password Y on my web application, how is issuing the following query wrong:
CREATE USER X WITH ENCRYPTED PASSWORD Y IN GROUP baseuser;
Then within my application, the user can open a connection to the database using his credentials and I don't have to bother at all of password management.
I see multiple advantages to this method:
If the RDBMS decides that the encryption algorithm needs to be changed, I don't need to touch anything, just to apply the security updates;
It is easy for me to manage the users authorizations. If a user is promoted to an administrator's role, I just have to add the user to the corresponding group;
SQL injections are now meaningless, for I manage permissions to allow exactly what I want to allow to each user in the database (for example, in a forum like SO, adding new posts, answering to posts, commenting and editing/deleting his own questions/answers/comments);
An user account "anonymous" can be used for unauthenticated connections to my application;
Each user is the owner of the data he provided.
But on virtually every question I see on this topic, there seems to be a general consensus that this is not the way things have to be done. My question is : why?
Note : The third point is allowed by policies in PostgreSQL, and security policies in Microsoft SQL Server. I realize that these concepts are newcomers, but anyway, now that they are here, why doesn't the technique I describe become the standard way to handle users accounts?
A:
Because for many applications, they don't want individual user accounts connecting to the database. The users/passwords/rights/permissions is all handled at the application layer, and a single dedicated service account is used to connect to the database back-end.
As a DBA, I don't want to have to manage, at the database level, the 10,000 active users of some medium-sized public-facing web application, or maybe the 2+ million users of some suddenly popular app.
In a very real sense, this is a difference in philosophy between application developers and database developers/DBAs.
Many/most application developers are not going to want to pass responsibility for major aspects of app functionality and/or business rules down to the database layer. Instead, they view the database as a tool to simply store and retrieve data.
In some cases, this might be short-sighted; many RDBMSes do have awesome features that could make app dev lives much easier (row-level security, columnar indexes, filestream storage, etc.).
But some of these cooler features are only available in newer versions, and organizations aren't always quick to upgrade existing environments (see this chart from 2014).
And in other cases, handling those things at the application layer is preferred (and not just for database platform portability, I frankly think that claim is overblown).
A:
The dividing line is getting a little bit fluffy at that point, but I would consider users and permissions at the database level to be part of the schema not part of the data, and in general applications have no place modifying the schema (there are, as always, exceptions to this rule).
I'd rather not give the application(s) the permissions they need to manage schema objects (logins, users and permissions) as new users are needed and old ones leave, because if that application gets hacked the attacker then has access to those permissions making it easier to crack the database open further. In MS SQL Server unless you are using fully contained databases logins are server level objects so you are needing to hand out rights beyond the single application database making it even more risky.
Furthermore even if you do have per-application-user accounts at your database level you still need application level user accounts to deal with non-authenticated requests - i.e. if the application needs information from the database before the application user has successfully authenticated (perhaps to display status information on the welcome/login screen?).
Also if portability between database engines is a goal (perhaps your app wants to be able to run on both mysql and postgres?) then your applications will need to abstract out the user/login management functions for each engine as they are not standard between them - if you are going to that effort then you might as well implement passwords yourself and get the management options you desire instead of accepting the lowest common feature-set the engines offer.
A:
Restating the question
Why storing users passwords at all?
The simplest answer is that you have to do so. You still store passwords in your alternative method. It's just that you use the database's built-in system to manage the storage. So your method is only as good as your database's. That may still be better than whatever you might do otherwise, but it's not avoiding storage. It's really just avoiding coding storage.
It also might not be better. If I compromise a database and get copies of the files, I can access the tables directly. So there's little point to using a brilliant password management system. Because if someone can access the system level table containing the passwords or hashed passwords, they can also access the files directly. Why bother with cracking passwords when you already have the data? It's not like you can encrypt the data easily either. Each user needs to be able to access it. So user-level encryption won't work so well.
But what you really seem to be asking is
Why use an application level authentication scheme when the database already has one?
Security
Ignoring the possibility that you could write a more secure version, others have suggested a number of reasons. I generally agree. But there's another that no one has mentioned yet. You are compromising the security of your database.
In this system, every user of your application has a database user and password. Sure, it's a limited user, but it's still a user who can connect to the database. Even if you use row level security, you are still allowing end users to know database connection info. If there is ever an exploit where a user can get even table level access, you've opened up your database to attack. And some exploits have gone beyond that to administrator access.
In the layers of the security onion, the normal system is:
Database, which only allows connections from certain machines.
Database, only allows connections as certain user/password combinations.
Servers with database permissions that allow connections from applications.
Applications are run on the server.
Applications have database connection info with limited privileges.
Applications authenticate users before allowing them to modify the database (except possibly to make new accounts).
In this system:
End users know user/password combinations that will work on the database, admittedly with very low privileges.
Only need to comprise a server or convincingly pretend to be an authorized server.
We've lost the entire application level of security. And we've voluntarily given up part of the database layer. So we only need two exploits:
Spoof or compromise an authorized server.
Increase the limited privilege account's access.
If we can do those two things, we have access to the database. So we go from three layers down to two. (The third layer in the normal system is that you need a valid user to connect to the database.)
You are going to be doing a lot of management of these accounts. What if you make a mistake? Instead of limiting user X to just certain rows, you give them all access to a critical table. That kind of stuff is normally done manually and there are only a few of them, so they are easy to audit. But in your system, you could be doing thousands or millions or even billions of user accounts, each with their own idiosyncratic access.
For that matter, does the database's system scale to millions or billions of users? If it does, what about the number of rules? If each user takes up a hundred or more rules about what they can and can't access, does that scale up to a billion users? You're taking a normally small scale system and making it large scale. That won't necessarily work. You may find system limitations as you grow.
| {
"pile_set_name": "StackExchange"
} |
Q:
Make Parallel Ajax requests return response in order
i want to make multiple ajax requests using jQuery that appends table rows into a table but i want their response in order
for (i=0;i<5;i++) {
//variables tempString, start_value updated here after every loop iteration
$.post(
'results.php',
{start_value:start_value,tempString:tempString},
function(data3){
// alert(data3);
$('#data_table tbody tr:last').after(data3);
}
);
}
results.php returns a set of table rows with every request but they dont append to the table in the right order.
how do I make the next ajax requests wait till the first ones are finished?
A:
You need to synchronus call and in your case it call asynchronously thats why it not append in right order.
function doAsyncCall(i) {
if (i < 5) {
$.post(
'results.php',
{start_value:start_value,tempString:tempString},
function(data3){
$('#data_table tbody tr:last').after(data3);
doAsyncCall(i+1);
}
);
}
}
doAsyncCall(0);
| {
"pile_set_name": "StackExchange"
} |
Q:
AS3 Automatically move object to another object when dragged
EDIT: My problem seems at first a bit confusing. Look at this SWF, then you will surely understand my problem. http://www.fastswf.com/AL5D5ZA
Try to drag the green object (which is pDRA, the red one is pCOMPLETE) As you can see only pComplete moves, but the green box should be always in the same position as the red one when moved!
I want to create a movable object using Action Script, but only some of the areas of the object should be dragged, so I have now the complete object movieclip (pCOMPLETE) and the object that can be dragged (pDRA)
How can I make "pDRA" automatically move to "pCOMPLETE" when it has been dragged?
Here is the script I already have:
pDRA.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
function fl_ClickToDrag(event:MouseEvent):void
{
pCOMPLETE.startDrag();
}
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void
{
pCOMPLETE.stopDrag();
}
A:
Place both your pDRA and pComplete in another movieClip so they would be dragged together and then drag that combined MovieClip.
Move your drag code to the timeline of that new movieclip (where both of your objects are in):
pDRA.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ClickToDrag(event:MouseEvent):void
{
this.startDrag();
}
function fl_ReleaseToDrop(event:MouseEvent):void
{
this.stopDrag();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Saving long detail in DB or in file?
Developing an asp.net site on .NET Framework 4.0 and SQL SERVER 2008.
When my admin member saves detail about project from HTMLEditorExtender where do i save it?
Can i save this in Database? (varchar has 8000 chars) Detail can be large.
or in File?
What is the best practice?
For now i saved it in Files because SQL Hosting has less DB space than Disk space.
If i saved it in File then How to get the formated data (with pictures and links) back?
Please Give me the best path to follow. Thanks
A:
You can use VARCHAR(MAX) instead of VARCHAR(8000) - it can hold around 2GB of data.
However, if you are saving HTML, consider using NVARCHAR(MAX) if the posted data may contain Unicode characters (think international audience).
Microsoft research have a good whitepaper about storing files in and out of the database which makes good reading - To Blob or not to Blob.
| {
"pile_set_name": "StackExchange"
} |
Q:
MPVolumeView, avoid displaying "No Volume Available"
I have a project with a MPVolumeView in it. It is set up, and it works, the only thing is that when I mute the device, the text "No Volume Available" comes up instead of the MPVolumeView. I would rather like the slider of the MPVolumeView to be disabled when the device is muted.
The volumeView is initialized in the view volumeBounds, with that view's bounds.
MPVolumeView *volumeView = [[[MPVolumeView alloc] initWithFrame:volumeBounds.bounds] autorelease];
[volumeBounds addSubview:volumeView];
[volumeView sizeToFit];
Thanks :)
If you are interested in helping me with something else, check out this question
A:
Use AudioServices to listen for the hardware volume. When the volume goes to zero, set the alpha of the MPVolumeSlider to zero and place your own disabled UISlider in the same position. Skin your slider to look like the volume slider.
AudioSessionAddPropertyListener( kAudioSessionProperty_CurrentHardwareOutputVolume , ... );
kAudioSessionProperty_AudioRouteChanged might also be useful.
If you walk the view hierarchy under the MPVolumeView, you should find a UISlider. If not, or if it is hidden, you know the mute string is showing.
Edit:
This describes the function prototype for your listener. To pass the message to an instance of your class, do something similar to:
void MyPropertyListener ( void *inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void *inData );
void MyPropertyListener ( void *inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void *inData ) {
if ( inID == kAudioSessionProperty_CurrentHardwareOutputVolume ) {
Float32 volume = *(Float32 *)inData;
[(MyDelegateClass *)inClientData hardwareVolumeChanged:volume];
}
}
AudioSessionAddPropertyListener( kAudioSessionProperty_CurrentHardwareOutputVolume ,
MyPropertyListener , aDelegateInstance );
| {
"pile_set_name": "StackExchange"
} |
Q:
Automated check for question quality
What would cause a question to receive the following message:
Oops! Your question couldn't be submitted because:
It does not meet our quality standards.
(When I added a few words to my question, it was accepted, so I'm guessing my original question was too short. Still, it would be helpful to have a more specific error message.)
A:
It's not just length; several other heuristics contribute to a question's "quality score", and if it scores too low, we block it. Usually, this works out well - questions that fail too many checks are in dire need of cleanup, and giving the author a chance to do this before posting saves everyone time and grief.
However, there are edge-cases where the system falls on its face. If you can't get around the problem by doing a bit of cleanup on your text, you can always ask us to take a look at it.
And yes, the message could be more specific, but that would defeat the purpose - we don't want folks to just pad out their questions until they get through, we're hoping they put a bit more thought into what they're asking.
Further reading: What can I do when getting “It does not meet our quality standards”?
| {
"pile_set_name": "StackExchange"
} |
Q:
Css z-index sub menu
I have a dropdown menu but my problem is that my sub-menu is hidding his parent's item when it appears.
How can I fix it ? I tried with z-index but it doesn't work.
I also tried to increase the margin-top of the sub-menu but the problem is that it becomes unreacheable.
.menu {
list-style: none none;
margin: 0;
padding: 0;
line-height: 1;
font-size: 1.3vw;
z-index: 40;
}
.menu a {
display: block;
padding: .5em;
color: grey;
z-index: 52;
padding-top: 25px;
text-decoration: bold;
background-color: #3A4044;
text-decoration: none;
border-top: 6px solid #3A4044;
}
.menu a:focus,
.menu a:hover {
color: #95A520;
background-color: #3A4044;
text-decoration: underline;
border-top: 6px solid #95A520;
}
.menu-item {
float: right;
/* Pour que les liens s’affichent horizontalement */
position: relative;
/* Crée un contexte de positionnement pour les sous-listes */
}
.menu-item:hover .sub-menu {
z-index: 20;
position: absolute;
/* Evite que la dimension du conteneur ne change quand la sous-liste est affichée */
left: 0;
/* FIX IE7 : pour que le sous-menu s’aligne avec son conteneur */
top: 2em;
/* FIX IE7 : pour que le sous-menu s’aligne avec son conteneur */
white-space: nowrap;
/* Pour que le texte ne revienne pas à la ligne */
background-color: #3A4044;
margin-top: -2px;
/* Pour que le sous-menu recouvre son parent, facilitant le passage de la souris de l’un à l’autre */
text-align: center;
}
.sub-menu {
z-index: 20;
list-style: none;
text-align: center;
position: absolute;
/* Evite que la dimension du conteneur ne change quand la sous-liste est affichée */
left: -1500px;
/* FIX IE7 : pour que le sous-menu s’aligne avec son conteneur */
top: 4em;
/* FIX IE7 : pour que le sous-menu s’aligne avec son conteneur */
white-space: nowrap;
/* Pour que le texte ne revienne pas à la ligne */
background-color: #3A4044;
margin-top: -2px;
/* Pour que le sous-menu recouvre son parent, facilitant le passage de la souris de l’un à l’autre */
}
.sub-menu a {
border: none;
z-index: 20;
}
.sub-menu ul {
margin-top: 15px;
}
.menu-item-has-children {
z-index: 999;
position: absolute;
}
.sub-menu a:hover {
border: none;
}
#menu {
background-color: #3A4044;
position: absolute;
display: inline;
top: 0px;
z-index: 1;
width: 100%;
Height: 12%;
}
<div id="menu">
<div class="menu-menu-container">
<ul id="menu-menu" class="menu">
<li id="menu-item-41" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-41"><a href="http://heriaucouverture.fr/presentation/">Présentation</a>
</li>
<li id="menu-item-44" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-44"><a href="http://heriaucouverture.fr/nos-realisations/">Nos réalisations</a>
<ul class="sub-menu">
<li id="menu-item-85" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-85"><a href="http://heriaucouverture.fr/nos-realisations/eglises/">Eglises</a>
</li>
<li id="menu-item-84" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-84"><a href="http://heriaucouverture.fr/nos-realisations/chateaux/">Châteaux</a>
</li>
<li id="menu-item-83" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-83"><a href="http://heriaucouverture.fr/nos-realisations/manoirs/">Manoirs</a>
</li>
<li id="menu-item-82" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-82"><a href="http://heriaucouverture.fr/nos-realisations/habitations/">Habitations</a>
</li>
</ul>
</li>
<li id="menu-item-47" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-47"><a href="http://heriaucouverture.fr/savoir-faire/">Savoir-faire</a>
</li>
<li id="menu-item-50" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-50"><a href="http://heriaucouverture.fr/ornementation/">Ornementation</a>
</li>
<li id="menu-item-53" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-53"><a href="http://heriaucouverture.fr/news/">News</a>
</li>
<li id="menu-item-56" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-56"><a href="http://heriaucouverture.fr/contact/">Contact</a>
</li>
<li id="menu-item-59" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59"><a href="http://heriaucouverture.fr/liens-utiles/">Liens utiles</a>
</li>
</ul>
</div>
</div>
A:
improve your code by this
i have just improved it by top: 3.45em; from top: 2em;
in .menu-item:hover .sub-menu
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does English need an article before any noun?
In my native language, we can say:
I have dog
Because I don't want to say a dog (one dog, how many dogs) or the dog (that dog, the listener don't care which dog).
p.s. after 3 years later, I have to say, why I ask this question, is I still cannot grasp how to use the right 'article word'. sometimes, a noun will use an article, sometimes, a noun could not(or omit) the article word before it. there aren't a formula for this. So, I have to remember all the time! I feel so frustrate
A:
Well, first of all, we don't need an article before any noun. I can say:
I like dogs.
As to your question of why, the answer is, "because that is how English works".
The articles perform a discourse function, by indicating new and old information. They often evolve from demonstratives (e.g. "this" and "that"). They evolve independently in unrelated languages. Normally, once an article system becomes a part of a language, it is an all-or-nothing thing. This is not unlike a verbal inflection system, a gender system, or a case system; once the system is in place, it is not optional.
Aside from this, there isn't really a more concrete reason for "why" English works this way.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i set the location of minor ticks in matplotlib
I want to draw a grid on the x-axis in a matplotlib plot at the positions of the minor ticks but not at the positions of the major ticks. My mayor ticks are at the positions 0, 1, 2, 3, 4, 5 and have to remain there. I want the grid at 0.5, 1.5, 2.5, 3.5, 4.5.
....
from matplotlib.ticker import MultipleLocator
....
minorLocator = MultipleLocator(0.5)
ax.xaxis.set_minor_locator(minorLocator)
plt.grid(which='minor')
The code above does not work since it gives the locations at 0.5, 1.0, 1.5, ... How can I set the positions of the minor ticks manually?
A:
You can use matplotlib.ticker.AutoMinorLocator. This will automatically place N-1 minor ticks at locations spaced equally between your major ticks.
For example, if you used AutoMinorLocator(5) then that will place 4 minor ticks equally spaced between each pair of major ticks. For your use case you want AutoMinorLocator(2) to just place one at the mid-point.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoMinorLocator
N = 1000
x = np.linspace(0, 5, N)
y = x**2
fig, ax = plt.subplots()
ax.plot(x, y)
minor_locator = AutoMinorLocator(2)
ax.xaxis.set_minor_locator(minor_locator)
plt.grid(which='minor')
plt.show()
Using AutoMinorLocator has the advantage that should you need to scale your data up, for example so your major ticks are at [0, 10, 20, 30, 40, 50], then your minor ticks will scale up to positions [5, 15, 25, 35, 45].
If you really need hard-set locations, even after scaling/changing, then look up matplotlib.ticker.FixedLocator. With this you can pass a fixed list, for example FixedLocator([0.5, 1.5, 2.5, 3.5, 4.5]).
| {
"pile_set_name": "StackExchange"
} |
Q:
Cancelling and restarting a task
I have read a few articles about this but I am currently none-the-wiser. I'm working on an application where there is a TabControl located on the form. When the user clicks on a tab page, I would like the background process to run off of the UI thread (as the process can take several minutes). This is fine, however if the user selects a different tab, I would like any currently active task to cancel, and for the attention to go to the new tab.
private void ParentTabControl_SelectedIndexChanged(object sender, EventArgs e)
{
Task testTask;
CancellationTokenSource testSource = new CancellationTokenSource();
CancellationToken testToken = testSource.Token;
switch (ParentTabControl.SelectedIndex)
{
case 0:
updateSummaryTab();
break;
case 1:
testTask = Task.Run(() =>
{
updateTabOne();
}, testToken);
break;
case 2:
updateTabTwo();
break;
}
}
If I set the testSource to cancel, then this will no longer by usable (though I am aware that I will need to use a token of some kind). I was previously using a different BackgroundWorker for each tab and simply checking the IsBusy property of it, but I thought using a single recycled Task may be the better option.
A:
The problem I get is when I cancel the task using the CancellationToken, the new task fails to launch
Create a fresh CTS (and CT) for each round of work that you are starting. You need to store the CTS for the last round in a field. Then, starting new work is:
if(cts != null) cts.Cancel();
cts = new ...;
StartWork(cts.Token);
Be aware, that cancelling running tasks is cooperative and passing the token to Task.Run does nothing because it does not stop the already running task.
| {
"pile_set_name": "StackExchange"
} |
Q:
Zenoss MySQL Query - Events per hour
I am working on some trending/analysis tools, and would like to query the events MySQL database for an events per hour metric so that I can send the metric out as a datapoint in graphite. Because some events will be in the status table, while others in the history table, I came up with the basic query I am looking for. Keeping in mind, that I am by no means a DBA, I would like to learn how to get a total count from both tables. Here is what I have so far:
mysql> SELECT COUNT(*) FROM events.history WHERE firstTime > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) AND (severity='5' OR severity='3')
-> UNION
-> SELECT COUNT(*) FROM events.status WHERE firstTime > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) AND (severity='5' OR severity='3')
-> ;
+----------+
| COUNT(*) |
+----------+
| 27 |
| 267 |
+----------+
2 rows in set (0.00 sec)
mysql>
I am hoping to modify the SQL to return a single row, with the count from both tables added, so in the example it would be 294. Somebody told me that I can accomplish this with a join, but I seem to be having some trouble getting the syntax dialed in.
A:
Put the union in a subquery and then use SUM() to add them together.
SELECT SUM(c) total
FROM (SELECT COUNT(*) c FROM events.history WHERE firstTime > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) AND (severity='5' OR severity='3')
UNION
SELECT COUNT(*) c FROM events.status WHERE firstTime > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) AND (severity='5' OR severity='3')
) u
| {
"pile_set_name": "StackExchange"
} |
Q:
Filter and list specific file names
I generated a list of files by writing the following code:
files = [file for file in Path(main_directory).rglob('*filename*v*.xlsx')]
It retrieves a list of files :
files[0] = .../2018/filename 2018 v 1.xlsx
files[1] = .../2019/filename 2019 v 5.xlsx
files[2] = .../2020/filename 2020 v 4.xlsx
files[3] = .../2020/filename 2020 v 5.xlsx
...
files[13] = .../2020/filename 2020 v 10.xlsx
What can I do to have an output to give me only the biggest v for each year, so I will have an output like this?
files[0] = .../2018/filename 2018 v 1.xlsx
files[1] = .../2019/filename 2019 v 5.xlsx
files[2] = .../2020/filename 2020 v 10.xlsx
I have to get the biggest v which doesn't mean it has the latest modified date, so I can not use that functionality.
I have tried os.path and re but I am getting no where.
A:
Assuming that the filenames of same years are together you can try this.
x=["2018/filename 2018 v 1.xlsx","2019/filename 2019 v 5.xlsx","2020/filename 2020 v 4.xlsx","2020/filename 2020 v 5.xlsx","2020/filename 2020 v 10.xlsx"]
from itertools import groupby
import re
for i,j in groupby(x, lambda x:int(re.findall(r"(?<=filename )\d+", x)[0])):
print max(j, key=lambda x:int(re.findall(r"(?<=v )\d+(?=\.xlsx)", x)[0]))
Output:
2018/filename 2018 v 1.xlsx
2019/filename 2019 v 5.xlsx
2020/filename 2020 v 10.xlsx
| {
"pile_set_name": "StackExchange"
} |
Q:
Rcpp - Capture result of sregex_token_iterator to vector
I'm an R user and am learning c++ to leverage in Rcpp. Recently, I wrote an alternative to R's strsplit in Rcpp using string.h but it isn't regex based (afaik). I've been reading about Boost and found sregex_token_iterator.
The website below has an example:
std::string input("This is his face");
sregex re = sregex::compile(" "); // find white space
// iterate over all non-white space in the input. Note the -1 below:
sregex_token_iterator begin( input.begin(), input.end(), re, -1 ), end;
// write all the words to std::cout
std::ostream_iterator< std::string > out_iter( std::cout, "\n" );
std::copy( begin, end, out_iter );
My rcpp function runs just fine:
#include <Rcpp.h>
#include <boost/xpressive/xpressive.hpp>
using namespace Rcpp;
// [[Rcpp::export]]
StringVector testMe(std::string input,std::string uregex) {
boost::xpressive::sregex re = boost::xpressive::sregex::compile(uregex); // find a date
// iterate over the days, months and years in the input
boost::xpressive::sregex_token_iterator begin( input.begin(), input.end(), re ,-1), end;
// write all the words to std::cout
std::ostream_iterator< std::string > out_iter( std::cout, "\n" );
std::copy( begin, end, out_iter );
return("Done");
}
/*** R
testMe("This is a funny sentence"," ")
*/
But all it does is print out the tokens. I am very new to C++ but I understand the idea of making a vector in rcpp with StringVector res(10); (make a vector named res of length 10) which I can then index res[1] = "blah".
My question is - how do I take the output of boost::xpressive::sregex_token_iterator begin( input.begin(), input.end(), re ,-1), end; and store it in a vector so I can return it?
http://www.boost.org/doc/libs/1_54_0/doc/html/xpressive/user_s_guide.html#boost_xpressive.user_s_guide.string_splitting_and_tokenization
Final working Rcpp solution
Including this because my need was Rcpp specific and I had to make some minor changes to the solution provided.
#include <Rcpp.h>
#include <boost/xpressive/xpressive.hpp>
typedef std::vector<std::string> StringVector;
using boost::xpressive::sregex;
using boost::xpressive::sregex_token_iterator;
using Rcpp::List;
void tokenWorker(/*in*/ const std::string& input,
/*in*/ const sregex re,
/*inout*/ StringVector& v)
{
sregex_token_iterator begin( input.begin(), input.end(), re ,-1), end;
// write all the words to v
std::copy(begin, end, std::back_inserter(v));
}
//[[Rcpp::export]]
List tokenize(StringVector t, std::string tok = " "){
List final_res(t.size());
sregex re = sregex::compile(tok);
for(int z=0;z<t.size();z++){
std::string x = "";
for(int y=0;y<t[z].size();y++){
x += t[z][y];
}
StringVector v;
tokenWorker(x, re, v);
final_res[z] = v;
}
return(final_res);
}
/*** R
tokenize("Please tokenize this sentence")
*/
A:
My question is - how do I take the output of
boost::xpressive::sregex_token_iterator begin( input.begin(),
input.end(), re ,-1), end; and store it in a vector so I can return
it?
You're already halfway there.
The missing link is just std::back_inserter
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <boost/xpressive/xpressive.hpp>
typedef std::vector<std::string> StringVector;
using boost::xpressive::sregex;
using boost::xpressive::sregex_token_iterator;
void testMe(/*in*/ const std::string& input,
/*in*/ const std::string& uregex,
/*inout*/ StringVector& v)
{
sregex re = sregex::compile(uregex);
sregex_token_iterator begin( input.begin(), input.end(), re ,-1), end;
// write all the words to v
std::copy(begin, end, std::back_inserter(v));
}
int main()
{
std::string input("This is his face");
std::string blank(" ");
StringVector v;
// find white space
testMe(input, blank, v);
std::copy(v.begin(), v.end(),
std::ostream_iterator<std::string>(std::cout, "|"));
std::cout << std::endl;
return 0;
}
output:
This|is|his|face|
I used legacy C++ because you used a regex lib from boost instead of std <regex>; maybe you better consider C++14 right from the start when you learn c++ right now; C++14 would have shortened even this small snippet and made it more expressive.
| {
"pile_set_name": "StackExchange"
} |
Q:
Vim colors too bright (terminal)
I have a problem with Vim and iTerm2, the colors are too bright (for ALL themes). It works with both Terminal.app and MacVim, so I guess it must be some setting in iTerm2 I've completely missed.
The picture below shows you the difference (iTerm2 to the left, MacVim / Terminal.app to right):
What I'm using:
iTerm2: Build 1.0.0.20130624
Terminal type: xterm-256
Shell: zsh 5.0.2
Vim: version 7.3.666
OS X: 10.7.5
Do you guys have any idea what I'm missing?
A:
You shouldn't compare colorschemes in GUI Vim and in CLI Vim: the number of colors that can be used in both contexts is very different and it makes any comparison worthless. You can get very subtle colors in GUI Vim but you can only approximate them in CLI Vim.
The values used for the gui and those used for the cli are probably different which explains what you see.
The only way to have the same colors in gui and cli vim is to use only colors from the xterm palette for the gui.
In Vim, you could :set background=light (and read :help 'background') to see if it makes the colors less bright.
In your terminal emulator, you could see if there's a setting that deals with color brightness or the usage of bold.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to write '&' in html without converting to '&'?
I need to ignore the character escaping and actually write & in my text.
Is there a way to escape the escape?
A:
You can use &amp for writing &
| {
"pile_set_name": "StackExchange"
} |
Q:
How to retrieve all usernames alongside a boolean flag for each user to indicate their membership to a group?
I am trying to build a page which allows the admin user to toggle membership to a particular group for each user. I aim to do this with AJAX functionality. I am using Django 2.2.
I have implemented an AJAX call which returns all users in the system - this data populates a data table. The next step is to have a checkbox next to each user, indicating their membership to a group.
I am using the code below in my view to retrieve users.
users = list(GeminiUser.objects.filter(is_active=1).values('email'))
I want the users query result to contain a boolean field for each user indicating their membership to a particular group. How can I achieve this?
Appreciate any guidance.
A:
We can do this with a subquery and with an Exists [Django-doc]:
from django.db.models import Exists, OuterRef
in_group = Group.objects.filter(
pk=mygroup.pk,
user=OuterRef('pk')
)
my_users = User.objects.annotate(in_group=Exists(in_group))
with mygroup.pk the primary key of the group for which you want to check membership.
This queryset contains User objects with an extra attribute in_group that is True if the user belongs to the group, and False otherwise.
For example:
>>> from django.contrib.auth.models import Group, User
>>> mygroup = Group.objects.first()
>>> from django.db.models import Exists, OuterRef
>>>
>>> in_group = Group.objects.filter(
... pk=mygroup.pk,
... user=OuterRef('pk')
... )
>>>
>>> my_users = User.objects.annotate(in_group=Exists(in_group))
>>> my_users
<QuerySet [<User: >, <User: test>]>
>>> [u.in_group for u in my_users]
[True, False]
You can perform extra filtering on the queryset as well, such that it for example only shows active users, etc.
As for the serialization, please use a serializer [Django REST framework doc] [Django-doc]. Using .values() is not recommended at all. By separating the query and representation, you make it easier to extend, update, etc. your REST views.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Saboteur after Bridge in Dominion
In Dominion I play a combo: Any card which gives me an additional 2 actions, then Bridge folloewed by Saboteur.
Bridge makes any card in my hand cheaper (i.e. cost $1 less) and cards in other players' hands, which is directly stated in the card's description. What about cards in other players' decks?
After playing Saboteur players should normally reveal cards from their decks until they find one which costs $3 or more. Does Bridge affect the prices of these cards too? (i.e. Do other players need to find a card worth originally $4 in this case?)
A:
Bridge affects the costs.
From the Dominion Intrigue rules, page 8
Saboteur
...
Costs of cards are affected by Bridge
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript object constructor doesn't register argument
Why do the isSingleand household arguments not seem to pass to the appropriate properties of the Person object when creating them and pushing them to kidsArr at the end of the script inside the switch while the instances created earlier in the script and being pushed to s20to24Arrseem to be getting the arguments properly? What am I missing?
startPop = 1000
var getRandom = function(min, max) {
return Math.random() * (max - min) + min;
};
var lastNames = ['SMITH', 'JOHNSON', 'WILLIAMS', 'JONES', 'BROWN', 'DAVIS', 'MILLER'];
var firstNamesMale = ["Michael", "Christopher", "Jason", "David", "James", "John"];
var firstNamesFemale = ["Jennifer", "Amy", "Melissa", "Michelle", "Kimberly"];
var sex = ["Male", "Female"];
var genSex = function() {
var index = Math.round(getRandom(0, sex.length - 1));
return sex[index];
};
var genLastName = function() {
var index = Math.round(getRandom(0, lastNames.length - 1));
return lastNames[index];
};
var genFirstNameMale = function() {
var index = Math.round(getRandom(0, firstNamesMale.length - 1));
return firstNamesMale[index];
};
var genFirstNameFemale = function() {
var index = Math.round(getRandom(0, firstNamesFemale.length - 1));
return firstNamesFemale[index];
};
var s20to24Arr = [];
var householdArray = [];
var kidsArr = [];
var sing20to24 = Math.round(startPop * 0.088 * 0.8385);
var Person = function(sex, age, isSingle, lastName, household) {
if (sex === undefined) {
this.sex = genSex();
} else {
this.sex = sex;
}
if (lastName === undefined) {
this.lastName = genLastName();
} else {
this.lastName = lastName;
}
this.firstName = this.sex === "Male" ? genFirstNameMale() : genFirstNameFemale();
if (age === undefined) {
this.age = genAgeAdult();
} else {
this.age = age;
}
//this.income = 0;
//this.isEmployed = true;
//this.isRetired = false;
this.isSingle = isSingle;
this.household = household;
};
var Household = function(man, woman) {
this.man = man;
this.woman = woman;
//this.house = undefined;
this.kid1 = undefined;
this.kid2 = undefined;
this.kid3 = undefined;
//this.income : this.man.income + this.woman.income;
//this.expenses : 0;
//this.savings : 0;
//this.debts : 0;
//this.isHomeOwner : true;
};
var numKids = function(isSingle) {
var num = getRandom(0, 100);
if (!isSingle) {
if (num <= 47.73) {
return 0;
} else if (num <= 68.22) {
return 1;
} else if (num <= 90.46) {
return 2;
} else {
return 3;
}
} else {
if (num <= 82.31) {
return 0;
} else if (num <= 93.04) {
return 1;
} else if (num <= 98.11) {
return 2;
} else {
return 3;
}
}
};
//This creates instances of the Person object with lastName, firstName, sex, age, isSingle and household properties. It also creates an instance of the Household object.
for (var i = 0; i < sing20to24; i += 2) {
s20to24Arr.push(new Person("Male", Math.round(getRandom(20, 24)), true));
s20to24Arr.push(new Person("Female", Math.round(getRandom(20, 24)), true));
var curMale = s20to24Arr[i],
curFem = s20to24Arr[i + 1];
householdArray.push(new Household(curMale));
var index = householdArray.length > 0 ? householdArray.length - 1 : 0;
curMale.household = householdArray[index];
householdArray.push(new Household(undefined, curFem));
curFem.household = householdArray[index + 1];
var kids = numKids(true);
switch (kids) {
case 0:
break;
case 1:
kidsArr.push(new Person(undefined, Math.round(getRandom(0, 5), true, curFem.lastName,
curFem.household)));
var ind = kidsArr.lenght - 1;
curFem.household.kid1 = kidsArr[ind];
break;
case 2:
kidsArr.push(new Person(undefined, Math.round(getRandom(0, 5), true, curFem.lastName,
curFem.household)));
kidsArr.push(new Person(undefined, Math.round(getRandom(0, 5), true, curFem.lastName,
curFem.household)));
var ind = kidsArr.lenght - 1;
curFem.household.kid1 = kidsArr[ind - 1];
curFem.household.kid2 = kidsArr[ind];
break;
case 3:
kidsArr.push(new Person(undefined, Math.round(getRandom(0, 5), true, curFem.lastName,
curFem.household)));
kidsArr.push(new Person(undefined, Math.round(getRandom(0, 5), true, curFem.lastName,
curFem.household)));
kidsArr.push(new Person(undefined, Math.round(getRandom(0, 5), true, curFem.lastName,
curFem.household)));
var ind = kidsArr.lenght - 1;
curFem.household.kid1 = kidsArr[ind - 2];
curFem.household.kid2 = kidsArr[ind - 1];
curFem.household.kid3 = kidsArr[ind];
break;
}
}
console.log(s20to24Arr[0]);
console.log(kidsArr[0]);
A:
Are you sure you are placing parentheses in correct places?
You do this:
new Person(
undefined,
Math.round(
getRandom(0, 5),
true,
curFem.lastName,
curFem.household
)
)
I indented the code on purpose so that you can see your error. You pass 2 parameters to the Person constructor, the second one being Math.round(...) which eats the rest of your parameters.
It should probably be like this:
new Person(
undefined,
Math.round(getRandom(0, 5)),
true,
curFem.lastName,
curFem.household
)
I didn't check anything else, there might be more errors but this is an overlooked basic mistake.
s20to24Arr gets correct object because you put parentheses correctly there:
s20to24Arr.push(
new Person("Male", Math.round(getRandom(20, 24)), true) // here Math.round takes only 1 parameter as it should
);
| {
"pile_set_name": "StackExchange"
} |
Q:
Android multiple lists using @id/android:list
I've got a new List of things that needs to be clicked but this one isn't working. onListItemClick is never called. I have another one in my app that has been working as expected and I can't figure out what the difference is. It occurs to me that maybe there's some conflict since they are both using the provided @id/android:list but they're in different Activities and I haven't found other people complaining about the same problem so I'm not sure.
Here is a bunch of code. I would appreciate any suggestions.
Working:
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
// get the item that was clicked
v_ProjectInvestigatorSiteContact project = (v_ProjectInvestigatorSiteContact) this.getListAdapter().getItem(
position);
Intent myIntent = new Intent(this, Details.class);
myIntent.putExtra(res.getString(R.string.project), project);
startActivity(myIntent);
}// onListItemClick
Not Working:
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
// get the item that was clicked
final v_SitePeople vSitePeople = (v_SitePeople) this.getListAdapter().getItem(
position);
AlertDialog.Builder builder = new AlertDialog.Builder(Share.this);
builder.setTitle(res.getString(R.string.forgot_password_check_dialog_title))
.setMessage(res.getString(R.string.share_check_dialog_text))
.setPositiveButton(res.getString(R.string.send), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
sendShareEmail(vSitePeople);
}
}).setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// cancelled, so do nothing
}
});
AlertDialog msgBox = builder.create();
msgBox.show();
}// onListItemClick
Working XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffffff"
android:orientation="vertical" >
<!-- dummy item to prevent edittext from gaining focus on activity start -->
<LinearLayout
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/title_background" >
<ImageView
android:id="@+id/logo"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_logo" >
</ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/logo"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingLeft="50dp"
android:paddingRight="60dp"
android:paddingTop="5dp"
android:text="@string/app_header"
android:textColor="#ffffffff"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/search_gradient" >
<ImageView
android:id="@+id/searchBoxIcon"
android:layout_width="38dp"
android:layout_height="38dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:scaleType="centerCrop"
android:src="@drawable/action_search" >
</ImageView>
<EditText
android:id="@+id/searchBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="@+id/searchBoxIcon"
android:layout_marginRight="8dp"
android:layout_marginTop="4dp"
android:layout_toRightOf="@+id/searchBoxIcon"
android:background="@drawable/search_box"
android:hint="@string/search_hint"
android:inputType="text"
android:maxLines="1"
android:minHeight="30sp"
android:paddingBottom="2dp"
android:paddingLeft="25sp"
android:paddingTop="2dp"
android:textColor="#ff000000" />
</RelativeLayout>
<ListView
android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/divider_gray"
android:cacheColorHint="#00000000"
android:divider="@color/divider_gray"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false" />
<TextView
android:id="@+id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/loading"
android:textColor="@color/loading_gray"
android:textSize="20sp" />
</LinearLayout>
Not Working XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffffff"
android:orientation="vertical" >
<!-- dummy item to prevent edittext from gaining focus on activity start -->
<LinearLayout
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/title_background" >
<ImageView
android:id="@+id/logo"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_logo" >
</ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/logo"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingLeft="50dp"
android:paddingRight="60dp"
android:paddingTop="5dp"
android:text="@string/share_header"
android:textColor="#ffffffff"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
<ListView
android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/divider_gray"
android:cacheColorHint="#00000000"
android:divider="@color/divider_gray"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false" />
<TextView
android:id="@+id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/loading"
android:textColor="@color/loading_gray"
android:textSize="20sp" />
</LinearLayout>
Here is more on how the broken one works, just in case you want more code.
Not Working Row XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:layout_weight="1"
android:baselineAligned="false"
android:orientation="vertical"
android:padding="6dp"
android:background="#ffffffff"
android:layout_margin="10dp" >
<TextView
android:id="@+id/toptext"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toLeftOf="@id/moreInfo"
android:gravity="center_vertical"
android:minHeight="20sp"
android:textColor="#ff000000"
android:textStyle="bold" />
</RelativeLayout>
Not Working View Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null)
{
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.share_row, null);
convertView.setTag(holder);
}// if
else
{
holder = (ViewHolder) convertView.getTag();
}
v_SitePeople i = items.get(position);
if (i != null)
{
TextView topText = (TextView) convertView.findViewById(R.id.toptext);
topText.setGravity(Gravity.CENTER_VERTICAL);
topText.setMinHeight(40);
if (topText != null)
{
if (i.SitePerson != null)
{
if (i.PersonTitle != null)
{
topText.setText(String.format(i.SitePerson + ", " + i.PersonTitle));
}
else
{
topText.setText(i.SitePerson);
}
}// if has ProtocolNumber
else
{
if (i.Nickname != null)
{
topText.setText(i.Nickname);
}
}// if does not have ProtocolNumber
}// if
}// if
return convertView;
}// getView
Thank you so much for your help.
More code as requested.
Working setListAdapter:
public void updateDisplay(ArrayList<v_ProjectInvestigatorSiteContact> vProjectInvestigatorSiteContactList)
{
if (fullAdapter != null)
{
if (fullAdapter.isEmpty())
{
fullAdapter = new ProjectAdapter(this, R.layout.row, vProjectInvestigatorSiteContactList);
fullAdapter = reOrder(fullAdapter);
setListAdapter(fullAdapter);
}
else
{
filteredAdapter = new ProjectAdapter(this, R.layout.row, vProjectInvestigatorSiteContactList);
filteredAdapter = reOrder(filteredAdapter);
setListAdapter(filteredAdapter);
}
}
else
{
fullAdapter = new ProjectAdapter(this, R.layout.row, vProjectInvestigatorSiteContactList);
fullAdapter = reOrder(fullAdapter);
setListAdapter(fullAdapter);
}
}// updateDisplay
Working list setup:
private class DownloadProjectsTask extends AsyncTask<String, Void, ArrayList<v_ProjectInvestigatorSiteContact>> {
@Override
protected ArrayList<v_ProjectInvestigatorSiteContact> doInBackground(String... URLs)
{
return ProjectsHelper.parseProjects(URLs, CurrentStudies.this);
}// doInBackground
@Override
protected void onPostExecute(ArrayList<v_ProjectInvestigatorSiteContact> vProjectInvestigatorSiteContactList)
{
updateDisplay(vProjectInvestigatorSiteContactList);
}// onPostExecute
}// DownloadProjectsTask
Working adapter:
public class ProjectAdapter extends ArrayAdapter {
private ArrayList items;
private Resources res;
public ProjectAdapter(Context context, int textViewResourceId, ArrayList<v_ProjectInvestigatorSiteContact> items)
{
super(context, textViewResourceId, items);
this.items = items;
this.res = context.getResources();
}// ProjectAdapater
@Override
public int getCount()
{
return items.size();
}
@Override
public v_ProjectInvestigatorSiteContact getItem(int position)
{
return items.get(position);
}
@Override
public long getItemId(int position)
{
return position;
}
@Override
public int getViewTypeCount()
{
return 2;
}
@Override
public int getItemViewType(int position)
{
if (items.get(position).ProjectID == null)
{
return 0;
}
else
{
return 1;
}
}
@Override
public boolean isEnabled(int position)
{
if (getItemViewType(position) == 0)
{
return false;
}
return true;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null)
{
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (type == 0)
{
convertView = vi.inflate(R.layout.row_header, null);
}
else
{
convertView = vi.inflate(R.layout.row, null);
}
convertView.setTag(holder);
}// if
else
{
holder = (ViewHolder) convertView.getTag();
}
v_ProjectInvestigatorSiteContact i = items.get(position);
if (i != null)
{
TextView topText = (TextView) convertView.findViewById(R.id.toptext);
TextView bottomText = (TextView) convertView.findViewById(R.id.bottomtext);
if (topText != null)
{
if (i.ProtocolNumber != null)
{
if (i.WebIndication != null)
{
topText.setText(i.ProtocolNumber);
bottomText.setText(i.WebIndication);
}
else if (i.ProjectName != null)
{
topText.setText(i.ProtocolNumber);
bottomText.setText(i.ProjectName);
}
}// if has ProtocolNumber
else
{
if (i.WebIndication != null)
{
topText.setText(i.WebIndication);
topText.setMinHeight(40);
topText.setGravity(Gravity.CENTER_VERTICAL);
}
else if (i.ProjectName != null)
{
topText.setText(i.ProjectName);
topText.setMinHeight(40);
topText.setGravity(Gravity.CENTER_VERTICAL);
}
else
{
topText.setText(i.SiteID);
topText.setMinHeight(40);
topText.setGravity(Gravity.CENTER_VERTICAL);
}
}// if does not have ProtocolNumber
}// if
// Coming Soon logic
if (i.ProjectStatusID != null)
{
if (i.ProjectStatusID.equals(res.getString(R.string.feasibility_id)))
{
topText.setTextColor(res.getColor(R.color.coming_soon_gray));
bottomText.setText("(Coming Soon)");
}
else {
topText.setTextColor(Color.BLACK);
}
}//if
if (bottomText != null)
{
if (type == 0)
{
if (position == getCount() - 1 || getItemViewType(position + 1) == 0)
{
bottomText.setVisibility(View.VISIBLE);
bottomText.setText(res.getString(R.string.no_studies));
bottomText.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 0, (float) 1.0));
}
else
{
bottomText.setVisibility(View.GONE);
}
}// header followed by another header, or end of list
}// if
//recenters row headers
if (type == 0)
{
topText.setGravity(Gravity.CENTER);
}
}// if
return convertView;
}// getView
public static class ViewHolder {
public TextView textView;
}
}// ProjectAdapter
Not Working setListAdapter:
public void updateDisplay(ArrayList<v_SitePeople> vSitePeopleShareList)
{
adapter = new ShareAdapter(this, R.layout.share_row, vSitePeopleShareList);
setListAdapter(adapter);
}// updateDisplay
Not Working list setup:
private class DownloadShareTask extends AsyncTask<String, Void, ArrayList<v_SitePeople>> {
@Override
protected ArrayList<v_SitePeople> doInBackground(String... params)
{
return ProjectsHelper.getSharePeople(params[0], Share.this);
}// doInBackground
@Override
protected void onPostExecute(ArrayList<v_SitePeople> vSitePeopleShareList)
{
updateDisplay(vSitePeopleShareList);
}// onPostExecute
}// DownloadProjectsTask
A:
I figured it out. I didn't ever post the relevant code, or I'm sure you guys would have spotted it for me.
I copied a non working adapter from a working piece of code which returns false if the viewType is 0. And since my second list only has one type, everything was disabled.
Thank you all for your efforts. I apologize that I didn't give you the correct code.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you send a signal to a remote process in python?
I've seen the signal module, it seems alright for installing signal handlers and setting up alarms but is sending a signal to another process done via, for example
os.system('kill -s SIGUSR2 8269')
And then is there a simple way to do this if the process is on a different host machine?
A:
os.kill() for local processes, paramiko and the kill command for remote systems.
| {
"pile_set_name": "StackExchange"
} |
Q:
onload redirect aleatorio
Gostaria de criar uma função que carregasse uma página aleatória de um determinado endereço. Algo do tipo www.meusite.com/(numeros entre 0-100).html
Acho que a função deveria criar a tag A, depois preencher com o texto www.meusite.com/ + random number + .html; e no final ser ativada por onload dentro da tag body.
Tem como fazer algo do tipo usando JS? Acredito que sim mas nem sei por onde começar.
Agradeço desde já qualquer ajuda.
A:
No HTML insira um onload que chama uma função:
<body onLoad="mudarPagina()">
Função JavaScript:
function mudarPagina() {
var random = Math.floor((Math.random() * 100) + 1);
location.href="http://www.meusite.com/"+random+".html";
}
Seria isso?
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing one event listener to another?
I am new to jquery and I was wondering if it s possible to change all click events (for elements within a specific div) to double click events using jquery? Many thanks in advance.
function isTouchDevice(){
return (typeof(window.ontouchstart) != 'undefined') ? true : false;
}
if(isTouchDevice()===true){
//change click events to doubleclick events
}
A:
Watch this magic:
$('*').each(function(){
var click = $(this).data('events').click;
if(click[0]) { //check if there is a click handler attached
$(this).on('dblclick', click[0].handler).off('click');
}
});
The above will go through every element on the page and move it's click handler to its dblclick handler.
Using * is not usually advised. I would try just selecting all of the elemts that have a click selector instead and go through them.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to deserialize YAML with YAMLDotNet?
I want to deserialize this YAML with YAMLDotNet.
It have sequence and nested mapping.
data.yml
people:
- name: "John"
age: 20
- name: "Michael"
age: 21
- name: "William"
age: 22
network:
address: "192.168.1.1"
port: 1234
param:
paramNumber: 10
paramString: "text data"
paramBool: true
This is my code. But, It can't compile.
I would like to know the following two things.
How to define class to decerialize nested mapping?
How to access it?
Print Deserialized Data
DeserializedObject obj = YamlImporter.Deserialize("data.yml");
foreach(var people in obj.people)
{
Console.WriteLine(people.name);
Console.WriteLine(people.age);
}
Console.WriteLine(obj.network["address"]);
Console.WriteLine(obj.network["port"]);
/* how to access param? */
Deserializer Code (YAMLDotNet)
public class YamlImporter
{
public static DeserializedObject Deserialize(string yamlName)
{
StreamReader sr = new StreamReader(yamlName);
string text = sr.ReadToEnd();
var input = new StringReader(text);
var deserializer = new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build();
DeserializedObject deserializeObject = deserializer.Deserialize<DeserializedObject>(input); /* compile error */
return deserializeObject;
}
}
public class DeserializedObject
{
public List<People> people { get; set; }
public class People
{
public string name { get; set; }
public int age { get; set; }
}
public Dictionary<string, Network> network { get; set; }
public class Network
{
public string address { get; set; }
public int port { get; set; }
public Dictionary<string, Param> param { get; set; }
}
public class Param
{
public int paramNumber { get; set; }
public string paramString { get; set; }
public bool paramBool { get; set; }
}
}
Thanks,
A:
@AluanHaddad's advice helped me solve my problem. Thanks,
// How to access params? //
Console.WriteLine(obj.network.param.paramNumber);
Console.WriteLine(obj.network.param.paramString);
Console.WriteLine(obj.network.param.paramBool);
//public Dictionary<string, Network> network { get; set; }
public Network network { get; set; }
public class Network
{
public string address { get; set; }
public int port { get; set; }
//public Dictionary<string, Param> param { get; set; }
public Param param { get; set; }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
The sum of all the odd numbers to infinity
We have this sequence:
S1: 1+2+3+4+5+6.. (to infinity)
It has been demonstrated, that S1 = -1/12.
Now, what happens if i multiply by a factor of 2?
S2: 2+4+6+8+10+12.... (to infinity).
I have 2S1, which is equal to -1/6
On this, we can create a equation for the odd numbers:
S3: 1+3+5+5+7+9+11... (to infinity)
We know that for every term in S2, every term in S3 is just (n-1)
Or, The sum of the even numbers, Minus , the sum of infinitely many (-1)s
So S3 = -1/6 - ∞
However, we also know that the odd numbers + the even numbers = The natural numbers.
So let's try it.
-1/6 - (-1/6 -∞)
We have -1/6 + 1/6 + ∞
Which is just ∞
So, there we have it. a paradox. S1 cannot be both -1/12 or ∞
A:
Since
$$
\zeta(z)=\sum_{k=1}^\infty\frac1{k^{\large z}}
$$
and
$$
2^{-{\large z}}\zeta(z)=\sum_{k=1}^\infty\frac1{(2k)^{\large z}}
$$
we have
$$
\left(1-2^{-{\large z}}\right)\zeta(z)=\sum_{k=1}^\infty\frac1{(2k-1)^{\large z}}
$$
Thus, the same reasoning that says
$$
\sum_{k=1}^\infty k=\zeta(-1)=-\frac1{12}
$$
would say that
$$
\sum_{k=1}^\infty2k=2\zeta(-1)=-\frac16
$$
and
$$
\sum_{k=1}^\infty(2k-1)=(1-2)\zeta(-1)=\frac1{12}
$$
Taking the difference of these last two, would lead one to conclude that
$$
\sum_{k=1}^\infty1=-\frac14
$$
not $\infty$.
When dealing with divergent series, as with quantum mechanics, things are not always the way one would expect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional gem dependencies
Is it possible to conditionally set a dependency on a gem at install time? Here's my situation which will hopefully clarify the question.
There is a gem I maintain that depends on the json gem. However, I frequently use jruby which has a port of the json gem that's called json-jruby. To work around this I have to build two separate gems for each dependency. I'd like to build one gem that either says it depends on json OR json-jruby, or it checks at install time and uses the right dependency.
Anyone have a good solution to this?
A:
Hmm,
I believe one can code multiple dependencies because I've noticed gems which seemed to do this. But I would you advise against doing this. No matter how simple the code you are inserting here is, when you consider that the user will be loading one gem which depends on another which depends on another, even a small glitch in the logic of one piece of code or another can make the whole dependency train a nightmare.
So, I'd leave your kludge as-is. Further, I'd suggest you have a tarball that users can download as well. I've had to manually extract the code inside of gems whose configuration code wouldn't let me install them.
A:
checkout a somewhat tutorial here: https://github.com/rdp/ruby_tutorials_core/wiki/gem (https://en.wikibooks.org/wiki/Ruby_Programming/RubyGems)
it shows how to install different versions of dependencies depending on what version of ruby the installee is using.
(short answer--it ain't as easy as it should be)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to merge values from an array by position looping
I'm looking to append the values of two arrays by their respective positions [0] and [1]. For example - firstArray = [“John”, “Sam”] and secondArray = [“Smith”, “Thomas”].
I would like the output to read as John Smith and Sam Thomas.
I've tried creating a loop to loop through as shown below:
import UIKit
var firstArray = ["John", "Tim"]
var secondArray = ["Smith"]
for i in firstArray.count - 1 {
let name = firstArray[i] + secondArray[i]
}
Error message: Type 'Int' does not conform to protocol 'Sequence'
A:
The correct syntax of a for loop is:
for [VARIABLE_NAME] in [SEQUENCE] {
}
In this case it could be
for i in 0...(firstArray.count - 1) { }
or
for i in 0..<firstArray.count { }
To merge both arrays, you could do:
let firstArray = ["John", "Sam"]
let secondArray = ["Smith",]
var names = zip(firstArray, secondArray).map { $0 + " " + $1 }
If you want to add the rest of the longer array:
if firstArray.count < secondArray.count {
names.append(contentsOf: secondArray[firstArray.count...])
} else if secondArray.count < firstArray.count {
names.append(contentsOf: firstArray[secondArray.count...])
}
print(names) //["John Smith", "Sam"]
Finally, you could join them this way:
let joinedNames = names.joined(separator: " and ") //John Smith and Sam
More generically, you could merge any number of arrays this way:
func zigzag<T>(through arrays: [[T]]) -> [T] {
var result = [T]()
var index = 0
while true {
var didAppend = false
for array in arrays {
if index < array.count {
result.append(array[index])
didAppend = true
}
}
if didAppend == false { break }
index += 1
}
return result
}
For example:
zigzag(through: [[11, 12], [21, 22, 23, 24], [31, 32, 33]])
//[11, 21, 31, 12, 22, 32, 23, 33, 24]
| {
"pile_set_name": "StackExchange"
} |
Q:
python 2.7 chained conditions If Else not working. What's wrong?
I can't figure out why the following doesn't work.
# Example
print "So, yes or no?"
answer = raw_input()
print answer
if answer == "Yes":
print "Yes indeed!"
elif answer == "yes" or "y":
print "Oh yeah!"
elif answer == "No":
print "No it isn't!"
elif answer == "no" or "n":
print "Not really!"
else:
print "Say what?"
When I remove the or, it does work. What am I doing wrong?
-edit-
I have it now, thanks a lot!
# Example
print "So, yes or no?"
answer = raw_input()
print answer
if answer in "Yes":
print "Yes indeed!"
elif answer in ("yes", "y"):
print "Oh yeah!"
elif answer in "No":
print "No it isn't!"
elif answer in ("no", "n"):
print "Not really!"
else:
print "Say what?"
A:
One problem I see is this:
elif answer == "yes" or "y":
that literally translates to "if answer is yes or True" which always result in True.
You could write it like this:
elif answer in ("yes", "y"):
A:
elif answer == "yes" or answer == "y":
elif answer == "No" or answer == "n":
Using elif answer == "yes" or "y": etc.. you are basically checking if bool("n") not comparing if answer is equal to "n" so your statements will always evaluate to True:
any non empty string will always evaluate to True:
In [38]: bool("n")
Out[38]: True
In [39]: bool("y")
Out[39]: True
In [40]: bool("")
Out[40]: False
You can also test for membership using in if you want to check against more than one value:
elif answer in {"yes", "y"}:
| {
"pile_set_name": "StackExchange"
} |
Q:
Serializing C# model with a custom list to JSON
I have a model with a list that I need to serialize to JSON in order to send a request to a web service.
The problem is that in my model I have a list that need to be serialized in a specific format.
My class looks like the following:
[DataContract()]
public class StanjeZalihaLek : BaseParameters
{
[DataMember(Name = "datumStanje")]
public string _datumStanja;
[DataMember(Name = "type")]
public int Type { get; set; }
[IgnoreDataMember]
public DateTime? DatumStanja { get; set; }
[IgnoreDataMember()]
public List<Lek> ListaLek { get; set; }
[OnSerializing()]
protected void OnSerializingMethod(StreamingContext context)
{
_datumStanja = DatumStanja?.ToString(FormatDate);
}
}
So all the elements are ok except the List ListaLek { get; set; } member that looks like the following:
[DataContract()]
public class Lek
{
const string FormatDate = "dd.MM.yyyy";
[DataMember(Name = "datumUlaz")]
string _datumUlaza;
[DataMember(Name = "datumRok")]
string _rokUpotrebe;
[DataMember(Name = "jkl")]
public string JedinstvenaKlasifikacijaLeka { get; set; }
[DataMember(Name = "kolicina)")]
public double Kolicina { get; set; }
[DataMember(Name = "kpp")]
public string Kpp { get; set; }
[IgnoreDataMember]
public DateTime? DatumUlaza { get; set; }
[IgnoreDataMember]
public DateTime? RokUpotrebe { get; set; }
[OnSerializing()]
protected void OnSerializingMethod(StreamingContext context)
{
_datumUlaza = DatumUlaza?.ToString(FormatDate);
_rokUpotrebe = RokUpotrebe?.ToString(FormatDate);
}
}
This is the way my serialized code is supposed to look like:
{
"idZu": "12345678",
"user": "ustanova1",
"pass": "pass1w0rd",
"type": "1",
"datumStanje": "26.02.2019",
"0": {
"jkl": "0010200",
"kolicina": "4",
"kpp": "071",
"datumUlaz": "26.02.2019",
"datumRok": " 31.12.2019"
},
"1": {
"jkl": "0010220",
"kolicina": "8",
"kpp": "071",
"datumUlaz": "26.02.2019",
"datumRok": " 31.12.2019"
},
"2": {
"jkl": "12205014",
"kolicina": "12",
"kpp": "071",
"datumUlaz": "26.02.2019",
"datumRok ": "31.12.2019"
}
}
So each new element of the list has a number as its DataMember name, with idZu, user and pass being parameters from the BaseParameters class which StanjeZalihaLek derives.
Any ideas? Thanks
A:
Problem solved:
public static byte[] Serialize(this StanjeZalihaLek data)
{
var sb = new StringBuilder();
using (var tw = new System.IO.StringWriter(sb))
{
Newtonsoft.Json.JsonTextWriter jsonWriter = new JsonTextWriter(tw);
jsonWriter.WriteStartObject();
jsonWriter.WriteRaw(JsonConvert
.SerializeObject(data)
.Substring(1)
.TrimEnd('}'));
jsonWriter.WriteRaw(",");
int inx = 0;
foreach (var item in data.ListaLek)
{
var str = $"{inx++}";
jsonWriter.WritePropertyName(str);
jsonWriter.WriteRawValue(JsonConvert.SerializeObject(item));
}
jsonWriter.WriteEndObject();
jsonWriter.Close();
}
return System.Text.Encoding.UTF8.GetBytes(sb.ToString());
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to show a tensor is symmetric
What is the best method for showing that a tensor is a symmetric tensor?
For instance, I would like to show that the second fundamental form
$$II_{ab}=\nabla^T_a \hat{n}_b \big\vert_\Sigma$$
where $\Sigma$ is a restriction to a hypersurface is a symmetric tensor.
I thought about using the theorem that states "the product of a symmetric and antisymmetric tensor is zero" might be a way to do this, but am not sure if there's an easier method for showing such a tensor is symmetric.
A:
Look at how the tensor acts on the two vectors $a$ and $b$. And then compare this to the result when you interchanged $a$ and $b$. If the result is the same for general $a, b$ then you have your proof.
| {
"pile_set_name": "StackExchange"
} |
Q:
List folder ftp sort() expects parameter 1 to be array
My code:
function listar_pastas($pasta) {
$this->lista = ftp_nlist($this->conexao,$pasta);
sort($this->lista);
foreach ($this->lista as $objeto) {
if($this->verificar_pasta($objeto)) {
$pastas[] = $objeto;
}
}
return $pastas;
}
Secund code:
$ftp = new FTP();
$ftp->conectar("host");
$ftp->autenticar("user","pass");
$array_pastas = $ftp->listar_pastas(".");
foreach ($array_pastas as $pasta) {
if($pasta != "." && $pasta != "..") {
$total_musicas = $ftp->total_arquivos($pasta,"mp3");
echo '<option value="'.$pasta.'">'.$pasta.' ('.$total_musicas.')</option>';
}
}
Return erro:
[08-Aug-2014 06:29:55 UTC] PHP Warning: sort() expects parameter 1 to
be array, boolean given in
/home/cassiano/public_html/admin/inc/classe.ftp.php on line 44
[08-Aug-2014 06:29:55 UTC] PHP Warning: Invalid argument supplied for
foreach() in /home/cassiano/public_html/admin/inc/classe.ftp.php on
line 46 [08-Aug-2014 06:29:55 UTC] PHP Warning: Invalid argument
supplied for foreach() in
/home/cassiano/public_html/gerenciar-musicas.php on line 153
[08-Aug-2014 06:29:57 UTC] PHP Warning: sort() expects parameter 1 to
be array, boolean given in
/home/cassiano/public_html/admin/inc/classe.ftp.php on line 44
Ps: The Same code is working on another server!
But on my new server I get this error.
A:
You are assuming everything works as should. But, you should catch the errors.
For example: ftp_nlist return FALSE on error: "Returns an array of filenames from the specified directory on success or FALSE on error.".
You case for that particular function should be:
$this->lista = ftp_nlist($this->conexao,$pasta);
if ($this->lista !== FALSE) {
sort($this->lista);
foreach ($this->lista as $objeto) {
if($this->verificar_pasta($objeto)) {
$pastas[] = $objeto;
}
}
return $pastas;
}
else {
echo 'Unable to list files in the given directory';
die();
}
You should catch the errors for ALL your functions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fat-Free-Framework global variables and functions
I'm new to fat free framework and i'm a little bit confused about the global variables.
$f3->route('GET /@page','display');
function display($f3) {
echo 'I cannot object to an object' . $f3->get('PARAMS.page');
};
$f3->run();
Here i'm using GET /@page as a token for the url route. In the
function i then use $f3->get('PARAMS.page') to get the value of that
variable.
Since $f3->get is the method to get a global variable, why do i have
to pass the $f3 class to the function.
The below code doesn't work ($f3 class not passed to the function).
$f3->route('GET /@page','display');
function display() {
echo 'I cannot object to an object' . $f3->get('PARAMS.page');
};
$f3->run();
So my question is: why do i have to pass the $f3 class to the function?
Thx...
A:
The F3 instance variable which is declared at the very start of your index.php ($f3=require...) can be retrieved anywhere in the code using the static call $f3=Base::instance().
Anyway, for convenience purpose, at routing time this F3 instance as well as the route parameters are passed to the route handler. Therefore, instead of defining your route handler as:
function display() {
$f3=Base::instance();
echo 'I cannot object to an object' . $f3->get('PARAMS.page');
};
you could define it as:
function display($f3) {
echo 'I cannot object to an object' . $f3->get('PARAMS.page');
};
or even better:
function display($f3,$params) {
echo 'I cannot object to an object' . $params['page'];
};
These 3 functions are absolutely identical so you should pick up the one that you understand best. But you should remember that $f3 and $params are only passed at routing time, which means to 3 functions: the route handler, the beforeRoute() hook and the afterRoute() hook. Anywhere else in the code (including inside a class constructor), you should call Base::instance() to retrieve the F3 instance.
PS: your question being "why do i have to pass the $f3 class to the function?", I would suggest you to rename its title to reflect it.
UPDATE: Since release 3.2.1, the F3 instance is also passed to the constructor of the route handler class:
class myClass {
function display($f3,$params) {
echo 'I cannot object to an object' . $params['page'];
}
function __construct($f3) {
//do something with $f3
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pair a beer with a glass?
I have recently begun to learn somethings about beer and I suddenly noticed that, for a while now, I have always been served similar types of beer on different looking beer glasses... which is confusing me. It could be human error, but it's got me wondering what beer glasses should I really be sipping from?
So I decided to get some beer glasses, and what do I find? A plethora of beer glasses, all kinds and funky shapes, where not one glass is like the next. It makes me feel like the beer glass industry is very opinionated, rather than factual, and I need to know how to choose correctly.
Could anyone please instruct me on the general type of beers and how they pair with beer glasses, as well as why x glass goes with y beer?
A:
It might sound snobbish to be peckish about the type of glass but the glass does influence the taste of the beer.
Some things are:
- the thickness of the glass. A thin glass invites to a more delicate way of drinking, a really thick glass would let you expect a sturdier beer.
- the surface compared to the volume of beer. A big surface gives a change to let of more aroma's but I would think you also need a little more foam.
- the capacity to keep the aroma's. As pointed out by Rube. Think of a cognac glass versus a vase. Some glasses also take in you nose deeper than others.
- the way the beer flows. The shape of the glass how quickly you can drink it without spilling. Think of kwak, you HAVE to drink the last very carefully.
So to answer your question: there are many factors how the glass influences how you taste a beer. What's best is very subjective. You could at first stick to the opinion of the brewer, what he finds the best glass for it. If you like the taste with an other glass better, use that. I would not approach this as a hard science. Brewers might choose a specific glass to "stand out".
A:
Beer glasses are mainly a product of the region in which the beer was originated and therefore tied to a specific beer.
Belgian beers - Normally served in goblets because the beers have very complex aromas and the shape of the glass can help present and concentrate them for consumption.
British beers - Normally served in the "nonic" glass. Simply a glass that is easier to hold in the hand whilst standing around the pub. Normally associated with most British ales.
Pilsner - High sided flute to concentrate the hop aroma and show off the high carbonation of Pilsners.
Weissbeir - German wheat beers are usually served in tall glasses to show off the cloudy beer and also the creamy tall head of foam.
Scottish Ale - a Thistle glass designed to evoke the image of the national flower of Scotland.
Stout - Popularized by Guinness, a glass designed to show off the nitrogen bubbles.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to install dkim-filter by apt-get?
In tutorial, DKIM is installed by
sudo apt-get install dkim-filter
I wonder why on my Ubuntu 10.10, I am unable to do this as I receive error of
E: Unable to locate package dkim-filter
How can I install DKIM by apt-get?
A:
Maybe because it is not there anymore in 10.10:
Package "dkim-filter"
WARNING: the "dkim-filter" package was deleted from this repository
Name: dkim-filter
Description:
DomainKeys Identified Mail (DKIM) Milter implementation
Implements a Sendmail Mail Filter (Milter) for the DomainKeys
Identified Mail (DKIM) standard. DKIM provides a way for senders to
confirm their identity when sending email by adding a cryptographic
signature to the headers of the message.
The dkim-milter implements both signing and verification.
Latest version: *DELETED*
Release: maverick (10.10)
Level: base
Repository: universe
Head package: dkim-milter
However I've found this googling a little bit. Just download the .deb file an install it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Optimising sorting time in half an hour interval arrays
I have developed a small function that will sort array of objects that have
lastAccessedTime datetime information into sortedData array that holds same informations but placed in half an hour intervals (preparedData is an array that will hold only start and end time interval information).
My question is: is this the best way to achieve expected result? As data array gets bigger the prepareData() gets slower so I need to minimise time to do this preparing.
Created a small fiddle to checkout logic https://jsfiddle.net/mtcljiljana/nvfq6h9h/
const data = [{"lastAccessedTime":"2017-11-16T07:15:41Z","path":"/login.htm"},{"lastAccessedTime":"2017-11-16T07:32:42Z","path":"/login.htm"},{"lastAccessedTime":"2017-11-16T07:32:47Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:36:02Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:36:55Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:37:28Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:39:48Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:40:47Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:42:31Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:44:06Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:46:04Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:46:43Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:50:31Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:52:54Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T07:53:53Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T08:14:00Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T08:14:44Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T08:16:20Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T08:17:32Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T08:19:21Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T08:20:13Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T08:20:59Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T08:22:59Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T08:25:14Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T08:26:17Z","path":"/concurrent_users.htm"},{"id":913,"cookieId":"WfP2r2jiq4xAKo9YziaV5winTllwY5HL","creationTime":"2017-11-16T08:47:15Z","lastAccessedTime":"2017-11-16T08:47:15Z","path":"/login.htm"},{"lastAccessedTime":"2017-11-16T08:49:47Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:12:39Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:24:25Z","path":"/login.htm"},{"lastAccessedTime":"2017-11-16T09:26:15Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:28:10Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:28:53Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:30:49Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:31:48Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:34:01Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:43:47Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:44:21Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:44:30Z","path":"/login.htm"},{"lastAccessedTime":"2017-11-16T09:44:34Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:44:48Z","path":"/"},{"lastAccessedTime":"2017-11-16T09:44:54Z","path":"/login.htm"},{"lastAccessedTime":"2017-11-16T09:44:56Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:45:09Z","path":"/"},{"lastAccessedTime":"2017-11-16T09:45:14Z","path":"/login.htm"},{"lastAccessedTime":"2017-11-16T09:45:16Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:45:30Z","path":"/"},{"lastAccessedTime":"2017-11-16T09:45:35Z","path":"/login.htm"},{"lastAccessedTime":"2017-11-16T09:45:38Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:49:31Z","path":"/settings/license.htm"},{"lastAccessedTime":"2017-11-16T09:50:47Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:50:57Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:51:32Z","path":"/settings/license.htm"},{"lastAccessedTime":"2017-11-16T09:52:06Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:58:55Z","path":"/concurrent_users.htm"},{"lastAccessedTime":"2017-11-16T09:59:12Z","path":"/connections/qc.htm"},{"lastAccessedTime":"2017-11-16T09:59:22Z","path":"/connections/rally.htm"},{"lastAccessedTime":"2017-11-16T10:07:10Z","path":"/connections/rally.htm"},{"lastAccessedTime":"2017-11-16T10:11:21Z","path":"/connections/rally.htm"},{"lastAccessedTime":"2017-11-16T10:22:48Z","path":"/connections/rally.htm"},{"lastAccessedTime":"2017-11-16T10:30:27Z","path":"/connections/rally.htm"},{"lastAccessedTime":"2017-11-16T10:34:10Z","path":"/connections/rally.htm"}];
const prepareData = (data) => {
const sortedData = [];
const startDate = [];
const endDate = [];
// transform GMT to local time
data.forEach(d => {
d.lastAccessedTime = moment(d.lastAccessedTime).format('YYYY-MM-DD HH:mm:ss');
});
// sort dates in ascending order
data.sort((a, b) => moment(a.lastAccessedTime) - moment(b.lastAccessedTime));
data.forEach(d => {
const start = moment(d.lastAccessedTime);
let put = sortedData;
let endMinutes;
let startMinutes;
if (start.minute() < 30) {
endMinutes = 30 - start.minute();
startMinutes = -start.minute();
} else {
endMinutes = 60 - start.minute();
startMinutes = 30 - start.minute();
};
const startTime = moment(start)
.add(startMinutes, 'minutes')
.add(-start.seconds(), 'seconds')
.format('YYYY-MM-DD HH:mm:ss');
const endTime = moment(start)
.add(endMinutes, 'minutes')
.add(-start.seconds(), 'seconds')
.format('YYYY-MM-DD HH:mm:ss');
sortedData.forEach(itm2 => {
itm2.forEach(itm3 => {
const date = moment(itm3.lastAccessedTime);
const min = moment(startTime);
const max = moment(endTime);
if (date < max && date > min) {
put = itm2;
}
});
});
if (put === sortedData) {
startDate.push(startTime);
endDate.push(endTime);
put.push([d]);
} else {
put.push(d);
};
});
const preparedData = sortedData.map((data, i) => {
const object = {
startDate: startDate[i],
endDate: endDate[i]
};
return object;
});
console.log(JSON.stringify(sortedData));
console.log(JSON.stringify(preparedData));
};
prepareData(data);
A:
You could sort the array by using the ISO 8601 date string and take a hash table for grouping the same time slot.
var array = [{ lastAccessedTime: "2017-11-16T07:15:41Z", path: "/login.htm" }, { lastAccessedTime: "2017-11-16T07:32:42Z", path: "/login.htm" }, { lastAccessedTime: "2017-11-16T07:32:47Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:36:02Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:36:55Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:37:28Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:39:48Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:40:47Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:42:31Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:44:06Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:46:04Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:46:43Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:50:31Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:52:54Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T07:53:53Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T08:14:00Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T08:14:44Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T08:16:20Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T08:17:32Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T08:19:21Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T08:20:13Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T08:20:59Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T08:22:59Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T08:25:14Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T08:26:17Z", path: "/concurrent_users.htm" }, { id: 913, cookieId: "WfP2r2jiq4xAKo9YziaV5winTllwY5HL", creationTime: "2017-11-16T08:47:15Z", lastAccessedTime: "2017-11-16T08:47:15Z", path: "/login.htm" }, { lastAccessedTime: "2017-11-16T08:49:47Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:12:39Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:24:25Z", path: "/login.htm" }, { lastAccessedTime: "2017-11-16T09:26:15Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:28:10Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:28:53Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:30:49Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:31:48Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:34:01Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:43:47Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:44:21Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:44:30Z", path: "/login.htm" }, { lastAccessedTime: "2017-11-16T09:44:34Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:44:48Z", path: "/" }, { lastAccessedTime: "2017-11-16T09:44:54Z", path: "/login.htm" }, { lastAccessedTime: "2017-11-16T09:44:56Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:45:09Z", path: "/" }, { lastAccessedTime: "2017-11-16T09:45:14Z", path: "/login.htm" }, { lastAccessedTime: "2017-11-16T09:45:16Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:45:30Z", path: "/" }, { lastAccessedTime: "2017-11-16T09:45:35Z", path: "/login.htm" }, { lastAccessedTime: "2017-11-16T09:45:38Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:49:31Z", path: "/settings/license.htm" }, { lastAccessedTime: "2017-11-16T09:50:47Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:50:57Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:51:32Z", path: "/settings/license.htm" }, { lastAccessedTime: "2017-11-16T09:52:06Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:58:55Z", path: "/concurrent_users.htm" }, { lastAccessedTime: "2017-11-16T09:59:12Z", path: "/connections/qc.htm" }, { lastAccessedTime: "2017-11-16T09:59:22Z", path: "/connections/rally.htm" }, { lastAccessedTime: "2017-11-16T10:07:10Z", path: "/connections/rally.htm" }, { lastAccessedTime: "2017-11-16T10:11:21Z", path: "/connections/rally.htm" }, { lastAccessedTime: "2017-11-16T10:22:48Z", path: "/connections/rally.htm" }, { lastAccessedTime: "2017-11-16T10:30:27Z", path: "/connections/rally.htm" }, { lastAccessedTime: "2017-11-16T10:34:10Z", path: "/connections/rally.htm" }],
groups = Object.create(null),
result = [];
array.sort((a, b) => a.lastAccessedTime > b.lastAccessedTime || -(a.lastAccessedTime < b.lastAccessedTime));
array.forEach(function (o) {
var slot = Math.floor(o.lastAccessedTime.slice(14, 16) / 30),
key = o.lastAccessedTime.slice(0, 14) + (slot ? '30' : '00');
if (!groups[key]) {
groups[key] = [];
result.push(groups[key]);
}
groups[key].push(o);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
| {
"pile_set_name": "StackExchange"
} |
Q:
a very strange question in mathematica
I am doing this in mma v7.0:
r[x_] := Rationalize[x, 0];
N[Nest[Sqrt, 10., 53] // r, 500]
It gave me
1.000000000000000222044604925031308084726333618164062500000000000000000
However, if I go one step further
N[Nest[Sqrt, 10., 54] // r, 500]
I got all zeros. Does anybody know an explanation, or it is a bug?
Besides, looks like this way to produce more digits from the solution Nest[Sqrt, 10., 53] is not working very well. How to obtain more significant digits for this calculation?
Many thanks.
Edit
If I did Nest[Sqrt, 10., 50], I still got a lot of significant digits.
A:
You have no significant digits other than zeros if you do this 54 times. Hence rationalizing as you do (which simply preserves bit pattern) gives what you saw.
InputForm[n53 = Nest[Sqrt, 10., 53]]
Out[180]//InputForm=
1.0000000000000002
InputForm[n54 = Nest[Sqrt, 10., 54]]
Out[181]//InputForm=
1.
Rationalize[n53, 0]
4503599627370497/4503599627370496
Rationalize[n54, 0]
Out[183]= 1
For the curious: the issue is not loss of precision in the sense of degradation with iterations computation. Indeed, iterating these square roots actually increases precision. We can see this with bignum input.
InputForm[n54 = Nest[Sqrt, 10.`20, 54]]
Out[188]//InputForm=
1.0000000000000001278191493200323453724568038240908339267044`36.25561976585499
Here is the actual problem. When we use machine numbers then after 54 iterations there are no significant digits other than zeros in the resulting machine double. That is to say, our size restriction on the numbers is the cause.
The reason is not too mysterious. Call the resulting value 1+eps. Then we have (1+eps)^(2^54) equal (to close approximation) to 10. A second order expansion then shows eps must be smaller than machine epsilon.
InputForm[epsval =
First[Select[
eps /. N[Solve[Sum[eps^j*Binomial[2^54, j], {j, 2}] == 9, eps]],
Head[#] === Real && # > 0 &]]]
Out[237]//InputForm=
1.864563472253985*^-16
$MachineEpsilon
Out[235]= 2.22045*10^-16
Daniel Lichtblau
Wolfram Research
A:
InputForm /@ NestList[Sqrt, 10., 54]
10.
3.1622776601683795
1.7782794100389228
1.333521432163324
1.1547819846894583
1.0746078283213176
1.036632928437698
1.018151721718182
1.0090350448414476
1.0045073642544626
1.002251148292913
1.00112494139988
1.0005623126022087
1.00028111678778
1.0001405485169472
1.0000702717894114
1.000035135277462
1.0000175674844227
1.0000087837036347
1.0000043918421733
1.0000021959186756
1.000001097958735
1.0000005489792168
1.0000002744895706
1.000000137244776
1.0000000686223856
1.000000034311192
1.0000000171555958
1.0000000085777978
1.0000000042888988
1.0000000021444493
1.0000000010722245
1.0000000005361123
1.0000000002680562
1.0000000001340281
1.000000000067014
1.000000000033507
1.0000000000167535
1.0000000000083769
1.0000000000041884
1.0000000000020943
1.0000000000010472
1.0000000000005236
1.0000000000002618
1.000000000000131
1.0000000000000655
1.0000000000000329
1.0000000000000164
1.0000000000000082
1.000000000000004
1.000000000000002
1.0000000000000009
1.0000000000000004
1.0000000000000002
1.
Throwing N[x, 500] on this is like trying to squeeze water from a rock.
The calculations above are done in machine precision, which is very fast. If you are willing to give up speed, you can utilize Mathematica's arbitrary precision arithmetic by specifying a non-machine precision on the input values. The "backtick" can be used to do this (as in the example below) or you can use SetPrecision or SetAccuracy. Here I will specify that the input is the number 10 up to 20 digits of precision.
NestList[Sqrt, 10`20, 54]
10.000000000000000000
3.1622776601683793320
1.77827941003892280123
.
.
.
1.00000000000000051127659728012947952
1.00000000000000025563829864006470708
1.000000000000000127819149320032345372
As you can see you do not need to use InputForm as Mathematica will automatically print arbitrary-precision numbers to as many places as it accurately can.
If you do use InputForm or FullForm you will see a backtick and then a number, which is the current precision of that number.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proguard can't find referenced class after migration to Kotlin
I'm getting which looks to be a simple ProGuard error saying that a referenced class can not be found. The error happened just after migrate the class from Java to Kotlin.
Warning: com.x.android.ui.ads.offerwall.OfferWallLoader$initIronSrc$1$1$run$1$1: can't find referenced class com.x.android.ui.ads.offerwall.OfferWallLoader$initIronSrc$1$1
Warning: com.x.android.ui.ads.offerwall.OfferWallLoader$initIronSrc$1$1$run$1$1: can't find referenced class com.x.android.ui.ads.offerwall.OfferWallLoader$initIronSrc$1$1
The problem is that I'm trying to keep it in the proguard file, but it looks like it's not having effect..
-keep class com.x.android.ui.ads.offerwall.OfferWallLoader$initIronSrc$* { *;}
I'm not sure to understand the difference when keeping a class or a member after $ in the name.
How can I fix it, what am I doing wrong?
Edit: this is the migrated code to Kotlin which is failing (the code is simplified):
private fun initIronSrc(activity: Activity) {
synchronized(initIronSrcLock) {
if (isIronSourceInitialised) {
return
}
MyStaticClass.callAsync(object : BackgroundRunnable() {
override fun run(backgroundServiceAccess: BackgroundServiceAccess) {
synchronized(initIronSrcLock) {
if (isIronSourceInitialised) {
return
}
// Init IronSource
}
}
})
}
}
Notice is failing to access initIronSrc$1$1$run$1$1
A:
After some digging and investigation it turned out like is a tracked issue from Jetbrains: https://youtrack.jetbrains.com/issue/KT-16084
Basically: Proguard can't find enclosing class of let closure inside apply closure
So, seems to be an issue with nested classes or nested calls.
In my case, I'm enclosing a static method call inside a synchronized block, so proguard is not able to resolve the call.
The solution is get the call out of that block. In this case the sync can be handled anyway, being sure about the single use of the code and the single colaborator initialisation:
private fun initIronSrc(activity: Activity) {
synchronized(initIronSrcLock) {
if (isIronSourceInitialised) {
return
}
}
MyStaticClass.callAsync(object : BackgroundRunnable() {
override fun run(backgroundServiceAccess: BackgroundServiceAccess) {
synchronized(initIronSrcLock) {
if (isIronSourceInitialised) {
return
}
// Init IronSource
}
}
})
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Insert a value into a link at the given index
Given the class Link,
class Link:
"""A linked list.
>>> s = Link(1, Link(2, Link(3, Link(4))))
>>> len(s)
4
>>> s[2]
3
>>> s
Link(1, Link(2, Link(3, Link(4))))
"""
empty = ()
def __init__(self, first, rest=empty):
self.first = first
self.rest = rest
def __getitem__(self, i):
if i == 0:
return self.first
else:
return self.rest[i-1]
def __len__(self):
return 1 + len(self.rest)
def __repr__(self):
if self.rest:
rest_str = ', ' + repr(self.rest)
else:
rest_str = ''
return 'Link({0}{1})'.format(self.first, rest_str)
How would I write this function?
def insert(link, value, index):
"""Insert a value into a Link at the given index.
>>> link = Link(1, Link(2, Link(3)))
>>> insert(link, 9001, 0)
>>> link
Link(9001, Link(1, Link(2, Link(3))))
>>> insert(link, 100, 2)
>>> link
Link(9001, Link(1, Link(100, Link(2, Link(3)))))
>>> insert(link, 4, 5)
Index out of bounds
"""
"*** YOUR CODE HERE ***"
A:
check below please:
class Link:
empty = ()
def __init__(self, first, rest=empty):
self.first = first
self.rest = rest
def __getitem__(self, i):
if i == 0:
return self.first
else:
return self.rest[i-1]
def __len__(self):
return 1 + len(self.rest)
def __repr__(self):
if self.rest:
rest_str = ', ' + repr(self.rest)
else:
rest_str = ''
return 'Link({0}{1})'.format(self.first, rest_str)
def insert(link, value, index):
if index >= link.__len__():
print "Index out of bounds"
else:
if index == 0:
tmp = link.first
link.first = value
link.rest = Link(tmp, link.rest)
else:
insert(link.rest, value, index - 1)
a = Link(1, Link(2, Link(3, Link(4))))
print a
insert(a,23,0)
print a
insert(a,12,2)
print a
insert(a,3,6)
print a
insert(a,3,5)
print a
| {
"pile_set_name": "StackExchange"
} |
Q:
Filter an array by comparing its property value with another array in angular/typescript
I have two arrays
//1st one
tasks.push({ ID: 1, Address: "---", Latitude: 312313, Longitude: 21312 });
tasks.push({ ID: 3, Address: "---", Latitude: 312313, Longitude: 21312 });
//2nd one
agentTasks.push({ID:2,AgentID: 2,TaskID:1});
Now I want to filter tasks array to get only those values which are not included in agentTasks array. Like task id 1 is included in agentTasks but 3 is not included. So I want ID 3 value only. How can I do this in angular/typescript?
A:
You could create a Set of all TaskIDs from agentTasks and then use .filter() on the tasks array to keep only those tasks which ID doesn't exist in the set of TaskIds:
const tasks = [
{ ID: 1, Address: "---", Latitude: 312313, Longitude: 21312 },
{ ID: 3, Address: "---", Latitude: 312313, Longitude: 21312}
];
const agentTasks = [{ID:2,AgentID: 2,TaskID:1}];
const taskIds = new Set(agentTasks.map(({TaskID}) => TaskID));
const res = tasks.filter(({ID}) => !taskIds.has(ID));
console.log(res);
| {
"pile_set_name": "StackExchange"
} |
Q:
Depth-first search
I have a suffix tree, each node of this tree is a struct
struct state {
int len, link;
map<char,int> next; };
state[100000] st;
I need to make dfs for each node and get all strings which I can reach, but I don't know how to make.
This is my dfs function
void getNext(int node){
for(map<char,int>::iterator it = st[node].next.begin();it != st[node].next.end();it++){
getNext(it->second);
}
}
It will be perfect if I can make something like
map<int,vector<string> >
where int is a node of my tree and vector strings which I can reach
now it works
void createSuffices(int node){//, map<int, vector<string> > &suffices) {
if (suffices[sz - 1].size() == 0 && (node == sz - 1)) {
// node is a leaf
// add a vector for this node containing just
// one element: the empty string
//suffices[node] = new vector<string>
//suffices.add(node, new vector<string>({""}));
vector<string> r;
r.push_back(string());
suffices[node] = r;
} else {
// node is not a leaf
// create the vector that will be built up
vector<string> v;
// loop over each child
for(map<char,int>::iterator it = st[node].next.begin();it != st[node].next.end();it++){
createSuffices(it->second);
vector<string> t = suffices[it->second];
for(int i = 0; i < t.size(); i ++){
v.push_back(string(1,it->first) + t[i]);
}
}
suffices[node] = v;
}
}
A:
You can pass the map<int, vector<string>> together with your depth first search. When a recursive call returns from a certain node n, you know that all suffices from that node are ready. My C++ skills are too limited, so I'll write it in pseudo-code:
void createSuffices(int node, map<int, vector<string>> suffices) {
if (st[node].next.empty()) {
// node is a leaf
// add a vector for this node containing just
// one element: the empty string
suffices.add(node, new vector<string>({""}));
} else {
// node is not a leaf
// create the vector that will be built up
vector<string> v;
// loop over each child
foreach pair<char, int> p in st[node].next {
// handle the child
createSuffices(p.second, suffices);
// prepend the character to all suffices of the child
foreach string suffix in suffices(p.second) {
v.add(concatenate(p.first, suffix));
}
}
// add the created vector to the suffix map
suffices.add(node, v);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Help proving a function is continuously differentiable
So i have a function $$f:\mathbb{R} \rightarrow \mathbb{R}$$ that's differentiable at x=0 and for $x,y \in \mathbb{R}$ let this be true:
$$f(x+2y)=2f(x)f(y)$$
So how can i prove that this function is continuously differentiable?
I thought i could use any of these theorems: Lagrange's and Rolle's, but i don't know which one and how, perhaps should i show at first it's differentable and then that derivative is continous?
A:
Let $x \in \mathbb{R}$. We want to show that $\lim_{h \to 0} \frac{f(x+h)-f(x)}{h}$ exists.
We calculate
$\frac{f(x+h)-f(x)}{h} = \frac{f(x+2h/2)-f(x + 0)}{h} = \frac{2f(x)f(h/2)-f(x)f(0)}{h}= f(x)\frac{f(h/2)-f(0)}{h}=f(x)\frac{f(\tilde{h})-f(0)}{2\tilde{h}} = \frac{f(x)}{2}\frac{f(\tilde{h})-f(0)}{\tilde{h}}$.
So that the limit $\lim_{h \to 0} \frac{f(x+h)-f(x)}{h}$ equals $\frac{f(x)}{2} f'(0)$.
As $f$ is continuous, this also implies that $f'$ is contiuous as we have
$f'(x) = \frac{f(x)}{2} \cdot f'(0).$
A:
I think this is only possible if $f(x)$ is constant for all values of $x$.
Take $y=0$ and let $x$ be arbitrary. Then $$f(x+2\cdot 0) = 2f(x)f(0)$$ which means $f(x)=2f(x)f(0)$ for every $x\in\mathbb R$. Now, if $f(x)=0$ for every $x$, we are done. Otherwise, take some $x$ such that $f(x)\neq 0$, and divide the equation by $f(x)$ to get $1=2f(0)$ or $f(0)=\frac12$.
Take $x=0$ and let $y$ be arbitrary. Then $$f(0+2y)=2f(0)f(y)$$ which means that $f(2y)=2f(0)f(y)$ for every $y\in\mathbb R$. From 1., we know that $2f(0)=1$, so we have that for every $y\in\mathbb R$, you have $f(2y)=f(y)$.
Using the rule $f(y)=f(2y)$, we can show inductively that for every $x\in\mathbb R$ and every $n\in\mathbb N$, we have $$f(x)=f\left(\frac{x}{2^n}\right)$$
This last equality, along with the fact that $f$ is continuous at $0$ (because if it is differentiable, it is also continuous), can be used to prove that $f(x)=f(0)$ for every $x\in\mathbb R$:
Let $x\in\mathbb R$ be arbitrary, and let $\epsilon > 0$. Then, there exists some $\delta$ such that $|f(y)-f(0)|<\epsilon$ if $|y|<\delta$ (continuity at $0$).
Let $n$ be such that $\overline x = \frac{|x|}{2^n}<\delta$. We then know that $|f(\overline x) - f(0)| < \epsilon$.
Then, since $f(x)=f(\overline x)$, we have $|f(x)-f(0)|<\epsilon$.
In the beginning, the choice of $\epsilon$ was arbitrary. This means that $|f(x)-f(0)|<\epsilon$ for every value of $\epsilon$, something only possible if $f(x)=f(0)$
Since $x$ is arbitrary, $f(x)=f(0)$ is true for every $x$.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS Positioning for jquery player
I have a jQuery player on my front page that seems centered and ok for me in Chrome and Safari.
But everyone else is seeing it on the left side of the screen for some reason.
I tried different variations of positions like absolute, relative and tried margins without positions..nothing seems to put it in place for all others.
the css for the div is:
#container {
width: 525px;
height: auto;
position: relative;
left: 373px;
margin: 0;
padding: 0;
z-index: 10;
its on -
www.tranceil.fm
A:
Remove the left property and adjust your margin to margin:0 auto;
#container {
width: 525px;
position: relative;
margin: 0 auto;
padding: 0;
z-index: 10;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the "Urgent wish for children" card in Caverna allow construction of all types of dwellings?
The B side of the "Wish for children" card titled "Urgent wish for children" requires you to build a "Dwelling" prior to family growth. Dwelling is written with a capital D on the card. Does that mean that you are required to build the regular dwelling priced at 4 wood, 3 stone that gives you 3 goal points or are you allowed to build any of the different types of dwellings?
A:
I don't think the capital D in "Dwelling" has any significance. In the rule book Dwelling is always capitalized. I would think that you could build any of the Dwellings. If you couldn't, I think there would be a specific explanation in the rule book.
There are 6 different types of Dwellings. Every Dwelling provides room for one or two dwarfs. (P. 15)
| {
"pile_set_name": "StackExchange"
} |
Q:
Matlab ( Input as string -> function -> plot it ) GUI
I'm trying to get a function from edit text, then write it as function so I can plot it. However, What I did isn't working :(. Please if you can help me with this.
Can you fix the problem here. I'm trying to get the function from a user as string then write change it to a function, and the output is going to be the plot of the input function.By the way I'm using gui, which have (edit box, pushbutton, and axes).
t=0:0.1:10;
maxi= get(handles.edit1, 'String');
whatever= strcat('@(x) ', maxi);
fh = str2func(whatever);
plot(t,fh(t))
Please explain what's the mistake that I did thanks, or show me what's the wright way to do it.
A:
maxi= get(handles.edit1, 'String'); gets the string data from the editbox as a cell array. So, before using into strcat, you need to convert maxi from the cell array version to a char array with char(..).
Thus, the only edit you need to make in your codes would be -
whatever= strcat('@(x) ', char(maxi));
| {
"pile_set_name": "StackExchange"
} |
Q:
is it possible to direct connect a client and server with 10GBASE CX4 copper cables?
Server has two 10GBASE-CX4 ports.
client has 10GBASE CX4 HBA.
can theybe directly connected with a CX4 cable without the need for a switch? like SAS Infiband connectors?
A:
Yes, it works perfectly fine without a switch. Give each system an IP on the same subnet.
I've run this setup with dual-port Intel CX4 10GbE cards between a VMware host server and a Sun x4540 storage unit.
| {
"pile_set_name": "StackExchange"
} |
Q:
the domain for $\dfrac{1}{x}\leq\dfrac{1}{2}$
What is the domain for $$\dfrac{1}{x}\leq\dfrac{1}{2}$$
according to the rules of taking the reciprocals, $A\leq B \Leftrightarrow \dfrac{1}{A}\geq \dfrac{1}{B}$, then the domain should be simply $$x\geq2$$
however negative numbers less than $-2$ also satisfy the original inequality. When am I missing in my understanding?
A:
The equivalence
$$A\leq B\iff \frac{1}{A}\geq\frac{1}{B}$$
only holds for numbers $A$ and $B$ that have the same sign (i.e., are both positive or both negative). Remember, when $c>0$, we have
$$A\leq B \iff c A\leq c B$$
and when $c<0$, we have
$$A\leq B\iff cA\geq cB.$$
To go from $A\leq B$ to
$$\frac{1}{A} \mathbin{\fbox{$\leq$ or $\geq$}} \frac{1}{B}$$
you'll multiply both sides by $c=\frac{1}{AB}$. This $c$ is greater than $0$ when $AB>0$, which happens when $A$ and $B$ have the same sign, and it is less than $0$ when $AB<0$, which happens when $A$ and $B$ have opposite signs.
Thus,
$$\frac{1}{x}\leq\frac{1}{2}\iff\begin{cases} x\geq 2 &\text{ if }x\text{ has the same sign as 2},\\
x\leq 2 &\text{ if }x\text{ has the opposite sign as 2}.
\end{cases}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Assistance with jquery .children
Im creating some buttons rollovers and for "graceful degradation" sake, and for the sake of not writing code for EVERY image rollover etc, im trying to write better more efficient code. That said, what im wanting to do is that with a few lines of code, that my rollovers become a bit smarter about what they display on the screen.
one of the things im trying to achieve is that on rollover, that the text to appear in the center of the images div(via css absolute pos.) is the same text that is in the alt property/element of the image.
This is the reg div with thumbnail image:
<div class="imgW"><img src="img src here"/></div>
now for the rollover, i add it via jquery :
$('.imgW').prepend('<div class="portSecRollOver">lopan</div>');
So on page render, it should be outputted like this:
<div class="imgW">
<div class="portSecRollOver">lopan</div>
<img src="img src here"/>
</div>
at page load, portSecRollOver is hidden via css.(display:none);
on rollover, portSecRollOver is shown via jquery:
$('.imgW').mouseover(function(){
$(this).children('.portSecRollOver').css("display","block");
});
etc...
now on this same rollover function block above, what i wanted to do is that on rollover,
the text to appear inside of portSecRollOver div is the value of that divs image alt tag.
How can i achieve this?
ive tried many approaches and they all end up as nothing. when i do a console.log on it to test it, i always get an "undefined" which leads me to assume im not targeting the correct dom object.
Any ideas? Ive tried many ways but, this is to give you an idea as to what ive tried...something like
$(this).children('.portSecRollOver').html($(this).children('a img').attr('alt'));
Thanks in advanced.
A:
You can achieve it very easily by coding this way, or if you want something more interesting you can make it like this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Merging small polygons with the biggest adjacent ones
I want to merge the RED polygons with the YELLOW polygons.
But i want to merge the one red polygon with the adjancent polygon with yellow one. This polygons are in one Feature class but classified in atributes.
I am trying many methods but it doesnt work or i dont know how to do.
A:
Use the Eliminate tool to accomplish this. It does exactly this: "Eliminates polygons by merging them with neighboring polygons that have the largest area or the longest shared border. "
| {
"pile_set_name": "StackExchange"
} |
Q:
Extract only text content from a web page
I need to extract all the text content from a web page. I have used 'document.body.textContent'.
But I get the javascript content as well.How do I ensure that I get only the readable text content?
function myFunction() {
var str = document.body.textContent
alert(str);
}
<html>
<title>Test Page for Text extraction</title>
<head>I hope this works</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>
<p>Test on this content to change the 5th word to a link
<p>
<button onclick="myFunction()">Try it</button>
</body>
</hmtl>
A:
Just remove the tags you dont want read before doing body.textContent.
function myFunction() {
var bodyScripts = document.querySelectorAll("body script");
for(var i=0; i<bodyScripts.length; i++){
bodyScripts[i].remove();
}
var str = document.body.textContent;
document.body.innerHTML = '<pre>'+str+'</pre>';
}
<html>
<title>Test Page for Text extraction</title>
<head>I hope this works</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>
<p>Test on this content to change the 5th word to a link
<p>
<button onclick="myFunction()">Try it</button>
</body>
</hmtl>
| {
"pile_set_name": "StackExchange"
} |
Q:
Solr stats facet left out some values
I want to facet over products in Solr and want to retrieve statistics about the categories.
My schema has got a field called categories, a multiValued field.
the problem is, that the statistics left out a bunch of categories. Am I wrong with following query? Obviously, but how do I make it right? Pleeeease help, I'm despairing.
q=*:*&rows=0&stats=true&stats.field=product_id&rows=0&stats.facet=categories
A:
The query looks fine, the problem is that it's faceting on a multiValued field:
http://wiki.apache.org/solr/StatsComponent
Computing statistics using stats.facet over a multi-valued field does
not work properly.
https://issues.apache.org/jira/browse/SOLR-1782
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
AWS SQS - Append data to message on retries
I have a SQS queue which is accessed by a lambda. I'm leveraging the retry capability provided by SQS using redrive policy and forwarding the message to a dead letter queue on max retries. I would like to append additional data to the message on each retry , but would like SQS to continue managing the retries. Is this possible?
A:
This is not possible.
The ReceiveMessages action provides an attribute called ApproximateReceiveCount, which is a counter that automatically increments with each receive... but otherwise, it isn't possible to change anything about a message in the queue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Element by Element Matrix Multiplication in Scala
I have an input mllib matrix like,
matrix1: org.apache.spark.mllib.linalg.Matrix =
1.0 0.0 2.0 1.0
0.0 3.0 1.0 1.0
2.0 1.0 0.0 0.0
The dimensions of matrix1 is 3*4.
I need to do an element by element matrix multiplication with another matrix so that dimensions of two matrices will be the same in all cases. Let us assume I have another matrix named matrix2 like
matrix2: org.apache.spark.mllib.linalg.Matrix =
3.0 0.0 2.0 1.0
1.0 9.0 5.0 1.0
2.0 5.0 0.0 0.0
with dimensions 3*4
My resultant matrix should be,
result: org.apache.spark.mllib.linalg.Matrix =
3.0 0.0 4.0 1.0
0.0 27.0 5.0 1.0
4.0 5.0 0.0 0.0
How can I achieve this in Scala ? (Note: inbuilt function multiply of spark mllib works as per exact matrix multiplication.)
A:
Below is one way of doing it. Here we iterate both the matrix column wise and find their element multiplication. This solution assumes that both the matrix are of same dimensions.
First let's create test matrix as given in question.
//creating example matrix as per the question
val m1: Matrix = new DenseMatrix(3, 4, Array(1.0, 0.0, 2.0, 0.0, 3.0, 1.0, 2.0, 1.0, 0.0, 1.0, 1.0, 0.0))
val m2: Matrix = new DenseMatrix(3, 4, Array(3.0, 1.0, 2.0, 0.0, 9.0, 5.0, 2.0, 5.0, 0.0, 1.0, 1.0, 0.0))
Now let's define a function which takes two Matrix and returns their element multiplication.
//define a function to calculate element wise multiplication
def elemWiseMultiply(m1: Matrix, m2: Matrix): Matrix = {
val arr = new ArrayBuffer[Array[Double]]()
val m1Itr = m1.colIter //operate on each columns
val m2Itr = m2.colIter
while (m1Itr.hasNext)
//zip both the columns and then multiple element by element
arr += m1Itr.next.toArray.zip(m2Itr.next.toArray).map { case (a, b) => a * b }
//return the resultant matrix
new DenseMatrix(m1.numRows, m1.numCols, arr.flatten.toArray)
}
You can then call this function for your element multiplication.
//call the function to m1 and m2
elemWiseMultiply(m1, m2)
//output
//3.0 0.0 4.0 1.0
//0.0 27.0 5.0 1.0
//4.0 5.0 0.0 0.0
| {
"pile_set_name": "StackExchange"
} |
Q:
making citrix run with squid
Scenario: Our employees are on on-site assignment with company X. Company X has placed them behind a squid proxy for any internet-related access.
There are a couple of applications that our employees need to access via citrix hosted in our organization. If they access it using a data-card (so that they are directly on the internet), they can connect and work perfectly.
Problem: However, when they try to access our citrix
site, they end up with
'Could not find Citrix Presentation Server' or 'The Citrix SSL Relay Name could not be resolved'
We managed to fix the second problem by opening up the 1494 port on squid and changing the .ica file by updating the following:
ProxyType=Auto
ProxyUseFQDN=On
The Citrix support chaps said that unless the client machine cannot directly resolve and connect (in other words, has a 'route') to your citrix server, it ain't gonna work.
Has anyone out there got this working? If you done it by adding routes to the client machine, could you please tell me how to do it too? :)
Thanks.
A:
If your Citrix server is directly on the Internet then you not be able connect to your Citrix server. As the company has blocked all direct connections. You have 2 options
1) Have the company setup a Socks Proxy, as this will allow you to resolve the external addresses.
You will need to add the following lines to your ICA file
ICASOCKSProtocolVersion=0
ICASOCKSProxyHost= "IP address of the proxy server"
ICASOCKSProxyPortNumber=1080
2) Setup a Citrix Web Interface at your site which will allow you to connect from any proxy server.
3) Allow routes/ports through the X Company firewall to your Citrix Servers
| {
"pile_set_name": "StackExchange"
} |
Q:
oracle database AUDIT doesn't show SQL text and bind values
Based on this tutorial I have configured auditing on a database with these options:
AUDIT ALL BY db BY ACCESS;
AUDIT SELECT TABLE, UPDATE TABLE, INSERT TABLE, DELETE TABLE BY db BY ACCESS;
AUDIT EXECUTE PROCEDURE BY db BY ACCESS;
I prepare query from java and run a SELECT query. DBA_AUDIT_TRAIL table shows my SELECT query but SQL_TEXT and SQL_BIND fields are empty. How can I see them? Should I enable any other option? I'm using Oracle 11.2 Express Edition. Is this because It is express edition?
A:
The column SQLTEXT and SQLBIND are populated only when AUDIT_TRAIL option is set to db, extended. Here is an example:
SQL> alter system set audit_trail=db,extended scope=spfile;
System altered
Restart the instance.
SQL> audit select on your_table;
Audit succeeded
SQL> select sqltext from sys.aud$ where obj$name = 'YOUR_TABLE';
SQLTEXT
--------------------------------------------------------------------------------
null
SQL> select count(*) from your_table;
COUNT(*)
----------
3
SQL> select sqltext from sys.aud$ where obj$name = 'YOUR_TABLE';
SQLTEXT
--------------------------------------------------------------------------------
select count(*) from your_table
SQL>
| {
"pile_set_name": "StackExchange"
} |
Q:
type conversion error, c#
I am using Advanced Matrix Library in C#. NET@
http://www.codeproject.com/KB/recipes/AdvancedMatrixLibrary.aspx?msg=4042613#xx4042613xx.
library css file is like
using System;
namespace MatrixLibrary
{
public class Matrix
{
private double[,] in_Mat;
public Matrix(int noRows, int noCols)
{
this.in_Mat = new double[noRows, noCols];
}
public Matrix(double [,] Mat)
{
this.in_Mat = (double[,])Mat.Clone();
}
public static double[,] Identity(int n)
{
double[,] temp = new double[n,n];
for (int i=0; i<n;i++) temp[i,i] = 1;
return temp;
}
public static double[,] ScalarDivide(double Value, double[,] Mat)
{
int i, j, Rows, Cols;
double[,] sol;
try {Find_R_C(Mat, out Rows, out Cols);}
catch{throw new MatrixNullException();}
sol = new double[Rows+1, Cols+1];
for (i = 0; i<=Rows;i++)
for (j = 0; j<=Cols;j++)
sol[i, j] = Mat[i, j] / Value;
return sol;
}
}}
I am trying to get identity matrix and getting error of type conversion. Could some one please guide me.
Matrix id_mat = MatrixLibrary.Matrix.Identity(6);
Can't implicity convert typedouble[,] to Matrix.
But
Matrix B = new Matrix(4, 4);
Random rnd = new Random();
for (int i = 0; i < B.NoRows; i++)
for (int j = 0; j < B.NoCols; j++)
B[i, j] = 2 * rnd.NextDouble();
Matrix E = Matrix.ScalarDivide(2, B);
It works and I can Have a matrix. Please guide me?
regards,
A:
Read the error message.
You have a method that returns double[,] and you are trying to store the reference in a variable for Matrix. There is no implicit conversion from a multidimensional array of doubles to a Matrix.
To use that method, you would write
double[,] id_max = MatrixLibrary.Maxtrix.Identify(6);
If you actually need to store it as a Matrix, you need to define the appropriate conversion to do so.
| {
"pile_set_name": "StackExchange"
} |
Q:
MongoDB _id length getting as 25
I am trying to remove a document from MongoDB using nodeJS.
My code flow is as below:
1.The user can delete a particular student.
2.So I have pulled all the student documents fron the DB and stored in students object.
3. User can filter the search with the textbox provided and can select a particular student and can delete that.
Please find the below UI:
The HTML page as below:
<h2 align="center">Delete Student</h2>
<div ng-controller="deleteStudentController">
<form ng-submit="deleteStudent()">
Student Name:<input type="text" letters-only ng-model="searchName"/><br>
<div ng-repeat="student in students | filter:searchName" ng-show="searchName.length">
<input type="radio" ng-model="$parent.studentRadio" name="studentRadio" value="{{student._id}}"/>{{student | formatter}}
</div>
<input type="submit" value="Delete Student"/>
{{output}}
</form>
</div>
The angularJS controller associated with the UI is as below:
mainApp.controller("deleteStudentController", function($scope,$http) {
var resData = {};
$scope.student = {};
var urlGet = "/students/all";
$http.get(urlGet)
.then(function(response) {
$scope.students = angular.fromJson(response.data);
});
$scope.deleteStudent = function(){
var urlDelete = "/students/remove:"+$scope.studentRadio;
$http.delete(urlDelete)
.success(function(response, status, headers, config){
$scope.output = "Student successfully deleted.";
})
.error(function(response, status, headers, config){
$scope.output = "Error in processing. Please try again.";
});
}
});
Which inturn calls the node controller:
router.delete("/remove:studId", function(req,res){
Students.remove(req.params.studId, function(err) {
if (err) {
throw err;
}
else {
var respOut = "Student deleted";
res.send(respOut);
}
});
});
Inside the controller, there is an object of student model, in which the DB communication is made. I have used mongodb.ObjectID.createFromHexString() method to create objectID from the _id value that I got from the DB
The student model code to delete a document:
exports.remove = function(studentId, cb) {
var collection = db.get().collection('students');
console.log("_id"+studentId);
console.log("Length---->"+studentId.length);
collection.remove({_id: mongodb.ObjectID.createFromHexString(studentId)}, function(err) {
if (err) {
throw err;
}
else {
cb(err);
console.log("Record deleted.");
}
});
}
But its giving the error as "Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters". So I tried to log the _id value that I got from the DB student document and its length. Surprisingly I am getting the length as '25'.
Please find the below console out that I am getting:
_id:576aba09090560f80bd2caaa
Length---->25
Any idea about this issue? Please help.....
A:
Your Angular code is setting the endpoint like this:
"/students/remove:"+$scope.studentRadio
I assume that you want the : to be there, so the URL will look something like this:
/students/remove:576c1d4781aaa4f16a68af24
Your Express route looks like this:
router.delete("/remove:studId", ...)
: is a special character in Express routes (it declares a named parameter called studId). This means that your route will take everything after /remove to be the value of studId, including the colon that's in the URL. So req.params.studId is :576c1d4781aaa4f16a68af24, which has a length of 25 characters.
If you want to use this sort of URL scheme, you need to make the colon to be part of the match by escaping it (so it loses its special meaning):
router.delete("/remove\\::studId", ...)
| {
"pile_set_name": "StackExchange"
} |
Q:
Circular reference problem Singleton
I'm trying to creating a Singleton class like below where MyRepository lies in separate DAL project. It's causing me a circular reference problem because GetMySingleTon() method returns MySingleTon class and needs its access. Same way I need MyRepository access in constructor of MySingleTon class.
public class MySingleTon
{
static MySingleTon()
{
if (Instance == null)
{
MyRepository rep = new MyRepository();
Instance = rep.GetMySingleTon();
}
}
public static MySingleTon Instance { get; private set; }
public string prop1 { get; set; }
public string prop2 { get; set; }
}
UPDATE: I was doing it very wrongly.
I think didn't needed any singleton. Now I've created a class with static properties in a third project and I'm setting it once and accessing it everywhere. And it has solved my problem for now.
Thanks everyone for your answers.
A:
The repository should not return a singleton object, a repository is used to access data and not returning singleton objects. Your repository could by itself be a singleton, but I don't recommend it, and I don't recommend using a singleton for the class using the repository either. In the code you have it seems like the repository needs to be aware of the "business layer" which is all messed up, the relationships should go only one way. I would re-write it as:
public class MySingleTon
{
private MySingleTon()
{
// You constructor logic, maybe create a reference
// to your repository if you need it
}
private static MySingleTon _instance;
public static MySingleTon Instance {
get
{
if(_instance == null)
_instance = new MySingleTon();
return _instance;
}
}
public string prop1 { get; set; }
public string prop2 { get; set; }
}
I don't recommend my solution, but it should solve you problem. What I do recommend is looking into dependency injection and inversion of control since your design seems sort of wrong. Have a look at NInject.
EDIT: One other thing, why does your singleton have several properties that are public? A singleton shouldn't expose properties it should only expose functions, and should mainly be used when you have a utility class like Math or a true singleton like a logger.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.