id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32,634,320 | How to structure Redux components/containers | <p>I’m using redux and I’m not sure about how to organize my components, I think the best is to keep them in folders with the name of the main component as the name of the folder and all inner components inside: </p>
<pre>
components
Common/ things like links, header titles, etc
Form/ buttons, inputs, etc
Player/ all small components forming the player
index.js this one is the top layout component
playBtn.js
artistName.js
songName.js
Episode/ another component
</pre>
<p>Then, in the containers folder, I’ve one container per page, that are the only ones I'm actually connecting to Redux:</p>
<pre>
containers/
HomePageApp.js
EpisodePageApp.js
...
</pre>
<p>and then the actions are one per each top component, instead of one per page, so in the page container that I connect to Redux I pass all the actions of the components used in that page. For example:</p>
<pre>
actions/
Player.js
Episode.js
...
</pre>
<p>Am I doing this right? I haven't found much information about it googling, and the ones I've found I think they are limited to small projects.</p>
<p>Thanks!</p> | 32,921,576 | 6 | 1 | null | 2015-09-17 15:29:10.247 UTC | 22 | 2019-07-26 16:04:44.543 UTC | 2017-03-07 23:18:13.563 UTC | null | 2,619,939 | null | 4,537,278 | null | 1 | 45 | javascript|reactjs|redux|reactjs-flux | 23,152 | <p>In the official examples we have several top-level directories:</p>
<ul>
<li><code>components</code> for <a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0">“dumb”</a> React components unaware of Redux;</li>
<li><code>containers</code> for “smart” React components connected to Redux;</li>
<li><code>actions</code> for all action creators, where file name corresponds to part of the app;</li>
<li><code>reducers</code> for all reducers, where file name corresponds to state key;</li>
<li><code>store</code> for store initialization.</li>
</ul>
<p>This works well for small and mid-level size apps.</p>
<p>When you want to go more modular and group related functionality together, <a href="https://github.com/erikras/ducks-modular-redux">Ducks</a> or <a href="http://marmelab.com/blog/2015/12/17/react-directory-structure.html">other ways of grouping functionality by domain</a> is a nice alternative way of structuring your Redux modules.</p>
<p>Ultimately choose whatever structure works best for you. There is no way Redux authors can know what’s convenient for you better than you do.</p> |
9,315,258 | Aggregating sub totals and grand totals with data.table | <p>I've got a <code>data.table</code> in R:</p>
<pre><code>library(data.table)
set.seed(1)
DT = data.table(
group=sample(letters[1:2],100,replace=TRUE),
year=sample(2010:2012,100,replace=TRUE),
v=runif(100))
</code></pre>
<p>Aggregating this data into a summary table by group and year is simple and elegant:</p>
<pre><code>table <- DT[,mean(v),by='group, year']
</code></pre>
<p>However, aggregating this data into a summary table, including subtotals and grand totals, is a little more difficult, and a lot less elegant:</p>
<pre><code>library(plyr)
yearTot <- DT[,list(mean(v),year='Total'),by='group']
groupTot <- DT[,list(mean(v),group='Total'),by='year']
Tot <- DT[,list(mean(v), year='Total', group='Total')]
table <- rbind.fill(table,yearTot,groupTot,Tot)
table$group[table$group==1] <- 'Total'
table$year[table$year==1] <- 'Total'
</code></pre>
<p>This yields:</p>
<pre><code>table[order(table$group, table$year), ]
</code></pre>
<p>Is there a simple way to specify subtotals and grand totals with data.table, such as the <code>margins=TRUE</code> command for plyr? I would prefer to use data.table over plyr on my dataset, as it is a very large dataset that I already have in the data.table format.</p> | 45,759,118 | 5 | 0 | null | 2012-02-16 16:41:31.233 UTC | 9 | 2017-08-18 15:04:32.87 UTC | 2012-02-16 20:08:46.957 UTC | null | 168,868 | null | 345,660 | null | 1 | 14 | r|aggregate|plyr|data.table | 7,458 | <p>In recent devel data.table you can use new feature called "grouping sets" to produce sub totals:</p>
<pre><code>library(data.table)
set.seed(1)
DT = data.table(
group=sample(letters[1:2],100,replace=TRUE),
year=sample(2010:2012,100,replace=TRUE),
v=runif(100))
cube(DT, mean(v), by=c("group","year"))
# group year V1
# 1: a 2011 0.4176346
# 2: b 2010 0.5231845
# 3: b 2012 0.4306871
# 4: b 2011 0.4997119
# 5: a 2012 0.4227796
# 6: a 2010 0.2926945
# 7: NA 2011 0.4463616
# 8: NA 2010 0.4278093
# 9: NA 2012 0.4271160
#10: a NA 0.3901875
#11: b NA 0.4835788
#12: NA NA 0.4350153
cube(DT, mean(v), by=c("group","year"), id=TRUE)
# grouping group year V1
# 1: 0 a 2011 0.4176346
# 2: 0 b 2010 0.5231845
# 3: 0 b 2012 0.4306871
# 4: 0 b 2011 0.4997119
# 5: 0 a 2012 0.4227796
# 6: 0 a 2010 0.2926945
# 7: 2 NA 2011 0.4463616
# 8: 2 NA 2010 0.4278093
# 9: 2 NA 2012 0.4271160
#10: 1 a NA 0.3901875
#11: 1 b NA 0.4835788
#12: 3 NA NA 0.4350153
</code></pre> |
9,119,236 | C++ class forward declaration | <p>When I try to compile this code, I get:</p>
<pre><code>52 C:\Dev-Cpp\Projektyyy\strategy\Tiles.h invalid use of undefined type `struct tile_tree_apple'
46 C:\Dev-Cpp\Projektyyy\strategy\Tiles.h forward declaration of `struct tile_tree_apple'
</code></pre>
<p>some part of my code:</p>
<pre><code>class tile_tree_apple;
class tile_tree : public tile
{
public:
tile onDestroy() {return *new tile_grass;};
tile tick() {if (rand()%20==0) return *new tile_tree_apple;};
void onCreate() {health=rand()%5+4; type=TILET_TREE;};
};
class tile_tree_apple : public tile
{
public:
tile onDestroy() {return *new tile_grass;};
tile tick() {if (rand()%20==0) return *new tile_tree;};
void onCreate() {health=rand()%5+4; type=TILET_TREE_APPLE;};
tile onUse() {return *new tile_tree;};
};
</code></pre>
<p>I dont really know what to do, I searched for the solution but I couldn't find anything simmilar to my problem... Actually, I have more classes with parent "tile" and It was ok before...</p>
<p>EDIT:</p>
<p>I decided to change all returned types to pointers to avoid memory leaks, but now I got:</p>
<pre><code>27 C:\Dev-Cpp\Projektyyy\strategy\Tiles.h ISO C++ forbids declaration of `tile' with no type
27 C:\Dev-Cpp\Projektyyy\strategy\Tiles.h expected `;' before "tick"
</code></pre>
<p>Its only in base class, everything else is ok... Every function in tile class which return *tile has this error...</p>
<p>Some code:</p>
<pre><code>class tile
{
public:
double health;
tile_type type;
*tile takeDamage(int ammount) {return this;};
*tile onDestroy() {return this;};
*tile onUse() {return this;};
*tile tick() {return this};
virtual void onCreate() {};
};
</code></pre> | 9,119,275 | 8 | 0 | null | 2012-02-02 20:10:21.213 UTC | 13 | 2020-12-14 11:44:17.043 UTC | 2020-12-14 11:44:17.043 UTC | null | 11,336,762 | null | 1,023,753 | null | 1 | 24 | c++|class|forward-declaration | 172,215 | <p>In order for <code>new T</code> to compile, <code>T</code> must be a complete type. In your case, when you say <code>new tile_tree_apple</code> inside the definition of <code>tile_tree::tick</code>, <code>tile_tree_apple</code> is incomplete (it has been forward declared, but its definition is later in your file). Try moving the inline definitions of your functions to a separate source file, or at least move them after the class definitions.</p>
<p>Something like:</p>
<pre><code>class A
{
void f1();
void f2();
};
class B
{
void f3();
void f4();
};
inline void A::f1() {...}
inline void A::f2() {...}
inline void B::f3() {...}
inline void B::f4() {...}
</code></pre>
<p>When you write your code this way, all references to A and B in these methods are guaranteed to refer to complete types, since there are no more forward references!</p> |
30,146,562 | Error: Qualifiers dropped in binding reference of type x to initializer of type y | <p>why does the following throw this error:</p>
<blockquote>
<p>IntelliSense: qualifiers dropped in binding reference of type
"string &" to initializer of type "const string"</p>
</blockquote>
<p><strong>.h</strong></p>
<pre><code>class A
{
public:
wstring& GetTitle() const;
private:
wstring title;
};
</code></pre>
<p><strong>.cpp</strong></p>
<pre><code>wstring& GetTitle() const
{
return this->title;
}
</code></pre>
<p><strong>If i remove the const word, it stops complaining</strong>, and yet i have never made any changes to the variable?</p> | 30,146,581 | 2 | 4 | null | 2015-05-10 00:50:51.173 UTC | 8 | 2022-08-16 05:43:12.9 UTC | null | null | null | null | 360,822 | null | 1 | 19 | c++ | 31,455 | <p>By returning a non-const reference to a member of your class, you are giving the caller access to the object as if it's non const. But <code>GetTitle</code>, being a const function, does not have the right to grant that access.</p>
<p>For example:</p>
<pre><code>A a;
string& b = a.GetTitle(); // Allows control over original variable
</code></pre> |
10,673,628 | Implementing OnClickListener for dynamically created buttons in Android | <p>I dynamically created buttons through code rather than from XML.
<Br>
The code is as below : <br></p>
<pre><code> dynamicview = (LinearLayout)findViewById(R.id.llayout);
LinearLayout.LayoutParams lprams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
for(int i=0;i<nob;i++){
Button btn = new Button(this);
btn.setId(i+1);
btn.setText("Button"+(i+1));
btn.setLayoutParams(lprams);
dynamicview.addView(btn);
}
</code></pre>
<p><br>
I am not finding a way in which I can implement OnClickListener to each of these buttons so that I can perform action based on the reference I get.
<br>
Can anyone help me in sorting out this issue. ?
<br>
Thanks in Advance,</p> | 10,673,676 | 6 | 1 | null | 2012-05-20 13:01:30.567 UTC | 9 | 2017-06-15 12:29:03.79 UTC | null | null | null | null | 1,276,092 | null | 1 | 12 | android|android-layout|android-widget | 36,007 | <p>See the code below:</p>
<pre><code>for(int i=0;i<nob;i++) {
Button btn = new Button(this);
btn.setId(i+1);
btn.setText("Button"+(i+1));
btn.setLayoutParams(lprams);
final int index = i;
btn.setOnClickListener(new OnClickListener() {
void onClick(View v) {
Log.i("TAG", "The index is" + index);
}
});
dynamicview.addView(btn);
}
</code></pre>
<p>My example is pretty simple, but demonstrates how you can get the button index into the <code>OnClickListeber</code>. You can access any <code>final</code> field in the declared anonymous classes (e..g the <code>OnClickListener</code>).</p> |
10,335,285 | C Language: what does the .mm extension stand for? | <p>A project with some Objective-C has a few C classes with the implementation files having a <strong>.mm</strong> extension.</p>
<pre><code>file.h
file.mm
</code></pre>
<p>What does the <strong>.mm</strong> mean? Shouldn't it just be <strong>.m</strong>?</p> | 10,335,364 | 3 | 1 | null | 2012-04-26 14:14:27.317 UTC | 7 | 2020-02-06 18:40:35.01 UTC | 2016-03-15 18:56:39.91 UTC | null | 1,038,379 | null | 257,022 | null | 1 | 71 | objective-c|objective-c++ | 52,641 | <p>The extension <code>.mm</code> is the extension for the <code>C++</code> compilation unit expected by the Objective-C compiler, while the <code>.m</code> extension is the extension for the <code>C</code> compilation unit expected by the Objective-C compiler.</p>
<p>That's assuming you don't use a compiler flag to override the file extension, <a href="http://sseyod.blogspot.com/2009/02/objective-c.html" rel="noreferrer">as this gentleman has done</a>.</p> |
22,543,644 | How to Drag and Drop from One QListWidget to Another | <p>There are two QListWIdgets sitting in a same dialog window. The DragDrop functionality has been enabled for both. If I drag and drop a file to any of two ListWidges the program recognizes it and prints out the list of the files dropped. But aside from drag and dropping files I would like to be able to drag and drop the List widget Items from one to another. If I drag the ListItems the drag and drop event is triggered. But it is not able to recognize what Items were dropped onto the widget. The example code is below. The goal is to drag-drop the list items from one ListWidget to another.</p>
<pre><code>import sys, os
from PyQt4 import QtCore, QtGui
class ThumbListWidget(QtGui.QListWidget):
def __init__(self, type, parent=None):
super(ThumbListWidget, self).__init__(parent)
self.setAcceptDrops(True)
self.setIconSize(QtCore.QSize(124, 124))
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
event.ignore()
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
self.listItems={}
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidgetA = ThumbListWidget(self)
for i in range(12):
QtGui.QListWidgetItem( 'Item '+str(i), self.listWidgetA )
myBoxLayout.addWidget(self.listWidgetA)
self.listWidgetB = ThumbListWidget(self)
myBoxLayout.addWidget(self.listWidgetB)
self.listWidgetA.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.listWidgetA.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.connect(self.listWidgetA, QtCore.SIGNAL("dropped"), self.items_dropped)
self.listWidgetA.currentItemChanged.connect(self.item_clicked)
self.listWidgetB.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.listWidgetB.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.connect(self.listWidgetB, QtCore.SIGNAL("dropped"), self.items_dropped)
self.listWidgetB.currentItemChanged.connect(self.item_clicked)
def items_dropped(self, arg):
print arg
def item_clicked(self, arg):
print arg
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
</code></pre>
<h1>EDIT # 2</h1>
<p>Here is the code that does it all. But there is no way to track down what object was dropped. The droppedOnA() and droppedOnB() methods are still not working.</p>
<hr>
<pre><code>from PyQt4 import QtGui, QtCore
import sys, os
class MyClassItem(QtGui.QListWidgetItem):
def __init__(self, parent=None):
super(QtGui.QListWidgetItem, self).__init__(parent)
class ThumbListWidget(QtGui.QListWidget):
def __init__(self, type, parent=None):
super(ThumbListWidget, self).__init__(parent)
self.setIconSize(QtCore.QSize(124, 124))
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
super(ThumbListWidget, self).dragEnterEvent(event)
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
super(ThumbListWidget, self).dragMoveEvent(event)
def dropEvent(self, event):
print 'dropEvent', event
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
event.setDropAction(QtCore.Qt.MoveAction)
super(ThumbListWidget, self).dropEvent(event)
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
self.listItems={}
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidgetA = ThumbListWidget(self)
self.listWidgetB = ThumbListWidget(self)
for i in range(7):
listItemAInstance=MyClassItem()
listItemAInstance.setText('A'+'%04d'%i)
listItemAInstance.setBackgroundColor(QtCore.Qt.darkGray)
if i%2: listItemAInstance.setBackgroundColor(QtCore.Qt.gray)
self.listWidgetA.addItem(listItemAInstance)
listItemBInstance=MyClassItem()
listItemBInstance.setText('B'+'%04d'%i)
if i%2: listItemBInstance.setBackgroundColor(QtCore.Qt.lightGray)
self.listWidgetB.addItem(listItemBInstance)
myBoxLayout.addWidget(self.listWidgetA)
myBoxLayout.addWidget(self.listWidgetB)
self.connect(self.listWidgetA, QtCore.SIGNAL("dropped"), self.droppedOnA)
self.connect(self.listWidgetB, QtCore.SIGNAL("dropped"), self.droppedOnB)
def droppedOnA(self, arg):
print '\n\t droppedOnA', arg.text
def droppedOnB(self, arg):
print '\n\t droppedOnB', arg.text
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
</code></pre>
<h1>EDIT # 3</h1>
<p>Here is another attempt this time using MIME to pass dropped Item's objects to ListWidget. Unfortunately cPickle refuses to accept binary objects throwing a </p>
<blockquote>
<p>TypeError: the sip.wrapper type cannot be instantiated or sub-classed</p>
</blockquote>
<p>To get around it I convert each object names to string and use it with self.listItems={} dictionary as its key to retrieve list Item's binary objects. Which seems to be working well. But at the end when I almost though it as all done, a ListWidget with no visible errors doesn't add the dropped list Item to itself... It's strange. </p>
<blockquote>
<p>self.listWidgetB.addItem(droppedItemInstance)</p>
</blockquote>
<p>.</p>
<hr>
<pre><code>from PyQt4 import QtGui, QtCore
import sys, os
import cPickle
class MyClassItem(QtGui.QListWidgetItem):
def __init__(self, parent=None):
super(QtGui.QListWidgetItem, self).__init__(parent)
class ThumbListWidget(QtGui.QListWidget):
def __init__(self, type, parent=None):
super(ThumbListWidget, self).__init__(parent)
self.setIconSize(QtCore.QSize(124, 124))
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
super(ThumbListWidget, self).dragEnterEvent(event)
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
super(ThumbListWidget, self).dragMoveEvent(event)
def dropEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
else:
event.setDropAction(QtCore.Qt.MoveAction)
super(ThumbListWidget, self).dropEvent(event)
def mimeTypes(self):
return ['bstream', 'text/xml']
def mimeData(self, droppedItems):
mimedata = QtCore.QMimeData()
droppedItemsAsStrings=[]
for each in droppedItems:
droppedItemsAsStrings.append( str(each) )
bstream = cPickle.dumps(droppedItemsAsStrings)
mimedata.setData('bstream', bstream)
return mimedata
def dropMimeData(self, action, mimedata, row):
if action == QtCore.Qt.IgnoreAction: return True
dropped=cPickle.loads(str(mimedata.data('bstream')))
self.emit(QtCore.SIGNAL("dropped"), dropped)
return True
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
self.listItems={}
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidgetA = ThumbListWidget(self)
self.listWidgetB = ThumbListWidget(self)
for i in range(7):
listItemAInstance=MyClassItem()
listItemAInstance.setText('A'+'%04d'%i)
listItemAInstance.setBackgroundColor(QtCore.Qt.darkGray)
if i%2: listItemAInstance.setBackgroundColor(QtCore.Qt.gray)
self.listWidgetA.addItem(listItemAInstance)
listItemBInstance=MyClassItem()
listItemBInstance.setText('B'+'%04d'%i)
if i%2: listItemBInstance.setBackgroundColor(QtCore.Qt.lightGray)
self.listWidgetB.addItem(listItemBInstance)
self.listItems[str(listItemAInstance)]=listItemAInstance
self.listItems[str(listItemBInstance)]=listItemBInstance
myBoxLayout.addWidget(self.listWidgetA)
myBoxLayout.addWidget(self.listWidgetB)
self.connect(self.listWidgetA, QtCore.SIGNAL("dropped"), self.droppedOnA)
self.connect(self.listWidgetB, QtCore.SIGNAL("dropped"), self.droppedOnB)
def droppedOnA(self, droppedItemsAsStrings):
print '\n\t droppedOnA()'
for each in droppedItemsAsStrings:
if each in self.listItems.keys():
droppedItemInstance = self.listItems[each]
print 'adding', droppedItemInstance.text()
self.listWidgetA.addItem(droppedItemInstance)
def droppedOnB(self, droppedItemsAsStrings):
print '\n\t droppedOnB()'
for each in droppedItemsAsStrings:
if each in self.listItems.keys():
droppedItemInstance = self.listItems[each]
self.listWidgetB.addItem(droppedItemInstance)
print 'adding', droppedItemInstance.text()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
</code></pre> | 22,546,488 | 3 | 0 | null | 2014-03-20 19:50:49.033 UTC | 8 | 2019-02-21 21:29:42.92 UTC | 2014-03-21 03:03:15.103 UTC | null | 1,107,049 | null | 1,107,049 | null | 1 | 9 | python|pyqt4|qlistwidget | 11,769 | <p>Here is a revised code. It is working like a charm! Bravo!</p>
<pre><code>from PyQt4 import QtGui, QtCore
import sys, os
class ThumbListWidget(QtGui.QListWidget):
def __init__(self, type, parent=None):
super(ThumbListWidget, self).__init__(parent)
self.setIconSize(QtCore.QSize(124, 124))
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
super(ThumbListWidget, self).dragEnterEvent(event)
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
super(ThumbListWidget, self).dragMoveEvent(event)
def dropEvent(self, event):
print 'dropEvent', event
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
event.setDropAction(QtCore.Qt.MoveAction)
super(ThumbListWidget, self).dropEvent(event)
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
self.listItems={}
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidgetA = ThumbListWidget(self)
for i in range(12):
QtGui.QListWidgetItem( 'Item '+str(i), self.listWidgetA )
myBoxLayout.addWidget(self.listWidgetA)
self.listWidgetB = ThumbListWidget(self)
myBoxLayout.addWidget(self.listWidgetB)
self.connect(self.listWidgetA, QtCore.SIGNAL("dropped"), self.items_dropped)
self.listWidgetA.currentItemChanged.connect(self.item_clicked)
self.connect(self.listWidgetB, QtCore.SIGNAL("dropped"), self.items_dropped)
self.listWidgetB.currentItemChanged.connect(self.item_clicked)
def items_dropped(self, arg):
print 'items_dropped', arg
def item_clicked(self, arg):
print arg
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
</code></pre> |
7,693,040 | How to translate model in Ruby class/module namespace? | <p>I have a model Products::Car. How can I translate its attributes?</p>
<p>I have already tried this:</p>
<pre><code>activerecord:
models:
products:
car: "Автомобиль"
attributes:
products:
car:
owner: "Владелец"
</code></pre>
<p>And this:</p>
<pre><code>activerecord:
models:
products_car: "Автомобиль"
attributes:
products_car:
owner: "Владелец"
</code></pre>
<p>But if I try to use Products::Car.model_name.human it still says "Car". My other translations work well, and the language is set to :ru.</p> | 7,697,615 | 2 | 2 | null | 2011-10-07 21:29:23.213 UTC | 11 | 2018-06-05 17:38:36.47 UTC | 2018-05-18 21:50:42 UTC | null | 283,398 | null | 285,710 | null | 1 | 49 | ruby-on-rails|model|localization|namespaces|internationalization | 9,520 | <p>I have checked 'model_name.human' source code and found 'i18n_key' method. I have tried this:</p>
<pre><code>irb(main):006:0> Products::Car.model_name.i18n_key
=> :"products/car"
</code></pre>
<p>Then I changed my yml file to this:</p>
<pre><code>activerecord:
models:
products/car: "Автомобиль"
attributes:
products/car:
owner: "Владелец"
</code></pre>
<p>and it works!</p>
<p>EDIT:</p>
<p>For further reference: the <code>i18n_key</code> is set in the initializer of <code>ActiveModel::Name</code> <a href="https://github.com/rails/rails/blob/375a4143cf5caeb6159b338be824903edfd62836/activemodel/lib/active_model/naming.rb#L147" rel="noreferrer">https://github.com/rails/rails/blob/375a4143cf5caeb6159b338be824903edfd62836/activemodel/lib/active_model/naming.rb#L147</a></p>
<p>and it is simply based on</p>
<pre><code>MyClass.name.underscore
</code></pre> |
22,986,347 | Go vs. return button in iOS keyboard for HTML input forms | <p>Managing the iOS keyboard for HTML <code><input></code> forms (used in <code>UIWebView</code>) is well known, i.e. <code><input type="tel"></input></code> for telephone numbers.</p>
<p><a href="https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html" rel="noreferrer">https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html</a></p>
<p>But I was wondering about the keyboard's blue 'Go' button.
Sometimes the keyboard has a blue <strong>'Go' button</strong>, sometimes the keyboard has a gray <strong>return button</strong>.
Is there any opportunity to control this behavior programmatically?</p> | 39,485,162 | 3 | 1 | null | 2014-04-10 11:09:42.003 UTC | 7 | 2021-04-25 13:56:35.95 UTC | 2016-09-11 16:11:59.133 UTC | null | 2,581,872 | null | 2,270,880 | null | 1 | 43 | ios|forms|input|uiwebview|keyboard | 18,616 | <p><strong>Update 2020/2021</strong></p>
<p>As <a href="https://stackoverflow.com/a/67132913/2270880">Cameron Cobb</a> pointed out,
Safari Mobile supports the new HTML attribute <code>enterkeyhint</code> since version 13.7 ~ Sept. 2020 (<a href="https://caniuse.com/mdn-html_global_attributes_enterkeyhint" rel="noreferrer">https://caniuse.com/mdn-html_global_attributes_enterkeyhint</a>).</p>
<p>The following values are possible (<a href="https://mixable.blog/ux-improvements-enterkeyhint-to-define-action-label-for-the-keyboard-of-mobile-devices/" rel="noreferrer">https://mixable.blog/ux-improvements-enterkeyhint-to-define-action-label-for-the-keyboard-of-mobile-devices/</a>):</p>
<pre><code><input enterkeyhint="enter">
<input enterkeyhint="done">
<input enterkeyhint="go">
<input enterkeyhint="next">
<input enterkeyhint="previous">
<input enterkeyhint="search">
<input enterkeyhint="send">
</code></pre>
<hr />
<p><strong>Original Answer</strong></p>
<p>Aha...</p>
<p>The 'Go' button is only shown, if the <code><input></code> tag is inside a <code><form></code> tag (and the form tag has an <code>action</code> attribute).
So, if you access your form elements afterwards with i.e. JavaScript, you can omit <code><form></code> tags.</p>
<p><strong>'Go' button</strong>:</p>
<pre><code><form action="..." method="...">
<input type="text"></input>
</form>
</code></pre>
<p><img src="https://i.stack.imgur.com/NKKg0.png" alt="iOS 7.1 screenshot of keyboard" /></p>
<p><strong>'return' button</strong>:</p>
<pre><code><input type="text"></input>
</code></pre>
<p><img src="https://i.stack.imgur.com/q4u5J.png" alt="iOS 7.1 screenshot of keyboard" /></p> |
17,865,620 | Multiple inheritance workarounds | <p>I'm trying to discover a pattern for combining multiple interfaces into one abstract class. Presently I can combine multiple interfaces via <code>implements</code>, but an interface cannot declare a constructor. When I must introduce a constructor I'm forced to use an abstract class. When I use a abstract class I must re-declare the entire composite interface! Surely I'm missing something?</p>
<pre><code>interface ILayerInfo {
a: string;
}
interface ILayerStatic {
b(): string;
}
class Layer implements ILayerInfo, ILayerStatic {
constructor(info: ILayerInfo);
a: string;
b(): string;
}
</code></pre>
<p><strong>ANSWER</strong>: Use <code>new</code>:</p>
<pre><code>interface Layer extends ILayerInfo, ILayerStatic {
new(info: ILayerInfo);
}
// usage: new Layer({ a: "" });
</code></pre> | 17,866,346 | 2 | 1 | null | 2013-07-25 18:09:46.573 UTC | 8 | 2022-02-05 00:48:24.093 UTC | 2019-03-26 16:07:10.153 UTC | null | 3,345,644 | null | 485,183 | null | 1 | 32 | abstract-class|typescript|multiple-inheritance | 37,048 | <p>Declaring a constructor on the same interface as the instance members doesn't really make much sense -- if you're going to pass in a type dynamically to use in a constructor, it's the static side of the class that would be restricted. What you would want to do is probably something like this:</p>
<pre><code>interface Colorable {
colorize(c: string): void;
}
interface Countable {
count: number;
}
interface ColorCountable extends Colorable, Countable {
}
interface ColorCountableCreator {
new(info: {color: string; count: number}): ColorCountable;
}
class ColorCounted implements ColorCountable {
count: number;
colorize(s: string) { }
constructor(info: {color: string; count: number}) {
// ...
}
}
function makeThings(c: ColorCountableCreator) {
var results: ColorCountable[];
for(var i = 0; i < 10; i++) {
results.push(new c({color: 'blue', count: i}));
}
return results;
}
var items = makeThings(ColorCounted);
console.log(items[0].count);
</code></pre>
<p>See also <a href="https://stackoverflow.com/questions/13407036/how-does-typescript-interfaces-with-construct-signatures-work">How does typescript interfaces with construct signatures work?</a></p> |
2,138,487 | How does the Google Docs PDF viewer work? | <p>I am curious to know how the Google Docs PDF viewer works? It's not a flash like scribd.com; it looks like pure HTML. Any idea how do they did it? </p>
<p><a href="http://docs.google.com/viewer?url=http://www.idfcmf.com/downloads/monthly_fund/2009/IDFC-Premier-Equityfund-jan10.pdf" rel="noreferrer">Sample link to view the PDF</a></p> | 2,138,496 | 3 | 3 | null | 2010-01-26 09:30:57.663 UTC | 17 | 2013-12-29 07:34:48.213 UTC | 2013-12-29 07:34:48.213 UTC | null | 881,229 | null | 79,442 | null | 1 | 19 | pdf|google-docs | 37,232 | <p>Google is simply serving up an an image (right click -> save as), with an overlay to highlight text.</p>
<p>You should check out <a href="https://stackoverflow.com/questions/297743/any-way-to-build-google-docs-like-viewer-for-pdf-files">this SO question</a> where others go into more detail.</p>
<p>You should also look through the source of your PDF link, it would appear Google are passing the PDF link through to be converted into an image.</p>
<p>Example:</p>
<pre><code><script type="text/javascript">
var gviewElement = document.getElementById('gview');
var config = {
'api': false,
'chrome': true,
'csi': true,
'ddUrl': "http://www.idfcmf.com/downloads/monthly_fund/2009/IDFC-Premier-Equityfund-jan10.pdf",
'element': gviewElement,
'embedded': false,
'initialQuery': "",
'oivUrl': "http://docs.google.com/viewer?url\x3dhttp%3A%2F%2Fwww.idfcmf.com%2Fdownloads%2Fmonthly_fund%2F2009%2FIDFC-Premier-Equityfund-jan10.pdf",
'sdm': 200,
'userAuthenticated': true
};
var gviewApp = _createGView(config);
gviewApp.setProgress(50);
window.jstiming.load.name = 'view';
window.jstiming.load.tick('_dt');
</script>
</code></pre>
<p><strong>Edit</strong></p>
<p>Also if you were to view the PDF viewer in Firefox with Firebug, you will notice that when you 'highlight' text it's really only enabling a load of divs, I'm guessing Google scans the document using OCR, detects where the text is and provides a matrix of coordinates on which to base the div placement on, when you click and drag it introgates the mouse pointer location to determine which divs to display.</p> |
1,927,450 | Use variable with TOP in select statement in SQL Server without making it dynamic | <pre><code>declare @top int
set @top = 5
select top @top * from tablename
</code></pre>
<p>Is it possible?</p>
<p>Or any idea for such a logic (i don't want to use dynamic query)?</p> | 1,927,460 | 3 | 0 | null | 2009-12-18 10:35:18.26 UTC | 21 | 2009-12-18 10:56:04.587 UTC | 2009-12-18 10:36:54.513 UTC | null | 4,574 | null | 115,783 | null | 1 | 237 | sql|sql-server|sql-server-2005|tsql | 108,899 | <p>Yes, in SQL Server 2005 it's possible to use a variable in the <code>top</code> clause.</p>
<pre><code>select top (@top) * from tablename
</code></pre> |
189,422 | How do I create and query linked database servers in SQL Server? | <p>I need to do a join across two different database servers (IPs 10.0.0.50 and 10.0.0.51). What's the best way?</p> | 189,431 | 4 | 0 | null | 2008-10-09 22:21:29.07 UTC | 8 | 2015-08-07 17:20:07.853 UTC | null | null | null | kurious | 109 | null | 1 | 18 | sql|sql-server|database | 99,584 | <p>You need to use sp_linkedserver to create a linked server.</p>
<pre><code>sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ]
[ , [ @provider= ] 'provider_name' ]
[ , [ @datasrc= ] 'data_source' ]
[ , [ @location= ] 'location' ]
[ , [ @provstr= ] 'provider_string' ]
[ , [ @catalog= ] 'catalog' ]
</code></pre>
<p>More information available on <a href="http://msdn.microsoft.com/en-us/library/ms190479.aspx" rel="noreferrer">MSDN</a>.</p> |
803,918 | Is it possible to add info or help text to an iPhone settings bundle? | <p>Several of the Apple-provided apps have informational/help text in their settings. For example, the Keyboard settings screen includes, under the <em>“.” shortcut</em> toggle, the help text "Double tapping the space bar will...".</p>
<p>I know I can do this in my app by adding a group footer, but is it possible to do this in the settings app by adding a field to the plist file in my Settings.bundle?</p> | 3,191,813 | 4 | 0 | null | 2009-04-29 19:34:58.463 UTC | 9 | 2017-06-29 15:45:10.313 UTC | 2016-03-13 16:10:21.21 UTC | null | 411,022 | null | 8,964 | null | 1 | 27 | iphone|settings|plist|settings.bundle | 8,021 | <p>According to recently changed Apple document, a FooterText key is available in PSGroupSpecifier dictionary, which is only available in iOS 4.0 or later.</p>
<p>Reference:
<a href="https://developer.apple.com/library/content/documentation/PreferenceSettings/Conceptual/SettingsApplicationSchemaReference/Articles/PSGroupSpecifier.html" rel="nofollow noreferrer">https://developer.apple.com/library/content/documentation/PreferenceSettings/Conceptual/SettingsApplicationSchemaReference/Articles/PSGroupSpecifier.html</a></p> |
719,194 | How can you make a vote-up-down button like in Stackoverflow? | <p><strong>Problems</strong></p>
<ol>
<li>how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease</li>
<li>how to save the action af an user to an variable NumberOfVotesOfQuestionID</li>
</ol>
<p>I am not sure whether I should use database or not for the variable. However, I know that there is an easier way too to save the number of votes.</p>
<p><strong>How can you solve those problems?</strong></p>
<p>[edit]</p>
<p>The server-side programming language is Python.</p> | 719,475 | 4 | 0 | null | 2009-04-05 16:07:30.077 UTC | 28 | 2009-10-17 15:14:14.457 UTC | 2009-10-17 15:14:14.457 UTC | null | 109,941 | null | 54,964 | null | 1 | 33 | javascript|python|html|ajax | 7,545 | <p>This is a dirty/untested theoretical implementation using jQuery/Django.</p>
<p>We're going to assume the voting up and down is for questions/answers like on this site, but that can obviously be adjusted to your real life use case.</p>
<h3>The template</h3>
<pre><code><div id="answer_595" class="answer">
<img src="vote_up.png" class="vote up">
<div class="score">0</div>
<img src="vote_down.png" class="vote down">
Blah blah blah this is my answer.
</div>
<div id="answer_596" class="answer">
<img src="vote_up.png" class="vote up">
<div class="score">0</div>
<img src="vote_down.png" class="vote down">
Blah blah blah this is my other answer.
</div>
</code></pre>
<h3>Javascript</h3>
<pre><code>$(function() {
$('div.answer img.vote').click(function() {
var id = $(this).parents('div.answer').attr('id').split('_')[1];
var vote_type = $(this).hasClass('up') ? 'up' : 'down';
if($(this).hasClass('selected')) {
$.post('/vote/', {id: id, type: vote_type}, function(json) {
if(json.success == 'success') {
$('#answer_' + id)
.find('img.' + vote_type);
.attr('src', 'vote_' + vote_type + '_selected.png')
.addClass('selected');
$('div.score', '#answer_' + id).html(json.score);
}
});
} else {
$.post('/remove_vote/', {id: id, type: vote_type}, function(json) {
if(json.success == 'success') {
$('#answer_' + id)
.find('img.' + vote_type);
.attr('src', 'vote_' + vote_type + '.png')
.removeClass('selected');
$('div.score', '#answer_' + id).html(json.score);
}
});
}
});
});
</code></pre>
<h3>Django views</h3>
<pre><code>def vote(request):
if request.method == 'POST':
try:
answer = Answer.objects.get(pk=request.POST['id'])
except Answer.DoesNotExist:
return HttpResponse("{'success': 'false'}")
try:
vote = Vote.objects.get(answer=answer, user=request.user)
except Vote.DoesNotExist:
pass
else:
return HttpResponse("{'success': 'false'}")
if request.POST['type'] == 'up':
answer.score = answer.score + 1
else:
answer.score = answer.score - 1
answer.save()
Vote.objects.create(answer=answer,
user=request.user,
type=request.POST['type'])
return HttpResponse("{'success':'true', 'score':" + answer.score + "}")
else:
raise Http404('What are you doing here?')
def remove_vote(request):
if request.method == 'POST':
try:
answer = Answer.objects.get(pk=request.POST['id'])
except Answer.DoesNotExist:
return HttpResponse("{'success': 'false'}")
try:
vote = Vote.objects.get(answer=answer, user=request.user)
except Vote.DoesNotExist:
return HttpResponse("{'success': 'false'}")
else:
vote.delete()
if request.POST['type'] == 'up':
answer.score = answer.score - 1
else:
answer.score = answer.score + 1
answer.save()
return HttpResponse("{'success':'true', 'score':" + answer.score + "}")
else:
raise Http404('What are you doing here?')
</code></pre>
<p>Yikes. When I started answering this question I didn't mean to write this much but I got carried away a little bit. You're still missing an initial request to get all the votes when the page is first loaded and such, but I'll leave that as an exercise to the reader. Anyhow, if you <em>are</em> in fact using Django and are interested in a more tested/real implemention of the Stackoverflow voting, I suggest you check out the <a href="http://cnprog.googlecode.com/svn/trunk/" rel="noreferrer">source code</a> for cnprog.com, a Chinese clone of Stackoverflow written in Python/Django. They released their code and it is pretty decent.</p> |
579,515 | What is the best web server for Ruby on Rails application? | <p>What is the best web server for ruby on rails application? Why?</p> | 579,535 | 4 | 0 | null | 2009-02-23 21:46:57.707 UTC | 17 | 2011-09-03 02:17:18.173 UTC | 2011-09-03 02:17:18.173 UTC | null | 36,446 | ecleel | 36,446 | null | 1 | 50 | ruby-on-rails|webserver | 51,454 | <p><a href="http://www.modrails.com/" rel="noreferrer">Passenger</a> running on Apache. Easy to set up, low memory usage, and well supported.</p> |
440,585 | Building Boost BCP | <p>I was trying to build <a href="http://en.wikipedia.org/wiki/Boost_C%2B%2B_Libraries" rel="noreferrer">Boost C++ Libraries</a> for last two hours and stopped without any result. Since I am new to C++, I am unable to get the build right. How can I build it correctly using Visual Studio 2008?</p>
<p>I need to use the BCP tool to extract a subset of library. So I need to build BCP first, right? How to do this? When I tried to build it, I got the following error</p>
<blockquote>
<p><em>fatal error LNK1104: cannot open file 'libboost_filesystem-vc90-mt-gd-1_37.lib'.</em> </p>
</blockquote>
<p>Where can I get the above given library file?</p> | 440,653 | 4 | 0 | null | 2009-01-13 20:09:22.407 UTC | 17 | 2022-09-19 12:37:46.787 UTC | 2010-02-27 20:09:24.833 UTC | null | 63,550 | Appu | 50,419 | null | 1 | 53 | c++|boost | 18,720 | <p>First, you need to have the proper PATH, INCLUDE and LIB environment variables in your command shell. For this, call the file "<code>vcvarsall.bat</code>" (or similar) with parameter:</p>
<pre><code>vcvarsall.bat x86
</code></pre>
<p>Next you have to build bjam (you can also download it from the Boost page, but it's almost as quick). Go to the <code>tools\jam\src</code> folder in Boost and type:</p>
<pre><code>build.bat
</code></pre>
<p>It should produce a subfolder <code>bin.ntx86</code> that contains bjam.exe. For convenience, copy it to the Boost main folder. Next, you can build bcp. Go into the <code>tools\bcp</code> folder and type:</p>
<pre><code>..\..\bjam.exe --toolset=msvc
</code></pre>
<p>Back in the Boost main folder you can then build any library you wish:</p>
<pre><code>bjam toolset=msvc –-with-{library}
</code></pre>
<p>where <code>{library}</code> is one of the libraries to build. All buildable libraries can be shown with:</p>
<pre><code>bjam –-show-libraries
</code></pre>
<p>There are many more bjam build parameters. Some parameters with keywords you can specify are:</p>
<pre><code>variant=debug|release
link=shared|static
threading=multi|single
</code></pre>
<p>An example would be:</p>
<pre><code>bjam toolset=msvc –-with-filesystem threading=multi variant=debug stage
</code></pre>
<p>For more infos, visit the <a href="http://www.boost.org/doc/libs" rel="noreferrer">Boost documentation pages</a>.</p>
<p>Edit: Updated link to point to most recent Boost documentation</p>
<p>Edit: Corrected options --with-{library} and –-show-libraries</p> |
48,893,528 | keras vs. tensorflow.python.keras - which one to use? | <p>Which one is the recommended (or more future-proof) way to use Keras?</p>
<p>What are the advantages/disadvantages of each?</p>
<p>I guess there are more differences than simply saving one <code>pip install</code> step and writing <code>tensorflow.python.keras</code> instead of <code>keras</code>.</p> | 49,073,626 | 2 | 0 | null | 2018-02-20 20:16:53.637 UTC | 8 | 2019-10-29 11:43:23.513 UTC | null | null | null | null | 1,866,775 | null | 1 | 34 | python|tensorflow|pip|deep-learning|keras | 7,195 | <p><a href="https://www.tensorflow.org/api_docs/python/tf/keras" rel="noreferrer"><code>tensorflow.python.keras</code></a> is just a bundle of keras with a single backend inside <code>tensorflow</code> package. This allows you to start using keras by installing just <code>pip install tensorflow</code>.</p>
<p><a href="https://keras.io/" rel="noreferrer"><code>keras</code></a> package contains full keras library with three supported backends: tensorflow, theano and CNTK. If you even wish to switch between backends, you should choose <code>keras</code> package. This approach is also more flexible because it allows to install keras updates independently from tensorflow (which may not be easy to update, for example, because the next version may require a different version of CUDA driver) or vice versa. For this reason, I prefer to install <code>keras</code> as another package.</p>
<p>In terms of API, there is no difference right now, but keras will probably be integrated more tightly into tensorflow in the future. So there is a chance there will be tensorflow-only features in keras, but even in this case it's not a blocker to use <code>keras</code> package.</p>
<p><strong><em>UPDATE</em></strong></p>
<p>As of Keras 2.3.0 release, Francois Chollet announced that users should switch towards <strong>tf.keras</strong> instead of plain Keras. Therefore, the change to <strong>tf.keras</strong> instead of <strong>keras</strong> should be made by all users.</p> |
41,038,970 | How to determine previous page URL in Angular? | <p>Suppose I am currently on the page which has the URL <code>/user/:id</code> . Now from this page I navigate to next page <code>:id/posts</code>.</p>
<p>Now Is there a way, so that i can check what is the previous URL, i.e. <code>/user/:id</code>.</p>
<p>Below are my routes</p>
<pre><code>export const routes: Routes = [
{
path: 'user/:id', component: UserProfileComponent
},
{
path: ':id/posts', component: UserPostsComponet
}
];
</code></pre> | 41,039,092 | 22 | 0 | null | 2016-12-08 11:58:21.343 UTC | 41 | 2022-05-04 11:43:54.907 UTC | 2017-12-27 12:03:04.78 UTC | null | 2,131,286 | null | 5,247,871 | null | 1 | 150 | angular|angular2-routing | 265,490 | <p>You can subscribe to route changes and store the current event so you can use it when the next happens</p>
<pre class="lang-ts prettyprint-override"><code>previousUrl: string;
constructor(router: Router) {
router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
console.log('prev:', event.url);
this.previousUrl = event.url;
});
}
</code></pre>
<p>See also <a href="https://stackoverflow.com/questions/33520043/how-to-detect-route-change-in-angular-2/38080657#38080657">How to detect a route change in Angular?</a></p> |
42,150,499 | How do I delete DB (sqlite3) in Django 1.9 to start from scratch? | <p>I made a spelling error in my model and now one of my columns is misspelled. I'd like to drop all tables in the database, fix the error in the model.py, and recreate the database with the correct spelling in model.</p>
<p>I've tried to use the suggestions in the <a href="http://eli.thegreenplace.net/2014/02/20/clearing-the-database-with-django-commands" rel="noreferrer">this article</a> but the table still exists after I follow the commands outlined there.</p>
<p>Anyone have a quick way to do this?</p> | 42,150,639 | 4 | 0 | null | 2017-02-10 02:28:31.163 UTC | 35 | 2020-11-28 11:24:22.43 UTC | null | null | null | null | 7,516,957 | null | 1 | 40 | django|sqlite | 62,466 | <ol>
<li><strong>Delete the sqlite database file</strong> (often <code>db.sqlite3</code>) in your django project folder (or wherever you placed it)</li>
<li><strong>Delete</strong> everything except <code>__init__.py</code> file from <strong><code>migration</code></strong> folder in all django apps (eg: <code>rm */migrations/0*.py</code>)</li>
<li>Make changes in your models (<code>models.py</code>).</li>
<li>Run the command <strong><code>python manage.py makemigrations</code></strong> or <code>python3 manage.py makemigrations</code></li>
<li>Then run the command <strong><code>python manage.py migrate</code></strong>.</li>
</ol>
<p>That's all.</p>
<p>If your changes to the models are not detected by <code>makemigrations</code> command, please <a href="https://stackoverflow.com/questions/24912173/django-1-7-makemigrations-not-detecting-changes/46362750#46362750">check this answer</a></p> |
33,261,359 | pandas replace zeros with previous non zero value | <p>I have the following dataframe:</p>
<pre><code>index = range(14)
data = [1, 0, 0, 2, 0, 4, 6, 8, 0, 0, 0, 0, 2, 1]
df = pd.DataFrame(data=data, index=index, columns = ['A'])
</code></pre>
<p>How can I fill the zeros with the previous non-zero value using pandas? Is there a fillna that is not just for "NaN"?. </p>
<p>The output should look like:</p>
<pre><code>[1, 1, 1, 2, 2, 4, 6, 8, 8, 8, 8, 8, 2, 1]
</code></pre>
<p>(This question was asked before here <a href="https://stackoverflow.com/questions/30488961/fill-zero-values-of-1d-numpy-array-with-last-non-zero-values">Fill zero values of 1d numpy array with last non-zero values</a> but he was asking exclusively for a numpy solution)</p> | 33,261,465 | 2 | 0 | null | 2015-10-21 13:59:09.187 UTC | 7 | 2020-03-24 12:43:36.973 UTC | 2017-05-23 12:17:33.35 UTC | null | -1 | null | 5,235,265 | null | 1 | 36 | python|pandas | 48,230 | <p>You can use <code>replace</code> with <code>method='ffill'</code></p>
<pre><code>In [87]: df['A'].replace(to_replace=0, method='ffill')
Out[87]:
0 1
1 1
2 1
3 2
4 2
5 4
6 6
7 8
8 8
9 8
10 8
11 8
12 2
13 1
Name: A, dtype: int64
</code></pre>
<p>To get numpy array, work on <code>values</code></p>
<pre><code>In [88]: df['A'].replace(to_replace=0, method='ffill').values
Out[88]: array([1, 1, 1, 2, 2, 4, 6, 8, 8, 8, 8, 8, 2, 1], dtype=int64)
</code></pre> |
1,678,032 | Exporting / Archiving changed files only in Git | <p>Is there a simple way to export / archive only the changed files from a given commit or series of commits in git? I can't seem to find clear instructions to do this (and I'm new to Linux/Git).</p>
<p>I am using msysgit, and for the most part I'm fine with deploying entire repositories but in many cases it is much more efficient to deploy small fixes a few files at a time. </p>
<p>Pushing/pulling/installing git on the remote servers isn't really an option as my level of access varies between projects and clients.</p>
<p>Is there a straight-forward way to (rough guess):</p>
<pre><code>pipe 'diff --names-only' to 'git-archive'?
</code></pre> | 1,678,056 | 1 | 0 | null | 2009-11-05 02:54:12.09 UTC | 15 | 2014-08-17 05:03:27.047 UTC | 2014-08-17 05:03:27.047 UTC | null | 2,702,368 | null | 203,121 | null | 1 | 10 | git|export|archive|msysgit | 8,267 | <p>I don't think there's any need to involve git-archive. Using <code>--name-only</code>, you could tar up the files:</p>
<pre><code>tar czf new-files.tar.gz `git diff --name-only [diff options]`
</code></pre>
<p>Since you're new to Linux, this might need some explanation:</p>
<p>The backticks in the command line cause the shell to first execute the command within the backticks, then substitute the output of that command into the command line of <code>tar</code>. So the <code>git diff</code> is run first, which generates a list of filenames, one on each line. The newlines are collapsed to spaces and the whole list of files is placed on the <code>tar</code> command line. Then <code>tar</code> is run to create the given archive. Note that this can generate quite long command lines, so if you have a very large number of changed files you may need a different technique.</p> |
19,840,688 | Bypassing http response header Cache-Control: how to set cache expiration? | <p>All http responses from a server come with the headers that inform our app not to cache the responses:</p>
<pre><code>Cache-Control: no-cache
Pragma: no-cache
Expires: 0
</code></pre>
<p>So, if you are making NSUrlRequests with default cache policy "NSURLRequestUseProtocolCachePolicy" then the app will always load data from the server. However, we need to cache the responses and the obvious solution would be to set these headers to some time for example (at backend side), set to 10 seconds. But I'm interested in a solution how to bypass this policy and cache every request for 10 seconds. </p>
<p>For that you need to setup shared cache. That might be done in AppDelegate didFinishLaunchingWithOptions:</p>
<pre><code>NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
diskCapacity:20 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
</code></pre>
<p>Then, we need to embed our code to force to cache a response. If you use an instance of AFHttpClient then it can be done by overriding the method below and manually storing the cache into the shared cache: </p>
<pre><code>- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse {
NSMutableDictionary *mutableUserInfo = [[cachedResponse userInfo] mutableCopy];
NSMutableData *mutableData = [[cachedResponse data] mutableCopy];
NSURLCacheStoragePolicy storagePolicy = NSURLCacheStorageAllowedInMemoryOnly;
// ...
return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
data:mutableData
userInfo:mutableUserInfo
storagePolicy:storagePolicy];
}
</code></pre>
<p>And the last thing is to set cachePolicy for the requests. In our case we want to set the same cache policy to all requests. So again, if you use an instance of AFHttpClient then it can be done by overriding the method below:</p>
<pre><code>- (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters {
NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters];
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
return request;
}
</code></pre>
<p>So far so good. "NSURLRequestReturnCacheDataElseLoad" makes to perform request first time and load response from cache all other times. The problem is, it's unclear how to set cache expiration time, for example 10 seconds. </p> | 19,847,811 | 3 | 0 | null | 2013-11-07 16:03:14.457 UTC | 9 | 2015-09-22 21:28:48.033 UTC | 2013-11-07 16:30:48.47 UTC | null | 597,292 | null | 597,292 | null | 1 | 10 | ios|objective-c|afnetworking | 8,704 | <p>You can implement a custom NSURLCache that only returns cached responses that has not expired. </p>
<p>Example:</p>
<pre><code>#import "CustomURLCache.h"
NSString * const EXPIRES_KEY = @"cache date";
int const CACHE_EXPIRES = -10;
@implementation CustomURLCache
// static method for activating this custom cache
+(void)activate {
CustomURLCache *urlCache = [[CustomURLCache alloc] initWithMemoryCapacity:(2*1024*1024) diskCapacity:(2*1024*1024) diskPath:nil] ;
[NSURLCache setSharedURLCache:urlCache];
}
-(NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
NSCachedURLResponse * cachedResponse = [super cachedResponseForRequest:request];
if (cachedResponse) {
NSDate* cacheDate = [[cachedResponse userInfo] objectForKey:EXPIRES_KEY];
if ([cacheDate timeIntervalSinceNow] < CACHE_EXPIRES) {
[self removeCachedResponseForRequest:request];
cachedResponse = nil;
}
}
return cachedResponse;
}
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request {
NSMutableDictionary *userInfo = cachedResponse.userInfo ? [cachedResponse.userInfo mutableCopy] : [NSMutableDictionary dictionary];
[userInfo setObject:[NSDate date] forKey:EXPIRES_KEY];
NSCachedURLResponse *newCachedResponse = [[NSCachedURLResponse alloc] initWithResponse:cachedResponse.response data:cachedResponse.data userInfo:userInfo storagePolicy:cachedResponse.storagePolicy];
[super storeCachedResponse:newCachedResponse forRequest:request];
}
@end
</code></pre>
<p>If this does not give you enough control then I would implement a custom NSURLProtocol with a <em>startLoading</em> method as below and use it in conjunction with the custom cache.</p>
<pre><code>- (void)startLoading
{
NSMutableURLRequest *newRequest = [self.request mutableCopy];
[NSURLProtocol setProperty:@YES forKey:@"CacheSet" inRequest:newRequest];
NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:self.request];
if (cachedResponse) {
[self connection:nil didReceiveResponse:[cachedResponse response]];
[self connection:nil didReceiveData:[cachedResponse data]];
[self connectionDidFinishLoading:nil];
} else {
_connection = [NSURLConnection connectionWithRequest:newRequest delegate:self];
}
}
</code></pre>
<p>Some links:</p>
<ul>
<li><a href="http://nshipster.com/nsurlcache/">Useful info on NSURLCache</a></li>
<li><a href="http://eng.42go.com/customizing-uiwebview-requests-with-nsurlprotocol/">Creating a custom NSURLProtocol</a></li>
</ul> |
20,282,672 | Record, save and/or convert video in mp4 format? | <p>I have the following problem - I am trying to create an app that records video, then save it to the camera roll and after that I am uploading that video to the web. The problem is that the only supported format is "mp4", but my videos are "mov". </p>
<p>So my question is how to save video from camera in "mp4" format, or save it in "mov" and then convert it to "mp4".</p>
<p>Here's my code:</p>
<ul>
<li><p>this is how I open the camera:</p>
<pre><code>picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.delegate = self;
picker.showsCameraControls = YES;
picker.allowsEditing = YES;
picker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
[self presentViewController:picker animated:YES completion:nil];
</code></pre></li>
<li><p>this is how I save the video:</p>
<pre><code>NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
if (CFStringCompare ((__bridge_retained CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo)
{
NSString *moviePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
videoURL = info[UIImagePickerControllerMediaURL];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath))
{
UISaveVideoAtPathToSavedPhotosAlbum(moviePath, self, nil, nil);
}
}
[nextScreenButton setTitle:@"ПРОДЪЛЖИ" forState:UIControlStateNormal];
[self dismissViewControllerAnimated:YES completion:nil];
</code></pre></li>
</ul>
<p>Thanks in advance!</p> | 20,283,319 | 4 | 0 | null | 2013-11-29 09:45:07.577 UTC | 27 | 2020-05-13 05:11:29.84 UTC | null | null | null | null | 2,165,644 | null | 1 | 17 | ios|iphone|xcode|video|mp4 | 29,473 | <p>You are doing right thing.. Now you need to convert this mov file to mp4 as below.</p>
<pre><code>NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
NSString *videoPath1 = @"";
if (CFStringCompare ((__bridge_retained CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo)
{
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath))
{
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *moviePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
videoPath1 =[NSString stringWithFormat:@"%@/xyz.mov",docDir];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
[videoData writeToFile:videoPath1 atomically:NO];
// UISaveVideoAtPathToSavedPhotosAlbum(moviePath, self, nil, nil);
}
}
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:videoPath1] options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality])
{
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetPassthrough];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
videoPath = [NSString stringWithFormat:@"%@/xyz.mp4", [paths objectAtIndex:0]];
exportSession.outputURL = [NSURL fileURLWithPath:videoPath];
NSLog(@"videopath of your mp4 file = %@",videoPath); // PATH OF YOUR .mp4 FILE
exportSession.outputFileType = AVFileTypeMPEG4;
// CMTime start = CMTimeMakeWithSeconds(1.0, 600);
// CMTime duration = CMTimeMakeWithSeconds(3.0, 600);
// CMTimeRange range = CMTimeRangeMake(start, duration);
// exportSession.timeRange = range;
// UNCOMMENT ABOVE LINES FOR CROP VIDEO
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed:
NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(@"Export canceled");
break;
default:
break;
}
UISaveVideoAtPathToSavedPhotosAlbum(videoPath, self, nil, nil);
[exportSession release];
}];
}
[nextScreenButton setTitle:@"ПРОДЪЛЖИ" forState:UIControlStateNormal];
[self dismissViewControllerAnimated:YES completion:nil];
</code></pre> |
20,019,231 | VT Not Supported when Installing HAXM | <p>I am trying to install fast Android emulator which uses Intel x86 emulator accelerator.
I've downloaded the accelerator via SDK manager but when I tried to install it I got following error message in the beginning of the installation:</p>
<p><img src="https://i.stack.imgur.com/gQjON.png" alt="HAXM failed"></p>
<p>I know that my CPU (i7-3520M) supports VT-X virtualization so I went to BIOS to make sure that it is enabled:</p>
<p><img src="https://i.stack.imgur.com/Okj20.jpg" alt="BIOS"></p>
<p>As you can see, the feature is enabled in BIOS. I've found 'securable.exe' utility on the internet and when I launch it the following window is shown:</p>
<p><img src="https://i.stack.imgur.com/ZlnSj.png" alt="securable"></p>
<p>Any thoughts or recommendations? I have Lenovo Z580 Laptop with Intel Core i7 and I know for sure it should support such a basic virtualization functionality.</p>
<p>OS is Windows 8 Pro, I also have Hyper-V enabled, I use this machine for Windows Phone 8 development.</p>
<p>--- edit ---</p>
<p>It turns out that VT-x starts working when you turn off the Hyper-V! It is very annoying because I cannot use Android and WP emulators at the same time. Does anyone know how to fix it?</p> | 20,033,339 | 11 | 0 | null | 2013-11-16 13:51:02.477 UTC | 20 | 2022-05-09 14:25:55.573 UTC | 2013-11-16 18:43:32.847 UTC | null | 1,645,784 | null | 1,645,784 | null | 1 | 49 | windows|x86|emulation|virtualization|haxm | 107,074 | <p>So the only solution I've found to make it work is to completely disable Hyper-V in Control Panel -> Programs and Features -> Turn Features On or Off.</p>
<p>If anyone knows how to enable VT-x without disabling Hyper-V please answer this question...</p>
<p><a href="https://i.stack.imgur.com/3ABiB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3ABiB.png" alt="enter image description here"></a></p> |
26,501,670 | Visual Studio website is redirecting http to https when debugging | <p>I am having an issue with IIS express or Visual Studio 2013.</p>
<p>The site has NO https or ssl enabled or setup in the properties.</p>
<p>When I click debug, the site launches in the broswer and tries to load:
<code>http://localhost:61488/Default.aspx</code></p>
<p>it then for some reason gets automatically redirected to:
<code>https://localhost:61488/Default.aspx</code>
and I then get an <code>Error code: ERR_SSL_PROTOCOL_ERROR</code> in chrome</p>
<p>Im not quite sure what to do?</p> | 28,321,836 | 5 | 0 | null | 2014-10-22 06:41:12.373 UTC | 24 | 2020-11-25 01:04:47.447 UTC | 2014-10-22 06:51:28.87 UTC | null | 1,331,971 | null | 1,331,971 | null | 1 | 55 | c#|asp.net|https|visual-studio-2013|iis-express | 27,731 | <p>I believe this is caused by HSTS - see <a href="http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security" rel="noreferrer">http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security</a></p>
<p>If you have (developed) any other localhost sites which send a HSTS header...</p>
<p>eg. Strict-Transport-Security: max-age=31536000; includeSubDomains; preload</p>
<p>...then depending on the value of max-age, future requests to localhost will be required to be served over HTTPS. </p>
<p>To get around this, I did the following. </p>
<ul>
<li>In the Chrome address bar type "chrome://net-internals/#hsts"</li>
<li>At the very bottom of a page is QUERY domain textbox - verify that localhost is known to the browser</li>
<li>If it is, DELETE the localhost domain using the textbox above</li>
<li>Your site should now work using plain old HTTP</li>
</ul>
<p>This is not a permanent solution, but will at least get it working between projects. If anyone knows how to permanently exclude localhost from the HSTS list please let me know :)</p>
<p><strong>Update</strong> - as pointed out in <a href="https://stackoverflow.com/a/44460301/3394022">an answer below</a>, you will likely need to <strong>clear the browser cache</strong> after performing the step above to get the browser to completely "forget" the HSTS info for localhost.</p> |
49,683,014 | What's the difference between Cluster and Instance in AWS Aurora RDS | <p>I guess the title is pretty objective, but just to clarify:</p>
<p>When you create an Aurora Database Instance, it is asked to give a name for a Database Instance, a Database Cluster and a Database (where the name of the Database is optional, and no databases are created if it is not specified...). When you create another instance, you have to give the name for both again, and neither of them can be the same one as the first ones.</p>
<p>So, what's the difference between an Aurora Database Instance and an Aurora Database Cluster?</p>
<p>Also, can (and when do) you connect to each one of them?</p>
<p>Thanks!!</p> | 49,683,723 | 1 | 0 | null | 2018-04-05 23:25:53.863 UTC | 4 | 2018-04-06 01:03:18.713 UTC | null | null | null | null | 4,212,870 | null | 1 | 33 | amazon-web-services|cluster-computing|amazon-rds|amazon-aurora | 24,980 | <p>An Aurora cluster is simply a group of instances. By default, Aurora will create two instances in a cluster - one for reads and the other for writes. But you can change that configuration to be whatever you need.</p>
<p>For the names:</p>
<ul>
<li><strong>Database Cluster</strong> is the name of the cluster that holds the instances</li>
<li><strong>Database Instances</strong> are the names of each instance in the cluster. By
default, if you named the instances "mydb", AWS will append the AZ to
the name. So it would become "mydb-us-east-1c" for example. </li>
<li><strong>Database Name</strong> is the name of the initial database that will be created within Aurora. Think database like where you will add tables and data. If you do not specify a Database Name, you will just need to create your own - which is likely what you want to do anyway.</li>
</ul>
<p>To connect, just point your application at the cluster endpoint. RDS will route traffic and handle failovers for you.</p> |
44,204,828 | Testing react component enclosed in withRouter (preferably using jest/enzyme) | <p>I have a React component which is enclosed within Higher Order Component withRouter as below:</p>
<pre><code>module.exports = withRouter(ManageProfilePage);
</code></pre>
<p>My routes are as below:</p>
<pre><code><Route path="/" component={AdrApp}>
<IndexRoute component={Login}/>
<Route component={CheckLoginStatus}>
<Route path="manage-profiles/:profileId" component=
{ManageProfilesPage}/>
</Route>
<Route path="*" component={notFoundPage}/>
</Route>
</code></pre>
<p>I need to use once of the Router lifecycle methods, that is why I need withRouter:</p>
<pre><code>class ManageProfilePage extends React.Component {
componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, () => {
...
})
render(){
...
}
}
</code></pre>
<p>I need to test this component using Jest/Enzyme and I wrote the test case as below:</p>
<pre><code>describe('manage profile page test suite', () => {
it('snapshot test', () => {
const setRouteLeaveHook =jest.fn();
let wrapper = shallow(
<ManageProfilePage params={{id : 25, router:
setRouteLeaveHook}}/>
);
expect(wrapper).toMatchSnapshot();
})
})
</code></pre>
<p>The issue is it is not rendering one level deep. I am pasting the snapshot below:</p>
<pre><code>exports[`manage drug term page test suites snapshot test 1`] = `
<ManageProfilePage
params={
Object {
"id": 25,
"router": [Function],
}
}
/>
`;
</code></pre>
<p>Is there any different way I can write my test case so that I am able to render ManageProfilePage atleast 1 level deep? It is not able to render as it is enclosed within WithRouter? How do we test these type of components?</p> | 44,266,353 | 4 | 0 | null | 2017-05-26 15:06:45.97 UTC | 6 | 2020-04-23 00:07:09.92 UTC | 2018-09-21 13:44:15.413 UTC | null | 5,521,183 | null | 157,704 | null | 1 | 35 | reactjs|unit-testing|react-router|jestjs|enzyme | 23,606 | <p>Normally if we try to test such components we won’t be able to render it as it is wrapped within WithRouter (WithRouter is a wrapper over a component which provides
Router props like match, route and history to be directly used within the component).
module.exports = withRouter(ManageProfilePage);</p>
<p>To render such components, we have to explicitly tell it to render the wrapped component using WrappedComponent keyword.
For Eg. we will use below code for snapshot test:</p>
<pre><code>describe('manage profile page test suite', () => {
it('snapshot test', () => {
const setRouteLeaveHook =jest.fn();
let wrapper = shallow(
<ManageProfilePage.WrappedComponent params={{id : 25, router:
setRouteLeaveHook}}/>
);
expect(wrapper).toMatchSnapshot();
})
})
</code></pre>
<p>This will tell enzyme to do shallow rendering (Shallow Rendering renders only that particular component and skips child components) for ManageProfilePage which is wrapped component within WithRouter. </p> |
31,846,263 | How to change the font and text color of the title of UINavigationBar | <p>I want to be change the font of the title to Avenir, and I want to make it white. Here is my code in the <code>viewDidLoad</code> method:</p>
<pre><code>UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Avenir", size: 20)!]
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
</code></pre>
<p>This code only changes the color of the title, not the font. Additionally, I tried implementing this in the App Delegate File, but that did not work. </p>
<p>Here is what my UINavigationBar looks like:<a href="https://i.stack.imgur.com/KHRAb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KHRAb.png" alt="enter image description here"></a></p>
<p>I want the title to have a font of Avenir as well. How do I achieve this?</p> | 31,846,318 | 7 | 0 | null | 2015-08-06 03:20:49.277 UTC | 2 | 2021-12-21 20:25:07.81 UTC | 2015-08-06 03:22:18.877 UTC | null | 2,237,785 | null | 3,741,998 | null | 1 | 28 | ios|swift|fonts|uinavigationcontroller|uinavigationbar | 30,357 | <p>It seems this is needed as well:</p>
<pre><code>self.navigationController?.navigationBar.barStyle = UIBarStyle.Black // I then set the color using:
self.navigationController?.navigationBar.barTintColor = UIColor(red: 204/255, green: 47/255, blue: 40/255, alpha: 1.0) // a lovely red
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() // for titles, buttons, etc.
let navigationTitleFont = UIFont(name: "Avenir", size: 20)!
self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: navigationTitleFont]
</code></pre> |
32,368,101 | mysqldump with multiple tables with or without where clause | <p>I have a set of tables in my database that I have to take a dump ( :D ) of. My problem is I want to take some data from some tables that only date back certain days and would like to keep the remaining tables in tact.</p>
<p>The query I came up with was something like:</p>
<pre><code>mysqldump -h<hostname> -u<username> -p <databasename>
<table1> <table2> <table3>
<table4> --where 'created > DATE_SUB(now(), INTERVAL 7 DAY)',
<table5> --where 'created > DATE_SUB(now(), INTERVAL 7 DAY)
--single-transaction --no-create-info | gzip
> $(date +%Y-%m-%d-%H)-dump.sql.gz
</code></pre>
<p>The trouble with the above code is that table1, table2 and table3 will try to take the where clause of table4. I don't want that cause that would spit out an error that created field does not exist in these tables.</p>
<p>I tried putting comma (,) after table names as I did after where clause but it doesn't work.</p>
<p>At this point I'm pretty much stuck and have no more alternative expect create two different sql dump files, which I wouldn't want to do. </p> | 32,369,707 | 3 | 0 | null | 2015-09-03 06:07:16.9 UTC | 6 | 2022-02-22 16:11:49.833 UTC | 2015-09-03 07:10:30.09 UTC | null | 456,912 | null | 456,912 | null | 1 | 18 | mysql|mysqldump | 42,131 | <p>make two dumps or if you dont want to make two dumps then try two command</p>
<p>a.</p>
<pre><code>mysqldump -h<hostname> -u<username> -p
<databasename> <table1> <table2> <table3>
--single-transaction --no-create-info > dumpfile.sql
</code></pre>
<p>b. </p>
<pre><code>mysqldump -h<hostname> -u<username> -p <databasename>
<table4> --where 'created > DATE_SUB(now(), INTERVAL 7 DAY)',
<table5> --where 'created > DATE_SUB(now(), INTERVAL 7 DAY)
--single-transaction --no-create-info >> dumpfile.sql
</code></pre>
<p>c. </p>
<pre><code>gzip dumpfile.sql
</code></pre> |
47,843,056 | Create React App not working | <p><a href="https://i.stack.imgur.com/R6lrT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/R6lrT.png" alt="Command Prompt showing create react app, not working"></a></p>
<p>Help! I have no idea what is going on here, create react app is not working I have also tried reinstalling and yet to no avail, please help!</p>
<p>Npm version: 5.4.2
Node version: 8.70</p>
<p>Tried the npm install --save --save-exact --loglevel error react react-dom react-scripts</p>
<p><a href="https://i.stack.imgur.com/SXCyG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SXCyG.png" alt="enter image description here"></a></p> | 47,843,561 | 19 | 7 | null | 2017-12-16 06:08:20.827 UTC | 7 | 2022-03-22 09:25:04.713 UTC | 2017-12-16 06:57:56.43 UTC | null | 6,591,864 | null | 6,591,864 | null | 1 | 31 | reactjs|command-prompt|create-react-app | 123,386 | <p>Please try this:</p>
<pre><code>npm cache clean --force
</code></pre> |
47,918,792 | 2D bin packing on a grid | <p>I have an <em>n</em> × <em>m</em> grid and a collection of <a href="https://en.wikipedia.org/wiki/Polyomino" rel="noreferrer">polyominos</a>. I would like to know if it is possible to pack them into the grid: no overlapping or rotation is allowed.</p>
<p>I expect that like most packing problems this version is NP-hard and difficult to approximate, so I'm not expecting anything crazy, but an algorithm that could find reasonable packings on a grid around 25 × 25 and be fairly comprehensive around 10 × 10 would be great. (My tiles are mostly tetrominos -- four blocks -- but they could have 5–9+ blocks.)</p>
<p>I'll take whatever anyone has to offer: an algorithm, a paper, an existing program which can be adapted.</p> | 47,934,736 | 3 | 14 | null | 2017-12-21 05:58:56.813 UTC | 9 | 2020-12-27 19:23:34.787 UTC | null | null | null | null | 341,362 | null | 1 | 6 | algorithm|mathematical-optimization|discrete-mathematics|bin-packing | 3,417 | <p>Here is a prototype-like <a href="https://en.wikipedia.org/wiki/Boolean_satisfiability_problem" rel="noreferrer">SAT-solver</a> approach, which tackles:</p>
<ul>
<li>a-priori fixed polyomino patterns (see <code>Constants / Input</code> in code)
<ul>
<li>if rotations should be allowed, rotated pieces have to be added to the set</li>
</ul></li>
<li>every polyomino can be placed 0-inf times</li>
<li>there is no scoring-mechanic besides:
<ul>
<li>the number of non-covered tiles is minimized!</li>
</ul></li>
</ul>
<p>Considering classic off-the-shelf methods for combinatorial-optimization (<a href="https://en.wikipedia.org/wiki/Boolean_satisfiability_problem" rel="noreferrer">SAT</a>, <a href="https://en.wikipedia.org/wiki/Constraint_programming" rel="noreferrer">CP</a>, <a href="https://en.wikipedia.org/wiki/Integer_programming" rel="noreferrer">MIP</a>), this one will probably scale best (educated guess). It will also be very hard to beat when designing customized heuristics!</p>
<p>If needed, these slides provide some <a href="http://www-pr.informatik.uni-tuebingen.de/forschung/sat/SlidesDanielLeBerreWorkshopTuebingen.pdf" rel="noreferrer">practical introduction</a> to SAT-solvers in practice. Here we are using <a href="https://en.wikipedia.org/wiki/Conflict-Driven_Clause_Learning" rel="noreferrer">CDCL</a>-based solvers which are <em>complete</em> (will always find a solution in finite time if there is one; will always be able to prove there is no solution in finite time if there is none; memory of course also plays a role!).</p>
<p>More complex (linear) per-tile scoring-functions are hard to incorporate in general. This is where a (M)IP-approach can be better. But in terms of pure search SAT-solving is much faster in general.</p>
<p>The <code>N=25</code> problem with my polyomino-set takes <em>~ 1 second</em> (and one could easily parallize this on multiple granularity-levels -> SAT-solver (threadings-param) vs. outer-loop; the latter will be explained later).</p>
<p>Of course the following holds:</p>
<ul>
<li>as this is an NP-hard problem, there will be easy and non-easy instances</li>
<li>i did not do scientific benchmarks with many different sets of polyominos
<ul>
<li>it's to be expected that some sets are easier to solve than others </li>
</ul></li>
<li>this is <em>one possible SAT-formulation</em> (not the most trivial!) of infinite many
<ul>
<li>each formulation has advantages and disadvantages</li>
</ul></li>
</ul>
<h3>Idea</h3>
<p>The general approach is creating a <em>decision-problem</em> and transforming it into <a href="https://en.wikipedia.org/wiki/Conjunctive_normal_form" rel="noreferrer">CNF</a>, which is then solved by highly efficient SAT-solvers (here: cryptominisat; CNF will be in <a href="https://logic.pdmi.ras.ru/~basolver/dimacs.html" rel="noreferrer">DIMCAS-CNF format</a>), which will be used as black-box solvers (no parameter-tuning!).</p>
<p>As the goal is to optimize the number of filled tiles and we are using a decision-problem, we need an outer-loop, adding a minimum tile-used constraint and try to solve it. If not successful, decrease this number. So in general we are calling the SAT-solver multiple times (from scratch!).</p>
<p>There are many different formulations / transformations to CNF possible. Here we use (binary) decision-variables <code>X</code> which indicate a <em>placement</em>. A <em>placement</em> is a tuple like <code>polyomino, x_index, y_index</code> (this index marks the top-left field of some pattern). There is a one-to-one mapping between the number of variables and the number of possible placements of all polyominos.</p>
<p>The core idea is: search in the space of all possible placement-combinations for one solution, which is not invalidating some constraints. </p>
<p>Additionally, we have decision-variables <code>Y</code>, which indicate a tile being filled. There are <code>M*N</code> such variables. </p>
<p>When having access to all possible placements, it's easy to calculate a collision-set for each tile-index (M*N). Given some fixed tile, we can check which placements can fill this one and constrain the problem to only select <code><=1</code> of those. This is active on <code>X</code>. In the (M)IP world this probably would be called convex-hull for the collisions.</p>
<p><code>n<=k</code>-constraints are ubiquitous in SAT-solving and many different formulations are possible. Naive-encoding would need an exponential number of clauses in general which easily becomes infeasibly. Using new variables, there are many variable-clause trade-offs (see <a href="https://en.wikipedia.org/wiki/Tseytin_transformation" rel="noreferrer">Tseitin-encoding</a>) possible. I'm reusing one (old code; only reason why my code is python2-only) which worked good for me in the past. It's based on describing hardware-based counter-logic into CNF and provides good empirical- and theoretical performance (see paper). Of course there are many alternatives.</p>
<p>Additionally, we need to force the SAT-solver not to make all variables negative. We have to add constraints describing the following (that's one approach):</p>
<ul>
<li>if some field is used: there has to be at least one placement active (poly + x + y), which results in covering this field!
<ul>
<li>this is a basic logical implication easily formulated as one potentially big <em>logical or</em></li>
</ul></li>
</ul>
<p>Then only the core-loop is missing, trying to fill N fields, then N-1 until successful. This is again using the <code>n<=k</code> formulation mentioned earlier.</p>
<h3>Code</h3>
<p>This is python2-code, which needs the SAT-solver <a href="https://github.com/msoos/cryptominisat" rel="noreferrer">cryptominisat 5</a> in the directory the script is run from.</p>
<p>I'm also using tools from python's excellent scientific-stack.</p>
<pre class="lang-python prettyprint-override"><code># PYTHON 2!
import math
import copy
import subprocess
import numpy as np
import matplotlib.pyplot as plt # plotting-only
import seaborn as sns # plotting-only
np.set_printoptions(linewidth=120) # more nice console-output
""" Constants / Input
Example: 5 tetrominoes; no rotation """
M, N = 25, 25
polyominos = [np.array([[1,1,1,1]]),
np.array([[1,1],[1,1]]),
np.array([[1,0],[1,0], [1,1]]),
np.array([[1,0],[1,1],[0,1]]),
np.array([[1,1,1],[0,1,0]])]
""" Preprocessing
Calculate:
A: possible placements
B: covered positions
C: collisions between placements
"""
placements = []
covered = []
for p_ind, p in enumerate(polyominos):
mP, nP = p.shape
for x in range(M):
for y in range(N):
if x + mP <= M: # assumption: no zero rows / cols in each p
if y + nP <= N: # could be more efficient
placements.append((p_ind, x, y))
cover = np.zeros((M,N), dtype=bool)
cover[x:x+mP, y:y+nP] = p
covered.append(cover)
covered = np.array(covered)
collisions = []
for m in range(M):
for n in range(N):
collision_set = np.flatnonzero(covered[:, m, n])
collisions.append(collision_set)
""" Helper-function: Cardinality constraints """
# K-ARY CONSTRAINT GENERATION
# ###########################
# SINZ, Carsten. Towards an optimal CNF encoding of boolean cardinality constraints.
# CP, 2005, 3709. Jg., S. 827-831.
def next_var_index(start):
next_var = start
while(True):
yield next_var
next_var += 1
class s_index():
def __init__(self, start_index):
self.firstEnvVar = start_index
def next(self,i,j,k):
return self.firstEnvVar + i*k +j
def gen_seq_circuit(k, input_indices, next_var_index_gen):
cnf_string = ''
s_index_gen = s_index(next_var_index_gen.next())
# write clauses of first partial sum (i.e. i=0)
cnf_string += (str(-input_indices[0]) + ' ' + str(s_index_gen.next(0,0,k)) + ' 0\n')
for i in range(1, k):
cnf_string += (str(-s_index_gen.next(0, i, k)) + ' 0\n')
# write clauses for general case (i.e. 0 < i < n-1)
for i in range(1, len(input_indices)-1):
cnf_string += (str(-input_indices[i]) + ' ' + str(s_index_gen.next(i, 0, k)) + ' 0\n')
cnf_string += (str(-s_index_gen.next(i-1, 0, k)) + ' ' + str(s_index_gen.next(i, 0, k)) + ' 0\n')
for u in range(1, k):
cnf_string += (str(-input_indices[i]) + ' ' + str(-s_index_gen.next(i-1, u-1, k)) + ' ' + str(s_index_gen.next(i, u, k)) + ' 0\n')
cnf_string += (str(-s_index_gen.next(i-1, u, k)) + ' ' + str(s_index_gen.next(i, u, k)) + ' 0\n')
cnf_string += (str(-input_indices[i]) + ' ' + str(-s_index_gen.next(i-1, k-1, k)) + ' 0\n')
# last clause for last variable
cnf_string += (str(-input_indices[-1]) + ' ' + str(-s_index_gen.next(len(input_indices)-2, k-1, k)) + ' 0\n')
return (cnf_string, (len(input_indices)-1)*k, 2*len(input_indices)*k + len(input_indices) - 3*k - 1)
def gen_at_most_n_constraints(vars, start_var, n):
constraint_string = ''
used_clauses = 0
used_vars = 0
index_gen = next_var_index(start_var)
circuit = gen_seq_circuit(n, vars, index_gen)
constraint_string += circuit[0]
used_clauses += circuit[2]
used_vars += circuit[1]
start_var += circuit[1]
return [constraint_string, used_clauses, used_vars, start_var]
def parse_solution(output):
# assumes there is one
vars = []
for line in output.split("\n"):
if line:
if line[0] == 'v':
line_vars = list(map(lambda x: int(x), line.split()[1:]))
vars.extend(line_vars)
return vars
def solve(CNF):
p = subprocess.Popen(["cryptominisat5.exe"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
result = p.communicate(input=CNF)[0]
sat_line = result.find('s SATISFIABLE')
if sat_line != -1:
# solution found!
vars = parse_solution(result)
return True, vars
else:
return False, None
""" SAT-CNF: BASE """
X = np.arange(1, len(placements)+1) # decision-vars
# 1-index for CNF
Y = np.arange(len(placements)+1, len(placements)+1 + M*N).reshape(M,N)
next_var = len(placements)+1 + M*N # aux-var gen
n_clauses = 0
cnf = '' # slow string appends
# int-based would be better
# <= 1 for each collision-set
for cset in collisions:
constraint_string, used_clauses, used_vars, next_var = \
gen_at_most_n_constraints(X[cset].tolist(), next_var, 1)
n_clauses += used_clauses
cnf += constraint_string
# if field marked: one of covering placements active
for x in range(M):
for y in range(N):
covering_placements = X[np.flatnonzero(covered[:, x, y])] # could reuse collisions
clause = str(-Y[x,y])
for i in covering_placements:
clause += ' ' + str(i)
clause += ' 0\n'
cnf += clause
n_clauses += 1
print('BASE CNF size')
print('clauses: ', n_clauses)
print('vars: ', next_var - 1)
""" SOLVE in loop -> decrease number of placed-fields until SAT """
print('CORE LOOP')
N_FIELD_HIT = M*N
while True:
print(' N_FIELDS >= ', N_FIELD_HIT)
# sum(y) >= N_FIELD_HIT
# == sum(not y) <= M*N - N_FIELD_HIT
cnf_final = copy.copy(cnf)
n_clauses_final = n_clauses
if N_FIELD_HIT == M*N: # awkward special case
constraint_string = ''.join([str(y) + ' 0\n' for y in Y.ravel()])
n_clauses_final += N_FIELD_HIT
else:
constraint_string, used_clauses, used_vars, next_var = \
gen_at_most_n_constraints((-Y).ravel().tolist(), next_var, M*N - N_FIELD_HIT)
n_clauses_final += used_clauses
n_vars_final = next_var - 1
cnf_final += constraint_string
cnf_final = 'p cnf ' + str(n_vars_final) + ' ' + str(n_clauses) + \
' \n' + cnf_final # header
status, sol = solve(cnf_final)
if status:
print(' SOL found: ', N_FIELD_HIT)
""" Print sol """
res = np.zeros((M, N), dtype=int)
counter = 1
for v in sol[:X.shape[0]]:
if v>0:
p, x, y = placements[v-1]
pM, pN = polyominos[p].shape
poly_nnz = np.where(polyominos[p] != 0)
x_inds, y_inds = x+poly_nnz[0], y+poly_nnz[1]
res[x_inds, y_inds] = p+1
counter += 1
print(res)
""" Plot """
# very very ugly code; too lazy
ax1 = plt.subplot2grid((5, 12), (0, 0), colspan=11, rowspan=5)
ax_p0 = plt.subplot2grid((5, 12), (0, 11))
ax_p1 = plt.subplot2grid((5, 12), (1, 11))
ax_p2 = plt.subplot2grid((5, 12), (2, 11))
ax_p3 = plt.subplot2grid((5, 12), (3, 11))
ax_p4 = plt.subplot2grid((5, 12), (4, 11))
ax_p0.imshow(polyominos[0] * 1, vmin=0, vmax=5)
ax_p1.imshow(polyominos[1] * 2, vmin=0, vmax=5)
ax_p2.imshow(polyominos[2] * 3, vmin=0, vmax=5)
ax_p3.imshow(polyominos[3] * 4, vmin=0, vmax=5)
ax_p4.imshow(polyominos[4] * 5, vmin=0, vmax=5)
ax_p0.xaxis.set_major_formatter(plt.NullFormatter())
ax_p1.xaxis.set_major_formatter(plt.NullFormatter())
ax_p2.xaxis.set_major_formatter(plt.NullFormatter())
ax_p3.xaxis.set_major_formatter(plt.NullFormatter())
ax_p4.xaxis.set_major_formatter(plt.NullFormatter())
ax_p0.yaxis.set_major_formatter(plt.NullFormatter())
ax_p1.yaxis.set_major_formatter(plt.NullFormatter())
ax_p2.yaxis.set_major_formatter(plt.NullFormatter())
ax_p3.yaxis.set_major_formatter(plt.NullFormatter())
ax_p4.yaxis.set_major_formatter(plt.NullFormatter())
mask = (res==0)
sns.heatmap(res, cmap='viridis', mask=mask, cbar=False, square=True, linewidths=.1, ax=ax1)
plt.tight_layout()
plt.show()
break
N_FIELD_HIT -= 1 # binary-search could be viable in some cases
# but beware the empirical asymmetry in SAT-solvers:
# finding solution vs. proving there is none!
</code></pre>
<h3>Output console</h3>
<pre><code>BASE CNF size
('clauses: ', 31509)
('vars: ', 13910)
CORE LOOP
(' N_FIELDS >= ', 625)
(' N_FIELDS >= ', 624)
(' SOL found: ', 624)
[[3 2 2 2 2 1 1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 2 2]
[3 2 2 2 2 1 1 1 1 1 1 1 1 2 2 2 2 2 2 1 1 1 1 2 2]
[3 3 3 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 1 1 1 1 2 2]
[2 2 3 1 1 1 1 1 1 1 1 2 2 2 2 1 1 1 1 2 2 2 2 2 2]
[2 2 3 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 2 2 2 2 2 2]
[1 1 1 1 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 2 2]
[1 1 1 1 3 3 3 2 2 1 1 1 1 2 2 2 2 2 2 2 2 1 1 1 1]
[2 2 1 1 1 1 3 2 2 2 2 2 2 2 2 1 1 1 1 2 2 2 2 2 2]
[2 2 2 2 2 2 3 3 3 2 2 2 2 1 1 1 1 2 2 2 2 2 2 2 2]
[2 2 2 2 2 2 2 2 3 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2]
[2 2 1 1 1 1 2 2 3 3 3 2 2 2 2 2 2 1 1 1 1 2 2 2 2]
[1 1 1 1 1 1 1 1 2 2 3 2 2 1 1 1 1 1 1 1 1 1 1 1 1]
[2 2 3 1 1 1 1 3 2 2 3 3 4 1 1 1 1 2 2 1 1 1 1 2 2]
[2 2 3 1 1 1 1 3 1 1 1 1 4 4 3 2 2 2 2 1 1 1 1 2 2]
[2 2 3 3 5 5 5 3 3 1 1 1 1 4 3 2 2 1 1 1 1 1 1 1 1]
[2 2 2 2 4 5 1 1 1 1 1 1 1 1 3 3 3 2 2 1 1 1 1 2 2]
[2 2 2 2 4 4 2 2 1 1 1 1 1 1 1 1 3 2 2 1 1 1 1 2 2]
[2 2 2 2 3 4 2 2 2 2 2 2 1 1 1 1 3 3 3 2 2 2 2 2 2]
[3 4 2 2 3 5 5 5 2 2 2 2 1 1 1 1 2 2 3 2 2 2 2 2 2]
[3 4 4 3 3 3 5 5 5 5 1 1 1 1 2 2 2 2 3 3 3 2 2 2 2]
[3 3 4 3 1 1 1 1 5 1 1 1 1 4 2 2 2 2 2 2 3 2 2 2 2]
[2 2 3 3 3 1 1 1 1 1 1 1 1 4 4 4 2 2 2 2 3 3 0 2 2]
[2 2 3 1 1 1 1 1 1 1 1 5 5 5 4 4 4 1 1 1 1 2 2 2 2]
[2 2 3 3 1 1 1 1 1 1 1 1 5 5 5 5 4 1 1 1 1 2 2 2 2]
[2 2 1 1 1 1 1 1 1 1 1 1 1 1 5 1 1 1 1 1 1 1 1 2 2]]
</code></pre>
<h3>Output plot</h3>
<p><a href="https://i.stack.imgur.com/akxNT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/akxNT.png" alt="enter image description here"></a></p>
<p>One field cannot be covered in this parameterization!</p>
<h3>Some other examples with a bigger set of patterns</h3>
<p><strong>Square</strong> <code>M=N=61</code> (prime -> intuition: harder) where the base-CNF has 450.723 clauses and 185.462 variables. There is an optimal packing!</p>
<p><a href="https://i.stack.imgur.com/atmVw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/atmVw.png" alt="enter image description here"></a></p>
<p><strong>Non-square</strong> <code>M,N =83,131</code> (double prime) where the base-CNF has 1.346.511 clauses and 553.748 variables. There is an optimal packing!</p>
<p><a href="https://i.stack.imgur.com/jPuM6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jPuM6.png" alt="enter image description here"></a></p> |
21,967,254 | How to write a "reader-friendly" sessionInfo() to text file | <p>I would like to save the output of "sessionInfo()" to a text file. Using "write()" failed because "list() cannot be handled by 'cat()'". I then tried "save()" with ascii = T but the resulting file is not really helpful.</p>
<p>I would like to have an output <a href="https://stackoverflow.com/a/11103209/2369943">like this</a> in a text file. Any easy, straightforward way to do this?</p> | 21,967,272 | 5 | 1 | null | 2014-02-23 10:51:32.97 UTC | 9 | 2020-08-20 08:24:36.123 UTC | 2017-05-23 12:32:06.76 UTC | null | -1 | null | 2,369,943 | null | 1 | 36 | r | 8,625 | <p>Capture the screen output into a character vector and use <code>writeLines</code>.</p>
<pre><code>writeLines(capture.output(sessionInfo()), "sessionInfo.txt")
</code></pre> |
23,565,790 | Printing integer variable and string on same line in SQL | <p>Ok so I have searched for an answer to this on Technet, to no avail. </p>
<p>I just want to print an integer variable concatenated with two String variables. </p>
<p>This is my code, that doesn't run:</p>
<pre><code>print 'There are ' + @Number + ' alias combinations did not match a record'
</code></pre>
<p>It seems like such a basic feature, I couldn't imagine that it is not possible in T-SQL. But if it isn't possible, please just say so. I can't seem to find a straight answer.</p> | 23,565,860 | 6 | 1 | null | 2014-05-09 13:24:48.38 UTC | 9 | 2022-01-04 13:18:11.963 UTC | 2014-05-09 13:36:08.8 UTC | null | 3,043 | user2993456 | null | null | 1 | 106 | sql|sql-server|tsql | 181,852 | <pre class="lang-sql prettyprint-override"><code>declare @x INT = 1 /* Declares an integer variable named "x" with the value of 1 */
PRINT 'There are ' + CAST(@x AS VARCHAR) + ' alias combinations did not match a record' /* Prints a string concatenated with x casted as a varchar */
</code></pre> |
53,170,330 | Reload data when using FutureBuilder | <p>I am loading data when widget is loading like the code below. Once the UI is fully loaded, I like to add one refresh button to reload the data again. </p>
<p>How can I refresh the view ? </p>
<pre><code> class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
var futureBuilder = new FutureBuilder(
future: _getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return new Text('loading...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return createListView(context, snapshot);
}
},
);
return new Scaffold(
appBar: new AppBar(
title: new Text("Home Page"),
),
body: futureBuilder,
);
}
Future<List<String>> _getData() async {
var values = new List<String>();
await new Future.delayed(new Duration(seconds: 5));
return values;
}
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
}
}
</code></pre> | 53,170,458 | 5 | 1 | null | 2018-11-06 10:46:50.41 UTC | 5 | 2022-08-03 03:32:08.92 UTC | null | null | null | null | 9,690,423 | null | 1 | 42 | flutter|flutter-layout | 56,232 | <pre><code>Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
RaisedButton button = RaisedButton(
onPressed: () {
setState(() {});
},
child: Text('Refresh'),
);
//.. here create widget with snapshot data and with necessary button
}
</code></pre> |
25,706,537 | Specifying a fixed column width in jQuery Datatables | <p>I'm trying to specify a fixed width for a few columns in a jQuery datatable. I've attempted to accomplish this via the column definitions specified in the <a href="http://datatables.net/reference/option/columns.width">datatables documentation</a>, but the column and column header still get auto-sized. </p>
<p>Here's the jsFiddle I've been working with: <a href="http://jsfiddle.net/hunterhod/4foLcq0w/">jsFiddle</a></p>
<p><strong>JavaScript:</strong></p>
<pre><code>var table = $('#example2').DataTable({
"tabIndex": 8,
"dom": '<"fcstTableWrapper"t>lp',
"bFilter": false,
"bAutoWidth": false,
"data": [],
"columnDefs": [
{
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": '',
"targets": 0
},
{
"targets": 1},
{
"targets": 2,
"width": "60px"},
{
"targets": 3,
"width": "1100px"},
{
"targets": 4},
{
"targets": "dlySlsFcstDay"},
{
"targets": "dlySlsFcstWkTtl",
"width": "60px"}
],
"order": [
[1, 'asc']
]
});
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><div class="forecastTableDiv">
<table id="example2" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th colspan="5"></th>
<th class="slsFiscalWk" colspan="8">201424</th>
<th class="slsFiscalWk" colspan="8">201425</th>
<th class="slsFiscalWk" colspan="8">201426</th>
<th class="slsFiscalWk" colspan="8">201427</th>
</tr>
<tr>
<!--<th></th>-->
<!--<th>Vendor</th>-->
<!--<th>Origin ID</th>-->
<!--<th>Destination</th>-->
<!--<th>Vendor Part Nbr</th>-->
<!--<th>SKU</th>-->
<!--<th>Mon</th>-->
<!--<th>Tue</th>-->
<!--<th>Wed</th>-->
<!--<th>Thu</th>-->
<!--<th>Fri</th>-->
<!--<th>Week Ttl</th>-->
<th></th>
<th>Vendor</th>
<th>Origin ID</th>
<th style="width: 200px">Vendor Part Nbr</th>
<th>SKU</th>
<!-- First week -->
<th class="dlySlsFcstDay" >Mon</th>
<th class="dlySlsFcstDay" >Tue</th>
<th class="dlySlsFcstDay" >Wed</th>
<th class="dlySlsFcstDay" >Thu</th>
<th class="dlySlsFcstDay" >Fri</th>
<th class="dlySlsFcstDay" >Sat</th>
<th class="dlySlsFcstDay" >Sun</th>
<th class="dlySlsFcstWkTtl" >Week Ttl</th>
<!-- Second week -->
<th class="dlySlsFcstDay" >Mon</th>
<th class="dlySlsFcstDay" >Tue</th>
<th class="dlySlsFcstDay" >Wed</th>
<th class="dlySlsFcstDay" >Thu</th>
<th class="dlySlsFcstDay" >Fri</th>
<th class="dlySlsFcstDay" >Sat</th>
<th class="dlySlsFcstDay" >Sun</th>
<th class="dlySlsFcstWkTtl" >Week Ttl</th>
<!-- Third week -->
<th class="dlySlsFcstDay" >Mon</th>
<th class="dlySlsFcstDay" >Tue</th>
<th class="dlySlsFcstDay" >Wed</th>
<th class="dlySlsFcstDay" >Thu</th>
<th class="dlySlsFcstDay" >Fri</th>
<th class="dlySlsFcstDay" >Sat</th>
<th class="dlySlsFcstDay" >Sun</th>
<th class="dlySlsFcstWkTtl" >Week Ttl</th>
<!-- Fourth and final week -->
<th class="dlySlsFcstDay" >Mon</th>
<th class="dlySlsFcstDay" >Tue</th>
<th class="dlySlsFcstDay" >Wed</th>
<th class="dlySlsFcstDay" >Thu</th>
<th class="dlySlsFcstDay" >Fri</th>
<th class="dlySlsFcstDay" >Sat</th>
<th class="dlySlsFcstDay" >Sun</th>
<th class="dlySlsFcstWkTtl" >Week Ttl</th>
</tr>
</thead>
<tfoot>
</table>
</div>
</code></pre>
<p>When I inspect the live code, I can see that the width I'm specifying in the column definition is getting added to the column as a style attribute, but it doesn't match the actual width of the column.</p> | 25,752,866 | 4 | 1 | null | 2014-09-07 02:22:02.977 UTC | 9 | 2020-08-08 13:40:18.883 UTC | null | null | null | null | 2,305,349 | null | 1 | 15 | datatables|html-table|jquery-datatables|css-tables | 55,212 | <p>This is not a DataTables issue. See <a href="http://www.w3.org/TR/CSS21/tables.html#auto-table-layout" rel="noreferrer">how column widths are determined</a>. Based on this algorithm I see the following two solutions.</p>
<p><strong>Solution 1</strong></p>
<p>Calculate yourself the table width and set it accordingly.</p>
<pre><code>#example {
width: 3562px;
}
</code></pre>
<p>See live example here: <a href="http://jsfiddle.net/cdog/jsf6cg6L/" rel="noreferrer">http://jsfiddle.net/cdog/jsf6cg6L/</a>.</p>
<p><strong>Solution 2</strong></p>
<p>Set the minimum content width (MCW) of each cell and let the user agent to determine the column widths.</p>
<p>To do this, add classes to the target columns to be able to style them:</p>
<pre><code>var table = $('#example').DataTable({
tabIndex: 8,
dom: '<"fcstTableWrapper"t>lp',
bFilter: false,
bAutoWidth: false,
data: [],
columnDefs: [{
class: 'details-control',
orderable: false,
data: null,
defaultContent: '',
targets: 0
}, {
targets: 1
}, {
class: 'col-2',
targets: 2
}, {
class: 'col-3',
targets: 3
}, {
targets: 4
}, {
targets: 'dlySlsFcstDay'
}, {
targets: 'dlySlsFcstWkTtl'
}],
order: [[1, 'asc']]
});
</code></pre>
<p>Then set the desired value of the minimum width property for each class:</p>
<pre><code>.col-2,
.dlySlsFcstWkTtl {
min-width: 60px;
}
.col-3 {
min-width: 1100px;
}
</code></pre>
<p>See live example here: <a href="http://jsfiddle.net/cdog/hag7Lpm5/" rel="noreferrer">http://jsfiddle.net/cdog/hag7Lpm5/</a>.</p> |
20,371,144 | Which version of Java does SBT use? | <p>How to find out, which version of JDK SBT uses?</p>
<p>My laptop has both JDK 1.6 and JDK 1.7 installed, so I was just wondering.</p> | 20,379,163 | 5 | 1 | null | 2013-12-04 09:10:10.507 UTC | 5 | 2018-09-27 14:29:33.693 UTC | null | null | null | user972946 | null | null | 1 | 32 | scala|sbt | 24,799 | <p>Just run sbt console and you'll get something like this:</p>
<p>Welcome to Scala version 2.10.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_45).
Type in expressions to have them evaluated.
Type :help for more information.</p>
<p>Which shows you the version of Java being used. </p>
<p>Cheers</p>
<p>JC</p> |
51,938,056 | Spring boot upload form data and file | <p>I am making a spring boot REST application. I am trying to make a multipart form upload controller which will handle a form data and a file upload together. This is my controller code at the moment :</p>
<pre><code> @RequestMapping(value = "", method = RequestMethod.POST, headers="Content-Type=multipart/form-data")
@PreAuthorize("hasRole('ROLE_MODERATOR')")
@ResponseStatus(HttpStatus.CREATED)
public void createNewObjectWithImage(
/*@RequestParam(value="file", required=true) MultipartFile file,
@RequestParam(value="param_name_1", required=true) final String param_name_1,
@RequestParam(value="param_name_2", required=true) final String param_name_2,
@RequestParam(value="param_name_3", required=true) final String param_name_3,
@RequestParam(value="param_name_4", required=true) final String param_name_4,
@RequestParam(value="param_name_5", required=true) final String param_name_5*/
@ModelAttribute ModelDTO model,
BindingResult result) throws MyRestPreconditionsException {
//ModelDTO model = new ModelDTO(param_name_1, param_name_2, param_name_3, param_name_4, param_name_5);
modelValidator.validate(model, result);
if(result.hasErrors()){
MyRestPreconditionsException ex = new MyRestPreconditionsException(
"Model creation error",
"Some of the elements in the request are missing or invalid");
ex.getErrors().addAll(
result.getFieldErrors().stream().map(f -> f.getField()+" - "+f.getDefaultMessage()).collect(Collectors.toList()));
throw ex;
}
// at the moment, model has a MultipartFile property
//model.setImage(file);
modelServiceImpl.addNew(model);
}
</code></pre>
<p>I have tried both with the @ModelAttribute annotation and sending request parameters, but both of these methods have failed.</p>
<p>This is the request i am sending :</p>
<pre><code>---------------------------acebdf13572468
Content-Disposition: form-data; name="file"; filename="mint.jpg"
Content-Type: image/jpeg
<@INCLUDE *C:\Users\Lazaruss\Desktop\mint.jpg*@>
---------------------------acebdf13572468
Content-Disposition: form-data; name=”param_name_1”
string_value_1
---------------------------acebdf13572468
Content-Disposition: form-data; name=”param_name_2”
string_value_2
---------------------------acebdf13572468
Content-Disposition: form-data; name=”param_name_3”
string_value_3
---------------------------acebdf13572468
Content-Disposition: form-data; name=”param_name_4”
string_value_4
---------------------------acebdf13572468
Content-Disposition: form-data; name=”param_name_5”
string_value_5
---------------------------acebdf13572468--
</code></pre>
<p>My application is stateless, and uses spring security with authorities.
In my security package, i have included the AbstractSecurityWebApplicationInitializer class</p>
<pre><code>public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
@Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(servletContext, new MultipartFilter());
}
}
</code></pre>
<p>I also use a StandardServletMultipartResolver in my @Configuration class</p>
<p>And in my WebInitializer, i add this code :</p>
<pre><code>MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/tmp",
3 * 1024 * 1024, 6 * 1024 * 1024, 1 * 512 * 1024);
apiSR.setMultipartConfig(multipartConfigElement);
</code></pre>
<p>When i try to use the controller with the commented code (@RequestParams annotations), i get a 404 not found error.
And when i try to use the controller with the @ModuleAttribute annotation, the model object is empty.</p> | 51,960,678 | 2 | 2 | null | 2018-08-20 20:26:46.587 UTC | 6 | 2020-01-28 06:29:23.677 UTC | null | null | null | null | 5,663,107 | null | 1 | 10 | java|spring-boot|spring-security|multipartform-data | 42,837 | <p>I had a similar problem. When you want to send <code>Object</code> + <code>Multipart</code>. You have to (or at least I don't know other solution) make your controller like that:</p>
<pre><code>public void createNewObjectWithImage(@RequestParam("model") String model, @RequestParam(value = "file", required = false) MultipartFile file)
</code></pre>
<p>And then: Convert String to your Object using:</p>
<pre><code>ObjectMapper mapper = new ObjectMapper();
ModelDTO modelDTO = mapper.readValue(model, ModelDTO.class);
</code></pre>
<p>And in Postman you can send it like that:
<a href="https://i.stack.imgur.com/605Xq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/605Xq.png" alt="enter image description here"></a></p> |
4,409,072 | Visual Studio Immediate Window - Lambda Expressions Aren't Allowed - Is there a Work-around or Alternative? | <p>I'm debugging some tricky generic List-based code in VS 2010 - lots of hierarchy-processing etc.. Of course lambda expressions and anonymous methods aren't permitted within the immediates window and I can't be doing with stepping thru the code in the usual way as I'm still trying to get my head around the hierarchies ...</p>
<p>Can anyone suggest a workaround or an alternative tool?</p> | 13,765,810 | 1 | 4 | null | 2010-12-10 13:03:26.953 UTC | 9 | 2015-05-13 19:12:53.213 UTC | 2015-05-13 19:12:53.213 UTC | null | 4,640,209 | null | 2,671,514 | null | 1 | 53 | c#|.net|visual-studio-2010|lambda|immediate-window | 13,857 | <p>At times like this I always turn to the most excellent <a href="http://www.linqpad.net/">LINQPad</a>.</p>
<p>The front page of the linked site (at time of writing) immediately jumps in with stuff about SQL but don't let that obscure how powerful and flexible this tool really is. I sort of treat it like an Immediate Window on steroids. I find it invaluable for working my way through complex LINQ queries.</p>
<p>If you can live without intellisense it's free (the intellisense version is chargeable).</p> |
13,962,772 | Not a GROUP BY expression error | <p>I'm relatively new to databases. I am using Oracle and I'm trying to implement this query to find the number of personal training sessions the member has had.</p>
<p>The tables are;</p>
<p><strong>MEMBERS</strong> </p>
<pre><code>MEMBERS_ID(NUMBER),
MEMBERSHIP_TYPE_CODE(VARCHAR),
ADDRESS_ID(NUMBER), CLUB_ID(NUMBER)
MEMBER_NAME(VARCHAR),
MEMBER_PHONE(VARCHAR),
MEMBER_EMAIL(VARCHAR)
</code></pre>
<p><strong>PERSONAL_TRAINING_SESSIONS</strong></p>
<pre><code>SESSION_ID(VARHCAR),
MEMBER_ID (NUMBER),
STAFF_ID(VARCHAR),
SESSION_DATETIME(DATE)
</code></pre>
<p>My query is returing this error:</p>
<blockquote>
<p>ORA-00979: not a GROUP BY expression
00979. 00000 - "not a GROUP BY expression"
*Cause:<br>
*Action: Error at Line: 1 Column: 8</p>
</blockquote>
<pre><code>SELECT MEMBERS.MEMBER_ID,MEMBERS.MEMBER_NAME, COUNT(personal_training_sessions.session_id)
FROM MEMBERS JOIN personal_training_sessions
ON personal_training_sessions.member_id=members.member_id
GROUP BY personal_training_sessions.session_id;
</code></pre>
<p>Can anyone point me in the right direction? I have looked around do I need to separate the count query?</p> | 13,962,793 | 2 | 1 | null | 2012-12-19 23:08:06.46 UTC | 1 | 2012-12-19 23:25:31.643 UTC | 2012-12-19 23:21:21.463 UTC | null | 1,917,229 | null | 1,205,414 | null | 1 | 5 | sql|oracle|group-by | 43,558 | <p>The error says it all, you're not grouping by <code>MEMBERS.MEMBER_ID</code> and <code>MEMBERS.MEMBER_NAME</code>.</p>
<pre><code>SELECT MEMBERS.MEMBER_ID, MEMBERS.MEMBER_NAME
, COUNT(personal_training_sessions.session_id)
FROM MEMBERS
JOIN personal_training_sessions
ON personal_training_sessions.member_id = members.member_id
GROUP BY MEMBERS.MEMBER_ID, MEMBERS.MEMBER_NAME
</code></pre>
<p>You want the count of personal sessions <em>per</em> member, so you need to group by the member information. </p>
<p>The basic (of course it can get a lot more complex) GROUP BY, SELECT query is:</p>
<pre><code>SELECT <column 1>, <column n>
, <aggregate function 1>, <aggregate function n>
FROM <table_name>
GROUP BY <column 1>, <column n>
</code></pre>
<p>An aggregate function being, as Ken White says, something like <code>MIN()</code>, <code>MAX()</code>, <code>COUNT()</code> etc. You GROUP BY <em>all</em> the columns that are not aggregated.</p>
<p>This will only work as intended if your <code>MEMBERS</code> table is unique on <code>MEMBER_ID</code>, but based on your query I suspect it is. To clarify what I mean, if your table is not unique on <code>MEMBER_ID</code> then you're not counting the number of sessions per <code>MEMBER_ID</code> but the number of sessions per <code>MEMBER_ID</code> <em>and</em> per <code>MEMBER_NAME</code>. If they're in a 1:1 relationship then it's effectively the same thing but if you can have multiple <code>MEMBER_NAME</code>s per <code>MEMBER_ID</code> then it's not.</p> |
48,563,650 | Does React keep the order for state updates? | <p>I know that React may perform state updates asynchronously and in batch for performance optimization. Therefore you can never trust the state to be updated after having called <code>setState</code>. But can you trust React to <strong>update the state in the same order as <code>setState</code> is called</strong> for</p>
<ol>
<li>the same component?</li>
<li>different components?</li>
</ol>
<p>Consider clicking the button in the following examples:</p>
<p><strong>1.</strong> Is there ever a possibility that <strong>a is false and b is true</strong> for:</p>
<pre><code>class Container extends React.Component {
constructor(props) {
super(props);
this.state = { a: false, b: false };
}
render() {
return <Button onClick={this.handleClick}/>
}
handleClick = () => {
this.setState({ a: true });
this.setState({ b: true });
}
}
</code></pre>
<p><strong>2.</strong> Is there ever a possibility that <strong>a is false and b is true</strong> for:</p>
<pre><code>class SuperContainer extends React.Component {
constructor(props) {
super(props);
this.state = { a: false };
}
render() {
return <Container setParentState={this.setState.bind(this)}/>
}
}
class Container extends React.Component {
constructor(props) {
super(props);
this.state = { b: false };
}
render() {
return <Button onClick={this.handleClick}/>
}
handleClick = () => {
this.props.setParentState({ a: true });
this.setState({ b: true });
}
}
</code></pre>
<p>Keep in mind that these are extreme simplifications of my use case. I realize that I can do this differently, e.g. updating both state params at the same time in example 1, as well as performing the second state update in a callback to the first state update in example 2. However, this is not my question, and I am only interested in if there is a well defined way that React performs these state updates, nothing else.</p>
<p>Any answer backed up by documentation is greatly appreciated.</p> | 48,610,973 | 4 | 6 | null | 2018-02-01 13:13:36.647 UTC | 136 | 2022-04-19 10:39:08.687 UTC | null | null | null | null | 3,779,732 | null | 1 | 183 | javascript|reactjs|state|setstate | 65,917 | <p>I work on React.</p>
<p><strong>TLDR:</strong></p>
<blockquote>
<p>But can you trust React to update the state in the same order as setState is called for</p>
<ul>
<li>the same component?</li>
</ul>
</blockquote>
<p>Yes.</p>
<blockquote>
<ul>
<li>different components?</li>
</ul>
</blockquote>
<p>Yes.</p>
<p>The <strong>order</strong> of updates is always respected. Whether you see an intermediate state "between" them or not depends on whether you're inside in a batch or not.</p>
<p>In React 17 and earlier, <strong>only updates inside React event handlers are batched by default</strong>. There is an unstable API to force batching outside of event handlers for rare cases when you need it.</p>
<p><strong>Starting from React 18, React <a href="https://reactjs.org/blog/2022/03/29/react-v18.html#new-feature-automatic-batching" rel="noreferrer">batches all updates by default</a>.</strong> Note that React will never batch updates from two different intentional events (like clicks or typing) so, for example, two different button clicks will never get batched. In the rare cases that batching is not desirable, you can use <a href="https://reactjs.org/docs/react-dom.html#flushsync" rel="noreferrer"><code>flushSync</code></a>.</p>
<hr />
<p>The key to understanding this is that <strong>no matter how many <code>setState()</code> calls in how many components you do <em>inside a React event handler</em>, they will produce only a single re-render at the end of the event</strong>. This is crucial for good performance in large applications because if <code>Child</code> and <code>Parent</code> each call <code>setState()</code> when handling a click event, you don't want to re-render the <code>Child</code> twice.</p>
<p>In both of your examples, <code>setState()</code> calls happen inside a React event handler. Therefore they are always flushed together at the end of the event (and you don't see the intermediate state).</p>
<p>The updates are always <strong>shallowly merged in the order they occur</strong>. So if the first update is <code>{a: 10}</code>, the second is <code>{b: 20}</code>, and the third is <code>{a: 30}</code>, the rendered state will be <code>{a: 30, b: 20}</code>. The more recent update to the same state key (e.g. like <code>a</code> in my example) always "wins".</p>
<p>The <code>this.state</code> object is updated when we re-render the UI at the end of the batch. So if you need to update state based on a previous state (such as incrementing a counter), you should use the functional <code>setState(fn)</code> version that gives you the previous state, instead of reading from <code>this.state</code>. If you're curious about the reasoning for this, I explained it in depth <a href="https://github.com/facebook/react/issues/11527#issuecomment-360199710" rel="noreferrer">in this comment</a>.</p>
<hr />
<p>In your example, we wouldn't see the "intermediate state" because we are <strong>inside a React event handler</strong> where batching is enabled (because React "knows" when we're exiting that event).</p>
<p>However, both in React 17 and earlier versions, <strong>there was no batching by default outside of React event handlers</strong>. So if in your example we had an AJAX response handler instead of <code>handleClick</code>, each <code>setState()</code> would be processed immediately as it happens. In this case, yes, you <strong>would</strong> see an intermediate state in React 17 and earlier:</p>
<pre><code>promise.then(() => {
// We're not in an event handler, so these are flushed separately.
this.setState({a: true}); // Re-renders with {a: true, b: false }
this.setState({b: true}); // Re-renders with {a: true, b: true }
this.props.setParentState(); // Re-renders the parent
});
</code></pre>
<p>We realize it's inconvenient that <strong>the behavior is different depending on whether you're in an event handler or not</strong>. In React 18, this is no longer necessary, but before that, <strong>there was an API you can use to force batching</strong>:</p>
<pre><code>promise.then(() => {
// Forces batching
ReactDOM.unstable_batchedUpdates(() => {
this.setState({a: true}); // Doesn't re-render yet
this.setState({b: true}); // Doesn't re-render yet
this.props.setParentState(); // Doesn't re-render yet
});
// When we exit unstable_batchedUpdates, re-renders once
});
</code></pre>
<p>Internally React event handlers are all being wrapped in <code>unstable_batchedUpdates</code> which is why they're batched by default. Note that wrapping an update in <code>unstable_batchedUpdates</code> twice has no effect. The updates are flushed when we exit the outermost <code>unstable_batchedUpdates</code> call.</p>
<p>That API is "unstable" in the sense that we will eventually remove it in some major version after 18 (either 19 or further). You safely rely on it until React 18 if you need to force batching in some cases outside of React event handlers. With React 18, you can remove it because it doesn't have any effect anymore.</p>
<hr />
<p>To sum up, this is a confusing topic because React used to only batch inside event handlers by default. But the solution is not to <em>batch less</em>, it's to <em>batch more</em> by default. That's what we're doing in React 18.</p> |
6,647,177 | Set equal width of columns in table layout in Android | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2865497/xml-table-layout-two-equal-width-rows-filled-with-equally-width-buttons">XML Table layout? Two EQUAL-width rows filled with equally width buttons?</a> </p>
</blockquote>
<p>I am using <code>TableLayout</code> to show list of data in 4 columns. </p>
<p><strong><em>Problem description:</em></strong> </p>
<p>I am unable to set equal width of all 4 columns, which are in my <code>TableLayout</code>.
I am putting my layout code, which I am using...</p>
<pre><code><TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="0">
<TableRow>
<TextView android:text="table header1" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textSize="10dip" android:textStyle="bold"/>
<TextView android:text="table header2" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textSize="10dip" android:textStyle="bold"/>
<TextView android:text="table header3" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textSize="10dip" android:textStyle="bold"/>
<TextView android:text="table header4" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textSize="10dip" android:textStyle="bold"/>
</TableRow>
</TableLayout>
</code></pre>
<p><em>How should I rewrite this layout to show 4 columns with equal sizes?</em></p> | 6,647,228 | 2 | 1 | null | 2011-07-11 07:49:52.053 UTC | 29 | 2019-03-04 16:04:48.577 UTC | 2017-05-23 12:18:29.303 UTC | null | -1 | null | 550,966 | null | 1 | 83 | android|tablelayout | 138,243 | <p><a href="http://androidadvice.blogspot.com/2010/10/tablelayout-columns-equal-width.html">Try this.</a></p>
<p>It boils down to adding <code>android:stretchColumns="*"</code> to your <code>TableLayout</code> root and setting <code>android:layout_width="0dp"</code> to all the children in your <code>TableRow</code>s.</p>
<pre><code><TableLayout
android:stretchColumns="*" // Optionally use numbered list "0,1,2,3,..."
>
<TableRow
android:layout_width="0dp"
>
</code></pre> |
7,590,838 | How to find EOF in a string in java? | <p>I am working in school project. In that what they told is, I will be given a String which contains an actual program like....</p>
<blockquote>
<p>import java.io.*\npublic class A{\n...........EOF</p>
</blockquote>
<p>And My job is to find particular regular expressions in that String(Program).</p>
<p>Now My question is..</p>
<pre><code>void myFunc(String s)
{
while(s.charAt(i) != EOF) /*needed replacement for EOF*/
{
// Actual Code
}
}
</code></pre>
<p>In the above code, how to find whether EOF is reached in a string?</p> | 7,590,847 | 3 | 6 | null | 2011-09-28 23:30:17.373 UTC | 2 | 2015-02-06 03:04:21.527 UTC | null | null | null | null | 598,824 | null | 1 | 8 | java|string|eof | 47,151 | <p>There is no EOF character in a string. You just need to <a href="https://stackoverflow.com/questions/196830/what-is-the-easiest-best-most-correct-way-to-iterate-through-the-characters-of-a">iterate over the characters in the string</a>:</p>
<pre><code>for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//Process char
}
</code></pre> |
7,305,785 | Does C# have an Unsigned Double? | <p>I need to use an <em>unsigned double</em> but it turns out C# does not provide such a type.</p>
<p>Does anyone know why?</p> | 7,305,827 | 4 | 3 | null | 2011-09-05 08:53:02.927 UTC | null | 2020-01-09 10:18:22.393 UTC | 2020-01-09 10:18:22.393 UTC | null | 743 | null | 62,898 | null | 1 | 39 | c#|double|unsigned | 32,082 | <p>Floating point numbers are simply the implementation of the IEEE 754 spec. There is no such thing as an unsigned double there as far as i know. </p>
<p><a href="http://en.wikipedia.org/wiki/IEEE_754-2008" rel="noreferrer">http://en.wikipedia.org/wiki/IEEE_754-2008</a></p>
<p>Why do you need an unsigned floating point number?</p> |
7,652,749 | 'object' does not contain a definition for 'X' | <p>I had this problem once before and didn't resolve it. I have a list (generated in an MVC3 controller):</p>
<pre><code>ViewBag.Languages = db.Languages
.Select(x => new { x.Name, x.EnglishName, x.Id })
.ToList();
</code></pre>
<p>and on my page (Razor) I try to iterate through it:</p>
<pre><code>foreach (var o in ViewBag.Languages)
{
string img = "Lang/" + o.EnglishName + ".png";
@* work *@
}
</code></pre>
<p>but the reference to <code>o.EnglishName</code> fails with the error:</p>
<blockquote>
<p>'object' does not contain a definition for 'EnglishName'</p>
</blockquote>
<p>though the curious thing is that if I type into the Immediate Window (whilst debugging):</p>
<blockquote>
<pre><code>o
{ Name = བོད་སྐད་, EnglishName = Tibetan, Id = 31 }
EnglishName: "Tibetan"
Id: 31
Name: "བོད་སྐད་"
</code></pre>
</blockquote>
<p>so obviously the field is there. What is my problem here?</p> | 7,652,765 | 4 | 1 | null | 2011-10-04 18:58:35.343 UTC | 7 | 2016-11-14 11:45:36.62 UTC | null | null | null | null | 709,223 | null | 1 | 42 | c#|asp.net-mvc|razor | 55,044 | <p>You are using an anonymous object here:</p>
<pre><code>ViewBag.Languages = db.Languages
.Select(x => new { x.Name, x.EnglishName, x.Id })
.ToList();
</code></pre>
<p>Anonymous objects are emitted as <code>internal</code> by the compiler. The Razor views are automatically compiled into a separate assembly by the ASP.NET runtime. This means that you cannot access any anonymous objects generated in your controllers.</p>
<p>So in order to fix your issue you could define a view model:</p>
<pre><code>public class LanguageViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string EnglishName { get; set; }
}
</code></pre>
<p>and then in your controller use this view model:</p>
<pre><code>ViewBag.Languages = db.Languages
.Select(x => new LanguageViewModel
{
Name = x.Name,
EnglishName = x.EnglishName,
Id = x.Id
})
.ToList();
</code></pre>
<p>And now that you have a view model the next improvement to your code is of course to get rid of this crap of <code>ViewBag</code> that I am sick of seeing and simply use view models and strong typing:</p>
<pre><code>public ActionResult Foo()
{
var model = db
.Languages
.Select(x => new LanguageViewModel
{
Name = x.Name,
EnglishName = x.EnglishName,
Id = x.Id
})
.ToList();
return View(model);
}
</code></pre>
<p>and then of course have a strongly typed view:</p>
<pre><code>@model IEnumerable<LanguageViewModel>
@Html.DisplayForModel()
</code></pre>
<p>and then define the corresponding display template which will automatically be rendered by the ASP.NET MVC engine for each element of the view model so that you don't even need to write a single foreach in your views (<code>~/Views/Shared/DisplayTemplates/LanguageViewModel.cshtml</code>):</p>
<pre><code>@model LanguageViewModel
... generate the image or whatever you was attempting to do in the first place
</code></pre> |
24,150,359 | Is [UIScreen mainScreen].bounds.size becoming orientation-dependent in iOS8? | <p>I ran the following code in both iOS 7 and iOS 8:</p>
<pre><code>UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
BOOL landscape = (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight);
NSLog(@"Currently landscape: %@, width: %.2f, height: %.2f",
(landscape ? @"Yes" : @"No"),
[[UIScreen mainScreen] bounds].size.width,
[[UIScreen mainScreen] bounds].size.height);
</code></pre>
<p>The following is the result from iOS 8:</p>
<pre><code>Currently landscape: No, width: 320.00, height: 568.00
Currently landscape: Yes, width: 568.00, height: 320.00
</code></pre>
<p>Comparing to the result in iOS 7:</p>
<pre><code>Currently landscape: No, width: 320.00, height: 568.00
Currently landscape: Yes, width: 320.00, height: 568.00
</code></pre>
<p>Is there any documentation specifying this change? Or is it a temporary bug in iOS 8 APIs?</p> | 24,153,540 | 18 | 1 | null | 2014-06-10 20:35:14.483 UTC | 80 | 2017-11-29 15:08:18.227 UTC | 2017-06-07 14:04:05.303 UTC | null | 4,761,607 | null | 3,155,503 | null | 1 | 184 | ios|ios8|orientation|uiinterfaceorientation|uiscreen | 88,812 | <p>Yes, it's orientation-dependent in iOS8, not a bug. You could review session 214 from WWDC 2014 for more info: <a href="https://developer.apple.com/videos/wwdc/2014/#214">"View Controller Advancements in iOS 8"</a></p>
<p>Quote from the presentation:</p>
<p>UIScreen is now interface oriented:</p>
<ul>
<li>[UIScreen bounds] now interface-oriented</li>
<li>[UIScreen applicationFrame] now interface-oriented</li>
<li>Status bar frame notifications are interface-oriented</li>
<li>Keyboard frame notifications are interface-oriented</li>
</ul> |
7,699,076 | Where did the class name 'hero' come from in CSS? | <p>A widely adopted CSS naming practice is to use <code>hero</code> as the class name applied to a site's main banner.</p>
<p>Where did this naming convention come from, and is it a reference to something in particular?</p> | 7,699,122 | 1 | 0 | null | 2011-10-08 18:58:53.95 UTC | 7 | 2021-05-31 07:56:32.55 UTC | 2012-12-19 17:54:44.833 UTC | null | 276,959 | null | 276,959 | null | 1 | 46 | css|class|naming-conventions | 17,078 | <p>'Hero' is a word beloved by marketing people that describes the main focal point of an advertisement etc.</p>
<p><a href="https://unbounce.com/conversion-glossary/definition/hero-shot/#:%7E:text=Definition,benefits%20and%20context%20of%20use" rel="nofollow noreferrer">https://unbounce.com/conversion-glossary/definition/hero-shot/#:~:text=Definition,benefits%20and%20context%20of%20use</a>.</p> |
21,506,128 | Best way to combine probabilistic classifiers in scikit-learn | <p>I have a logistic regression and a random forest and I'd like to combine them (ensemble) for the final classification probability calculation by taking an average.</p>
<p>Is there a built-in way to do this in sci-kit learn? Some way where I can use the ensemble of the two as a classifier itself? Or would I need to roll my own classifier?</p> | 21,544,196 | 4 | 3 | null | 2014-02-02 01:54:06.103 UTC | 16 | 2019-12-10 07:00:11.45 UTC | 2014-02-04 04:53:22.4 UTC | null | 1,507,844 | null | 1,507,844 | null | 1 | 25 | python|machine-learning|classification|scikit-learn | 19,679 | <p>NOTE: The <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.VotingClassifier.html#sklearn.ensemble.VotingClassifier" rel="noreferrer">scikit-learn Voting Classifier</a> is probably the best way to do this now</p>
<hr>
<p>OLD ANSWER:</p>
<p>For what it's worth I ended up doing this as follows:</p>
<pre><code>class EnsembleClassifier(BaseEstimator, ClassifierMixin):
def __init__(self, classifiers=None):
self.classifiers = classifiers
def fit(self, X, y):
for classifier in self.classifiers:
classifier.fit(X, y)
def predict_proba(self, X):
self.predictions_ = list()
for classifier in self.classifiers:
self.predictions_.append(classifier.predict_proba(X))
return np.mean(self.predictions_, axis=0)
</code></pre> |
1,528,444 | Accessing scoped proxy beans within Threads of | <p>I have a web application running in tomcat where I'm using a ThreadPool (Java 5 ExecutorService) to run IO intensive operations in parallel to improve performance. I would like to have some of the beans used within each pooled thread be in the request scope, but the Threads in the ThreadPool do not have access to the spring context and get a proxy failure. Any ideas on how to make the spring context available to the threads in the ThreadPool to resolve the proxy failures?</p>
<p>I'm guessing there must be a way to register/unregister each thread in the ThreadPool with spring for each task, but haven't had any luck finding how to do this.</p>
<p>Thanks!</p> | 1,837,084 | 4 | 0 | null | 2009-10-06 22:32:32.797 UTC | 15 | 2012-04-16 03:39:12.907 UTC | null | null | null | null | 110,288 | null | 1 | 16 | java|spring|spring-mvc|threadpool | 10,620 | <p>I am using the following super class for my tasks that need to have access to request scope. Basically you can just extend it and implement your logic in onRun() method.</p>
<pre><code>import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
/**
* @author Eugene Kuleshov
*/
public abstract class RequestAwareRunnable implements Runnable {
private final RequestAttributes requestAttributes;
private Thread thread;
public RequestAwareRunnable() {
this.requestAttributes = RequestContextHolder.getRequestAttributes();
this.thread = Thread.currentThread();
}
public void run() {
try {
RequestContextHolder.setRequestAttributes(requestAttributes);
onRun();
} finally {
if (Thread.currentThread() != thread) {
RequestContextHolder.resetRequestAttributes();
}
thread = null;
}
}
protected abstract void onRun();
}
</code></pre> |
2,150,265 | Retrieve an Image stored as BLOB on a MYSQL DB | <p>I'm trying to create a PDF based on the information that resides on a database. Know I need to retrieve a TIFF image that is stored as a BLOB on a mysql database from Java. And I don't know how to do it. The examples I've found shows how to retrieve it and save it as a File (but on disk) and I needed to reside on memory.</p>
<p>Table name: IMAGENES_REGISTROS</p>
<p>BLOB Field name: IMAGEN</p>
<p>Any Ideas?</p> | 2,150,375 | 4 | 2 | null | 2010-01-27 21:09:14.66 UTC | 14 | 2018-04-27 10:41:40.37 UTC | 2010-01-28 03:45:46.057 UTC | null | 203,907 | null | 98,644 | null | 1 | 16 | java|mysql|image|jdbc|blob | 89,070 | <p>On your <code>ResultSet</code> call: </p>
<pre><code>Blob imageBlob = resultSet.getBlob(yourBlobColumnIndex);
InputStream binaryStream = imageBlob.getBinaryStream(0, imageBlob.length());
</code></pre>
<p>Alternatively, you can call:</p>
<pre><code>byte[] imageBytes = imageBlob.getBytes(1, (int) imageBlob.length());
</code></pre>
<p>As BalusC noted in his comment, you'd better use:</p>
<pre><code>InputStream binaryStream = resultSet.getBinaryStream(yourBlobColumnIndex);
</code></pre>
<p>And then the code depends on how you are going to read and embed the image.</p> |
2,214,162 | F# code organization: types & modules | <p>How do you decide between writing a function inside a module or as a static member of some type?</p>
<p>For example, in the source code of F#, there are lots of types that are defined along with a equally named module, as follows:</p>
<pre><code>type MyType = // ...
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module MyType = // ...
</code></pre>
<p>Why don't you simply define the operations as static members of type MyType?</p> | 2,214,347 | 4 | 0 | null | 2010-02-06 18:27:29.973 UTC | 11 | 2017-07-14 21:26:42.883 UTC | null | null | null | null | 150,339 | null | 1 | 24 | f#|module|code-organization|static-members | 4,825 | <p>Here are some notes about the technical distinctions.</p>
<p><strong>Modules can be 'open'ed</strong> (unless they have RequireQualifiedAccessAttribute). That is, if you put functions (<code>F</code> and <code>G</code>) in a module (<code>M</code>), then you can write</p>
<pre><code>open M
... F x ... G x ...
</code></pre>
<p>whereas with a static method, you'd always write</p>
<pre><code>... M.F x ... M.G x ...
</code></pre>
<p><strong>Module functions cannot be overloaded</strong>. Functions in a module are let-bound, and let-bound functions do not permit overloading. If you want to be able to call both</p>
<pre><code>X.F(someInt)
X.F(someInt, someString)
</code></pre>
<p>you must use <code>member</code>s of a type, which only work with 'qualified' calls (e.g. <code>type.StaticMember(...)</code> or <code>object.InstanceMember(...)</code>).</p>
<p>(Are there other differences? I can't recall.)</p>
<p>Those are the main technical differences that influence the choice of one over the other.</p>
<p>Additionally, there is some tendency in the F# runtime (FSharp.Core.dll) to use modules only for F#-specific types (that are typically not used when doing interop with other .Net languages) and static methods for APIs that are more language-neutral. For example, all the functions with curried parameters appear in modules (curried functions are non-trivial to call from other languages).</p> |
1,518,263 | PayPal SOAP and NVP | <p>I am new to PayPal and i want to know which is batter way to implement PayPal, SOAP or NVP API.</p>
<p>And what is the major difference between these two???</p> | 2,620,645 | 4 | 0 | null | 2009-10-05 04:26:06.163 UTC | 5 | 2017-10-26 07:57:54.137 UTC | null | null | null | null | 112,023 | null | 1 | 33 | soap|paypal|paypal-soap|paypal-nvp|nvp | 19,438 | <p>I would recommend using the NVP (Name-value pair, basically POST with data) API over the SOAP API. NVP should be significantly lighter weight than SOAP. There are <a href="https://stackoverflow.com/questions/686634/soap-whats-the-point">a few questions</a> already <a href="https://stackoverflow.com/questions/676123/why-is-http-soap-considered-to-be-thick">on SO</a> that <a href="https://stackoverflow.com/questions/76595/soap-or-rest/77018#77018">complain about SOAP</a>. I just was trying to figure out which to use and came upon those. Hope that helps.</p>
<p>Also, here's how <a href="https://www.paypal.com/IntegrationCenter/ic_nvp.html" rel="noreferrer">PayPal describes the NVP API</a>:</p>
<blockquote>
<p>The PayPal Name-Value Pair API (NVP API) enables you to leverage the functionality of the PayPal API by simply sending an HTTP request to PayPal and specifying request parameters using name-value pairs. The NVP API is <strong>a lightweight alternative</strong> to the <a href="https://www.paypal.com/IntegrationCenter/ic_sdk-resource.html" rel="noreferrer">PayPal SOAP API</a> and provides access to the <strong>same set of functionality</strong> as the SOAP API.</p>
</blockquote>
<p><em>Emphasis my own.</em></p> |
1,631,396 | What is an xs:NCName type and when should it be used? | <p>I ran one of my xml files through a schema generator and everything generated was what was expected, with the exception of one node:</p>
<pre><code><xs:element name="office" type="xs:NCName"/>
</code></pre>
<p>What exactly is <code>xs:NCName</code>? And why would one use it, rather <code>xs:string</code>?</p> | 1,631,480 | 4 | 0 | null | 2009-10-27 14:58:51.427 UTC | 12 | 2013-06-05 20:17:12.03 UTC | 2011-11-28 17:17:39.067 UTC | null | 420,851 | user189320 | null | null | 1 | 101 | xml|xsd|xml-namespaces | 90,721 | <p><a href="http://www.w3.org/TR/xmlschema-2/#NCName" rel="noreferrer">NCName</a> is non-colonized name e.g. "name". Compared to QName which is qualified name e.g. "ns:name". If your names are not supposed to be qualified by different namespaces, then they are NCNames.</p>
<p>xs:string puts no restrictions on your names at all, but xs:NCName basically disallows ":" to appear in the string.</p> |
36,652,675 | java.security.UnrecoverableKeyException: Failed to obtain information about private key | <p>I have the following lines to get the private key from key store on Android</p>
<pre><code>KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
// generating key pair code omitted
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) this.keyStore.getEntry("alias", null);
</code></pre>
<p>Everything works fine except that when the OS upgrades from Android 5.1.1 to Android 6.0.1, the 3rd line will throw <code>java.security.UnrecoverableKeyException: Failed to obtain information about private key</code> for very first execution. But it will work fine again afterward. Now my workaround is to execute the line for 2 times. At the same time, I am also wondering if there is better way to avoid the exception.</p>
<h2>Update</h2>
<p>The exception trace</p>
<pre><code>W/System.err﹕ java.security.UnrecoverableKeyException: Failed to obtain information about private key
W/System.err﹕ at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:217)
W/System.err﹕ at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:253)
W/System.err﹕ at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(AndroidKeyStoreProvider.java:263)
W/System.err﹕ at android.security.keystore.AndroidKeyStoreSpi.engineGetKey(AndroidKeyStoreSpi.java:93)
W/System.err﹕ at java.security.KeyStoreSpi.engineGetEntry(KeyStoreSpi.java:372)
W/System.err﹕ at java.security.KeyStore.getEntry(KeyStore.java:645)
W/System.err﹕ at com.example.keystoretest.MainActivity.onCreate(MainActivity.java:113)
W/System.err﹕ at android.app.Activity.performCreate(Activity.java:6251)
W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
W/System.err﹕ at android.app.ActivityThread.-wrap11(ActivityThread.java)
W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err﹕ at android.os.Looper.loop(Looper.java:148)
W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5417)
W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
W/System.err﹕ Caused by: android.security.KeyStoreException: Invalid key blob
W/System.err﹕ at android.security.KeyStore.getKeyStoreException(KeyStore.java:632)
W/System.err﹕ at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:218)
W/System.err﹕ ... 18 more
</code></pre> | 36,747,600 | 3 | 7 | null | 2016-04-15 16:46:02.297 UTC | 10 | 2020-09-06 05:33:16.053 UTC | 2016-04-20 22:54:04.53 UTC | null | 691,626 | null | 691,626 | null | 1 | 31 | java|android|keystore|private-key|java-security | 15,544 | <h2>When this error happens and why?</h2>
<p><strong>Ans:</strong> When loading Android keys and storing public key from Keystore, this error may happen if the state is locked or uninitialized.</p>
<h2>Error generating portion code is given below:</h2>
<pre><code>@NonNull
public static AndroidKeyStorePublicKey loadAndroidKeyStorePublicKeyFromKeystore(
@NonNull KeyStore keyStore, @NonNull String privateKeyAlias)
throws UnrecoverableKeyException {
KeyCharacteristics keyCharacteristics = new KeyCharacteristics();
int errorCode = keyStore.getKeyCharacteristics(privateKeyAlias, null,
null, keyCharacteristics);
if (errorCode != KeyStore.NO_ERROR) {
throw (UnrecoverableKeyException) new UnrecoverableKeyException(
"Failed to obtain information about private key")
.initCause(KeyStore.getKeyStoreException(errorCode)); // this exception is generated
}
......
......
......
}
</code></pre>
<p>KeyStore has 10 response code. They are</p>
<pre><code>// ResponseCodes
NO_ERROR = 1;
LOCKED = 2;
UNINITIALIZED = 3;
SYSTEM_ERROR = 4;
PROTOCOL_ERROR = 5;
PERMISSION_DENIED = 6;
KEY_NOT_FOUND = 7;
VALUE_CORRUPTED = 8;
UNDEFINED_ACTION = 9;
WRONG_PASSWORD = 10;
</code></pre>
<blockquote>
<p>KeyStore has 3 states. They are UNLOCKED, LOCKED, UNINITIALIZED</p>
<p>NO_ERROR is only happened when the state is UNLOCKED. For your
upgrading case the state is LOCKED or UNINITIALIZED for first time, so
the error is happened only once.</p>
</blockquote>
<h2>State Checking code is given below:</h2>
<pre><code>public State state() {
execute('t');
switch (mError) {
case NO_ERROR:
return State.UNLOCKED;
case LOCKED:
return State.LOCKED;
case UNINITIALIZED:
return State.UNINITIALIZED;
default:
throw new AssertionError(mError);
}
}
</code></pre>
<p>Resource Link:</p>
<ol>
<li><a href="https://android.googlesource.com/platform/frameworks/base/+/android-6.0.0_r25/keystore/java/android/security/keystore/AndroidKeyStoreProvider.java" rel="noreferrer">AndroidKeyStoreProvider java class</a> </li>
<li><a href="https://github.com/nelenkov/android-keystore/blob/master/src/org/nick/androidkeystore/android/security/KeyStore.java" rel="noreferrer">KeyStore java class</a></li>
</ol>
<hr>
<h2>UPDATE:</h2>
<p>From your error log, it is now clear that</p>
<pre><code>W/System.err﹕ Caused by: android.security.KeyStoreException: Invalid key blob
</code></pre>
<p>this is the main issue which is caused when user tries to UNLOCK from LOCK/UNINITIALIZED. It is by default defined as 30 secs for timing. <strong>This problem is it's API related implementation issue.</strong></p>
<pre><code>/**
* If the user has unlocked the device Within the last this number of seconds,
* it can be considered as an authenticator.
*/
private static final int AUTHENTICATION_DURATION_SECONDS = 30;
</code></pre>
<p>For encryption/decryption some data with the generated key only works if the user has just authenticated via device credentials. The error occurs from</p>
<pre><code>// Try encrypting something, it will only work if the user authenticated within
// the last AUTHENTICATION_DURATION_SECONDS seconds.
cipher.init(Cipher.ENCRYPT_MODE, secretKey); // error is generated from here.
</code></pre>
<p>Actual error is thrown from here. Your error is generated from <code>InvalidKeyException</code>.</p>
<h2>Solution:</h2>
<p>You have to remove the <code>InvalidKeyException</code> class from the catch argument. This will still allow you to check for <code>InvalidKeyException</code>. After checking you have to try for second time with code so that the problem is not shown in eye but doing 2 times checking it may solve your issue. I have not tested the code but should be like below:</p>
<pre><code>try {
....
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) this.keyStore.getEntry("alias", null);
....
} catch (final Exception e) {
e.printStackTrace();
if (e instanceof InvalidKeyException) { // bypass InvalidKeyException
.......
// You can again call the method and make a counter for deadlock situation or implement your own code according to your situation
if (retry) {
keyStore.deleteEntry(keyName);
return getCypher(keyName, false);
} else {
throw e;
}
}
}
</code></pre>
<h2>Resource Link:</h2>
<ol>
<li><a href="https://github.com/googlesamples/android-ConfirmCredential/blob/master/Application/src/main/java/com/example/android/confirmcredential/MainActivity.java#L128" rel="noreferrer">MainActivity.java</a> </li>
<li><a href="https://stackoverflow.com/questions/36488219/android-security-keystoreexception-invalid-key-blob">android.security.KeyStoreException: Invalid key blob</a></li>
</ol> |
36,421,287 | Laravel 5.2: Unable to locate factory with name [default] | <p>I want to seed database
when I use this </p>
<pre><code> public function run()
{
$users = factory(app\User::class, 3)->create();
}
</code></pre>
<p>Add three user in database but when I use this </p>
<pre><code> public function run()
{
$Comment= factory(app\Comment::class, 3)->create();
}
</code></pre>
<p>Show me error</p>
<blockquote>
<p>[InvalidArgumentException]<br>
Unable to locate factory with name [default] [app\Comment].</p>
</blockquote> | 36,422,350 | 17 | 8 | null | 2016-04-05 08:42:44.29 UTC | 6 | 2022-04-28 22:51:33.123 UTC | 2016-04-05 09:20:14.007 UTC | null | 3,977,560 | null | 3,977,560 | null | 1 | 54 | php|laravel|laravel-5|laravel-5.2|laravel-seeding | 75,658 | <p>By default the laravel installation comes with this code in the <code>database/factories/ModelFactory.php</code> File.</p>
<pre><code>$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => bcrypt(str_random(10)),
'remember_token' => str_random(10),
];
});
</code></pre>
<p>So you need to define a factory Model before you use it to seed database.
This just uses an instance of <a href="https://packagist.org/packages/fzaninotto/faker" rel="noreferrer">Faker Library</a> which is used to generate fake Data for seeding the database to perform testing.</p>
<p>Make sure You have added a similar Modal Factory for the Comments Model. </p>
<p>So your Comments Model Factory will be something like this : </p>
<pre><code>$factory->define(App\Comment::class, function (Faker\Generator $faker) {
return [
'comment' => $faker->sentence,
// Any other Fields in your Comments Model
];
});
</code></pre> |
7,381,201 | JavaScript: should I worry about memory leaks in 2011? | <p>The topic of memory leaks in JavaScript is not brought up often. However, I stumbled upon <a href="http://www.ibm.com/developerworks/web/library/wa-memleak/" rel="noreferrer">this article</a>, written in 2007. The authors state:</p>
<blockquote>
<p>Internet Explorer and Mozilla Firefox are the two Web browsers most
commonly associated with memory leaks in JavaScript.</p>
</blockquote>
<p>Should I still be worrying about JavaScript memory leaks in 2011? If so, what should I be careful about?</p> | 7,381,597 | 5 | 8 | null | 2011-09-11 20:58:44.923 UTC | 16 | 2017-02-14 06:01:23.817 UTC | null | null | null | null | 707,381 | null | 1 | 23 | javascript|memory-leaks | 1,958 | <p>A good javascript developer would be aware of various design patterns that can lead to memory leaks and you'd avoid coding anything that could turn in to a leak in pretty much all the pages you code.</p>
<p>For example, keeping a reference to any DOM object in a javascript variable will keep that DOM object alive in memory even if it's long since been removed from the DOM and you intended for it to be freed.</p>
<p>Practically speaking, leaks are only significant in some circumstances. Here's where I specifically worry about them:</p>
<ol>
<li>Anything I'm doing repetitively on a timer, particularly if it can be left running for a long time. For example, if you have a slideshow that might just loop forever, you have to make absolutely sure that nothing in the slideshow is an accumulating leak of either JS or DOM objects.</li>
<li>A web page that works like an app and the user may stay on the same page for a long time, interacting with the page, doing ajax calls, etc... For example a web mail app might be open and on the same actual browser document for a very long time doing lots and lots of user and server interactions.</li>
<li>A web page that regularly creates and destroys lots of DOM elements like something that regularly uses ajax to fetch a bunch of new HTML.</li>
</ol>
<p>Places where I don't really worry about leaks:</p>
<ol>
<li>A web page that doesn't have a long running set of interactions the user can do.</li>
<li>A web page that doesn't stay on screen very long before some other page is loaded or this page is reloaded.</li>
</ol>
<p>Some of the key things I keep an eye out for. </p>
<ol>
<li>Any lasting JS variables or properties that contain references to DOM elements when DOM elements are being created/destroyed.</li>
<li>Any properties of a DOM object that contain references to other DOM objects or references to JS objects that contain reference to other DOM objects (this can create circular references and cross references between JS/DOM that some older browsers have trouble freeing).</li>
<li>Any large data structures that I load for temporary use. I make sure that no references to these large data structures are every kept around.</li>
<li>Any data caches. Make sure nothing really large gets cached that you don't want cached. Make sure all caches that get used repeatedly don't accumulate forever and have some sort of aging mechanism to get rid of old objects.</li>
</ol> |
7,681,024 | Negative numbers are stored as 2's complement in memory, how does the CPU know if it's negative or positive? | <p>-1 can be represented in 4 bit binary as (2's complement) 1111 </p>
<p>15 is also represented as 1111.</p>
<p>So, how does CPU differentiate between 15 and -1 when it gets values from memory? </p> | 7,681,094 | 5 | 0 | null | 2011-10-06 22:05:06.087 UTC | 11 | 2022-09-09 10:23:48.43 UTC | 2020-12-08 15:47:28.003 UTC | null | 224,132 | null | 805,796 | null | 1 | 24 | binary|cpu-architecture|numeric|sign|twos-complement | 16,334 | <p>The CPU doesn't care whether a byte holds -1 or 15 when it moves it from one place to another. There's no such thing as a "signed move" (to a location of the same size - there is a signed move for larger or smaller destinations).</p>
<p>The CPU only cares about the representation when it does arithmetic on the byte. The CPU knows whether to do signed or unsigned arithmetic according to the op-code that you (or the compiler on your behalf) chose.</p> |
14,230,602 | Git error when pushing: Object from LD_PRELOAD cannot be preloaded | <p>This has something that's just started happening recently, although I'm not sure what I could have done to trigger it.</p>
<p>Whenever I run a <code>git push</code> I get the following error:</p>
<pre><code>ERROR: ld.so: object '/lib/liblm.so' from LD_PRELOAD cannot be preloaded: ignored.
</code></pre>
<p>The push does procede after that and works correctly.</p>
<p>I've updated to the latest version of Git (via homebrew) and that didn't solve it.</p>
<p><strong>EDIT:</strong> Apologies, I wasn't very clear exactly what I was asking. I guess my question is two fold:</p>
<ul>
<li>Out of interest, what is causing the error?</li>
<li>How can I fix the error so it goes away? It doesn't seem to be causing any problems that I can see, but it's a bit irritating!</li>
</ul> | 14,230,784 | 1 | 15 | null | 2013-01-09 07:57:29.447 UTC | 2 | 2013-01-09 09:38:09.443 UTC | 2013-01-09 09:38:09.443 UTC | null | 177,414 | null | 177,414 | null | 1 | 33 | git | 11,458 | <p>I have to assume it's a server mis-configuration. The message is originating from the GitHub server. So rest assured it has nothing to do with your git.</p>
<p>For anyone who cares, here's a good SO explanation for LD_PRELOAD: <a href="https://stackoverflow.com/a/426260/591166">https://stackoverflow.com/a/426260/591166</a></p>
<p><strong>Update</strong>: GitHub has apparently fixed the issue.</p> |
13,944,078 | Concatenate rows of a data frame | <p>I would like to take a data frame with characters and numbers, and concatenate all of the elements of the each row into a single string, which would be stored as a single element in a vector. As an example, I make a data frame of letters and numbers, and then I would like to concatenate the first row via the paste function, and hopefully return the value "A1"</p>
<pre><code>df <- data.frame(letters = LETTERS[1:5], numbers = 1:5)
df
## letters numbers
## 1 A 1
## 2 B 2
## 3 C 3
## 4 D 4
## 5 E 5
paste(df[1,], sep =".")
## [1] "1" "1"
</code></pre>
<p>So paste is converting each element of the row into an integer that corresponds to the 'index of the corresponding level' as if it were a factor, and it keeps it a vector of length two. (I know/believe that factors that are coerced to be characters behave in this way, but as R is not storing df[1,] as a factor at all (tested by is.factor(), I can't verify that it is actually an index for a level)</p>
<pre><code>is.factor(df[1,])
## [1] FALSE
is.vector(df[1,])
## [1] FALSE
</code></pre>
<p>So if it is not a vector then it makes sense that it is behaving oddly, but I can't coerce it into a vector</p>
<pre><code>> is.vector(as.vector(df[1,]))
[1] FALSE
</code></pre>
<p>Using <code>as.character</code> did not seem to help in my attempts</p>
<p>Can anyone explain this behavior?</p> | 13,944,315 | 4 | 1 | null | 2012-12-19 01:07:34.68 UTC | 7 | 2021-12-15 22:35:43.293 UTC | 2018-01-19 09:07:54.483 UTC | null | 680,068 | null | 1,599,501 | null | 1 | 45 | r|vector|concatenation|paste|r-factor | 98,850 | <p>While others have focused on why your code isn't working and how to improve it, I'm going to try and focus more on getting the result you want. From your description, it seems you can readily achieve what you want using paste:</p>
<pre><code>df <- data.frame(letters = LETTERS[1:5], numbers = 1:5, stringsAsFactors=FALSE)
paste(df$letters, df$numbers, sep=""))
## [1] "A1" "B2" "C3" "D4" "E5"
</code></pre>
<p>You can change <code>df$letters</code> to character using <code>df$letters <- as.character(df$letters)</code> if you don't want to use the <code>stringsAsFactors</code> argument.</p>
<p>But let's assume that's not what you want. Let's assume you have hundreds of columns and you want to paste them all together. We can do that with your minimal example too:</p>
<pre><code>df_args <- c(df, sep="")
do.call(paste, df_args)
## [1] "A1" "B2" "C3" "D4" "E5"
</code></pre>
<h3>EDIT: Alternative method and explanation:</h3>
<p>I realised the problem you're having is a combination of the fact that you're using a factor and that you're using the <code>sep</code> argument instead of <code>collapse</code> (as @adibender picked up). The difference is that <code>sep</code> gives the separator between two separate vectors and <code>collapse</code> gives separators within a vector. When you use <code>df[1,]</code>, you supply a single vector to <code>paste</code> and hence you must use the <code>collapse</code> argument. Using your idea of getting every row and concatenating them, the following line of code will do exactly what you want:</p>
<pre><code>apply(df, 1, paste, collapse="")
</code></pre>
<p>Ok, now for the explanations:</p>
<p><strong>Why won't <code>as.list</code> work?</strong></p>
<p><code>as.list</code> converts an object to a list. So it does work. It will convert your dataframe to a list and subsequently ignore the <code>sep=""</code> argument. <code>c</code> combines objects together. Technically, a dataframe is just a list where every column is an element and all elements have to have the same length. So when I combine it with <code>sep=""</code>, it just becomes a regular list with the columns of the dataframe as elements.</p>
<p><strong>Why use <code>do.call</code>?</strong></p>
<p><code>do.call</code> allows you to call a function using a named list as its arguments. You can't just throw the list straight into <code>paste</code>, because it doesn't like dataframes. It's designed for concatenating vectors. So remember that <code>dfargs</code> is a list containing a vector of letters, a vector of numbers and sep which is a length 1 vector containing only "". When I use <code>do.call</code>, the resulting paste function is essentially <code>paste(letters, numbers, sep)</code>.<br>
But what if my original dataframe had columns <code>"letters", "numbers", "squigs", "blargs"</code> after which I added the separator like I did before? Then the paste function through <code>do.call</code> would look like:</p>
<pre><code>paste(letters, numbers, squigs, blargs, sep)
</code></pre>
<p>So you see it works for any number of columns.</p> |
14,035,090 | How to get existing fragments when using FragmentPagerAdapter | <p>I have problem making my fragments communicating with each other through the <code>Activity</code>, which is using the <code>FragmentPagerAdapter</code>, as a helper class that implements the management of tabs and all details of connecting a <code>ViewPager</code> with associated <code>TabHost</code>. I have implemented <code>FragmentPagerAdapter</code> just as same as it is provided by the Android sample project <em>Support4Demos</em>.</p>
<p>The main question is how can I get particular fragment from <code>FragmentManager</code> when I don't have neither Id or Tag? <code>FragmentPagerAdapter</code> is creating the fragments and auto generating the Id and Tags.</p> | 29,269,509 | 14 | 4 | null | 2012-12-26 01:07:56.177 UTC | 57 | 2022-05-04 00:04:55.46 UTC | 2014-12-28 00:24:28.817 UTC | null | 212,862 | null | 1,565,829 | null | 1 | 111 | android|android-fragments|fragmentpageradapter | 90,977 | <h2>Summary of the problem</h2>
<p><em>Note: In this answer I'm going to reference <code>FragmentPagerAdapter</code> and its source code. But the general solution should also apply to <code>FragmentStatePagerAdapter</code>.</em></p>
<p>If you're reading this you probably already know that <code>FragmentPagerAdapter</code>/<code>FragmentStatePagerAdapter</code> is meant to create <code>Fragments</code> for your <code>ViewPager</code>, but upon Activity recreation (whether from a device rotation or the system killing your App to regain memory) these <code>Fragments</code> won't be created again, but instead their <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.2_r1/android/support/v4/app/FragmentPagerAdapter.java?av=f#90"><strong>instances retrieved from the <code>FragmentManager</code></strong></a>. Now say your <code>Activity</code> needs to get a reference to these <code>Fragments</code> to do work on them. You don't have an <code>id</code> or <code>tag</code> for these created <code>Fragments</code> because <code>FragmentPagerAdapter</code> <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.2_r1/android/support/v4/app/FragmentPagerAdapter.java?av=f#100"><strong>set them internally</strong></a>. So the problem is how to get a reference to them without that information...</p>
<h2>Problem with current solutions: relying on internal code</h2>
<p>A lot of the solutions I've seen on this and similar questions rely on getting a reference to the existing <code>Fragment</code> by calling <code>FragmentManager.findFragmentByTag()</code> and mimicking the <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.2_r1/android/support/v4/app/FragmentPagerAdapter.java?av=f#173"><strong>internally created tag: <code>"android:switcher:" + viewId + ":" + id</code></strong></a>. The problem with this is that you're relying on internal source code, which as we all know is not guaranteed to remain the same forever. The Android engineers at Google could easily decide to change the <code>tag</code> structure which would break your code leaving you unable to find a reference to the existing <code>Fragments</code>.</p>
<h2>Alternate solution without relying on internal <code>tag</code></h2>
<p>Here's a simple example of how to get a reference to the <code>Fragments</code> returned by <code>FragmentPagerAdapter</code> that doesn't rely on the internal <code>tags</code> set on the <code>Fragments</code>. The key is to override <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.2_r1/android/support/v4/app/FragmentPagerAdapter.java?av=f#83"><strong><code>instantiateItem()</code></strong></a> and save references in there <em>instead</em> of in <code>getItem()</code>.</p>
<pre><code>public class SomeActivity extends Activity {
private FragmentA m1stFragment;
private FragmentB m2ndFragment;
// other code in your Activity...
private class CustomPagerAdapter extends FragmentPagerAdapter {
// other code in your custom FragmentPagerAdapter...
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// Do NOT try to save references to the Fragments in getItem(),
// because getItem() is not always called. If the Fragment
// was already created then it will be retrieved from the FragmentManger
// and not here (i.e. getItem() won't be called again).
switch (position) {
case 0:
return new FragmentA();
case 1:
return new FragmentB();
default:
// This should never happen. Always account for each position above
return null;
}
}
// Here we can finally safely save a reference to the created
// Fragment, no matter where it came from (either getItem() or
// FragmentManger). Simply save the returned Fragment from
// super.instantiateItem() into an appropriate reference depending
// on the ViewPager position.
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
// save the appropriate reference depending on position
switch (position) {
case 0:
m1stFragment = (FragmentA) createdFragment;
break;
case 1:
m2ndFragment = (FragmentB) createdFragment;
break;
}
return createdFragment;
}
}
public void someMethod() {
// do work on the referenced Fragments, but first check if they
// even exist yet, otherwise you'll get an NPE.
if (m1stFragment != null) {
// m1stFragment.doWork();
}
if (m2ndFragment != null) {
// m2ndFragment.doSomeWorkToo();
}
}
}
</code></pre>
<p><strong>or</strong> if you prefer to work with <code>tags</code> instead of class member variables/references to the <code>Fragments</code> you can also grab the <code>tags</code> set by <code>FragmentPagerAdapter</code> in the same manner:
NOTE: this doesn't apply to <code>FragmentStatePagerAdapter</code> since it doesn't set <code>tags</code> when creating its <code>Fragments</code>.</p>
<pre><code>@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
// get the tags set by FragmentPagerAdapter
switch (position) {
case 0:
String firstTag = createdFragment.getTag();
break;
case 1:
String secondTag = createdFragment.getTag();
break;
}
// ... save the tags somewhere so you can reference them later
return createdFragment;
}
</code></pre>
<p>Note that this method does NOT rely on mimicking the internal <code>tag</code> set by <code>FragmentPagerAdapter</code> and instead uses proper APIs for retrieving them. This way even if the <code>tag</code> changes in future versions of the <code>SupportLibrary</code> you'll still be safe.</p>
<hr>
<p><strong>Don't forget</strong> that depending on the design of your <code>Activity</code>, the <code>Fragments</code> you're trying to work on may or may not exist yet, so you have to account for that by doing <code>null</code> checks before using your references.</p>
<p><strong>Also, if instead</strong> you're working with <code>FragmentStatePagerAdapter</code>, then you don't want to keep hard references to your <code>Fragments</code> because you might have many of them and hard references would unnecessarily keep them in memory. Instead save the <code>Fragment</code> references in <code>WeakReference</code> variables instead of standard ones. Like this:</p>
<pre><code>WeakReference<Fragment> m1stFragment = new WeakReference<Fragment>(createdFragment);
// ...and access them like so
Fragment firstFragment = m1stFragment.get();
if (firstFragment != null) {
// reference hasn't been cleared yet; do work...
}
</code></pre> |
30,012,910 | How do you quickly find the implementation(s) of an interface in Golang? | <p>Let's say I want to find all implementations of the io.ReadCloser interface.</p>
<p>How can I do this in Go?</p> | 30,012,956 | 1 | 5 | null | 2015-05-03 10:47:37.153 UTC | 10 | 2015-05-03 10:57:15.093 UTC | null | null | null | null | 306,478 | null | 1 | 20 | go | 8,897 | <p>You can use:</p>
<ul>
<li>the <a href="https://docs.google.com/document/d/1SLk36YRjjMgKqe490mSRzOPYEDe0Y_WQNRv-EiFYUyw/view#heading=h.15us5y9rxrbh">go oracle implements</a> command</li>
<li>the <a href="https://godoc.org/golang.org/x/tools/go/types#Implements"><code>go types Implements()</code> function</a> (which was <a href="https://sourcegraph.com/blog/go-interfaces-and-implementations">used by Sourcegraph at one time</a>)</li>
</ul>
<p>You also have:</p>
<ul>
<li><a href="https://github.com/dominikh/implements"><code>dominikh/implements</code></a> (uses <code>go types</code> as well)</li>
<li><a href="https://github.com/fzipp/pythia"><code>fzipp/pythia</code></a>, a browser based user interface (uses <code>go oracle</code>)</li>
</ul> |
34,271,236 | Centering table on a page on bootstrap | <p>I am trying to center a table using bootstrap.</p>
<p>Here is the html:</p>
<pre><code><div class="container-fluid">
<table id="total votes" class="table table-hover text-centered">
<thead>
<tr>
<th>Total votes</th>
<th> = </th>
<th>Voter A</th>
<th> + </th>
<th>Voter B</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ total_votes }}</td>
<td> = </td>
<td>{{ total_voter_a }}</td>
<td> + </td>
<td>{{ total_voter_b }}</td>
</tr>
</tbody>
</table>
</div>
</code></pre>
<p>However, no matter how I adjust the <code>css</code>, the table is still aligned to the left. I'm sure I am missing something simple. I also thought <code>container-fluid</code> would make the table span across the whole page.</p>
<p>here is the css:</p>
<pre><code>.table th {
text-align: center;
}
.table {
border-radius: 5px;
width: 50%;
float: none;
}
</code></pre> | 34,271,359 | 2 | 4 | null | 2015-12-14 15:50:31.81 UTC | 1 | 2016-09-19 12:17:18.497 UTC | 2015-12-14 16:00:34.863 UTC | null | 3,965,631 | null | 5,222,301 | null | 1 | 14 | html|css|twitter-bootstrap | 77,249 | <p>You're missing the <code>margin:auto</code></p>
<pre><code>.table {
border-radius: 5px;
width: 50%;
margin: 0px auto;
float: none;
}
</code></pre>
<p><a href="http://codepen.io/Ayeetu/pen/KVdYep" rel="noreferrer"><strong>Example</strong></a></p> |
44,929,282 | Angular: Formatting numbers with commas | <p>Title very much sums up my needs. </p>
<pre><code>123456789 => 123,456,789
12345 => 12,345
</code></pre>
<p>What's the best way to get this conversion ? Don't suggest currency pipe in Angular-2 as I don't need $ or currency symbol to be prepend to my output.</p> | 44,929,496 | 4 | 2 | null | 2017-07-05 14:38:03.543 UTC | 9 | 2021-10-08 15:10:39.147 UTC | 2017-07-05 20:05:46.977 UTC | null | 4,888,735 | null | 2,160,616 | null | 1 | 63 | javascript|angular|typescript | 98,153 | <p>Use DecimalPipe like this</p>
<p><code>{{attr | number}}</code></p>
<p><a href="https://plnkr.co/edit/ZzE5NOoytQu2yxD6" rel="noreferrer">Working Plunker</a></p>
<p>Documentation available at <a href="https://angular.io/api/common/DecimalPipe" rel="noreferrer">https://angular.io/api/common/DecimalPipe</a></p> |
672,237 | Running an asynchronous operation triggered by an ASP.NET web page request | <p>I have an asynchronous operation that for various reasons needs to be triggered using an HTTP call to an ASP.NET web page. When my page is requested, it should start this operation and immediately return an acknowledgment to the client.</p>
<p>This method is also exposed via a WCF web service, and it works perfectly.</p>
<p>On my first attempt, an exception was thrown, telling me:</p>
<pre>Asynchronous operations are not allowed in this context.
Page starting an asynchronous operation has to have the Async
attribute set to true and an asynchronous operation can only be
started on a page prior to PreRenderComplete event.</pre>
<p>So of course I added the <code>Async="true"</code> parameter to the <code>@Page</code> directive. Now, I'm not getting an error, but the page is blocking until the Asynchronous operation completes.</p>
<p>How do I get a true fire-and-forget page working?</p>
<p><strong>Edit:</strong> Some code for more info. It's a bit more complicated than this, but I've tried to get the general idea in there.</p>
<pre><code>public partial class SendMessagePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string message = Request.QueryString["Message"];
string clientId = Request.QueryString["ClientId"];
AsyncMessageSender sender = new AsyncMessageSender(clientId, message);
sender.Start();
Response.Write("Success");
}
}
</code></pre>
<p>The AsyncMessageSender class:</p>
<pre><code>public class AsyncMessageSender
{
private BackgroundWorker backgroundWorker;
private string client;
private string msg;
public AsyncMessageSender(string clientId, string message)
{
this.client = clientId;
this.msg = message;
// setup background thread to listen
backgroundThread = new BackgroundWorker();
backgroundThread.WorkerSupportsCancellation = true;
backgroundThread.DoWork += new DoWorkEventHandler(backgroundThread_DoWork);
}
public void Start()
{
backgroundThread.RunWorkerAsync();
}
...
// after that it's pretty predictable
}
</code></pre> | 672,285 | 5 | 3 | null | 2009-03-23 04:28:31.743 UTC | 22 | 2016-02-17 00:08:46.743 UTC | 2009-03-23 05:16:05.327 UTC | Damovisa | 77,546 | Damovisa | 77,546 | null | 1 | 57 | c#|asp.net|asynchronous | 68,889 | <p>If you don't care about returning anything to the user, you can just fire up either a separate thread, or for a quick and dirty approach, use a delegate and invoke it asynchrnously. If you don't care about notifying the user when the async task finishes, you can ignore the callback. Try putting a breakpoint at the end of the SomeVeryLongAction() method, and you'll see that it finishes running after the page has already been served up:</p>
<pre><code>private delegate void DoStuff(); //delegate for the action
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//create the delegate
DoStuff myAction = new DoStuff(SomeVeryLongAction);
//invoke it asynchrnously, control passes to next statement
myAction.BeginInvoke(null, null);
Button1.Text = DateTime.Now.ToString();
}
private void SomeVeryLongAction()
{
for (int i = 0; i < 100; i++)
{
//simulation of some VERY long job
System.Threading.Thread.Sleep(100);
}
}
</code></pre> |
611,298 | How to create a WPF Window without a border that can be resized via a grip only? | <p>If you set <code>ResizeMode="CanResizeWithGrip"</code> on a WPF <code>Window</code> then a resize grip is shown in the lower right corner, as below:</p>
<p><img src="https://i.stack.imgur.com/kwmCH.png" alt=""></p>
<p>If you set <code>WindowStyle="None"</code> as well the title bar disappears but the grey bevelled edge remains until you set <code>ResizeMode="NoResize"</code>. Unfortunately, with this combination of properties set, the resize grip also disappears.</p>
<p>I have overridden the <code>Window</code>'s <code>ControlTemplate</code> via a custom <code>Style</code>. I want to specify the border of the window myself, and I don't need users to be able to resize the window from all four sides, but I do need a resize grip.</p>
<p>Can someone detail a simple way to meet all of these criteria?</p>
<ol>
<li><strong>Do not</strong> have a border on the <code>Window</code> apart from the one I specify myself in a <code>ControlTemplate</code>.</li>
<li><strong>Do</strong> have a working resize grip in the lower right corner.</li>
<li><strong>Do not</strong> have a title bar.</li>
</ol> | 611,309 | 5 | 3 | null | 2009-03-04 16:17:53.32 UTC | 44 | 2020-03-09 15:42:25.897 UTC | 2017-07-20 12:17:31.657 UTC | Drew Noakes | 6,083,675 | Drew Noakes | 24,874 | null | 1 | 103 | .net|wpf|window|controltemplate|resizegrip | 143,041 | <p>If you set the <code>AllowsTransparency</code> property on the <code>Window</code> (even without setting any transparency values) the border disappears and you can only resize via the grip.</p>
<pre><code><Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="640" Height="480"
WindowStyle="None"
AllowsTransparency="True"
ResizeMode="CanResizeWithGrip">
<!-- Content -->
</Window>
</code></pre>
<p>Result looks like:</p>
<blockquote>
<p><img src="https://i.stack.imgur.com/5qP3U.png" alt=""></p>
</blockquote> |
133,886 | Efficiently match multiple regexes in Python | <p>Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with:</p>
<pre><code>import re
import sys
class Token(object):
""" A simple Token structure.
Contains the token type, value and position.
"""
def __init__(self, type, val, pos):
self.type = type
self.val = val
self.pos = pos
def __str__(self):
return '%s(%s) at %s' % (self.type, self.val, self.pos)
class LexerError(Exception):
""" Lexer error exception.
pos:
Position in the input line where the error occurred.
"""
def __init__(self, pos):
self.pos = pos
class Lexer(object):
""" A simple regex-based lexer/tokenizer.
See below for an example of usage.
"""
def __init__(self, rules, skip_whitespace=True):
""" Create a lexer.
rules:
A list of rules. Each rule is a `regex, type`
pair, where `regex` is the regular expression used
to recognize the token and `type` is the type
of the token to return when it's recognized.
skip_whitespace:
If True, whitespace (\s+) will be skipped and not
reported by the lexer. Otherwise, you have to
specify your rules for whitespace, or it will be
flagged as an error.
"""
self.rules = []
for regex, type in rules:
self.rules.append((re.compile(regex), type))
self.skip_whitespace = skip_whitespace
self.re_ws_skip = re.compile('\S')
def input(self, buf):
""" Initialize the lexer with a buffer as input.
"""
self.buf = buf
self.pos = 0
def token(self):
""" Return the next token (a Token object) found in the
input buffer. None is returned if the end of the
buffer was reached.
In case of a lexing error (the current chunk of the
buffer matches no rule), a LexerError is raised with
the position of the error.
"""
if self.pos >= len(self.buf):
return None
else:
if self.skip_whitespace:
m = self.re_ws_skip.search(self.buf[self.pos:])
if m:
self.pos += m.start()
else:
return None
for token_regex, token_type in self.rules:
m = token_regex.match(self.buf[self.pos:])
if m:
value = self.buf[self.pos + m.start():self.pos + m.end()]
tok = Token(token_type, value, self.pos)
self.pos += m.end()
return tok
# if we're here, no rule matched
raise LexerError(self.pos)
def tokens(self):
""" Returns an iterator to the tokens found in the buffer.
"""
while 1:
tok = self.token()
if tok is None: break
yield tok
if __name__ == '__main__':
rules = [
('\d+', 'NUMBER'),
('[a-zA-Z_]\w+', 'IDENTIFIER'),
('\+', 'PLUS'),
('\-', 'MINUS'),
('\*', 'MULTIPLY'),
('\/', 'DIVIDE'),
('\(', 'LP'),
('\)', 'RP'),
('=', 'EQUALS'),
]
lx = Lexer(rules, skip_whitespace=True)
lx.input('erw = _abc + 12*(R4-623902) ')
try:
for tok in lx.tokens():
print tok
except LexerError, err:
print 'LexerError at position', err.pos
</code></pre>
<p>It works just fine, but I'm a bit worried that it's too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ? </p>
<p>Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?</p> | 134,168 | 6 | 0 | null | 2008-09-25 15:10:05.74 UTC | 10 | 2016-04-06 12:49:00.303 UTC | 2016-04-06 12:49:00.303 UTC | null | 12,166 | eliben | 8,206 | null | 1 | 16 | python|regex|lexical-analysis | 9,554 | <p>You can merge all your regexes into one using the "|" operator and let the regex library do the work of discerning between tokens. Some care should be taken to ensure the preference of tokens (for example to avoid matching a keyword as an identifier).</p> |
1,187,402 | Ant run command with pipes | <p>I must to implement command : <code>java -jar test.jar page.xml | mysql -u user -p base</code>
in ant. So i Have tried with this task:</p>
<pre><code><java jar="test.jar" fork="true">
<arg line="page.xml | mysql -u user -p base"/>
</java>
</code></pre>
<p>But i have got en exception with pipe - "|" :</p>
<pre><code> java.lang.IllegalArgumentException: Input already set; can't set to |
</code></pre>
<p>So, that's the problem:)</p> | 1,187,434 | 6 | 0 | null | 2009-07-27 10:11:13.917 UTC | 9 | 2022-05-02 17:37:21.15 UTC | 2009-07-27 10:12:07.267 UTC | null | 21,234 | null | 139,436 | null | 1 | 26 | java|ant | 18,041 | <p>The pipe (|) can only be used in a shell script. You're passing it as an argument to the java process.</p>
<p>So you need to execute a shell script. You can do this by executing (say) <code>bash -c</code> and passing the above as a shell statement (albeit <em>inline</em> - you could write a separate script file but it seems a bit of an overhead here)</p>
<pre><code> <exec executable="bash">
<arg value="-c"/>
<arg line="java -jar test.jar page.xml | mysql -u user -p base"/>
</exec>
</code></pre> |
573,646 | mysql select from n last rows | <p>I have a table with index (autoincrement) and integer value. The table is millions of rows long.</p>
<p>How can I search if a certain number appear in the last n rows of the table most efficiently?</p> | 574,148 | 6 | 0 | null | 2009-02-21 19:59:37.62 UTC | 17 | 2016-06-29 11:56:44.927 UTC | null | null | null | Nir | 64,106 | null | 1 | 68 | mysql|select|query-optimization | 152,675 | <p>Starting from the <a href="https://stackoverflow.com/questions/573646/mysql-select-from-n-last-rows/573665#573665">answer</a> given by @chaos, but with a few modifications:</p>
<ul>
<li><p>You should always use <code>ORDER BY</code> if you use <code>LIMIT</code>. There is no implicit order guaranteed for an RDBMS table. You may <em>usually</em> get rows in the order of the primary key, but you can't rely on this, nor is it portable.</p></li>
<li><p>If you order by in the descending order, you don't need to know the number of rows in the table beforehand.</p></li>
<li><p>You must give a <em>correlation name</em> (aka table alias) to a derived table.</p></li>
</ul>
<p>Here's my version of the query:</p>
<pre><code>SELECT `id`
FROM (
SELECT `id`, `val`
FROM `big_table`
ORDER BY `id` DESC
LIMIT $n
) AS t
WHERE t.`val` = $certain_number;
</code></pre> |
869,529 | Difference between `set`, `setq`, and `setf` in Common Lisp? | <p>What is the difference between "set", "setq", and "setf" in Common Lisp?</p> | 869,693 | 6 | 1 | null | 2009-05-15 16:00:32.483 UTC | 66 | 2015-07-31 20:27:04.42 UTC | 2015-07-31 20:27:04.42 UTC | null | 114,979 | null | 102,654 | null | 1 | 191 | common-lisp | 99,966 | <p>Originally, in Lisp, there were no lexical variables -- only dynamic ones. And
there was no SETQ or SETF, just the SET function.</p>
<p>What is now written as:</p>
<pre><code>(setf (symbol-value '*foo*) 42)
</code></pre>
<p>was written as:</p>
<pre><code>(set (quote *foo*) 42)
</code></pre>
<p>which was eventually abbreviavated to SETQ (SET Quoted):</p>
<pre><code>(setq *foo* 42)
</code></pre>
<p>Then lexical variables happened, and SETQ came to be used for assignment to them too -- so it was no longer a simple wrapper around SET.</p>
<p>Later, someone invented SETF (SET Field) as a generic way of assigning values to data structures, to mirror the l-values of other languages:</p>
<pre><code>x.car := 42;
</code></pre>
<p>would be written as</p>
<pre><code>(setf (car x) 42)
</code></pre>
<p>For symmetry and generality, SETF also provided the functionality of SETQ. At this point it would have been correct to say that SETQ was a Low-level primitive, and SETF a high-level operation.</p>
<p>Then symbol macros happened. So that symbol macros could work transparently, it was realized that SETQ would have to act like SETF if the "variable" being assigned to was really a symbol macro:</p>
<pre><code>(defvar *hidden* (cons 42 42))
(define-symbol-macro foo (car *hidden*))
foo => 42
(setq foo 13)
foo => 13
*hidden* => (13 . 42)
</code></pre>
<p>So we arrive in the present day: SET and SETQ are atrophied remains of older dialects, and will probably be booted from eventual successors of Common Lisp.</p> |
69,047,142 | VSCode is suddenly defaulting to powershell for integrated terminal and tasks | <p>When I woke up this morning and launched VSCode my default terminal on launch, and when running tasks is now powershell, instead of Git Bash. I am on windows. I have tried changing the settings.json to no avail. Is there something I'm missing?</p>
<pre><code>{
"workbench.startupEditor": "newUntitledFile",
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
"[javascript]": {
"editor.defaultFormatter": "rvest.vs-code-prettier-eslint"
},
"aws.samcli.location": "C:\\Users\\king\\AppData\\Roaming\\npm\\sam.exe",
"typescript.updateImportsOnFileMove.enabled": "always",
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
},
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"javascript.updateImportsOnFileMove.enabled": "always",
"explorer.confirmDragAndDrop": false,
"diffEditor.maxComputationTime": 0,
"extensions.ignoreRecommendations": true,
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.renderControlCharacters": true,
"[jsonc]": {
"editor.quickSuggestions": {
"strings": true
},
"editor.suggest.insertMode": "replace"
},
"window.zoomLevel": 0,
"editor.accessibilitySupport": "off",
"workbench.editor.untitled.hint": "hidden",
"terminal.integrated.defaultProfile.windows": "Git Bash",
"terminal.external.windowsExec": "C:\\Program Files\\Git\\bin\\bash.exe",
"terminal.explorerKind": "external",
"terminal.integrated.automationShell.linux": ""
}
</code></pre>
<p>I found this <a href="https://stackoverflow.com/questions/60537341/how-can-i-start-powershell-script-as-noprofile-in-visual-studio-code/60555493#60555493">related SO post</a> making the default powershell, but I didn't see anything that was incorrect about my setting...especially because my goal is the opposite- to stop Powershell!</p> | 69,050,730 | 6 | 6 | null | 2021-09-03 15:11:35.61 UTC | 16 | 2022-07-10 06:34:49.757 UTC | null | null | null | null | 1,634,753 | null | 1 | 74 | powershell|visual-studio-code|git-bash | 13,757 | <p><em>Update</em>: <strong>Version v1.60.0 had a bug. Upgrade to v1.60.1 or higher for a fix</strong>.</p>
<p>The bug manifested in the following <strong>symptoms</strong>:</p>
<ul>
<li><p>The <code>Open in Integrated Terminal</code> shortcut-menu command in the Explorer pane's shortcut always uses the built-in default shell (PowerShell on Windows), ignoring the configured one.</p>
</li>
<li><p>The same goes for running tasks (with or without a separate <code>terminal.integrated.automationShell.*</code> setting).</p>
</li>
<li><p>Also, if a given folder or workspace happened to have an integrated terminal open when quitting Visual Studio Code, the shell that is launched when the integrated terminal automatically reopens the next time is again the built-in default shell, not the configured one. By contrast, if reopening doesn't auto-open the integrated terminal, opening it manually <em>does</em> respect the configured default shell, and so does manually creating another shell instance later.</p>
</li>
</ul>
<p>See <a href="https://github.com/microsoft/vscode/issues/132150" rel="noreferrer">GitHub issue #132150</a></p>
<p>The following information turned out to be unrelated to the bug, but is hopefully still useful general information about Visual Studio Code's recent change in how shells for the integrated terminal are configured:</p>
<hr />
<h4>Migrating from the legacy default shell settings to <em>shell profiles</em>:</h4>
<ul>
<li><p>Recently, the <strong><code>"terminal.integrated.shell.*"</code> and <code>"terminal.integrated.shellArgs.*"</code> settings were <em>deprecated</em></strong> and replaced with a <strong>more flexible model that allows defining <em>multiple</em> shells to select from</strong>, via so-called <strong><a href="https://code.visualstudio.com/docs/editor/integrated-terminal#_configuring-profiles" rel="noreferrer">shell <em>profiles</em></a></strong>, optionally defined in setting <code>"terminal.integrated.profiles.*"</code>, with an associated mandatory <code>"terminal.integrated.defaultProfile.*"</code> setting referencing the name of the profile to use <em>by default</em> - which may be an explicitly defined custom profile or one of the built-in, platform-appropriate default profiles.</p>
<ul>
<li>Note: <code>*</code> in the setting names above represents the appropriate <em>platform identifier</em>, namely <code>windows</code>, <code>linux</code>, or <code>osx</code> (macOS).</li>
</ul>
</li>
<li><p>As of v1.60.1, if legacy <code>"terminal.integrated.shell.*"</code> settings are <em>also</em> present, the <em>new</em> settings take precedence (even though the tooltip when editing <code>"terminal.integrated.shell.*"</code> in <code>settings.json</code> suggests that this change is yet to come).</p>
<ul>
<li><p>In the absence of <em>both</em> settings, <strong>Visual Studio Code's <em>built-in</em> default shell</strong> is used, which on <strong>Windows</strong> is <strong><em>PowerShell</em>,</strong><sup>[1]</sup> and on <strong>Unix-like platforms</strong> the user's default shell, as <strong>specified in the <code>SHELL</code> environment variable</strong>.</p>
</li>
<li><p>Recent Visual Studio Code versions, starting <em>before</em> v1.60 - seemingly as <em>one-time</em> opportunity - displayed a prompt offering to <em>migrate</em> the deprecated settings to the new ones.</p>
<ul>
<li><p><em>Accepting</em> the migration results in the following:</p>
<ul>
<li>Creation of setting <code>"terminal.integrated.shell.*"</code> containing a custom shell profile derived from the values of legacy settings <code>"terminal.integrated.shell.*"</code> and, if present, <code>"terminal.integrated.shellArgs.*"</code>; that custom profile's name has the suffix <code> (migrated)</code></li>
<li>Creation of setting <code>terminal.integrated.defaultProfile.*</code> whose value is the migrated profile's name, making it the default shell.</li>
<li>Removal of legacy settings <code>"terminal.integrated.shell.*"</code> and <code>"terminal.integrated.shellArgs.*"</code></li>
</ul>
</li>
<li><p>If you <em>decline</em> the migration, you can later effectively perform it by re-choosing the default shell, as described below.</p>
<ul>
<li>Note: The new <code>"terminal.integrated.defaultProfile.*"</code> setting that is created in the process then effectively <em>overrides</em> the legacy <code>"terminal.integrated.shell.*"</code> and <code>"terminal.integrated.shellArgs.*"</code> settings, but the latter won't be removed automatically. To avoid confusion, it's best to remove them from <code>settings.json</code> manually.</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Choose the <em>default shell profile</em> to use</strong> in order to (re)specify the default shell:</p>
<ul>
<li><p>Click on the down-arrow part of the shell-selector icon (<img src="https://i.stack.imgur.com/vru5o.png" alt="shell selector" />) on the right side of the integrated terminal, select <code>Select Default Profile</code>, which presents a list of the defined profiles to select the default from - in the absence of explicitly defined profiles, <em>standard</em> profiles are offered (see below).</p>
</li>
<li><p>This translates into a <code>terminal.integrated.defaultProfile.*</code> setting in <code>settings.json</code>, whose value is the name of the chosen shell profile - which may be the name of a <em>built-in</em> profile or one of the ones explicitly defined in <code>"terminal.integrated.profiles.*"</code></p>
</li>
<li><p>Note: This shell is by default also used for <em>tasks</em> (defined in <code>tasks.json</code>), but that can be overridden with a <code>"terminal.integrated.automationShell.*"</code> setting pointing to the executable of an alternative shell.</p>
</li>
</ul>
</li>
<li><p><em>Optionally</em>, in your <code>settings.json</code> file, you may <strong>create a platform-appropriate <code>terminal.integrated.profiles.*</code> setting with <a href="https://code.visualstudio.com/docs/editor/integrated-terminal#_configuring-profiles" rel="noreferrer">shell profiles</a> of interest</strong>:</p>
<ul>
<li><p>Note: Even if your <code>settings.json</code> contains <em>no</em> (platform-appropriate) <code>"terminal.integrated.profiles.*"</code> setting, Visual Studio code has built-in <em>standard</em> profiles it knows of and offers them for selection when choosing the <em>default</em> shell.</p>
<ul>
<li>These standard profiles are a mix of shells that come with the host platform as well as some that Visual Studio detects dynamically on a given system, such as Git Bash on Windows.</li>
</ul>
</li>
<li><p>To <strong>create the <em>standard</em> profiles <em>explicitly</em></strong>, do the following:</p>
<ul>
<li><p>Note: You may choose to do this in order to <em>customize</em> the standard profiles. However, if your intent is merely to <em>add</em> custom profiles - see <a href="https://stackoverflow.com/a/68791496/45375">this answer</a> for an example - it isn't necessary to create the standard profiles inside the <code>"terminal.integrated.profiles.*"</code> setting, because Visual Studio Code knows about them even if not explicitly defined.</p>
</li>
<li><p>Via <code>File > Preferences > Settings</code> (<kbd>Ctrl-,</kbd>), search for <code>profiles</code> and click on <code>Edit in settings.json</code> below the platform-appropriate <code>Terminal > Integrated > Profiles > *</code> setting; this will open <code>settings.json</code> for editing, with the standard profiles added; simply saving the file is sufficient.</p>
<ul>
<li>Note: If the <code>"terminal.integrated.profiles.*"</code> setting shown doesn't contain the expected, platform-appropriate standard profiles, a setting by that name may already be present; to force creation of the standard profiles, remove or comment out the existing setting and save the file, then try again.</li>
</ul>
</li>
<li><p>On Windows, you'll end up with something like the following:</p>
<pre class="lang-json prettyprint-override"><code>"terminal.integrated.profiles.windows": {
"PowerShell": {
"source": "PowerShell",
"icon": "terminal-powershell"
},
"Command Prompt": {
"path": [
"${env:windir}\\Sysnative\\cmd.exe",
"${env:windir}\\System32\\cmd.exe"
],
"args": [],
"icon": "terminal-cmd"
},
"Git Bash": {
"source": "Git Bash"
}
}
</code></pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>The <a href="https://stackoverflow.com/questions/60537341/how-can-i-start-powershell-script-as-noprofile-in-visual-studio-code/60555493#60555493">answer</a> you link to in your question, which provides an <strong>overview of the various types of shells used in Visual Studio Code</strong>, has been updated to reflect the information about the new shell profiles.</p>
<hr />
<p><sup>[1] Note: If a <em>PowerShell (Core) v6+</em> installation is found, it takes precedence over the built-in <em>Windows PowerShell</em> version.</sup></p> |
35,604,836 | How do you inspect CSS variables in the browser? | <p>I am defining my variables <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables" rel="noreferrer">as per the spec</a> like so:</p>
<pre class="lang-css prettyprint-override"><code>:root {
--my-colour: #000;
}
</code></pre>
<p>And accessing them like this:</p>
<pre class="lang-css prettyprint-override"><code>.my-element {
background: var( --my-colour );
}
</code></pre>
<p>Which works fine. </p>
<p>However I was wondering if there was a way of debugging or inspecting the <code>:root</code> CSS rule to see what variables have been defined, and what their values were? </p>
<p>From my understanding the <code>:root</code> selector and <code>html</code> selectors both target the same element however when I inspect the <code>html</code> element using Chrome's debugging tools I cannot see anything defined:</p>
<p><a href="https://i.stack.imgur.com/EbNvh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EbNvh.png" alt="inspecting the html element"></a></p>
<p>Is there a way finding out what variables have been defined and their values?</p> | 35,605,574 | 2 | 3 | null | 2016-02-24 14:27:02.113 UTC | 5 | 2018-05-10 09:18:55.09 UTC | 2016-02-24 15:02:26.357 UTC | null | 1,317,805 | null | 1,499,016 | null | 1 | 42 | html|css|google-chrome-devtools|web-component|css-variables | 22,034 | <p>Using Chrome Canary, you can access this by viewing the element's <em>Computed</em> styles and enabling the <em>Show all</em> filter:</p>
<blockquote>
<p><img src="https://i.stack.imgur.com/hlqAS.png" alt="Computed tab"> ... <img src="https://i.stack.imgur.com/TsoKd.png" alt="Example"></p>
</blockquote> |
35,497,069 | Passing IPython variables as arguments to bash commands | <p>How do I execute a bash command from Ipython/Jupyter notebook passing the value of a python variable as an argument like in this example:</p>
<pre><code>py_var="foo"
!grep py_var bar.txt
</code></pre>
<p>(obviously I want to grep for <code>foo</code> and not the literal string <code>py_var</code>)</p> | 35,497,161 | 4 | 4 | null | 2016-02-19 04:01:47.673 UTC | 22 | 2022-05-11 18:06:22.473 UTC | 2021-08-04 04:31:24.07 UTC | null | 2,230,844 | null | 937,153 | null | 1 | 126 | python|bash|jupyter-notebook|ipython|command-line-arguments | 52,426 | <p>Prefix your <strong>variable</strong> names with a <code>$</code>. </p>
<p><strong>Example</strong></p>
<p>Say you want to copy a file <code>file1</code> to a path stored in a python variable named <code>dir_pth</code>:</p>
<pre><code>dir_path = "/home/foo/bar"
!cp file1 $dir_path
</code></pre>
<p>from Ipython or Jupyter notebook</p>
<p><strong>EDIT</strong></p>
<p>Thanks to the suggestion from Catbuilts, if you want to concatenate multiple strings to form the path, use <code>{..}</code> instead of <code>$..$</code>.
A general solution that works in both situations is to stick with <code>{..}</code></p>
<pre><code>dir_path = "/home/foo/bar"
!cp file1 {dir_path}
</code></pre>
<p>And if you want to concatinate another string <code>sub_dir</code> to your path, then:</p>
<pre><code>!cp file1 {dir_path + sub_dir}
</code></pre>
<p><strong>EDIT 2</strong></p>
<p>For a related discussion on the use of raw strings (prefixed with <code>r</code>) to pass the variables, see <a href="https://stackoverflow.com/q/61606054/937153">Passing Ipython variables as string arguments to shell command</a></p> |
21,342,596 | Tree Structure from Adjacency List | <p>I am trying to generate a hierarchical tree object from a flat array with parent IDs.</p>
<pre><code>// `parent` represents an ID and not the nesting level.
var flat = [
{ id: 1, name: "Business", parent: 0 },
{ id: 2, name: "Management", parent: 1 },
{ id: 3, name: "Leadership", parent: 2 },
{ id: 4, name: "Finance", parent: 1 },
{ id: 5, name: "Fiction", parent: 0 },
{ id: 6, name: "Accounting", parent: 1 },
{ id: 7, name: "Project Management", parent: 2 }
];
</code></pre>
<p>The final tree object should look as follows:</p>
<pre><code>{
id: 1,
name: "Business",
children: [
{
id: 2,
name: "Management",
children: [
{ id: 3, name: "Leadership" },
{ id: 7, name: "Project Management" }
]
}
// [...]
]
}
// [...]
</code></pre>
<p>You can see my current work on <a href="http://jsfiddle.net/xnpRa/">this fiddle</a>, but it only works on the first two levels.</p>
<p>I thought about collecting the orphans (objects from <code>flat</code> without a parent in <code>tree</code> yet) and then looping over them again to see if they now have a parent. But that could mean many loops over the tree object, especially with many categories over multiple levels.</p>
<p>I'm sure there is a more elegant solution.</p> | 21,343,255 | 2 | 4 | null | 2014-01-24 21:15:57.253 UTC | 9 | 2020-05-19 19:29:10.993 UTC | 2020-05-19 19:29:10.993 UTC | null | 1,243,641 | null | 835,568 | null | 1 | 17 | javascript|recursion|tree|adjacency-list | 5,073 | <p>Looks like you can do this in 2 passes no matter the tree depth:</p>
<pre><code>var flat = [
{ id: 1, name: "Business", parent: 0 },
{ id: 2, name: "Management", parent: 1 },
{ id: 3, name: "Leadership", parent: 2 },
{ id: 4, name: "Finance", parent: 1 },
{ id: 5, name: "Fiction", parent: 0 },
{ id: 6, name: "Accounting", parent: 1 },
{ id: 7, name: "Project Management", parent: 2 }
];
var nodes = [];
var toplevelNodes = [];
var lookupList = {};
for (var i = 0; i < flat.length; i++) {
var n = {
id: flat[i].id,
name: flat[i].name,
parent_id: ((flat[i].parent == 0) ? null : flat[i].parent),
children: []
};
lookupList[n.id] = n;
nodes.push(n);
if (n.parent_id == null) {
toplevelNodes.push(n);
}
}
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
if (!(n.parent_id == null)) {
lookupList[n.parent_id].children = lookupList[n.parent_id].children.concat([n]);
}
}
console.log(toplevelNodes);
</code></pre> |
17,958,887 | Make a button change value of a textview | <p>So, my friend got me to mess with android programming in android studio today. I started making a beginner application and have had some good results. But right now I am trying to get a button to change the value of a textview. </p>
<p>Here is the code for the button and the textview</p>
<pre><code><Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one"
android:id="@+id/button3"
android:layout_alignBottom="@+id/button2"
android:layout_alignRight="@+id/textView"
android:layout_toRightOf="@+id/button"
android:onClick="addone"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/counter"
android:textSize="40dp"
android:layout_alignTop="@+id/button3"
android:layout_centerHorizontal="true"/>
</code></pre>
<p>and here is the code that is attempting to change the value of the text view.</p>
<pre><code>public void addone(){
numtest+=1;
TextView t = (TextView) findViewById(R.id.counter);
t.setText(numtest);
}
</code></pre>
<p>THe program compiles and opens, but it crashes whenever i press the button. I believe I have narrowed down the culprit to this line, but im not sure why it isnt working</p>
<pre><code>TextView t = (TextView) findViewById(R.id.counter);
</code></pre>
<p>Any ideas?</p> | 17,958,925 | 3 | 1 | null | 2013-07-30 22:55:46.113 UTC | 3 | 2013-07-30 23:14:54.333 UTC | null | null | null | null | 780,204 | null | 1 | 6 | java|android|variables|button|textview | 43,695 | <p>An overloaded method is your problem. It is subtle, a mistake even a seasoned programmer could make. I've made it myself before.</p>
<p>You are calling <a href="http://developer.android.com/reference/android/widget/TextView.html#setText%28int%29" rel="noreferrer">TextView.setText(Integer)</a>. This attempts to load a string having a resource id of numtest, which does not exist.</p>
<p>Try this instead:</p>
<pre><code>public void addone(View v){
numtest+=1;
TextView t = (TextView) findViewById(R.id.counter);
t.setText(numtest+"");
}
</code></pre>
<p>This will call <a href="http://developer.android.com/reference/android/widget/TextView.html#setText%28java.lang.CharSequence%29" rel="noreferrer">TextView.setText(CharSequence)</a> instead, which is what you're really trying to do.</p>
<p>Also, as Osmium USA demonstrated, your method signature is incorrect. The button pressed callback method must accept a view, and must be public.</p> |
33,498,064 | Pass multiple parameters to addTarget | <p>In my <code>UITableViewCell</code> I have a button. And I want to add action to it by passing multiple parameters in <code>cellForRowAtIndexPath</code> method.</p>
<pre><code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CartCell", forIndexPath:
indexPath) as! CartTableViewCell
cell.buyButton.addTarget(self, action: self.buyButton(indexPath, 2, 3 ,4 , 5, 6), forControlEvents: .TouchUpInside)
}
</code></pre> | 33,500,326 | 5 | 3 | null | 2015-11-03 11:32:42.01 UTC | 9 | 2016-10-28 21:04:23.227 UTC | 2015-11-03 13:41:14.407 UTC | null | 5,264,388 | null | 1,786,016 | null | 1 | 13 | ios|swift|uitableview | 24,722 | <p>May be you can do something like this</p>
<pre><code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CartCell", forIndexPath:indexPath) as! CartTableViewCell
cell.buyButton.tag = (indexPath.section*100)+indexPath.row
cell.buyButton.addTarget(self, action: "btnBuy_Click:", forControlEvents: .TouchUpInside)
}
func btnBuy_Click(sender: UIButton) {
//Perform actions here
let section = sender.tag / 100
let row = sender.tag % 100
let indexPath = NSIndexPath(forRow: row, inSection: section)
self.buyButton(indexPath, 2, 3 ,4 , 5, 6)
}
</code></pre>
<p>Create tag value according to you'r requirement and maintaint it's integrity too.</p> |
1,508,807 | Getting website data into Adobe InDesign | <p>I'd like our magazine team to be able to download website data in a file that Adobe InDesign can read. They can then import/open the file, make a few tweaks, and cut out a vast deal of repetitive manual labour (they currently use copy&paste for a few hours).</p>
<p>After a brief Google I note that v2 of InDesign can import/export XML so perhaps that is my best bet? Are there any alternatives, and can anyone offer any advice on them?</p>
<p>I am using a PC, and the magazine team are on Macs; testing will be tiresome I fear.</p>
<p>The data we wish to format is fairly simple - a title followed by a short chunk of text (repeated about 50 times, say). I'll ask about importing images later.</p>
<p>Thanks for your help. I will return to Google now, but it would be great if anyone can point me in a more specific direction first!</p> | 1,615,534 | 5 | 2 | null | 2009-10-02 10:39:11.367 UTC | 10 | 2013-01-14 01:56:16.237 UTC | 2009-10-02 21:45:09.007 UTC | null | 11,461 | null | 11,461 | null | 1 | 7 | adobe|adobe-indesign | 6,824 | <p>There is a xhtml to idml (indesign markup language) xsl template in the latest indesign sdk. You can start with that to help you format your idml output.</p>
<p>Here is a link to the sdk:
<a href="http://www.adobe.com/devnet/indesign/sdk/" rel="noreferrer">http://www.adobe.com/devnet/indesign/sdk/</a></p>
<p>Download the "products" version. The xsl file is in this path in the zip file: devtools/sdktools/idmltools/samples/icmlbuilder/xsl/icml.xsl</p>
<p>Because of the mac issue, you can have them 'save' a xhtml file to a shared directory, you can then create a utility program to watch that directory and transform the saved files to an output directory.</p>
<p>Otherwise, there is a firefox add-on to transform xml files called XSL Results:
<a href="https://addons.mozilla.org/en-US/firefox/addon/5023" rel="noreferrer">https://addons.mozilla.org/en-US/firefox/addon/5023</a></p>
<p>I have not used it myself but it appears it could do the job of transforming the xhtml to idml for you on a mac...</p> |
1,760,096 | Override default behaviour for link ('a') objects in Javascript | <p>I don't know if what I'm trying to accomplish is possible at all. I would like to override the default behaviour for all the anchor objects (<code>A</code> tag) for a given HTML page. I know I can loop through all the <code>A</code> elements and dynamically add an <code>onclick</code> call to each one of them from the body element <code>onload</code> method, but I'm looking for a more absolute solution. What I need is that all <code>A</code> elements get assigned an <code>onclick</code> action which calls a method that passes the element <code>href</code> property as an argument, so the following:</p>
<pre><code><a href="http://domain.tld/page.html">
</code></pre>
<p>Dynamically becomes:</p>
<pre><code><a href="http://domain.tld/page.html" onclick="someMethodName('http://domain.tld/page.html'); return false;">
</code></pre>
<p>Like I said, the ideal way to do this would be to somehow override the Anchor class altogether when the document loads. If it's not possible then I'll resort to the loop-through-all <code>A</code> elements method (which I already know how to do).</p> | 1,760,127 | 5 | 4 | 2009-11-19 00:23:19.693 UTC | 2009-11-19 00:23:19.693 UTC | 8 | 2018-09-30 02:35:02.457 UTC | 2012-06-11 06:05:41.3 UTC | null | 709,626 | null | 91,458 | null | 1 | 29 | javascript|dom|overriding|anchor | 41,517 | <p>If you don't want to iterate over all your anchor elements, you can simply use <a href="http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/" rel="noreferrer">event delegation</a>, for example:</p>
<pre><code>document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == 'A') {
someFunction(element.href);
return false; // prevent default action and stop event propagation
}
};
</code></pre>
<p>Check the above example <a href="http://jsbin.com/ufexa" rel="noreferrer">here</a>.</p> |
1,932,770 | Haskell vs. Prolog comparison | <p>What kind of problems is better solved in Prolog than in Haskell? What are the main differences between these two languages?</p>
<hr>
<p><strong>Edit</strong></p>
<p>Is there a Haskell library (kind of a logical solver) that can mimic Prolog functionality?</p> | 1,932,778 | 5 | 4 | null | 2009-12-19 12:17:32.243 UTC | 33 | 2017-11-29 03:41:32.983 UTC | 2016-09-02 14:04:22.43 UTC | null | 3,924,118 | null | 19,884 | null | 1 | 58 | haskell|prolog | 33,812 | <p>Prolog is mainly a language targeted at logical problems, especially from the AI and linguistic fields. Haskell is more of a general-purpose language.</p>
<p>Prolog is declarative (logical) language, what makes it easier to state logical problems in it. Haskell is a functional language and hence much better suited to computational problems.</p>
<p>Wikipedia on declarative programming:</p>
<blockquote>
<p>In computer science, declarative
programming is a programming paradigm
that expresses the logic of a
computation without describing its
control flow. It attempts to minimize
or eliminate side effects by
describing what the program should
accomplish, rather than describing how
to go about accomplishing it. This is
in contrast from imperative
programming, which requires a detailed
description of the algorithm to be
run.</p>
<p>Declarative programming consider
programs as theories of a formal
logic, and computations as deductions
in that logic space. Declarative
programming has become of particular
interest recently, as it may greatly
simplify writing parallel programs.</p>
</blockquote>
<p>Wikipedia on functional programming:</p>
<blockquote>
<p>In computer science, functional
programming is a programming paradigm
that treats computation as the
evaluation of mathematical functions
and avoids state and mutable data. It
emphasizes the application of
functions, in contrast to the
imperative programming style, which
emphasizes changes in state.
Functional programming has its roots
in the lambda calculus, a formal
system developed in the 1930s to
investigate function definition,
function application, and recursion.
Many functional programming languages
can be viewed as embellishments to the
lambda calculus.</p>
</blockquote>
<p>In short a declarative language declares a set of rules about what outputs should result from which inputs and uses those rules to deduce an output from an input, while a functional language declares a set of mathematical or logical functions which define how input is translated to output.</p>
<hr>
<p>As for the ADDED question : none that I know of but you can either <a href="http://www.cs.bris.ac.uk/Teaching/Resources/COMS30106/slides/haskell2prolog.pdf" rel="noreferrer">translate</a> Haskell to Prolog, or <a href="http://propella.blogspot.com/2009/04/prolog-in-haskell.html" rel="noreferrer">implement</a> Prolog in Haskell :)</p> |
1,862,283 | Create a jTDS connection string | <p>my sql server instance name is MYPC\SQLEXPRESS and I'm trying to create a jTDS connection string to connect to the database 'Blog'. Can anyone please help me accomplish that?</p>
<p>I'm trying to do like this:</p>
<pre><code>DriverManager.getConnection("jdbc:jtds:sqlserver://127.0.0.1:1433/Blog", "user", "password");
</code></pre>
<p>and I get this:</p>
<pre><code> java.sql.SQLException: Network error IOException: Connection refused: connect
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:395)
at net.sourceforge.jtds.jdbc.ConnectionJDBC3.<init>(ConnectionJDBC3.java:50)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at SqlConnection.Connect(SqlConnection.java:19)
at main.main(main.java:11)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:305)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:255)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:323)
... 6 more
</code></pre> | 1,862,508 | 5 | 0 | null | 2009-12-07 19:23:46.83 UTC | 28 | 2018-12-16 05:52:14.753 UTC | 2018-12-16 05:52:14.753 UTC | null | 1,033,581 | null | 112,100 | null | 1 | 61 | java|jdbc|connection-string|jtds | 218,111 | <p>As detailed in the jTDS <a href="http://jtds.sourceforge.net/faq.html#urlFormat" rel="noreferrer">Frequenlty Asked Questions</a>, the URL format for jTDS is:</p>
<pre><code>jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
</code></pre>
<p>So, to connect to a database called "Blog" hosted by a MS SQL Server running on <code>MYPC</code>, you may end up with something like this:</p>
<pre><code>jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t
</code></pre>
<p>Or, if you prefer to use <code>getConnection(url, "sa", "s3cr3t")</code>:</p>
<pre><code>jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS
</code></pre>
<p><strong>EDIT:</strong> Regarding your <code>Connection refused</code> error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.</p> |
1,711,492 | What are the different types of keys in RDBMS? | <p>What are the different types of keys in RDBMS? Please include examples with your answer.</p> | 1,711,506 | 7 | 0 | null | 2009-11-10 21:51:46.14 UTC | 24 | 2017-06-03 07:58:08.597 UTC | 2011-11-14 18:48:41.153 UTC | null | 53,587 | null | 200,349 | null | 1 | 29 | rdbms | 135,973 | <p>From <a href="http://www.coders2020.com/what-are-the-different-types-of-keys-in-rdbms" rel="noreferrer">here</a> and <a href="http://wiki.answers.com/Q/What_are_different_types_of_keys_in_rdbms_with_examples" rel="noreferrer">here</a>: (after i googled your title)</p>
<blockquote>
<ul>
<li>Alternate key - An alternate key is any candidate key which is not selected to be the primary key</li>
<li>Candidate key - A candidate key is a field or combination of fields that can act as a primary key field for that table to uniquely identify each record in that table.</li>
<li>Compound key - compound key (also called a composite key or concatenated key) is a key that consists of 2 or more attributes.</li>
<li>Primary key - a primary key is a value that can be used to identify a unique row in a table. Attributes are associated with it. Examples of primary keys are Social Security numbers (associated to a specific person) or ISBNs (associated to a specific book).
In the relational model of data, a primary key is a candidate key chosen as the main method of uniquely identifying a tuple in a relation.</li>
<li>Superkey - A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a superkey can also be defined as a set of attributes of a relvar upon which all attributes of the relvar are functionally dependent.</li>
<li>Foreign key - a foreign key (FK) is a field or group of fields in a database record that points to a key field or group of fields forming a key of another database record in some (usually different) table. Usually a foreign key in one table refers to the primary key (PK) of another table. This way references can be made to link information together and it is an essential part of database normalization</li>
</ul>
</blockquote> |
2,217,878 | C++ std::set update is tedious: I can't change an element in place | <p>I find the update operation on <code>std::set</code> tedious since there's no such an API on <a href="http://en.cppreference.com/w/cpp/container/set" rel="noreferrer">cppreference</a>. So what I currently do is something like this:</p>
<pre><code>//find element in set by iterator
Element copy = *iterator;
... // update member value on copy, varies
Set.erase(iterator);
Set.insert(copy);
</code></pre>
<p>Basically the iterator return by <code>Set</code> is a <code>const_iterator</code> and you can't change its value directly.</p>
<p>Is there a better way to do this? Or maybe I should override <code>std::set</code> by creating my own (which I don't know exactly how it works..)</p> | 2,217,889 | 7 | 6 | null | 2010-02-07 18:59:24.587 UTC | 24 | 2022-03-10 11:11:35.19 UTC | 2019-01-17 00:12:11.99 UTC | user283145 | 8,414,561 | null | 217,549 | null | 1 | 79 | c++|stl|set | 29,305 | <p><code>set</code> returns <code>const_iterators</code> (the standard says <code>set<T>::iterator</code> is <code>const</code>, and that <code>set<T>::const_iterator</code> and <code>set<T>::iterator</code> may in fact be the same type - see 23.2.4/6 in n3000.pdf) because it is an ordered container. If it returned a regular <code>iterator</code>, you'd be allowed to change the items value out from under the container, potentially altering the ordering.</p>
<p>Your solution is the idiomatic way to alter items in a <code>set</code>.</p> |
2,078,915 | A regular expression to exclude a word/string | <p>I have a regular expression as follows:</p>
<pre><code>^/[a-z0-9]+$
</code></pre>
<p>This matches strings such as <code>/hello</code> or <code>/hello123</code>.</p>
<p>However, I would like it to exclude a couple of string values such as <code>/ignoreme</code> and <code>/ignoreme2</code>.</p>
<p>I've tried a few variants but can't seem to get any to work!</p>
<p>My latest feeble attempt was </p>
<pre><code>^/(((?!ignoreme)|(?!ignoreme2))[a-z0-9])+$
</code></pre>
<p>Any help would be gratefully appreciated :-)</p> | 2,078,953 | 7 | 1 | null | 2010-01-16 21:07:44.853 UTC | 110 | 2022-07-31 23:12:44.057 UTC | 2010-01-16 21:12:47.12 UTC | lutz | null | null | 251,461 | null | 1 | 413 | regex | 884,477 | <p>Here's yet another way (using a <a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">negative look-ahead</a>): </p>
<pre><code>^/(?!ignoreme|ignoreme2|ignoremeN)([a-z0-9]+)$
</code></pre>
<p>Note: There's only one capturing expression: <code>([a-z0-9]+)</code>. </p> |
2,260,792 | Remove duplicates in list (Prolog) | <p>I am completely new to Prolog and trying some exercises. One of them is:</p>
<blockquote>
<p>Write a predicate set(InList,OutList)
which takes as input an arbitrary
list, and returns a list in which each
element of the input list appears only
once.</p>
</blockquote>
<p>Here is my solution:</p>
<pre><code>member(X,[X|_]).
member(X,[_|T]) :- member(X,T).
set([],[]).
set([H|T],[H|Out]) :-
not(member(H,T)),
set(T,Out).
set([H|T],Out) :-
member(H,T),
set(T,Out).
</code></pre>
<p>I'm not allowed to use any of built-in predicates (It would be better even do not use <code>not/1</code>). The problem is, that <code>set/2</code> gives multiple <em>same</em> solutions. The more repetitions in the input list, the more solutions will result. What am I doing wrong? Thanks in advance.</p> | 2,260,879 | 9 | 1 | null | 2010-02-14 10:49:24.89 UTC | 2 | 2019-02-09 08:28:32.533 UTC | null | null | null | null | 229,151 | null | 1 | 15 | list|prolog | 47,031 | <p>You are getting multiple solutions due to Prolog's backtracking. Technically, each solution provided is correct, which is why it is being generated. If you want just one solution to be generated, you are going to have to stop backtracking at some point. This is what the Prolog <a href="http://en.wikipedia.org/wiki/Cut_%28logic_programming%29" rel="noreferrer">cut</a> is used for. You might find that reading up on that will help you with this problem.</p>
<p>Update: Right. Your <code>member()</code> predicate is evaluating as <code>true</code> in several different ways if the first variable is in multiple positions in the second variable.</p>
<p>I've used the name <code>mymember()</code> for this predicate, so as not to conflict with GNU Prolog's builtin <code>member()</code> predicate. My knowledge base now looks like this:</p>
<pre><code>mymember(X,[X|_]).
mymember(X,[_|T]) :- mymember(X,T).
not(A) :- \+ call(A).
set([],[]).
set([H|T],[H|Out]) :-
not(mymember(H,T)),
set(T,Out).
set([H|T],Out) :-
mymember(H,T),
set(T,Out).
</code></pre>
<p>So, <code>mymember(1, [1, 1, 1]).</code> evaluates as <code>true</code> in three different ways:</p>
<pre><code>| ?- mymember(1, [1, 1, 1]).
true ? a
true
true
no
</code></pre>
<p>If you want to have only one answer, you're going to have to use a cut. Changing the first definition of <code>mymember()</code> to this:</p>
<pre><code>mymember(X,[X|_]) :- !.
</code></pre>
<p>Solves your problem.</p>
<p>Furthermore, you can avoid <code>not()</code> altogether, if you wish, by defining a <code>notamember()</code> predicate yourself. The choice is yours.</p> |
2,068,488 | Are there any practical alternatives to threads? | <p>While reading up on SQLite, I stumbled upon this quote in the FAQ: <a href="http://www.sqlite.org/faq.html#q6" rel="noreferrer">"Threads are evil. Avoid them."</a></p>
<p>I have a lot of respect for SQLite, so I couldn't just disregard this. I got thinking what else I could, according to the "avoid them" policy, use instead in order to parallelize my tasks. As an example, the application I'm currently working on requires a user interface that is always responsive, and needs to poll several websites from time to time (a process which takes at least 30 seconds for each website).</p>
<p>So I opened up the PDF linked from that FAQ, and essentially it seems that the paper suggests several techniques to be applied <em>together</em> with threads, such as barriers or transactional memory - rather than any techniques to replace threads altogether.</p>
<p>Given that these techniques do not fully dispense with threads (unless I misunderstood what the paper is saying), I can see two options: either the SQLite FAQ does <em>not literally</em> mean what it says, or there exist practical approaches that actually <em>avoid</em> the use of threads altogether. Are there any?</p>
<hr>
<p>Just a quick note on tasklets/cooperative scheduling as an alternative - this looks great in small examples, but I wonder whether a large-ish UI-heavy application can be practically parallelized in a solely cooperative way. If you have done this successfully or know of such examples this certainly qualifies as a valid answer!</p> | 2,079,863 | 12 | 2 | null | 2010-01-15 00:07:32.8 UTC | 9 | 2017-04-26 15:41:03.8 UTC | null | null | null | null | 33,080 | null | 1 | 12 | multithreading|language-agnostic|thread-safety | 4,771 | <p><strong>Note</strong>: This answer no longer accurately reflects what I think about this subject. I don't like its overly dramatic, somewhat nasty tone. Also, I am not so certain that the quest for provably correct software has been so useless as I seemed to think back then. I am leaving this answer up because it is accepted, and up-voted, and to edit it into something I currently believe would pretty much vandalize it.</p>
<hr>
<p>I finally got around to reading the paper. Where do I start?</p>
<p>The author is singing an old song, which goes something like this: "If you can't prove the program is correct, we're all doomed!" It sounds best when screamed loudly accompanied by over modulated electric guitars and a rapid drum beat. Academics started singing that song when computer science was in the domain of mathematics, a world where if you don't have a proof, you don't have anything. Even after the first computer science department was cleaved from the mathematics department, they kept singing that song. They are singing that song today, and nobody is listening. Why? Because the rest of us are busy creating useful things, good things out of software that can't be proved correct.</p>
<p>The presence of threads makes it even more difficult to prove a program correct, but who cares? Even without threads, only the most trivial of programs can be proved correct. Why do I care if my non-trivial program, which could not be proved correct, is even more unprovable after I use threading? I don't.</p>
<p>If you weren't sure the author was living in an academic dreamworld, you can be sure of it after he maintains that the coordination language he suggests as an alternative to threads could best be expressed with a "visual syntax" (drawing graphs on the screen). I've never heard that suggestion before, except every year of my career. A language that can only be manipulated by GUI and does not play with any of the programmer's usual tools is not an improvement. The author goes on to cite UML as a shining example of a visual syntax which is "routinely combined with C++ and Java." Routinely in what world?</p>
<p>In the mean time, I and many other programmers go on using threads without all that much trouble. How to use threads well and safely is pretty much a solved problem, as long as you don't get all hung up on provability.</p>
<p>Look. Threading is a big kid's toy, and you do need to know some theory and usage patterns to use them well. Just as with databases, distributed processing, or any of the other beyond-grade-school devices that programmers successfully use every day. But just because you can't prove it correct doesn't mean it's wrong.</p> |
8,960,550 | C++ map<string, vector<char> > access | <p>I've created a map of vectors that looks like this:</p>
<pre><code>map<string, vector<char> > myMap;
string key = "myKey";
vector<char> myVector;
myMap[key] = myVector;
</code></pre>
<p>I want to be able to append 'char's' to the vector in the map but I can't figure out how to access said vector to append once the particular key/value(vector) has been created. Any suggestions? I'm iterating over char's and might be adding a lot to the vector as I go so it would be nice to have a simple way to do it. Thanks.</p>
<hr>
<p>I would like the vector in map to be appended as I go. I don't need the original vector...I just need to return the map of key/vector's that I've created (after apending) so that I can pass it to another function. What does the * in map* > do? Is that refrencing a pointer? (I haven't gotten there in lecture yet) Also, do I need:
myMap[key]->push_back('s');
or
myMap[key].push_back('s');
??</p> | 8,960,568 | 4 | 2 | null | 2012-01-22 10:56:24.307 UTC | 7 | 2012-01-22 19:25:21.4 UTC | 2012-01-22 19:25:21.4 UTC | null | 50,049 | null | 1,130,069 | null | 1 | 13 | c++|stl|vector|map | 61,498 | <p>To append:</p>
<pre><code>myMap[key].push_back('c');
</code></pre>
<p>Or use <code>myMap.find</code>, but then you have to check whether you get an <code>end</code> iterator. <code>operator[]</code> returns a reference to the <code>vector</code>.</p>
<p>But this modifies the <code>vector</code> stored in the <code>map</code>, not the original one, since you've stored a copy in the <code>map</code> with <code>myMap[key] = myVector;</code>. If that's not what you want, you should rethink your design and maybe store (smart) pointers to vectors in your map.</p> |
17,923,635 | Found unsigned entry in resource | <p>i have the following JNLP file:</p>
<pre><code><jnlp spec="1.0+" codebase="http://****:****" href="tcm2012.jnlp">
<information>
<title>TCM 2012</title>
<vendor>Drift og Performance, *** Servicecenter</vendor>
<homepage href="http://******"/>
<description/>
</information>
<security>
<all-permissions/>
</security>
<resources>
<j2se version="1.6+"/>
<jar href="tcm2012.jar"/>
</resources>
<application-desc main-class="com.****.kundeservice.TCMApplication"/>
</jnlp>
</code></pre>
<p>Now when i try to run in from the web i get the following error:</p>
<pre><code>Found unsigned entry in resource
</code></pre>
<p>With the following exepction</p>
<pre><code>com.sun.deploy.net.JARSigningException: Found unsigned entry in resource: http://*****:****/tcm2012.jar
at com.sun.javaws.security.SigningInfo.getCommonCodeSignersForJar(Unknown Source)
at com.sun.javaws.security.SigningInfo.check(Unknown Source)
at com.sun.javaws.security.JNLPSignedResourcesHelper.checkSignedResourcesHelper(Unknown Source)
at com.sun.javaws.security.JNLPSignedResourcesHelper.checkSignedResources(Unknown Source)
at com.sun.javaws.Launcher.prepareResources(Unknown Source)
at com.sun.javaws.Launcher.prepareAllResources(Unknown Source)
at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source)
at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source)
at com.sun.javaws.Launcher.launch(Unknown Source)
at com.sun.javaws.Main.launchApp(Unknown Source)
at com.sun.javaws.Main.continueInSecureThread(Unknown Source)
at com.sun.javaws.Main.access$000(Unknown Source)
at com.sun.javaws.Main$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
</code></pre>
<p>Does anyone know how to fix this problem?</p> | 23,874,664 | 5 | 10 | null | 2013-07-29 12:09:02.427 UTC | 5 | 2016-11-11 15:12:16.837 UTC | 2016-10-27 13:44:40.003 UTC | null | 1,647,457 | null | 1,647,457 | null | 1 | 27 | java|jar|jnlp|java-web-start | 74,793 | <p>This worked for me:</p>
<p>Go the Control Panel/Java.</p>
<p>Then click on “Settings” button and activate the option “Keep temporary files on my computer.”</p>
<p>It’s weird, but it worked!</p> |
6,322,194 | Cocoa bindings for the Go language | <p>Is it possible to write macOS/Cocoa applications in Google Go?</p>
<p>Is there a Go-Obj-C bridge? (it seems to me that Obj-C dynamism would be a great fit for Golang's interfaces)</p>
<p>Can I at least link the two together and make them talk to each other via plain-old C functions?</p> | 35,750,248 | 3 | 5 | null | 2011-06-12 13:25:39.86 UTC | 6 | 2021-12-29 00:36:39.553 UTC | 2019-09-28 12:36:15.817 UTC | null | 27,009 | null | 27,009 | null | 1 | 35 | cocoa|go|cocoa-bindings|scripting-bridge | 8,651 | <p>You can have a look at <a href="http://thread0.me/2015/07/gogoa-cocoa-bindings-for-go/" rel="nofollow">my blog post as an example</a>. I'm afraid I didn't keep working on it, but here's <a href="https://github.com/alediaferia/gogoa" rel="nofollow">the source code</a> that can help you setting up a bare Cocoa/ObjC/Go project.</p>
<p>You're gonna be able to do something like this, as mentioned in the README.</p>
<pre><code>package main
import (
"github.com/alediaferia/gogoa"
)
func main() {
app := gogoa.SharedApplication()
window := gogoa.NewWindow(0, 0, 200, 200)
window.SetTitle("Gogoga!")
window.MakeKeyAndOrderFront()
app.Run()
}
</code></pre> |
35,821,245 | github: server certificate verification failed | <p>I just created a github account and a repository therein, but when trying to create a local working copy using the recommende url via</p>
<pre><code>git clone https://github.com/<user>/<project>.git
</code></pre>
<p>I get an error like</p>
<blockquote>
<p>fatal: unable to access '<a href="https://github.com/<user>/<project>.git" rel="noreferrer">https://github.com/<user>/<project>.git</a>': server certificate verification failed. CAfile: /home/<user>/.ssl/trusted.pem CRLfile: none</p>
</blockquote>
<p>I'm on Debian Jessie, and I would have expected both Debian and GitHub to provide / rely on a selection of commonly accepted CAs, but apparently my system doesn't trust GibHub's certificate.</p>
<p>Any simple way to fix this (without the frequently recommended "GIT_SSL_NO_VERIFY=true" hack and similar work-arounds)?</p>
<p>EDIT:</p>
<p>Additional information:</p>
<ul>
<li>The ca-certificate package is installed.</li>
<li>Installing cacert.org's certificates as
suggested by @VonC didn't change anything.</li>
<li>My personal ~/.ssl/trusted.pem file does contain a couple of entries, but to be
honest, I don't remember where the added certificates came from...</li>
<li><p>When removing ~/.ssl/trusted.pem, the git error message changes to</p>
<pre><code>fatal: unable to access 'https://github.com/tcrass/scans2jpg.git/': Problem with the SSL CA cert (path? access rights?)
</code></pre></li>
</ul>
<p>EDIT:</p>
<p>@VonC's advice regarding the git https.sslCAinfo option put me on the right track -- I just added the downloaded cacert.org CAs to my trusted.pem, and now git doesn't complain anymore.</p> | 35,824,116 | 12 | 3 | null | 2016-03-05 23:35:36.783 UTC | 38 | 2022-09-07 10:37:56.973 UTC | 2018-01-06 22:52:53.3 UTC | null | 3,885,376 | null | 6,023,799 | null | 1 | 80 | git|github|debian | 208,201 | <p>2016: Make sure first that you have certificates installed on your Debian in <code>/etc/ssl/certs</code>.</p>
<p>If not, reinstall them:</p>
<pre><code>sudo apt-get install --reinstall ca-certificates
</code></pre>
<p>Since that <a href="https://www.brightbox.com/blog/2014/03/04/add-cacert-ubuntu-debian/" rel="nofollow noreferrer">package does not include <em>root</em> certificates</a>, add:</p>
<pre><code>sudo mkdir /usr/local/share/ca-certificates/cacert.org
sudo wget -P /usr/local/share/ca-certificates/cacert.org http://www.cacert.org/certs/root.crt http://www.cacert.org/certs/class3.crt
sudo update-ca-certificates
</code></pre>
<p>Make sure your git does reference those CA:</p>
<pre><code>git config --global http.sslCAinfo /etc/ssl/certs/ca-certificates.crt
</code></pre>
<hr />
<p><a href="https://stackoverflow.com/users/616460/jason-c">Jason C</a> mentions another potential cause (<a href="https://stackoverflow.com/questions/35821245/github-server-certificate-verification-failed/35824116#comment72366364_35824116">in the comments</a>):</p>
<blockquote>
<p>It was the clock. The NTP server was down, the system clock wasn't set properly, I didn't notice or think to check initially, and the incorrect time was causing verification to fail.</p>
</blockquote>
<p><a href="https://stackoverflow.com/a/21181447/6309">Certificates are time sensitive</a>.</p>
<hr />
<p>2022: <a href="https://stackoverflow.com/users/334719/auspex">Auspex</a> adds in <a href="https://stackoverflow.com/questions/35821245/github-server-certificate-verification-failed/35824116?noredirect=1#comment129795717_35824116">the comments</a>:</p>
<blockquote>
<p>ca-certificates does indeed contain root certificates.<br />
It doesn't contain the CAcert root certificates.</p>
<p>This might have been a good answer 6 1/2 years ago, but those certificates were suspect way back then and haven't improved.<br />
There's a reason they're not in the <code>ca-certificates</code> package.</p>
<p>These days we have <a href="https://letsencrypt.org/" rel="nofollow noreferrer">LetsEncrypt</a>, so everyone has certificates with reliable auditing and nobody needs to rely on CAcert.</p>
</blockquote> |
35,285,309 | FileNotFoundException (permission denied) when trying to write file to sdcard in Android | <p>As you can notice from title, I have a problem with writing file to sdcard in Android. I've checked <a href="https://stackoverflow.com/questions/4823992/java-io-filenotfoundexception-permission-denied-when-trying-to-write-to-the-an">this question</a> but it didn't help me. I want to write file that will be in public space on sdcard so that any other app could read it.</p>
<p>First, I check if sdcard is mounted:</p>
<pre><code>Environment.getExternalStorageState();
</code></pre>
<p>Then, I run this code:</p>
<pre><code>File baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
baseDir.mkdirs();
File file = new File(baseDir, "file.txt");
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
Log.d("NEWFILE", file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
</code></pre>
<p>I have:</p>
<pre><code><manifest>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
...
</application>
</manifest>
</code></pre>
<p>in my AndroidManifest.xml.</p>
<p>Exact error is this:</p>
<pre><code>java.io.FileNotFoundException: /storage/1510-2908/Download/secondFile.txt: open failed: EACCES (Permission denied)
</code></pre>
<p>I'm testing my code on emulator (emulating Nexus5 API 23). My minimum required SDK version is 19 (4.4 Kitkat).</p>
<hr>
<p>Also, everything works fine with writing files to private folder on sdcard with same code so I'd say former code should work too:</p>
<pre><code>File newFile = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "esrxdtcfvzguhbjnk.txt");
newFile.getParentFile().mkdirs();
try {
FileOutputStream out = new FileOutputStream(newFile);
out.flush();
out.close();
Log.d("NEWFILE", newFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
</code></pre>
<p>Does anyone have any clue what could be the problem? Could it be that somehow KitKat 4.4 just doesn't allow writing to public space in sdcard anymore or?</p> | 35,285,667 | 1 | 5 | null | 2016-02-09 06:27:57.273 UTC | null | 2016-02-09 07:15:15.7 UTC | 2017-05-23 11:33:25.387 UTC | null | -1 | null | 1,344,487 | null | 1 | 23 | java|android|filenotfoundexception|android-permissions | 40,638 | <blockquote>
<ol>
<li>Everything works fine with writing files to private folder on sdcard</li>
</ol>
</blockquote>
<p>Beginning with Android 4.4, these permissions are not required if you're
reading or writing only files that are private to your app. For more information, see <a href="http://developer.android.com/guide/topics/data/data-storage.html#AccessingExtFiles" rel="noreferrer">saving files that are app-private.</a></p>
<blockquote>
<ol start="2">
<li>FileNotFoundException (permission denied) when trying to write file to sdcard in Android</li>
</ol>
</blockquote>
<p>As you are trying to write the file in emulator having API 23(Marshmallow), You need to Request <code>WRITE_EXTERNAL_STORAGE</code> permission at runtime also. Check <a href="http://developer.android.com/training/permissions/requesting.html" rel="noreferrer">this</a> and <a href="http://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en" rel="noreferrer">this</a> for more detail.</p> |
16,184,653 | Sorting ArrayList of Arraylist<String> in java | <p>I have an ArrayList of ArrayList of String.</p>
<p>In Outer ArrayList on each index each Inner ArrayList has four items have four parameters.</p>
<ol>
<li>Contacts Id</li>
<li>Contacts Name</li>
<li>Contacts Adress</li>
<li>Contacts Number</li>
</ol>
<p>Now I want to sort the complete ArrayList of the on the basis of Contact Name Parameter.</p>
<p>Means I want to access the outer Arraylist and the inner ArrayList present on each index of outer Arraylist should be sorted according to contact Name.</p>
<p>Comparator / Comparable Interfaces not likely to help me.</p>
<p>Collection.sort can't help me </p>
<p><a href="https://stackoverflow.com/questions/13154108/sorting-arraylist-of-arraylist-of-bean">Sorting Arraylist of Arraylist of Bean</a>. I have read this post but it is for <code>ArrayList</code> of <code>ArrayList<Object></code>. How to figure out this problem?</p> | 16,184,857 | 7 | 4 | null | 2013-04-24 06:15:06.717 UTC | null | 2016-02-05 13:35:31.79 UTC | 2017-05-23 12:32:10.313 UTC | null | -1 | null | 2,218,452 | null | 1 | 5 | java|sorting|arraylist|comparator|comparable | 40,026 | <p>Assuming your Lists in your List has Strings in the order id, name, address and number (i.e. name is at index 1), you can use a <code>Comparator</code>, as follows:</p>
<pre><code>List<List<String>> list;
Collections.sort(list, new Comparator<List<String>> () {
@Override
public int compare(List<String> a, List<String> b) {
return a.get(1).compareTo(b.get(1));
}
});
</code></pre>
<p>Incidentally, it matters not that you are using <code>ArrayList</code>: It is good programming practice to declare variables using the abstract type, i.e. <code>List</code> (as I have in this code).</p> |
19,035 | JavaScript Load Order | <p>I am working with both <a href="http://activemq.apache.org/ajax.html" rel="nofollow noreferrer">amq.js</a> (ActiveMQ) and <a href="http://code.google.com/apis/maps/documentation/reference.html" rel="nofollow noreferrer">Google Maps</a>. I load my scripts in this order</p>
<pre><code><head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>AMQ & Maps Demo</title>
<!-- Stylesheet -->
<link rel="stylesheet" type="text/css" href="style.css"></link>
<!-- Google APIs -->
<script type="text/javascript" src="http://www.google.com/jsapi?key=abcdefg"></script>
<!-- Active MQ -->
<script type="text/javascript" src="amq/amq.js"></script>
<script type="text/javascript">amq.uri='amq';</script>
<!-- Application -->
<script type="text/javascript" src="application.js"></script>
</head>
</code></pre>
<p>However in my application.js it loads Maps fine but I get an error when trying to subscribe to a Topic with AMQ. AMQ depends on prototype which the error console in Firefox says object is not defined. I think I have a problem with using the amq object before the script is finished loading. <strong>Is there a way to make sure both scripts load before I use them in my application.js?</strong> </p>
<p>Google has this nice function call <code>google.setOnLoadCallback(initialize);</code> which works great. I'm not sure amq.js has something like this.</p> | 19,348 | 8 | 0 | null | 2008-08-20 22:53:25.373 UTC | 7 | 2018-03-06 07:23:08.737 UTC | 2018-03-06 07:23:08.737 UTC | null | 1,905,949 | Bernie Perez | 1,992 | null | 1 | 30 | javascript|google-maps|activemq | 38,611 | <blockquote>
<p><strong>Is there a way to make sure both scripts load before I use them in my application.js?</strong></p>
</blockquote>
<p>JavaScript files should load sequentially <em>and block</em> so unless the scripts you are depending on are doing something unusual all you should need to do is load application.js after the other files.</p>
<p><a href="http://yuiblog.com/blog/2008/07/22/non-blocking-scripts/" rel="noreferrer">Non-blocking JavaScript Downloads</a> has some information about how scripts load (and discusses some techniques to subvert the blocking).</p> |
413,699 | Restore SQL Server 2008 DB *to* SQL Server 2005 | <p>Got myself in a bit of a pickle here ... working on a CMS project, under the assumption that sql server 2008 was greenlighted as the db of choice. Well it wasn't, we now have to backport all of our content out SQL Server 2008 and into SQL Server 2005. </p>
<p>A simple backup/restore procedure yields: "RESTORE HEADERONLY is terminating abnormally. (Microsoft SQL Server, Error: 3241)". </p>
<p>Unfortunately, exporting the data to an excel spreadsheet yields multiple OLE errors which I believe is actually a problem in the db of the cms. </p>
<p>Does anyone out there have other approaches they would like to recommend for this task? Thanks in advance</p> | 413,801 | 9 | 1 | null | 2009-01-05 16:36:40.583 UTC | 5 | 2016-10-01 18:09:52.33 UTC | null | null | null | null | 49,611 | null | 1 | 21 | sql-server-2005|sql-server-2008 | 47,103 | <p>Use <a href="http://www.red-gate.com/products/sql_data_compare/index.htm" rel="nofollow noreferrer">RedGate</a>:</p>
<blockquote>
<p>tool for comparing and deploying SQL Server database contents.</p>
<p>You can work with live databases, backups, or SQL scripts in source control. Damaged or missing data can be restored to a single row, without the need for a full database recovery.</p>
<p>SQL Data Compare helps you compare and deploy changes quickly, simply, and with zero errors...</p>
</blockquote> |
469,597 | Destruction order of static objects in C++ | <p>Can I control the order static objects are being destructed?
Is there any way to enforce my desired order? For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static object?</p> | 469,613 | 9 | 0 | null | 2009-01-22 15:32:42.09 UTC | 15 | 2016-11-25 19:45:01.257 UTC | 2014-07-17 11:32:19.333 UTC | null | 2,642,204 | Gal Goldman | 46,418 | null | 1 | 59 | c++|static|destruction | 40,750 | <p>The static objects are destructed in the reverse order of construction. And the order of construction is very hard to control. The only thing you can be sure of is that two objects defined in the same compilation unit will be constructed in the order of definition. Anything else is more or less random.</p> |
784,173 | What are the performance characteristics of sqlite with very large database files? | <p><strong>2020 update</strong>, about 11 years after the question was posted and later closed, preventing newer answers.</p>
<p><strong>Almost everything written here is obsolete. Once upon a time sqlite was limited to the memory capacity or to 2 GB of storage (32 bits) or other popular numbers... well, that was a long time ago.</strong></p>
<p><strong><a href="https://www.sqlite.org/limits.html" rel="noreferrer">Official limitations are listed here</a>. Practically sqlite is likely to work as long as there is storage available</strong>. It works well with dataset larger than memory, it was originally created when memory was thin and it was a very important point from the start.</p>
<p>There is absolutely no issue with storing 100 GB of data. It could probably store a TB just fine but eventually that's the point where you need to question whether SQLite is the best tool for the job and you probably want features from a full fledged database (remote clients, concurrent writes, read-only replicas, sharding, etc...).</p>
<hr />
<p>Original:</p>
<p>I know that sqlite doesn't perform well with extremely large database files even when they are supported (there used to be a comment on the sqlite website stating that if you need file sizes above 1GB you may want to consider using an enterprise rdbms. Can't find it anymore, might be related to an older version of sqlite).</p>
<p>However, for my purposes I'd like to get an idea of how bad it really is before I consider other solutions.</p>
<p>I'm talking about sqlite data files in the multi-gigabyte range, from 2GB onwards.
Anyone have any experience with this? Any tips/ideas?</p> | 811,862 | 9 | 6 | null | 2009-04-24 01:09:33.047 UTC | 198 | 2020-10-01 09:36:06.973 UTC | 2020-10-01 09:36:06.973 UTC | null | 5,994,461 | null | 92,633 | null | 1 | 355 | database|performance|sqlite | 193,179 | <p>So I did some tests with sqlite for very large files, and came to some conclusions (at least for my specific application).</p>
<p>The tests involve a single sqlite file with either a single table, or multiple tables. Each table had about 8 columns, almost all integers, and 4 indices.</p>
<p>The idea was to insert enough data until sqlite files were about 50GB.</p>
<p><strong>Single Table</strong></p>
<p>I tried to insert multiple rows into a sqlite file with just one table. When the file was about 7GB (sorry I can't be specific about row counts) insertions were taking far too long. I had estimated that my test to insert all my data would take 24 hours or so, but it did not complete even after 48 hours. </p>
<p>This leads me to conclude that a single, very large sqlite table will have issues with insertions, and probably other operations as well.</p>
<p>I guess this is no surprise, as the table gets larger, inserting and updating all the indices take longer.</p>
<p><strong>Multiple Tables</strong></p>
<p>I then tried splitting the data by time over several tables, one table per day. The data for the original 1 table was split to ~700 tables. </p>
<p>This setup had no problems with the insertion, it did not take longer as time progressed, since a new table was created for every day.</p>
<p><strong>Vacuum Issues</strong></p>
<p>As pointed out by i_like_caffeine, the VACUUM command is a problem the larger the sqlite file is. As more inserts/deletes are done, the fragmentation of the file on disk will get worse, so the goal is to periodically VACUUM to optimize the file and recover file space.</p>
<p>However, as pointed out by <a href="http://www.sqlite.org/lang_vacuum.html" rel="noreferrer">documentation</a>, a full copy of the database is made to do a vacuum, taking a very long time to complete. So, the smaller the database, the faster this operation will finish.</p>
<p><strong>Conclusions</strong></p>
<p>For my specific application, I'll probably be splitting out data over several db files, one per day, to get the best of both vacuum performance and insertion/delete speed.</p>
<p>This complicates queries, but for me, it's a worthwhile tradeoff to be able to index this much data. An additional advantage is that I can just delete a whole db file to drop a day's worth of data (a common operation for my application).</p>
<p>I'd probably have to monitor table size per file as well to see when the speed will become a problem.</p>
<p>It's too bad that there doesn't seem to be an incremental vacuum method other than <a href="http://www.sqlite.org/pragma.html#pragma_auto_vacuum" rel="noreferrer">auto vacuum</a>. I can't use it because my goal for vacuum is to defragment the file (file space isn't a big deal), which auto vacuum does not do. In fact, documentation states it may make fragmentation worse, so I have to resort to periodically doing a full vacuum on the file.</p> |
368,281 | SVN - Not a working copy error | <p>I'm pulling my hair out on this one.</p>
<p>I have a site which is version controlled using Subversion. I use aptana (eclipse, subclipse) to do the svn. I have been checking in and out files, updating etc and everything is fine. However the system we have been building has been adding its own files and folders.</p>
<p>When I try to commit these, it tells me <code><path></code> is not a working copy. If I try to do a cleanup then it gives the same error. I found I can manually add each file to version control but this throws the same error. Doing an update doesn't help, refreshing the workspace does not do anything either. Cleanup seems to die after the error and then the directory is locked.</p>
<p>I know you're supposed to add files using SVN, but how on earth do you work with generated files? How do I get around this "<code><folder></code> is not a working copy directory" error? How do I get Subversion to just look at the files and add them to its repository?</p> | 368,307 | 10 | 0 | null | 2008-12-15 12:56:58.373 UTC | 7 | 2016-08-28 06:42:24.803 UTC | 2011-03-28 03:38:17.657 UTC | null | 143,804 | Paul M | 28,241 | null | 1 | 26 | svn|aptana|working-copy | 89,607 | <p>If you want the generated files to be added to SVN, use <code>svn add</code> to recursively add them - this will make sure that all directories are part of the working copy, and all files and directories are added to SVN, and will be committed as part of the next <code>svn commit</code>.</p>
<p>However, often generated files and folders should not be added to SVN, since they are generated <em>from</em> the source files as part of a build. In this case, you should mark the with <a href="http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.ignore.html" rel="noreferrer">svn:ignore</a> so that they are not part of the working copy.</p> |
518,579 | Why can't I select a null value in a ComboBox? | <p>In WPF, it seems to be impossible to select (with the mouse) a "null" value from a ComboBox. <strong>Edit</strong> To clarify, this is .NET 3.5 SP1.</p>
<p>Here's some code to show what I mean. First, the C# declarations:</p>
<pre><code>public class Foo
{
public Bar Bar { get; set; }
}
public class Bar
{
public string Name { get; set; }
}
</code></pre>
<p>Next, my Window1 XAML:</p>
<pre><code><Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<ComboBox x:Name="bars"
DisplayMemberPath="Name"
Height="21"
SelectedItem="{Binding Bar}"
/>
</StackPanel>
</Window>
</code></pre>
<p>And lastly, my Window1 class:</p>
<pre><code>public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
bars.ItemsSource = new ObservableCollection<Bar>
{
null,
new Bar { Name = "Hello" },
new Bar { Name = "World" }
};
this.DataContext = new Foo();
}
}
</code></pre>
<p>With me? I have a ComboBox whose items are bound to a list of Bar instances, one of which is null. I have bound the window to an instance of Foo, and the ComboBox is displaying the value of its Bar property.</p>
<p>When I run this app, the ComboBox starts with an empty display because Foo.Bar is null by default. That's fine. If I use the mouse to drop the ComboBox down and select the "Hello" item, that works too. But then if I try to re-select the empty item at the top of the list, the ComboBox closes and returns to its previous value of "Hello"!</p>
<p>Selecting the null value with the arrow keys works as expected, and setting it programatically works too. It's only selecting with a mouse that doesn't work.</p>
<p>I know an easy workaround is to have an instance of Bar that represents null and run it through an IValueConverter, but can someone explain why selecting null with the mouse doesn't work in WPF's ComboBox?</p> | 1,904,186 | 10 | 4 | null | 2009-02-06 00:03:44.203 UTC | 11 | 2017-04-18 07:39:02.097 UTC | 2009-02-06 01:25:41.777 UTC | Matt Hamilton | 615 | Matt Hamilton | 615 | null | 1 | 48 | wpf|data-binding|combobox | 42,662 | <p><strong>The null "item" is not being selected by the keyboard at all - rather the previous item is being unselected and no subsequent item is (able to be) selected.</strong> This is why, after "selecting" the null item with the keyboard, you are thereafter unable to re-select the previously selected item ("Hello") - except via the mouse!</p>
<p><em>In short, you can neither select nor deselect a null item in a ComboBox. When you think you are doing so, you are rather deselecting or selecting the previous or a new item.</em></p>
<p>This can perhaps best be seen by adding a background to the items in the ComboBox. You will notice the colored background in the ComboBox when you select "Hello", but when you deselect it via the keyboard, the background color disappears. We know this is not the null item, because the null item actually has the background color when we drop the list down via the mouse!</p>
<p>The following XAML, modified from that in the original question, will put a LightBlue background behind the items so you can see this behavior.</p>
<pre><code><Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<ComboBox x:Name="bars" Height="21" SelectedItem="{Binding Bar}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid Background="LightBlue" Width="200" Height="20">
<TextBlock Text="{Binding Name}" />
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</Window>
</code></pre>
<p>If you want further validation, you can handle the SelectionChanged event on the ComboBox and see that "selecting the null item" actually gives an empty array of AddedItems in its SelectionChangedEventArgs, and "deselecting the null item by selecting 'Hello' with the mouse" gives an empty array of RemovedItems.</p> |
707,832 | How do I pass a variable from one Thread Group to another in JMeter | <p>I have a JMeter test with 2 Thread Groups - the first is a single thread (which creates some inventory) and the second has multiple threads (which purchase all the inventory). I use BeanShell Assertions and XPath Extractors to parse the returned value (which is XML) and store variables (such as the ids of the items to be purchased). </p>
<p>But, values that are created in the first Thread Group, whether extracted into standard <code>${jmeter}</code> type variables, or <code>${__BeanShell(vars.get("jmeter"))}</code> type vars, are not available in the second Thread Group. Is there anyway to create a variable in the first Thread Group and make it visible to the second?</p> | 710,156 | 10 | 0 | null | 2009-04-02 00:08:52.737 UTC | 12 | 2021-12-12 18:39:32.87 UTC | 2012-01-10 00:12:38.553 UTC | null | 648,313 | Todd R | 61,592 | null | 1 | 61 | java|testing|jmeter|beanshell | 99,772 | <p>I was not able to do this with variables (since those are local to individual threads). However, I was able to solve this problem with properties!</p>
<p>Again, my first ThreadGroup does all of the set up, and I need some information from that work to be available to each of the threads in the second ThreadGroup. I have a BeanShell Assertion in the first ThreadGroup with the following:</p>
<pre><code>${__setProperty(storeid, ${storeid})};
</code></pre>
<p>The ${storeid} was extracted with an XPath Extractor. The BeanShell Assertion does other stuff, like checking that storeid was returned from the previous call, etc.</p>
<p>Anyway, in the second ThreadGroup, I can use the value of the "storeid" property in Samplers with the following:</p>
<pre><code>${__property(storeid)}
</code></pre>
<p>Works like a charm!</p> |
977,615 | Many to Many Relation Design - Intersection Table Design | <p>I'm wondering what a better design is for the intersection table for a many-to-many relationship.</p>
<p>The two approaches I am considering are:</p>
<pre><code>CREATE TABLE SomeIntersection
(
IntersectionId UNIQUEIDENTIFIER PRIMARY KEY,
TableAId UNIQUEIDENTIFIER REFERENCES TableA NOT NULL,
TableBId UNIQUEIDENTIFIER REFERENCES TableB NOT NULL,
CONSTRAINT IX_Intersection UNIQUE(TableAId, TableBId )
)
</code></pre>
<p>or</p>
<pre><code>CREATE TABLE SomeIntersection
(
TableAId UNIQUEIDENTIFIER REFERENCES TableA NOT NULL,
TableBId UNIQUEIDENTIFIER REFERENCES TableB NOT NULL,
PRIMARY KEY(TableAId, TableBId )
)
</code></pre>
<p>Are there benefits to one over the other?<br>
<strong>EDIT 2:****Please Note:</strong> I plan to use Entity Framework to provide an API for the database. With that in mind, does one solution work better with EF than the other?</p>
<p><strong>EDIT:</strong> On a related note, for a intersection table that the two columns reference the same table (example below), is there a way to make the two fields differ on a record?</p>
<pre><code>CREATE TABLE SomeIntersection
(
ParentRecord INT REFERENCES TableA NOT NULL,
ChildRecord INT REFERENCES TableA NOT NULL,
PRIMARY KEY(TableAId, TableBId )
)
</code></pre>
<p>I want to prevent the following</p>
<pre><code>ParentRecord ChildRecord
=================================
1 1 --Cyclical reference!
</code></pre> | 977,646 | 11 | 2 | null | 2009-06-10 19:19:02.087 UTC | 16 | 2009-06-11 17:14:11.583 UTC | 2009-06-11 16:07:27.61 UTC | null | 53,587 | null | 53,587 | null | 1 | 23 | sql|tsql|database-design | 12,997 | <p>The second version is the best for me, it avoids the creation of an extra index.</p> |
245,584 | D Templates: Coolest Hack | <p>What is the coolest <strong>somewhat practical</strong> metaprogramming hack you've done or seen done in the D programming language? Somewhat practical means excluding, for example, the compile-time raytracer.</p> | 704,969 | 12 | 0 | 2011-01-08 08:29:42.793 UTC | 2008-10-29 02:11:21.493 UTC | 9 | 2013-04-05 13:18:37.5 UTC | 2012-08-08 01:50:16.917 UTC | KiwiBastard | 1,288 | dsimcha | 23,903 | null | 1 | 22 | templates|metaprogramming|d | 2,576 | <p>In terms of the outright coolest, I'd have to say Kirk McDonald's <a href="http://pyd.dsource.org/" rel="noreferrer" title="PyD">PyD</a> (and other similar bindings) as these have do to a huge amount of work in detecting and handling lots of different types, as well as complex code generation.</p>
<p>That said, PyD only wins because <a href="http://www.digitalmars.com/d/archives/digitalmars/D/BLADE_0.2Alpha_Vector_operations_with_mixins_expression_templates_51617.html" rel="noreferrer">BLADE</a> technically uses CTFE, not templates.</p>
<p>On a more personal note, D templates have gotten extensive use in a research project of mine. It's a simulation framework where modules can define their own private data types. Exposing a new user type to the framework requires a single line of code which creates an XML parser for the type as well as associated network serialisation/deserialisation code.</p> |
46,214 | Good ways to improve jQuery selector performance? | <p>I'm looking for any way that I can improve the selector performance of a jQuery call. Specifically things like this:</p>
<p>Is <code>$("div.myclass")</code> faster than <code>$(".myclass")</code></p>
<p>I would think it might be, but I don't know if jQuery is smart enough to limit the search by tag name first, etc. Anyone have any ideas for how to formulate a jQuery selector string for best performance?</p> | 46,253 | 12 | 0 | null | 2008-09-05 16:22:26.837 UTC | 32 | 2012-07-13 17:37:11.57 UTC | 2010-02-13 00:28:47.927 UTC | Jeff Atwood | 89,989 | JC Grubbs | 4,541 | null | 1 | 74 | javascript|jquery|performance|css-selectors | 29,977 | <p>There is no doubt that <strong>filtering by tag name first is much faster</strong> than filtering by classname.</p>
<p>This will be the case until all browsers implement getElementsByClassName natively, as is the case with getElementsByTagName.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.