text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Why is a directory I copied from my local machine not showing in the directory listing?
This is the chain of commands I ran:
1) Copy the local directory to the remote server:
$ scp -r <directory> callum@<remote-server-ip>:
2) Log into the remote server and move the directory to the public html directory:
$ sudo mv <directory> /var/www/html
3) From the command line I can see that <directory> is now listed at /var/www/html:
/var/www/html$ ls
<directory> node-apps
When I visit the server IP in the browser, a directory listing is returned and only node-apps appears.
If, from the command line, I create a new directory or file, these are shown in the directory listing in the browser.
The user callum has sudo privileges and I have ssh-key authentication set up, and root login disabled.
Any ideas why my copied directory isn't showing up in the directory listing in the browser?
EDIT: running ls -lsa ouputs:
4 drwxrwx--- 9 callum callum 4096 Mar 8 12:26 <directory>
4 drwxrwxr-x 3 callum callum 4096 Jan 26 14:06 node-apps
A:
In order to solve the problem you need to give access permission to the directory.
The following command should solve the problem:
sudo chmod 775 /var/www/html/<directory_name>
sudo - execute as root
chmod - change permission of the directory
755 - provides read/execute access to anyone
Note, you might also need to give access to the files inside the directory, using the following recursive chmod command:
sudo chmod -R 775 /var/www/html/<directory_name>
Same as above, with the additional paramater:
-R - recursive
| {
"pile_set_name": "StackExchange"
} |
Q:
Php zipping only one file whereas two files are given
I have a form that inputs two files one is eps file other is jpg file.
I put the paths of these two files in an array.
function create_zip($files = array(), $destination=""){
if(count($files)){
$zip = new ZipArchive();
if($zip->open($destination, ZIPARCHIVE::CREATE) !== true) {
return false;
}
foreach($files as $file){
$file_name = explode(".", $file);
$check = count($file_name)-1;
$name = "vector". "." . $file_name[$check];
$zip->addFile($file,$name);
//$zip->addFile($file,$name);
echo "{$name}";
//$zip->addFile($file,$file);
}
$zip->close();
return file_exists($destination);
}
}
This code creates zip file in the destination but the problem is that it only creates zip of eps. Jpg is not added in the zip.
This is how I call this function
$files = array($target_path_jpg,$target_path);
create_zip($files, "../download/{$name}.zip");
There is no problem with paths.
Thanks in advance.
A:
Basically it gives no error whether file exists or not. So there was no file at that time it was created after that
| {
"pile_set_name": "StackExchange"
} |
Q:
how to access events of a specific QML control from c++
Is there a way of accessing signals(such as clicked()) of a QML control such as a button, from c++. Assume that I have the memory address of that specific control. I just want to simulate a click event from c++ code.
A:
Easy. You just create a slot in a C++ object that has a QObject base to it, make sure its registered as a QML type, then you "instantiate" it in the QML document, and connect the desired signal to the C++ object through QML using connect() and handle the logic from the C++ side.
Example:
I have a Rectangle I want to get the onWidthChanged signal from and use it in my class ShapeTracker which tracks when shapes change or whatever
in main.cpp:
#include "shapetracker.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
/* this is where you register ShapeTracker as a QML type that can be
accessed through the QML engine even though its a C++ QObject */
qmlRegisterType<ShapeTracker>("my_cpp_classes", 1, 0, "ShapeTracker");
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
then in
main.qml
import QtQuick 2.6
/* import the C++ class you registered into this QML document */
import my_cpp_classes 1.0
Window {
visible: true
Item {
/* set up a parent item that has a signal which is exposed to
the ShapeTracker object and the Rectangle you want to track */
id: myRootItem
signal rectangleChanged(var newWidth)
/* Heres our special Rectangle from QML that will send a signal when
its width changes */
Rectangle {
id: specialRectangle
width: 250
/* send the signal rectangleChanged(width) from our parent item
root item whenever width changes
*/
onWidthChanged: function() { rectangleChanged(width); }
}
/* Special Button that when clicked enlarges the Rectangle but
10px */
Button {
id: mySpecialButton
onClicked: { click_handler(mouse); }
function click_handler(mouse): {
if (specialRectangle.width < 500)
specialRectangle.width += 10;
}
}
/* Heres the actual ShapeTracker instance, which exists
as a QObject inside of the QML context, but has its methods
which are declared in C++, and exposed to the QML engine */
ShapeTracker {
id: myShapeTracker
/* similar to a constructor, but more like a callback */
Component.onCompleted: {
/* connect our signal from the parent root Item called
"rectangleChanged" to the ShapeTracker's Slot called
"myRectangleChangeHandler" */
myRootItem.rectangleChanged.connect(myShapeTracker.myRectangleChangeHandler);
/* connect send_mouse_click to the click_handler of
the button */
myShapeTracker.send_mouse_click.connect(mySpecialButton.click_handler)
}
}
}
}
in shapetracker.h you simply add a new slot with the name myRectangleChangeHandler and it will receive that signal whenever it is send via QML to be processed via C++
class ShapeTracker : public QObject {
Q_OBJECT
public:
ShapeTracker(QObject *parent = 0 );
signal:
void send_mouse_click(QMouseEvent *event);
public slots:
void myRectangleChangeHandler(QVariant newWidth) {
/* Perform a mouse click on our QML Object mySpecialButton
using QQuickItem::mousePressEvent and sending it via
signal back to QML */
QMouseEvent myEvent(QEvent::MouseButtonPress, QPointF(1,1), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QMouseEvent* pressEvent = QQuickItem::mousePressEvent(&myEvent);
emit send_mouse_click(pressEvent);
}
};
In Summary, you expose a C++ QObject to QML, then you use
object.signal.connect(cppObject.desired_slot)
To connect them -- all the extra stuff was for a functional example in case anyone needs it later
In reality, you don't even need this functionality because anything happening in an onClick event could just as easily be put into any other property such on
Rectangle {
id: rect
signal customClick(var var1)
onCustomClick : { console.log(var1); }
}
Item {
rect.customClick(1);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I maintain health insurance during unpaid leave?
When taking a couple months of unpaid sabbatical in the UK, the employer will usually drop all benefits until the employee is back. Quite certain this policy would cut the national health insurance payments too.
What are the options to maintain cover by health insurance during the sabbatical ? Not asking about the private health insurance, but the one that allows access to NHS services.
Some context: say the sabbatical is for world travel. But there would be a couple weeks in total, in between travel, to be spent in the UK. Would a travel insurance policy cover health costs in the UK too ?
A:
When taking a couple months of unpaid sabbatical in the UK, the
employer will usually drop all benefits until the employee is back.
Quite certain this policy would cut the national health insurance
payments too.
What are the options to maintain cover by health insurance during the
sabbatical ? Not asking about the private health insurance, but the
one that allows access to NHS services.
It seems you are misunderstanding how access to the NHS works. Yes, your employer will pay money to the NHS on your behalf (payments to National Insurance). However, these payments, despite the name, are not like traditional insurance premiums - instead, they are more like a tax.
In particular, as Patricia Shanahan explained in a comment:
Access to NHS care is based on residency in the UK, not on paying contributions.
So it does not matter that your employer will no longer pay National Insurance for you, you are still eligible for NHS care.
Would a travel insurance policy cover health costs in the UK too ?
No, travel insurance typically only covers treatment during travel (that's why it's usually less expensive than regular health insurance). Additionally, it often excludes health problems that existed before the travel, so if you fall ill, you cannot travel just to be covered. Read the policy for details.
At any rate, you do not need cover from your travel insurance when you are in the UK, as you are covered by the NHS, as explained above.
A:
The NHS is largely funded from taxes, including employment related taxes, but it is not an employment-related insurance system. It is a service, primarily for UK residents.
There are complications such as fee-for-service for some services to visitors. Some visa types require a contribution to the NHS.
The simplest case, and the one that seems to apply here, is that anyone who is Ordinarily Resident in the UK is covered. The OP has been living in the UK, and plans to travel outside the UK during a two month period while keeping their main home in the UK.
The OP will need travel insurance for the time outside the UK.
| {
"pile_set_name": "StackExchange"
} |
Q:
get query execution time in command prompt
I'm doing this query select * from rentals. This table has more than 10,000 rows and it takes more than 4 minutes to retrieve the results.
But I get this time after I get the results: 10000 rows in set (0,05 sec).
Do you know how to get the real execution time?
I try with:
set profiling = 1;
select * from rentals;
show profiles;
But also appears that the query duration is: 0,5080950.
A:
In all probability, your query takes half a second to run, but it takes a lot more time to display all the results.
The latter depends on the speed of your network and that of your computer and is not really relevant from a performance tuning perspective.
To answer your question, the query execution time (0.5 seconds) is the execution time.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to upload application with app groups to Apple store?
I create an app with Watchkit extension using App Groups function. Now I want to upload this app to Apple store. I do like this:
Create App ID for my App (ex:com.standardApplication.tictactoe)
Enable appGroup in Capabilities in Xcode for IOS app and Watchkit app using identifier: "group.com.standardApplication.ticTacToe"
Create Provisioning Profiles for Development and Distribution on Certificates, Identifiers & Profiles center with my App ID that I create before. Download it and double klick to add it to my Xcode.
After that I go to Itune connect to make a new App with my App ID and info...
After that in Xcode and build Setting, I changed the code signing for all targets(iOS Target and Watchkit target) like this:
But when I tried to archive my app for submit to Apple Store I got this error:
Check dependencies
Code Sign error: No matching provisioning profiles found: None of the valid provisioning profiles allowed the specified entitlements: com.apple.security.application-groups.
CodeSign error: code signing is required for product type 'WatchKit Extension' in SDK 'iOS 8.3'
I don't know how to fix that, although I tried some method that I know or search google but no luck, please help me.
A:
You have a also create WatchKit Extension provisioning profiles & create and set the same way to your ios app.
create Extension app id (ex:com.standardApplication.tictactoe.watchkitApp)
Enable appGroup Capabilities in Extension app id and set Extension
app target
Create Provisioning Profiles for Extension app and then set..
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL: strange behaviour using UNION, MAX and GROUP BY
I had a simple table that stores messages:
+----+--------+----------+--------------+------+
| id | sender | receiver | dt | text |
+----+--------+----------+--------------+------+
| 1 | a | b | ..19.26.00.. | msg1 |
+----+--------+----------+--------------+------+
| 2 | c | b | ..19.26.02.. | msg2 |
+----+--------+----------+--------------+------+
| 3 | b | a | ..19.26.03.. | msg3 |
+----+--------+----------+--------------+------+
I want to select the most recent message in a conversation. For example, for b I want:
+--------------+--------------+------+
| conversation | MAX(maxdt) | text |
+--------------+--------------+------+
| ab | ..19.26.03.. | msg3 |
+--------------+--------------+------+
| cb | ..19.26.02.. | msg2 |
+--------------+--------------+------+
so I use this query:
SELECT conversation, MAX(maxdt), text FROM
(SELECT CONCAT(sender, receiver) AS conversation, MAX(dt) AS maxdt, text
FROM message
WHERE receiver='b' GROUP BY conversation
UNION
SELECT CONCAT(receiver, sender) AS conversation, MAX(dt) AS maxdt, text
FROM message
WHERE sender='b' GROUP BY conversation) AS x
GROUP BY conversation
but the result is:
+--------------+--------------+------+
| conversation | MAX(maxdt) | text |
+--------------+--------------+------+
| ab | ..19.26.03.. | msg1 |
+--------------+--------------+------+
| cb | ..19.26.02.. | msg2 |
+--------------+--------------+------+
So, the datetime value is correct but the text comes from the wrong tuple!
Any suggestions? SQL Fiddle
A:
Ok I have a possible solution, working SQL fiddle. Try this:
SELECT CONCAT('b',other) AS conversation, text, dt AS maxdt FROM
(
SELECT IF(sender='b',receiver, sender) AS other, dt, text
FROM message
WHERE (receiver='b' OR sender='b') order by dt desc
)
AS TBL group by other
if you want the conversation field standardized you can just CONCAT ('b', other) as conversation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Obtaining windows menu from the dock with a quick click
In OS X (and in Mountain Lion, in particular) when you minimize a window and you want to retrieve it, you can press on an icon in the dock and wait 1 second to get the menu with the opened windows. Is it possible to change this setting so that this menu opens on a mouse click immediately (preferably, the menu would appear when there is more than one window and, as it is currently, the click maximizes the minimized window if there is only one window instance of that program)?
A:
If you mean this menu
you can show it immediately by just secondary-clicking (which usually means right-clicking) the Dock icon.
| {
"pile_set_name": "StackExchange"
} |
Q:
Azure App Service Continuous Deployment Webhook doesn't work
(I already asked in the Microsoft Forum but didn't get an answer.)
I have an App Service using a private registry with Continuous Deployment enabled. The app is running totally fine but the Webhook URL for the Continuous Deployment doesn't work.
Here's the output of an HTTP GET request to the webhook:
$ curl https://\$MySiteName:[email protected]/docker/hook
"No route registered for '/docker/hook'"
Someone in the Microsoft Forum told me to try a POST request, so here's the output of that:
$ curl -X POST https://\$MySiteName:[email protected]/docker/hook
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Length Required</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Length Required</h2>
<hr><p>HTTP Error 411. The request must be chunked or have a content length.</p>
</BODY></HTML>
I haven't found anywhere in the Microsoft Azure docs how to use the webhook.
A:
After more searching, I found this answer.
The answer suggests to do the following:
curl https://\$MySiteName:[email protected]/docker/hook -H "" -d ""
No idea why this works and I wish there was something in the Azure docs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Replace all odd occurrences of a substring using regex
I have a string ~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~
I want to replace the odd occurrences of substring '~~' i.e 1st, 3rd.. with another string '**'.
My output should be **40~~ Celsius Temp: 33 Celsius Temp:**50~~
How to achieve this with regex in Java?
A:
You really need a rudimentary parser to handle this; regex wasn't designed to count occurrences like this. The logic of the code below is simple. Every time we hit a match ~~ we do one of two things. If it is an odd occurrence, then we append empty string to the replacement, otherwise we reappend the ~~ which we matched.
String input = "~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~";
Pattern p = Pattern.compile("~~");
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer(input.length());
int i = 0;
while (m.find()) {
if (i % 2 == 0) {
m.appendReplacement(sb, "**");
}
else {
m.appendReplacement(sb, m.group(0));
}
++i;
}
m.appendTail(sb);
System.out.println(sb.toString());
**40~~ Celsius Temp: 33 Celsius Temp:**50~~
Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
Updating a single element in a nested list with official C# MongoDB driver
I have a simple game with multiple rounds and I want to update the most recent round:
class Game
{
public ObjectId Id { get; set; }
public List<Round> Rounds { get; set; }
}
class Round
{
public int A { get; set; }
public int B { get; set; }
}
How can I do the equivalent of games.Rounds.Last().A = x using the official MongoDB C# driver?
Edit: Added Round.B. Note that in this case, both A and B may be updated concurrently so I cannot save back the entire document. I only want to update the A field.
A:
If you're using the drivers with LINQ support, then I suppose you could do this:
var last = collection.AsQueryable<Game>().Last();
last.A = x;
collection.Save(last);
I imagine it wouldn't be as efficient as a hand-coded update statement, but this does functionally mirror your javascript version for the most part.
Edit: Without LINQ, and doing a subset update
var query = Query.EQ("_id", MongoDB.Bson.BsonValue.Create(games.Id);
var update = Update.Set("Rounds." + games.Rounds.Length - 1 + ".A", MongoDB.Bson.BsonValue.Create(x));
Collection.Update(query, update);
Not so pretty looking, but you can index into an array by the number in Mongo, so you'd miss out on the case where a new Round was added to the game before you update.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proof of Integration formula
$$\int_0^{\infty}x^{-1}e^{-ax}\sin (bx) \;\mathrm dx = \arctan \frac{b}{a}$$
How to prove this result?
A:
Let
$$F(a)=\int_0^{\infty}x^{-1}e^{-ax}\sin (bx) \;\mathrm dx $$
then we can prove using Leibniz theorem: differentiate under the sign $\int$ that:
$$F'(a)=-\int_0^{\infty}e^{-ax}\sin (bx) \;\mathrm dx=-\operatorname{Im} \int_0^{\infty}e^{(-a+ib)x} \;\mathrm dx=\operatorname{Im}\frac{1}{-a+ib}=-\frac b{a^2+b^2}$$
so
$$F(a)=-\int \frac b{a^2+b^2}da=\arctan\frac b a+C$$
Notice that $C=0$ since the integral is zero for $b=0$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Example Servlet Filter that catches and blocks IP's that request suspicious URL's
To avoid re-developing the wheel. Are there any example Java EE servlet filters that take care of some basic security checks/ i.e.
Block web requests for a time period if a rootkit hits the server, ie with a url that ends in .exe or contains "../../.."
Throttle or block IP's that are making unexpectedly high number of requests.
I also wonder if something equivalent to a Thread.sleep(1000); in the servlet filter for those particular types of requests wouldn't be such a bad thing.
A:
Maybe this will help.
public class SuspiciousURLFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String requestURI = httpRequest.getRequestURI();
if (requestURI.endsWith(".exe")) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
//send error or maybe redirect to some error page
httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
filterChain.doFilter(request, response);
}
@Override
public void init(FilterConfig config) throws ServletException {
}
}
In your web.xml:
<filter>
<filter-name>suspiciousURLFilter </filter-name>
<filter-class>your.package.SuspiciousURLFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SuspiciousURLFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
| {
"pile_set_name": "StackExchange"
} |
Q:
.htaccess remove index.php sort of works, but not the first time after browser cache is cleared
I don't know if this is a new thing or if it's been an issue all along, but the client just noticed and i recreated the issue myself. If I clear my browser cache and then visit my client's site at a URL like http://www.example.com/product/product1 it will redirect to http://www.example.com/index.php/product/product1. The page looks fine. After refreshing or visiting that URL again the URL will pull up correctly at http://www.example.com/product/product1. If I clear my browser cache again it will redirect to the index.php url again.
Here's my .htaccess file, any ideas why this might be happening? Thanks for any ideas!
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond $1 !(^index\.php|(\.(gif|jpe?g|png|css|js)))$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
Redirect 301 /helpdesk http://helpdesk.example.com
Redirect 301 /splash http://example.com
Redirect 301 /webmail http://mail.example.com:32000
Redirect 301 /email http://mail.example.com:32000
Redirect 301 /timeclock http://timeclock.example.com:62345
Redirect 301 /signature http://signature.example.com
EDIT: I modified my .htaccess file to the recommended one from EllisLab and that seems to have fixed the index.php from showing up. Something is still a little wonky though. When I clear the browser cache and visit a url with a hash tag at the end (http://www.example.com/product/product1#tab3), the redirect removes the hash tag and the rest of the url after it. If I refresh the page it will work as expected. it only has issues with the first time visiting the url after a clean browser cache. Any ideas?
RewriteEngine On
RewriteBase /
# Removes index.php from ExpressionEngine URLs
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteCond %{REQUEST_URI} !/system/.* [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
# Directs all EE web requests through the site index file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
A:
On further investigation, it appears that this redirect is coming from inside that template.
See the attached image
All of your header assets are being loaded just fine until something else triggers the redirect, in this example it happened after the server already responded to 15 gets from the generated page. What kind of addons does this template use? Try investigating that.
EDIT: To be clear, anchor tags are never even sent to the server. If it is the .htaccess setup, there is no way it's rewriting anything based on anchors.
| {
"pile_set_name": "StackExchange"
} |
Q:
clear command - terminals database is inaccessible
I am using Ubuntu 16.04 while using clear in terminal, it produces error
terminals database is inaccessible
But when I use sudo clear it works as intended. I have removed some files in /var/www/ and this problem started. I checked this question "clear" command in GNOME terminal returns "terminals database is inaccessible" but that did not help in any way
Edit: Output of strace -etrace=open clear
open("/home/user/anaconda3/bin/../lib/tls/x86_64/libncursesw.so.5", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/home/user/anaconda3/bin/../lib/tls/libncursesw.so.5", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/home/user/anaconda3/bin/../lib/x86_64/libncursesw.so.5", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/home/user/anaconda3/bin/../lib/libncursesw.so.5", O_RDONLY|O_CLOEXEC) = 3
open("/home/user/anaconda3/bin/../lib/libc.so.6", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
terminals database is inaccessible
+++ exited with 1 +++
A:
You might have moved the anaconda directory after installation and some bash script links in some files from anaconda directory are still pointing to the previous location. Simplest solution is to delete your current anaconda installation directory, remove any paths in .bashrc pointing to it and reinstall it in the desired location.
A:
Path for Anaconda3 is set in .bashrc. It is interfering with clear command.
Removing Anaconda path from path solved the issue. Here is the github reference for the issue https://github.com/ContinuumIO/anaconda-issues/issues/331
| {
"pile_set_name": "StackExchange"
} |
Q:
MGTwitterEngine currentNode is unavailable
I am using the MGTwitterEngine in an iOS app that was built by a third party. I have taken over development but have limited experience in objective c.
I am getting an error: 'currentNode' is unavailable.
This is in the MGTwitterXMLParser.m file. The interface has a weak link like this:
__weak NSMutableDictionary *currentNode;
I had to add the libOAuth.a file because it was missing and I am wondering if this is the cause. Do I need a certain version of libOAuth?
The weird part is that it worked with the new libOAuth.a until I updated XCode to the latest version which is 7.3. Is anyone having issues with MGTwitterEngine in 7.3?
UPDATE:
In XCode (I was compiling in AppCode) I now see that it says, "Declaration uses __weak, but ARC is disabled."
This is in MGTwitterXMLParser:
__weak NSMutableDictionary *currentNode;
My project has ARC enabled and I don't see any way to set ARC for the MGTwitterEngine or any individual files. Is there a way to do this?
A:
Okay, the answer was simple once I understood the problem. I simply needed to discard the __weak for the NSMutableDictionary and it compiled.
Still need to test Twitter and look for any memory leaks. Also, not sure how the app ever compiled before with a __weak reference in a non-ARC file.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the lldb equivalent of gdb's --args?
I'm used to running gdb like so:
$ gdb --args exe --lots --of --flags -a -b -c d e
...
(gdb) r
Is there an equivalent for lldb?
A:
Yes, it's just -- instead of --args. From the help:
lldb -v [[--] <PROGRAM-ARG-1> [<PROGRAM_ARG-2> ...]]
Thus:
$ lldb -- exe --lots --of --flags -a -b -c d e
| {
"pile_set_name": "StackExchange"
} |
Q:
google maps v3-- why are these map methods undefined?
I'm new to the V3 version of the maps API, having used V2 in the past. As a result, there are some map creation issues I've run into while trying to port our app from V2 to V3.
I'm creating a map like this now, and it seems to work-- I'm returned a map object in the variable m_oGoogleMap:
m_oGoogleMap = new google.maps.Map(
$('Map'), {
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 8,
center: new google.maps.LatLng(LAT, LNG)
});
...However, after doing this I cannot call methods such as getBounds() or getProjection() without receiving an undefined error-- I can see stubs for those methods while debugging, in the Chrome watch expressions area, but calling them there (or on the page itself) yields an undefined error. Am I missing how to create and initialize a map in V3?
Other methods on the map object, such as getDiv(), work just fine. So I'm not sure if I have a half-initialized object or what might be happening?
A:
The creation of a map is an asynchronous process, some methods/properties are not accessible before this process has been finished. Wait for events like idle or tilesloaded before you access these methods.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Linq .Min() - At least one object must implement IComparable
I want to get the smallest value in a collection and I am using LINQ to do this. I've read online I can use Min() but I am getting the error message:
At least one object must implement IComparable
This is my code
public virtual void GetBestValue(ModelEnergyCalculator ModelEnergyCalculator)
{
ModelTariffQuote ModelTariffQuote = (from q in ModelEnergyCalculator.ModelTariffQuotes
select q).Min();
}
This is my collection
- - ModelEnergyCalculator {EnergyHelpline.Model.ModelEnergyCalculator} EnergyHelpline.Model.ModelEnergyCalculator
- ModelTariffQuotes Count = 4 System.Collections.Generic.List<EnergyHelpline.Model.ModelTariffQuote>
- [0] {EnergyHelpline.Model.ModelTariffQuote} EnergyHelpline.Model.ModelTariffQuote
ElectricityUsage 0 decimal
FinalElectricityCost 179.97655091937073972602739726 decimal
FinalGasCost 112.48534432460671232876712328 decimal
GasUsage 0 decimal
InitialElectricityCost 30.0117245403146958904109589 decimal
InitialGasCost 18.757327837696684931506849312 decimal
+ QuoteIssuedDate {01/01/0001 00:00:00} System.DateTime
TariffName null string
TotalCalculatedCost 341.23094762198883287671232875 decimal
+ [1] {EnergyHelpline.Model.ModelTariffQuote} EnergyHelpline.Model.ModelTariffQuote
+ [2] {EnergyHelpline.Model.ModelTariffQuote} EnergyHelpline.Model.ModelTariffQuote
+ [3] {EnergyHelpline.Model.ModelTariffQuote} EnergyHelpline.Model.ModelTariffQuote
+ Raw View
+ ModelTariffs Count = 4 System.Collections.Generic.List<EnergyHelpline.Model.ModelTariff>
How do I fix this error or is there a better way for getting the smallest value?
A:
An easier and more flexible way of doing this than using IComparable is to order the objects as you need and take the first one. If you need the highest then you just need to use OrderByDescending.
var lowest = ModelEnergyCalculator.ModelTariffQuotes
.OrderBy(m => m.GasFinalRate)
.FirstOrDefault();
| {
"pile_set_name": "StackExchange"
} |
Q:
Set a hidden property to a ListBox Item - C#
hey,
Does anybody knows a way to set a hidden value to a ListBox Item.
As an alternative i can use another listbox simultaneously.
Thanks.
A:
You are probably looking for the Tag property. It holds an object type, which means you can save a reference to anything in there.
Although before setting on using the tag property, take a look at ItemsSource. Basically you can tie a collection of things to be the provider for your listbox, it's usually a superior alternative to dealing with Listbox items individually.
| {
"pile_set_name": "StackExchange"
} |
Q:
useEffect has missing dependency
For the life of me I can't seem to remove the ESlinting warning about my useEffect having a missing dependency fetchProfile(). When I add fetchProfile to the dependency array, I get an endless loop. I would really appreciate any suggestions that could help me stifle this warning. The code is as follows:
import React, { useEffect, useContext, useReducer } from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import './App.css'
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles/'
import UserContext from './contexts/UserContext'
import jwtDecode from 'jwt-decode'
import axios from 'axios'
// utils
import reducer from './utils/reducer'
import themeFile from './utils/theme'
import AuthRoute from './utils/AuthRoute'
import UnAuthRoute from './utils/UnAuthRoute'
// Components
import NavBar from './components/NavBar'
// Pages
import Home from './pages/Home'
import Login from './pages/Login'
import Profile from './pages/Profile'
import SignUp from './pages/SignUp'
import Admin from './pages/Admin'
import Dashboard from './pages/Dashboard'
import Alumni from './pages/Alumni'
// context
import { ProfileContext } from './contexts/ProfileContext'
const theme = createMuiTheme(themeFile)
// axios.defaults.baseURL = `https://us-central1-jobtracker-4f14f.cloudfunctions.net/api`
const App = () => {
const initialState = useContext(UserContext)
const [user, setUser] = useContext(ProfileContext)
const [state, dispatch] = useReducer(reducer, initialState)
const fetchProfile = async token => {
await axios
.get(`/user`, {
headers: {
Authorization: `${token}`
}
})
.then(res => {
setUser(res.data)
})
.catch(err => console.log({ err }))
}
// keeps userContext authorized if signed in
useEffect(
_ => {
const token = localStorage.FBIdToken
if (token && token !== 'Bearer undefined') {
const decodedToken = jwtDecode(token)
if (decodedToken.exp * 1000 < Date.now()) {
localStorage.removeItem('FBIdToken')
dispatch({ type: 'LOGOUT' })
} else {
dispatch({ type: 'LOGIN' })
state.isAuth && fetchProfile(token)
}
} else {
dispatch({ type: 'LOGOUT' })
localStorage.removeItem('FBIdToken')
}
},
[state.isAuth]
)
return (
<MuiThemeProvider theme={theme}>
<UserContext.Provider value={{ state, dispatch }}>
<div className="App">
<Router>
<NavBar isAuth={state.isAuth} />
<div className="container">
<Switch>
<Route exact path="/" component={Home} />
<UnAuthRoute
path="/signup"
component={SignUp}
isAuth={state.isAuth}
/>
<UnAuthRoute
path="/login"
component={Login}
isAuth={state.isAuth}
/>
<AuthRoute
path="/profile"
component={Profile}
isAuth={state.isAuth}
/>
<AuthRoute
path="/dashboard"
component={Dashboard}
isAuth={state.isAuth}
/>
<Route path="/admin" component={Admin} isAuth={state.isAuth} />
<AuthRoute
path="/users/:id"
component={Alumni}
isAuth={state.isAuth}
/>
</Switch>
</div>
</Router>
</div>
</UserContext.Provider>
</MuiThemeProvider>
)
}
export default App
A:
You can do one of two things:
Move fetchProfile out of the component entirely, and use its result instead of having it call setUser directly.
Memoize fetchProfile so you only create a new one when something it depends on changes (which is...never, because fetchProfile only depends on setUser, which is stable). (You'd do this with useMemo or its close cousin useCallback, probably, though in theory useMemo [and thuse useCallback] is for performance enhancement, not "semantic guarantee.")
For me, #1 is your best bet. Outside your component:
const fetchProfile = token => {
return axios
.get(`/user`, {
headers: {
Authorization: `${token}`
}
})
}
then
useEffect(
_ => {
const token = localStorage.FBIdToken
if (token && token !== 'Bearer undefined') {
const decodedToken = jwtDecode(token)
if (decodedToken.exp * 1000 < Date.now()) {
localStorage.removeItem('FBIdToken')
dispatch({ type: 'LOGOUT' })
} else {
dispatch({ type: 'LOGIN' })
if (state.isAuth) { // ***
fetchProfile(token) // ***
.then(res => setUser(res.data)) // ***
.catch(error => console.error(error)) // ***
} // ***
}
} else {
dispatch({ type: 'LOGOUT' })
localStorage.removeItem('FBIdToken')
}
},
[state.isAuth]
)
Since the action is asynchronous, you might want to cancel/disregard it if the component re-renders in the meantime (it depends on your use case).
| {
"pile_set_name": "StackExchange"
} |
Q:
I want to make border like attached image
I want to make border like attached image in my app. Please help me for same.
original screen is as same as a code below.
I want to make as first screen image . Tell me changes in xml .
How to make a border like a scereen image?
customborder.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="2dp">
<shape android:shape="rectangle" >
<stroke
android:width="2dp"
android:color="#009bdb" />
<solid android:color="#00FFFFFF" />
<padding android:left="0dp"
android:right="0dp"
android:top="2dp"
android:bottom="0dp" />
</shape>
</item>
</layer-list>
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/customborder"
android:layout_margin="10dp"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:orientation="horizontal"
android:background="#cbe5f8"
android:padding="5dip"
>
<TextView
android:id="@+id/textView1"
android:text="Order Id:"
android:textColor="@color/textcolor"/>
<TextView
android:id="@+id/textView2"
android:text="Placed Date:"
android:gravity="right"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="15dip"></TextView>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:padding="5dip"
android:orientation="vertical"
android:background="@drawable/bdr_top_bottom"
>
<TextView
android:id="@+id/textView3"
android:text="Address:" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:padding="5dip"
android:orientation="vertical"
android:background="@drawable/bdr_top_bottom">
<TextView
android:id="@+id/textView4"
android:text="Placed Order:" />
<TextView
android:id="@+id/placedorder"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1"
/>
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:padding="5dip"
android:orientation="vertical"
android:background="@drawable/bdr_top_bottom">
<TextView
android:id="@+id/textView5"
android:text="Service Opted: " />
<TextView
android:id="@+id/serviceopted"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1"
/>
</TableRow>
<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:padding="5dip"
android:orientation="vertical"
android:background="@drawable/bdr_top_bottom">
<TextView
android:id="@+id/textView6"
android:text="Order Status:" />
<TextView
android:id="@+id/orderstatus"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1"
/>
</TableRow>
<TableRow
android:id="@+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:padding="5dip"
android:orientation="vertical"
android:background="@drawable/bdr_top_bottom">
<TextView
android:id="@+id/textView7"
android:text="Time Slot:" />
<TextView
android:id="@+id/timeslot"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1"
/>
</TableRow>
<TableRow
android:id="@+id/tableRow7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:padding="5dip"
android:orientation="vertical"
android:background="@drawable/bdr_top_bottom">
<TextView
android:id="@+id/textView8"
android:text="Contact Number:" />
<TextView
android:id="@+id/contactno"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:text="8556023080"
android:layout_weight="1"
/>
</TableRow>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"
android:padding="6dp"
android:weightSum="2">
<Button
android:id="@+id/repeat"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_marginTop="20dp"
android:text="Repeat Order"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_marginBottom="20dp"
android:textSize="20dp"
android:background="#009bdb"
android:textColor="#FFFFFF"
android:layout_weight="1"/>
</LinearLayout>
</TableLayout>
A:
Add this xml in your drawable folder
bdr_top.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:bottom="-2dp"
android:left="-2dp"
android:right="-2dp"
android:top="2dp">
<shape android:shape="rectangle" >
<stroke
android:width="2dp"
android:color="#009bdb" />
<solid android:color="#00FFFFFF" />
<padding android:left="0dp"
android:right="0dp"
android:top="0dp"
android:bottom="0dp" />
</shape>
</item>
</layer-list>
bdr_top_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:bottom="-1dp"
android:left="-1dp"
android:right="-1dp"
android:top="1dp">
<shape android:shape="rectangle" >
<stroke
android:width="1dp"
android:color="#7e7e7e" />
<solid android:color="#00FFFFFF" />
<padding android:left="0dp"
android:right="0dp"
android:top="0dp"
android:bottom="0dp" />
</shape>
</item>
</layer-list>
bdr_all.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp">
<shape android:shape="rectangle" >
<stroke
android:width="1dp"
android:color="#7e7e7e" />
<solid android:color="#00FFFFFF" />
<padding android:left="0dp"
android:right="0dp"
android:top="0dp"
android:bottom="0dp" />
</shape>
</item>
</layer-list>
Your xml replace with it
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/llParent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bdr_top"
android:layout_marginTop="10dp"
android:orientation="vertical"
android:padding="10dip">
<TableLayout
android:id="@+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="@drawable/bdr_all">
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#7e7e7e"
android:orientation="horizontal"
android:padding="10dip">
<TextView
android:id="@+id/textView1"
android:text="Order Id:" />
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:padding="5dip"
android:text="Placed Date:"></TextView>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bdr_top_bottom"
android:orientation="vertical"
android:padding="10dip">
<TextView
android:id="@+id/textView3"
android:text="Address:" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bdr_top_bottom"
android:orientation="vertical"
android:padding="10dip">
<TextView
android:id="@+id/textView4"
android:text="Placed Order:" />
<TextView
android:id="@+id/placedorder"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bdr_top_bottom"
android:orientation="vertical"
android:padding="10dip">
<TextView
android:id="@+id/textView5"
android:text="Service Opted: " />
<TextView
android:id="@+id/serviceopted"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1" />
</TableRow>
<TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bdr_top_bottom"
android:orientation="vertical"
android:padding="10dip">
<TextView
android:id="@+id/textView6"
android:text="Order Status:" />
<TextView
android:id="@+id/orderstatus"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1" />
</TableRow>
<TableRow
android:id="@+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bdr_top_bottom"
android:orientation="vertical"
android:padding="10dip">
<TextView
android:id="@+id/textView7"
android:text="Time Slot:" />
<TextView
android:id="@+id/timeslot"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1" />
</TableRow>
<TableRow
android:id="@+id/tableRow7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bdr_top_bottom"
android:orientation="vertical"
android:padding="10dip">
<TextView
android:id="@+id/textView8"
android:text="Contact Number:" />
<TextView
android:id="@+id/contactno"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1"
android:text="8556023080" />
</TableRow>
</TableLayout>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:padding="6dp"
android:weightSum="2">
<Button
android:id="@+id/repeat"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:background="#009bdb"
android:text="Repeat Order"
android:textColor="#FFFFFF"
android:textSize="20dp" />
</LinearLayout>
| {
"pile_set_name": "StackExchange"
} |
Q:
UnicodeDecodeError reading a CSV file
I use the following code to read a CSV file:
address=r'C:\Users\ssadangi\Desktop\Lynda Python data analytics\Ch02\02_05\Superstore-Sales.csv'
df=pd.read_csv(address,index_col='Order Date',parse_dates=True)
The code gives me this error:
UnicodeDecodeError Traceback (most recent call last)
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._convert_tokens()
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._convert_with_dtype()
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._string_convert()
pandas/_libs/parsers.pyx in pandas._libs.parsers._string_box_utf8()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 16: invalid start byte
During handling of the above exception, another exception occurred:
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-28-3fa20db347ab> in <module>()
----> 1 df=pd.read_csv('Superstore-Sales.csv',index_col='Order Date',parse_dates=True)
~\Documents\Softwares\Anaconda\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
707 skip_blank_lines=skip_blank_lines)
708
--> 709 return _read(filepath_or_buffer, kwds)
710
711 parser_f.__name__ = name
~\Documents\Softwares\Anaconda\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
453
454 try:
--> 455 data = parser.read(nrows)
456 finally:
457 parser.close()
~\Documents\Softwares\Anaconda\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
1067 raise ValueError('skipfooter not supported for iteration')
1068
-> 1069 ret = self._engine.read(nrows)
1070
1071 if self.options.get('as_recarray'):
~\Documents\Softwares\Anaconda\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
1837 def read(self, nrows=None):
1838 try:
-> 1839 data = self._reader.read(nrows)
1840 except StopIteration:
1841 if self._first_chunk:
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.read()
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory()
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_rows()
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._convert_column_data()
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._convert_tokens()
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._convert_with_dtype()
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._string_convert()
pandas/_libs/parsers.pyx in pandas._libs.parsers._string_box_utf8()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 16: invalid start byte
A:
This is encoding error when you use pd.read_csv() function you have to define encoding as well
address=r'C:\Users\ssadangi\Desktop\Lynda Python data analytics\Ch02\02_05\Superstore-Sales.csv'
df=pd.read_csv(address,index_col='Order Date',parse_dates=True,encoding='latin1') #here i am using encoding attribute
| {
"pile_set_name": "StackExchange"
} |
Q:
Add item in order to a list
What is the best way to add an item to an ordered list?
I want that when an item changes the value the value of that control is placed on a list.
Example
-radiobutton value = radiobuttonvalue;
-checkbox value = checkboxvalue;
-textbox value = textboxvalue;
clicks: first on the checkbox than radiobutton and last textbox.
output:
<ul>
<li>radiobuttonvalue</li>
<li>checkboxvalue</li>
<li>textboxvalue</li>
</ul>
so i that it doen't matter in wich control is clicked first, the output is always in the same order.
A:
So you want to output the values of your fields in the order of the fields in the form? If so, this might be what you're looking for:
$(function() {
var fieldValues = [];
$('.field').change(function() {
// get the index of the field
var fieldIndex = $(this).index();
// store the value of the field in the array using it's index
fieldValues[fieldIndex] = $(this).val();
// our output list
var $list = $("#output");
// clear the list
$list.html("");
// loop through our values and add them to the list
for(value in fieldValues) {
$list.append("<li>"+fieldValues[value]+"</li>");
}
});
});
html:
<input class="field" />
<input class="field" />
<input class="field" />
<input class="field" />
<ul id="output"></ul>
| {
"pile_set_name": "StackExchange"
} |
Q:
Regular expression for parsing array indexing expressions in C++
Am doing some semantic analysis on C++ source code.
I have a regular expression to transform the array declarations from int [123] [1234] to int [number] [number].
But I want the expression also be able to match dimensions such as these
int [i * x][ring_size][w + 6].
How do I tell it to match anything inside (symbols and spaces included) [ ]?
My regular expression so fas is: regex arrayDims("\\[[0-9]+\\]");. I am using C++11 regex header.
Thank you
A:
If you want to match anything inside [], then try using \\[.+?\\], or something similar. The ? turns the * into non-greedy. Read more on this page.
Edit: I have to note that, while this works for slightly more complex expression than just numbers, if there are more [] inside the expression, this will not work.
E.g. applying my pattern to array[anotherarray[5]] results in [anotherarray[5], instead of [anotherarray[5]] (note the extra bracket at the end).
See this answer for more information on bracket matching.
| {
"pile_set_name": "StackExchange"
} |
Q:
Verify DNSSEC being used by Safari when visiting a web site
Is there some way to verify that DNSSEC was used by Safari when visiting a web site?
I'm most interested in Safari for Mac OS X. But if there is a way in iOS, that would be important as well.
A:
DNSSEC is an extension of the DNS infrastructure. Usually a browser is not involved in domain name resolution. So there is no way for Safari to detect DNSSEC directly.
There is an Safari DNSSEC extension though which allows you to check the existence and validity of DNS Security Extensions (DNSSEC) records and Transport Layer Security Association (TLSA) records related to domain names. You can download it for several browsers here: DNSSEC/TLSA Validator
Direct link of the Safari extension:
dnssec-tlsa-plugin-2.2.0
(this is a shell script which has to be executed in Terminal.app)
| {
"pile_set_name": "StackExchange"
} |
Q:
Torque/Maui Custer
I have a Torque/Maui cluster with NFS and i'm trying to do something similar with GCE. I am working with gent4 that I have to preinstall it in each node or create an image for al nodes.
I do not know how to do something similar with GCE. In aws I have found starcluster with it works perfectly.
Any Ideas?
A:
This is a opensource project which I have routinely used to spin clusters of different kind and supports different clouds.
http://gc3-uzh-ch.github.io/elasticluster/
| {
"pile_set_name": "StackExchange"
} |
Q:
Should an exception be thrown when the data from db is bad?
In this particular application, there is no separate data layer and the data access code is in the Entity itself. For example, consider a Customer entity, then in the Customer.cs file where the members and properties are defined, you have methods to load the Customer object as below
public bool TryLoad(int customerID, out Customer customer)
{
bool success = false
try
{
//code which calls the db and fills a SqlDataReader
ReadDataFromSqlDataReader(reader);
success = true;
}
catch(Exception ex)
{
LogError();
success = false;
}
return success;
}
Now, in the ReadDataFromSqlDataReader(reader), tryparse is used to load data from the reader into the object. e.g.
public void ReadDataFromSqlDataReader(reader)
{
int.TryParse(reader["CustomerID"].ToString(), out this.CustomerID);
PhoneNumber.TryParse(reader["PhoneNumber"].ToString(), out this.PhoneNumber);
... similar TryParse code for all the other fields..
}
Is using TryParse to read all the properties from the reader a good practise? A dev told me that its done this way as TryParse has a better performance than int.Parse. But wouldnt you want an exception to be throw when the value you are reading from the db does not conform to what your code expects? I mean in this case, if there is a wrong phone number in the db then perhaps the object shouldn't be initialized at all instead of loading an object with an empty phone number?
A:
Yes, following the fail-fast principle, you would want an exception to be thrown the moment a value comes back that cannot be converted into the expected type.
If one of these operations fails and you continue as if nothing happened, you are likely to get weird errors that are hard to catch and hard to pinpoint: objects being added to the database when they should have been updating an existing row, data mysteriously disappearing, dogs and cats living together... you get the idea.
On the other hand, if you throw an exception immediately, you know exactly where your problem is and you can catch it and fix it before it becomes worse.
TryParse will work faster than Parse in case of failure simply because it doesn't have to throw an exception (which can be expensive), but if you're assuming that things will succeed (which this code is doing by not using the result of the parse), you should get equivalent performance using Parse.
| {
"pile_set_name": "StackExchange"
} |
Q:
Spark DataFrame to Dict - dictionary update sequence element error
I'm trying to convert the DataFrame as Dict using collectAsMap() function in RDD.
Code:
dict = df.rdd.collectAsMap()
Error log:
ValueError: dictionary update sequence element #0 has length 8; 2 is required
Update:
The DF has 8 fields, does it mean the collectAsMap() can be used only DF with two fields?
A:
below is an explanation to do same thing in pyspark. I agree with Ram explanation.
collectAsMap is only applicable to pairedrdd so you need to convert your dataframe to pair rdd first and then can convert it into some dictionary using collectAsMap function.
For example, I have a below dataframe:
df = spark.sql("""select emp_id,emp_city from udb.temptable_1 order by emp_id""");
+------+--------+
|emp_id|emp_city|
+------+--------+
| 1|NOIDA |
| 2|GURGAON |
| 3|DWARKA |
| 4|SAKET |
| 5|USA |
| 6|UP |
| 7|NOIDA |
| 8|SAKET |
| 9|GURGAON |
+------+--------+
converting it into a key value pair rdd
newrdd = df.rdd.map(lambda x : (x[0],x))
>>> type(newrdd)
<class 'pyspark.rdd.PipelinedRDD'>
[(1, Row(emp_id=1, emp_city=u'NOIDA ')),
(2, Row(emp_id=2, emp_city=u'GURGAON ')),
(3, Row(emp_id=3, emp_city=u'DWARKA ')),
(4, Row(emp_id=4, emp_city=u'SAKET ')),
(5, Row(emp_id=5, emp_city=u'USA ')),
(6, Row(emp_id=6, emp_city=u'UP ')),
(7, Row(emp_id=7, emp_city=u'NOIDA ')),
(8, Row(emp_id=8, emp_city=u'SAKET ')),
(9, Row(emp_id=9, emp_city=u'GURGAON '))]
finally you can use collectAsMap to convert your key-value pair rdd into a dict
dict = newrdd.collectAsMap()
{1: Row(emp_id=1, emp_city=u'NOIDA '),
2: Row(emp_id=2, emp_city=u'GURGAON '),
3: Row(emp_id=3, emp_city=u'DWARKA '),
4: Row(emp_id=4, emp_city=u'SAKET '),
5: Row(emp_id=5, emp_city=u'USA '),
6: Row(emp_id=6, emp_city=u'UP '),
7: Row(emp_id=7, emp_city=u'NOIDA '),
8: Row(emp_id=8, emp_city=u'SAKET '),
9: Row(emp_id=9, emp_city=u'GURGAON ')}
>>> dict.keys()
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> dict.get(2)
Row(emp_id=2, emp_city=u'GURGAON ')
| {
"pile_set_name": "StackExchange"
} |
Q:
XmlSchema object from an XML file with inlined Xsd
In .Net, I'm trying to get a XmlSchema object from Xml file with an embedded Xsd and can not find out how to do it? anybody know?
For example if it just an Xml file I can Infer Schema using the XmlSchemaInference class or if its a Xsd I can use XmlSchema class, but can not find away with inlined Xsd.
example file is at http://pastebin.com/7yAjz4Z4 (for some reason wouldn't show on here)
Thank you
A:
This can be done by obtaining an XmlReader for the xs:schema element node and passing it to XmlSchema.Read.
using System;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
namespace EmbeddedXmlSchema
{
class Program
{
static void Main(string[] args)
{
XNamespace xs = "http://www.w3.org/2001/XMLSchema";
XDocument doc = XDocument.Load("XMLFile1.xml");
XmlSchema sch;
using (XmlReader reader = doc.Element("ReportParameters").Element(xs + "schema").CreateReader())
{
sch = XmlSchema.Read(reader, null);
}
}
}
}
(If you are using XmlDocument instead of XDocument, look into XmlNode.CreateNavigator().ReadSubtree().)
| {
"pile_set_name": "StackExchange"
} |
Q:
Carousel Seating Logic Puzzle
Puzzle from my good friend and fellow Sporcle user, AuroraIllumina!
Eight children are riding the carousel: four girls (Anna, Beth, Claire, Diana), and four boys (Eric, Frank, George, Henry). It is your job to determine which position each of them is sitting in.
Rules:
The two people with 6-letter names are opposite each other (four seats apart)
None of the people with 5-letter names are adjacent to one another
Each boy is adjacent to exactly one girl
Exactly two people are in seats with the same number of letters in their name, both are boys
Frank is not adjacent to George
Beth and Claire are both the same distance from Anna (based on the number of seats)
If the carousel rotated 180 degrees, then three girls would end up in positions with the same number of letters as their names
A:
Solution:
1 Diana
2 Claire
3 Frank
4 Eric
5 Anna
6 George
7 Henry
8 Beth
Why?
If the carousel rotated 180 degrees, then three girls would end up in positions with the same number of letters as their names.
> Claire has to be opposite of 6 > Claire=2
> Diana has to be opposite of 5 > Diana=1
> another girl has to be opposite of 4 > Anna/Beth=8
The two people with 6-letter names are opposite each other (four seats apart)
> since Claire is on 2, George has to be on 6
Each boy is adjacent to exactly one girl
> a girl has to be on 5 > Anna/Beth=5
Exactly two people are in seats with the same number of letters in their name, both are boys
> Eric has to be on 4
Frank is not adjacent to George
> only 3 is left for Frank
> only 7 is left for Henry
Beth and Claire are both the same distance from Anna (based on the number of seats)
> Beth=8
> Anna=5
A:
2 and 1
Claire Diana
3 and 8
Frank Beth
4 and 7
Eric Henry
5 and 6
Anna George
with the picture
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove brackets with javascript
I have a function to get the GPS coordinates once map is clicked, however the result is in brackets ()
I need to remove the brackets
function onClickCallback(event){
var str = event.latLng
var Gpps = str //.replace("(","");
document.getElementById('latlng').value = Gpps; // resuts provided (in brackets)
bellow not giving the gps in any format :(
function onClickCallback(event){
var str = event.latLng
var Gpps = str.replace("(","");
document.getElementById('latlng').value = Gpps; / NO result
A:
Your callback event.latLng may be an object instead of a string.
Either of these may get you going:
var str = event.latLng.toString().replace(/^\((.+)\)$/,"$1")
or
var str = event.latLng.toString().slice(1,-1)
| {
"pile_set_name": "StackExchange"
} |
Q:
Accessing value returned by method in another thread
How can I access a value that has been returned by a method that is running in another thread?
Lets say:
public string[,] method1
{
string a = "blah";
return a;
}
private void btn_Click(object sender, EventArgs e)
{
Thread thread = new Thread(method1);
thread.Start();
// here I want to use a ...
Label1.Text = a;
}
Can anyone tell me please?
A:
why not,
public Task<string> Method1()
{
return Task.Run(() => "blah");
}
private async void btn_Click(object sender, EventArgs e)
{
Label1.Text = await Method1();
}
or, if the function takes parameters,
public Task<string> Method1(string someString, int someInt)
{
return Task.Run(() => string.Format("{0}{1}", someString, someInt));
}
private async void btn_Click(object sender, EventArgs e)
{
Label1.Text = await Method1("EZ", 1);
}
or even,
private Task<string[][]> ArrayMaker(uint x, uint y)
{
return Task.Run(() =>
{
var result = new string[x][]
for (var i = 0; i < x; i++)
{
result[i] = new string[y];
for (var j = 0; j < y; j++)
{
result[i][j] = ((long)i * j).ToString(
CultureInfo.InvariantCulture);
}
}
return result;
});
}
private async void btn_Click(object sender, EventArgs e)
{
var bigArray = await ArrayMaker(1000000, 1000000);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
check whether a class is disjoint or not with the given class using owl API
I want to check class disjoint axioms using owl API.here my problem.suppose I have two classes ChickenTopping and HamTopping.ChickenTopping class has a subclass of axiom hasSpiciness some Hot and HamTopping class has a subclass of axiom hasSpiciness some Mild. these Hot and Mild classes are disjointed ones. due to that subclass of axioms, ChickenTopping and HamTopping classes are disjointed. so how can check whether the given HamTopping class is disjoint with Chicken class or not?
A:
Galigator already mentioned a few reasoners you could use.
To check if a class is disjoint with another known class, once you create an OWLReasoner, you can use the following code:
OWLClass a = ...
OWLClass b = ...
OWLReasoner reasoner = ...
OWLDataFactory df = ...
OWLAxiom axiom = df.getOWLDisjointClassesAxiom(Arrays.asList(a, b));
boolean classesAreDisjoint = reasoner.isEntailed(axiom);
| {
"pile_set_name": "StackExchange"
} |
Q:
Jmeter - Increment value before each sampler request
I have test plan in jmeter with few SOAP samplers where I append to request body counter value and I'm looking for way how to increment counter before each sampler request.
With setup below jmeter is peforming requests in this order:
First Request - with counter 1
Second Request - with counter 1
First Request - with counter 2
Second Request - with counter 2
I would like to achive this behaviour:
First Request - with counter 1
Second Request - with counter 2
Third Request - with counter 3
...
N Request - with counter n
Number of users:
Number of threads: 1
Ramp-Up Period: 1
Loop Count: 2
Counter
Starting value: 1
Increment: 1
Maximum value: 2
How can I do it ? I'm guessing I should introduce Loop Controller somehow ?
A:
You can do it this way:
In Test Plan, define variable "counter" set to 0
Then add a User Parameters which is a PreProcessor (so executed BEFORE SAMPLER) component using __intSum function
It will be executed each time thanks to scoping rules.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to connect mysql database to desktop java application using jdbc?
how to connect mysql database to desktop java application using jdbc ?
the environment is ubuntu 12.04 Lts i tried so many ways but all of them throw an exception on executing
Class.forName("com.mysql.jdbc.Driver");
the exception say :
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
the full code is :
import java.sql.*;
public class CRUDForGoods {
private Connection connection ;
public Vector<GoodsStore> goods ;
public CRUDForGoods(){
try{
DriverManager.registerDriver(new JdbcOdbcDriver());
connection = DriverManager.getConnection("jdbc:odbc:dbName","root", "root");
}
catch(Exception ex) {
System.out.println("##connection");
ex.printStackTrace();
}
}
A:
com.mysql.jdbc.Driver not found while executing the code.
You need mysql connector to get it run (the jar includes com.mysql.jdbc.Driver). You can find it here
Download and include the jar file in your classpath.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I make non-breaking spaces visible? Maybe through CSS, (without replacing the non-breaking space character with another character)
How can I make non-breaking spaces visible, maybe through CSS? For editing purposes of text.
Word as example, has a button where you can click and see the non-breaking spaces as examples, they show up as some circle unicode. Not sure if it replaces the font or something.
I'm not sure if it's possible to change the color, I guess it is, but there's nothing to colorize it.
A:
If you are able to wrap them into some span tags, you can use the CSS after directive like so:
<p>hello<span class="space"> </span>world</p>
.space::after {
content: " ";
position: absolute;
transform: translate(-3px, 9px);
width: 3px;
height: 3px;
border-radius: 50%;
background-color: red;
}
Take a look at this Codepen.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to count the number of columns with blank or 0 values
I am new to mysql . Please help me to solve the below requirement.
Table example :-
--------+-----------+-----------+--------+---------+
Id. | fname | lname | qid1 | qid2 |
--------+-----------+-----------+--------+---------+
1 | atul. | | 0 | 0 |
--------+-----------+-----------+--------+---------+-
I want the answer as "3" of 1st id because 'lname' is blank and 'qid1', 'qid2' are 0.
A:
You can use case in most databases; however, MySQL provides a shortcut where you can just add the boolean expressions:
select t.*,
((fname is null or fname = '') +
(lname is null or lname = '') +
(qid1 is null or qid1 = '') +
(qid2 is null or qid2 = '')
) as numBlankOrNull
from t;
| {
"pile_set_name": "StackExchange"
} |
Q:
how is mysql 200 connections limit applied?
I am building an ecommerce site hosted on godaddy shared hosting and I saw that only 200 database connections are allowed.
I am using Codeigniter framework for the site and I have 2 databases for the project.
Database 1 for storing sessions only with a user with read, write, update and delete privileges
Database 2 rest of tables needed for site, with a read only user.
Since 1 website visitor will be connecting to 2 databases does this mean that I can only have 100 visitoras at a time? Since each one will be using 2 connections.
Or can someone explain the 200 connections limit please.
A:
As @Drew said, it depends. Limits exist everywhere (hardware, software, bandwidth etc). GoDaddy has it's own limitations (not only to database connections). Optimizing your code can help you take the maximum of the web-server and database servers.
For example if your code uses the database connection for 1 second to each database, you can serve 100 visitors per second. If you use it for 0.2 of a sec then you can serve 500 visitors every second.
Optimization is necessary especially on heavy web applications. Maybe you could organize your app so it does not need connecting to both databases for every request (this would double the available connectios per time fraction). Optimizing the SQL queries and minimizing JOINing tables will help your app too (also it will make it run faster).
Finally you can use caching, so you will not have your server constructing the same content again and again. This is not a full list of all optimizations you can do, but a start point to do your research and planning. Hope you find it helpful.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sublists in a 2D List, Referencing
I have a 2D List of objects. I'm trying to access a list and replace it with a sublist of itself. I made up a simple example below, I want to replace dList.get(0) with dList.get(0).subList(1,3). I use a reference variable, which updates the values in the original list, but the subList is not getting updated. I`m a bit new to this, any help in the form of examples, explanations and directing me documentation is appreciated.
List<List<Double>> dList = new ArrayList<List<Double>>();
/**
* Initialize, the 2D List with some values
*/
protected void init() {
List<Double> d = new ArrayList<Double>();
d.add(1.0);
d.add(2.0);
d.add(3.0);
d.add(4.0);
d.add(5.0);
dList.add(d);
}
/**
* Check if the subList update works.
*/
protected void check() {
List<Double> tmp = dList.get(0); //get the reference into a temporary variable
tmp = tmp.subList(1, 3); //get the sublist, in the end the original list dList.get(0) should be this.
tmp.set(0, 4.5); //reference works, the dList.get(0) values get updated
for (int i = 0; i < tmp.size(); i++) {
System.out.println(tmp.get(i));
}
System.out.println("....Original 2D List Values....");
for (int i = 0; i < dList.get(0).size(); i++) {
System.out.println(dList.get(0).get(i)); // still has all the elements, and not the sublist
}
System.out.println("Result" + dList.get(0).size());
}
A:
tmp.subList() returns a new List instance that is different from the first element of dList. That's why the original List was unchanged.
You need to set the first element of dList to refer to the sub-list you created :
List<Double> tmp = dList.get(0);
tmp = tmp.subList(1, 3);
tmp.set(0, 4.5);
dList.set (0, tmp);
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom Key Events
How can I send a custom SWT key event such that it results in the typing of that exact literal character without any conversion?
We are making a custom on-screen graphical keyboard that allows for multiple possible layouts - QWERTY being the main one, but several others planned, including ones that visually simulate the iPhone keyboard layout or others that are non-standard relative to the PC.
I would like to be able to send any arbitrary character of my choosing as an event, such that it will result in the typing of that exact character. However, whenever I send an event with a given character, SWT seems to automatically interpret and convert it based on the system's keyboard settings and status, changing it to be capitalized/lowercase or using the shifted symbols depending on whether or not the shift key (the real one on the actual keyboard, for instance) is pressed. For instance, passing the character 'T' through a key event will result in either 't' or 'T' depending on the shift key. It performs similarly with the '4' character, doing either '4' or '$' based on shift.
This is problematic, as I wish to perform the shifting of characters manually, and indeed may not wish to use the same shift characters as the standard QWERTY keyboard in any given case (perhaps, for instance, I want '$' to be the shifted (or 'function' key) version of 'R' on a smaller, cellphone-like keyboard). How can I use these events such that it does not assume the usage of QWERTY keys?
The documentation for the 'character' field in the SWT events says the following:
the character represented by the key that was typed. This is the final
character that results after all modifiers have been applied. For
example, when the user types Ctrl+A, the character value is 0x01. It
is important that applications do not attempt to modify the character
value based on a stateMask (such as SWT.CTRL) or the resulting
character will not be correct.
This makes me believe that it should not be converting my character as it is doing, as I am commanding it to use my "final" result.
I have created a simple, stand-alone example to demonstrate my issue (please note that this is not how I am doing the actual Keyboard, and is only meant to highlight the key event issue):
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Button;
public class KeyboardIssueExample extends Shell {
private Text txtTextArea;
private Composite cmpButtons;
private Button btnBigA;
private Button btnBigS;
private Button btnLittleD;
private Button btnSix;
private Button btnSeven;
private Button btnDollah;
private Button btnStar;
private SelectionListener mainListener = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent selE) {
Button b = (Button)selE.widget;
char c = b.getText().charAt(0);
sendKey(c);
}
};
/**
* Launch the application.
* @param args
*/
public static void main(String args[]) {
try {
Display display = Display.getDefault();
KeyboardIssueExample shell = new KeyboardIssueExample(display);
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the shell.
* @param display
*/
public KeyboardIssueExample(Display display) {
super(display, SWT.SHELL_TRIM);
createContents();
}
/**
* Create contents of the shell.
*/
protected void createContents() {
setText("SWT Application");
setSize(450, 300);
setLayout(new GridLayout());
txtTextArea = new Text(this, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);
txtTextArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
cmpButtons = new Composite(this, SWT.NONE);
cmpButtons.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
GridLayout gl_cmpButtons = new GridLayout(7, false);
gl_cmpButtons.marginWidth = 0;
gl_cmpButtons.marginHeight = 0;
cmpButtons.setLayout(gl_cmpButtons);
btnBigA = new Button(cmpButtons, SWT.NONE);
btnBigA.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
btnBigA.setText("A");
btnBigS = new Button(cmpButtons, SWT.NONE);
btnBigS.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
btnBigS.setText("S");
btnLittleD = new Button(cmpButtons, SWT.NONE);
btnLittleD.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
btnLittleD.setText("d");
btnSix = new Button(cmpButtons, SWT.NONE);
btnSix.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
btnSix.setText("6");
btnSeven = new Button(cmpButtons, SWT.NONE);
btnSeven.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
btnSeven.setText("7");
btnDollah = new Button(cmpButtons, SWT.NONE);
btnDollah.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
btnDollah.setText("$");
btnStar = new Button(cmpButtons, SWT.NONE);
btnStar.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
btnStar.setText("*");
init();
}
private void init() {
btnBigA.addSelectionListener(mainListener);
btnBigS.addSelectionListener(mainListener);
btnLittleD.addSelectionListener(mainListener);
btnSix.addSelectionListener(mainListener);
btnSeven.addSelectionListener(mainListener);
btnDollah.addSelectionListener(mainListener);
btnStar.addSelectionListener(mainListener);
}
@Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
private void sendKey(char c) {
sendKeyEvent(c, SWT.KeyDown);
sendKeyEvent(c, SWT.KeyUp);
}
private void sendKeyEvent(char c, int eventType) {
txtTextArea.forceFocus();
Event event = new Event();
event.type = eventType;
event.character = c;
getDisplay().post(event);
}
}
As you will find, the key events do not respect my own custom usage of capitalization, and instead uses its own. How troublesome.
A:
Looking at the source of Display.post for the Mac and for Windows there is a lot of code specific to the key up/down events. This includes calls to OS specific APIs to convert the character and key code you specify to the parameters required by the OS specific method used to generate the key stroke event.
For Windows this code calls VkKeyScan which according to the Microsoft documentation does look at the current keyboard state.
Display does have a postEvent(Event) method which adds to the event queue without changing anything, but this is not public so you would have to access it using reflection. Since it is not part of the official API it may change.
Edit:
There is actually an Eclipse bug report here for this. It has been open for 10 years so probably isn't going to be fixed!
Update:
There is also a Widget.notifyListeners(eventType, Event) method which could be used to send the key events to a specific control. You will have to create the Event and set the required fields.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I remove a Workflow from a List?
I'm trying to remove a workflow that's been associated to a document library. Normally I would go to the library settings and then to workflow settings and remove the workflow, but on my O365 site I do not get that option because it tells be in the browser that no workflows are associated, however, SPD tells me that 3 workflows are associated to that list. Am I doing something wrong?
A:
Answer is here:
https://technet.microsoft.com/en-us/library/cc262779(v=office.14).aspx
In case the link dies here is the text:
To remove a workflow association from a list or document library
Verify that you have the following administrative credentials:
You must be a member of the Site Owners group on the SharePoint site that you are configuring.
Browse to the list or library from which you want to remove a workflow.
Do one of the following:
For a list, on the List Tools tab, click List.
In the Settings group, click List Settings.
For a library, on the Library Tools tab, click Library.
In the Settings group, click Library Settings.
On the List Settings or Library Settings page, in the Permissions and Management section, click Workflow Settings.
On the Workflow Settings page, click Remove a workflow.
Note - The Remove a workflow link is not displayed if no workflows are associated with the list or library.
On the Remove Workflows page, find the workflow that you want to remove and choose from the following options:
Select No New Instances to prevent new instances of this workflow from running but still allow for running instances to finish.
After all running workflows are finished, you can return to this page to completely remove the workflow association.
Select Remove to prevent new instances of this workflow from running and remove all instances of this workflow. This option removes
instances that are already running.
Click OK.
| {
"pile_set_name": "StackExchange"
} |
Q:
What do I need to do to finish this outside-door install properly?
A new steel door was installed to our unfinished garage but I am not satisfied with how it currently looks. The previous door had trim covering the gap between the siding and the door, as well as the bottom between the riser and the concrete pad.
Is this what is typically done? or is there a better approach to take to this?
A:
You can use a PVC trim molding glued to the metal frame and fitted against the siding J-Channel. On the bottom, again, pick out a PVC trim piece. A quarter round or stop trim would work. That can be nailed and glued. Use small galvanized or stainless steel nails.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to store an array in Django model?
I was wondering if it's possible to store an array in a Django model?
I'm asking this because I need to store an array of int (e.g [1,2,3]) in a field and then be able to search a specific array and get a match with it or by it's possible combinations.
I was thinking to store that arrays as strings in CharFields and then, when I need to search something, concatenate the values(obtained by filtering other model) with '[', ']' and ',' and then use a object filter with that generated string. The problem is that I will have to generate each possible combination and then filter them one by one until I get a match, and I believe that this might be inefficient.
So, I hope you can give me other ideas that I could try.
I'm not asking for code, necessarily, any ideas on how to achieve this will be good.
A:
I'd have two advices for you:
1) Use ArrayField if you are using PostgreSQL as your database. You can read more about ArrayField here.
2) Encode your array as JSON and store it either as a plain string or using a JSONField as found here.
I'd personally prefer option number 1 since that is the cleaner and nicer way but depending on what you are actually using to store your data that might not be available to you.
A:
Yes, you can use it like this:
from django.contrib.postgres.fields import ArrayField
class Board(models.Model):
pieces = ArrayField(ArrayField(models.IntegerField()))
However, it can only be available when using PostgreSQL for the database.
A:
If you aren't using Postgres, I recommend Django's validate_comma_separated_integer_list validator.
https://docs.djangoproject.com/en/dev/ref/validators/#django.core.validators.validate_comma_separated_integer_list
You use is as a validator on a CharField().
| {
"pile_set_name": "StackExchange"
} |
Q:
(C++) How to declare an object class member based on a conditional
I'm working on an object-oriented tic tac toe game and I'm having a problem. One of my classes acts as the main controller of the game and controls all other objects. Below is a stripped back version of the class.
The end user can choose between one and two players. So, it is unnecessary for me to create both a second player AND an ai player. The game only needs one or the other. As you can see below, I tried to use an if statement to solve the problem, but the objects do not have scope.
How can can I initialize one object or the other based on the number of players passed to the Game constructor?
Thanks!
Game.h
#include "Player.h"
#include "AIPlayer.h"
class Game
{
private:
Player human;
// I would like to put these here so they have scope
// but it is unecessary to declare them both
// If the user chooses one player then human2 is unecessary
// if the user choosed two player then ai is unecessary
AIPlayer ai;
Player human2;
public:
Game(int players)
{
if (players == 1)
{
AIPlayer ai; // this does not have scope
}
else
{
Player human2; // this does not have scope
}
}
};
A:
My suggestion would be to derive both AIPlayer and Player (or perhaps better, HumanPlayer) from a common base class (e.g., Player), and have a pointer to that base class in Game. The constructor then instantiates either AIPlayer or HumanPlayer and assigns it to the pointer.
Any methods that differ between AIPlayer and HumanPlayer should be declared in the base class Player as virtual methods, and then be implemented in the derived classes.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I add a LinearLayout inside a RelativeLayout, programmatically?
I've a RelativeLayout which consists of an ImageView and TextView. Now, to this RelativeLayout I want to add a LinearLayout, which should be aligned below the TextView. Right now, the LinearLayout is added to the RelativeLayout, but it is not aligned below the TextView. Here is my code :
void addRatingToImage(RelativeLayout relativelLayout, Movies movieObject) {
ImageView ratingImageView;
LinearLayout ratingLayout = new LinearLayout(mContext);
ratingLayout.setOrientation(LinearLayout.HORIZONTAL);
double roundedRating = roundUpRating(Double.parseDouble(movieObject.mRating));
for(int i = 0; i < 5; i++) { //TODO: Check
ratingImageView = new ImageView(mContext);
if(i < roundedRating) {
ratingImageView.setBackgroundResource(R.drawable.star_2);
ratingLayout.addView(ratingImageView);
}
else {
ratingImageView.setBackgroundResource(R.drawable.star_1);
ratingLayout.addView(ratingImageView);
}
}
RelativeLayout.LayoutParams ratingLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
TextView movieNameTextView = (TextView)relativelLayout.getChildAt(2);
ratingLayoutParams.addRule(RelativeLayout.BELOW, movieNameTextView.getId());
ratingLayout.setLayoutParams(ratingLayoutParams);
relativelLayout.addView(ratingLayout);
}
I have one doubt here. Does RelativeLayout.BELOW work, when it is applied to a different kind of layout, nested in a RelativeLayout? Thanks.
A:
Yes, RelativeLayout.BELOW will work. It is recognized by parent RelativeLayout no matter what the child view class is.
According to your problem, I suppose that RelativeLayout is behaving that way because you've set fill_parent for your TextView movieNameTextView's layout width.
| {
"pile_set_name": "StackExchange"
} |
Q:
Automated build Hudson/SVN
There is an Hudson version 2.2.1 set up and running build upon a subversion. I now want to automate the build process where if a user commits to the svn a build automatically takes place and send an email id if the build fails. But it requires editing post commit hooks. Is there any other way of achieving the same without using svn hooks?
-sam
A:
Without post commit hooks, the only way that hudson can be notified of a change is through polling the svn server.
The Subversion plugin supports setting up a polling schedule (cron format- ex: every minute).
| {
"pile_set_name": "StackExchange"
} |
Q:
Question about number of solutions in $\mathbb{F_{p}}$
Let $N(x^{n}=a)$ denote the number of solution to $x^{n}=a$ in $\mathbb{F_{p}}$
Lemma: $N(x^{n}=a)=\sum_{\chi^{n}=\epsilon}\chi{(a)}$ where the sum is taken over all characters. In particular, $N(x^{2}=a)=1+(^{a}_{p})$, where $(^{a}_{p})$ is the Legendre symbol.
Question1: Why is it that $N(x^{n}+y^{n}=1)=\sum_{a+b=1}N(x^{n}=a)N(y^{n}=b)$?
Question2: By direct substitution, we should get that $N(x^{2}+y^{2}=1)=p+\sum_{a}(^{a}_{p})+\sum_{b}(^{b}_{p})+\sum_{a+b=1}(^{a}_{p})(^{b}_{p})$, but I am not able to get this because I don't know how to deal with the summation in two variables.
A:
Summation in two variables can be simplified when one of the variables is determined by the other one. Here we have $a+b=1$, so we can simply replace $b$ with $1-a$ in the inner expression and sum over all $a\in\mathbb{F}$. However doing this is not always necessary to derive formulas or solutions.
Now for question 1, note that any solution $(x,y)$ to $x^n+y^n=1$ will correspond to $u$ and $v$ such that their sum $u+v=1$; simply take $u=x^n$ and $v=y^n$. So we can take the set of all solutions and partition them into cells, each cell is labelled by $(u,v)$ such that $u+v=1$ and inside each cell are all the $x$ and $y\in\mathbb{F}$ such that $x^n=u$ and $y^n=v$. Since these $x$ and $y$ are independent of each other when $u$ and $v$ are fixed, we conclude tha the number of solutions inside the cell labelled $(u,v)$ is just the product of $N(x^n=u)$ and $N(y^n=v)$. Summing over the available indices gives
$$N(x^n+y^n=1)=\sum_{u+v=1}N(x^n=u)N(y^n=v).$$
For question 2, we use direct substitution:
$$N(x^2+y^2=1)=\sum_{u+v=1}N(x^2=u)N(y^2=v)=\sum_{u+v=1}\left(1+\left(u\over p\right)\right)\left(1+\left(v \over p\right)\right)$$
Multiply out the summand on the RHS and split into multiple summations. Note that if you are summing over $u+v=1$ but the summand only depends on $u$ (respectively, $v$), then we need only note that for any $u$ (resp. $v$) there is exactly one $v$ (resp. $u$) to make $(u,v)$ a solution to $u+v=1$, so we are effectively just summing over all $u\in\mathbb{F}$ in that case!
n.b. I replaced $a$ and $b$ with $u$ and $v$ here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mongo replica node with docker
I have setup a Mongo Primary node with docker using docker image https://hub.docker.com/_/mongo/.
Now I wish to add replica node in my current setup using docker only.
Can anybody help me with this?
A:
You could check a guide like "Deploy a MongoDB Cluster in 9 steps Using Docker", but that involve multiple working docker servers.
It uses a key file key file to be used on all nodes (openssl rand -base64 741 > mongodb-keyfile) for internal authentication.
That allows to create an admin user, which then adds the replica servers:
docker run \
--name mongo \
-v /home/core/mongo-files/data:/data/db \
-v /home/core/mongo-files:/opt/keyfile \
--hostname="node1.example.com" \
--add-host node1.example.com:${node1} \
--add-host node2.example.com:${node2} \
--add-host node3.example.com:${node3} \
-p 27017:27017 -d mongo:2.6.5 \
--smallfiles \
--keyFile /opt/keyfile/mongodb-keyfile \
--replSet "rs0"
On each replica, you initiate and then check the config:
rs.initiate()
rs.conf()
Back to node 1, you declare the replica:
rs0:PRIMARY> rs.add("node2.example.com")
rs0:PRIMARY> rs.add("node3.example.com")
| {
"pile_set_name": "StackExchange"
} |
Q:
pass string to facet_grid : ggplot2
In ggplot2 you can pass character arguments inside a user defined function using aes_string. How can you do the same for facet grid which takes a formula, not aes?
FUN <- function(data, x, y, fac1, fac2) {
ggplot(data = data, aes_string(x=x, y=y)) +
geom_point() + facet_grid(as.formula(substitute(fac1 ~ fac2)))
}
FUN(mtcars, 'hp', 'mpg', 'cyl', 'am')
A:
reformulate() seems to work just fine.
FUN <- function(data, x, y, fac1, fac2) {
ggplot(data = data, aes_string(x=x, y=y)) +
geom_point() + facet_grid(reformulate(fac2,fac1))
}
FUN(mtcars, 'hp', 'mpg', 'cyl', 'am')
A:
With rlang magic and new ggplot2 v3.0.0 features you can do :
FUN <- function(data, x, y, fac1, fac2) {
ggplot(data = data, aes(x = !!ensym(x), y = !!ensym(y))) +
geom_point() +
facet_grid(eval(expr(!!ensym(fac1) ~ !!ensym(fac2))))
}
FUN(mtcars, 'hp', 'mpg', 'cyl', 'am')
Note that we don't use aes_string, which is soft deprecated.
Personally in these cases I like to use a function I called glue_formula (referencing package glue) :
glue_formula <- function(.formula, .envir = parent.frame(), ...){
formula_chr <- gsub("\\n\\s*","",as.character(.formula)[c(2,1,3)])
args <- c(as.list(formula_chr), .sep=" ", .envir = .envir)
as.formula(do.call(glue::glue, args),env = .envir)
}
FUN2 <- function(data, x, y, fac1, fac2) {
ggplot(data = data, aes(x = !!ensym(x), y = !!ensym(y))) +
geom_point() + facet_grid(glue_formula({fac1} ~ {fac2}))
}
FUN2(mtcars, 'hp', 'mpg', 'cyl', 'am')
It's not tidyverse approved (see interesting discussion here) but it has served me well.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to insert "event dummy" (?) based on time interval in different dataframe
I have a dataframe which provides the start and end date of an event for different countries. Events can occur for several times for each country (e.g. country A).
Start.Year <- c("1990","1992","1997","1995")
End.Year <- c("1995","1993","2000","1996")
Country <- c("A","B","A","C")
a <- data.frame(Start.Year,End.Year,Country)
a$Start.Year <- as.numeric(as.character(a$Start.Year))
a$End.Year <- as.numeric(as.character(a$End.Year))
Start.Year End.Year Country
1990 1995 A
1992 1993 B
1997 2000 A
1995 1996 C
I have a second data frame which is in a time-series cross section format (Year/Country/Event(Yes/No).
b1 <-as.data.frame(expand.grid(year=(1990:2000), Country=unique(a$Country)))
b1$Event <-0
b1$year <- as.numeric(as.character(b1$year))
How can I obtain the result below (apologies for the clumsy presentation). Event should be "1" when the year is between the start and end year of the first dataframe; for each country; the second dataframe exists already, meaning that I don't want to convert the first dataframe, but rather match (?) the information from the first dataframe to the second one.
I tried
b1$Event[a$Start.Year<=b1$year & a$End.Year>=b1$year] <- 1
but get "longer object length is not a multiple of shorter object length" as error message. Grateful for any hint/advice!
Result aimed at:
Year Country Event
1990 A 1
1991 A 1
1992 A 1
1993 A 1
1994 A 1
1995 A 1
1996 A 0
1997 A 1
1998 A 1
1999 A 1
2000 A 1
1990 B 0
1991 B 0
1992 B 1
1993 B 1
1994 B 0
1995 B 0
1996 B 0
1997 B 0
1998 B 0
1999 B 0
2000 B 0
1990 C 0
1991 C 0
1992 C 0
1993 C 0
1994 C 0
1995 C 1
1996 C 1
1997 C 0
1998 C 0
1999 C 0
2000 C 0
A:
Here is a solution using the rolling join feature in data.table. I have slightly changed (fixed?) your definition of a and removed the Event column in b1.
require(data.table)
Start.Year <- c(1990, 1992, 1997, 1995)
End.Year <- c(1995, 1993, 2000, 1996)
Country <- c("A", "B", "A", "C")
a <- data.frame(Start.Year, End.Year, Country)
a <- data.table(a) ## convert to use feature
b1 <-as.data.frame(expand.grid(year=(1990:2000), Country=unique(a$Country)))
b1 <- data.table(b1) ## convert
## join by Start.Year, setting matching keys for each dataset
setkey(a, Country, Start.Year)
setkey(b1, Country, year)
# the tricky part
# roll=TRUE means all years will match to
# next smallest event Start.Year
ab <- a[b1, roll=TRUE]
setnames(ab, c('Country', 'Year', 'Event')) ## fix names
ab[Year > Event, Event:=NA] ## stop index at end year
ab[!is.na(Event), Event:=1] ## transform year markers to 1
ab[is.na(Event), Event:=0] ## transform missing matches to 0
ab is the data in the format you want. You can use it just like a data.frame or convert it back if you don't want to keep it in that class. The join should be very fast.
| {
"pile_set_name": "StackExchange"
} |
Q:
Blue Selector - iPhone
How can you turn the blue selector to go off when I move back into the view? At the moment, when I select it, I get pushed to another view. However, when I go back into the original view, it is still selected.
How can I turn it off when I go back onto the original view?
Thanks.
A:
In your tableView:didSelectRowAtIndexPath: method you should include the following:
[tableView deselectRowAtIndexPath:indexPath animated:YES];
A:
You can also try this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"myCellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
// Set up the cell...
cell.textLabel.text = @"foo";
return cell;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Erro: object of type 'float' has no len
Eu estava debugando operações simples no interpretador do Python, e o comando a seguir me tornou esta curiosidade:
>>> b = 3.12; len(b)
Com o seguinte erro:
Traceback (most recent call last):
File "", line 1, in
TypeError: object of type 'float' has no len()
No meu entendimento o interpretador Python está acusando que o objeto do tipo float não tem tamanho. Não sei, eu estava esperando que a saída fosse 3 ou 4 que seria a quantidade de dígitos que ele demonstra, contando o ponto ou não.
A:
Ele até tem um tamanho na memória, mas a função len() não é para analisar o tamanho ocupado na memória. E nem é a intenção, afinal sua expectativa é que ele mostrasse a quantidade de dígitos que é mostrado no número. São coisas completamente diferentes. A forma como o dado está na memória e como ele é mostrado na tela - ou é armazenado em algum lugar para um humano ver - são coisas bem diferentes.
Você está vendo uma representação do dado em forma de caracteres gráficos que por acaso são dígitos numéricos. Mas o importante aí é que são caracteres. O que você está vendo é uma sequência (cadeia) de caracteres, ou seja, está vendo uma string. Então para saber o tamanho dessa string, você tem que dizer que quer isto. Tem que transformar o número no tipo string e aí dá para usar a função len() para saber quantos caracteres ela tem.
A função len() está disponível para alguns tipos de dados, não para todos. O dado numérico em si tem um tamanho na memória que é um detalhe de implementação. A gente sabe que é 4 bytes, mas isto não importa na maior parte do tempo. Len é a contração de length, ou seja, comprimento. Então ela não fornece exatamente o tamanho de nada, mas sim o comprimento. Há uma diferença sutil aí. O comprimento pode ser obtido em todo tipo que seja uma sequência de alguma coisa. Que é o caso de uma string.
A forma mais simples de converter float para string é com a função str():
b = 3.12; len(str(b))
Outra forma é com o repr():
b = 3.12; len(repr(b))
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
A:
Ao contrário de C, o tamanho que objetos Python ocupam na memória é abstraído, e a principio um programa Python não precisa saber do mesmo.
Claro que é bom ter uma noção - e eventualemente você pode otimizar alguma coisa, por exemplo, usando namedtuples em vez de dicionários, etc.... A função len é praticamente um operador em Python: ela devolve a quantidade de itens de uma sequência - e isso não tem nada a ver com o tamanho do objeto sequência na memória, nem com os objetos dentro da sequência.
Um número inteiro, ou float, ou outro tipo não é uma sequência. Uma string de texto é uma sequência, mas o valor retornado por len para a mesma pode não ter relação alguma com o seu tamanho na memória: se for um objeto de texto unicode, cada caractér pode ocupar 4 bytes. Se for um texto codificado em utf-8, os caractéres tem comprimento variável em bytes, e assim por diante.
Dito isso, Python tem uma função auxiliar para dizer o tamanho em bytes de um objeto na memória - no módulo sys, a função getsizeof.
Então você conseguira o que estava tentando fazendo:
>>> import sys
>>> b = 3.12
>>> sys.getsizeof(b)
24
E a resposta é essa: 24 - um objeto Python do tipo "float" ocupa 24 bytes na memória. O dado em si, o número, no caso específico do float em Python é um float IEEE 754 de 64bits - que usa 8 bytes - os demais 16 bytes do objeto float são metadados usados pelo Python para controlar o ciclo de vida do objeto, dentre outras coisas.
Como eu disse antes, essa informação não é muito útil. Ou o seu programa vai ter algumas poucas variáveis de ponto flutuante - menos que 10 ou 20, e fazer alguma conta com elas, e nesse caso esse tamanho em bytes numa máquina com várias centenas de megabytes de memória, como é tipicamente a memória de máquinas que rodam Python, é irrelevante, ou, se você estiver trabalhando com computação científica, em que o tamanho em memória de um número pode fazer diferença, você vai estar usando objetos especializados para armazenar
seus números (mesmo por que é essencial que as operações matemáticas e lógicas em cima de dados em massa seja feita em código nativo). Normalmente se usam as arrays da biblioteca numpy em código desse tipo - mas você também pode usar as arrays nativas da stdlib do Python. Qualquer uma das duas permite que você especifique o tipo exato de dado de cada elemento, e aí você pode escolher usar floats de 32 ou 64bits (4 ou 8 bytes por número). No caso do numpy há inclusive suporte a floats de 128bit (16 bytes, mas isso pode ficar lento, uma vez que não há suporte em hardware nas CPUs atuais para esse tipo de dado).
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic Column Name in SQL in Update statement
DECLARE @sql NVARCHAR(max)
DECLARE @ParmDefinition NVARCHAR(500)
SET @sql = 'UPDATE [Table1] SET [Table1].[@columnName] = TEST';
SET @ParmDefinition = N'@columnName NVARCHAR(50)';
EXEC sp_executesql @sql, @ParmDefinition, @columnName = N'MyColumn';
When I run the above query, I get Invalid column name '@columnName'.. Clearly, the column name is not being replaced when the query is run.
In reality, my @sql variable is much larger and I have many columns I wish to update, thus I would like to avoid doing SET SQL = for all enumerations of the column name.
I'd like to declare the sql string once, and invoke the query with different values. e.g.:
EXEC sp_executesql @sql, @ParmDefinition, @columnName = N'MyColumn';
EXEC sp_executesql @sql, @ParmDefinition, @columnName = N'AnotherColumn';
EXEC sp_executesql @sql, @ParmDefinition, @columnName = N'YetAnotherColumn';
-- And so on
Is something like this possible?
A:
Yes, you have to concatenate the variable outside the string. In other words:
SET @sql = 'UPDATE [Table1] SET [Table1].[' + @columnName + '] = t1.Value ' +
EDIT: Another solution we have used is to replace tokens in the base sql to construct a new sql variable for execution.
DECLARE @sql nvarchar(max) = 'SELECT @ColumnName FROM @TableName';
DECLARE @sql2 nvarchar(max) = REPLACE(REPLACE(@sql,'@ColumnName',@ColumnNameVariable),'@TableName',@TableNameVariable)
EXEC (@sql2)
...Some code that changes the values of @ColumnNameVariable and @TableNameVariable...
DECLARE @sql2 nvarchar(max) = REPLACE(REPLACE(@sql,'@ColumnName',@ColumnNameVariable),'@TableName',@TableNameVariable)
EXEC (@sql2)
And you'll notice that the Declaration and Exec of SQL2 are exactly the same lines in both cases. This lends itself to use in a LOOP if that is applicable. (Except that you wouldn't DECLARE @Sql2 in the loop...just populate/re-populate it).
A:
First of all, kudos for trying to parameterize your dsql using sp_executesql. The problem is, you can only parameterize something you could put into a variable in the first place such as in a search predicate or select list.
However it's still possible; just concatenate the column name with your DSQL string, wrapping it with the quotename function
set @sql = 'update table1 set table1.' + quotename(@ColumnName) + ' = ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I take my client to court for non payment of invoice before invoice is due?
He has stated in an email that he will not be paying it. I had set the payment terms to 28 days. This means that I'll have to wait a month to start the claim process, beginning with a letter before action. Since he has already stated he won't pay, can I start the process now?
A:
I am NOT a lawyer.
It is my understanding that in the United States, if you have evidence of an intent to default on payment or a contract, you can start the legal processes of repercussions due to that default, i.e. small claims.
Certainly someone stating, in writing "I won't pay" is evidence that there is direct intent to breach any contract for payment.
A:
There is nothing stopping you from getting in touch with a lawyer now and getting things set up proactively. They will be able to give you better advice that is tailored to these circumstances. Much of the specifics, such as what constitutes reasonable delays and even intent to default (as brought up by others) may be subject to state statutes.
Your lawyer may still elect to not pursue this until the 28 days has lapsed, but at least by that point you'll have done the necessary legwork already.
If you feel that the invoice is worth more than the cost of hiring your legal representation, then go for it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Match_parent not working in ImageView in Android Studio 2.3
I am new here and trying to learning android programming but i got a problem and unable to fix this, kindly help me on this. I am using Android Studio 2.3 and problem is when i try to use "match_parent" value in
android:layout_width="match_parent"
android:layout_height="match_parent"
it auto turn into below:-
android:layout_width="0dp"
android:layout_height="0dp"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="16dp" />
below is the my complete code, kindly help me on this.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rj.happybirthday.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="36sp"
android:textColor="@android:color/white"
android:fontFamily="sans-serif-light"
android:text="Happy Birthday Rj!"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="0dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:fontFamily="sans-serif-light"
android:textColor="@android:color/white"
android:textSize="36sp"
android:text="From, Rj!"
/>
<ImageView
android:src="@drawable/party"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="16dp" />
</android.support.constraint.ConstraintLayout>
A:
ConstraintLayout child views cannot specify match_parent as their desired dimensions. Use match_constraint (0dp) with left/right or top/bottom constraints set to "parent".
Widgets dimension constraints
The dimension of the widgets can be specified by setting the android:layout_width and android:layout_height attributes in 3 different ways:
Using a specific dimension (either a literal value such as 123dp or a Dimension reference)
Using WRAP_CONTENT, which will ask the widget to compute its own size
Using 0dp, which is the equivalent of "MATCH_CONSTRAINT"
Fig. 7 - Dimension Constraints
The first two works in a similar fashion as other layouts. The last one will resize the widget in such a way as matching the constraints that are set (see Fig. 7, (a) is wrap_content, (b) is 0dp). If margins are set, they will be taken in account in the computation (Fig. 7, (c) with 0dp).
Important: MATCH_PARENT is not supported for widgets contained in a ConstraintLayout, though similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent".
Source : https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Does selenium webdriver support css contains?
I've read that "the css2 contains function is not in css3, however selenium supports the superset of css 1,2 and 3."
Will contains be supported by Selenium Server using webDriver or it only supported when using the Selenium IDE?
A:
I recently came across some more information that may be useful to you. To use contains in css selector. You will have to use :contains pseudo class however this is not properly supported in recent versions of CSS selector engines,upon which WebDriver relies for CSS selector, hence it is not a preferred way these days. To get the same effect of using a contains use
div[name*='part'] in CSS Selector and will match all div tags where id contains 'part'. This is equivalent to using //div[contains(@name,'part')] in XPath selector.
This question has similar discussions as your own.
Check this stackexchange answer for more information.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does Mail do when it sends Windows friendly attachments?
What does Mail do to the file or files differently when it sends attachments that are Windows friendly?
A:
According to http://www.ncmug.org/tips/mail_attachments.html:
By default, Mail assumes your recipient is also a Mac user and therefore includes the resource forks (if any) of attached files. Normally a Mac user sees such attachments as a single file, whereas a Windows user sees two individual files - one containing the data fork of the file and the other containing the resource fork.
When you choose "Windows Friendly" attachments, Mail strips the resource fork so that Windows users receive just one file, not two (one of which would be unusable anyway). In most cases - at least for files created with modern applications - all the crucial parts of files are in the data fork; as long as the filename has the correct extension and they have an appropriate application, Windows users can open the file.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to customize json output in rails?
I have a model for languages and i want to get all the languages as json but the json output looks as follows
[{"language":{"created_at":null,"id":1,"language":"English","updated_at":null}},{"language":{"created_at":null,"id":2,"language":"Swedish","updated_at":null}},{"language":{"created_at":null,"id":3,"language":"German","updated_at":null}},{"language":{"created_at":null,"id":4,"language":"French","updated_at":null}},{"language":{"created_at":null,"id":5,"language":"spanish","updated_at":null}},{"language":{"created_at":null,"id":6,"language":"dutch","updated_at":null}},{"language":{"created_at":"2012-12-03T05:01:18Z","id":7,"language":"Tamil","updated_at":"2012-12-03T05:01:18Z"}}]
but i want to make this as
{"language":[{"created_at":null,"id":1,"language":"English","updated_at":null},{"created_at":null,"id":2,"language":"Swedish","updated_at":null},{"created_at":null,"id":3,"language":"German","updated_at":null},{"created_at":null,"id":4,"language":"French","updated_at":null},{"created_at":null,"id":5,"language":"spanish","updated_at":null},{"created_at":null,"id":6,"language":"dutch","updated_at":null},{"created_at":null,"id":7,"language":"Tamil","updated_at":null} ] }
Update
def index
@languages = Language.all
respond_to do |format|
format.json { render json: @languages}
end
end
update 2
class Language < ActiveRecord::Base
ActiveRecord::Base.include_root_in_json = false
has_and_belongs_to_many :users
end
A:
I believe this should work:
format.json { render json: { "language" => @languages.as_json(:root => false) }.to_json }
What this does it to convert the @languages array into an array of JSON-formatted hash models with no root keys (using as_json), then wraps the result in a hash with a root key "language", and convert that hash into a JSON-formatted string with to_json. (See the docs for details on including or not including a root node using as_json.)
For example, with a model Post:
posts = Post.all
#=> [#<Post id: 1, name: "foo", title: "jkl", content: "some content", created_at: "2012-11-22 01:05:46", updated_at: "2012-11-22 01:05:46">]
# convert to array of hashes with no root keys
posts.as_json(root: false)
#=> [{"content"=>"some content", "created_at"=>Thu, 22 Nov 2012 01:05:46 UTC +00:00, "id"=>1, "name"=>"foo", "title"=>"jkl", "updated_at"=>Thu, 22 Nov 2012 01:05:46 UTC +00:00}]
# add root back to collection:
{ "post" => posts.as_json(root: false) }
#=> {"post"=>[{"content"=>"some content", "created_at"=>Thu, 22 Nov 2012 01:05:46 UTC +00:00, "id"=>1, "name"=>"foo", "title"=>"jkl", "updated_at"=>Mon, 03 Dec 2012 09:41:42 UTC +00:00}]}
# convert to JSON-formatted string
{ "post" => posts.as_json(root: false) }.to_json
#=> "{\"post\":[{\"content\":\"some content\",\"created_at\":\"2012-11-22T01:05:46Z\",\"id\":1,\"name\":\"foo\",\"title\":\"jkl\",\"updated_at\":\"2012-12-03T09:43:37Z\"}]}"
A:
override the as_json on the Model you want to customize
def as_json options={}
{
id: id,
login: login,
name: custom.value, #for custom name
...
}
end
==> or
def as_json(options={})
super(:only => [:id, :login, :name ....])
end
from : here
Other link: here
| {
"pile_set_name": "StackExchange"
} |
Q:
Specifying login in Feature Setup of SpecFlow and Selenium
I have set up SpecFlow to execute a number of Selenium tests to test a website. This all works fine!
I am just considering if there might be room for some optimization on the structuring of the SpecFlow features.
All the scenarios in a specific feature should use the same login. This is something I have hardcoded in the StepDefinition using the [BeforeScenario()] hook at the moment, since I don't really wan't pollute the scenarios with login info. It isn't relevant for the test.
But at the same time, I would like to remove the hardcoded part, and move this into my feature.
My question is two part.
Can I specify login credentials in my feature description. Sort of like a Given:
Feature: As a user I want to be able to see my ongoing orders, and interact with them.
Given I am logged in with username abc and password xyz
Scenario: See list of ongoing order
Given I place an order
When I navigate to MyOrders page
Then I can see at least one order in the list
Is this good practice?
Does it make sense to do it like this, on the feature level I mean. The scenarios are not dependent on a specific order, and they would execute faster if I didn't need to log in for each scenario.
Thanks for your input.
A:
For steps that are common to all scenarios in a feature you can use Backgrounds:
Feature: As a user I want to be able to see my ongoing orders, and interact with them.
Background:
Given I am logged in with username abc and password xyz
Scenario: See list of ongoing order
Given I place an order
When I navigate to MyOrders page
Then I can see at least one order in the list
Too much abuse of background steps can be a bad practice because it introduces coupling between your scenarios.
Another solution is to put the login part directly into your "I Place an order" step.
This will remove all the noise about login stuff since it's implicit that you need to log in to place an order.
I'd also suggest to call it "I've placed an order" instead of "I place an order".
Given steps are usually pre-condition that describes what happened prior using the functionnality (when steps)
A:
When I first read your post, I thought of Dan North: Who's domain is it anyway? and that influences me to think that we should be trying to write our tests so that they stick to a single knowledge domain. As you talk about specific users and navigation and orders in a list, well its very like the example he gives in that your specification is crossing domains. This kind of leads me towards almost making your specification less specific, i.e. its not about navigating and checking a list, do you have an order or not!
Scenario: See list of ongoing order
Given I am logged in with username abc and password xyz
And I place an order
Then should have at least one order
I wanted to give you another example link, to a post I cant find, which talks about the benefits that a team has got by actually defining some example users and what value that gives their testing. So in your business domain you might have a user called Jack who will have placed a large order in the system, and another prospective client Jill with no orders. In this way tests such as
Given I am Jack
When I search for my orders
Then I will find 1
Given I am Jill
When I search for my orders
Then I will find 0
can guarantee that you are only testing your Search functionality, and less about getting the setup in place.
I'd also suggest that you have a look at Liz Keogh: Acceptance Criteria vs Scenarios who asserts that more general broad definitions are less valuable than very specific examples. (It is Specification By Example after all :-) )
So to answer your question, I think having the specified user is a good thing, but doing it how you are doing it is heading a very complicated route.
| {
"pile_set_name": "StackExchange"
} |
Q:
what does "______, thy name is ______" mean?
No only can I not get what the following sentence means, I fail to understand the concept of the bold part, as well.
Frailty, thy name is woman
"______, thy name is ______"
A:
Frailty, thy name is woman
The meaning of the sentence is "women embody frailty to the full extent" or
The quality called "frailty" is most closely expressed by the object called "woman".
or, even:
Women are so frail that the words "frailty" and "woman" are equal in meaning.
That is, women are considered to be more delicate, more frail than men. The author of the sentence tries to express it in "high language", to add emphasis.
Other examples of the same structure:
Treachery thy name is government bureaucrat! (source)
It turns out there's a Wikipedia page about this structure: "Thy name is".
| {
"pile_set_name": "StackExchange"
} |
Q:
Which (non get/kiddushin) shtaros exist on a d'oraisa level?
Besides a get (written explicitly in the Torah Deuteronomy 24:1) & a shtar kiddushin (learned from a get via a hekesh Kiddushin 5a)- are there other shtaros that exist on a d'oraisa level, and if so which ones?
(minority opinions also welcome- ie Rabbeinu Tam/ Ri are of the opinion that a ketubah is d'oraisa Tos' Ketubot 10a)
A:
Not including the ones mentioned in the OP, the documents for buying any of the following are d’Oraisa:
Jewish slaves (Kiddushin 16a, either from comparison to Kiddushin based on Shemos 21:10 or from a combination of Shemos 21:7 and Vayikra 25:46)
Non-Jewish slaves (Kiddushin 22b, from comparison to land based on Vayikra 25:46)
Bill of emancipation (Kiddushin 23a and Gittin 41b, by Geziras HaKasuv from Gittin in Devarim 24:1 to Vayikra 19:20)
Even freeing half a slave (Gittin 41b, by comparison to freeing a slave through money based on Vayikra 19:20)
Land given as a gift (Kiddushin 26a, from Yirmiya 32:11)
Movable property acquired via land (Kiddushin 26a, from Divrei HaYamim 2:21:3)
| {
"pile_set_name": "StackExchange"
} |
Q:
Storage and 'weight' of Arrays and Object variables
So...
var testArray=new Array("hello");
testArray.length=100;
console.log(testArray.length);
I believe the above means I have created an array that has 100 elements. The first element contains the word hello, the others are null, but their position reserved. While small, I suspect reserving these "slots" uses memory.
What about
var myObj={ testArray: new Array(), testVar: "elvis", anotherArray: new Array() };
myObj.testArray.length=1000;
What is the impact or weight of this setup within javascript. Does the engine reserve three containers, each of similar size for testArray, testVar and anotherArray since they fall under myObj?
I tend to create a single global object (called DATA), and then I create variables under that. These variables contain temporary session data within an intranet app which is used several hours a day. Some of the variables are arrays, some are strings. I do it this way because with a single command DATA=null I can empty everything which would not be the case if I were to have several global variables.
I'm just wondering if my thinking is poor or acceptable/understandable. The answer will also help me to better understand how javascript stores data.
Comments welcome...
A:
I believe the above means I have created an array that has 100
elements. The first element contains the word hello, the others are
null, but their position reserved. While small, I suspect reserving
these "slots" uses memory.
You created an array with 1 element, then you changed the length of that array to 100. However, that does not mean that you have 99 null elements; you only have 1 element in the array. In other words, the length property of the array does not necessary tell you the number of defined elements. The process to reserve this does take memory, but is negligible for a small number of elements. However, I do not recommend using the .length property as an assignment; you are really introducing the potential for some unexpected behavior in your code, as well as mismanaging resources. Instead,You should allow the array to grow and shrink as needed, using functions; .push() and .pop(), .splice(). By doing this, you are minimizing the amount of space required by the array and improving performance.
What is the impact or weight of this setup within JavaScript. Does the engine reserve three containers, each of similar size for testArray, testVar and anotherArray since they fall under myObj?
There are 3 containers that are created for the object.
1)DATA object gets a container2)testArray gets a container because you used the constructor approach (not best-practice)3)anotherArray container because you used the constructor approach (not best-practice)
In your example, DATA is the container for all of the name:value pairs that exist within this container. The "weight" is exactly the same as your first approach (except you are allocating 1000 slots, instead of 100).
I highly suggest that you do not have statements that assign a value to the length of the array. The array should only use as much space as is needed, no more and no less.
You should also create arrays with the literal approach: var array = []; NOT with the new keyword, constructor approach, as you are doing. By using the new keyword, you raise the potential to have bugs in your code. Also, JavaScript variables declared using the new keyword are always created as objects. See the below example.
var data = new Array(2, 10); // Creates an array with two elements (2 and 10)
var data = new Array(2); // Creates an array with 2 undefined elements
Avoid polluting the global namespace!!!! Using an object is a good approach in your situation, but it's very important to keep the global namespace clean and free of clutter as much as possible.
Further supporting resources:
MDN Arrays
MDN array.length
MDN Objects
Writing Fast, Memory-Efficient JavaScript
| {
"pile_set_name": "StackExchange"
} |
Q:
groupIdx parameter of spark regexp_extract function
I don't understand how last parameter groupIdx works in below function, I can't find any details in documentation. I am using this function with groupIdx = 0, when I changed this value to > 0, I've received an error java.lang.IndexOutOfBoundsException: No group 1. Can someone explain how it works and when groupIdx > 0 could be applied?
regexp_extract(e: Column, exp: String, groupIdx: Int): Column
A:
The argument extracts the part of a match that was captured with the specified capturing group.
See the docs:
regexp_extract(str, regexp[, idx]) - Extracts a group that matches regexp.
Examples:
> SELECT regexp_extract('100-200', '(\d+)-(\d+)', 1);
100
The 100 substring is captured with the first (\d+) in the regex pattern, and the 1 argument makes the function return just this part of the whole match (which is 100-200).
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there any indeclinable adjectives?
I had until recently believed that only nouns could be "declinable" versus "indeclinable": most nouns follow set declensions patterns, while a few (mostly foreign, like Abraham from Hebrew, but some native, like fas) look the same in every form.
However, brianpck corrected me in his comment on this answer, pointing out that the adjective nēquam is also indeclinable.
Are there any other indeclinable adjectives out there?
A:
There certainly are other indeclinable adjectives:
damnas
frugi (gramatically, this is really a "dative of service")
nēquam
potis (though pote sometimes occurs in the neuter)
quot (also: aliquot)
tŏt (also: totidem)
And, after tres, almost every numerical adjective, e.g. quattuor, decem, viginti, mille, etc.
Allen & Greenough discusses this, along with many of the above examples, in §122, along with a mention of defective and common adjectives.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where does Google Dataproc store Spark logs on disk?
I'd like to get command line access to the live logs produced by my Spark app when I'm SSH'd into the master node (the machine hosting the Spark driver program). I'm able to see them using gcloud dataproc jobs wait, the Dataproc web UI, and in GCS, but I'd like to be able to access the live log via command line so I can grep, etc. through it.
Where can I find the logs produced by Spark on the driver (and on the executors too!)?
A:
At the moment, Dataproc doesn't actually tee out any duplicate copy of the driver output to local disk vs just placing it in GCS, in part because it doesn't quite fit into standard log-rotation policies or YARN task log cleanup, so it requires extra definitions of how to perform garbage-collection of these output files on the local disk or otherwise risking slowly running out of disk space on a longer-lived cluster.
That said, such deletion policies are certainly surmountable, so I'll go ahead and add this as a feature request to tee the driver output out to both GCS and a local disk file for better ease-of-use.
In the meantime though, you have a couple options:
Enable the cloud-platform scope when creating your cluster (gcloud dataproc clusters create --scopes cloud-platform) and then even on the cluster you can gcloud dataproc jobs wait <jobid> | grep foo
Alternatively, use gsutil cat; if you can gcloud dataproc jobs describe from another location first to find the driverOutputResourceUri field, this points at the GCS prefix (which you probably already found since you mentioned finding them in GCS). Since the output parts are named with a padded numerical prefix, gsutil cat gs://bucket/google-cloud-dataproc-metainfo/cluster-uuid/jobs/jobid/driveroutput* will print out the job output in the correct order, and then you can pipe that into whatever you need.
| {
"pile_set_name": "StackExchange"
} |
Q:
insert into sql database using php
I have been working on adding data to my sql database i have tryed many different ways of doing this but am still gettting the same errors.
Notice: Undefined index: ModuleId in N:\ftp\compc\d11os\Project\addModule.php on line 63
Notice: Undefined index: Title in N:\ftp\compc\d11os\Project\addModule.php on line 64
Notice: Undefined index: CreditLevel in N:\ftp\compc\d11os\Project\addModule.php on line 65
Notice: Undefined index: CreditPoints in N:\ftp\compc\d11os\Project\addModule.php on line 66
Notice: Undefined index: Status in N:\ftp\compc\d11os\Project\addModule.php on line 67
what am i doing wring i know it probly somthing smalll but i cant see it and really need help?
here is the code i am using
<?php
$con=mysqli_connect("localhost","ROOT","ROOT","ROOTdb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$ModuleId = mysqli_real_escape_string($con, $_POST['ModuleId']);
$Title = mysqli_real_escape_string($con, $_POST['Title']);
$CreditLevel = mysqli_real_escape_string($con, $_POST['CreditLevel']);
$CreditPoints = mysqli_real_escape_string($con, $_POST['CreditPoints']);
$Status = mysqli_real_escape_string($con, $_POST['Status']);
$Award = mysqli_real_escape_string($con, $_POST['Award']);
$sql="INSERT INTO module(ModuleId, Title, CreditLevel, CreditPoints, Status, Award)
VALUES ('$ModuleId', '$Title', '$CreditLevel' ,'$CreditPoints', '$Status', '$Award')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Html code im using
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<img src="logo.jpg" alt="University of Ulster Logo" width="332" height="132">
<h1 style="font-family:Bell MT;color:blue;font-size:28px;">Add a New Module.</h1>
</head>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0">
<tr><td>Module:</td><td>
<input type="text" name="name" maxlength="60" required>
</td></tr>
<tr><td>Title:</td><td>
<input type="text" name="telephoneNo" maxlength="60" required>
</td></tr>
<tr><td>CreditLevel:</td><td>
<input type="text" name="email" maxlength="60" required>
</td></tr>
<tr><td>CreditPoints:</td><td>
<input type="text" name="course" maxlength="60" required>
</td></tr>
<tr><td>Status:</td><td>
<input type="text" name="Staus" maxlength="100" required>
</td></tr>
<tr><td>Award:</td><td>
<input type="text" name="Award" maxlength="100" required>
</td></tr>
<td colspan="2" style="text-align:center">
<input type="submit" name='submit' value='Submit'>
</form>
A:
The issue is appearing because the variables you are using are not defined in the $_POST array.
Try something like
if (isset($_POST['ModuleId']))
{
$ModuleId = mysqli_real_escape_string($con, $_POST['ModuleId']);
} else {
$ModuleId = -1; // Default value or Error flag
echo "Module Id is not specified.";
}
and so on for your other variables.
It is probably a good idea to check that all the values are present, prior to insert. For example,
if ($ModuleId != -1) {
$sql="INSERT INTO module(ModuleId, Title, CreditLevel, CreditPoints, Status, Award)
VALUES ('$ModuleId', '$Title', '$CreditLevel' ,'$CreditPoints', '$Status', '$Award')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
mysqli_close($con);
// EDIT
You issue seems to be stemming from not checking if the page has done a post back. When the page is first loaded, it will try to insert data - but there is no data to insert as you have not submitted the form.
Wrap your php code with a simple check like so
<?php
if (isset($_POST['submit']))
{
$con=mysqli_connect("localhost","ROOT","ROOT","ROOTdb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$ModuleId = mysqli_real_escape_string($con, $_POST['ModuleId']);
$Title = mysqli_real_escape_string($con, $_POST['Title']);
$CreditLevel = mysqli_real_escape_string($con, $_POST['CreditLevel']);
$CreditPoints = mysqli_real_escape_string($con, $_POST['CreditPoints']);
$Status = mysqli_real_escape_string($con, $_POST['Status']);
$Award = mysqli_real_escape_string($con, $_POST['Award']);
$sql="INSERT INTO module(ModuleId, Title, CreditLevel, CreditPoints, Status, Award)
VALUES ('$ModuleId', '$Title', '$CreditLevel' ,'$CreditPoints', '$Status', '$Award')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
}
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
The wrong site title is coming up for home page
For some reason, the title of our website in browser windows and tabs is coming up as something else. We aren't even sure where this title came from, as it has nothing to do with our site.
I checked the page source to see what was showing up in the <title> tags, and sure enough, it's the same, incorrect title.
I tried changing the name of the site and the site's slogan, hoping that would help. I've cleared the caches. It's been going on for about 8 months, before we made some upgrades to core and modules.
Other page titles seem to be working correctly. There are no nodes with this title. We are using Drupal Commons. Drupal version 7.50.
A:
Normally the <title> element is set in template_preprocess_html
// Construct page title.
if (drupal_get_title()) {
$head_title = array(
'title' => strip_tags(drupal_get_title()),
'name' => check_plain(variable_get('site_name', 'Drupal')),
);
}
else {
$head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
if (variable_get('site_slogan', '')) {
$head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
}
}
$variables['head_title_array'] = $head_title;
$variables['head_title'] = implode(' | ', $head_title);
That is then output in your theme html.tpl.php
You may have some code or configuration overriding the default title there in a module or theme.
I'd suggest searching through the codebase for the title text, or perhaps in a db dump file.
After that, you can either update it, or add some code for your own HTML <title> logic.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sequelize - How to get entries from one table that are not assiciated by another table
I used Sequelize to define three Entities for users rating posts:
var User = sequelize.define('User', {
email: {
type: Sequelize.STRING,
primaryKey: true
}
});
var Post = sequelize.define('Post', {
link: {
type: Sequelize.STRING,
primaryKey: true
}
});
var Rating = sequelize.define('Rating', {
result: Sequelize.STRING
});
Rating.belongsTo(Post);
Post.hasMany(Rating);
Rating.belongsTo(User);
User.hasMany(Rating);
A user can rate several posts. Each rating belongs to exactly one user and one post.
Now I'd like to query for a given user all posts that are not already rated by this user. I tried a thousand ways but without success. Any idea how to achieve this in Sequelize? Thanks a lot!
A:
There are two methods either use raw query in Sequelize or via Sequelize query as well -
Raw -
return Db.sequelize.query("SELECT * FROM Post P WHERE (P.id NOT IN (SELECT postId FROM Ratings R WHERE R.userId="+userId+")) ",{ type: Sequelize.QueryTypes.SELECT });
Sequelize -
return Post.findAll({
where: {
Sequelize.literal("(posts.id NOT IN (SELECT R.postId FROM Rating R WHERE R.userId="+userId+"))")
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
If $p$ is prime and $p$ $\equiv$ $1$ (mod 4), then the congruence $x^2$ $\equiv$ $-1$ (mod $p$) has two incongruent solutions...
Question: If $p$ is prime and $p$ $\equiv$ $1$ (mod 4), then the congruence $x^2$ $\equiv$ $-1$ (mod $p$) has two incongruent solutions given by $x$ $\equiv$ $\pm$ $\frac{(p-1)}{2}$!(mod $p$).
I noticed that the congruence $x^2$ $\equiv$ $-1$ (mod $p$) fits the form of Wilson's theorem but can't figure out how to modify/change the congruency to fit Wilson's theorem. Sorry if this is a duplicate, I wasn't able to find any other question similar to this one but it could just be my incorrect usage of MathJax.
A:
You need to consider the product $$-\frac {p-1}2 \cdot -\frac {p-3}2\cdot \dots -2\cdot -1\cdot 1 \cdot 2 \dots \cdot \frac {p-1}2 \equiv (p-1)!\bmod p$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Apart from Arabic, is there such a thing as "Islamic languages"?
Is there such a thing as "Islamic languages"?
There's a totally false online rumour, spread by people opposed to Islam, claiming that Japan is really anti-Islam. But there's one part that states that "Islamic languages" aren't taught in Japan, and I want to know if there's even such a thing as "Islamic languages".
The exact quote of the rumour is "In the University of Japan, Arabic or any Islamic language is not taught." - it's probably written by someone who isn't a native speaker of English, and it probably means "neither Arabic nor any other Islamic language is taught".
I know that Arabic plays a special role in Islam. For example it's the language the Quran is written in. But are there any other "Islamic languages"?
A:
No. There are no other languages that have links to Islam itself. This can be seen easily by doing a Google search for "Islamic languages". They're probably just trying to make a point and doing it badly. In fact, I can disprove it right here. That link shows that the University of Japan in fact offers three courses on Arabic.
| {
"pile_set_name": "StackExchange"
} |
Q:
Specify a C# Generic Constraint to be of ClassA OR ClassB?
Is there a way to specify that a generic type be of one type or another type?
public class SoftDrink<T>
where T : TypeOne or TypeTwo
{ }
A:
Nope because that wouldn't make any sense. If you try to access a member function of "T", how can the compiler tell which base class to try and resolve members of?
You could try creating a common interface for TypeOne and TypeTwo and having the constraint specify that interface? What are you trying to accomplish, exactly?
A:
You can't. The best you can do is use a common base class for the two, or a common interface implemented by both as a single type constraint.
| {
"pile_set_name": "StackExchange"
} |
Q:
Selecting a Word Interop Header Range causes Word to switch to Draft View
When selecting a Header Range using .Select(), Microsoft Word automatically switches to Draft View from my current view type (Print layout). How do I stop Word from switching to Draft View?
The following code example demonstrates what I'm doing:
// this.Document is a Microsoft.Office.Interop.Word.Document
Section section = this.Document.Sections.First;
foreach (HeaderFooter header in section.Headers)
{
if (header.Exists)
{
header.Range.Select(); // When I call this, Word switches to Draft View.
break;
}
}
Edit (3):
Apparently saving the View Type and resetting it does work. However, this causes a annoying flickering when Word switches to Draft View and then back to Print Layout. Additionally, when I double click in the main document space to get out of the header section, Word switches back to Draft View.
WdViewType viewType = this.Document.ActiveWindow.View.Type;
range.Select();
this.Document.ActiveWindow.View.Type = viewType;
A:
The View.SeekView property must be set for all view types excluding wdNormalView (Draft View) before the range is selected.
var window = this.Document.ActiveWindow;
// wdNormalView == Draft View, where SeekView can't be used and isn't needed.
if (window.View.Type != WdViewType.wdNormalView)
{
// -1 Not Header/Footer, 0 Even page header, 1 Odd page header, 4 First page header
// 2 Even page footer, 3 Odd page footer, 5 First page footer
int rangeType = range.Information[WdInformation.wdHeaderFooterType];
if (rangeType == 0 || rangeType == 1 || rangeType == 4)
window.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
if (rangeType == 2 || rangeType == 3 || rangeType == 5)
window.View.SeekView = WdSeekView.wdSeekCurrentPageFooter;
}
header.Range.Select();
| {
"pile_set_name": "StackExchange"
} |
Q:
Drawable as Background for CardView
the CardView ( android.support.v7.cardview ) stays white even though I set a backround drawable via android:backround - The documentation gives me the feeling that it should work. No Idea what I am doing wrong here.
A:
I know this is an old question, but I have a simple solution - just make the first child of your CardView an ImageView and specify the scale type to fitXY. You can get rid of the extra CardView padding by setting cardElevation and cardMaxElevation to 0dp:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="200dp"
app:cardCornerRadius="4dp"
app:cardElevation="0dp"
app:cardMaxElevation="0dp">
<ImageView
android:src="@drawable/your_background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"/>
<... your layout
.../>
</android.support.v7.widget.CardView>
A:
for drawable or color just use:
cvSellerShopp.setBackgroundResource(R.drawable.ic_action_add_image);
for color use:
cvSellerShopp.setCardBackgroundColor(R.color.colorPrimary);
but this one does not produce the intended results
A:
I got this working by adding a linearlayout in the cardview and then setting cardPreventCornerOverlap to false in the cardview.
<android.support.v7.widget.CardView
android:id="@+id/result_cv"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_margin="4dp"
app:cardCornerRadius="16dp"
app:cardElevation="8dp"
app:cardPreventCornerOverlap="false"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient"
android:gravity="center"
>
<!-- your views -->
</LinearLayout>
</android.support.v7.widget.CardView>
| {
"pile_set_name": "StackExchange"
} |
Q:
Python 2.7.5 how to accumulate and declare values in an array/ list from user input?
My apologizes for the basic question, I'm working through a programming book discussing arrays, Using python 2.7.5 I want to ask the user for input and store the numbers in an array, I can assign a value in the array to a string but don't want to do that, instead of doing:
emp_name[0] = raw_input("please enter employee name")
I want to add values to the array emp_name, and recall something like: emp_name[1] and have the 2nd name entered displayed for the user. I apologize for the novice question but I'm still wrapping my head around arrays.
I think I have to use a for numbers in range loop, or a while loop? Please assist
A:
give this a shot
emp_names = []
num_to_enter = 10
while num_to_enter > 0:
emp_names.append(raw_input("enter name"))
num_to_enter -= 1
print emp_names[0]
#do what you need to do
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use Google Datastore CompositeFilter with Dataflow?
When reading data from Datastore as input for a pipeline I am able to create a "simple" query, where I set a filter on a single property like so:
Pipeline p = ...
Filter filter = Filter.newBuilder()
.setPropertyFilter(PropertyFilter.newBuilder()
.setProperty(PropertyReference.newBuilder()
.setName("propertyA"))
.setOp(PropertyFilter.Operator.EQUAL)
.setValue(Value.newBuilder().setStringValue("valueA").build())
.build())
.build();
Query query = Query.newBuilder()
.addKind(KindExpression.newBuilder().setName("myKind").build())
.setFilter(filter)
.build();
p.apply("read", DatastoreIO.v1().read().withProjectId("myProjectId")
.withNamespace("myNamespace").withQuery(query)).apply(.....
When I tried to apply multiple Filters on the query by concatenating the "setFilter()"-calls, only the last set Filter was applied to the query.
Upon some research I found a CompositeFilter which is supposed to enable the combination of multiple filters. I can build a composite filter, but when i want to set it on the query as a filter, the IDE complains that the types don't match and there doesn't seem to be another method to apply filters.
I managed to use a query with multiple filters by using GQL and can see in the logs that it is transformed into a CompositeFilter. I am not here to complain as the usage of GQL is much nicer than building the queries/filters by hand, but wanted to ask how the composite filter of the library WOULD be used in the context of DatastoreIO.v1().read(....) or if it isn't possible.
I am using com.google.cloud.dataflow/google-cloud-dataflow-java-sdk-all/2.2.0
Thank you for your help.
A:
According to the docs, you can. You can use CompositeFilter newBuilder method, and create a filter like the following:
Filter composeFilter = Filter.newBuilder() .setCompositeFilter(CompositeFilter.newBuilder().addFilters(filter1).addFilters(filter2).build()).build();
Filter1 and Filter2 here are filters like the ones you have created. My IDE allows me to do this (I'm using IntelliJ IDEA, last version).
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery Are you Sure + Rails Nav being ignored
I have a Rails app, and wanted to emulate the onunload effect to prompt before leaving changes. While looking around I found out about Are You Sure?.
I have it implemented on a form, and it works on page refreshes, but it isn't working on links that leave the page. I'm thinking this is turbolink based so I tried running $('body').attr("data-no-turbolink", "true"); in the ready statement, however I'm getting the same effect.
Since this is Rails specific I'm unsure how to truly emulate it via a Fiddle.
I've tried running it globally on both form and the id of the form, and both give the above results.
$('form').areYouSure();
Is this a turbolinks issue, or a known issue (That I can't find in the Git Issues) about beforeunload?
A:
I also believe this is turbolinks problem. Turbolinks 5 is not more compatible with gem 'jquery-turbolinks', '~> 2.1', which would solve this issues with the jquery libraries.
Discussion about this
https://github.com/kossnocorp/jquery.turbolinks/issues/56
The reason is that the event names changed, so that gem is not working anymore.
https://github.com/codedance/jquery.AreYouSure/blob/master/jquery.are-you-sure.js
If you check the jquery.are-you-sure.js you can see that the function inside it is wrapped in a $(document).ready() statement, (function($) { })(jQuery);
https://github.com/codedance/jquery.AreYouSure/blob/master/jquery.are-you-sure.js
You can test this by disabling turbolinks on a specific link
https://github.com/turbolinks/turbolinks#disabling-turbolinks-on-specific-links
If you have Turbolinks < 5 you can solve this issue by installing a gem called gem 'jquery-turbolinks', '~> 2.1', otherwise you need to understand why the jquery code is not executing on page change... You need to change that $(document).ready() statement or (function($) { })(jQuery); statement in a $(document).on("turbolinks:load", function() {});
| {
"pile_set_name": "StackExchange"
} |
Q:
Confusion with the styles in Ionic app + Bootstrap
I have Ionic app in which I use angular-ui-bootstrap Datepicker. To apply bootstrap style only on this datepicker I apply class="bootstrap" on div element (I import bootstrap using Sass and wrap it with .bootstrap):
<div class="bootstrap">
<uib-datepicker ng-model="dt" class="well well-sm"></uib-datepicker>
</div>
It works fine. But Ionic styles does apply on elements inside this div, I mean month name and arrows are shown incorrectly. I try redefine styles but without any success. This style don't works
.tr {
vertical-align: middle;
}
http://codepen.io/anon/pen/xwmxQL
How can I fix this?
A:
I find my mistake. Instead of tr I must use th:
.th {
vertical-align: middle;
}
Now it works.
| {
"pile_set_name": "StackExchange"
} |
Q:
UML Diagram choice
What would be the best UML diagram to show decoupling of two multithreaded classes, joined
by a producer consumer queue.
I've done a whole bundle of class diagrams in the past, but they seem to be really static.
Is it possibly the case that UML is not very good at modelling threading.
Thanks.
A:
Use a sequence diagram. One lifeline for each class, one lifeline for the queue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Per-thread hashtable-like data structure implementation in CUDA
Short version of my question:
I have a CUDA program where each thread needs to store numbers in different "bins", and I identify each of these bins by an integer. For a typical run of my program, each CUDA thread might only store numbers in 100 out of millions of bins, so I'd like to know if there is a data structure other than an array that would allow me to hold this data. Each thread would have its own copy of this structure. If I were programming in Python, I would just use a dictionary where the bin numbers are the keys, for example mydict[0] = 1.0, mydict[2327632] = 3.0, and then at the end of the run I would look at the keys and do something with them (and ignore the bins where no numbers are stored in them since they aren't in the dictionary). I tried implementing a hash table for every thread in my cuda program and it killed performance.
Long version:
I have a CUDA Monte Carlo simulation which simulates the transport of particles through a voxelized (simple volume elements) geometry. The particles deposit energy during their transport and this energy is tallied on a voxel-per-voxel basis. The voxels are represented as a linearized 3D grid which is quite large, around 180^3 elements. Each CUDA thread transports 1-100 particles and I usually try to maximize the number of threads that I spawn my kernel with. (Currently, I use 384*512 threads). The energy deposited in a given voxel is added to the linearized 3d grid which resides in global memory through atomicAdd.
I'm running into some problems with a part of my simulation which involves calculating uncertainties in my simulation. For a given particle, I have to keep track of where (which voxel indices) it deposits energy, and how much energy for a given voxel, so that I can square this number at the end of the particle transport before moving on to a new particle. Since I assign each thread one (or a few) particle, this information has to be stored at a per-thread scope. The reason I only run into this problem with uncertainty calculation is that energy deposition can just be done as an atomic operation to a global variable every time a thread has to deposit energy, but uncertainty calculation has to be done at the end of a particle's transport, so I have to somehow have each thread keep track of the "history" of their assigned particles.
My first idea was to implement a hash table whose key would be the linearized voxel index, and value would be energy deposited, and I would just square every element in that hash table and add it to a global uncertainty grid after a particle is done transporting. I tried to implement uthash but it destroyed the performance of my code. I'm guessing it caused a huge amount of thread divergence.
I could simply use two dynamic arrays where one stores the voxel index and the other would store the energy deposited for that voxel, but I am thinking that it would also be very bad for performance. I'm hoping that there is a data structure that I don't know about which would lend itself well to being used in a CUDA program. I also tried to include many details in case I am completely wrong in my approach to the problem.
Thank you
A:
Your question is a bit jargon-ful. If you can distill out the science and leave just the computer science, you might get more answers.
There have been CUDA hash tables implemented. The work at that link will be included in the 2.0 release of the CUDPP library. It is already working in the SVN trunk of CUDPP, if you would like to try it.
That said, if you really only need per-thread storage, and not shared storage, you might be able to do something much simpler, like some per-thread scratch space (in shared or global memory) or a local array.
| {
"pile_set_name": "StackExchange"
} |
Q:
Storing a string into a property
In my class, we are just starting object-oriented Python (we were doing functional programming since the beginning of the semester).
Write a new class called Sentence with the following methods:
An __init__ method which takes a single parameter for a sentence as a string and stores this string in a property. Assume the sentence has no punctuation.
A get_words method which returns the number of words in the sentence. Hint: split.
A capitalize method which modifies the property to make sure the first letter is capitalized. Nothing is returned. Hint: upper but only to the first character.
I'm confused on the init method portion. What does it mean by "store this string in a property".
Also, irrelevant to this hmwk assignment, but why do we call the function init? Is it sort of like the "main" function like in C programming (I come from a C background).
A:
In Python, you can add attributes to objects at any time. For example:
class Sentence(object):
pass
sentence = Sentence()
sentence.the_string = "This is a sentence."
An __init__ method is a special method that gets called when you construct an instance of the class. For example, that Sentence() ends up calling __init__ with no extra arguments. Because I didn't define any __init__, I get the default, which does nothing. But now let's define one, and give it an extra parameter:
class Sentence(object):
def __init__(self, the_sentence):
pass
sentence = Sentence("This is a sentence.")
sentence.the_string = "This is a different sentence."
Now, the only thing left is moving that attribute creation into the __init__ method:
class Sentence(object):
def __init__(self, the_sentence):
self.the_string = the_sentence
sentence = Sentence("This is a sentence.")
The actual question asked about storing the string in a property instead of an attribute. This is almost certainly not part of what you're actually supposed to learn, but rather a sign that your instructor or textbook or tutorial writer doesn't actually know Python very well. A property is a way of faking normal attributes on top of methods, which you shouldn't be learning about any time soon.
| {
"pile_set_name": "StackExchange"
} |
Q:
create a simple two dimensinal array from unknown depth array
I have unknown depth of array but i want to make simple two dimensional array as following , earlier i think my question doesn't make exact sense so i edited this , please help
private function arrayDepth($a) {
$arr = array();
foreach ($a as $key => $val) {
if (is_array($val)) {
$this->arrayDepth($val);
}
else {
$arr[] = $a;
}
}
}
my current array is
Array
(
[0] => Array
(
[0] => Array
(
[0] => 41
[uid] => 41
[1] => 16
[pid] => 16
[2] => 30
[oid] => 30
[3] => 1
[value] => 1
[4] => 0
[optval] => 0
[5] => 2014-05-26 16:41:31
[updateDate] => 2014-05-26 16:41:31
)
[1] => Array
(
[0] => Array
(
[0] => 42
[uid] => 42
[1] => 16
[pid] => 16
[2] => 31
[oid] => 31
[3] => 1
[value] => 1
[4] => 0
[optval] => 0
[5] => 2014-05-26 16:45:49
[updateDate] => 2014-05-26 16:45:49
)
[1] => Array
(
[0] => 44
[uid] => 44
[1] => 16
[pid] => 16
[2] => 31
[oid] => 31
[3] => 1
[value] => 1
[4] => 0
[optval] => 0
[5] => 2014-05-26 16:42:01
[updateDate] => 2014-05-26 16:42:01
)
[2] => Array
(
[0] => 47
[uid] => 47
[1] => 16
[pid] => 16
[2] => 31
[oid] => 31
[3] => 1
[value] => 1
[4] => 0
[optval] => 0
[5] => 2014-05-26 16:45:19
[updateDate] => 2014-05-26 16:45:19
)
[3] => Array
(
[0] => Array
(
[0] => 51
[uid] => 51
[1] => 16
[pid] => 16
[2] => 32
[oid] => 32
[3] => 1
[value] => 1
[4] => 0
[optval] => 0
[5] => 2014-05-26 16:47:27
[updateDate] => 2014-05-26 16:47:27
)
)
)
)
)
i need my output like all array which contain some value into a single array like
array(
[0] => Array
(
[0] => 41
[uid] => 41
[1] => 16
[pid] => 16
[2] => 30
[oid] => 30
[3] => 1
[value] => 1
[4] => 0
[optval] => 0
[5] => 2014-05-26 16:41:31
[updateDate] => 2014-05-26 16:41:31
)
[1] => Array
(
[0] => 42
[uid] => 42
[1] => 16
[pid] => 16
[2] => 31
[oid] => 31
[3] => 1
[value] => 1
[4] => 0
[optval] => 0
[5] => 2014-05-26 16:45:49
[updateDate] => 2014-05-26 16:45:49
)
[2] => Array
(
[0] => 44
[uid] => 44
[1] => 16
[pid] => 16
[2] => 31
[oid] => 31
[3] => 1
[value] => 1
[4] => 0
[optval] => 0
[5] => 2014-05-26 16:42:01
[updateDate] => 2014-05-26 16:42:01
) ...... and so on .....
A:
so finally i solved this issue, if you guys have any better solution please provide
function arrayDepth($a,&$arr) {
foreach ($a as $key => $val) {
if(is_array($val))
if (is_array(@$val[0])) {
arrayDepth($val,$arr);
}
else {
$arr[] = $val;
}
}
}
arrayDepth($aNonFlat,$arr);
var_dump($arr);
| {
"pile_set_name": "StackExchange"
} |
Q:
What will the required time to process 500GB of images using NVIDIA GEFORCE 930M GPU
I have an image dataset of size 500GiB, and my system specs are NVIDIA GEFORCE 930M, 12GB of RAM and Intel Core i5.
I have the following questions:
Is it possible such a large dataset to be used in my local machine?
If yes, How much time will be required for one epoch or equivalently on iteration? Any links or reference on how to compute the required processing time will be helpful.
If my system is not good, what are the other possible solutions I have?
A:
The large size of your data is acceptable for deep learning and big data projects. Your system is also acceptable, though it is not powerful. If you have enough hard disk to store them all, it will suffice which means you can train your network. The elapsed time for each epoch depends on multiple aspects. For instance, some elements which are important are, the batch size and your vectorized implementation, the bottle-neck between the disk and RAM, the bottle between RAM and GPU, the size of the model, the size of training data, the memory size of your GPU alongside the size of your RAM, the size of each data, the load which is imposed to your GPU by your OS, and so forth. The easiest way is to code your network and try it yourself.
As I've mentioned, by the current settings you can train your network, but you may not have very fast computation. However, you can use some techniques to faciliate your training phase as much as possible. For instance, you have two main bottle-necks. The first bottleneck, which exists between disk and RAM, can be dealt with using generators. Namely, you can employ generators to decrease the number of disk calls. The other bottle-neck, between RAM and GPU, can be handled using vectorized implementation of your neural network. After loading your network, you can find the appropriate batch size to use all available GPU memory.
I also want to point out that the current GPU you have may have space limitations. This can incur difficulties when your network is very large. In such cases, you won't be able to load your entire network to your GPU.
| {
"pile_set_name": "StackExchange"
} |
Q:
Refactoring from anonymous type to defined type
I've been tasked with refactoring some code so that it is changed from an anonymous type to a well defined type. However, this anonymous type is defined inside a lambda expression and I'm not too sure how to go about setting it (I'm very new to using lambda).
Here's the logic with the anonymous type:
var groupedData = exportData.GroupBy(x => x.Key.MetricInstance.EntityID)
.Select(grp => new
{
k = grp.Key,
v = grp.Select(x => new
{
trm = x.Key,
tsd = x.Value
})
.ToList()})
.ToList();
The target in question is the k and v variables respectively. k is an int and v is a dictionary. I have created a new class to hold this data:
public class EntityMetricData
{
public int entityID { get; set; }
public Dictionary<TRInfo, List<TimeData>> entityMetrics { get; set; }
}
I would like to store the value of k inside the entityID field and the value of v inside the dictionary, how can I go about doing this? I've tried something like this but it doesn't compile:
var grouping = csvData.GroupBy(x => x.Key.MetricInstance.EntityID)
.Select(grp => new EntityMetricData emd
{
emd.entityID = grp.Key,
emd.entityMetrics = grp.Select(x => new
{
trm = x.Key,
tsd = x.Value
})
.ToList() })
.ToList();
I get an error saying that "grp doesn't exist in the current context".
A:
You don't need the emd variable:
var grouping = csvData
.GroupBy(x => x.Key.MetricInstance.EntityID)
.Select(grp => new EntityMetricData {
entityID = grp.Key,
entityMetrics = grp
.Select(x => new {
trm = x.Key,
tsd = x.Value })
.ToList() })
.ToList();
| {
"pile_set_name": "StackExchange"
} |
Q:
Two right joins / right + outer join, etc not working
I have 3 tables:
Salesman table (containing all salesman ID numbers and their names), a week number table (just a table with 53 numbered entries), and a sales data table with all sales.
I need an output of all salesman, all weeks, even if 0. I can get a list of all weeks, or all salesman, but not both.
Here is what I have so far:
SELECT
DATEPART(wk, d1.u_date) as 'Week',
d4.week AS 'AllWeeks',
convert(decimal,d1.U_slsm) as 'Salesman',
S1.SalesmanNum
from [test].[dbo].[@ORDERLOG] D1
right outer join [test].[dbo].[@weekcounter] d4 on (d4.week = DATEPART(wk, d1.u_date) and DATEPART(yy, d1.u_date) > 2014)
full outer join (select salesmannum from EXECUTIVE...Salesman) S1 on convert(decimal,d1.U_slsm) = S1.salesmannum
order by d4.Week, S1.SalesmanNum
This gives me all 53 weeks even if there are no sales (desired), and it gives me all the salesman who had sales each week (desired), but it only gives me one instance of all the salesman who didn't have sales. I need all salesman for each week. 20 salesman, 53 weeks, 1060 results. What am I doing wrong? Or is there a better way to do this?
This will ultimately include sales data, but I can't get this much to work so far...
I have tried many combinations of joins to no avail...
This is in MSSQL 2008 R2.
A:
If you want all combinations of salesman and week number you can use a cross join between the tables to generate the cartesian product of the two sets.
Your query would look something like this (adjust source tables names as needed):
SELECT
DATEPART(wk, d1.u_date) as 'Week',
all_salesman_weeks.week AS 'AllWeeks',
convert(decimal,d1.U_slsm) as 'Salesman',
all_salesman_weeks.SalesmanNum
from (
select * from
EXECUTIVE...Salesman
cross join
[test].[dbo].[@weekcounter]
) all_salesman_weeks
left join [test].[dbo].[@ORDERLOG] D1
on (all_salesman_weeks.week = DATEPART(wk, d1.u_date) and DATEPART(yy, d1.u_date) > 2014)
and convert(decimal,d1.U_slsm) = all_salesman_weeks.salesmannum
order by all_salesman_weeks.Week, all_salesman_weeks.SalesmanNum
| {
"pile_set_name": "StackExchange"
} |
Q:
How to choose between "show" and "display" something?
English is not my native language but "show" and "display" seems very similar to me.
I work on a Web Application and I don't know if it's better to use "show" or "display" in my UI.
I need to use these terms inside links and buttons. Are there any differences between them ?
Example :
I have to add a link next to the name (in my grid header) in order to display the user's capacity.
download bmml source – Wireframes created with Balsamiq Mockups
Is-it better to use Display, Show or just leave the "Capacity" alone ?
A:
I think "show" is better for a link that provides the user additional information in the same interface, upon clicking. The word pair "show" and "hide" are more active/dynamic, while "display" is more static. For example, if I'm showing you a book, I'm revealing it or directing your attention to it, but if I'm displaying it, I've just set it out for people to observe passively.
From the Macmillan online thesaurus:
show: verb -
to let someone see something
display: verb -
to put something in a particular place so that people can see it easily
| {
"pile_set_name": "StackExchange"
} |
Q:
Declare Cursor dynamically
I need to create Cursors dynamically in stored procedure based on what situation i'm in, the ideal is below:
IF (varOrgGroupCode = '') THEN
BEGIN
DECLARE groupCode CURSOR FOR
SELECT `groupcode` FROM `LICENSEKEYS`;
END;
ELSE
BEGIN
DECLARE groupCode CURSOR FOR
SELECT `groupcode` FROM `LICENSEKEYS` WHERE `groupcode` = varOrgGroupCode;
END;
END IF;
The code above will cause an syntax error. I've googled & someone did it by using temp table. Can anyone tell me how please?
A:
Probably the thing you found on Google was to create a temp table, populate that temp table based on your predicate and then reference the temp table in your cursor declaration.
Something like this:
DELIMITER $$
CREATE PROCEDURE `some_procedure`(IN varOrgGroupCode varchar(100))
BEGIN
DECLARE bNoMoreRows BOOLEAN DEFAULT FALSE;
DECLARE vGroupCode varchar(100);
DECLARE groupCode CURSOR FOR
SELECT `groupcode` FROM `LICENSEKEYS_TEMP`;
declare continue handler for not found set bNoMoreRows := true;
BEGIN
drop table if exists LICENSEKEYS_TEMP;
create temporary table `LICENSEKEYS_TEMP` (groupCode varchar(100));
IF (varOrgGroupCode = '') THEN
insert into `LICENSEKEYS_TEMP` (groupCode) SELECT `groupcode` FROM `LICENSEKEYS`;
ELSE
insert into `LICENSEKEYS_TEMP` (groupCode) SELECT `groupcode` FROM `LICENSEKEYS` WHERE `groupcode` = varOrgGroupCode;
END IF;
open groupCode;
GROUPCODE_LOOP: loop
fetch groupCode into vGroupCode;
-- Do some stuff
if bNoMoreRows then
close groupCode;
leave GROUPCODE_LOOP;
end if;
END LOOP GROUPCODE_LOOP;
END;
END$$
DELIMITER ;
| {
"pile_set_name": "StackExchange"
} |
Q:
X-UA-Compatible in JavaScript and CSS files
For IE8 compatibility, we have added the X-UA-Compatible: IE=EmulateIE7 header to the IIS response headers list.
For some reason these headers are being sent down for ASPX etc, but not for static files - JS/CSS.
Does this header have any relevance for JS/CSS content which gets linked into HTML content? My guess is that as long as the HTML received has this response header along with it, IE8 should respect this header and display the content based on EmulateIE7 compatibility mode. Is that the case?
A:
Does this header have any relevance for JS/CSS content which gets linked into HTML content?
no, you just have to send the header with the HTML file. The browser than switches to backward compatibility mode and treats all linked resources "the ie7 way".
| {
"pile_set_name": "StackExchange"
} |
Q:
Output part of a string in velocity
apologies if I waffle or talk a bit of jibberish but I'm new to velocity, and these forums!
I need to check the contents of a string for a certain character and output the second part of the text if it appears. For example:
set ($string = "This is a long string *** but I only want to output this on my email").
I want to output all text after the 3 Asterisks. I've scoured the forums but cant quite find anything that helps me completely.
A:
Velocity is just a façade for real Java objects, so you have access to all the public methods of the String class, including indexOf and substring. So try something like:
#set ($string = "This is a long string *** but I only want to output this on my email")
#set ($index = $string.indexOf('***'))
#set ($index = $index + 3)
#set ($end = $string.substring($index))
If you have more control over what objects you put in the context, you could add an instance of StringUtils as a helper tool, and then use substringAfter directly.
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery function wired select list
Hi everyone i have a Jquery function wired to a select list onchange. When i change the class of the select list (Error class) the onchange snap.
How i can inhibit the onchange when i change class? this is my example:
<apex:selectList value="{!countries}" multiselect="false" onchange="function()">
<apex:selectOptions value="{!items}"/>
</apex:selectList>
A:
Check if the element has the error class and if so exit the function
if($(this).hasClass('errorClass') return false;
| {
"pile_set_name": "StackExchange"
} |
Q:
Selecting Data from a different Table through the value of a other table
REPLACE INTO `Lehrling` (`idLehrling`,`Nachname`,`Vorname`,`Aufnahmedatum`,`Austrittsdatum`,`Klasse`,`Klassensprecher`,`Betriebe_idBetriebe`,`Ausbildungsberufe_idAusbildungsberufe`,`Credentials_idCredentials`) VALUES (1,'Krahn','Daniel','09.02.2015','31.12.2015','FI31',0,1,3,1);
REPLACE INTO `Credentials` (`idCredentials`,`Benutzername`,`Passwort`,`Anlegedatum`) VALUES (1,'krahnd','osz123','10.02.2015');
My goal is to select Nachname,Vorname from 'Lehrling' where Klasse is 'FI31' and also select Benutzername,Passwort from Credentials through the 'idCredentials' at the same time.
A:
This process is called joining:
Select Lehrling.Nachname, Lehrling.Vorname, Credentials.Benutzername, Credentials.Passwort
From Lehrling
inner join Credentials on Credentials.idCredentials = Lehrling.Credentials_idCredentials
Where Lehrling.Klasse = 'FI31'
| {
"pile_set_name": "StackExchange"
} |
Q:
Sr. Software Engineer vs. Management Responsibility?
[Question moved from Project Management queue]
I have a question from a developer perspective. I am currently on a team where I likely have the most advanced technical skills, and the management team has little to no development experience. This frequently leaves me in a position where I am on my own. At times, I get asked by management for advice on projects from a technical perspective, which is expected. However, the consultation and support that I have been giving lately seems to be overlapping what seems like should be management responsibility. I received a question from management the other day, and it kind of threw me off, so I am wondering if others can offer advice.
I was asked by a manager as to whether our department should merge with another department, that has their own database/server implementation, but is currently operating as a completely separate unit from ours. It is not like two units who are working side-by-side that could benefit simply by coordinating more. This would be a big change to absorb the technical support for a business unit into an IT division. I expressed that the overall vision would have some benefits, though I was concerned about the feasibility and planning to make it happen. I basically referred the manager to my director and told the manager that the issue was above my level.
The things that are going through my mind are all of the steps that I think typically a manager would be heavily involved in, such as a budget analysis, funding acquisition, resource/staffing analysis, project plan, work breakdown structure, and architecture, just to start. Most of this seems like it would be management tasks, except for needing advice on the architecture. I was recently promoted to a more senior role, and I know part of my job is to give advice. Usually this has been from a more technical perspective, though. Sometimes senior engineers do provide feedback from a staffing perspective, though this seemed like too much was being asked of me.
I was curious to get others' thoughts. Is this the kind of question that would normally fall into the responsibility of a senior software engineer? What other options would I have to handle situations like this in the future? Any advice would be appreciated.
A:
This is the type of question I as a manager would ask my lead and/or most valued employees if I knew the topic would or has come up for discussion.
Being a senior developer with technical skills higher then your manager would allow the manager to gain insite into the feasablity of the move from a technical standpoint. Since you would be in a position to point out pitfalls or areas of conern that he may not be able to see or know about.
I would not expect anything less of my manager. One would not be happy if such a merger would happen without any consultation with the senior developers.
Hope this helps.
A:
Yes this is an entirely appropriate question. As you move up in seniority, you are often asked to go beyond the technicalities of your job and into the technicalities of the next higher job or from the needs of your individual unit to the needs of the business as a whole. Someone needs to be able to analyze situations like this and apparently, your boss thinks you are the best person he has available. I would have been highly insulted if I was not asked to provide input into such a consolidation that could affect my ability to do my job if I were in your position. It is a compliment to your technical ability that you were asked.
This is also part of grooming people for promotion. Your career development should always include doing some tasks that would normally be done at a higher level, that is part of how you gain those skills and your performance on them is part of how management decides who is and isn't ready for the next step up.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pronounce "×" in "12 × 3 mm²"?
I have this expression:
12 × 3 mm².
I guess that it should not be pronounced as "twelve multiplied by three millimeters squared". I've tried to google it already but it seemed to be difficult because of my lack of proficiency in searching keywords.
Note that 12 x 3 should be pronounced in the same way as shape e.g. 4x2 rectangle (rectangle with width = 4 and height = 2).
A:
'by' as in 12 by 3 square millimeters
A:
If it is describing the size of a single rectangular shape, then by is the correct pronunciation.
If it is describing a number of squares, then you can leave it silent.
12 3 millimeter squares.
If it is a scalar multiplied to a square unit in a mathematical calculation, then times can be used.
12 times 3 mm2
| {
"pile_set_name": "StackExchange"
} |
Q:
To Show Push Notification content into the Alert Dialog when application is either running or not in android
I am new for the Android.
Currently, I have integrated GCM Functionality into the my android application. I got the push notification very well from my 3rd party-server application.
But now my problem is that whenever push notification is comes it shows into the Notification Bar area and when I click on that notification it simply disappear as expected.
But I want the functionality that when user clicks on the push notification into the notification bar it will shows a pop-up and shows notification content into that pop-up.
I want this functionality either the application is running or not.
i.e. If the application is not running, then by clicking the notification it will automatically shown the alert on the application's first activity.
And if application is already running, then it will shows the alert box on the current activity of the application.
Currently my application has 7 activities.
A:
try Using Pending Intent in android with activity as Dialog theme . the link will help u how to use pending intents help
| {
"pile_set_name": "StackExchange"
} |
Q:
What did C-3PO say in a foreign language?
I didn't hear this clearly when I went to see The Rise of Skywalker, but...
What did C-3PO say in the Sith language?
The best I could find online is:
So of course, C-3PO courageously sacrifices his memories to save his friends, and for a second his eyes gleam bright red -- as seen in the trailers -- as he recites the coordinates of Exegol and the Sith Fleet.
Star Wars: C-3PO’s Biggest Limitation in Rise of Skywalker Makes NO Sense
I'm even more confused, since I thought we needed the Sith wayfinder to get to Exegol, and not just "directions":
C-3PO: Oh, I read it, sir. I know exactly where the wayfinder is. Unfortunately, it is written in the runic language of the Sith.
Star Wars: The Rise of Skywalker Best Quotes – ‘No one’s ever really gone.’
A:
C-3PO isn't giving them the directions to Exegol, he says that they can find another Wayfinder at the site of the crashed Death Star II.
"The Emperor's Wayfinder is in the Imperial Vault. At Delta 3 6, Transient 9 3 6, Bearing 3 2, on a moon in the Endor System. From the Southern shore, only this blade tells".
The Emperor's Wayfinder will then give them the directions and transit points to get to Exegol.
A:
What C-3PO read on the blade was where to find the Wayfinder, not directions to Exegol.
He recites instructions where to find the Wayfinder including if I remember correctly that it is a vault in the Emporer's throne room on the remains of the Death Star.
| {
"pile_set_name": "StackExchange"
} |
Q:
how many ways can I reach Q from P?
without passing trough the same path again how many paths are from P to Q?
The answer is B) but I don't know how to solve the problem
A:
We want know how many distinct paths are there from $P$ to $Q$ such that no backtracking is done.
Starting at $P$ (the top of the head of what looks like a teddy bear) we have $2$ choices (go left or right). At the ear we have $3$ choices (go around the ear clockwise, go around the ear counterclockwise, or not going into the ear at all). At the neck we have $2$ choices again. At either arm we have $3$ choices again. And at either leg we have $3$. We arrive at the... umm... point $Q$.
This gives $2\cdot 3 \cdot 2 \cdot 3 \cdot 3 =108$.
| {
"pile_set_name": "StackExchange"
} |
Q:
algorithm of sorting d sorted arrays
Please help to understand the running time of the following algorithm
I have d already sorted arrays (every array have more than 1 element) with total n elements.
i want to have one sorted array of size n
if i am not mistaken insertion sort is running linearly on partially sorted arrays
if i will concatenate this d arrays into one n element array and sort it with insertion sort
isn't it a partially sorted array and running time of insertion sort on this array wont be O(n) ?
A:
Insertion sort is O(n²), even when original array is concatenation of several presorted arrays. You probably need to use mergesort to combine several sorted arrays into one sorted array. This will give you O(n·ln(d)) performance
| {
"pile_set_name": "StackExchange"
} |
Q:
SVN Commits and Eclipse
I am using SVN for the first time. I was given a repo which contained several directories, one of which was a Java program directory, the others were various other things.
I used the Eclipse SVN plugin to checkout the repo, and only checked out the relevant Java subdirectory into Eclipse (the other directories were irrelevant for my purpose).
Now I have done the changes to this directory.
Am I right in thinking that if I "commit" the updates, the new head will be created with the updated Java directory AND all the other directories? What I am worried about is losing the other directories.
A:
It should work perfectly fine. Just ensure that your "commit" happens only in the relevant sub-directory that you have checked out via Eclipse.
| {
"pile_set_name": "StackExchange"
} |
Q:
Disconnected no supported authentication methods available
Yes, I'm aware questions like this already exist, and I've already checked quite a few out, but the methods were unable to help me. I am running CentOS 6 on my VPS. This error occurs when I try to log into the username while connecting with PuTTY.
I am trying to log into a user. The path is /home/[name].
Here are my sshd_config settings (it's not on default port):
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_key
PasswordAuthentication no
ChallengeResponseAuthentication no
The authorized_key contains the public key. I am relatively new to Linux, so any tips would be appreciated.
EDIT: I've tried adding the private key to PuTTY, and now it just says "Server refused our key", and the same error message pops up.
A:
Linux is very sensitive to permissions settings.
From your home directory, you should have the following:
user@server:~$ ls -alF .ssh/
drwxr-xr-x 2 user user 4096 Oct 30 04:39 ./
drwxr-x--- 5 user user 4096 Nov 5 15:50 ../
-rw------- 1 user user 1457 Oct 30 00:55 authorized_keys
| {
"pile_set_name": "StackExchange"
} |
Q:
Indicator functions, $I_A=\sum_i I_{A\cap B_i}$
In my textbook it says something I don't quite understand regarding indicator functions:
$$I_A(\omega)=\left\{ \begin{array}{ccc} 1 &\mbox{if}& \omega\in A \\ 0&\mbox{if}& \omega\notin A\end{array} \\ \right.$$
Then, suppose:
$ \{B_i: i\in I\} $ is a family of disjoint evens with $A\subseteq \bigcup_{i \in I} B_i$ then:
$$I_A=\sum_i I_{A\cap B_i}$$
I don't understand this at all, we're saying that A is a subset of the union of $B_i$, that's as far as I get it. As I understand it, the indicator function can be 1 or 0, so what does it mean when $I_A$ is the sum of the indicator functions of the intersections of A and $B_i$? If anyone can explain this with an example I'd be very grateful.
Thank you.
A:
The given identity means for every $x$,
$$I_A(x) = \sum_i I_{A\cap B_i}(x).$$
Let's look at it case by case. If $I_A(x) = 0$ then $x \not\in A \implies x \not\in A\cap B_i$, so $I_{A\cap B_i} = 0$. Clearly, both sides of the sum are zero.
If $I_A(x) = 1$ then $x \in A \implies x \in \cup_i B_i$ (as $A \subseteq \cup_i B_i$). So $x$ must be one of $B_i$'s, say in $B_j$. But if $x$ is in $B_j$ it cannot be in any $B_i$'s when $i \neq j$ (as $B_i's$ are disjoint). Thus, $I_{A\cap B_i} = 0$ unless $i = j$ in which case it is $1$. On the RHS, you are adding up one $1$ and a bunch of $0$'s, thus both sides give $1$.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits