_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d17301 | val | remove holder and close if loop for inflate like how i am closed also use logic for toggle inside getGroupView .because every time u scroll the listview the getGroupView get called so every time it this method has to check the condition.
private WifiAPListActivity context;
public ArrayList<ExpandListGroup> groups;
private WifiManager wifiManager;
WifiStatus checkWifiStatus;
public ToggleButton togglebtn;
int pos;
Holder holder;
int previousPosition = -1;
private static final int CHILD_COUNT = 1;
public WifiAPListAdapter(WifiAPListActivity context,
ArrayList<ExpandListGroup> result) {
this.context = context;
this.groups = result;
wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
checkWifiStatus = new WifiStatus(context);
}
public Object getChild(int groupPosition, int childPosition) {
return groups.get(groupPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return groupPosition;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View view, ViewGroup parent) {
previousPosition = groupPosition;
ExpandListGroup child = (ExpandListGroup) getChild(groupPosition,
groupPosition);
// Log.i("", "getChildView: "+childPosition);
if (view == null) {
holder = new Holder();
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = infalInflater.inflate(R.layout.list_child_item, null);
}
label_ssid = (TextView) view.findViewById(R.id.label_ssid);
tv_ssid = (TextView) view.findViewById(R.id.tvssid);
label_bssid = (TextView) view.findViewById(R.id.label_bssid);
tv_bssid = (TextView) view.findViewById(R.id.tvbssid);
label_capabilities = (TextView) view
.findViewById(R.id.label_capabilities);
tv_capabilities = (TextView) view
.findViewById(R.id.tvcapabilities);
label_signalStrength = (TextView) view
.findViewById(R.id.label_signalstrength);
tv_signalStrength = (TextView) view
.findViewById(R.id.tvsignalstrength);
wifi_signalimg = (ImageView) view.findViewById(R.id.signal);
// *********************setting data to the child list**************
tv_ssid.setText(child.getSSID());
tv_bssid.setText(child.getBSSID());
tv_capabilities.setText(child.getCapabilities());
tv_signalStrength.setText(child.getData());
Bitmap bitmap = setSignalImage(Integer.parseInt(child.getData()));
wifi_signalimg.setImageBitmap(bitmap);
return view;
}
public int getChildrenCount(int groupPosition) {
Log.i("", "getChildrenCount: " + groupPosition);
return CHILD_COUNT;
}
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
public int getGroupCount() {
Log.i("", "getGroupCount: " + groups.size());
return groups.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isLastChild, View view,
ViewGroup parent) {
Log.i("", "getGroupView: " + groupPosition);
if (view == null) {
holder = new Holder();
LayoutInflater inf = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inf.inflate(R.layout.list_parent_items, null);
}
tv_ssid = (TextView) view.findViewById(R.id.ssid);
tv_bssid = (TextView) view.findViewById(R.id.bssid);
btn_toggle = (ToggleButton) view.findViewById(R.id.togBtn);
// holder.btn_toggle.setTag(groups.get(groupPosition).getBSSID());
// holder.btn_toggle.setTag(groups.get(groupPosition).getBSSID());
tv_ssid.setText(groups.get(groupPosition).getSSID());
tv_bssid.setText(groups.get(groupPosition).getBSSID());
return view;
}
public void toggle(View v) {
if (btn_toggle.isChecked()) {
}
Log.i("", "toggle");
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
A: This is happening because of mechanism of Recycling of Views. I had written a blog post for the same taking into consideration ListView.
If you are not aware about recycling of views then probably you must read this blog to get exact idea about how recycling of view works! | unknown | |
d17302 | val | In general, never close a document based application when the last window closes. The user will expect to be able to open a new document without relaunching the application, and it will confuse them if they can't.
For non-document based applications, you need to consider a few things:
*
*How long does it take for my application to open? If it takes more than a second, you should probably not quit.
*Does my application need a window to be useful? If your application can do work without windows, you should not quit.
iTunes doesn't quit because, as Anne mentioned, you don't need a window to play music (question 2). It is also not based on Cocoa, so it is much more difficult to close after the last window, especially since it allows you to open windows for specific playlists so there are an indefinite number of possible windows to be open.
In my opinion, Address Book does not need to stay open. This could be a left-over design decision from older versions of OS X, or it could be that someone at Apple just thought it was better to leave it open (maybe so you can add a contact?). Both iTunes and Address Book provide access to their main interfaces through the Window menu, as well as a keyboard shortcut (Option+Command+1 for iTunes, Command+0 for Address Book).
A: Per Apple's Human Interface Guidelines (a guide for Mac developers):
In most cases, applications that are
not document-based should quit when
the main window is closed. For
Example, System Preferences quits if
the user closes the window. If an
application continues to perform some
function when the main window is
closed, however, it may be appropriate
to leave it running when the main
window is closed. For example, iTunes
continues to play when the user closes
the main window.
A: The main iTunes window can be reopened from the 'Window' menu. Mail.app has similar behavior. I can't think of any applications that close when the last window is closed, and as such I don't think there's a good reason that your app should behave that way (in fact, i'm surprised its not in Apple's user experience guidelines, it would really bother me!).
One reason why you'd want to close e.g. the iTunes main window but keep the app open is to be able to use the app as sort of a server for third party scripts/applications. I rarely use the main iTunes interface, but instead control my music with a third party app. I also write AppleScripts for other apps that I launch instead of interacting with that app's interface. | unknown | |
d17303 | val | If the container of your form has the width of the page then setting fxFlex.lt-sm="100%" should work. But if you're using fxLayout=column instead of row then it will set your max-height to 100% so you would need to set the width manually.
If this doesn't help, please post your html code and I'll update my answer
EDIT
<!-- Card -->
<div style="width: 100%" fxLayoutAlign="center center">
<md-card fxFlex="448px" fxFlex.lt-sm="100%">
Seems to work if you modify like that | unknown | |
d17304 | val | Because VACUUM has never run on the table. That command builds and maintains the visibility map.
You are probably on PostgreSQL v12 or lower, and the table not received enough updates or deletes to trigger autovacuum. If your use case involves insert-only tables, upgrade – from v13 on, autovacuum will also run on insert-only tables. | unknown | |
d17305 | val | A crude solution would be to replace this
if char == " " :
chiper += ' '
with this
if not char.isalpha():
chiper += char
A: The special characters are not considered because they're also being encrypted. This approach places an if condition before that where isalnum() decides only alpha numeric characters to become encrypted.
def caesar_encript(txt, shift):
chiper = ""
for i in range(len(txt)):
char = txt[i]
if not char.isalnum():
chiper+=char
else:
if (char.isupper()):
chiper += chr((ord(char) + shift - 65) % 26 + 65)
elif (char.islower()):
chiper += chr((ord(char) + shift - 97) % 26 + 97)
Output
plain text : Random Mesage, WOOOWW!
chiper text : Verhsq Qiweki, ASSSAA! | unknown | |
d17306 | val | Is the following program ill-formed according to the C++14 standard?
No. If you have some specific reason for thinking this might be invalid, you might be able to get a more detailed answer, but quoting each and every sentence of the standard in an attempt to point out that that sentence doesn't render the program invalid is not productive.
If not, is the sole function call expression contained within a discard-value expression?
The sole function call expression is the discarded-value expression.
5.2.9 Static cast [expr.static.cast]
6 Any expression can be explicitly converted to type cv void, in which case it becomes a discarded-value expression (Clause 5). [...]
I am assuming you are already aware that a C-style cast performs a static_cast if possible. | unknown | |
d17307 | val | If an app uses, for example, significant change service, the icon stays on even if the app is killed (because with significant change service, the app will be automatically re-awaken when iOS determines that a significant change has taken place; i.e. the iOS is effectively still tracking your location on behalf of the app, even though the app has been manually terminated). This is the documented behavior of significant change service, which, while less accurate than can be rendered by standard location services, continues tracking you even after the app has been terminated. The purple icon of location services won't be turned off until the app explicitly disables significant change service, or the app has been uninstalled. | unknown | |
d17308 | val | I'm not sure how really ereg_replace works, but first of all it's deprecated, and second - I think you cannot have spaces between the expressions => "[^A-Z a-z0-9]" should be "[^A-Za-z0-9]"
A: Your input tags should be inside a form tag... where is your form tag?
$_POST retrieve your input data from a form
A: during echo, variables don't need to be in quotes. so it's better like this:
<?php echo $propertytype; ?>.
undefined variable error means that probably the $_POST are not defined. But in this case you should get errors there as well.
From php page about function ereg_replace : This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged. | unknown | |
d17309 | val | You could use a dict
dict = {"labelA",arrayVal}
list1 = [1, 2, 3, 4, 5]
list2 = [123, 234, 456]
d = {'a': [], 'b': []}
d['a'].append(list1)
d['a'].append(list2)
print d['a']
For your array you can use a notation like
array[FROM INDEX ROW:TOINDEX ROW, :]
The : means take all cols
FROM INDEX ROW:TOINDEX ROW means take all values from the FROM INDEX upto the TOINDEX. | unknown | |
d17310 | val | void QTableWidget::setCellWidget(int row, int column, QWidget *widget)
Sets the given widget to be displayed in the cell in the given row and column, passing the ownership of the widget to the table.
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Window(QWidget):
def __init__(self, rows, columns):
super().__init__()
self.table = QTableWidget(rows, columns, self)
for row in range(rows):
widget = QWidget()
checkbox = QCheckBox()
checkbox.setCheckState(Qt.Unchecked)
layoutH = QHBoxLayout(widget)
layoutH.addWidget(checkbox)
layoutH.setAlignment(Qt.AlignCenter)
layoutH.setContentsMargins(0, 0, 0, 0)
self.table.setCellWidget(row, 0, widget) # <----
self.table.setItem(row, 1, QTableWidgetItem(str(row)))
self.button = QPushButton("Control selected QCheckBox")
self.button.clicked.connect(self.ButtonClicked)
layoutV = QVBoxLayout(self)
layoutV.addWidget(self.table)
layoutV.addWidget(self.button)
def ButtonClicked(self):
checked_list = []
for i in range(self.table.rowCount()):
if self.table.cellWidget(i, 0).findChild(type(QCheckBox())).isChecked():
checked_list.append(self.table.item(i, 1).text())
print(checked_list)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window(3, 3)
window.resize(350, 300)
window.show()
sys.exit(app.exec_()) | unknown | |
d17311 | val | Ok, so prior to asking this question I've been confused about something. Because I've added other operator overrides inside of the class, I thought that I was supposed to add that operator"" s inside of the class as well. But apparently, that is not so.
I'm keeping this just as a reference to the answer @user0042 gave to me.
This is what solved the problem for me. | unknown | |
d17312 | val | Load text into json object and fetch with keys
import requests
url = "http://some.api.com"
def get_job_status():
response = requests.request("POST", url)
if response.status_code == 200:
json_data = json.loads(response.text)
job_name = json_data["name"]
job_status = json_data["status"]
else:
return "Error with Request" | unknown | |
d17313 | val | I fixed the same error by upgrading the Jadira Usertype library dependency that the plugin was using.
The Joda Time plugin recommends "org.jadira.usertype:usertype.jodatime:1.9", which only works for Hibernate 3. Try switching to "org.jadira.usertype:usertype.core:3.2.0.GA" when using Hibernate 4. | unknown | |
d17314 | val | Here's a relatively simply and NOT error-handling example of what I think you're trying to accomplish:
*
*Don't count color tags when checking maximum length
*Remove characters from the end, don't destroy color tags
*If you end up with color tags with no text between them, remove those tags
Note: This code is not thoroughly tested. Feel free to use it for whatever you want, but I would write a lot of unit-tests here. In particular I'm scared about the existance of edge-cases that lead to an infinite loop.
public static string Shorten(string input, int requiredLength)
{
var tokens = Tokenize(input).ToList();
int current = tokens.Count - 1;
// assumption: color tags doesn't contribute to *visible* length
var totalLength = tokens.Where(t => t.Length == 1).Count();
while (totalLength > requiredLength && current >= 0)
{
// infinite-loop detection
if (lastCurrent == current && lastTotalLength == totalLength)
throw new InvalidOperationException("Infinite loop detected");
lastCurrent = current;
lastTotalLength = totalLength;
if (tokens[current].Length > 1)
{
if (current == 0)
return "";
if (tokens[current].StartsWith("</") && tokens[current - 1].StartsWith("<c"))
{
// Remove a <color></color> pair with no text between
tokens.RemoveAt(current);
tokens.RemoveAt(current - 1);
current -= 2;
// Since color tags doesn't contribute to length, don't adjust totalLength
continue;
}
// Remove one character from inside the color tags
tokens.RemoveAt(current - 1);
current--;
totalLength--;
}
else
{
// Remove last character from string
tokens.RemoveAt(current);
current--;
totalLength--;
}
}
// If we're now at the right length, but the last two tokens are <color></color>, remove them
if (tokens.Count >= 2 && tokens.Last().StartsWith("</") && tokens[tokens.Count - 2].StartsWith("<c"))
{
tokens.RemoveAt(tokens.Count - 1);
tokens.RemoveAt(tokens.Count - 1);
}
return string.Join("", tokens);
}
public static IEnumerable<string> Tokenize(string input)
{
int index = 0;
while (index < input.Length)
{
if (input[index] == '<')
{
int endIndex = index;
while (endIndex < input.Length && input[endIndex] != '>')
endIndex++;
if (endIndex < input.Length)
endIndex++;
yield return input.Substring(index, endIndex - index);
index = endIndex;
}
else
{
yield return input.Substring(index, 1);
index++;
}
}
}
Example code:
var myString = "My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>";
for (int length = 1; length < 100; length++)
Console.WriteLine($"{length}: {Shorten(myString, length)}");
Output:
1: M
2: My
3: My
4: My n
5: My na
6: My nam
7: My name
8: My name
9: My name i
10: My name is
11: My name is
12: My name is <color=#ff00ee>A</color>
13: My name is <color=#ff00ee>AB</color>
14: My name is <color=#ff00ee>ABC</color>
15: My name is <color=#ff00ee>ABCD</color>
16: My name is <color=#ff00ee>ABCDE</color>
17: My name is <color=#ff00ee>ABCDE</color>
18: My name is <color=#ff00ee>ABCDE</color> a
19: My name is <color=#ff00ee>ABCDE</color> an
20: My name is <color=#ff00ee>ABCDE</color> and
21: My name is <color=#ff00ee>ABCDE</color> and
22: My name is <color=#ff00ee>ABCDE</color> and I
23: My name is <color=#ff00ee>ABCDE</color> and I
24: My name is <color=#ff00ee>ABCDE</color> and I l
25: My name is <color=#ff00ee>ABCDE</color> and I lo
26: My name is <color=#ff00ee>ABCDE</color> and I lov
27: My name is <color=#ff00ee>ABCDE</color> and I love
28: My name is <color=#ff00ee>ABCDE</color> and I love
29: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>m</color>
30: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>mu</color>
31: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>mus</color>
32: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>musi</color>
33: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
34: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
35: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
36: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
37: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
38: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
39: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
... and so on
A: I generate 2 lists :
*
*One that contains the indexes of the real text
*One that contains the staring and ending indexes of tags
Then I take the text until the max length in the first array.
Finally, I check if there was an opening tag and if so, I close it.
N.B. : My code doesn't handle nested tags. You'd have to change the closing tag part.
public static string Truncate(string text, int maxLength)
{
if (text.Length <= maxLength) return text;
var tagIndexes = new List<int>();
var realTextIndexes = new List<int>();
bool isInTag = false;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '<')
{
isInTag = true;
tagIndexes.Add(i);
}
if (!isInTag)
{
realTextIndexes.Add(i);
}
if (text[i] == '>')
{
isInTag = false;
tagIndexes.Add(i);
}
}
if (realTextIndexes.Count <= maxLength) return text;
string truncatedText = text.Substring(0, realTextIndexes[maxLength - 1] + 1);
// Should we close a tag ?
for (int i = 0; i < tagIndexes.Count; i++)
{
if (tagIndexes[i] > realTextIndexes[maxLength - 1])
{
if ((i % 4) == 2) // If the next tag is a closing tag
{
truncatedText += text.Substring(tagIndexes[i], tagIndexes[i + 1] - tagIndexes[i] + 1);
}
break;
}
}
return truncatedText;
} | unknown | |
d17315 | val | You can use the IsChecked property.
I hope this helps.
Damian
A: Using this:
Window2 w2 = new Window2();
//This doesn't work
w2.Checked = true;
You're setting the Checked property of the window not the control. It should be somehting like this:
Window2 w2 = new Window2();
w2.MyCheckBox.IsChecked = true;
A: I'd say that you should move towards pushing the view model into the view via IoC or some other fashion. Tie the value to a property and let the framework make your life easier via binding, instead of having to hard code values all over the place.
http://msdn.microsoft.com/en-us/library/ms752347.aspx | unknown | |
d17316 | val | This example Get MD5 hash in a few lines of Java has a related example.
I believe you should be able to do
MessageDigest m=MessageDigest.getInstance("MD5");
m.update(message.getBytes(), 0, message.length());
BigInteger bi = new BigInteger(1,m.digest());
and if you want it printed in the style "d41d8cd98f00b204e9800998ecf8427e" you should be able to do
System.out.println(bi.toString(16));
A:
Actually i used md5's digest method which returned me array of byte which i want to convert into a BigInteger.
You can use new BigInteger(byte[]).
However, it should be noted that the MD5 hash is not really an integer in any useful sense. It is really just a binary bit pattern.
I guess you are just doing this so that you can print or order the MD5 hashes. But there are less memory hungry ways of accomplishing both tasks. | unknown | |
d17317 | val | The status in your question doesn't contain any deadlock information, so you haven't taken it just after the deadlock.Could be that the server had been restarted before you took the status
The status must cointain a section that looks like this example:
------------------------
LATEST DETECTED DEADLOCK
------------------------
2015-01-06 11:47:02 da8
*** (1) TRANSACTION:
TRANSACTION 24103246, ACTIVE 16 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 3 lock struct(s), heap size 376, 2 row lock(s)
MySQL thread id 3, OS thread handle 0xde8, query id 102 localhost 127.0.0.1 test
updating
update test set test=1 where test=1
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 489 page no 3 n bits 80 index `PRIMARY` of table `test`.`t
est` trx id 24103246 lock_mode X locks rec but not gap waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 4; hex 80000001; asc ;;
1: len 6; hex 0000016fc940; asc o @;;
2: len 7; hex a80000026e0110; asc n ;;
*** (2) TRANSACTION:
TRANSACTION 24103245, ACTIVE 63 sec starting index read, thread declared inside
InnoDB 5000
mysql tables in use 1, locked 1
3 lock struct(s), heap size 376, 2 row lock(s)
MySQL thread id 4, OS thread handle 0xda8, query id 103 localhost 127.0.0.1 test
updating
update test set test=4 where test=4
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 489 page no 3 n bits 80 index `PRIMARY` of table `test`.`t
est` trx id 24103245 lock_mode X locks rec but not gap
Record lock, heap no 2 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 4; hex 80000001; asc ;;
1: len 6; hex 0000016fc940; asc o @;;
2: len 7; hex a80000026e0110; asc n ;;
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 489 page no 3 n bits 80 index `PRIMARY` of table `test`.`t
est` trx id 24103245 lock_mode X locks rec but not gap waiting
Record lock, heap no 5 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 4; hex 80000004; asc ;;
1: len 6; hex 0000016fc940; asc o @;;
2: len 7; hex a80000026e0137; asc n 7;;
*** WE ROLL BACK TRANSACTION (2)
------------
TRANSACTIONS
------------ | unknown | |
d17318 | val | Ok I found this answer on the github forum.
"Output is likely being buffered, meaning you did not send enough data to flush the buffer at least once. Closing stdin (by ending the process) forces the buffer to flush, causing your app to receive data. This is very common, you typically don't want to write every single byte as it would be too IO intensive."
https://github.com/extrabacon/python-shell/issues/8
So I changed my code app.py code to
import sys
import time
print("START")
sys.stdout.flush()
time.sleep(10)
print("After 10 seconds")
and now the output is correct
MAIN: Script started
Message from APP: START
MAIN: 5 seconds
MAIN: 10 seconds
Message from APP: After 10 seconds
The exit code was: 0
The exit signal was: null
finished
MAIN: 15 seconds
I don't know if there are other better solutions, but with this one it works
A: Please use flush in the print function of Python
print('Python started from NODE.JS', flush=True) | unknown | |
d17319 | val | Have a look at window.navigator.onLine
A: You could try an ajax request to a reliable site.
// THIS IS OUR PAGE LOADER EVENT!
window.onload = function() {
testConnection();
};
function testConnection(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
} else if (xmlhttp.readyState==4){
alert("NO INTERNET DETECTED!");
}
}
xmlhttp.open("GET","http://www.w3schools.com/ajax/ajax_info.txt",true);
xmlhttp.send();
}
Now you will have to play around with it for a way to use the response because it is asynchronous, but this will work to test a connection.
A: Previously discussed here: Check if Internet Connection Exists with Javascript? and here: How to know if the network is (dis)connected?.
A: GM_xmlhttpRequest({
method: "GET",
url: "http://www.google.com/",
onload: function(response) {
if(response.responseText != null) {
alert("OK");
} else {
alert("not connected");
}
}
});
*
*second alternative
var HaveConnection = navigator.onLine; | unknown | |
d17320 | val | first of all, you need to query/order the data with the date
you can simply do it using this sample.
mRef.child("lessons").orderByKey().equalTo(Date_lesson)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot :dataSnapshot.getChildren()) {
String key = postsnapshot.getKey();
dataSnapshot.getRef().removeValue();
}
});
where mRefis you lessons branch ref | unknown | |
d17321 | val | When you initialize calculate as list type you can append values with + operator:
numberOfcalculations = 3
count = 1
calculate = []
while count <= numberOfcalculations:
num = int(input(' number:'))
num2 = int(input(' other number:'))
calculate += [ num * num2 ]
print(calculate)
count = count + 1
Also you have to change contador somehow or you will end up in an infinite loop maybe. I used count here instead to give the user the ability to input 3 different calculations. | unknown | |
d17322 | val | JOPtionPane provides a number of preset dialog types that can be used. However, when you are trying to do something that does not fit the mold of one of those types, it is best to create your own dialog by making a sub-class of JDialog. Doing this will give you full control over how the controls are laid out and ability to respond to button clicks as you want. You will want to add an ActionListener for the OK button. Then, in that callback, you can extract the values from the text fields.
The process of creating a custom dialog should be very similar to how you created the main window for your GUI. Except, instead of extending JFrame, you should extend JDialog. Here is a very basic example. In the example, the ActionListener just closes the dialog. You will want to add more code that extracts the values from the text fields and provides them to where they are needed in the rest of your code.
A: I guess looking at your question, you need something like this. I had made a small JDialog, where you will enter a UserName and Answer, this will then be passed to the original GUI to be shown in the respective fields, as you press the SUBMIT JButton.
Try your hands on this code and ask any question that may arise :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* This is the actual GUI class, which will get
* values from the JDIalog class.
*/
public class GetDialogValues extends JFrame
{
private JTextField userField;
private JTextField questionField;
public GetDialogValues()
{
super("JFRAME");
}
private void createAndDisplayGUI(GetDialogValues gdv)
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 2));
JLabel userName = new JLabel("USERNAME : ");
userField = new JTextField();
JLabel questionLabel = new JLabel("Are you feeling GOOD ?");
questionField = new JTextField();
contentPane.add(userName);
contentPane.add(userField);
contentPane.add(questionLabel);
contentPane.add(questionField);
getContentPane().add(contentPane);
pack();
setVisible(true);
InputDialog id = new InputDialog(gdv, "Get INPUT : ", true);
}
public void setValues(final String username, final String answer)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
userField.setText(username);
questionField.setText(answer);
}
});
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
GetDialogValues gdv = new GetDialogValues();
gdv.createAndDisplayGUI(gdv);
}
};
SwingUtilities.invokeLater(runnable);
}
}
class InputDialog extends JDialog
{
private GetDialogValues gdv;
private JTextField usernameField;
private JTextField questionField;
private JButton submitButton;
private ActionListener actionButton = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (usernameField.getDocument().getLength() > 0
&& questionField.getDocument().getLength() > 0)
{
gdv.setValues(usernameField.getText().trim()
, questionField.getText().trim());
dispose();
}
else if (usernameField.getDocument().getLength() == 0)
{
JOptionPane.showMessageDialog(null, "Please Enter USERNAME."
, "Invalid USERNAME : ", JOptionPane.ERROR_MESSAGE);
}
else if (questionField.getDocument().getLength() == 0)
{
JOptionPane.showMessageDialog(null, "Please Answer the question"
, "Invalid ANSWER : ", JOptionPane.ERROR_MESSAGE);
}
}
};
public InputDialog(GetDialogValues gdv, String title, boolean isModal)
{
this.gdv = gdv;
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
setModal(isModal);
setTitle(title);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
JLabel usernameLabel = new JLabel("Enter USERNAME : ");
usernameField = new JTextField();
JLabel questionLabel = new JLabel("How are you feeling ?");
questionField = new JTextField();
panel.add(usernameLabel);
panel.add(usernameField);
panel.add(questionLabel);
panel.add(questionField);
submitButton = new JButton("SUBMIT");
submitButton.addActionListener(actionButton);
add(panel, BorderLayout.CENTER);
add(submitButton, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
} | unknown | |
d17323 | val | It looks like an authentication problem. control your host, port, username and password. | unknown | |
d17324 | val | In Python2.x, the simplest solution in terms of number of characters should probably be :
>>> a=range(20)
>>> a[::-1]
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Though i want to point out that if using xrange(), indexing won't work because xrange() gives you an xrange object instead of a list.
>>> a=xrange(20)
>>> a[::-1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence index must be integer, not 'slice'
After in Python3.x, range() does what xrange() does in Python2.x but also has an improvement accepting indexing change upon the object.
>>> a = range(20)
>>> a[::-1]
range(19, -1, -1)
>>> b=a[::-1]
>>> for i in b:
... print (i)
...
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
>>>
the difference between range() and xrange() learned from source: http://pythoncentral.io/how-to-use-pythons-xrange-and-range/
by author: Joey Payne
A: You can assign your variable to None:
>>> a = range(20)
>>> a[15:None:-1]
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>>
A: Omit the end index:
print a[15::-1]
A: >>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> print a[:6:-1]
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7]
>>> a[7] == a[:6:-1][-1]
True
>>> a[1] == a[:0:-1][-1]
True
So as you can see when subsitute a value in start label :end: it will give you from start to end exclusively a[end].
As you can see in here as well:
>>> a[0:2:]
[0, 1]
-1 is the last value in a:
>>> a[len(a)-1] == a[-1]
True
A: EDIT: begin and end are variables
I never realized this, but a (slightly hacky) solution would be:
>>> a = range(5)
>>> s = 0
>>> e = 3
>>> b = a[s:e]
>>> b.reverse()
>>> print b
[2, 1, 0]
A: If you use negative indexes you can avoid extra assignments, using only your start and end variables:
a = range(20)
start = 20
for end in range(21):
a[start:-(len(a)+1-end):-1] | unknown | |
d17325 | val | If frmMain.ds.Tables(0).Rows(i).Item(0) = lblSI.Text Then
frmMain.sql = "UPDATE TblUser SET LOGINSTATUS = 'SignedIn'"
frmMain.cnn.Close()
End If
It seems that the UPDATE statement doesn't get executed.
I don't see ExecuteNonQuery for it.
ps: The UPDATE statement is to update all records in the table. Look out!
ps2: I'm not familiar with the VB(.net) :)
A: I think you are missing executeNonQuery in second form and is there only one user then query is fine if more than one consider using " Where Clause" eg.
sql= "UPDATE TblUser SET LOGINSTATUS = 'SignedIn' where ID =" <provide id>
if that doesn't solve your problem then feel free to ask more.
Regards. | unknown | |
d17326 | val | I think the reason you only see examples using the accelerometer values is because the gravity sensor was only launched in API 9 and also because most phones might not give this values separated from the accelerometer values, or dont have the sensor, etc, etc..
Another reason would be because in most of the cases the result tend to be the same, since what the accelerometer sensor outputs is the device linear acceleration plus gravity, but most of the time the phone will be standing still or even moving at a constant velocity, thus the device acceleration will be zero.
From the setRotationMatrix Android Docs:
The matrices returned by this function are meaningful only when the device is not free-falling and it is not close to the magnetic north. If the device is accelerating, or placed into a strong magnetic field, the returned matrices may be inaccurate.
Now, you're asking if the gravity data would me more reliable? Well, there is nothing like testing, but I suppose it wouldn't make much difference and it really depends on which application you want. Also, obtaining the simple gravity values is not trivial and it requires filtering, so you could end up with noisy results. | unknown | |
d17327 | val | No service available has a detailed 3d map of an area given gps coordinates. Google has a super simple height map that they draw and then map their aerial pictures onto, but even if you could get programmatic access to that it would look terrible if you were at street level. If you're okay with a horrid level of detail (like you're going to be viewing this from high up or something) maybe it would be feasible, but not as any kind of first person street level experience. | unknown | |
d17328 | val | 3) Updated Answer
Session Namespace Reference for beta(s) or RC1
Microsoft.AspNet.Session
Session Namespace Reference from CORE 1.0
Microsoft.AspNetCore.Session
2) Updated Answer - If accessing a session outside the controller then you need to inject the session into it as follows
public class TestClass
{
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session => _httpContextAccessor.HttpContext.Session;
public TestClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void SetString()
{
_session.SetString("Test", "Ben Rules!");
}
public string GetString()
{
return _session.GetString("Test");
}
}
1) Initial Answer - Incorrect for current scenario... but if session isn't working this is a good place to start
From the error message I assume you are using .NET Core?
If so then the middleware is added sequentially so you need to ensure that your code intitialises Session Management first before it uses MVC
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSession();
// ...
}
public void Configure(IApplicationBuilder app)
{
app.UseSession();
app.UseMvc();
// ...
} | unknown | |
d17329 | val | Solved! I forgot that I had to add
sys.stdout.flush()
After every print() called to force it to flush the buffer. | unknown | |
d17330 | val | Your view is working as intended. You are setting it to use a clear background color, which means exactly as it is named, clear, and you will see color and possibly other UI elements underneath your view. Think of it as placing clear plastic wrap (the view) on top of colored construction paper (the super view). If you wish to find where the black color is coming from, I would start with your root controller's view. | unknown | |
d17331 | val | Don't store the object in the cache, store the Lazy.
private static T GetCachedCollection<T>(Guid cacheKey, Lazy<T> initializer)
{
var cachedValue = (Lazy<T>)(MemoryCache.Default.AddOrGetExisting(
cacheKey.ToString(), initializer, _policy) ?? initializer);
return cachedValue.Value;
} | unknown | |
d17332 | val | 1) Business and test accounts are supposed to mimic the real accounts. For example, when a test user buys your product that money gets added to the business account.
3) Doubt it. Sandbox is meant for everyone.
Update: Looks like the Australian site is different.
A: It appears the reason for my confusion was that the Australian Pay Pal website is presented differently from the international version - and looks nothing like the Sandbox.
So, for the record, provided your account Type is Business the encryption settings on the Australian version are at:
Profile > My Selling Tools > Encrypted Payment Settings (right at the bottom of the page) | unknown | |
d17333 | val | Use the np.linalg.solve library:
https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html
import numpy as np
a = np.array([[1,1,0], [1,0,1], [0,1,1]])
b = np.array([0,0,1])
x = np.linalg.solve(a, b)
A: alternative to the answer
import numpy as np
A = np.array([[1, 1, 0], [1, 0, 1], [0, 1, 1]])
B = np.array([0, 0, 1])
X = np.linalg.inv(A).dot(B)
print(X) | unknown | |
d17334 | val | I found the solution
learn = load_learner('','model.pkl')
the first arg. had to be space '' . | unknown | |
d17335 | val | Objects in JS can't be sorted, and the order of the properties is not reliable, ie it depends on browsers' implementations. That's why _.sortBy() is converting your object into a sorted array.
I can think of 2 options to work with that.
Add the key to the objects in the array
If you just need an ordered array with the keys in the objects, so you can render a list.
var data = {
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
};
var result = _(data)
.map(function(v, k) { // insert the key into the object
return _.merge({}, v, { key: k });
})
.sortBy('name') // sort by name
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Create an order array
Create an array of ordered keys, and use them when you wish to render the objects in order.
var data = {
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
};
var orderArray = _(data)
.keys() // create an array of keys
.sortBy(function(key) { // sort the array using the original names
return data[key].name;
}) // sort by name
.value();
console.log('The order array', orderArray);
console.log(orderArray.map(function(k) {
return data[k];
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
A: I use something like this.
let data = {
'g34ghgj3kj': {
YOUR_KEY: 'g34ghgj3kj',
'key1': false,
'key2': false,
},
'hh334h664': {
YOUR_KEY: 'hh334h664',
'key1': true,
'key2': false,
},
//{...}
};
_.orderBy(data, ['key1', 'key2'], ['desc', 'desc']).reduce((result, value) => {
result[value.YOUR_KEY] = value;
return result;
}, {}); | unknown | |
d17336 | val | Yes it is. I think that one of your closing parenthesis was not where you meant it to be:
with open('test.txt', 'w') as f:
f.write('{0:10} {1:10}'.format('one', 'two')) | unknown | |
d17337 | val | In my case I was getting this error :
getParameters failed (empty parameters)
when I called getParameters() after unlocking the camera. So, please call getParameters() before you call camera.unlock().
A: Is there a specific Android device that experiences this error? Or do you see it across many devices.
In general, you should not see this kind of an error. It's possible your application has some sort of race condition which results in this, but it'd have to involve trying to call getParameters on an uninitialized or already-released camera.
It could also be an error in the device-specific camera code, or a rare race condition somewhere in the camera code stack. Without more detail (logcat or Android bugreport from such a crash), it's impossible to tell - the error itself just says that the device-specific camera code returned an empty set of parameters.
But once you get this error, there's not a lot you can do - the camera subsystem is in some odd state. If you want to try to deal with it, all I can suggest is to close and reopen the camera device.
A: As +Eddy Talvala mentioned, this happens when the camera is in a bad state.
How does the camera get in a bad state?
1) Probably the most common reason would be closing/releasing the camera while still using it afterward. This can be especially problematic if you are using the Camera object on multiple threads without synchronizing access to the Camera. Make sure you only ever have a single thread accessing the Camera at a time.
2) In my case it was a bit more tricky. I use a SurfaceTexture so that I can use the camera output as an OpenGL texture. In Android 4.0 (ICS), there is a new method SurfaceTexture.release(). This method is important to use when using SurfaceTextures as it cleans up the memory quicker than it previously did.
The problem is that I was calling SurfaceTexture.release() while the camera preview was still active. This was crashing the Camera service, which was causing the issue explained in the question.
In my case I fixed it by delaying the call to SurfaceTexture.release() until after I had replaced it with a new SurfaceTexture. This way I was certain the SurfaceTexture could be cleaned up without any bad side-effects.
A: camera objects are always locked by default
so when you can unlock method then you allow to other procceses to use your parameters
so make sure that you re locked the camera before getting parameters | unknown | |
d17338 | val | What i did
Create table tasks
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('type'); // optional
$table->string('frequency_function');
$table->string('frequency_params')->nullable(); // optional
$table->string('job_name')->nullable(); // optional
$table->integer('user_id')->nullable(); // optional
$table->timestamps();
});
/*
Example task data
type = 'subscription_credit'
frequency_function = 'weeklyOn'
frequency_params = 'a:2:{i:0;i:3;i:1;s:5:"12:20";}' // serialize(array(3, '12:20'))
job_name = App/Jobs/Premium/CreditPremiumMoney
user_id = 1
*/
I need to schedule Job so I have job_name column.
For example, depending on your needs, you can add command_name column if you want to schedule the execution of a command.
Update Kernel
In your App\Console\Kernel.php schedule method write:
protected function schedule(Schedule $schedule)
{
$tasks = Task::all();
foreach ($tasks as $task) {
$type = $task->type; // optional
$frequencyFunc = $task->frequency_function;
$frequencyFuncParams = $task->frequency_params
? unserialize($task->frequency_params)
: [];
if ($type === 'subscription_credit') { // optional
$job = $task->job_name;
$userId = $task->user_id;
$schedule->job(new $job($userId), 'low', 'redis')
->$frequencyFunc(...$frequencyFuncParams);
} else if ($type === '...') {
// Other optional type logic
}
}
}
You can remove type condition if you do not need it or add multiple types logic if you need type.
Try It
Add all your tasks to your database.
Local
Run command php artisan schedule:work and the scheduler will run to process your tasks at the scheduled dataTime
Production
Add CRON to your server like here
On each environment, the scheduler will run every minute and check if there are tasks to execute in tasks table. | unknown | |
d17339 | val | You can try and use % operator to decide if the two doubles produce a perfect division and use integer casting like below.
double num1 = 20.0;
double num2 = 5.0;
if (num1%num2 == 0) {
System.out.println((long) (num1/num2));
} else {
System.out.println(num1/num2);
} | unknown | |
d17340 | val | so there are a few ways of doing this, but a really simple one is something like this:
var width = $(window).width(); //jquery
var width = window.innerWidth; //javascript
if(width > 1000){do large screen width display)
else{handle small screen}
of course 1000 is just an arbitrary number. it gets tricky because when you consider tables, there really are screens of all sizes so its up to you to determine what belongs where
A:
How can I test on the website if it a mobile device or a PC, so I can
turn off if "Website" hamburger if its a mobile,
If I understood you correctly, you could use CSS @media -rules, to setup CSS rules that only apply to smaller devices. Below is a simple code-snippet example of a CSS media-query.
@media (min-width: 700px), handheld
{
.w3-sidebar
{
display: none;
}
} | unknown | |
d17341 | val | I was able to work this out
With the animated(loading) gif running in the WebView page I called a couple of async methods using following
await Task.WhenAll(method1(), method2());
await Navigate.PushAsync(new NextPage(var1, var2));
The laoding gif (which is an animated logo) runs until the tasks are complete then navigates to the next page
A: Using an ImageView apparently this doesn't look like its possible to playback animated Gif's as can be seen here http://forums.xamarin.com/discussion/17448/animated-gif-in-image-view.
So i very much doubt the ActivityIndicator would, if it could. In the ActivityIndicator I can't see any functionality to change the content of the what is shown when it is busy.
You could always create your own animated image view by creating a custom renderer instead however. It isn't particularly hard to cycle images at pre-determined gaps if you have a list of the images split up.
A: GIF images can be used in Xamarin forms to show custom activity indicator, since in Xamarin forms it is not possible to show GIF images directly web-view must be used. For android image must be placed inside assets folder and Build Action must be set to AndroidAsset. For iOS image must be placed inside resources and Build Action must be set to BundleResource. AbsoluteLayout can used for placing the image to center, IsBusy property of mvvm helpers nuget can used for controlling the visibility of the activity indicator. Dependency service must used for getting the image path. You can check this https://github.com/LeslieCorrea/Xamarin-Forms-Custom-Activity-Indicator for example.
A: Xamarin.Forms now supports .GIF, from version 4.4-pre3 and up on iOS, Android and UWP. Before using, first add the .GIF to the platforms projects, or as an embedded resource in the shared project and then use it like a regular image. The API on the Image control has been extended with the IsAnimationPlaying bindable property.
For e.g., loader.gif is added in all platform projects, then below code make it animating.
<Image Source="loader" IsAnimationPlaying="True" WidthRequest="36" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" /> | unknown | |
d17342 | val | Create a command class for each level. Mark Zone- and Segment-command as @Validateable.
To your GroupCommand, add:
List zones = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(ZoneCommand.class))
To your ZoneCommand, add:
List segments = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(SegmentCommand.class))
In your form just use group.zones[0].segments[0]. If you change a field type of your command class, remember to restart the grails server. | unknown | |
d17343 | val | I would simply save the information with the tags between quotes and use the following :
http://php.net/manual/en/function.strip-tags.php
Hope it helps, the second comment from the above site is a good example, more specifically
http://php.net/manual/en/function.strip-tags.php#86964 | unknown | |
d17344 | val | Option 1 - Yes, this will work. The server will perform index seek by (A,B,C,D,E) and furter index scan by (G).
Option 2 - Makes no sense in most cases, server uses only one index for one source table copy. But when the selectivity of single index by (G) is higher than one for (A,B,C,D,E) combination then the server will use this single-column index.
Option 3 - The processing is equal to one in Option 2.
A: Are the PRIMARY KEY's column(s) included in A..E ? If so, none of the indexes are needed.
What datatypes are involved?
Are they all really tests on =? If not then 'all bets are off'. More specifically, useful indexes necessarily start with the columns tested with = (in any order). In particular, F IS NOT NULL is not = (but IS NULL would count as =).
I would expect INDEX(A,B,C,D,E, anything else or nothing else) to work for all of the queries you listed. (Hence, I suspect there are some details missing from your over-simplified description.)
How "selective" are F and G? For example, if most of the values of G are distinct, then INDEX(G) would possibly be useful by itself.
Please provide SHOW CREATE TABLE and EXPLAIN SELECT ... | unknown | |
d17345 | val | Simply set children to body
Like so:
BackdropFilter(
filter: ImageFilter.blur(sigmaX:10, sigmaY:10),
child: Container(
color: Colors.black.withOpacity(0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: body,
)
),
),
) | unknown | |
d17346 | val | See https://dzone.com/articles/why-does-javascript-loop-only-use-last-value
Solution 1 - Creating a new function setElementBackground
for (i = 0; i < input.files.length; i++) {
setElementBackground(input.files[i], i);
}
function setElementBackground(file, i) {
var image = file;
var imageDiv = "contactImage" + i.toString();
var element = document.getElementById(imageDiv);
var reader = new FileReader();
reader.onloadend = function() {
element.style.backgroundImage = "url(" + reader.result + ")";
};
if (image) {
reader.readAsDataURL(image);
}
}
Solution 2 - Using Another Closure inside for loop
for (i = 0; i < input.files.length; i++) {
(function() {
var count = i;
var image = input.files[count];
var imageDiv = "contactImage" + count.toString();
var element = document.getElementById(imageDiv);
var reader = new FileReader();
reader.onloadend = function() {
element.style.backgroundImage = "url(" + reader.result + ")";
};
if (image) {
reader.readAsDataURL(image);
}
})();
} | unknown | |
d17347 | val | It is due to Your table view cell colour.
Select table view cell:
Set its background colour as clear.
A: I suggest you to debug it in your Xcode. To do this you can launch it on you device(or on simulator), click 'Debug View Hierarchy' button.
Then by Mouse Click + Dragging on the screen rectangle you can rotate all layers of your screen and see which view is causing that white background.
A: this white background is due to table view cell select table view cell and from navigator make its background clear. or you can do it in
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier", for: indexPath) as! YourCellClass
cell.backgroundColor = .clear
}
this will solve your problem...
:) | unknown | |
d17348 | val | One (relatively robust) option is to run
find . -iregex ".*\(_web\|_thumb\)\.\(jpg\|png\|bmp\)" -delete
Assuming that you don't have anything other than image files in the directory, another (simpler) option is to run
rm *_web.* *_thumb.*
Warning: this will also delete files that are named something like my_web.file.jpg, so if you want to play safe, you'll have to add all the extensions instead of relying on .*
If you know that your extensions are always going to be 3 characters long, you can use something like *_thumb.???
A: I don't have a MAC or a UNIX terminal in front of me, but I imagine something like the following might work
rm *_web.jpg
rm *_web.jpg
rm *_thumb.gif | unknown | |
d17349 | val | x IN (a, b) can be consisidered shorthand for x = ANY (ARRAY[a,b]). Similarly, x IN (SELECT ...) and x = ANY (SELECT ...).
The = can actually be replaced by any binary operator. Thus, you can use:
SELECT ... WHERE x LIKE ANY (SELECT ...)
A: Use SIMILAR TO instead of LIKE
AND state SIMILAR TO '%(idle|disabled)%'
https://www.postgresql.org/docs/9.0/static/functions-matching.html
A: Users of MySQL or Oracle may find it a bit different, but in PostGreSQL, to filter data using LIKE clause, one should use something like -
select * from table-name where column-name::text like '%whatever-to-be-searched%'
A: Actually using something IN (<value list>) is similar to something = any(array[<value list>]) in the PostgreSQL:
postgres=# explain select 1 where 'a' in ('a','b','c');
QUERY PLAN
----------------------------------------------------------
Result (cost=0.00..0.01 rows=1 width=0)
One-Time Filter: ('a'::text = ANY ('{a,b,c}'::text[]))
(2 rows)
Fortunately we can use like or even ilike instead of =:
select 1 where 'aa' ilike any(array['%A%','%B%','%C%']);
?column?
----------
1
(1 row)
So in your case it could be
... state LIKE ANY(ARRAY['%idle%', '%disabled%'])
And the additional advantage: it can be passed as a parameter from the client application. | unknown | |
d17350 | val | If you read ?help, it says that the return value of load is:
A character vector of the names of objects created, invisibly.
This suggests (but admittedly does not state) that the true work of the load command is by side-effect, in that it inserts the objects into an environment (defaulting to the current environment, often but not always .GlobalEnv). You should immediately have access to them from where you called load(...).
For instance, if I can guess at variables you might have in your rda file:
x
# Error: object 'x' not found
# either one of these on windows, NOT BOTH
dat = load("C:\\Users\\user\\AppData\\Local\\Temp\\1_29_923-Macdonell.RData")
dat = load("C:/Users/user/AppData/Local/Temp/1_29_923-Macdonell.RData")
dat
# [1] "x" "y" "z"
x
# [1] 42
If you want them to be not stored in the current environment, you can set up an environment to place them in. (I use parent=emptyenv(), but that's not strictly required. There are some minor ramifications to not including that option, none of them earth-shattering.)
myenv <- new.env(parent = emptyenv())
dat = load("C:/Users/user/AppData/Local/Temp/1_29_923-Macdonell.RData",
envir = myenv)
dat
# [1] "x" "y" "z"
x
# Error: object 'x' not found
ls(envir = myenv)
# [1] "x" "y" "z"
From here you can get at your data in any number of ways:
ls.str(myenv) # similar in concept to str() but for environments
# x : num 42
# y : num 1
# z : num 2
myenv$x
# [1] 42
get("x", envir = myenv)
# [1] 42
Side note:
You may have noticed that I used dat as my variable name instead of data. Though you are certainly allowed to use that, it can bite you if you use variable names that match existing variables or functions. For instance, all of your code will work just fine as long as you load your data. If, however, you run some of your code without pre-loading your objects into your data variable, you'll likely get an error such as:
mean(data$x)
# Error in data$x : object of type 'closure' is not subsettable
That error message is not immediately self-evident. The problem is that if not previously defined as in your question, then data here refers to the function data. In programming terms, a closure is a special type of function, so the error really should have said:
# Error in data$x : object of type 'function' is not subsettable
meaning that though dat can be subsetted and dat$x means something, you cannot use the $ subset method on a function itself. (You can't do mean$x when referring to the mean function, for example.) Regardless, even though this here-modified error message is less confusing, it is still not clearly telling you what/where the problem is located.
Because of this, many seasoned programmers will suggest you use unique variable names (perhaps more than just x :-). If you use my suggestion and name it dat instead, then the mistake of not preloading your data will instead error with:
mean(dat$x)
# Error in mean(dat$x) : object 'dat' not found
which is a lot more meaningful and easier to troubleshoot.
A: There are two ways to save R objects, and you've got them mixed up. In the first way, you save() any collection of objects in an environment to a file. When you load() that file, those objects are re-created with their original names in your current environment. This is how R saves and resotres workspaces.
The second way stores (serializes) a single R object into a file with the saveRDS() function, and recreates it in your environment with the readRDS() function. If you don't assign the results of readRDS(), it'll just print to your screen and drift away.
Examples below:
# Make a simple dataframe
testdf <- data.frame(x = 1:10,
y = rnorm(10))
# Save it out using the save() function
savedir <- tempdir()
savepath <- file.path(savedir, "saved.Rdata")
save(testdf, file = savepath)
# Delete it
rm(testdf)
# Load without assigning - and it's back in your environment
load(savepath)
testdf
# But if you assign the results of load, you just get the name of the object
wrong <- load(savepath)
wrong
# Compare with the RDS:
rds_path <- file.path(savedir, "testdf.rds")
saveRDS(testdf, file = rds_path)
rm(testdf)
testdf <- readRDS(file = rds_path)
testdf
Why the two different approaches? The save()-environment approach is good for creating a checkpoint of your entire environment that you can restore later - that's what R uses it for - but that's about it. It's too easy for such an environment to get cluttered, and if an object you load() has the same name as an object in your current environment, it will overwrite that object:
testdf$z <- "blah"
load(savepath)
testdf # testdf$z is gone
The RDS method lets you assign the name on read, as you're looking to do here. It's a little more annoying to save multiple objects, sure, but you probably shouldn't be saving objects very often anyway - recreating objects from scratch is the best way to ensure that your R code does what you think it does. | unknown | |
d17351 | val | Use below method and it will work definitely
$.mobile.navigate("#register", {transition: "slide"}); | unknown | |
d17352 | val | It seems that screenshot_as_png is not a valid command,
Try following this way:
https://pythonspot.com/selenium-take-screenshot/
Regards!
A: There is no method to the element object. It is holding the reference of the element returned by the method driver.find_element_by_css_selector('.-main.grid--cell'). Hence the error.
There is method in the WebDriver class called save_screenshot("filename.extension")
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.binary_location = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
driver = webdriver.Chrome(options=options, executable_path="C:/Users/Downloads/chromedriver.exe", )
driver.get('http://stackoverflow.com/')
element = driver.find_element_by_css_selector('.-main.grid--cell')
#element.screenshot_as_png() # there is no method on the element object hence the error
driver.save_screenshot("screenshot.png") # this is the method to get the screenshot
driver.quit() | unknown | |
d17353 | val | The updated or inserted value is always treated as type varchar(10) - before and after the trigger function. So, you cannot handle the value because the input type does not fit the value even if the trigger function converts it into a valid one.
It works if you have an unbounded text type. There you can see that the trigger is executed:
demo:db<>fiddle
So, the only chance to handle this, is, to normalize it before inserting or updating:
demo:db<>fiddle
INSERT INTO interesant VALUES (normalize_nip('555-555-5555'));
UPDATE interesant SET interesant_nip = normalize_nip('555-555-5555') | unknown | |
d17354 | val | This is probably because the package is outdated.
In my case it didn't work because I used the unity monetization version of the asset store instead of the one in the unity package editor, cause since version 2018.3 it stopped working. | unknown | |
d17355 | val | This will work:
local vars = getfenv()
for i=1, 10 do
local frame = "MyFrame"..i
vars[frame]:EnableMouseWheel(true)
end
Although you appear to be looking for the solution to the wrong problem. Why not store them in an array to begin with?
A: If you want to convert a string name into a variable name you need to access the global object as a table:
_G["MyFrame1"]
I don't know about what version of Lua warcraft uses. If its a really old version that doesn't have _G then you probably need to use the getglobal functions instead
getglobal("MyFrame1")
That said, this is usually an antipattern. If you are the one that originally defined the MyFrame variables its normally better to use an array instead:
Myframes = {
MyFrame1,
MyFrame2,
}
since this lets you avoid the string manipulation
local frame = MyFrames[i]
frame:EnableMouseWheel(true) | unknown | |
d17356 | val | The idea is actually the same as yours(i.e. splitting by . and get the first element), then $group them to get distinct records.
db.collection.aggregate([
{
$project: {
first: {
"$arrayElemAt": [
{
"$split": [
"$_id",
"."
]
},
0
]
}
}
},
{
"$group": {
"_id": "$first"
}
}
])
Here is the Mongo playground for your reference.
Here is the PyMongo implementation of the above query:
pipeline = [
{"$project": {"first": {"$arrayElemAt": [{"$split": ["$_id", "."]}, 0]}}},
{"$group": {"_id": "$first"}}
]
result = self.collection.aggregate(pipeline=pipeline, allowDiskUse=False) | unknown | |
d17357 | val | My understanding is that when a request is received, the Apache server will fork a new process and invoke the appropriate php script/file.
This is only the case for PHP-CGI configurations, which are not typical. Most deployments use the mod_php SAPI, which runs PHP scripts within the Apache process.
What happens when the session started by the php script, in this new process forked by Apache, has expired or the user has ended it by closing their browser ?
Nothing.
In PHP-CGI configurations, the process exits as soon as your script finishes generating a response. In mod_php configurations, the Apache process returns to listening for new requests when your script finishes.
The lifetime of sessions is not tied to any specific process. Keep in mind that sessions are stored as files in your system's temporary directory -- PHP periodically checks this directory for sessions which have expired and removes them as appropriate.
Closing your browser does not remove the session from the server's temporary directory. It may cause your browser to discard the cookies related to the session, causing the session to stop being used, but the server is not notified of this. | unknown | |
d17358 | val | Checkout the -g option on the daemon process. Can be used to locate the docker home on an alternative disk volume.
Explained in the following documentation links:
*
*http://docs.docker.com/reference/commandline/cli/#daemon
*http://docs.docker.com/articles/systemd/#custom-docker-daemon-options
A: Linked /var to /user1/var.
The mounts and the volumes stay the same.
I did this:
`telinit 1
cp -pR /var /user1/var
mv /var /var.old
ln -s /user1/var /var
telinit 2` | unknown | |
d17359 | val | The lifecycle method isn't called componentDidUnMount, it's called componentWillUnmount. Two important differences where the casing is Unmount and not UnMount and that it's Will and not Did. If it was called componentDidUnmount the component would have already been unmounted and the reference to the DOM node would have been released. So you clean up any DOM related things in componentWillUnmount just before the component is unmounted. | unknown | |
d17360 | val | Either Local Storage or Session Storage (works in IE8 and other browsers). | unknown | |
d17361 | val | I hope this work. It works for me.
android:layoutDirection="rtl"
A: If I am correct this is source for searchview https://android.googlesource.com/platform/frameworks/support.git/+/jb-mr2-release/v7/appcompat/res/layout/abc_search_view.xml .
From what it looks like, it uses linear layout and that mentioned icon is in front of text. That means there is not a nice way to put it on right side.
There are basically 3 options left, or at least which came to my mind.
*
*use custom made layout with drawable and edittext, I think some of the effects can be done using CollapsibleActionView or/and custom animations (really depends on what you need from it)
*use search view, style it without text icon:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:searchViewStyle">@style/appTheme.SearchView</item>
</style>
<style name="AppTheme.SearchView" parent="Widget.AppCompat.SearchView">
<item name="android:searchIcon" tools:targetApi="lollipop">@null</item>
</style>
And then basically add icon to right as a normal drawable.
*extend search view and inflate custom layout in constructor (haven't tested this one) | unknown | |
d17362 | val | Assuming your table is a list
with open('saveTo\Directory\file.csv','w') as f:
f.write(','.join(tableData))
Where you can technically, call the f.write method on each line of the table as soon as you have it, but change the 'w' parameter to 'a' to append to the file | unknown | |
d17363 | val | You can't cause PHP to output PHP and then parse that PHP and execute it.
Add your data via string concatenation instead.
Better yet: Geek echo statements to a minimum, and drop out of PHP mode with <? when you are just outputting static data.
A: <?php
echo"
<!-- header -->
";
include "../../access/$template/header.php";
echo "
<!-- content -->
<div>".$rs['username']." ~ ".$rs["webcam_status"]."</div>
<!-- content -->
<!--footer-->
";
include "../../access/$template/footer.php";
echo "
";
?> | unknown | |
d17364 | val | Upon further consideration, I decided that the simplest answer is to accumulate the IDs in an empty DIV:
google.maps.event.addListener(layer, 'click', function(e) {
newValue=document.getElementById('album').innerHTML + ':' + e.row['Bestand'].value;
document.getElementById('album').innerHTML=newValue;
});
This is just what I needed (called for help too soon?). | unknown | |
d17365 | val | The structure member
WorkingSetSize
gives the current used memory.
The working set is the amount of memory physically mapped to the
process context at a given time.
Ref.:Process Memory Usage Information. | unknown | |
d17366 | val | Shortcode should return a string:
<?php
add_shortcode( 'sms_order_form', 'sms_order_form_html' );
function sms_order_form_html() {
ob_start();
?>
<form>
<div class="tooltip">
0<input type="range" id="range" value="0" min="0" max="100"/>100
<span class="tooltiptext">0</span>
</div>
</form>
<?php
return ob_get_clean();
}
A: Shortcode functions need to return the output in form of a string as opposed to outputting HTML right away. You can use output buffering to return your code like so:
add_shortcode('sms_order_form', 'sms_order_form_html');
function sms_order_form_html() {
ob_start();
?>
<form>
<div class="tooltip">
0<input type="range" id="range" value="0" min="0" max="100"/>100
<span class="tooltiptext">0</span>
</div>
</form>
<?php
return ob_get_clean(); // clear the output buffer, and return as string
} | unknown | |
d17367 | val | What about using the recyleApp provider to stop and start the app pool?
msdeploy.exe -verb:sync -source:recycleApp -dest:recycleApp="Default Web Site",recycleMode="StopAppPool",computerName=remote-computer
... do your real deployment ...
msdeploy.exe -verb:sync -source:recycleApp -dest:recycleApp="Default Web Site",recycleMode="StartAppPool",computerName=remote-computer | unknown | |
d17368 | val | Mounting of the storage needs to be done once, or when you change credentials of the service principal. Unmount & mount during the execution may lead to a problems when somebody else is using that mount from another cluster.
If you really want to access storage only from that cluster, then you need to configure that properties in the cluster's Spark Conf, and access data directly using abfss://... URIs (see docs for details). Mounting the storage just for time of execution of the cluster doesn't make sense from the security perspective, because during that time, anyone in workspace can access mounted data, as mount is global, not local to a cluster. | unknown | |
d17369 | val | It's hard to tell what you're trying to do here because there are multiple issues in the code. Also though your title mentions SUM your code doesn't include it (though you do have + but that's not the same).
If this is part of a SELECT statement, then I'm guessing what you want is:
SELECT
CASE
WHEN COALESCE(t3.Count3,0)+ COALESCE(t2.Count2,0) >= t4.Count4::float
THEN 100 * t4.Count4::float/(COALESCE(t3.Count3::float,0)+COALESCE(t2.Count2::float,0))
ELSE 0
END as Count5
FROM MyTable | unknown | |
d17370 | val | Nope, that's not possible. You can't have several keys with the same name in an object. Just imagine, how would you address them?
It seems that you need to restructure your data and use arrays.
A: thanks to @Sam,
I modified my structure to add the upload tasks in a form of an array
TasksUploaded ["TaskA","TaskB","TaskC"]
Thank you | unknown | |
d17371 | val | Using the iris dataset:
library(dplyr) # Load package
iris %>% # Take the data
mutate(above_value = if_else(Sepal.Width > 3, "Above", "Below")) %>% # create an toy variable similar to your obese variable
count(Species, above_value) # Count by Species (or gender in your case) and the variable I created above
# A tibble: 6 x 3
Species above_value n
<fct> <chr> <int>
1 setosa Above 42
2 setosa Below 8
3 versicolor Above 8
4 versicolor Below 42
5 virginica Above 17
6 virginica Below 33
A: if your object is called data with columns sex, BP and Obese:
library(dplyr)
summary <- data %>%
group_by(sex) %>%
summarise(count_obese = sum(ifelse(Obese > 1, TRUE, FALSE), na.rm = TRUE),
count_healthy = sum(ifelse(Obese <= 1, TRUE, FALSE), na.rm = TRUE))
sum works as R equates the value TRUE to 1 and FALSE to 0. For example:
> TRUE + FALSE + TRUE
[1] 2 | unknown | |
d17372 | val | Make sure you can view all output:
reuts@reuts-K53SD:~/ccccc$ cat mmph.c && gcc mmph.c
#include<stdio.h>
main(){
int i,x;
for(i=1;i<1000;i++)
{
x=i%3;
if(x==0){
printf("%d\n",i);
}
}
}
reuts@reuts-K53SD:~/ccccc$ ./a.out | egrep "^3$|999"
3
999
As you can see, this works. Your output is probably truncated. | unknown | |
d17373 | val | The dollar sign is used by the compiler for inner classes. I thought it would be strange to manually make classes/files with those names though: As far as I know it's a compiler thing.
A: AFAIK if it's has number it's an anonymous inner class, if it has a name after $ sign it means just inner class.
Edit:
More about how compiler handles you can see here | unknown | |
d17374 | val | I would suggest you to see if there is any thread leak in the application.
You can look at the thread dump in the application master near the executor logs.
Try to set this parameter. --conf spark.cleaner.ttl=10000.
If you are using cache I would suggest you to use persist() it in both memory and disc | unknown | |
d17375 | val | Read this Create, write, and read a file topic about interaction with file in UWP.
To write string to StorageFile use FileIO.WriteTextAsync or FileIO.AppendTextAsync functions
Dim file As StorageFile = Await ApplicationData.Current.LocalFolder.CreateFileAsync("file.txt", CreationCollisionOption.ReplaceExisting)
Dim strData As String = "sample text to write"
Await FileIO.WriteTextAsync(file, strData) | unknown | |
d17376 | val | Windows services (that are created with the right attributes) can be suspended, but I am not sure how an executable can be suspended, or what exactly you mean by that.
If you mean that the program has been stopped, and when it does, you want to restart it, then here are a couple of code blocks that I have used to determine if a program is running:
1) by checking to see if the exe name exists, i.e., is running.
By the way, I recommend this one from my interpretation of your post:
BOOL ExeExists(char *exe)
{
HANDLE pss = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(pe);
if (Process32First(pss, &pe))
{
do
{
if (strstr(pe.szExeFile,exe))
{
CloseHandle(pss);
return TRUE;
}
}
while(Process32Next(pss, &pe));
}
CloseHandle(pss);
return FALSE;
}
2) by checking to see if the PID exists
BOOL PidExists(int pid)
{
HANDLE pss = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(pe);
if (Process32First(pss, &pe))
{
do
{
if (pe.th32ProcessID == pid)
{
CloseHandle(pss);
return TRUE;
}
}
while(Process32Next(pss, &pe));
}
CloseHandle(pss);
return FALSE;
}
By the way this is used to get the process ID (it is defined in winbase.h)
of the application making the call.
int GetProcessIdApp(void)
{
return GetProcessId(GetCurrentProcess());//defined in WinBase.h
}
Inside WinBase.h
WINBASEAPI
DWORD
WINAPI
GetProcessId(
__in HANDLE Process
);
In my scenario, An application broadcasts its PID at start up, such that
my monitoring program (the Windows service) can read it, then use it to make an ongoing determination of the application's status. If the app is discovered to be dead, and if other criteria indicate it should still be running, my service will start it back up. | unknown | |
d17377 | val | What are you trying to achieve? Why not just redirect to '/admin/login' ? And the mount point they are talking about is the place where your Express app is located, not necessarily the current URL. So /blog might be setup on your server to be the root of your app while / might be a totally different app. At least that's the way I read this.
A: The issue here is that while you are using your middleware off of /admin, your app itself is not mounted at /admin. Your app is still off of the root, and your configuration simply says to only use your isAuthenticatedHandler middleware if the request comes in off the /admin path.
I whipped together this gist. Notice how it uses 2 Express applications, one mounted inside the other (line 23 pulls this off). That is an example of mounting the application at a different point rather than just putting a given middleware at a given point. As presently written, that example will give you an endless redirect, since the isAuthenticatedHandler fires for everything off of / in the child application, which equates to /admin overall. Using 2 separate applications might introduce other issues you're not looking to deal with, and I only include the example to show what Express means when it talks about mounting entire applications.
For your present question, you'll either need to follow what Yashua is saying and redirect to /admin/login or mount your admin interface as a separate Express application. | unknown | |
d17378 | val | If you want to print out the x,y mouse positions, you can use .position() like so:
print(pyautogui.position())
It will output something like (346, 653) (the numbers will be different, and this is just an example) where the first value is the x coordinate of the cursor, and the second value being the y coordinate. | unknown | |
d17379 | val | You don't need to mess with Contract Resolvers in ASP.NET Core to use camel-case and F# record types, as you did with ASP.NET. I would take all of that out, or try creating a simple test project to get it working, then go back and make the appropriate changes to your real project. With no additional configuration, you should be able to get something working just by following these steps:
*
*Run dotnet new webapi -lang F#
*Add the following type to ValuesController.fs:
[<CLIMutable>]
type Request =
{
Name: string
Value: string
}
*Change the Post method to be something like this:
[<HttpPost>]
member this.Post([<FromBody>] request:Request) =
this.Created(sprintf "/%s" request.Name, request)
*Debug the service to validate that it works by sending the following request in PostMan:
{
"name": "test",
"value": "abc"
}
You should see the request object echoed back with a 201 response. | unknown | |
d17380 | val | The Google Issue haven't closed yet, but the problem was fix by the Google Team. | unknown | |
d17381 | val | You can use a capturing group to match and capture the digits preceding that word. The below regex will match/capture any character of: digits, . "one or more" times preceded by optional whitespace followed by the word "kcal".
var r = '1119 kJ / 266 kcal'.match(/([\d.]+) *kcal/)[1];
if (r)
console.log(r); //=> "266"
A: Regex is simpler and cleaner but if it's not for you then here's another route. You can split your string by the "/" then split it again by the resulting pairs:
foo = "1119 kJ / 266 kcal";
pairs = foo.split("/");
res = pairs[1]; //get second pair
var res = foo.split(" "); //spit pair by space.
if (isNumber(res[0]) {
alert("It's a number!");
}
function isNumber(n) {
//must test for both conditions
return !isNaN(parseFloat(n)) && isFinite(n);
} | unknown | |
d17382 | val | Xcode provides an object designed for your need. It's called UICollectionViewFlowLayout and all you need to do is subclass it and place your cells the way you want. The function prepareForLayout is call every time the collection view needs to update the layout.
The piece of code you need is below :
#import "CustomLayout.h"
#define MainCell @"MainCell"
@interface CustomLayout ()
@property (nonatomic, strong) NSMutableDictionary *layoutInfo;
@end
@implementation CustomLayout
-(NSMutableDictionary *) layoutInfo
{
if (!_layoutInfo) {
_layoutInfo = [NSMutableDictionary dictionary];
}
return _layoutInfo;
}
-(void) prepareLayout
{
NSMutableDictionary *cellLayoutInfo = [NSMutableDictionary dictionary];
NSIndexPath *indexPath;
CGFloat itemWidth;
CGFloat itemSpacing;
CGFloat widthWithoutSpacing = [self collectionViewContentSize].width / ([self.collectionView numberOfItemsInSection:0]);
if (widthWithoutSpacing > [self collectionViewContentSize].height) {
itemWidth = [self collectionViewContentSize].height;
itemSpacing = ([self collectionViewContentSize].width - itemWidth*[self.collectionView numberOfItemsInSection:0])/
([self.collectionView numberOfItemsInSection:0]+1);
}
else {
itemWidth = widthWithoutSpacing;
itemSpacing = 0;
}
CGFloat xPosition = itemSpacing;
for (NSInteger section = 0; section < [self.collectionView numberOfSections]; section++) {
for (NSInteger index = 0 ; index < [self.collectionView numberOfItemsInSection:section] ; index++) {
indexPath = [NSIndexPath indexPathForItem:index inSection:section];
UICollectionViewLayoutAttributes *itemAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
CGRect currentFrame=itemAttributes.frame;
currentFrame.origin.x = xPosition;
currentFrame.size.width = itemWidth;
currentFrame.size.height = itemWidth;
itemAttributes.frame=currentFrame;
cellLayoutInfo[indexPath] = itemAttributes;
xPosition += itemWidth + itemSpacing;
}
}
self.layoutInfo[MainCell] = cellLayoutInfo;
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return YES;
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.layoutInfo.count];
[self.layoutInfo enumerateKeysAndObjectsUsingBlock:^(NSString *elementIdentifier, NSDictionary *elementsInfo, BOOL *stop) {
[elementsInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath, UICollectionViewLayoutAttributes *attributes, BOOL *innerStop) {
if (CGRectIntersectsRect(rect, attributes.frame)) {
[allAttributes addObject:attributes];
}
}];
}];
return allAttributes;
}
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
return self.layoutInfo[MainCell][indexPath];
}
-(CGSize) collectionViewContentSize
{
return self.collectionView.frame.size;
}
@end
You can also change the y origin of your cells if you need to center them vertically.
A: try with this code. I get the width and use _armedRemindersArray (i guess you use this array for the items).
-(void)setupCollectionViewLayout{
UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout;
//Figure out if cells are wider than screen
CGFloat screenwidth = self.view.frame.size.width;
CGFloat width = screenwidth - ((sectionInsetLeft + sectionInsetRight) *_armedRemindersArray.count + minItemSpacing * (_armedRemindersArray.count -2));
CGSize itemsize = CGSizeMake(width,width);
flowLayout.itemSize = itemsize;
}
A: I don't know why you're setting the itemsize first, and then reducing it. I think you should do it the other way around:
-(void)setupCollectionViewLayout{
UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout;
CGFloat sectionInsetLeft = 10;
CGFloat sectionInsetRight = 10;
CGFloat minItemSpacing = flowLayout.minimumInteritemSpacing;
// Find the appropriate item width (<= 58)
CGFloat screenwidth = self.view.frame.size.width;
CGFloat itemsizeWidth = (screenwidth - sectionInsetLeft - sectionInsetRight - (minItemSpacing * (_armedRemindersArray.count -2))) / _armedRemindersArray.count
itemsizeWidth = itemsizeWidth > 58 ? 58 : itemsizeWidth;
flowLayout.itemSize = CGSizeMake(itemsizeWidth, itemsizeWidth);
}
Does this work? If not, could you please include more of your code? | unknown | |
d17383 | val | I had the same issue and finally found the reason, that is I used the default port 9200 (the correct is 9300 as default). | unknown | |
d17384 | val | It should work if you
*
*Specify which connection every model is using using the $connection property.
*Specify a custom pivot model in your belongsToMany relationship.
use Illuminate\Database\Eloquent\Model;
class Document extends Model
{
protected $connection = 'auth'; // database name
protected $table = 'documents'; // table name
public function items()
{
return $this->belongsToMany(Item::class, 'document_item')->using(DocumentItem::class);
}
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
protected $connection = 'inventory'; // database name
protected $table = 'items'; // table name
public function documents()
{
return $this->belongsToMany(Document::class, 'document_item')->using(DocumentItem::class);
}
}
use Illuminate\Database\Eloquent\Relations\Pivot;
class DocumentItem extends Pivot
{
protected $connection = 'inventory'; // database name
protected $table = 'document_item'; // table name
public function document()
{
return $this->belongsTo(Document::class);
}
public function item()
{
return $this->belongsTo(Item::class);
}
} | unknown | |
d17385 | val | AngularJS $scopes prototypically inherit from each other. Quoting the wiki:
In AngularJS, a child scope normally prototypically inherits from its parent scope. One exception to this rule is a directive that uses scope: { ... } -- this creates an "isolate" scope that does not prototypically inherit.(and directive with transclusion) This construct is often used when creating a "reusable component" directive. In directives, the parent scope is used directly by default, which means that whatever you change in your directive that comes from the parent scope will also change in the parent scope. If you set scope:true (instead of scope: { ... }), then prototypical inheritance will be used for that directive.
This means that assuming you did not pass scope: { ... } you can access properties on the parent's scope directly.
So for example if the parent scope has a x: 5 property - you can simply access it with $scope.x. | unknown | |
d17386 | val | @thindil gave me an idea on how to change the label text using the set_text procedure, however whenever I run his code this message always shows: "subprogram must not be deeper than access type".
Instead of getting a nested procedure, I created a new package. Here's the updated code:
main.adb
with Gdk.Event; use Gdk.Event;
with Gtk.Box; use Gtk.Box;
with Gtk.Label; use Gtk.Label;
with Gtk.Widget; use Gtk.Widget;
with Gtk.Main;
with Gtk.Window; use Gtk.Window;
with Gtk.Button; use Gtk.Button;
with button_click; use button_click;
procedure Main is
Win : Gtk_Window;
Box : Gtk_Vbox;
Box2 : Gtk_Vbox;
Box3 : Gtk_Hbox;
Box4 : Gtk_Hbox;
Box5 : Gtk_Hbox;
function Delete_Event_Cb
(Self : access Gtk_Widget_Record'Class;
Event : Gdk.Event.Gdk_Event)
return Boolean;
---------------------
-- Delete_Event_Cb --
---------------------
function Delete_Event_Cb
(Self : access Gtk_Widget_Record'Class;
Event : Gdk.Event.Gdk_Event)
return Boolean
is
pragma Unreferenced (Self, Event);
begin
Gtk.Main.Main_Quit;
return True;
end Delete_Event_Cb;
begin
-- Initialize GtkAda.
Gtk.Main.Init;
-- Create a window with a size of 400x400
Gtk_New (Win);
Win.Set_Default_Size (400, 400);
-- Create a box to organize vertically the contents of the window
Gtk_New_Vbox (Box);
Win.Add (Box);
-- Add a label inside Vbox Box
Gtk_New (button_click.Label, "Try Pressing the buttons :)");
Box.Add (button_click.Label);
-- Adding Vbox Box2 inside Box
Gtk_New_Vbox (Box2);
Box.Add (Box2);
-- Adding Hbox Box3 inside Box2
Gtk_New_Hbox (Box3);
Box2.Add (Box3);
-- Adding Hbox Box4 inside Vbox Box3
Gtk_New_Hbox (Box4);
Box3.Add (Box4);
-- Adding Hbox Box5 inside Vbox Box3
Gtk_New_Hbox (Box5);
Box3.Add (Box5);
-- Placing Button inside Hbox Box3
Gtk_New (button_click.Button, "Hello");
Box4.Add (button_click.Button);
On_Clicked(button_click.Button, button_clicked'Access);
-- Placing Button2 inside Hbox Box4
Gtk_New (button_click.Button2, "World");
Box5.Add (button_click.Button2);
On_Clicked(button_click.Button2, button_clicked'Access);
-- Placing Button3 inside Vbox Box2
Gtk_New (button_click.Button3, "Hello World");
Box2.Add (button_click.Button3);
On_Clicked(button_click.Button3, button_clicked'Access);
-- Stop the Gtk process when closing the window
Win.On_Delete_Event (Delete_Event_Cb'Unrestricted_Access);
-- Show the window and present it
Win.Show_All;
Win.Present;
-- Start the Gtk+ main loop
Gtk.Main.Main;
end Main;
button_click.ads
with Gtk.Button; use Gtk.Button;
with Gtk.Label; use Gtk.Label;
package button_click is
Button: Gtk_Button;
Button2: Gtk_Button;
Button3: Gtk_Button;
Label : Gtk_Label;
procedure button_clicked (Self : access Gtk_Button_Record'Class);
end button_click;
button_click.adb
with Gtk.Button; use Gtk.Button;
with Gtk.Label; use Gtk.Label;
package body button_click is
procedure button_clicked (Self : access Gtk_Button_Record'Class) is
begin
if Self = Button then
Set_Text(Label, "Hello");
elsif Self = Button2 then
Set_Text(Label, "World");
else
Set_Text(Label, "Hello World");
end if;
end button_clicked;
end button_click;
A: You have to add a callback to buttons to modify the label, in a very similar way like it is done in GTK. I didn't use GTKAda by some time, but it should work:
with Gdk.Event; use Gdk.Event;
with Gtk.Box; use Gtk.Box;
with Gtk.Label; use Gtk.Label;
with Gtk.Widget; use Gtk.Widget;
with Gtk.Main;
with Gtk.Window; use Gtk.Window;
with Gtk.Button; use Gtk.Button;
with Gtk.Grid; use Gtk.Grid;
procedure Main is
Win : Gtk_Window;
Label : Gtk_Label;
Box : Gtk_Vbox;
Button: Gtk_Button;
Button2: Gtk_Button;
Button3: Gtk_Button;
Grid : Gtk_Grid;
function Delete_Event_Cb
(Self : access Gtk_Widget_Record'Class;
Event : Gdk.Event.Gdk_Event)
return Boolean;
---------------------
-- Delete_Event_Cb --
---------------------
function Delete_Event_Cb
(Self : access Gtk_Widget_Record'Class;
Event : Gdk.Event.Gdk_Event)
return Boolean
is
pragma Unreferenced (Self, Event);
begin
Gtk.Main.Main_Quit;
return True;
end Delete_Event_Cb;
-- Callback to update label when buttons were clicked
procedure Update_Label(Self : access Gtk_Button_Record'Class) is
begin
if Self = Button then
Set_Text(Label, "Hello");
elsif Self = Button2 then
Set_Text(Label, "World");
else
Set_Text(Label, "Hello World");
end if;
end Update_Label;
begin
-- Initialize GtkAda.
Gtk.Main.Init;
-- Create a window with a size of 100x120
Gtk_New (Win);
Win.Set_Default_Size (100, 120);
-- Create a box to organize vertically the contents of the window
Gtk_New_Vbox (Box);
Win.Add (Box);
-- Add a label
Gtk_New (Label, "Hello world.");
Box.Add (Label);
-- Add a Grid
Gtk_New (Grid);
Box.Add (Grid);
-- Add the first button to the grid
Gtk_New (Button, "Hello");
-- Attach the callback to the button's event On_Click
On_Clicked(Button, Update_Label'Access);
Grid.Attach (Button, 0, 0, 1, 1);
-- Add Second button to the grid
Gtk_New (Button2, "World");
-- Attach the callback to the second button's event On_Click
On_Clicked(Button2, Update_Label'Access);
Grid.Attach (Button2, 1, 0, 1, 1);
-- Add the third button to the grid
Gtk_New (Button3, "Hello World!");
-- Attach the callback to the third button's event On_Click
On_Clicked(Button3, Update_Label'Access);
Grid.Attach (Button3, 0, 1, 2, 1);
-- Stop the Gtk process when closing the window
Win.On_Delete_Event (Delete_Event_Cb'Unrestricted_Access);
-- Show the window and present it
Win.Show_All;
Win.Present;
-- Start the Gtk+ main loop
Gtk.Main.Main;
end Main; | unknown | |
d17387 | val | You can set ascending or descending in the last argument of your query. In your case, your getData() method can return your string with the KEY_SCORE column in descending order by changing the query line to this:
Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, KEY_SCORE + " DESC");
Good Luck! | unknown | |
d17388 | val | The filePattern attribute is the pattern of the file name to use on rollover. But if you want the date pattern in the name of the file that is actively written tom, you can use Date Lookup in the filename attribute, i.e:
fileName="${sys:catalina.base}${sys:file.separator}logs${sys:file.separator}${web:contextPath}${sys:file.separator}app-${date:dd-MM-yyyy}.log" | unknown | |
d17389 | val | I would do update statement to do all in once like this :
UPDATE OrderTable
INNER JOIN table_to_fill ON OrderTable.refkey = table_to_fill.refkey
SET OrderTable.value = table_to_fill.value
A: Eloquent is very powerfull to manage complicated relationship, joins, eager loaded models etc... But this abstraction has a performance cost. Each model have to be created, filled and saved, it is packed with tons of features you don't need for this precise use case.
When editing thousand or even millions of records, it is highly inefficient to use Eloquent models. Instead you can either use the laravel Query builder or a raw SQL statement.
I would recommend this approach:
$table = Db::table('orders');
foreach ($xml as $row) {
$table->where('reference_key', $reference_key)
->update('new_value', (float)$row->new_value);
}
But you can also do something like this:
foreach ($xml as $row) {
DB::statement('UPDATE orders SET new_value=? WHERE reference_key=?',
[(float)$row->new_value, $reference_key]);
}
It will cut down your execution time significantly but the loop over millions of XML lines will still take a long time. | unknown | |
d17390 | val | 187)
gpg: no ultimately trusted keys found
*Finally I verified the tar archive:
gpg --verify emacs-26.1.tar.xz.sig emacs-26.1.tar.xz
This then returned (as stated at the top):
gpg: no valid OpenPGP data found.
gpg: the signature could not be verified.
Please remember that the signature file (.sig or .asc)
should be the first file given on the command line.
So, is the tar archive corrupt or had I not imported the correct keys? If the latter is the case, what are the correct keys for this GNU download? | unknown | |
d17391 | val | parseKeyFromFile is a convenience function that reads a file and parses the contents. You don't have a file, you have an asset that you are already doing the work of reading into a string. Having read the file, it just parses it - and that's what you need.
This should work:
final publicPem = await rootBundle.loadString('assets/public_key.pem');
final publicKey = RSAKeyParser().parse(publicPem) as RSAPublicKey;
and similar for the private key. | unknown | |
d17392 | val | It probably happens because when you die and get back to frame 1 (where this code probably is) you add another enterframe listener so now your function is executed twice per frame (one time for each event listener). Make sure you add your event listener only once:
var initialized:Boolean;
if(!initialized)
{
initialized = true;
flappy.addEventListener(Event.ENTER_FRAME, fl_gravity);
}
A: It looks like you're increasing the bird's gravity not only if it isn't dead but if it is. It lies outside of the conditional. Remove the line that increases your gravity outside of the conditional (line 16 in that excerpt) | unknown | |
d17393 | val | IIUC, I think you want something like this:
df['Avg Qty'] = (df.groupby([pd.Grouper(freq='180D', key='Date'),'A','B'])['Qty']
.transform('mean'))
Output:
Date A B Qty Cost Avg Qty
0 2017-12-11 Cancer Golf 1 100 1.5
1 2017-11-11 Cancer Golf 2 200 1.5
2 2017-11-11 Cardio Golf 2 300 2.0
3 2017-10-11 Cardio Baseball 3 600 3.0
4 2017-04-11 Cancer Golf 4 150 4.0
5 2016-01-01 Cancer Football 5 200 5.0
Edit:
df = df.set_index('Date')
df.groupby(['A','B']).apply(lambda x: x.sort_index().rolling('180D')['Qty'].mean()).reset_index()\
.merge(df.reset_index(), on=['Date','A','B'], suffixes=('_avg',''))
Output:
A B Date Qty_avg Qty Cost
0 Cancer Football 2016-01-01 5.0 5 200
1 Cancer Golf 2017-04-11 4.0 4 150
2 Cancer Golf 2017-11-11 2.0 2 200
3 Cancer Golf 2017-12-11 1.5 1 100
4 Cardio Baseball 2017-10-11 3.0 3 600
5 Cardio Golf 2017-11-11 2.0 2 300 | unknown | |
d17394 | val | If you save the pointer to AVAudioPlayer then your sound remains in memory and no other lag will occur.
First delay is caused by sound loading, so your 1st playback in viewDidAppear is right.
A: To avoid audio lag, use the .prepareToPlay() method of AVAudioPlayer.
Apple's Documentation on Prepare To Play
Calling this method preloads buffers and acquires the audio hardware
needed for playback, which minimizes the lag between calling the
play() method and the start of sound output.
If player is declared as an AVAudioPlayer then player.prepareToPlay() can be called to avoid the audio lag. Example code:
struct AudioPlayerManager {
var player: AVAudioPlayer? = AVAudioPlayer()
mutating func setupPlayer(soundName: String, soundType: SoundType) {
if let soundURL = Bundle.main.url(forResource: soundName, withExtension: soundType.rawValue) {
do {
player = try AVAudioPlayer(contentsOf: soundURL)
player?.prepareToPlay()
}
catch {
print(error.localizedDescription)
}
} else {
print("Sound file was missing, name is misspelled or wrong case.")
}
}
Then play() can be called with minimal lag:
player?.play() | unknown | |
d17395 | val | This question already has answers. Copy and pasted from here: Coinbase API v2 Getting Historic Price for Multiple Days
Any reason you aren't using coinbase pro?
The new api is very easy to use. Simply add the get command you want followed by the parameters separated with a question mark. Here is the new historic rates api documentation: https://docs.pro.coinbase.com/#get-historic-rates
The get command with the new api most similar to prices is "candles". It requires three parameters to be identified, start and stop time in iso format and granularity which is in seconds. Here is an example:
https://api.pro.coinbase.com/products/BTC-USD/candles?start=2018-07-10T12:00:00&stop=2018-07-15T12:00:00&granularity=900
EDIT: also, note the time zone is not for your time zone, I believe its GMT. | unknown | |
d17396 | val | I worked it out. It doesn't seem to automatically format as being typed on on save (there may be a format on save option somewhere).
Using reformat code:
Crt+Alt+L
Or go to Code in the menu bar, find Reformat Code in the drop down list as shown in the image. | unknown | |
d17397 | val | You need to reference the target table name and column name(s) in the ForeignKey. Therefore, the line:
user_id = db.Column(db.Integer, db.ForeignKey('user_id'), nullable=False)
should be:
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) | unknown | |
d17398 | val | Don't detach, but instead join:
std::vector<std::thread> ts;
for (unsigned int i = 0; i != n; ++i)
ts.emplace_back(OutputElement, v[i], v[i]);
for (auto & t : threads)
t.join();
A: And now for the slightly dissenting answer. And I do mean slightly because I mostly agree with the other answer and the comments that say "don't detach, instead join."
First imagine that there is no join(). And that you have to communicate among your threads with a mutex and condition_variable. This really isn't that hard nor complicated. And it allows an arbitrarily rich communication, which can be anything you want, as long as it is only communicated while the mutex is locked.
Now a very common idiom for such communication would simply be a state that says "I'm done". Child threads would set it, and the parent thread would wait on the condition_variable until the child said "I'm done." This idiom would in fact be so common as to deserve a convenience function that encapsulated the mutex, condition_variable and state.
join() is precisely this convenience function.
But imho one has to be careful. When one says: "Never detach, always join," that could be interpreted as: Never make your thread communication more complicated than "I'm done."
For a more complex interaction between parent thread and child thread, consider the case where a parent thread launches several child threads to go out and independently search for the solution to a problem. When the problem is first found by any thread, that gets communicated to the parent, and the parent can then take that solution, and tell all the other threads that they don't need to search any more.
For example:
#include <chrono>
#include <iostream>
#include <iterator>
#include <random>
#include <thread>
#include <vector>
void OneSearch(int id, std::shared_ptr<std::mutex> mut,
std::shared_ptr<std::condition_variable> cv,
int& state, int& solution)
{
std::random_device seed;
// std::mt19937_64 eng{seed()};
std::mt19937_64 eng{static_cast<unsigned>(id)};
std::uniform_int_distribution<> dist(0, 100000000);
int test = 0;
while (true)
{
for (int i = 0; i < 100000000; ++i)
{
++test;
if (dist(eng) == 999)
{
std::unique_lock<std::mutex> lk(*mut);
if (state == -1)
{
state = id;
solution = test;
cv->notify_one();
}
return;
}
}
std::unique_lock<std::mutex> lk(*mut);
if (state != -1)
return;
}
}
auto findSolution(int n)
{
std::vector<std::thread> threads;
auto mut = std::make_shared<std::mutex>();
auto cv = std::make_shared<std::condition_variable>();
int state = -1;
int solution = -1;
std::unique_lock<std::mutex> lk(*mut);
for (uint i = 0 ; i < n ; ++i)
threads.push_back(std::thread(OneSearch, i, mut, cv,
std::ref(state), std::ref(solution)));
while (state == -1)
cv->wait(lk);
lk.unlock();
for (auto& t : threads)
t.join();
return std::make_pair(state, solution);
}
int
main()
{
auto p = findSolution(5);
std::cout << '{' << p.first << ", " << p.second << "}\n";
}
Above I've created a "dummy problem" where a thread searches for how many times it needs to query a URNG until it comes up with the number 999. The parent thread puts 5 child threads to work on it. The child threads work for awhile, and then every once in a while, look up and see if any other thread has found the solution yet. If so, they quit, else they keep working. The main thread waits until solution is found, and then joins with all the child threads.
For me, using the bash time facility, this outputs:
$ time a.out
{3, 30235588}
real 0m4.884s
user 0m16.792s
sys 0m0.017s
But what if instead of joining with all the threads, it detached those threads that had not yet found a solution. This might look like:
for (unsigned i = 0; i < n; ++i)
{
if (i == state)
threads[i].join();
else
threads[i].detach();
}
(in place of the t.join() loop from above). For me this now runs in 1.8 seconds, instead of the 4.9 seconds above. I.e. the child threads are not checking with each other that often, and so main just detaches the working threads and lets the OS bring them down. This is safe for this example because the child threads own everything they are touching. Nothing gets destructed out from under them.
One final iteration can be realized by noticing that even the thread that finds the solution doesn't need to be joined with. All of the threads could be detached. The code is actually much simpler:
auto findSolution(int n)
{
auto mut = std::make_shared<std::mutex>();
auto cv = std::make_shared<std::condition_variable>();
int state = -1;
int solution = -1;
std::unique_lock<std::mutex> lk(*mut);
for (uint i = 0 ; i < n ; ++i)
std::thread(OneSearch, i, mut, cv,
std::ref(state), std::ref(solution)).detach();
while (state == -1)
cv->wait(lk);
return std::make_pair(state, solution);
}
And the performance remains at about 1.8 seconds.
There is still (sort of) an effective join with the solution-finding thread here. But it is accomplished with the condition_variable::wait instead of with join.
thread::join() is a convenience function for the very common idiom that your parent/child thread communication protocol is simply "I'm done." Prefer thread::join() in this common case as it is easier to read, and easier to write.
However don't unnecessarily constrain yourself to such a simple parent/child communication protocol. And don't be afraid to build your own richer protocol when the task at hand needs it. And in this case, thread::detach() will often make more sense. thread::detach() doesn't necessarily imply a fire-and-forget thread. It can simply mean that your communication protocol is more complex than "I'm done." | unknown | |
d17399 | val | It's because let is only restricted keyword when in strict mode MDN source:
let = new Array();
console.log(let);
VS
"use strict";
let = new Array();
console.log(let);
A: Let is the name of variable.
Example here:
let = new Array
foo = new Array
bar = new Array
console.log(let, foo, bar) | unknown | |
d17400 | val | you can do this
{{ "12/14/2016"|date("Y-m-d", option_timezone_convert) }}
be aware, it will create from that string a datetime object with the default timezone, if you apply a timezone option, it will convert it.
A: PHP's DateTime object can do this as a constructor:
$date = new DateTime('2015-06-20'); | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.