title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Grep apache server 500 errors to a separate file
|
<p>Hi I am trying to tail apache access logs and copy the errors to another file. I tried below options and all are working in command line but when triggered from a script they are not working.</p>
<p>I understand the tail command is not exiting and so there is no output. But not sure how to overcome this.</p>
<pre><code>/usr/bin/tail -f /apps/apache/logs/access_log | grep -h "HTTP\/1.1\" 50." >> /tmp/log_error_capture.txt
grep -m 1 "HTTP\/1.1\" 50." <(tail -f /apps/apache/logs/access_log)
( tail -f -n0 /apps/apache/logs/access_log & ) | grep -q "HTTP\/1.1\" 50." > /tmp/log_error_capture.txt
tail -f logfile |grep -m 1 "HTTP\/1.1\" 50." | xargs echo "" >> logfile \;
</code></pre>
<p>Can someone suggest a better way to grep the errors. Please.</p>
| 0 |
How to send Accept Encoding header with curl in PHP
|
<p>How to send Accept Encoding header with with curl in PHP </p>
<pre><code> $data=json_encode($data);
$url = 'url to send';
$headers = array(
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSLVERSION, 4);
$datas = curl_exec($ch);
curl_close($ch);
</code></pre>
<p>How to Decompress the response </p>
| 0 |
Convert ES6 JavaScript to ES5 without transpiler
|
<p>I am not familiar with new JavaScript ES6 coding conventions and have been given some code where I need it to be plain old JavaScript ES5.</p>
<p>I need to convert this JS code without the use of Babel or any other transpiler. I cannot use Babel as I am not allowed to use it at work. </p>
<p>I realise that all the "const" can be converted to "var" but unsure of new arrow functions and other items. </p>
<p>I have tried converting but getting:</p>
<blockquote>
<p>Uncaught ReferenceError: line is not defined</p>
</blockquote>
<p>The ES6 code that I would like converted to ES5 is:</p>
<pre><code>const data = [{ "rec": "1", "region": "LEFT", "intrface": "Line-1" },{ "rec": "1", "region": "LEFT", "intrface": "Line-2" },{ "rec": "1", "region": "RIGHT", "intrface": "Line-3" },{ "rec": "1", "region": "RIGHT", "intrface": "Line-4" }];
const s = Snap("#svg");
const height = 40;
const canvasWidth = 400;
const lineWidth = 180;
const rightOffset = canvasWidth/2 - lineWidth;
const leftLines = data.filter((line) => !isRightLine(line));
const rightLines = data.filter(isRightLine);
leftLines.forEach(drawLine);
rightLines.forEach(drawLine);
const numberOfLines = Math.max(leftLines.length, rightLines.length);
const rectSize = 20;
const rectangles = [];
for (let i = 0; i < numberOfLines; i++) {
rectangles.push(drawRect(i));
}
function drawLine(data, index) {
const {intrface} = data;
const isRight = isRightLine(data);
const x = isRight ? canvasWidth/2 + rightOffset : 0;
const y = height * (index + 1);
const stroke = isRight ? 'red' : 'black';
const line = s.line(x, y, x + 180, y);
line.attr({
stroke,
strokeWidth: 1
});
const text = s.text(x + 10, y - 5, intrface);
text.attr({
fill: stroke,
cursor: 'pointer'
});
text.click(() => {
console.log('clicked', data);
//window.location.href = "http://stackoverflow.com/";
});
}
function isRightLine({region}) {
return region === 'RIGHT';
}
function drawRect(index) {
const x = canvasWidth/2 - rectSize/2;
const y = height * (index + 1) - rectSize/2;
const rectangle = s.rect(x, y, rectSize, rectSize);
rectangle.attr({
fill: 'black'
});
console.log('rr', x, y);
return rectangle;
}
</code></pre>
| 0 |
How can I send a Firebase Cloud Messaging notification without use the Firebase Console?
|
<p>I'm starting with the new Google service for the notifications, <code>Firebase Cloud Messaging</code>. </p>
<p>Thanks to this code <a href="https://github.com/firebase/quickstart-android/tree/master/messaging">https://github.com/firebase/quickstart-android/tree/master/messaging</a> I was able to send notifications from my <strong>Firebase User Console</strong> to my Android device.</p>
<p>Is there any API or way to send a notification without use the Firebase console? I mean, for example, a PHP API or something like that, to create notifications from my own server directly.</p>
| 0 |
Unable to install vim or nano inside docker container
|
<p>Trying to install inside a docker, either vim or nano but I only get this:</p>
<pre><code>0% [Connecting to archive.ubuntu.com (91.189.88.152)]
</code></pre>
<p>Exit docker and do <code>ping archive.ubuntu.com</code> and I get reply, do the same time inside docker it does not respond. </p>
<p>What could be the problem?</p>
| 0 |
convert string to number node.js
|
<p>I'm trying to convert req.params to Number because that is what I defined in my schema for year param.</p>
<p>I have tried</p>
<pre><code>req.params.year = parseInt( req.params.year, 10 );
</code></pre>
<p>and</p>
<pre><code>Number( req.params.year);
</code></pre>
<p>and</p>
<pre><code>1*req.params.year;
</code></pre>
<p>but non of them works.
Do I need to install something?</p>
| 0 |
Is it safe to expose Firebase apiKey to the public?
|
<p>The <a href="https://firebase.google.com/docs/web/setup#add_firebase_to_your_app" rel="noreferrer">Firebase Web-App guide</a> states I should put the given <code>apiKey</code> in my Html to initialize Firebase:</p>
<pre class="lang-html prettyprint-override"><code>// TODO: Replace with your project's customized code snippet
<script src="https://www.gstatic.com/firebasejs/3.0.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
storageBucket: '<your-storage-bucket>'
};
firebase.initializeApp(config);
</script>
</code></pre>
<p>By doing so, the <code>apiKey</code> is exposed to every visitor.</p>
<p>What is the <strong>purpose of that key</strong> and is it really <strong>meant to be public</strong>?</p>
| 0 |
How to solve conflicts about project.pbxproj in Xcode use git?
|
<p>I always solved this problem by using directory structure of the other members shall prevail ,and then confirm don't have any conflicts and mend it to what directory structure I want.</p>
<p>So, I want to know, the <code>project.pbxproj</code> file have conflicts, how to solve it through other best way? </p>
| 0 |
How to encrypt password for cURL command in shell script. -u option cannot be used
|
<p>I am using cURL command in a shell script. If I use curl with <code>-u login:password</code> option, we can have access to these login and password as they are visible to anyone.</p>
<p>Is there way to make password not clear in script file (or encrypt and decrypt it)?</p>
| 0 |
Domain is currently unable to handle this request 500
|
<p>[domain] is currently unable to handle this request. When I try to install IPBoard, iv'e installed IPBoard multiple times on multiple servers and never had this issue, but maybe iv'e missed something out that I ain't noticed.</p>
<p>I have installed LAMP</p>
<p>Linux - Centos 7
Apache2
MySQL
PHP - 5.4</p>
<p>and then I allowed 10000 // 80 // 433 for Webmin and Apache and I put a simple home.html and info.php files in the /var/www/html/ directory and both load the pages correctly.</p>
<p>But when I upload the files from IPBoard to /var/www/html/ via FTP (filezilla) and load the webpage I just get 'Domain is currently unable to handle this request 500' and I'm not sure why maybe config in the PHP or something ? </p>
<p>Any help is great thanks!</p>
<p>Error log:</p>
<p>PHP Fatal error: Call to undefined function IPS\mb_internal_encoding() in /var/www/html/init.php on line 124</p>
<p>line 124:</p>
<p>mb_internal_encoding('UTF-8');</p>
| 0 |
Bootstrap 4 accepting offset-md-*, instead col-offset-md-* Naming Convention Bug
|
<p>I'm just a beginner in Bootstrap 4.</p>
<p>I just started learning it recently and sadly, I have been encountering problems already. I modified some code from the Bootstrap 4 manual itself. However, it fails miserably, with the offset not working properly. The code is perfectly simple and doesn't require a lot of code though. </p>
<h2>EDIT: MAY 25, 2016 [12:35 PM (GMT+8)]:</h2>
<h3>Using Boootrap 3.3.6 release, col-md-offset-* is working. However, it is in Bootrap 4 that has failure.</h3>
<h3>Issue has been posted on <a href="https://github.com/twbs/bootstrap/issues/19966" rel="nofollow noreferrer">https://github.com/twbs/bootstrap/issues/19966</a>!</h3>
<p>This is the code I used:</p>
<pre><code> <!-- This contains the .red, .blue and .green classes -->
<style> ... </style>
<div class="container">
<div class="row">
<div class="col-md-4 red">
Hello world
</div>
<div class="col-md-4 col-offset-md-4 green">
Hello world
</div>
<div class="col-md-4 col-offset-md-4 blue">
Hello world
</div>
</div>
</code></pre>
<p></p>
<hr>
<p>So, I doubted that there is in fact a class in bootstrap called "col-md-offset-*" as it fails to work. So, in Safari, I opened Develop > Show Web Inspector and took a look at the Bootstrap file that is linked via CDN. I searched for the class <code>col-md-offset-4</code>, and it didn't appear. However, I saw <code>md-offset-4</code> instead. I also saw that instead of the class <code>col-md-push-4</code>, all I found is <code>md-push-4</code> and so on and so forth. Therefore, I instead used the <code>md-push-4</code> and it worked as good as the example in Bootstrap.</p>
<h2>EDIT: MAY 25, 2016 [9:03 PM (GMT+8)]:</h2>
<p>This addresses answer by user Nate Conley. By the way, this was taken from <a href="http://v4-alpha.getbootstrap.com/layout/grid/" rel="nofollow noreferrer">http://v4-alpha.getbootstrap.com/layout/grid/</a> as of the time this question was edited. Any change of the Bootstrap team is unforeseen or unknown at this time of writing.</p>
<p><a href="https://i.stack.imgur.com/8bEHW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8bEHW.png" alt="Documentation Code Sample"></a></p>
<p><a href="https://i.stack.imgur.com/adlPX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/adlPX.png" alt="Code found in Bootsrap 1"></a></p>
<p><a href="https://i.stack.imgur.com/XU58M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XU58M.png" alt="Code found in Bootstrap 2"></a></p>
<h1>Therefore, I modified the code and it works perfectly fine.</h1>
<pre><code><style> ... </style>
<div class="container">
<div class="row">
<div class="col-md-4 red">
Hello world
</div>
<div class="col-md-4 offset-md-4 green">
Hello world
</div>
<div class="col-md-4 offset-md-4 blue">
Hello world
</div>
</div>
</code></pre>
<p></p>
<h1>Q: Is the problem with my browser, Safari (9.1), or with Bootstrap version 4, maxcdn, etc.? Is this a normal bug in Bootstrap 4?</h1>
| 0 |
Why were literal formatted strings (f-strings) so slow in Python 3.6 alpha? (now fixed in 3.6 stable)
|
<p>I've downloaded a Python 3.6 alpha build from the Python Github repository, and one of my favourite new features is literal string formatting. It can be used like so:</p>
<pre><code>>>> x = 2
>>> f"x is {x}"
"x is 2"
</code></pre>
<p>This appears to do the same thing as using the <code>format</code> function on a <code>str</code> instance. However, one thing that I've noticed is that this literal string formatting is actually very slow compared to just calling <code>format</code>. Here's what <code>timeit</code> says about each method:</p>
<pre><code>>>> x = 2
>>> timeit.timeit(lambda: f"X is {x}")
0.8658502227130764
>>> timeit.timeit(lambda: "X is {}".format(x))
0.5500578542015617
</code></pre>
<p>If I use a string as <code>timeit</code>'s argument, my results are still showing the pattern:</p>
<pre><code>>>> timeit.timeit('x = 2; f"X is {x}"')
0.5786435347381484
>>> timeit.timeit('x = 2; "X is {}".format(x)')
0.4145195760771685
</code></pre>
<p>As you can see, using <code>format</code> takes almost half the time. I would expect the literal method to be faster because less syntax is involved. What is going on behind the scenes which causes the literal method to be so much slower?</p>
| 0 |
Notification Icon with the new Firebase Cloud Messaging system
|
<p>Yesterday Google presented at Google I/O the new notification system based on the new Firebase. I tried this new FCM ( Firebase Cloud Messaging ) with the example on Github.</p>
<p><strong>The icon of the notification is always the <em>ic_launcher</em> despite I have declared a specific drawable</strong></p>
<p>Why ?
Here below the official code for handling the message</p>
<pre><code>public class AppFirebaseMessagingService extends FirebaseMessagingService {
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
sendNotification(remoteMessage);
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* @param remoteMessage FCM RemoteMessage received.
*/
private void sendNotification(RemoteMessage remoteMessage) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// this is a my insertion looking for a solution
int icon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.myicon: R.mipmap.myicon;
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(icon)
.setContentTitle(remoteMessage.getFrom())
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
</code></pre>
| 0 |
PHP How can I do multiple where conditions?
|
<p>This is my current code for taking a user log in:</p>
<pre><code><?php
$uName = "";
$uNameMsg = "";
$pWord = "";
$pWordMsg = "";
if(isset($_POST["submit"])){
$uName = $_POST["username"];
if (empty($uName)) {
$uNameMsg = "please enter a username<br/>";
}
$pWord = $_POST["password"];
if (empty($pWord)) {
$pWordMsg = "please enter a password<br/>";
}
}
?>
//form goes here
<?php
require_once("conn.php");
$sql = "SELECT username, password FROM customers
WHERE username = $uName
AND password = $pWord";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
if (mysqli_num_rows($results) < 1) {
echo "invalid username and password";
} else {
echo "query success, redirect header goes here";
}
?>
</code></pre>
<p>I get a syntax error saying that the 'AND password =' clause is wrong. and then it is saying that the error is located at line 3, my tag, while the 'AND password ='is in line 75.</p>
<p>this is the start of my code from line 1:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Customer Login</title>
<link rel="stylesheet" href="customerlogin.css">
</head>
</code></pre>
| 0 |
dlib vs opencv which one to use when
|
<p>I am currently learning OpenCV API with Python and its all good. I am making decent progress. Part of it comes from Python syntax's simplicity as against using it with C++ which I haven't attempted yet. I have come to realize that I have to get dirty with C++ bindings for OpenCV at some point if I intend to do anything production quality.</p>
<p>Just recently I came across dlib which also claims to do all the things OpenCV does and more. Its written in C++ and offers Python API too (surprise). Can anybody vouch for dlib based on their own implementation experience?</p>
| 0 |
Azure Service Fabric: cannot run local Service Fabric Cluster
|
<p>I have a problem with Azure Service Fabric.</p>
<p>I have installed it (on Windows 7) as it was said in <a href="https://azure.microsoft.com/en-gb/documentation/articles/service-fabric-get-started/" rel="noreferrer">https://azure.microsoft.com/en-gb/documentation/articles/service-fabric-get-started/</a>.</p>
<p>Then I have tried to run a Service Fabric application from Visual Studio 2015. I got an error “<strong>Connect-ServiceFabricCluster : No cluster endpoint is reachable, please check if there is connectivity/firewall/DNS issue</strong>”.</p>
<p>Here is the fill log of that run:</p>
<pre><code>1>------ Build started: Project: Application2, Configuration: Debug x64 ------
2>------ Deploy started: Project: Application2, Configuration: Debug x64 ------
-------- Package started: Project: Application2, Configuration: Debug x64 ------
Application2 -> c:\temp\Application2\Application2\pkg\Debug
-------- Package: Project: Application2 succeeded, Time elapsed: 00:00:01.7361084 --------
2>Started executing script 'Set-LocalClusterReady'.
2>Import-Module 'C:\Program Files\Microsoft SDKs\Service Fabric\Tools\Scripts\DefaultLocalClusterSetup.psm1'; Set-LocalClusterReady
2>--------------------------------------------
2>Local Service Fabric Cluster is not setup...
2>Please wait while we setup the Local Service Fabric Cluster. This may take few minutes...
2>
2>Using Cluster Data Root: C:\SfDevCluster\Data
2>Using Cluster Log Root: C:\SfDevCluster\Log
2>
2>Create node configuration succeeded
2>Starting service FabricHostSvc. This may take a few minutes...
2>
2>Waiting for Service Fabric Cluster to be ready. This may take a few minutes...
2>Local Cluster ready status: 4% completed.
2>Local Cluster ready status: 8% completed.
2>Local Cluster ready status: 12% completed.
2>Local Cluster ready status: 17% completed.
2>Local Cluster ready status: 21% completed.
2>Local Cluster ready status: 25% completed.
2>Local Cluster ready status: 29% completed.
2>Local Cluster ready status: 33% completed.
2>Local Cluster ready status: 38% completed.
2>Local Cluster ready status: 42% completed.
2>Local Cluster ready status: 46% completed.
2>Local Cluster ready status: 50% completed.
2>Local Cluster ready status: 54% completed.
2>Local Cluster ready status: 58% completed.
2>Local Cluster ready status: 62% completed.
2>Local Cluster ready status: 67% completed.
2>Local Cluster ready status: 71% completed.
2>Local Cluster ready status: 75% completed.
2>Local Cluster ready status: 79% completed.
2>Local Cluster ready status: 83% completed.
2>Local Cluster ready status: 88% completed.
2>Local Cluster ready status: 92% completed.
2>Local Cluster ready status: 96% completed.
2>Local Cluster ready status: 100% completed.
2>WARNING: Service Fabric Cluster is taking longer than expected to connect.
2>
2>Waiting for Naming Service to be ready. This may take a few minutes...
2>Connect-ServiceFabricCluster : **No cluster endpoint is reachable, please check
2>if there is connectivity/firewall/DNS issue.**
2>At C:\Program Files\Microsoft SDKs\Service
2>Fabric\Tools\Scripts\ClusterSetupUtilities.psm1:521 char:12
2>+ [void](Connect-ServiceFabricCluster @connParams)
2>+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2> + CategoryInfo : InvalidOperation: (:) [Connect-ServiceFabricClus
2> ter], FabricException
2> + FullyQualifiedErrorId : TestClusterConnectionErrorId,Microsoft.ServiceFa
2> bric.Powershell.ConnectCluster
2>
2>Naming Service ready status: 8% completed.
2>Naming Service ready status: 17% completed.
2>Naming Service ready status: 25% completed.
2>Naming Service ready status: 33% completed.
2>Naming Service ready status: 42% completed.
2>Naming Service ready status: 50% completed.
2>Naming Service ready status: 58% completed.
2>Naming Service ready status: 67% completed.
2>Naming Service ready status: 75% completed.
2>Naming Service ready status: 83% completed.
2>Naming Service ready status: 92% completed.
2>Naming Service ready status: 100% completed.
2>WARNING: Naming Service is taking longer than expected to be ready...
2>Local Service Fabric Cluster created successfully.
2>--------------------------------------------------
2>Launching Service Fabric Local Cluster Manager...
2>You can use Service Fabric Local Cluster Manager (system tray application) to manage your local dev cluster.
2>Finished executing script 'Set-LocalClusterReady'.
2>Time elapsed: 00:07:01.8147993
2>The PowerShell script failed to execute.
========== Build: 1 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 1 failed, 0 skipped ==========
</code></pre>
| 0 |
Cannot find module dtrace-provider
|
<p>I have a simple nodejs application that is throwing <code>"Cannot find module './build/Release/DTraceProviderBindings'"</code>. I look it up online and it looks like that a lot of people are having the same problem when using restify on windows (which is my case, I'm using restify on windows 10). Apparently, <a href="https://github.com/restify/node-restify/issues/100" rel="noreferrer">dtrace-provider is a optional module for restify</a> and there is no version of it for windows. So, what I tried so far:</p>
<ol>
<li>Update node to v6.2.0;</li>
<li>Uninstall all modules and run <code>npm install --no-optional</code>;</li>
<li>Uninstall only restify and run <code>npm install restify --no-optional</code>;</li>
<li>And my most desperate move npm install <code>dtrace-provider</code>.</li>
</ol>
<p>Everything I tried where found on github issues, I've seen same error on OSX users with other modules. Not sure what else to try.</p>
<p>Note: This exception does not stop my application, not even prints the error on the console, I just notice that this was happening using the debugger, in other words, my application runs fine, but this keeps happening on the background.</p>
<p>List of other modules I'm using:</p>
<pre><code>"dependencies": {
"restify": "latest",
"request": ">=2.11.1",
"cheerio": ">=0.10.0",
"xml2js": ">=0.2.0",
"botbuilder": "^0.11.1",
"applicationinsights": "latest"
}
</code></pre>
| 0 |
How to import Scipy and Numpy in Python?
|
<p>I am very new to Python and want to add Numpy and Scipy module. I think my question is very simple for you. I am using Python 3.06a.1 version. I think I already installed something called Anaconda that contains those library. When I type import scipy I get the following message:</p>
<pre><code>import scipy
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
import scipy
ImportError: No module named 'scipy'
</code></pre>
<p>also when I want to installed with command line I get the following message which means that I have it already. </p>
<pre><code> localhost:~ user$ pip install scipy
Requirement already satisfied (use --upgrade to upgrade): scipy in ./anaconda/lib/python3.5/site-packages
localhost:~ user$
</code></pre>
<p>Please help me to fix this problem</p>
| 0 |
Symfony ArrayCollection vs PersistentCollection
|
<p>As I understood when you query database by repository you get PersistentCollection and when your working with your entities you get ArrayCollection.</p>
<p>so consider I have one to many self referencing relation for my user entity.</p>
<p>and in my user entity I have a setChildren method which get ArrayCollection of users as argument .</p>
<pre><code><?php
namespace UserBundle\Entity;
use Abstracts\Entity\BaseModel;
use CertificateBundle\Entity\Certificate;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use EducationBundle\Entity\Education;
use LanguageBundle\Entity\Language;
use PostBundle\Entity\Post;
use ProfileBundle\Entity\Company;
use RoleBundle\Entity\Role;
use SkillBundle\Entity\Skill;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* User
*
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="UserBundle\Repository\Entity\UserRepository")
* @UniqueEntity("email")
* @UniqueEntity("username")
*/
class User implements UserInterface
{
use BaseModel;
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="type", type="string", columnDefinition="ENUM('merchant', 'company', 'customer') ")
*/
private $type;
/**
* @ORM\Column(type="string", unique=true)
* @Assert\NotBlank()
*/
private $username;
/**
* @var string
*
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank()
*/
private $email;
/**
* @var string
* @ORM\Column(type="string", nullable=true)
*/
private $avatar = null;
/**
* @var string
* @ORM\Column(type="string", nullable=true)
*/
private $cover = null;
/**
* @ORM\OneToMany(targetEntity="PostBundle\Entity\Post", mappedBy="user", orphanRemoval=true, cascade={"persist", "remove"})
*/
private $posts;
/**
* @ORM\OneToMany(targetEntity="EducationBundle\Entity\Education" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $educations;
/**
* @ORM\OneToMany(targetEntity="SkillBundle\Entity\SkillUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $skills;
/**
* @ORM\OneToMany(targetEntity="LanguageBundle\Entity\LanguageUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $languages;
/**
* @ORM\OneToMany(targetEntity="ResumeBundle\Entity\Resume" , mappedBy="user" , cascade={"all"})
*/
protected $resumes;
/**
* @ORM\OneToMany(targetEntity="CertificateBundle\Entity\CertificateUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $certificates;
/**
* @ORM\OneToOne(targetEntity="ProfileBundle\Entity\Company", mappedBy="user")
*/
protected $company;
/**
* @ORM\OneToOne(targetEntity="ProfileBundle\Entity\Customer", mappedBy="user")
*/
protected $customer;
/**
* @ORM\OneToOne(targetEntity="ProfileBundle\Entity\Merchant", mappedBy="user")
*/
protected $merchant;
/**
* @var string
* @Assert\NotBlank()
* @Assert\Length(min=4)
* @ORM\Column(name="password", type="string", length=255)
*
*/
private $password;
/**
* @ORM\ManyToMany(targetEntity="RoleBundle\Entity\Role", inversedBy="users", cascade={"persist"})
* @ORM\JoinTable(name="user_role", joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")}, inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")})
*/
private $roles;
/**
* @ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
*/
protected $parent;
/**
* @ORM\OneToMany(targetEntity="UserBundle\Entity\User", mappedBy="parent", orphanRemoval=true, cascade={"persist", "remove"})
*
*/
protected $children;
/**
* @var array
*/
public static $fields = [ 'email', 'username', 'id', 'avatar', 'cover', 'type'];
/**
* User Entity constructor.
*/
public function __construct(/*EncoderFactoryInterface $encoderFactory*/)
{
//$this->encoderFactory = $encoderFactory;
$this->posts = new ArrayCollection();
$this->skills = new ArrayCollection();
$this->languages = new ArrayCollection();
$this->certificates = new ArrayCollection();
$this->educations = new ArrayCollection();
$this->children = new ArrayCollection();
dump($this->children);
die();
}
/**
* @param User $user
* @return $this
*/
public function setParent(User $user)
{
$this->parent = $user;
return $this;
}
/**
* @return $this
*/
public function removeParent()
{
$this->parent = null;
return $this;
}
/**
* @param User $user
* @return $this
*/
public function addChild(User $user)
{
if(!$this->children->contains($user)){
$this->children->add($user);
}
return $this;
}
/**
* @param User $user
* @return bool
*/
public function hasChild(User $user)
{
return $this->children->contains($user);
}
/**
* @param User $user
* @return bool
*/
public function isChildOf(User $user)
{
return $user->getChildren()->contains($this);
}
/**
* @return ArrayCollection
*/
public function getChildren()
{
return $this->children;
}
/**
* @param User $user
* @return $this
*/
public function removeChild(User $user)
{
if($this->children->contains($user)){
$this->children->removeElement($user);
}
return $this;
}
/**
* @param ArrayCollection $users
* @return $this
*/
public function setChildren(ArrayCollection $users)
{
$this->children = $users;
return $this;
}
/**
* @return $this
*/
public function removeChildren()
{
$this->children->clear();
return $this;
}
/**
* @param ArrayCollection $certificates
* @return $this
*/
public function setCertificates(ArrayCollection $certificates)
{
$this->certificates = $certificates;
return $this;
}
/**
* @param Certificate $certificate
* @return $this
*/
public function addCertificate(Certificate $certificate)
{
if(!$this->certificates->contains($certificate))
$this->certificates->add($certificate);
return $this;
}
/**
* @param Certificate $certificate
* @return $this
*/
public function removeCertificate(Certificate $certificate)
{
if($this->certificates->contains($certificate))
$this->certificates->removeElement($certificate);
return $this;
}
/**
* @return $this
*/
public function removeCertificates()
{
$this->certificates->clear();
return $this;
}
/**
* @param ArrayCollection $skills
* @return $this
*/
public function setSkills(ArrayCollection $skills)
{
$this->skills = $skills;
return $this;
}
/**
* @param Skill $skill
* @return $this
*/
public function addSkill(Skill $skill)
{
if(!$this->skills->contains($skill))
$this->skills->add($skill);
return $this;
}
/**
* @param Skill $skill
* @return $this
*/
public function removeSkill(Skill $skill)
{
if($this->skills->contains($skill))
$this->skills->removeElement($skill);
return $this;
}
/**
* @return $this
*/
public function removeSkills()
{
$this->skills->clear();
return $this;
}
/**
* @param ArrayCollection $languages
* @return $this
*/
public function setLanguages(ArrayCollection $languages)
{
$this->languages = $languages;
return $this;
}
/**
* @param Language $language
* @return $this
*/
public function addLanguage(Language $language)
{
if(!$this->languages->contains($language))
$this->languages->add($language);
return $this;
}
/**
* @param Language $language
* @return $this
*/
public function removeLanguage(Language $language)
{
if($this->languages->contains($language))
$this->languages->removeElement($language);
return $this;
}
/**
* @return $this
*/
public function removeLanguages()
{
$this->languages->clear();
return $this;
}
/**
* @param ArrayCollection $posts
* @return $this
*/
public function setPosts(ArrayCollection $posts)
{
$this->posts = $posts;
return $this;
}
/**
* @param Post $post
* @return $this
*/
public function addPost(Post $post)
{
$this->posts->add($post);
return $this;
}
/**
* @param Post $post
* @return $this
*/
public function removePost(Post $post)
{
$this->posts->removeElement($post);
return $this;
}
/**
* @return $this
*/
public function removePosts()
{
$this->posts->clear();
return $this;
}
/**
* @param ArrayCollection $educations
* @return $this
*/
public function setEducations(ArrayCollection $educations)
{
$this->educations = $educations;
return $this;
}
/**
* @param Education $education
* @return $this
*/
public function addEducation(Education $education)
{
$this->educations->add($education);
return $this;
}
/**
* @param Education $education
* @return $this
*/
public function removeEducation(Education $education)
{
$this->educations->removeElement($education);
return $this;
}
/**
* @return $this
*/
public function removeEducations()
{
$this->educations->clear();
return $this;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @param integer $id
* @return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return mixed
*/
public function getType()
{
return $this->type;
}
/**
* @param mixed $type
* @return $this
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Set email
*
* @param string $email
* @return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param $username
* @return $this
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* @return mixed
*/
public function getUsername()
{
return $this->username;
}
/**
* @return array
*/
public function getRoles()
{
return ['ROLE_USER', 'IS_AUTHENTICATED_ANONYMOUSLY'];
}
/**
* @param $password
* @return $this
*/
public function setPassword($password)
{
//$password =$this->encoderFactory->getEncoder($this)->encodePassword($password, $this->getSalt());
$this->password = $password;
return $this;
}
/**
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
*
*/
public function getSalt()
{
return md5(sha1('somesalt'));
}
/**
*
*/
public function eraseCredentials()
{
}
/**
* @param $cover
* @return $this
*/
public function setCover($cover)
{
$this->cover = $cover;
return $this;
}
/**
* @return string
*/
public function getCover()
{
return $this->cover;
}
/**
* @param $avatar
* @return $this
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
return $this;
}
/**
* @return string
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* @param Role $roles
*/
public function addRoles(Role $roles)
{
$this->roles[] = $roles;
}
/**
* @return mixed
*/
public function getRoles2()
{
return $this->roles;
}
/**
* @return array
*/
public function getRolesAsArray()
{
$rolesArray = [];
foreach ($this->getRoles2() as $role) {
$rolesArray[] = $role->getName();
}
return $rolesArray;
}
/**
* @return Company
*/
public function getCompany()
{
return $this->company;
}
/**
* @param Company $company
* @return $this
*/
public function setCompany(Company $company)
{
$this->company = $company;
return $this;
}
}
</code></pre>
<p>and this is what I want to do </p>
<pre><code>$new_owner = $this->userRepository->findOneById($user_id, false);
$children = $old_owner->getChildren();
$old_owner->removeChildren();
$new_owner->setChildren($children);
</code></pre>
<p>and I get error which says :</p>
<blockquote>
<p>Argument 1 passed to
Proxies__CG__\UserBundle\Entity\User::setChildren() must be an
instance of Doctrine\Common\Collections\ArrayCollection, instance of
Doctrine\ORM\PersistentCollection given</p>
</blockquote>
<p>should I change my type hint in setChildren method to PersistentCollection ??
or I need to totally change my approach?</p>
| 0 |
Database schema design for posts, comments and replies
|
<p>In my previous project I had posts and comments as two tables:</p>
<p>post</p>
<ul>
<li>id</li>
<li>text</li>
<li>timestamp</li>
<li>userid</li>
</ul>
<p>comment</p>
<ul>
<li>id</li>
<li>message</li>
<li>timestamp</li>
<li>userid</li>
<li>postid</li>
</ul>
<p>Now I've got to design replies to comments. The replies is just one level, so users can only reply to comments, not to replies. The tree structure is only 1 level deep. My first idea was to use the same comment table for both comments and replies. I added a new column though:</p>
<p>comment</p>
<ul>
<li>id</li>
<li>message</li>
<li>timestamp</li>
<li>userid</li>
<li>postid</li>
<li>parentcommentid</li>
</ul>
<p>Replies have parentcommentid set to the parent comment they belong. Parent comments don't have it (null)</p>
<p>Retrieving comments for a given post is simple:</p>
<p>but this time I need another query to find out the comment replies. This has to be done for each comment:</p>
<p>This doesn't seem to be a good solution, is there a way to have a single query which returns the complete list of comments/replies in the correct order? (dictated by the timestamp and the nesting)</p>
| 0 |
PHP ImagickException: not authorized
|
<p>Any ideas how to fix this ?</p>
<pre><code> ImagickException: not authorized `/tmp/magick-1552lvf2nIjaqx1W' @ error/constitute.c/ReadImage/412
</code></pre>
<p>I thought it was a permission issue so just to test it out i set my /tmp dir to 777. No change. Its driving me crazy. </p>
<p>The command :</p>
<pre><code><?php
$image = new \Imagick();
$image->readImageBlob('<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $graph);
</code></pre>
| 0 |
The localhost page isn’t working
|
<p>I am using IIS 7 with oci8 with php and when I am writing </p>
<pre><code>$connection= oci_connect('username', 'password', 'localhost/XE');
</code></pre>
<p>and its showing me error</p>
<blockquote>
<p>The localhost page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500</p>
</blockquote>
<p>help me </p>
| 0 |
Javascript - How to stop pinch zoom, multi touch input attacks?
|
<p>Current Google chrome stable version stopped manually blocking pinch zoom, which was possible in older versions with following settings:</p>
<pre><code>chrome://flags/#enable-pinch
</code></pre>
<p>I am getting attacks in my kiosk from some random pinch zoom/multi touch inputs.</p>
<p>How to tell JavaScript to disable pinch zoom/multi touch? (to protect the kiosk)</p>
<p>I tried following but nothing is stopping the kiosk from ignore pinch zoom attacks.</p>
<pre><code>$(document).ready(function() {
$(document).bind('contextmenu', function() {
console.log('NO NO NO. STOP!!!');
window.location.reload();
return false;
});
$(document).mousedown( function() {
console.log('NO NO NO. STOP!!!');
return false;
});
});
</code></pre>
<p><strong>EDIT:</strong></p>
<p><code>chrome://flags/#enable-pinch</code> - never works anymore in Google chrome. Google should not have removed it and community should have protested to not have it removed.</p>
| 0 |
how to start jvm and can we have multiple jvm running on a single system?
|
<p>I had been asked this question in interview, how to start jvm and can we have multiple jvm running on a single system?</p>
| 0 |
Springboot Whitelabel Error Page
|
<p>I stuck with this simple MVC example. When I start the App and go to localhost:8080, I got "Whitelabel Error Page", even I created "index.html" in "src/main/resources/templates". I also add @RequestMapping("/") on my index method. I can't find the problems.</p>
<p><code>IndexController.java</code>:</p>
<pre><code>package controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/")
public String index(){
return "index";
}
}
</code></pre>
<p><code>SpringmvcApplication.java</code>:</p>
<pre><code>package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringmvcApplication {
public static void main(String[] args) {
SpringApplication.run(SpringmvcApplication.class, args);
}
}
</code></pre>
<p><code>index.html</code> - under "src/main/resources/templates":</p>
<pre><code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Hello Spring MVC</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>Hello World</h1>
<h2>This is my Thymeleaf index page.</h2>
</body>
</html>
</code></pre>
| 0 |
Display all MySQL table data in html table
|
<p>I am trying to display a whole <code>mysql</code> table in an html table. So far I have found the below code which works to display fields:</p>
<pre><code><?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</code></pre>
<p>Is there a way that I can display all columns/rows without having to type all the column names as </p>
<p><code>echo "<td>" . $row['FirstName'] . "</td>";</code></p>
| 0 |
Prediction on Neural Network in R
|
<p>I want to get the accuracy or the <code>RMSE</code> of the Prediction result of a neural network. I started using a Confusion Matrix, but as indicated by previous answers, the Confusion Matrix gives valid results for non Continuous variables. </p>
<p>Is there any way I can get the accuracy or the error rate of a Neural Network Prediction??</p>
<p>As an example here is the code I've got until now: </p>
<pre><code>library(nnet)
library(caret)
library(e1071)
data(rock)
newformula <- perm ~ area + peri + shape
y <- rock[, "perm"]
x <- rock[!colnames(rock)%in% "perm"]
original <- datacol(rock,"perm")
nnclas_model <- nnet(newformula, data = rock, size = 4, decay = 0.0001, maxit = 500)
nnclas_prediction <- predict(nnclas_model, x)
nnclas_tab <- table(nnclas_prediction, y)
rmse <- sqrt(mean((original - nnclas_prediction)^2))
</code></pre>
<p>Does anyone know how can I make this work? or how can I get the Accuracy or the of the Neural Network Prediction?
Any help will be deeply appreciated.</p>
| 0 |
Sed error "command a expects \ followed by text"
|
<p>Here is my script:</p>
<pre><code>openscad $1 -D generate=1 -o $1.csg 2>&1 >/dev/null |
sed 's/ECHO: \"\[LC\] //' |
sed 's/"$//' |
sed '$a;' >./2d_$1
</code></pre>
<p>That output:</p>
<pre><code>sed: 1: "$a;": command a expects \ followed by text
</code></pre>
| 0 |
GoogleSignatureVerifier signature not valid message (google play services 9.0.0)
|
<p>I have recently updated to the google play services library version 9.0.0, and I keep getting the following logcat message:</p>
<pre><code>05-19 23:07:30.023 19237-19508/? V/GoogleSignatureVerifier: options.developer.com.developeroptions signature not valid. Found:
</code></pre>
<p>While my app isn't using the google maps api but it is using the analytics, ads, and google plus apis.</p>
<p>The only mention in the documentation regarding the usage of the api key is when using google maps, or android places api.</p>
<p>I have also tried adding the 'com.google.android.geo.API_KEY' with a correct key but it didn't help.</p>
<p>here is my gradle.build file:</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "options.developer.com.developeroptions"
minSdkVersion 9
targetSdkVersion 23
versionCode 23
versionName "1.06"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile 'com.google.android.gms:play-services-plus:9.0.0'
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.google.android.gms:play-services-analytics:9.0.0'
compile 'com.google.android.gms:play-services-ads:9.0.0'
}
</code></pre>
| 0 |
How do I strip all leading and trailing punctuation in Python?
|
<p>I know how to remove all the punctuation in a string. </p>
<pre><code>import string
s = '.$ABC-799-99,#'
table = string.maketrans("","") # to remove punctuation
new_s = s.translate(table, string.punctuation)
print(new_s)
# Output
ABC79999
</code></pre>
<p>How do I strip all leading and trailing punctuation in Python? The desired result of <code>'.$ABC-799-99,#'</code> is <code>'ABC-799-99'</code>.</p>
| 0 |
php 7 php.ini upload_max_filesize not working
|
<p>I have read many solutions on internet , but still cannot change <code>upload_max_filesize</code> value (<code>upload_max_filesize</code> always = 2M )</p>
<p>here is my loaded <code>php.ini</code> in <code>phpinfo()</code> : </p>
<pre><code>Configuration File (php.ini) Path /etc/php/7.0/apache2
Loaded Configuration File /etc/php/7.0/apache2/php.ini
Scan this dir for additional .ini files /etc/php/7.0/apache2/conf.d
upload_max_filesize 2M 2M
post_max_size 8M 8M
</code></pre>
<p>here is my edited <code>php.ini</code> in <code>/etc/php/7.0/apache2/php.ini</code></p>
<pre><code>; http://php.net/post-max-size
post_max_size = 86M
; http://php.net/upload-max-filesize
upload_max_filesize = 40M
</code></pre>
<p>im using ubuntu 14.04,apache2,php7.0
(I have reset apache2 many time after each change in php.ini )</p>
| 0 |
Basic Firebase database save
|
<p>Anyone looking at this the below is the correct answer and I had everything setup correctly.
I still dont no what the issue is.
I was loggin in with facebook, using that to create a firebaseuser object.
and then sending the below as test data.
I've found it to be an intermittent issue. Uninstalling the app from the device and redeploying often fixes the issue.
very odd</p>
<p>Im actually struggling to get the example to work.</p>
<p>So basic.. set value....</p>
<pre><code>FirebaseDatabase database = FirebaseDatabase.getInstance();
Log.d(TAG, "db ref: "+database.getReference());
DatabaseReference myRef = database.getReference("message");
myRef.setValue("Hello, World!");
</code></pre>
<p>When I go into the database console I cant see the values I sent.
My log is returning a reference to the db though.
I've also set my rules up as public to be on the safe side.</p>
<p>Any ideas what I'm doing wrong?</p>
| 0 |
Flyway repair with Spring Boot
|
<p>I don't quite understand what I am supposed to do when a migration fails using Flyway in a Spring Boot project.</p>
<p>I activated Flyway by simply adding the Flyway dependency in my <code>pom.xml</code>. And everything works fine. My database scripts are migrated when I launch the Spring Boot app.</p>
<p>But I had an error in one of my scripts and my last migration failed. Now when I try to migrate, there is a "Migration checksum mismatch". Normally, I would run <code>mvn flyway:repair</code>, but since I am using Spring Boot, I am not supposed to use the Flyway Maven plug-in. So what am I supposed to do?</p>
| 0 |
Jquery Horizontal Scroll on Click
|
<p>I am trying to get this horizontal section of the page to auto scroll when the left or right arrows are clicked. I can get the Jquery code to run correctly in the console. However, the auto scroll events won't run at all on my page. Could anyone provide any insight into this issue?</p>
<p>The code is as follows :</p>
<p>HTML</p>
<pre><code><div class = "horizon horizon-prev">
<img src = "../images/left-arrow.png" />
</div>
<div class = "horizon horizon-next">
<img src = "../images/right-arrow.png" />
</div>
<div class="center" id="content">
<div class=internal>
div 1
</div>
<div class=internal>
div 2
</div>
<div class=internal>
div 3
</div>
<div class=internal>
div 4
</div>
<div class=internal>
div 5
</div>
<div class=internal>
div 6
</div>
<div class=internal>
div 7
</div>
<div class=internal>
div 8
</div>
</div>
</code></pre>
<p>CSS</p>
<pre><code>div.center {
width: 90%;
height: 210px;
border: 1px solid #000;
margin: auto;
overflow-x: hidden;
overflow-y: hidden;
white-space: nowrap;
}
div.internal {
display: inline-block;
vertical-align: middle;
width: 100%;
text-align: center;
}
</code></pre>
<p>Jquery</p>
<pre><code>$('.horizon-prev').click(function() {
event.preventDefault();
$('#content').animate({
scrollLeft: "-=775px"
}, "slow");
});
$('.horizon-next').click(function() {
event.preventDefault();
$('#content').animate({
scrollLeft: "+=775px"
}, "slow");
});
</code></pre>
| 0 |
Valet (Laravel): DNS address can not be found
|
<p>I'm trying out Valet, it looks really nice from what I've heard. </p>
<p>I've been trough the "whole" installation process, Valet is succesfully installed. </p>
<p>But when I <code>cd</code> into my projects file and enter <code>valet park</code> and browse to <code>http://blog.dev</code>, I get "The DNS server address of blog.dev can not be found."</p>
<p>I have no idea what I'm doing wrong. :) </p>
| 0 |
Service located in another namespace
|
<p>I have been trying to find a way to define a service in one namespace that links to a Pod running in another namespace. I know that containers in a Pod running in <code>namespaceA</code> can access <code>serviceX</code> defined in <code>namespaceB</code> by referencing it in the cluster DNS as <code>serviceX.namespaceB.svc.cluster.local</code>, but I would rather not have the code inside the container need to know about the location of <code>serviceX</code>. That is, I want the code to just lookup <code>serviceX</code> and then be able to access it.</p>
<p>The <a href="http://kubernetes.io/docs/user-guide/services/" rel="noreferrer">Kubernetes documentation</a> suggests that this is possible. It says that one of the reasons that you would define a service without a selector is that <strong>You want to point your service to a service in another Namespace or on another cluster</strong>.</p>
<p>That suggests to me that I should:</p>
<ol>
<li>Define a <code>serviceX</code> service in <code>namespaceA</code>, without a selector (since the POD I want to select isn't in <code>namespaceA</code>).</li>
<li>Define a service (which I also called <code>serviceX</code>) in <code>namespaceB</code>, and then</li>
<li>Define an Endpoints object in <code>namespaceA</code> to point to <code>serviceX</code> in <code>namespaceB</code>.</li>
</ol>
<p>It is this third step that I have not been able to accomplish.</p>
<p>First, I tried defining the Endpoints object this way:</p>
<pre class="lang-yaml prettyprint-override"><code>kind: Endpoints
apiVersion: v1
metadata:
name: serviceX
namespace: namespaceA
subsets:
- addresses:
- targetRef:
kind: Service
namespace: namespaceB
name: serviceX
apiVersion: v1
ports:
- name: http
port: 3000
</code></pre>
<p>That seemed the logical approach, and <em>obviously</em> what the <code>targetRef</code> was for. But, this led to an error saying that the <code>ip</code> field in the <code>addresses</code> array was mandatory. So, my next try was to assign a fixed ClusterIP address to <code>serviceX</code> in <code>namespaceB</code>, and put that in the IP field (note that the <code>service_cluster_ip_range</code> is configured as <code>192.168.0.0/16</code>, and <code>192.168.1.1</code> was assigned as the ClusterIP for <code>serviceX</code> in <code>namespaceB</code>; <code>serviceX</code> in <code>namespaceA</code> was auto assigned a different ClusterIP on the <code>192.168.0.0/16</code> subnet):</p>
<pre class="lang-yaml prettyprint-override"><code>kind: Endpoints
apiVersion: v1
metadata:
name: serviceX
namespace: namespaceA
subsets:
- addresses:
- ip: 192.168.1.1
targetRef:
kind: Service
namespace: namespaceB
name: serviceX
apiVersion: v1
ports:
- name: http
port: 3000
</code></pre>
<p>That was accepted, but accesses to <code>serviceX</code> in <code>namespaceA</code> did not get forwarded to the Pod in <code>namespaceB</code> - they timed out. Looking at the iptables setup, it looks like it would have had to do NAT pre-routing twice to accomplish that.</p>
<p>The only thing I did find that worked - but is not a satisfactory solution - is to lookup the actual IP address of the Pod providing <code>serviceX</code> in <code>namespaceB</code> and put that address in the Endpoints object in <code>namespaceA</code>. That isn't satisfactory, of course, because the Pod IP address may change over time. That's the problem service IPs are there to solve.</p>
<p>So, is there a way to meet what seems to be the promise of the documentation that I can point a service in one namespace to a <em>service</em> running in a different namespace?</p>
<p>A commenter questioned why you would want to do this - here is a use case that makes sense to me, at least:</p>
<p>Say you have a multi-tenant system, which also includes a common data-access function that can be shared between tenants. Now imagine that there are different flavors of this data-access function with common APIs, but different performance characteristics. Some tenants get access to one of them, other tenants have access to another one.</p>
<p>Each tenant's pods run in their own namespaces, but each one needs to access one of these common data-access services, which will necessarily be in another namespace (since it is accessed by multiple tenants). But, you wouldn't want the tenant to have to change their code if their subscription changes to access the higher-performing service.</p>
<p>A potential solution (the cleanest one I can think of, if only it worked) is to include a service definition in each tenant's namespace for the data-access service, with each one configured for the appropriate endpoint. This service definition would be configured to point to the proper data-access service each tenant is entitled to use.</p>
| 0 |
Remove focus from a EditText in Android
|
<p>I have two <code>EditText</code>s and one <code>CheckBox</code> and a <code>Button</code> in my layout in the above order. After entering the values to the <code>EditText</code>, the user has to accept terms and conditions by clicking the <code>Checkbox</code>. I need to remove focus from <code>EditText</code>s after the checkbox is clicked. Right now the focus is always on the second <code>EditText</code>. How can this be achieved? Please help.
<strong>Layout</strong>:
</p>
<pre><code> <EditText
android:id="@+id/pm_et_customer_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/customer_id_hint"
android:fontFamily="sans-serif-light"
android:gravity="center"
android:singleLine="true"
android:layout_centerHorizontal="true"
android:inputType="phone"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<RelativeLayout
android:id="@+id/pm_rl_mob_no_widget"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dp"
android:layout_below="@id/pm_et_customer_id"
android:gravity="center_horizontal">
<EditText
android:id="@+id/pm_et_dial_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/pm_et_msisdn"
android:layout_marginLeft="5dp"
android:ems="3"
android:fontFamily="sans-serif-thin"
android:gravity="center"
android:text="@string/plus_nine_one"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<EditText
android:id="@+id/pm_et_msisdn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/pm_et_dial_code"
android:ems="9"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal"
android:hint="@string/msisdn_hint"
android:inputType="phone"
android:maxLength="14"/>
</RelativeLayout>
<Button
android:id="@+id/pm_bt_proceed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/lay_t_c"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="8dp"
android:fontFamily="sans-serif-light"
android:text="@string/bt_label_proceed"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/pm_rl_mob_no_widget"
android:id="@+id/lay_t_c"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal">
<CheckBox
android:id="@+id/pm_check_t_and_c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-thin"
android:textSize="14sp"
android:text="@string/pm_label_accept"/>
<TextView
android:id="@+id/pm_tv_t_and_c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginRight="4dp"
android:layout_marginEnd="4dp"
android:paddingLeft="4dp"
android:paddingStart="4dp"
android:fontFamily="sans-serif-light"
android:text="@string/pm_label_t_and_c"
android:textSize="14sp"/>
</LinearLayout>
</RelativeLayout>
</code></pre>
| 0 |
Download "automatically" spreadsheet as .xlsx to local machine on event
|
<p>See below the function that converts the active Google Spreadsheet to a .xlsx file. The script saves the file in Google Drive.</p>
<pre><code>function downloadAsXlsx() {
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var ssID = spreadSheet.getId();
Logger.log(ssID);
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?format=xlsx";
var params = {method:"GET", headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url, params);
// save to drive
DriveApp.createFile(response);
}
</code></pre>
<p>If you replace the ssID in the URL above by the actual file id of the active Google Spreadsheet and copy and paste the URL in the browser, the active spreadsheet is downloaded "automatically". That is exactly what I need to be added to above script.</p>
<p>My question is how to change and/or extend the function above so that the file is instead downloaded to the local machine in the default download folder?</p>
| 0 |
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in
|
<p>I'm getting the following error:</p>
<blockquote>
<p>Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in C:\wamp\www\PTT\login.php on line 28</p>
</blockquote>
<p>Here's line 28:</p>
<pre><code>$voornaam = mysqli_real_escape_string($_POST['voornaam']);
</code></pre>
<p>Here's my code:</p>
<pre><code>//Generate a key, print a form:
$key = sha1(microtime());
$_SESSION['csrf'] = $key;
if(isset($_POST['registreer'])){
$voornaam = mysqli_real_escape_string($_POST['voornaam']);
$achternaam = mysqli_real_escape_string($_POST['achternaam']);
$land = mysqli_real_escape_string($_POST['land']);
$gebdate = mysqli_real_escape_string($_POST['year'].'-'.$_POST['month'].'-'.$_POST['day']);
$inlognaam = mysqli_real_escape_string($_POST['inlognaam']);
$wachtwoord = mysqli_real_escape_string($_POST['wachtwoord']);
$wachtwoord_nogmaals = mysqli_real_escape_string($_POST['wachtwoord_nogmaals']);
$wachtwoordmd5 = md5($wachtwoord);
$email = mysqli_real_escape_string($_POST['email']);
$wereld = mysqli_real_escape_string($_POST['wereld']);
$secondaccount = mysqli_real_escape_string($_POST['agreecheck']);
$schelden = mysqli_real_escape_string($_POST['agreecheck2']);
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("Y-m-d H:i:s");
$character = mysqli_real_escape_string($_POST['character']);
$referer = mysqli_real_escape_string($_POST['referer']);
$check = mysqli_fetch_assoc(mysqli_query("SELECT `ip_aangemeld`, `aanmeld_datum` FROM `gebruikers` WHERE `ip_aangemeld`='".$ip."' ORDER BY `user_id` DESC"));
$registerdate = strtotime($check['aanmeld_datum']);
$current_time = strtotime(date('Y-m-d H:i:s'));
$countdown_time = 604800-($current_time-$registerdate);
</code></pre>
| 0 |
Write large amount of data to excel c#
|
<p>I need to export lots of data from database table to excel (xls/xlsx) file.
It could be easily 10million rows and more. </p>
<p>I need open source solution which does not require Office to be installed (SpreadsheetGear and interop solutions will not work for me).</p>
<p>I am checking two libraries: OpenXML SDK and EPPlus. </p>
<p>For OpenXML SDK I found this method:</p>
<pre><code> private static void Write(string fileName, int numRows, int numCols)
{
using (var spreadsheetDocument = SpreadsheetDocument.Open(fileName, true))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
string origninalSheetId = workbookPart.GetIdOfPart(worksheetPart);
WorksheetPart replacementPart = workbookPart.AddNewPart<WorksheetPart>();
string replacementPartId = workbookPart.GetIdOfPart(replacementPart);
using (OpenXmlReader reader = OpenXmlReader.Create(worksheetPart))
{
using (OpenXmlWriter writer = OpenXmlWriter.Create(replacementPart))
{
Row row = new Row();
Cell cell = new Cell();
//CellFormula cellFormula = new CellFormula();
//cellFormula.CalculateCell = true;
//cellFormula.Text = "RAND()";
//cell.Append(cellFormula);
CellValue cellValue = new CellValue("val val");
cell.Append(cellValue);
while (reader.Read())
{
if (reader.ElementType == typeof(SheetData))
{
if (reader.IsEndElement)
continue;
writer.WriteStartElement(new SheetData());
for (int rowNumber = 0; rowNumber < numRows; rowNumber++)
{
writer.WriteStartElement(row);
for (int col = 0; col < numCols; col++)
{
writer.WriteElement(cell);
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
else
{
if (reader.IsStartElement)
{
writer.WriteStartElement(reader);
}
else if (reader.IsEndElement)
{
writer.WriteEndElement();
}
}
}
}
}
Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().First(s => s.Id.Value.Equals(origninalSheetId));
sheet.Id.Value = replacementPartId;
workbookPart.DeletePart(worksheetPart);
}
}
</code></pre>
<p>But it throws <code>Out of memory</code> exception.
I need <code>batch oriented</code> approach and to be able to <code>append</code> data to the end of excel document.
Unfortunately I did not find how to append rows with <code>OpenXML SDK</code>.</p>
<p>Also, I checked <a href="http://techbrij.com/export-excel-xls-xlsx-asp-net-npoi-epplus" rel="nofollow">EPPlus soluion</a> with <code>LoadFromCollection</code> method.
It does support <code>IDataReader</code> with <code>LoadFromDataReader</code> but I dont have datareader at that point in code.</p>
<p>The question: is there a way to append data to existing sheet xls/xlsx file with kind of writer? Like <code>OpenXMLWrite</code>r in <code>OpenXML SDK</code>.</p>
<p>UPD. Excel clearly does not support 10 million rows. Lets stick with 1m rows and lost of columns without out of memory exception.</p>
<p>UPD. Added EPPlus sample. 200k rows exports in 6 minutes and takes up to 1GB of RAM.</p>
<pre><code> private const string TempFile = @"C:\Users\vnechyp\Desktop\temp.xlsx";
private static void EPPlusExport()
{
var random = new Random();
var dt = new System.Data.DataTable();
for (int i = 0; i < 15; i++)
{
dt.Columns.Add($"column_{i}");
}
var values = Enumerable.Range(0, 15).Select(val => random.Next().ToString()).ToArray();
for (int i = 0; i < 10000; i++)
{
dt.Rows.Add(values);
}
using (ExcelPackage excelPackage = new ExcelPackage())
{
var workSheet = excelPackage.Workbook.Worksheets.Add("sheet");
workSheet.Cells[1, 1].LoadFromDataTable(dt, true);
excelPackage.SaveAs(new FileInfo(TempFile));
}
for (int i = 1; i < 50; i++)
{
Console.WriteLine($"Iteration: {i}");
var updateRow = i*10000;
Console.WriteLine($"Rows: {updateRow}");
FileInfo existingFile = new FileInfo(TempFile);
using (ExcelPackage excelPackage = new ExcelPackage(existingFile))
{
// get the first worksheet in the workbook
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[1];
worksheet.Cells[updateRow, 1].LoadFromDataTable(dt, true);
excelPackage.SaveAs(new FileInfo(TempFile));
}
}
}
</code></pre>
| 0 |
Seaborn timeseries plot with multiple series
|
<p>I'm trying to make a time series plot with seaborn from a dataframe that has multiple series.</p>
<p>From this post:
<a href="https://stackoverflow.com/questions/33461664/seaborn-time-series-from-pandas-dataframe#answer-33462384">seaborn time series from pandas dataframe</a></p>
<p>I gather that tsplot isn't going to work as it is meant to plot uncertainty.</p>
<p>So is there another Seaborn method that is meant for line charts with multiple series?</p>
<p>My dataframe looks like this:</p>
<pre><code>print(df.info())
print(df.describe())
print(df.values)
print(df.index)
</code></pre>
<p>output:</p>
<pre><code><class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 253 entries, 2013-01-03 to 2014-01-03
Data columns (total 5 columns):
Equity(24 [AAPL]) 253 non-null float64
Equity(3766 [IBM]) 253 non-null float64
Equity(5061 [MSFT]) 253 non-null float64
Equity(6683 [SBUX]) 253 non-null float64
Equity(8554 [SPY]) 253 non-null float64
dtypes: float64(5)
memory usage: 11.9 KB
None
Equity(24 [AAPL]) Equity(3766 [IBM]) Equity(5061 [MSFT]) \
count 253.000000 253.000000 253.000000
mean 67.560593 194.075383 32.547436
std 6.435356 11.175226 3.457613
min 55.811000 172.820000 26.480000
25% 62.538000 184.690000 28.680000
50% 65.877000 193.880000 33.030000
75% 72.299000 203.490000 34.990000
max 81.463000 215.780000 38.970000
Equity(6683 [SBUX]) Equity(8554 [SPY])
count 253.000000 253.000000
mean 33.773277 164.690180
std 4.597291 10.038221
min 26.610000 145.540000
25% 29.085000 156.130000
50% 33.650000 165.310000
75% 38.280000 170.310000
max 40.995000 184.560000
[[ 77.484 195.24 27.28 27.685 145.77 ]
[ 75.289 193.989 26.76 27.85 146.38 ]
[ 74.854 193.2 26.71 27.875 145.965]
...,
[ 80.167 187.51 37.43 39.195 184.56 ]
[ 79.034 185.52 37.145 38.595 182.95 ]
[ 77.284 186.66 36.92 38.475 182.8 ]]
DatetimeIndex(['2013-01-03', '2013-01-04', '2013-01-07', '2013-01-08',
'2013-01-09', '2013-01-10', '2013-01-11', '2013-01-14',
'2013-01-15', '2013-01-16',
...
'2013-12-19', '2013-12-20', '2013-12-23', '2013-12-24',
'2013-12-26', '2013-12-27', '2013-12-30', '2013-12-31',
'2014-01-02', '2014-01-03'],
dtype='datetime64[ns]', length=253, freq=None, tz='UTC')
</code></pre>
<p>This works (but I want to get my hands dirty with Seaborn):</p>
<pre><code>df.plot()
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/jwihb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jwihb.png" alt="enter image description here"></a></p>
<p>Thank you for your time!</p>
<p>Update1:</p>
<p><code>df.to_dict()</code> returned:
<a href="https://gist.github.com/anonymous/2bdc1ce0f9d0b6ccd6675ab4f7313a5f" rel="noreferrer">https://gist.github.com/anonymous/2bdc1ce0f9d0b6ccd6675ab4f7313a5f</a></p>
<p>Update2:</p>
<p>Using @knagaev sample code, I've narrowed it down to this difference:</p>
<p>current dataframe (output of <code>print(current_df)</code>):</p>
<pre><code> Equity(24 [AAPL]) Equity(3766 [IBM]) \
2013-01-03 00:00:00+00:00 77.484 195.2400
2013-01-04 00:00:00+00:00 75.289 193.9890
2013-01-07 00:00:00+00:00 74.854 193.2000
2013-01-08 00:00:00+00:00 75.029 192.8200
2013-01-09 00:00:00+00:00 73.873 192.3800
</code></pre>
<p>desired dataframe (output of <code>print(desired_df)</code>):</p>
<pre><code> Date Company Kind Price
0 2014-01-02 IBM Open 187.210007
1 2014-01-02 IBM High 187.399994
2 2014-01-02 IBM Low 185.199997
3 2014-01-02 IBM Close 185.529999
4 2014-01-02 IBM Volume 4546500.000000
5 2014-01-02 IBM Adj Close 171.971090
6 2014-01-02 MSFT Open 37.349998
7 2014-01-02 MSFT High 37.400002
8 2014-01-02 MSFT Low 37.099998
9 2014-01-02 MSFT Close 37.160000
10 2014-01-02 MSFT Volume 30632200.000000
11 2014-01-02 MSFT Adj Close 34.960000
12 2014-01-02 ORCL Open 37.779999
13 2014-01-02 ORCL High 38.029999
14 2014-01-02 ORCL Low 37.549999
15 2014-01-02 ORCL Close 37.840000
16 2014-01-02 ORCL Volume 18162100.000000
</code></pre>
<p>What's the best way to reorganize the <code>current_df</code> to <code>desired_df</code>?</p>
<p>Update 3:
I finally got it working from the help of @knagaev:</p>
<p>I had to add a dummy column as well as finesse the index: </p>
<pre><code>df['Datetime'] = df.index
melted_df = pd.melt(df, id_vars='Datetime', var_name='Security', value_name='Price')
melted_df['Dummy'] = 0
sns.tsplot(melted_df, time='Datetime', unit='Dummy', condition='Security', value='Price', ax=ax)
</code></pre>
<p>to produce:
<a href="https://i.stack.imgur.com/JtioA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JtioA.png" alt="enter image description here"></a></p>
| 0 |
How to build Dockerfile with two jar files
|
<p>I'm starting with Docker and I'm a little bit lost.</p>
<p>I have my java experiment with two jar files, zip files with testing data and two configuration files.
And I'm trying to run this exp on Docker.</p>
<p>If I want to run this exp on my pc there are two phases.</p>
<p>Phase 1: </p>
<pre><code>java -classpath library.jar;alg.jar library.utl.App.class in.cf
</code></pre>
<p>where the last parameter is configuration and after this I'll get generated file <strong>alg1.bin</strong></p>
<p>Phase 2: </p>
<pre><code>java -classpath library.jar;alg.jar library.utl.App.class ot.cf
</code></pre>
<p>where I'm working with file <strong>alg1.bin</strong> and this is main test.</p>
<p>I used Dockerfile for phase 1:</p>
<pre><code>FROM java:7
ADD java-exp /usr/local/
CMD ["java", "-classpath",
"/usr/local/library.jar;/usr/local/alg.jar",
"/usr/local/library.utl.App.class", "/usr/local/in.cf"]
</code></pre>
<p>This I built successfully but when I try</p>
<pre><code>docker run java-exp
</code></pre>
<p>I get an error:</p>
<blockquote>
<p>Error: Could not find or load main class
.usr.local.library.utl.App.class.</p>
</blockquote>
<p>Can anyone help me to solve this?</p>
<p>In the better way, help me merge both two phases into one Dockerfile?
Thanks.</p>
| 0 |
How to calculate decimal(x, y) max value in SQL Server
|
<p>How do I know the maximum value of <code>decimal</code> type?</p>
<p>For example:</p>
<pre><code>decimal(5, 2)
</code></pre>
<p>Can you please explain the mechanism of <code>decimal</code> type?</p>
| 0 |
String encoding conversion UTF-8 to SHIFT-JIS
|
<p>Variables used:</p>
<ul>
<li>JavaSE-6</li>
<li>No frameworks</li>
</ul>
<hr>
<p>Given this string input of <code>ピーター・ジョーズ</code> which is encoded in <strong>UTF-8</strong>, I am having problems converting the said string to <strong>Shift-JIS</strong> without the need of writing the said data to a file.</p>
<ul>
<li>Input (UTF-8 encoding): <code>ピーター・ジョーンズ</code></li>
<li>Output (SHIFT-JIS encoding): <code>ピーター・ジョーンズ</code> (SHIFT-JIS to be encoded)</li>
</ul>
<hr>
<p>I've tried this code snippets on how to convert UTF-8 strings to SHIFT-JIS:</p>
<ul>
<li><code>stringToEncode.getBytes(Charset.forName("SHIFT-JIS"))</code></li>
<li><code>new String(unecodedString.getBytes("SHIFT-JIS"), "UTF-8")</code></li>
</ul>
<p>Both code snippets return this string output: <code>�s�[�^�[�E�W���[���Y</code> (SHIFT-JIS encoded)</p>
<p>Any ideas on how this can be resolved?</p>
| 0 |
Android Floating Action Button Semi Transparent Background Color
|
<p>I want to use FAB with semi transparent background color.
But I am getting a FAB with two different colors. What's the problem?</p>
<pre><code><android.support.design.widget.FloatingActionButton
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|left"
android:fadingEdgeLength="5dp"
app:borderWidth="0dp"
app:elevation="4dp"
app:backgroundTint="#99f03456"
app:fabSize="normal"/>
</code></pre>
<p><a href="https://i.stack.imgur.com/MXsO2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MXsO2.png" alt="enter image description here"></a></p>
<p>And without any drawable.</p>
<p><a href="https://i.stack.imgur.com/eKLw5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eKLw5.png" alt="enter image description here"></a></p>
| 0 |
Button inside a label
|
<p>I have a <code>label</code> with "<code>for="the pointer to the checkbox input"</code>" and as long as I know, this <code>for</code> can be added only for <code>label</code>. Therefore, I need to add inside of the <code>label</code> a <code><button></code>(I need it), but the click event isn't working properly - it doesn't check the checkbox the <code>for</code> is pointing to. </p>
<p>What are the possibilities I can use here if I must place <code><button></code> inside the <code>label</code>, <strong>with only html+css</strong> coding?</p>
<p>some code for example:</p>
<pre><code><input type="checkbox" id="thecheckbox" name="thecheckbox">
<div for="thecheckbox"><button type="button">Click Me</button></div>
</code></pre>
| 0 |
mongoose doesn't return the output with findById
|
<p>I m learning nodejs and mongodb altogether with <a href="https://github.com/simonholmes/getting-MEAN" rel="nofollow">getting MEAN application</a> </p>
<p>my system specifications are </p>
<p>ubuntu 16.04 (64 bit)<br>
node v 6.1.0<br>
npm v 3.8.6</p>
<p>"mongodb": "^2.1.18",<br>
"mongoose": "^4.4.16",</p>
<p>So far I have created schema and add an entry in mongodb collection through terminal using <code>db.locations.save()</code> and get the generated document <strong>_id</strong> with <code>db.locations.find()</code>.</p>
<p>db.locations.find().pretty() in terminal returns below output</p>
<pre><code>{
"_id" : ObjectId("57428745e89f5c55e1d057dc"),
// and many other path
}
</code></pre>
<p>Now when I open <strong>/api/locations/57428745e89f5c55e1d057dc</strong> in browser, it neither gives result nor end the request. permanently show loading.. when testing with postman.</p>
<p>even tried with wrong Id than it returns proper error </p>
<blockquote>
<p>{"message":"Cast to ObjectId failed for value
\"57428745e89f5c55e1d057dca\" at path
\"_id\"","name":"CastError","kind":"ObjectId","value":"57428745e89f5c55e1d057dca","path":"_id"}</p>
</blockquote>
<p>and with correct id </p>
<pre><code>console.log(mongoose.Types.ObjectId.isValid(req.params.locationid)); // return true
</code></pre>
<p>even tried </p>
<p><code>findOne({"_id": mongoose.Types.ObjectId(req.params.locationid) })</code> </p>
<p>But no results </p>
<p>What could be the issue? Is there any bug in mongoose or anything missing .Below are my basic files with required code</p>
<h3>loc8r/app.js</h3>
<pre><code>require('./app_api/models/db');
var routesApi = require('./app_api/routes/index');
app.use('/api', routesApi);
</code></pre>
<h3>loc8r/app_api/models/db.js</h3>
<pre><code>var mongoose = require( 'mongoose' );
var mongoURI = 'mongodb://localhost/loc8r';
var mongoDB = mongoose.createConnection(mongoURI);
mongoDB.on('connected', function (){
console.log('mongoose connected to ' + mongoURI);
});
require('./locations');
</code></pre>
<hr>
<h3>loc8r/app_api/models/locations.js</h3>
<pre><code>var mongoose = require( 'mongoose' );
var openingTimeSchema = new mongoose.Schema({
days: {type: String, required: true},
opening: String,
closing: String,
closed: {type: Boolean, required: true}
});
var reviewSchema = new mongoose.Schema({
author: String,
rating: {type: Number, required: true, min: 0, max: 5},
reviewText: String,
createdOn: {type: Date, "default": Date.now}
});
var locationSchema = new mongoose.Schema({
name: {type: String, required: true},
address: String,
rating: {type: Number, "default": 0, min: 0, max: 5},
facilities: [String],
coords: {type: [Number], index: '2dspehere'},
openingTime: [openingTimeSchema],
reviews: [reviewSchema]
});
mongoose.model('Location', locationSchema);
</code></pre>
<h3>loc8r/app_api/router/index.js</h3>
<pre><code>var express = require('express');
var router = express.Router();
var ctrlLocations = require('../controllers/locations');
/* Locations pages */
router.get('/locations/:locationid', ctrlLocations.locationsReadOne);
</code></pre>
<hr>
<h3>loc8r/app_api/controllers/locations.js</h3>
<pre><code>var mongoose = require('mongoose');
var Loc = mongoose.model('Location');
module.exports.locationsReadOne = function (req, res) {
if(req.params && req.params.locationid) {
Loc
.findById(req.params.locationid)
.exec(function(err, location) {
if(err) {
sendJsonResponse(res, 404, err);
return;
}
if (!location) {
sendJsonResponse(res, 404, {"message": "locationid not found"});
return;
}
sendJsonResponse(res, 200, location);
});
} else {
sendJsonResponse(res, 200, {"message": "no location id in request"});
}
}
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
</code></pre>
| 0 |
make div disable in html
|
<p>I have a div like this:</p>
<pre><code><div class="load-more-home col-xs-12 btn" disabled="true">No more posts available </div>
</code></pre>
<p>I want to make it not clickable. So I added disable="true" but it doesn't work. </p>
<p><strong>I want to make it in HTML without javascript.</strong> </p>
<p>I want to know if exists any attribute in HTML that makes a div unclickable because <code>disabled</code> isn't working.
Please help.</p>
<p>Edit:</p>
<p>this class <code>load-more-home</code> is called in a javascript function that generates posts, actually, the difference between buttons is only the inner text.
When there are no more posts the text is replaced with "No more posts..". But by default I need to put there a not clickable div(div that acts like a button). I hope I explained it </p>
| 0 |
ImportError: cannot import name COMError in python
|
<p>I am trying to convert docx file to pdf with following code</p>
<pre><code>import sys
import os
import comtypes.client
wdFormatPDF = 17
in_file = os.path.abspath(sys.argv[1])
out_file = os.path.abspath(sys.argv[2])
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
doc.Close()
word.Quit()
</code></pre>
<p>It is throwing an error </p>
<pre><code>ImportError: cannot import name COMError
</code></pre>
<p>I have installed comtypes package.</p>
<p>I am very new to python, I can not figure out how to resolve this problem.</p>
<p>[Edit]</p>
<p>Stacktrace</p>
<pre><code>Traceback (most recent call last):
File "converttopdf.py", line 3, in <module>
import comtypes.client
File "/usr/local/lib/python2.7/dist-packages/comtypes-1.1.2-py2.7.egg/comtypes/__init__.py", line 23, in <module>
from _ctypes import COMError
ImportError: cannot import name COMError
</code></pre>
| 0 |
How to do a nested if else statement in ReactJS JSX?
|
<p>I wanted to know if its possible to do nested if else if in ReactJS JSX?</p>
<p>I have tried various different ways and I am unable to get it to work.</p>
<p>I am looking for</p>
<pre><code>if (x) {
loading screen
} else {
if (y) {
possible title if we need it
}
main
}
</code></pre>
<p>I have tried this but I can not get it to render. I have tried various ways. It always breaks once I add the nested if.</p>
<pre><code>{
this.state.loadingPage ? (
<div>loading page</div>
) : (
<div>
this.otherCondition && <div>title</div>
<div>body</div>
</div>
);
}
</code></pre>
<p><strong>Update</strong></p>
<p>I ended up choosing the solution to move this to renderContent and call the function. Both of the answers did work though. I think I may use the inline solution if it is for a simple render and renderContent for more complicated cases.</p>
<p>Thank you</p>
| 0 |
Angular 2 - Convenient way to store in session
|
<p>Is there a convenient way to save in sessionStorage without the need to manually watch for property changes and update?</p>
<p>I have a SearchComponent with a property "query" for example.</p>
<pre><code>export class SearchComponent {
private query: String;
private searchResult: SearchResult;
...
</code></pre>
<p>Every time the query or the searchResult changes (and there are even more properties), i have to manually update sessionStorage.</p>
<pre><code>sessionStorage.setItem('query', query);
</code></pre>
<p>Something like an annotation that does the job automatically would be great:</p>
<pre><code>export class SearchComponent {
@SessionStored
private query: String;
@SessionStored
private searchResult: SearchResult;
...
</code></pre>
<p>I already found a similar solution <a href="https://github.com/marcj/angular2-localStorage" rel="noreferrer">here</a>. But this one did not work for <em>sessionStorage</em>.</p>
| 0 |
How to export imported object in ES6?
|
<p>The use case is simple: I just want to export an object with the name just as it was imported.</p>
<p>for example:</p>
<pre><code>import React from 'react';
export React;
</code></pre>
<p>but this does not work. I have to write:</p>
<pre><code>import React from 'react';
export const React = React;
</code></pre>
<p>But this is odd. What is the right way to do this?</p>
<p><strong>UPDATED</strong>:</p>
<p>Thanks for helps and references. I have solved out my problem with many clues. I'd like to share some common cases for me and the solutions.</p>
<h3>export imports</h3>
<pre><code>import d, {obj} from '...';
export {obj, d};
export {obj as name1, d as name2};
</code></pre>
<h3>re-export all named imports</h3>
<pre><code>export * from '...';
export * as name1 from '...';
</code></pre>
<h3>re-export some named imports</h3>
<pre><code>export {a, b as name1} from '...';
</code></pre>
<h3>re-export default import as default export</h3>
<pre><code>export {default} from '...';
</code></pre>
<h3>re-export default import as named export</h3>
<pre><code>export {default as name1} from '...';
</code></pre>
| 0 |
Action bar not shown in Android Studio
|
<p>I'm using Android Studio for the first time and can't manage to make the <code>ActionBar</code> show when I run the app. Here's what I have so far:</p>
<p>My Activity <em>MainActivity.java</em></p>
<pre><code>package xeniasis.mymarket;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.support.v7.app.ActionBar;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
}
</code></pre>
<p>it's layout <em>activity_main.xml</em> (nothing there)</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="xeniasis.mymarket.MainActivity"></RelativeLayout>
</code></pre>
<p>and the menu with one item <em>activity_main.xml</em></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="xeniasis.mymarket.MainActivity">
<item
android:id="@+id/action_update"
android:icon="@drawable/ic_action_update"
android:showAsAction="ifRoom"
android:title="@string/update_app" />
</menu>
</code></pre>
<p>Do I need something else in order to show the <code>ActionBar</code>?</p>
<p><strong>EDIT</strong></p>
<p>here is the app theme</p>
<pre><code><style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</code></pre>
| 0 |
Android Studio: @Override "Annotations are not allowed here"
|
<p>I want to implement the ...</p>
<pre><code>@Override
public void onBackPressed() {
}
</code></pre>
<p>However, I get an error message saying, <strong>"Annotations are not allowed here"</strong>. I need this method to be implemented here. Is there an alternative?</p>
<pre><code>public class supbreh extends Appbreh
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_breh);
if (myBundle != null) {
String name = myBundle.getString("workout");
ShowDetails(name);
}
}
private void ShowAbDetails(String mName) {
if(mName.equals("abs1")){
@Override
public void onBackPressed() { //"Not Allowed here"
}
}
</code></pre>
| 0 |
Why does this java 8 stream operation evaluate to Object instead of List<Object> or just List?
|
<p>I'm working with a 3d party library, and they return Collections that lack type specifications (e.g. <code>public List getFoo();</code>) , and I'm trying to convert their return types and return a list with a proper type. </p>
<p>I have created a simple example that demonstrates the problem. e.g.</p>
<p><em>edit</em> The original question declared l2 as an <code>ArrayList</code> rather than a <code>List</code>, that is corrected now.</p>
<pre><code>import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class Foo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(1);
l.add(2);
List<String> l2 = l.stream().map(Object::toString).collect(Collectors.toList());
}
}
</code></pre>
<p>This fails to compile.</p>
<pre><code>$ javac Foo.java
Foo.java:10: error: incompatible types: Object cannot be converted to List<String>
List<String> l2 = l.stream().map(Object::toString).collect(Collectors.toList());
^
1 error
</code></pre>
<p>If I modify the program slightly so it compiles and I can check the return type of the stream/collect operation. It "works", although I'd have to cast the result.</p>
<p>e.g.</p>
<pre><code>import java.util.ArrayList;
import java.util.stream.Collectors;
public class Foo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(1);
l.add(2);
Object l2 = l.stream().map(Object::toString).collect(Collectors.toList());
System.out.println(l2.getClass());
}
}
</code></pre>
<p>Running this shows...</p>
<pre><code>$ javac Foo.java
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$ java Foo
class java.util.ArrayList
</code></pre>
<p>As expected.</p>
<p>So, Collectors.listCollector() does the right thing at runtime, but is this compile time behavior expected? If so, is there a "proper" way around it?</p>
| 0 |
How to run a bash script via Cron
|
<p>I have seen other questions that are similar but I can't find any real information on how to figure out the proper way to run a Bash script via Crontab. The <code>.sh</code> file is located in the user directory (in my case <code>serverpilot</code>). </p>
<p>The script is trying to copy the contents of the <code>apps</code> folder and send to my S3 bucket. The script works perfectly when run with <code>sh backupS3.sh</code> from the terminal but no joy via Cron. I've seen people reference PATH variables and the like but no idea where to even begin!</p>
<p>/backupS3.sh</p>
<pre><code>#!/bin/sh
echo 'Started backing to S3'
date +'%a %b %e %H:%M:%S %Z %Y'
aws s3 sync /apps s3://bucketname
date +'%a %b %e %H:%M:%S %Z %Y'
echo 'Finished backing to S3'
</code></pre>
<p>crontab</p>
<pre><code>*/10 * * * * /backupS3.sh >> backupS3.log
</code></pre>
<p>Can anyone point me at anything obvious I'm doing wrong? Thanks! </p>
<p>EDIT: I've added 2>&1 on to the end of the cron command and now I am getting something in the log file:</p>
<p><code>/bin/sh: 1: /backupS3.sh: not found</code></p>
| 0 |
How to check if a given number can be represented as the sum of 2 even numbers?
|
<p>I want to read in a number and check if the number can be written as the sum of 2 even numbers.</p>
<p>Input: A line containing the number <code>w</code>.</p>
<p>Output:Print YES, if the number can be divided into two parts, each of them being even; and NO in the opposite case.</p>
<hr />
<p>I've tried this code.</p>
<pre><code>#include <stdio.h>
int main () {
int w,i,b;
i=w%b;
printf("enter the weight");
scanf("%d", &w);
for (b=2;b<=10;b=b+2) {
if (i==0 && i&2==0) {
printf("YES");
} else {
printf("NO");
}
}
return 0;
}
</code></pre>
<p>but it's not showing any correct output. Can you tell me what am I missing here?</p>
| 0 |
No viable conversion from 'const std::__1::basic_string<char> to 'std::__1::basic_string<char> *'
|
<p>I'm currently working on an project for a class in which I've to implement cuckoo hashing in C++. The problem is, that C++ and I were never friends and I think we never will be...</p>
<p>The concrete problem is, that I can't wangle to set an pointer on an already existing Object. When I do so, I get the compile error:</p>
<p><em>No viable conversion from 'const std::__1::basic_string to 'std::__1::basic_string</em>'* </p>
<p>The error occurs for both statements:</p>
<pre><code>E * activeE = e;
E * tempE = v1[pos];
</code></pre>
<p>v1 is an array of E Objects.</p>
<p>I think this error is caused by my generally misunderstanding in the basic concept of C++. I think for you guys this problem is a joke, but I hope you help me anyway.</p>
<pre><code>template <typename E, size_t N>
void Hashing<E,N>::add_(const E& e) {
size_t pos = h1(e);
size_t i = 0;
E * activeE = e;
E * tempE = v1[pos];
while (i < nmax) {
if (tempE == NULL) {
v1[pos] = activeE;
break;
}
v1[pos] = activeE;
activeE = tempE;
pos = h2(activeE);
tempE = v2[pos];
if (tempE == NULL) {
v2[pos] = activeE;
break;
}
v2[pos] = activeE;
activeE = tempE;
pos = h1(activeE);
tempE = v1[pos];
}
}
</code></pre>
| 0 |
Codeigniter Increase the execution time
|
<p>I already increased the execution time of script in <code>php.ini</code> but seems like codeigniter neglect it and make my script stop after 30 seconds of execution. </p>
<p>I also googled how to increase the execution time of codeigniter and they say that its in the system core of codeigniter but when I checked, there's none to tweak. Must be because the version of my codeigniter is current. </p>
<p>I also added <code>ini_set('max_execution_time',0)</code> above my controller but no effect and so I put it inside the function but same outcome. </p>
<p>I also tried <code>set_time_limit(0)</code> above and before the script but none has gave good results.... </p>
<p>Please help because I need process more than 3000 records and it will take more than 10 minutes....</p>
| 0 |
Google Map Api v2 shows "V/GoogleSignatureVerifier : signature not valid" error message in log
|
<p>I am developing an Android application using <code>google map api v2</code> to show a Map in a Fragment. When I run the application, I always got this error message poppin in my log every now and then.</p>
<p>Things I've tried:</p>
<ul>
<li>Erasing the debug.keystore and rebuilding the app.</li>
<li>Downgrading the Google Play Service and upgrading it again.</li>
<li>Deselect Offline Work </li>
</ul>
<p>Nothing does the trick so far... </p>
<p>Once upon the time in the Log tab :</p>
<pre><code> 2364-3928/com.example.android.app E/DynamiteModule: Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.android.gms.googlecertificates.ModuleDescriptor" on path: DexPathList[[zip file "/data/app/com.example.android.app-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.android.app-2/lib/arm, /data/app/com.example.android.app-2/base.apk!/lib/armeabi-v7a, /vendor/lib, /system/lib]]
2364-3928/com.example.android.app I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:1
2364-3928/com.example.android.app I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 1
2364-3928/com.example.android.app W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/00000000/n/armeabi
2364-3928/com.example.android.app D/ChimeraFileApk: Primary ABI of requesting process is armeabi-v7a
2364-3928/com.example.android.app D/ChimeraFileApk: Classloading successful. Optimized code found.
2364-3928/com.example.android.app D/GoogleCertificates: com.google.android.gms.googlecertificates module is loaded
2364-3928/com.example.android.app D/GoogleCertificatesImpl: Fetched 154 Google release certificates
1921-2130/? V/GoogleSignatureVerifier: com.example.android.app signature not valid. Found:
MIIB3TCCAUYCAQEwDQYJKoZIhvcNAQEFBQAwNzEWMBQGA1UEAwwNQW5kcm9pZCBEZWJ1ZzEQMA4G
A1UECgwHQW5kcm9pZDELMAkGA1UEBhMCVVMwHhcNMTYwNTE3MTYxNzM0WhcNNDYwNTEwMTYxNzM0
WjA3MRYwFAYDVQQDDA1BbmRyb2lkIERlYnVnMRAwDgYDVQQKDAdBbmRyb2lkMQswCQYDVQQGEwJV
UzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAkafVu0j1zuB6+cpo6q5OsfhrlEFzVknFNs0c
vJorrlTTPZK3WSmkX9jZ0cp6oL60+4mHPouAR7Hq72gAs8u9Zh3eVrnV7uP7Rv2/z84DJuo34z1g
lahfkNPR/mCsYkK+ZqkC6uR46NnoftoKC/9vJSlUxYaBLT+mWvApz4rUKuMCAwEAATANBgkqhkiG
9w0BAQUFAAOBgQAERId+C7AD5Ew4Jv4mTmaZWBUtkinCKFSF4RtVa3xnHjL5xDPbAEq829gt+yx7
FkftGZO1x5nWEdAWyxiZgET3sKyl4ejRu1V5qvTMOcPMaVHw/e5v97FK8q756tQBcAu+Zs77P6MW
RxXtAwqeIkV1+L1rY8WueawfQ7Wbm1bPOg==
1921-2130/? V/GoogleSignatureVerifier: com.example.android.app signature not valid. Found:
MIIB3TCCAUYCAQEwDQYJKoZIhvcNAQEFBQAwNzEWMBQGA1UEAwwNQW5kcm9pZCBEZWJ1ZzEQMA4G
A1UECgwHQW5kcm9pZDELMAkGA1UEBhMCVVMwHhcNMTYwNTE3MTYxNzM0WhcNNDYwNTEwMTYxNzM0
WjA3MRYwFAYDVQQDDA1BbmRyb2lkIERlYnVnMRAwDgYDVQQKDAdBbmRyb2lkMQswCQYDVQQGEwJV
UzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAkafVu0j1zuB6+cpo6q5OsfhrlEFzVknFNs0c
vJorrlTTPZK3WSmkX9jZ0cp6oL60+4mHPouAR7Hq72gAs8u9Zh3eVrnV7uP7Rv2/z84DJuo34z1g
lahfkNPR/mCsYkK+ZqkC6uR46NnoftoKC/9vJSlUxYaBLT+mWvApz4rUKuMCAwEAATANBgkqhkiG
9w0BAQUFAAOBgQAERId+C7AD5Ew4Jv4mTmaZWBUtkinCKFSF4RtVa3xnHjL5xDPbAEq829gt+yx7
FkftGZO1x5nWEdAWyxiZgET3sKyl4ejRu1V5qvTMOcPMaVHw/e5v97FK8q756tQBcAu+Zs77P6MW
RxXtAwqeIkV1+L1rY8WueawfQ7Wbm1bPOg==
1921-2130/? V/GoogleSignatureVerifier: com.example.android.app signature not valid. Found:
MIIB3TCCAUYCAQEwDQYJKoZIhvcNAQEFBQAwNzEWMBQGA1UEAwwNQW5kcm9pZCBEZWJ1ZzEQMA4G
A1UECgwHQW5kcm9pZDELMAkGA1UEBhMCVVMwHhcNMTYwNTE3MTYxNzM0WhcNNDYwNTEwMTYxNzM0
WjA3MRYwFAYDVQQDDA1BbmRyb2lkIERlYnVnMRAwDgYDVQQKDAdBbmRyb2lkMQswCQYDVQQGEwJV
UzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAkafVu0j1zuB6+cpo6q5OsfhrlEFzVknFNs0c
vJorrlTTPZK3WSmkX9jZ0cp6oL60+4mHPouAR7Hq72gAs8u9Zh3eVrnV7uP7Rv2/z84DJuo34z1g
lahfkNPR/mCsYkK+ZqkC6uR46NnoftoKC/9vJSlUxYaBLT+mWvApz4rUKuMCAwEAATANBgkqhkiG
9w0BAQUFAAOBgQAERId+C7AD5Ew4Jv4mTmaZWBUtkinCKFSF4RtVa3xnHjL5xDPbAEq829gt+yx7
FkftGZO1x5nWEdAWyxiZgET3sKyl4ejRu1V5qvTMOcPMaVHw/e5v97FK8q756tQBcAu+Zs77P6MW
RxXtAwqeIkV1+L1rY8WueawfQ7Wbm1bPOg==
1921-2130/? V/GoogleSignatureVerifier: com.example.android.app signature not valid. Found:
MIIB3TCCAUYCAQEwDQYJKoZIhvcNAQEFBQAwNzEWMBQGA1UEAwwNQW5kcm9pZCBEZWJ1ZzEQMA4G
A1UECgwHQW5kcm9pZDELMAkGA1UEBhMCVVMwHhcNMTYwNTE3MTYxNzM0WhcNNDYwNTEwMTYxNzM0
WjA3MRYwFAYDVQQDDA1BbmRyb2lkIERlYnVnMRAwDgYDVQQKDAdBbmRyb2lkMQswCQYDVQQGEwJV
UzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAkafVu0j1zuB6+cpo6q5OsfhrlEFzVknFNs0c
vJorrlTTPZK3WSmkX9jZ0cp6oL60+4mHPouAR7Hq72gAs8u9Zh3eVrnV7uP7Rv2/z84DJuo34z1g
lahfkNPR/mCsYkK+ZqkC6uR46NnoftoKC/9vJSlUxYaBLT+mWvApz4rUKuMCAwEAATANBgkqhkiG
9w0BAQUFAAOBgQAERId+C7AD5Ew4Jv4mTmaZWBUtkinCKFSF4RtVa3xnHjL5xDPbAEq829gt+yx7
FkftGZO1x5nWEdAWyxiZgET3sKyl4ejRu1V5qvTMOcPMaVHw/e5v97FK8q756tQBcAu+Zs77P6MW
</code></pre>
<h1>UPDATE</h1>
<p><strong>I'm still having the error message, does anyone fix it since then?</strong></p>
<pre><code>/com.example.android.greenLeaf V/GoogleSignatureVerifier: com.google.android.gms signature not valid. Found:
MIIEQzCCAyugAwIBAgIJAMLgh0ZkSjCNMA0GCSqGSIb3DQEBBAUAMHQxCzAJBgNVBAYTAlVTMRMw
EQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtHb29n
bGUgSW5jLjEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDAeFw0wODA4MjEyMzEz
MzRaFw0zNjAxMDcyMzEzMzRaMHQxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYw
FAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtHb29nbGUgSW5jLjEQMA4GA1UECxMHQW5k
cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDCCASAwDQYJKoZIhvcNAQEBBQADggENADCCAQgCggEBAKtW
LgDYO6IIrgqWbxJOKdoR8qtW0I9Y4sypEwPpt1TTcvZApxsdyxMJZ2JORland2qSGT2y5b+3JKke
dxiLDmpHpDsz2WCbdxgxRczfey5YZnTJ4VZbH0xqWVW/8lGmPav5xVwnIiJS6HXk+BVKZF+JcWjA
sb/GEuq/eFdpuzSqeYTcfi6idkyugwfYwXFU1+5fZKUaRKYCwkkFQVfcAs1fXA5V+++FGfvjJ/Cx
URaSxaBvGdGDhfXE28LWuT9ozCl5xw4Yq5OGazvV24mZVSoOO0yZ31j7kYvtwYK6NeADwbSxDdJE
qO4k//0zOHKrUiGYXtqw/A0LFFtqoZKFjnkCAQOjgdkwgdYwHQYDVR0OBBYEFMd9jMIhF1Ylmn/T
gt9r45jk14alMIGmBgNVHSMEgZ4wgZuAFMd9jMIhF1Ylmn/Tgt9r45jk14aloXikdjB0MQswCQYD
VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEUMBIG
A1UEChMLR29vZ2xlIEluYy4xEDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNVBAMTB0FuZHJvaWSCCQDC
4IdGZEowjTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBAUAA4IBAQBt0lLO74UwLDYKqs6Tm8/y
zKkEu116FmH4rkaymUIE0P9KaMftGlMexFlaYjzmB2OxZyl6euNXEsQH8gjwyxCUKRJNexBiGcCE
yj6z+a1fuHHvkiaai+KL8W1EyNmgjmyy8AW7P+LLlkR+ho5zEHatRbM/YAnqGcFh5iZBqpknHf1S
KMXFh4dd239FJ1jWYfbMDMy3NS5CTMQ2XFI1MvcyUTdZPErjQfTbQe3aDQsQcafEQPD+nqActifK
Z0Np0IS9L9kR/wbNvyz6ENwPiTrjV2KRkEjH78ZMcUQXg0L3BYHJ3lc69Vs5Ddf9uUGGMYldX3Wf
MBEmh/9iFBDAaTCK
</code></pre>
| 0 |
Command Python2 not found
|
<p>I have to use <code>Python2</code> for the following command: <code>python2 -m pip install SomePackage</code> in the command line. I get the message that <code>Python2</code>is not found, but I have definitly installed Python 2.7.1.</p>
<p>When I run <code>python --version</code> I get the output <code>Python 3.5.1</code>. </p>
<p>Edit:
I use Windows. And the commands <code>whereis</code> and <code>env</code> were also not found.</p>
| 0 |
Retrofit : Getting error ** End of input at line 1 column 1**
|
<p>I don't know where my problem is. I've to post raw body like </p>
<pre><code>{"app_id":"abced","app_key":"abced","request":"login","username":"[email protected]","password":"1234"}
</code></pre>
<p>I'm using retrofit 2.0. I created a interface like</p>
<pre><code> @FormUrlEncoded
@POST("index.php/")
Call<LoginResponse> getHome(@Field("app_id") String request,
@Field("app_key") String request1,
@Field("request") String request2,
@Field("username") String request3,
@Field("password") String request4);
</code></pre>
<p>and calling like this:</p>
<pre><code> Retrofit retrofitget = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
MyAPI ApiData = retrofitget.create(MyAPI.class);
Call<LoginResponse> GalleryGetSet = ApiData.getHome("abced","abced","login","[email protected]","1234");
GalleryGetSet.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
Log.e(TAG, "data1" + response.body().getError());
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.e(TAG, "Error2" + t.getMessage());
}
});
</code></pre>
<p>always getting error : <strong>End of input at line 1 column 1</strong>
Is it right process to post the raw body data through retrofit post or i'm wrong. Already google it but not got my solution.
Please anyone help me out. </p>
<p>I also tried in this way
<strong>in interface</strong></p>
<pre><code>@FormUrlEncoded
@POST("index.php")
Call<LoginResponse> getHome1(@Field("login") String data);
</code></pre>
<p>and while calling </p>
<pre><code> Retrofit retrofitget = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.build();
MyAPI ApiData = retrofitget.create(MyAPI.class);
Call<LoginResponse> listGalleryGetSet = ApiData.getHome("ABCD","ABCD","login","[email protected]","1234");
listGalleryGetSet.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
Log.e(TAG, "data1" + response.body().getError());
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.e(TAG, "Error" + t.getMessage());
}
});
</code></pre>
<p>My LoginResponse class</p>
<pre><code>public class LoginResponse {
private String error;
private Boolean vlink;
/**
*
* @return
* The error
*/
public String getError() {
return error;
}
/**
*
* @param error
* The error
*/
public void setError(String error) {
this.error = error;
}
/**
*
* @return
* The vlink
*/
public Boolean getVlink() {
return vlink;
}
/**
*
* @param vlink
* The vlink
*/
public void setVlink(Boolean vlink) {
this.vlink = vlink;
}
</code></pre>
<p>}</p>
<p><a href="https://i.stack.imgur.com/LT56u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LT56u.png" alt="**This is how I'm posting on postman**"></a></p>
<p><strong>dependency</strong></p>
<pre><code> compile 'com.squareup.retrofit2:retrofit-converters:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
</code></pre>
<p><strong>Thanks in advance</strong></p>
| 0 |
how to install numpy on mac
|
<p>I'm trying to install Numpy on my mac so i can practice doing some programming for data science. However i have no idea what i'm doing when it comes to downloading software and btw my knowledge of software instillation in general is terrible (i'm more of a pure mathematician). If it isn't as simple as hit download and it works (as it seemed to do with windows) i'm finding myself getting stuck.</p>
<p>I have python 3.5.1 downloaded on my mac. So the book i'm going through at the moment when talking about arrays starts by saying >>>import numpy, in the command prompt. Thinking it would just be as easy as that i tried it, but obviously it wasn't that simple because i haven't downloaded it. Anyway then i looked into downloading numpy, i downloaded a folder in my downloads called numpy.1.11.0 and copied and pasted it into my desktop. I went back to the idle and typed >>>import numpy again, and again it didn't work. </p>
<p>I'm so confused as to what to do now, i've looked at some older posts but they haven't helped, i've also downloaded an open source package called anaconda (something mentioned in the other posts) which i think has everything (data science related) on it but i have no idea how to use it. Do i create python scripts in anaconda? Do i create the scripts before and some how run them in anaconda? </p>
<p>I'd really appreciate any help regarding how to get numpy installed or perhaps how to start using python in anaconda (or both). I've found myself getting lost in all the jargon in the other posts, a simple step by step approach i.e "first click this", "then install this" would probably be best suited to me, if anyone knows where i can find instructions in this form i'd very much appreciate it.</p>
<p>Thanks for the help!</p>
<p>Edit: Thanks to everyone for the help it has been great, in particular i tried pip3 install numpy in the command line. Now i can import numpy in the python idle. If i want to use it in a script file (i'm using text wrangler for this) would i just import numpy as usual?</p>
<p>In addition i started playing around with anaconda and using the spyder package this also let's me run python scripts and allows me to import numpy. </p>
| 0 |
Most efficient way to output a newline
|
<p>I was wondering what is the most efficient performant way to output a new line to console. Please explain why one technique is more efficient. Efficient in terms of performance.</p>
<p>For example:</p>
<pre><code>cout << endl;
cout << "\n";
puts("");
printf("\n");
</code></pre>
<p>The motivation for this question is that I find my self writing loops with outputs and I need to output a new line after all iterations of the loop. I'm trying to find out what's the most efficient way to do this assuming nothing else matters. This assumption that nothing else matters is probably wrong.</p>
| 0 |
Multiple Linear Regression Model by using Tensorflow
|
<p>I want to build a multiple linear regression model by using Tensorflow.</p>
<p>Dataset: <a href="http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&doc=exercises/ex3/ex3.html" rel="noreferrer">Portland housing prices</a></p>
<p>One data example: 2104,3,399900 (The first two are features, and the last one is house price; we have 47 examples)</p>
<p>Code below:</p>
<pre><code>import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# model parameters as external flags
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_float('learning_rate', 1.0, 'Initial learning rate.')
flags.DEFINE_integer('max_steps', 100, 'Number of steps to run trainer.')
flags.DEFINE_integer('display_step', 100, 'Display logs per step.')
def run_training(train_X, train_Y):
X = tf.placeholder(tf.float32, [m, n])
Y = tf.placeholder(tf.float32, [m, 1])
# weights
W = tf.Variable(tf.zeros([n, 1], dtype=np.float32), name="weight")
b = tf.Variable(tf.zeros([1], dtype=np.float32), name="bias")
# linear model
activation = tf.add(tf.matmul(X, W), b)
cost = tf.reduce_sum(tf.square(activation - Y)) / (2*m)
optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate).minimize(cost)
with tf.Session() as sess:
init = tf.initialize_all_variables()
sess.run(init)
for step in range(FLAGS.max_steps):
sess.run(optimizer, feed_dict={X: np.asarray(train_X), Y: np.asarray(train_Y)})
if step % FLAGS.display_step == 0:
print "Step:", "%04d" % (step+1), "Cost=", "{:.2f}".format(sess.run(cost, \
feed_dict={X: np.asarray(train_X), Y: np.asarray(train_Y)})), "W=", sess.run(W), "b=", sess.run(b)
print "Optimization Finished!"
training_cost = sess.run(cost, feed_dict={X: np.asarray(train_X), Y: np.asarray(train_Y)})
print "Training Cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n'
print "Predict.... (Predict a house with 1650 square feet and 3 bedrooms.)"
predict_X = np.array([1650, 3], dtype=np.float32).reshape((1, 2))
# Do not forget to normalize your features when you make this prediction
predict_X = predict_X / np.linalg.norm(predict_X)
predict_Y = tf.add(tf.matmul(predict_X, W),b)
print "House price(Y) =", sess.run(predict_Y)
def read_data(filename, read_from_file = True):
global m, n
if read_from_file:
with open(filename) as fd:
data_list = fd.read().splitlines()
m = len(data_list) # number of examples
n = 2 # number of features
train_X = np.zeros([m, n], dtype=np.float32)
train_Y = np.zeros([m, 1], dtype=np.float32)
for i in range(m):
datas = data_list[i].split(",")
for j in range(n):
train_X[i][j] = float(datas[j])
train_Y[i][0] = float(datas[-1])
else:
m = 47
n = 2
train_X = np.array( [[ 2.10400000e+03, 3.00000000e+00],
[ 1.60000000e+03, 3.00000000e+00],
[ 2.40000000e+03, 3.00000000e+00],
[ 1.41600000e+03, 2.00000000e+00],
[ 3.00000000e+03, 4.00000000e+00],
[ 1.98500000e+03, 4.00000000e+00],
[ 1.53400000e+03, 3.00000000e+00],
[ 1.42700000e+03, 3.00000000e+00],
[ 1.38000000e+03, 3.00000000e+00],
[ 1.49400000e+03, 3.00000000e+00],
[ 1.94000000e+03, 4.00000000e+00],
[ 2.00000000e+03, 3.00000000e+00],
[ 1.89000000e+03, 3.00000000e+00],
[ 4.47800000e+03, 5.00000000e+00],
[ 1.26800000e+03, 3.00000000e+00],
[ 2.30000000e+03, 4.00000000e+00],
[ 1.32000000e+03, 2.00000000e+00],
[ 1.23600000e+03, 3.00000000e+00],
[ 2.60900000e+03, 4.00000000e+00],
[ 3.03100000e+03, 4.00000000e+00],
[ 1.76700000e+03, 3.00000000e+00],
[ 1.88800000e+03, 2.00000000e+00],
[ 1.60400000e+03, 3.00000000e+00],
[ 1.96200000e+03, 4.00000000e+00],
[ 3.89000000e+03, 3.00000000e+00],
[ 1.10000000e+03, 3.00000000e+00],
[ 1.45800000e+03, 3.00000000e+00],
[ 2.52600000e+03, 3.00000000e+00],
[ 2.20000000e+03, 3.00000000e+00],
[ 2.63700000e+03, 3.00000000e+00],
[ 1.83900000e+03, 2.00000000e+00],
[ 1.00000000e+03, 1.00000000e+00],
[ 2.04000000e+03, 4.00000000e+00],
[ 3.13700000e+03, 3.00000000e+00],
[ 1.81100000e+03, 4.00000000e+00],
[ 1.43700000e+03, 3.00000000e+00],
[ 1.23900000e+03, 3.00000000e+00],
[ 2.13200000e+03, 4.00000000e+00],
[ 4.21500000e+03, 4.00000000e+00],
[ 2.16200000e+03, 4.00000000e+00],
[ 1.66400000e+03, 2.00000000e+00],
[ 2.23800000e+03, 3.00000000e+00],
[ 2.56700000e+03, 4.00000000e+00],
[ 1.20000000e+03, 3.00000000e+00],
[ 8.52000000e+02, 2.00000000e+00],
[ 1.85200000e+03, 4.00000000e+00],
[ 1.20300000e+03, 3.00000000e+00]]
).astype('float32')
train_Y = np.array([[ 399900.],
[ 329900.],
[ 369000.],
[ 232000.],
[ 539900.],
[ 299900.],
[ 314900.],
[ 198999.],
[ 212000.],
[ 242500.],
[ 239999.],
[ 347000.],
[ 329999.],
[ 699900.],
[ 259900.],
[ 449900.],
[ 299900.],
[ 199900.],
[ 499998.],
[ 599000.],
[ 252900.],
[ 255000.],
[ 242900.],
[ 259900.],
[ 573900.],
[ 249900.],
[ 464500.],
[ 469000.],
[ 475000.],
[ 299900.],
[ 349900.],
[ 169900.],
[ 314900.],
[ 579900.],
[ 285900.],
[ 249900.],
[ 229900.],
[ 345000.],
[ 549000.],
[ 287000.],
[ 368500.],
[ 329900.],
[ 314000.],
[ 299000.],
[ 179900.],
[ 299900.],
[ 239500.]]
).astype('float32')
return train_X, train_Y
def feature_normalize(train_X):
train_X_tmp = train_X.transpose()
for N in range(2):
train_X_tmp[N] = train_X_tmp[N] / np.linalg.norm(train_X_tmp[N])
train_X = train_X_tmp.transpose()
return train_X
import sys
def main(argv):
if not argv:
print "Enter data filename."
sys.exit()
filename = argv[1]
train_X, train_Y = read_data(filename, False)
train_X = feature_normalize(train_X)
run_training(train_X, train_Y)
if __name__ == '__main__':
tf.app.run()
</code></pre>
<p>Results I got:</p>
<blockquote>
<p>with learning rate 1.0 and 100 iterations, the model finally predicts a house with 1650 square feet and 3 bedrooms get a price $752,903, with:</p>
<p>Training Cost= 4.94429e+09</p>
<p>W= [[ 505305.375] [ 177712.625]]</p>
<p>b= [ 247275.515625]</p>
</blockquote>
<p>There must be some mistakes in my code as the plot of the cost function for different learning rates is just not same with the <a href="http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&doc=exercises/ex3/ex3.html" rel="noreferrer">solution</a></p>
<p>I should got the following results as solution suggested:</p>
<blockquote>
<p>theta_0: 340,413</p>
<p>theta_1: 110,631</p>
<p>theta_2: -6,649</p>
<p>The predicted price of the house should be $293,081.</p>
</blockquote>
<p>Any wrong with my usage of tensorflow?</p>
| 0 |
Hibernate exception: Duplicate entry for key 'PRIMARY'
|
<p>I've these (simplified) tables in my database</p>
<p><a href="https://i.stack.imgur.com/2VmOg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2VmOg.png" alt="enter image description here"></a></p>
<p>I've mapped the tables with these (simplified) two classes</p>
<p><strong>COMPANY</strong></p>
<pre><code>@Entity
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinTable(name="company_employee",
joinColumns={@JoinColumn(name="company_id")},
inverseJoinColumns={@JoinColumn(name="employee_id")})
@OrderBy("name ASC")
private SortedSet<Employee> employees = new TreeSet<Employee>();
// contructors + getters + setters
}
</code></pre>
<p><strong>EMPLOYEE</strong></p>
<pre><code>@Entity
public class Employee implements Comparable<Employee> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne(fetch = FetchType.LAZY, optional = true)
@JoinTable(name="company_employee",
joinColumns={@JoinColumn(name="employee_id")},
inverseJoinColumns={@JoinColumn(name="company_id")}
)
private Company company;
@Override
public int compareTo(Employee anotherEmployee) {
return this.name.compareTo(anotherEmployee.name);
}
// contructors + getters + setters + equals + hashcode
}
</code></pre>
<p>I'm using a <code>SortedSet/TreeSet</code> in employees defined in <code>Company</code> to obtain the employees sorted by name.</p>
<p>The problem arises when I persist the objects. I've read that you must establish the relation in both sides. I set the employee in company and the company in the employee before persisting the company. When I try to execute the persist, I'm obtaining the following exception</p>
<pre><code>Exception in thread "main" javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:86)
at es.rubioric.hibernate.MainTest.main(MainTest.java:43)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:67)
... 1 more
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1314)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:50)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:447)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:333)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:335)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1224)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:464)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:2890)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2266)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:230)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:61)
... 1 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '32-80' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2280)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2265)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
... 18 more
</code></pre>
<p>This is a simplified code that generates that exception. [EDITED commit location after comment by @NicolasFilotto]</p>
<pre><code> public static void main(String[] args) throws ParseException {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("TestDB");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
try {
Company c = new Company("Nike");
Employee e1 = new Employee("Anthony");
e1.setCompany(c); // line 26
Employee e2 = new Employee("Zenobia");
e2.setCompany(c); // line 28
Employee e3 = new Employee("Chuck");
e3.setCompany(c); // line 30
Employee e4 = new Employee("Bernard");
e4.setCompany(c); // line 32
c.getEmployees().add(e1);
c.getEmployees().add(e2);
c.getEmployees().add(e3);
c.getEmployees().add(e4);
em.persist(c);
tx.commit();
} finally {
em.close();
}
}
</code></pre>
<p>These are the SQL sentences internally executed by Hibernate.</p>
<pre><code>Hibernate: insert into Company (name) values (?)
Hibernate: insert into Employee (name) values (?)
Hibernate: insert into company_employee (company_id, employee_id) values (?, ?)
Hibernate: insert into Employee (name) values (?)
Hibernate: insert into company_employee (company_id, employee_id) values (?, ?)
Hibernate: insert into Employee (name) values (?)
Hibernate: insert into company_employee (company_id, employee_id) values (?, ?)
Hibernate: insert into Employee (name) values (?)
Hibernate: insert into company_employee (company_id, employee_id) values (?, ?)
Hibernate: insert into company_employee (company_id, employee_id) values (?, ?)
</code></pre>
<p>The same code works perfectly if I comment lines 26, 28, 30 and 32 (marked above). But I want to know why is that exception being generated. Why the duplicated key?</p>
<p>Thanks in advance.</p>
| 0 |
hide a column from table in MS SQL Server
|
<p>Can anyone please share the steps to hide the particular column from the table in SQL Server 2012 as I don't want to delete that column</p>
<p>By hide I mean that whenever I use the select query against that particular table it should never show me that column.</p>
<p>Is it possible?
I need to make the column as hidden irrespective of any user login and whatever query i use</p>
<h3>3rd party edit</h3>
<p>Based on the comment <code>But the problem is whenever i open the table in sql i dont want to see that particular column</code> i assume that the question is: </p>
<ul>
<li>How can i configure <a href="/questions/tagged/ssms" class="post-tag" title="show questions tagged 'ssms'" rel="tag">ssms</a> so that opening a table definition inside sql management studio to only show the columns the connected user has select right to?</li>
</ul>
<p>The screenshot below shows all columns of the table Employee despite the fact that the login <code>StackoverIntern</code> has no select rights to the columns <code>SSN, Salary</code></p>
<p><a href="https://i.stack.imgur.com/f8edM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f8edM.png" alt="SSMS table defintion shows all columns"></a> </p>
| 0 |
Uncaught TypeError: $(...).dataTable is not a function
|
<p>I have that error on my php file.
I have check my libraries order but i think is correct.
This is my script code:</p>
<pre><code>< script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js">
</script>
<script>
$(document).ready(function() {
$('#tablaLocalizaciones').dataTable({
"ajax": "tabla.php",
"columns":[
{ "data":"nombre"},
{ "data":"tipo"},
]
});
} );
</script>
</code></pre>
<p>any ideas?
Thanks</p>
| 0 |
Firebase confirmation email not being sent
|
<p>I've set up Firebase email/password authentication successfully, but for security reasons I want the user to confirm her/his email.
It says on Firebases website:</p>
<blockquote>
<p>When a user signs up using an email address and password, a confirmation email is sent to verify their email address.</p>
</blockquote>
<p>But when I sign up, I doesn't receive a confirmation email.</p>
<p>I've looked and can only find a code for sending the password reset email, but not a code for sending the email confirmation.</p>
<p>I've looked here:</p>
<p><a href="https://firebase.google.com/docs/auth/ios/manage-users#send_a_password_reset_email" rel="noreferrer">https://firebase.google.com/docs/auth/ios/manage-users#send_a_password_reset_email</a></p>
<p>anyone got a clue about how I can do it?</p>
| 0 |
Android Firebase DynamiteModule: Failed to load module descriptor
|
<p>Since upgrading to the newest version of Firebase (9.0.0), I can't get rid of the following two errors when authenticating a user through <code>signInWithEmailAndPassword()</code>. Does anyone have an idea what's going on?</p>
<pre><code> 05-19 18:09:49.245 23550-23589/[PACKAGE] E/DynamiteModule: Failed to load
module descriptor class: Didn't find class
"com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor"
on path: DexPathList[[zip file
"/data/app/[PACKAGE]-3/base.apk"],nativeLibraryDirectories=
[/data/app/[PACKAGE]-3/lib/x86, /vendor/lib, /system/lib]]
</code></pre>
<p>And</p>
<pre><code> 05-19 18:09:49.252 23550-23550/[PACKAGE] E/FirebaseApp: Firebase API
initialization failure.java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at com.google.firebase.FirebaseApp.zza(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.zzbu(Unknown Source)
at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1748)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1723)
at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
(...)
Caused by: java.lang.IncompatibleClassChangeError: The method 'java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)' was expected to be of type virtual but instead was found to be of type direct (declaration of 'com.google.firebase.iid.zzg' appears in /data/data/[PACKAGE]/files/instant-run/dex/slice-com.google.firebase-firebase-iid-9.0.0_95503dc60ed409569d1585da411de93e6c633bf7-classes.dex)
at com.google.firebase.iid.zzg.zzeC(Unknown Source)
at com.google.firebase.iid.zzg.<init>(Unknown Source)
at com.google.firebase.iid.zzg.<init>(Unknown Source)
at com.google.firebase.iid.zzd.zzb(Unknown Source)
at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
at java.lang.reflect.Method.invoke(Native Method)
at com.google.firebase.FirebaseApp.zza(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.zzbu(Unknown Source)
at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1748)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1723)
at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
(...)
</code></pre>
| 0 |
HTML: insert image at select tag
|
<h2>Question</h2>
<p>i want to make my select tag like google's one
this is mine
<a href="https://i.stack.imgur.com/os15k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/os15k.png" alt="i try to put the flag on background-image because i research at forum everyone say like that"></a></p>
<h2>This is my code</h2>
<pre><code> `<script >
function format(state) {
if (!state.id) return state.text;
return "<img class='flag' src='Photos/" + state.id.toLowerCase() + ".jpg'/>" + $(originalOption).data('foo') + "' />" + state.text;
}
</script>
<select id="mobilephone">
<option value="indo" ><img src="Photos/indo.jpg" id="captchaimg">Indonesia</option>
<option style="background-image:url(Photos/rico.png);">Rico</option>
<option style="background-image:url(Photos/SA.png);">South Africa</option>
<option style="background-image:url(Photos/UK.jpg);">United Kingdom</option>
</select>`
</code></pre>
<p>I want to make it like image below</p>
<p><a href="https://i.stack.imgur.com/FroMx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FroMx.png" alt="enter image description here"></a></p>
| 0 |
Module not found: Error: Cannot resolve module 'module' mongodb while bundling with webpack
|
<p>Webpack is throwing the following errors when I try to use mongoose connect in my node application.</p>
<p>Initially there were a couple more errors like,</p>
<pre><code>Module not found: Error: Cannot resolve module 'fs'
</code></pre>
<p>Making the following changes in my webpack config file did the trick,</p>
<ul>
<li><p>I added node-loader and node object in my webpack config file.</p>
<p>node: {
console: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty'
},</p></li>
</ul>
<p>but the bellow error is still there. Any idea how to resolve it?</p>
<pre><code>WARNING in ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional/index.js
Critical dependencies:
63:18-42 the request of a dependency is an expression
71:20-44 the request of a dependency is an expression
78:35-67 the request of a dependency is an expression
@ ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional/index.js 63:18-42 71:20-44 78:35-67
WARNING in ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional/README.md
Module parse failed: /Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/README.md Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '#' (1:0)
at Parser.pp.raise (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:920:13)
at Parser.pp.getTokenFromCode (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:2813:8)
at Parser.pp.readToken (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:2508:15)
at Parser.pp.nextToken (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:2500:71)
at Parser.parse (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:1615:10)
at Object.parse (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:882:44)
at Parser.parse (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/lib/Parser.js:902:15)
at DependenciesBlock.<anonymous> (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/lib/NormalModule.js:104:16)
at DependenciesBlock.onModuleBuild (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:310:10)
at nextLoader (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:275:25)
@ ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional ^\.\/.*$
WARNING in ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional/LICENSE
Module parse failed: /Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/LICENSE Unexpected token (1:40)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:40)
at Parser.pp.raise (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:920:13)
at Parser.pp.unexpected (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:1483:8)
at Parser.pp.semicolon (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:1462:73)
at Parser.pp.parseExpressionStatement (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:1976:8)
at Parser.pp.parseStatement (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:1754:188)
at Parser.pp.parseTopLevel (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:1648:21)
at Parser.parse (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:1616:17)
at Object.parse (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/node_modules/acorn/dist/acorn.js:882:44)
at Parser.parse (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/lib/Parser.js:902:15)
at DependenciesBlock.<anonymous> (/Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/webpack/lib/NormalModule.js:104:16)
@ ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional ^\.\/.*$
ERROR in ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional/~/resolve-from/index.js
Module not found: Error: Cannot resolve module 'module' in /Users/nitesh/Documents/learnReact/day1/r3-foundation-boilerplate/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from
@ ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional/~/resolve-from/index.js 3:13-30
Child extract-text-webpack-plugin:
chunk {0} extract-text-webpack-plugin-output-filename 221 kB [rendered]
[0] ./~/css-loader!./~/postcss-loader!./src/styles/app.css 219 kB {0} [built]
[1] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built]
Child extract-text-webpack-plugin:
chunk {0} extract-text-webpack-plugin-output-filename 8.56 kB [rendered]
[0] ./~/css-loader!./~/postcss-loader!./src/styles/styles.css 7.06 kB {0} [built]
[1] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built]
Child extract-text-webpack-plugin:
chunk {0} extract-text-webpack-plugin-output-filename 7.92 kB [rendered]
[0] ./~/css-loader!./~/postcss-loader!./src/styles/slider.css 6.42 kB {0} [built]
[1] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built]
Child extract-text-webpack-plugin:
chunk {0} extract-text-webpack-plugin-output-filename 234 kB [rendered]
[0] ./~/css-loader!./~/postcss-loader!./src/styles/app_override.css 232 kB {0} [built]
[1] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built]
Child extract-text-webpack-plugin:
Asset Size Chunks Chunk Names
404a525502f8e5ba7e93b9f02d9e83a9.eot 75.2 kB
926c93d201fe51c8f351e858468980c3.woff2 70.7 kB
891e3f340c1126b4c7c142e5f6e86816.woff 89.1 kB
fb650aaf10736ffb9c4173079616bf01.ttf 151 kB
bae4a87c1e5dff40baa3f49d52f5347a.svg 386 kB
chunk {0} extract-text-webpack-plugin-output-filename 41.4 kB [rendered]
[0] ./~/css-loader!./~/postcss-loader!./src/styles/index.css 264 bytes {0} [built]
[1] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built]
[2] ./~/css-loader!./~/font-awesome/css/font-awesome.css 39.1 kB {0} [built]
[3] ./~/font-awesome/fonts/fontawesome-webfont.eot 82 bytes {0} [built]
[4] ./~/font-awesome/fonts/fontawesome-webfont.eot?v=4.6.1 82 bytes {0} [built]
[5] ./~/font-awesome/fonts/fontawesome-webfont.woff2?v=4.6.1 84 bytes {0} [built]
[6] ./~/font-awesome/fonts/fontawesome-webfont.woff?v=4.6.1 83 bytes {0} [built]
[7] ./~/font-awesome/fonts/fontawesome-webfont.ttf?v=4.6.1 82 bytes {0} [built]
[8] ./~/font-awesome/fonts/fontawesome-webfont.svg?v=4.6.1 82 bytes {0} [built]
Child extract-text-webpack-plugin:
chunk {0} extract-text-webpack-plugin-output-filename 88.8 kB [rendered]
[0] ./~/css-loader!./~/postcss-loader!./~/sass-loader?outputStyle=expanded!./src/styles/foundation.scss 87.3 kB {0} [built]
[1] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built]
Module not found: Error: Cannot resolve module 'module' mongodb
</code></pre>
<p>webpack.config.js</p>
<pre><code>var path = require('path')
var webpack = require('webpack')
var autoprefixer = require('autoprefixer')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var assetPath = '/assets/'
var absolutePath = path.join(__dirname, 'build', assetPath)
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./src/index'
],
target: 'node-webkit',
output: {
path: absolutePath,
filename: 'bundle.js',
publicPath: assetPath
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin("bundle.css")
],
module: {
loaders: [
{
test: /\.js$/,
loaders: [ 'babel' ],
exclude: /node_modules/,
include: path.join(__dirname, 'src')
},
// fonts and svg
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
{
// images
test: /\.(ico|jpe?g|png|gif)$/,
loader: "file"
},
{
// for some modules like foundation
test: /\.scss$/,
exclude: [/node_modules/], // sassLoader will include node_modules explicitly
loader: ExtractTextPlugin.extract("style", "css!postcss!sass?outputStyle=expanded")
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style", "css!postcss")
},
{ test: /\.json$/, loader: 'json-loader' },
{
test: /\.node$/,
loader: 'node-loader'
}
]
},
resolve: {
extensions: [ '', '.js', '.json', '.jsx', '.es6', '.babel', '.node'],
modulesDirectories: [ 'node_modules', 'app' ]
},
node: {
console: true,
fs: 'empty',
net: 'empty',
tls: 'empty'
},
postcss: function(webpack) {
return [
autoprefixer({browsers: ['last 2 versions', 'ie >= 9', 'and_chr >= 2.3']})
]
},
sassLoader: {
includePaths: [path.resolve(__dirname, "node_modules")]
}
}
</code></pre>
<p>package.json</p>
<pre><code>{
"name": "nodeReactMongo",
"version": "1.0.0",
"description": "redux-react-router and foundation boilerplate",
"keywords": [
"redux",
"react",
"router",
"routing",
"frontend",
"client",
"webpack",
"babel",
"sass",
"foundation",
"postcss"
],
"main": "index.js",
"scripts": {
"start": "node server"
},
"author": "nitte93",
"license": "ISC",
"dependencies": {
"axios": "^0.11.1",
"classnames": "^2.2.0",
"firebase": "^3.0.3",
"font-awesome": "^4.3.0",
"foundation-sites": "^6.1.2",
"json-loader": "^0.5.4",
"mongodb": "^2.1.20",
"mongoose": "^4.4.19",
"react": "^0.14.5",
"react-addons-update": "^0.14.7",
"react-dom": "^0.14.7",
"react-modal": "^1.3.0",
"react-router": "2.0.0-rc5",
"react-router-redux": "^2.1.0",
"redux": "^3.2.1",
"redux-form": "^5.2.5",
"redux-logger": "^2.5.2",
"redux-thunk": "^1.0.3",
"rethinkdb": "^2.3.1",
"underscore": "^1.8.3",
"what-input": "^1.1.4"
},
"optionalDependencies": {},
"devDependencies": {
"autoprefixer": "^6.3.2",
"babel-core": "^6.3.15",
"babel-loader": "^6.2.0",
"babel-plugin-transform-runtime": "^6.5.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-react-hmre": "^1.0.1",
"babel-preset-stage-0": "^6.5.0",
"babel-runtime": "^6.9.0",
"css-loader": "^0.23.1",
"express": "^4.13.3",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.8.5",
"jquery": "^2.2.4",
"node-sass": "^3.4.2",
"postcss-loader": "^0.8.0",
"react-redux": "^4.4.5",
"redux-devtools": "^3.1.0",
"redux-devtools-dock-monitor": "^1.0.1",
"redux-devtools-log-monitor": "^1.0.3",
"sass-loader": "^3.1.2",
"script-loader": "^0.6.1",
"serve-static": "^1.10.2",
"style-loader": "^0.13.0",
"url-loader": "^0.5.7",
"webpack": "^1.9.11",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.2.0"
}
}
</code></pre>
<p>In one of my react components file as soon as I do <code>import mongoose from 'mongoose'</code>. I'm getting this error.</p>
<pre><code>import React, { Component, PropTypes } from 'react'
import request from '../api/requestHandler'
import { reduxForm } from 'redux-form'
//import rethink from 'rethinkdb'
import mongoose from 'mongoose'
</code></pre>
| 0 |
NullPointerException: Attempt to invoke virtual method 'android.app.FragmentTransaction android.app.FragmentManager.beginTransaction()'
|
<p>When I try to dissmiss a FragmentDialog, my app crashes sometimes.<br>
Here's the log:</p>
<pre><code>Process: com.xxx, PID: 9981
java.lang.RuntimeException: Error receiving broadcast Intent { act=xxxx flg=0x10 (has extras) } in xxxxxx
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:893)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5438)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentTransaction android.app.FragmentManager.beginTransaction()' on a null object reference
at android.app.DialogFragment.dismissInternal(DialogFragment.java:296)
at android.app.DialogFragment.dismissAllowingStateLoss(DialogFragment.java:277)
at xxxxx.updateStatus(BaseAppCompatActivity.java:96)
at xxxxx.access$000(BaseAppCompatActivity.java:43)
at xxxxx$1.onReceive(BaseAppCompatActivity.java:79)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:883)
</code></pre>
<p>xxxxx.updateStatus(BaseAppCompatActivity.java:96)<br>
this line is try to dismiss a DialogFragment:</p>
<pre><code>mDialogFragment.dismissAllowingStateLoss();
</code></pre>
<p><br>
A DialogFragment is in my Activity.<br></p>
<pre><code>private SimpleBlockedDialogFragment mDialogFragment = SimpleBlockedDialogFragment.newInstance();
</code></pre>
<p>So mDialogFragment is not null.</p>
<p>I show dialog like this:</p>
<pre><code>FragmentTransaction ft = getFragmentManager().beginTransaction();
mDialogFragment.updateMessage("xxx");
mDialogFragment.show(ft, "block_dialog");
</code></pre>
<p>And dismiss dialog like this:</p>
<pre><code>mDialogFragment.dismissAllowingStateLoss();
</code></pre>
<p>Sometimes, I show dialog only once, but dismiss more than once. But I don't think that cause a crash.</p>
<p>Here's the dismissInternal function in the DialogFragment:</p>
<pre><code>void dismissInternal(boolean allowStateLoss) {
if (mDismissed) {
return;
}
mDismissed = true;
mShownByMe = false;
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
mViewDestroyed = true;
if (mBackStackId >= 0) {
getFragmentManager().popBackStack(mBackStackId,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
mBackStackId = -1;
} else {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(this);
if (allowStateLoss) {
ft.commitAllowingStateLoss();
} else {
ft.commit();
}
}
}
</code></pre>
<p>log tells me that getFragmentManager() return null. I don't know why this happened.<br>
How to dismiss a FragmentDialog correctly?<br></p>
<p><strong>update:</strong><br>
I try android.support.v4.app.FragmentTransaction, and still get an exception.</p>
<pre><code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentTransaction android.support.v4.app.FragmentManager.beginTransaction()' on a null object reference
at android.support.v4.app.DialogFragment.dismissInternal(DialogFragment.java:196)
at android.support.v4.app.DialogFragment.dismissAllowingStateLoss(DialogFragment.java:177)
</code></pre>
<p>Help~</p>
| 0 |
Firebase onMessageReceived not called when app in background
|
<p>I'm working with Firebase and testing sending notifications to my app from my server while the app is in the background. The notification is sent successfully, it even appears on the notification centre of the device, but when the notification appears or even if I click on it, the onMessageReceived method inside my FCMessagingService is never called. </p>
<p>When I tested this while my app was in the foreground, the onMessageReceived method was called and everything worked fine. The problem occurs when the app is running in the background.</p>
<p>Is this intended behaviour, or is there a way I can fix this?</p>
<p>Here is my FBMessagingService:</p>
<pre><code>import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FBMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.i("PVL", "MESSAGE RECEIVED!!");
if (remoteMessage.getNotification().getBody() != null) {
Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getNotification().getBody());
} else {
Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getData().get("message"));
}
}
}
</code></pre>
| 0 |
How would I take an excel file and convert its columns into lists in Python?
|
<p>I had the following question. Namely, suppose I have an excel file with some names in the first row. Then the next however many rows are single letter entries (so "A", "B", "C" and so on). </p>
<p>My goal is to extract the column and make it into a list, so that, say, for column 1 the list would start in row 2, the next entry would be from row 3, and so on, until the end is reached.</p>
<p>How would I do that in Python?</p>
| 0 |
How can I get the name of a List<string>
|
<p>I am working on a C# WPF application. Here is a sample of my code:</p>
<pre><code>private static List<string> a = new List<string>();
private static List<string> b = new List<string>();
private static List<string> c = new List<string>();
</code></pre>
<p>Then I have another list like this:</p>
<pre><code>private static List<List<string>> alphabet = new List<List<string>>() { a, b, c };
</code></pre>
<p>I need to access a, b, or c as a string. so I need to get the name of the items inside alphabet list. It seems that list does not have any name property.</p>
| 0 |
Application Insights not logging custom events
|
<p>I have setup Application Insights in my ASP.NET Core application in the C# Controller and it is logging basic data like Page Views, Response Time, etc. But I want to create some custom events and log those as well, but I cannot get any oft he Custom Events to show up in the Azure portal. Currently I'm using the Free version of Application Insights.</p>
<p>The is very straight forward</p>
<pre><code>var appInsights = new TelemetryClient();
appInsights.TrackEvent(eventName, properties);
</code></pre>
<p>Where the eventName is a string containing the custom event that I want to track and properties is a Dictionary to track some additional properties.</p>
<p>After I run the app and hit those lines a couple of times I can then go to the azure portal and see the basic information, but when I do a Search it says that there is 0 Custom Events and searching for any of the custom events by name returns no results.</p>
<p>I have a class that has the Telemetry stuff in it below</p>
<pre><code>public class ApplicationInsightsTracker : IApplicationTracker
{
private readonly TelemetryClient AppInsights = new TelemetryClient();
public void TrackEvent(string eventName, string userName, Dictionary<string, string> properties = null)
{
AppInsights.Context.User.AccountId = userName;
TrackEvent(eventName, properties);
}
public void TrackRequest(string eventName, string userName, TimeSpan elapsed,
Dictionary<string, string> properties = null)
{
AppInsights.Context.User.AccountId = userName;
TrackEvent(eventName, properties);
AppInsights.TrackRequest(eventName, DateTimeOffset.Now, elapsed, "200", true);
AppInsights.Flush();
}
private void TrackEvent(string eventName, IDictionary<string, string> properties = null)
{
AppInsights.TrackEvent(eventName, properties);
AppInsights.Flush();
}
}
</code></pre>
<p>Then a simple example of me using it is</p>
<pre><code> Tracker.TrackEvent("Visit HomePage", User.Identity.Name);
</code></pre>
<p>Edit: The above event is working, but the below one is not, it is not logging this one at all. This calls the TrackRequest and also the TrackEvent on the TelementryClient, but I'm not seeing these at all.</p>
<pre><code> Tracker?.TrackRequest("Drill Report", userName, stopwatch.Elapsed,
new Dictionary<string, string>
{
{ "DrillBy", report.DrillBy == null ? "None" : report.DrillBy.FriendlyName }
});
</code></pre>
<p>I somewhat take that back. I am seeing some of these events come through, but I logged a bunch of them back to back and I only see 2 of the 6 that I should be seeing? Any ideas what could be going on?</p>
| 0 |
node.js express request Id
|
<p>I'm trying to create some sort of a request Id for logging purposes which will be available to me through every function in the request flow. I want to log every step of the request flow with an Id stating which log line is for which request.</p>
<p>I've looked over some ideas and ran into 2 main suggestions:</p>
<p>The first is creating a middleware that will add a field in the 'req' object like so(as suggested <a href="https://stackoverflow.com/questions/17701796/how-to-identify-request-by-id-through-middleware-chain-in-express">here</a>):</p>
<pre><code>var logIdIterator = 0;
app.all('*', function(req, res, next) {
req.log = {
id: ++logIdIterator
}
return next();
});
</code></pre>
<p>And the second is using <a href="https://www.npmjs.com/package/continuation-local-storage" rel="noreferrer">continuation-local-storage</a></p>
<p>The problems are:</p>
<p>For the first approach - it means I'll have to pass an extra argument to each function in the flow and this is not an easy solution to do over a mature application with countless APIs and flows.</p>
<p>The second one looks promising but unfortunately it has some issues where the state gets lost(see <a href="https://github.com/othiym23/node-continuation-local-storage/issues/29" rel="noreferrer">here</a> for example).
Also, it happened a few times when we used our redis library - which is bad because redis requests happen on each of our flows.</p>
<p>I guess if I don't find another solution, I'll have to use the first approach, it's just that I want to avoid passing an extra parameter to thousands of existing functions. </p>
<p>My question is - how do you suggest to maintain a request Id through the request flow?</p>
| 0 |
Proper way to invalidate collection view layout upon size change
|
<p>I'm implementing a collection view whose items are sized based on the bounds of the collection view. Therefore when the size changes, due to rotating the device for example, I need to invalidate the layout so that the cells are resized to consider the new collection view bounds. I have done this via the <code>viewWillTransitionToSize</code> API. </p>
<p>This works well until the user presents a modal view controller over the view controller that contains the collection view, rotates the device, then dismisses it. When that occurs the item size hasn't updated to the appropriate size. <code>viewWillTransitionToSize</code> is called and the layout is invalidated as expected, but the collection view's bounds is still the old value. For example when rotating from portrait to landscape the collection view bounds value still has its height greater than the width. I'm not sure why that's the case, but I'm wondering if this is the best way to invalidate upon size change? Is there a better way to do it?</p>
<p>I have also tried subclassing <code>UICollectionViewFlowLayout</code> and overriding <code>shouldInvalidateLayoutForBoundsChange</code> to return <code>YES</code>, but for some reason this doesn't work even rotating without a modal presentation. It doesn't use the proper collection view bounds either.</p>
<pre><code>- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(nonnull id<UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[self.collectionView.collectionViewLayout invalidateLayout];
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> __nonnull context) {
[self.collectionView.collectionViewLayout invalidateLayout];
} completion:^(id<UIViewControllerTransitionCoordinatorContext> __nonnull context) {
//finished
}];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewFlowLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
//collectionView.bounds.size is not always correct here after invalidating layout as explained above
}
</code></pre>
<p>I've also tried invaliding it in the completion block but it still doesn't use the proper collection view bounds.</p>
<p>If I invalidate the layout again in <code>viewWillAppear</code>, this does use the proper collection view bounds which resolves the issue with rotating with the modally presented view controller. But this shouldn't be necessary, perhaps there are other situations where this won't be sized properly.</p>
| 0 |
Single variable category scatter plot pandas
|
<p>Is It possible to plot single value as scatter plot?
I can very well plot it in line by getting the ccdfs with markers but I want to know if any alternative is available? </p>
<p>Input: </p>
<p>Input 1</p>
<pre><code>tweetcricscore 51 high active
</code></pre>
<p>Input 2</p>
<pre><code>tweetcricscore 46 event based
tweetcricscore 12 event based
tweetcricscore 46 event based
</code></pre>
<p>Input 3</p>
<pre><code>tweetcricscore 1 viewers
tweetcricscore 178 viewers
</code></pre>
<p>Input 4</p>
<pre><code>tweetcricscore 46 situational
tweetcricscore 23 situational
tweetcricscore 1 situational
tweetcricscore 8 situational
tweetcricscore 56 situational
</code></pre>
<p>I can very much write scatter plot code with <code>bokeh</code> and <code>pandas</code> using <code>x</code> and <code>y</code> values. But in case of single value ?</p>
<p>When all the inputs are merged as one input and are to be grouped by <code>col[3]</code>, values are <code>col[2]</code>. </p>
<p><strong>The code below is for data set with 2 variables</strong></p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from pylab import*
import math
from matplotlib.ticker import LogLocator
import pandas as pd
from bokeh.charts import Scatter, output_file, show
df = pd.read_csv('input.csv', header = None)
df.columns = ['col1','col2','col3','col4']
scatter = Scatter( df, x='col2', y='col3', color='col4', marker='col4', title='plot', legend=True)
output_file('output.html', title='output')
show(scatter)
</code></pre>
<p>Sample Output </p>
<p><a href="https://i.stack.imgur.com/akQlX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/akQlX.png" alt="enter image description here"></a></p>
| 0 |
Toggle Checkbox using JavaScript
|
<p>I had this working, but I didnt save and cannot replicate. I am trying to toggle checkboxes using <code>if else</code>. What am I doing wrong. </p>
<p>What I thought would work:</p>
<pre><code>function myForm() {
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == "checkbox") {
if(inputs[i].checked = false) {
inputs[i].checked = true;
} else {
if(inputs[i].checked = true) {
inputs[i].checked = false;
}
}
}
}
}
</code></pre>
| 0 |
Can't find "Python.h" file while installing Watchman
|
<p>I use Linux Mint 17 'Quiana' and I want to install Watchman to use later Ember.js. Here were my steps:</p>
<pre><code>$ git clone https://github.com/facebook/watchman.git
</code></pre>
<p>then</p>
<pre><code>$ cd watchman
$ ./autogen.sh
$ ./configure.sh
</code></pre>
<p>and, when I ran <code>make</code> to compile files, it returned the following error:</p>
<pre><code>pywatchman/bser.c:31:20: fatal error: Python.h: no such file or directory
#include <Python.h>
^
compilation terminated.
error: command 'i686-linux-gnu-gcc' failed with exit status 1
make[1]: *** [py-build] Error 1
make[1]: Leaving the directory `/home/alex/watchman'
make: *** [all] Error 2
</code></pre>
<p>I tried to run</p>
<pre><code>$ sudo apt-get install python3-dev
</code></pre>
<p>but it appears to be already in my system. What have I done wrong?</p>
| 0 |
How to open external programs in Python
|
<p>Duplicate edit: no, i did that but it doesnt want to launch firefox.
I am making a cortana/siri assistant thing, and I want it to lets say open a web browser when I say something. So I have done the if part, but I just need it to launch firefox.exe I have tried different things and I get an error . Here is the code. Please help! It works with opening notepad but not firefox..</p>
<pre><code>#subprocess.Popen(['C:\Program Files\Mozilla Firefox\firefox.exe']) opens the app and continues the script
#subprocess.call(['C:\Program Files\Mozilla Firefox\firefox.exe']) this opens it but doesnt continue the script
import os
import subprocess
print "Hello, I am Danbot.. If you are new ask for help!" #intro
prompt = ">" #sets the bit that indicates to input to >
input = raw_input (prompt) #sets whatever you say to the input so bot can proces
raw_input (prompt) #makes an input
if input == "help": #if the input is that
print "*****************************************************************" #says that
print "I am only being created.. more feautrues coming soon!" #says that
print "*****************************************************************" #says that
print "What is your name talks about names" #says that
print "Open (name of program) opens an application" #says that
print "sometimes a command is ignored.. restart me then!"
print "Also, once you type in a command, press enter a couple of times.."
print "*****************************************************************" #says that
raw_input (prompt) #makes an input
if input == "open notepad": #if the input is that
print "opening notepad!!" #says that
print os.system('notepad.exe') #starts notepad
if input == "open the internet": #if the input is that
print "opening firefox!!" #says that
subprocess.Popen(['C:\Program Files\Mozilla Firefox\firefox.exe'])
</code></pre>
| 0 |
C++ destructor with return
|
<p>In C++ if we define a class destructor as:</p>
<pre><code>~Foo(){
return;
}
</code></pre>
<p>upon calling this destructor will the object of <code>Foo</code> be destroyed or does
explicitly returning from the destructor mean that we don't ever want to destroy it.</p>
<p>I want to make it so that a certain object is destroyed only through another objects destructor i.e. only when the other object is ready to be destroyed.</p>
<p>Example:</p>
<pre><code>class Class1{
...
Class2* myClass2;
...
};
Class1::~Class1(){
myClass2->status = FINISHED;
delete myClass2;
}
Class2::~Class2(){
if (status != FINISHED) return;
}
</code></pre>
<p>I searched online and couldn't seem to find an answer to my question.
I've also tried figuring it out myself by going through some code step by step with a debugger but can't get a conclusive result.</p>
| 0 |
Adding spaces between words in a string c
|
<p>I am trying to write a program to insert spaces between words to fit a column, for example:</p>
<ul>
<li>You read in a line of text, eg: <code>Good morning how are you?</code></li>
<li>You read in the width of the column, eg: <code>40</code>.</li>
<li>Then I have counted how many spaces there are in this text (4).</li>
<li>Now I need to distribute the remaining spaces in between these words so the length of the text is 40.</li>
</ul>
<p>For example:</p>
<pre><code>Good morning how are you?
1234567890123456789012345678901234567890
</code></pre>
<p>My problem comes when I try to insert the spaces in between words as I don't know how to do this. This is what I have so far.</p>
<pre><code>#include <stdio.h>
#include <string.h>
char text[65], spaces[50], ch;
int i, remainder, spacesr, count, column, length, distribution;
int main(){
i = 0;
count = 0;
printf("Please enter a line of text: ");
while(ch != '\n')
{
ch = getchar();
text[i]=ch;
i++;
}
text[i]='\0';
printf("Text: %s",text);
printf ("Please enter the width of the column: ");
scanf ("%d", &column);
for (i = 0; text[i] != '\0'; i++) {
if (text[i] == ' ') {
count++;
}
}
length = strlen(text);
spacesr = column - length;
distribution = spacesr / count;
remainder = spacesr % count;
if (length > column) {
printf ("ERROR: Length of text exceeds column width.");
}
}
</code></pre>
<p>I have calculated the amount of spaces in the read in text, then calculated the amount of spaces I would have remaining, then divided that by the amount of spaces to determine how many spaces I need to put between each word. The remainder of these spaces will be distributed evenly after the main spaces have been entered.</p>
<blockquote>
<p>What do you mean by main spaces?</p>
</blockquote>
<p>Basically I want to fit the phrase "Good morning how are you?" to a column 40 characters wide by adding spaces between words. Is it possible to do something like this:</p>
<pre><code>for (i = 0; text[i] != '\0'; i++) {
if (text[i] == ' ') {
then add a certain amount of spaces to it
</code></pre>
| 0 |
Ansible: "Failed to connect to the host via ssh" error
|
<p>I'm trying to get set up with Ansible for the first time, to connect to a Raspberry Pi. Following the <a href="http://docs.ansible.com/ansible/intro_getting_started.html" rel="nofollow noreferrer">official 'getting started'</a> steps, I've made an inventory file:</p>
<pre><code>192.168.1.206
</code></pre>
<p>.. but the ping fails as follows:</p>
<pre><code>$ ansible all -m ping -vvv
No config file found; using defaults
<192.168.1.206> ESTABLISH SSH CONNECTION FOR USER: pi
<192.168.1.206> SSH: EXEC ssh -C -q -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=pi -o ConnectTimeout=10 -o ControlPath=/Users/username/.ansible/cp/ansible-ssh-%h-%p-%r 192.168.1.206 '/bin/sh -c '"'"'( umask 22 && mkdir -p "` echo $HOME/.ansible/tmp/ansible-tmp-1464128959.67-131325759126042 `" && echo "` echo $HOME/.ansible/tmp/ansible-tmp-1464128959.67-131325759126042 `" )'"'"''
192.168.1.206 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh.",
"unreachable": true
}
</code></pre>
<p>This looks the same as <a href="https://stackoverflow.com/questions/37213551/ansible-ssh-connection-fail">this question</a>, but adding password/user bits make no effect for me, shouldn't be necessary to ping, and aren't in the official example anyhow. In any case I'd prefer to configure Ansible to use a specific public/private key pair (as per <code>ssh -i ~/.ssh/keyfile</code> method..)</p>
<p>Grateful for assistance.</p>
<hr>
<p>Oh and yes the Raspberry is available at that address:</p>
<pre><code>$ ping 192.168.1.206
PING 192.168.1.206 (192.168.1.206): 56 data bytes
64 bytes from 192.168.1.206: icmp_seq=0 ttl=64 time=83.822 ms
</code></pre>
| 0 |
Executing a SAS program in R using system() Command
|
<p>My company recently converted to SAS and did not buy the SAS SHARE license so I cannot ODBC into the server. I am not a SAS user, but I am writing a program that needs to query data from the server and I want to have my R script call a .sas program to retrieve the data. I think this is possible using </p>
<p><code>df <- system("sas -SYSIN path/to/sas/script.sas")</code> </p>
<p>but I can't seem to make it work. I have spent all a few hours on the Googles and decided to ask here. </p>
<p>error message:</p>
<pre><code>running command 'sas -SYSIN C:/Desktop/test.sas' had status 127
</code></pre>
<p>Thanks!</p>
| 0 |
Custom Authentication Filters in multiple HttpSecurity objects using Java Config
|
<p>I want to have two different http web configurations with custom authentication filters using spring boot and spring java config.
I followed the sample application that can be found here: <a href="https://github.com/spring-projects/spring-security-javaconfig/blob/master/samples-web.md#sample-multi-http-web-configuration" rel="nofollow">https://github.com/spring-projects/spring-security-javaconfig/blob/master/samples-web.md#sample-multi-http-web-configuration</a>.
My understanding was, that this would end up in a separate spring filter chain for each of the web configurations. But both filters are invoked although the web configuration url pattern doesn't match the request.
For instance, requesting <a href="http://localhost:8080/api/dosomething" rel="nofollow">http://localhost:8080/api/dosomething</a> will invoke both filters, not only CustomApiAuthenticationFilter. Of course, it would be possible to check the request url in doFilterInternal and ignore the request if it doesn't match but I thought this should be done automatically by respecting the url pattern of the corresponding web configuration.
Furthermore, my RestController doesn't get called respectively Postman only receives Status Code 200 OK with no response body.</p>
<p>Two questions:
1. Is this behaviour by design or is the configuration wrong?
2. Why is my RestController not invoked?</p>
<pre><code>@EnableWebSecurity
public class SecurityConfiguration {
@Configuration
@Order(1)
public static class ApiConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Bean
public GenericFilterBean apiAuthenticationFilter() {
return new CustomApiAuthenticationFilter();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/**").addFilterAfter(apiAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests().antMatchers("/api/**").authenticated();
}
}
@Configuration
@Order(2)
public static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public GenericFilterBean webAuthenticationFilter() {
return new CustomWebAuthenticationFilter();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/").addFilterAfter(webAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class)
.authorizeRequests().antMatchers("/").authenticated();
}
}
}
public class CustomApiAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
Authentication auth = new UsernamePasswordAuthenticationToken("sub", "password", ImmutableList.of(new SimpleGrantedAuthority("API")));
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
public class CustomWebAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
Authentication auth = new UsernamePasswordAuthenticationToken("sub", "password", ImmutableList.of(new SimpleGrantedAuthority("USER")));
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
@RestController
public class ApiController {
@RequestMapping(value = "/api/v1/dosomething", method = RequestMethod.GET)
public String getSomething() {
return "something";
}
}
</code></pre>
| 0 |
Typescript error "class is not a constructor"
|
<p>I am running the following typescript code in the ES6 target environment and it says that "Cars is not a constructor"</p>
<p>I have followed the <a href="https://stackoverflow.com/questions/34581714/why-does-this-typescript-output-class-is-not-a-constructor">link</a> and tried changing the target environment to ES5. It is working fine. Can some one tell why it is not working for target ES6.</p>
<p>Here is my TypeScript code:</p>
<pre><code>export class Cars {
constructor(public len: number,public wid: number) { }
}
export function getSize(): Cars {
return new Cars(20, 30);
};
</code></pre>
<p>Error is "Cars is not a constructor" in the function getSize.</p>
<p>By the way I am trying to load all the files with Systemjs.</p>
<p>By the way I am getting the error in the browser........ Not while compiling it...</p>
<p>Here is the compiled code of the above typescript....</p>
<pre><code>System.register([], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var Cars;
function getSize() {
return new Cars(20, 30);
}
exports_1("getSize", getSize);
return {
setters:[],
execute: function() {
class Cars {
constructor(len, wid) {
this.len = len;
this.wid = wid;
}
}
;
exports_1("Cars", Cars);
}
}
});
//# sourceMappingURL=Cars.js.map
</code></pre>
| 0 |
How to get Youtube Live Stream by Channel Id in Youtube API V3 in android?
|
<p>I am able to get the list of live stream: <a href="https://developers.google.com/youtube/v3/live/docs/liveStreams/list#examples" rel="noreferrer">https://developers.google.com/youtube/v3/live/docs/liveStreams/list#examples</a>
But how to get the live stream status and live stream link or id for particular channel using youtube v3 api in android?</p>
| 0 |
Prevent React from re-rendering a specific child component
|
<p>I have a react component that conditionally renders several child components. Simplified code is just:</p>
<pre><code>render(): {
const component1 = condition ? renderComponent2() : null;
const component2 = renderComponent2();
return (
<div>
{component1}
{component2}
</div>
);
}
</code></pre>
<p>The problem is that <code>component2</code> is getting destroyed and re-rendered whenever the <code>condition</code> changes. I'm trying to prevent that and keep the original element around. I tried adding a <code>key</code> to <code>component2</code> with no luck.</p>
<p>[edit] This is happening even when <code>component1</code> always exists and I change flag on it to hide it or not with CSS :/</p>
| 0 |
How to handle elements inside Shadow DOM from Selenium
|
<p>I want to automate file download completion checking in <code>chromedriver</code>.
<code>HTML</code> of each entry in downloads list looks like </p>
<pre><code><a is="action-link" id="file-link" tabindex="0" role="link" href="http://fileSource" class="">DownloadedFile#1</a>
</code></pre>
<p>So I use following code to find target elements:</p>
<pre><code>driver.get('chrome://downloads/') # This page should be available for everyone who use Chrome browser
driver.find_elements_by_tag_name('a')
</code></pre>
<p>This returns empty list while there are 3 new downloads. </p>
<p>As I found out, only parent elements of <code>#shadow-root (open)</code> tag can be handled.
So How can I find elements inside this <code>#shadow-root</code> element?</p>
| 0 |
401- Unauthorized authentication using REST API Dynamics CRM with Azure AD
|
<p>I'm trying to access a Dynamics CRM Online REST API with Azure AD oAuth 2 Authentication. In order to do so I followed these steps:<br/><br/>
- I've registered a web application and/or web api in Azure<br/>
- Configured the permissions to Dynamics CRM to have Delegated permissions "Access CRM Online as organization user"<br/>
- And created a Key with a 1 year expiration and kept the Client ID generated.
<br/><br/>
After the web app was configured on Azure I have created a Console application in .NET/C# that uses ADAL to make a simple request, in this case to retrieve a list of accounts:
<br/><br/></p>
<pre><code> class Program
{
private static string ApiBaseUrl = "https://xxxxx.api.crm4.dynamics.com/";
private static string ApiUrl = "https://xxxxx.api.crm4.dynamics.com/api/data/v8.1/";
private static string ClientId = "2a5dcdaf-2036-4391-a3e5-9d0852ffe3f2";
private static string AppKey = "symCaAYpYqhiMK2Gh+E1LUlfxbMy5X1sJ0/ugzM+ur0=";
static void Main(string[] args)
{
AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(ApiUrl)).Result;
var clientCredential = new ClientCredential(ClientId, AppKey);
var authenticationContext = new AuthenticationContext(ap.Authority);
var authenticationResult = authenticationContext.AcquireToken(ApiBaseUrl, clientCredential);
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
var result = httpClient.GetAsync(Path.Combine(ApiUrl, "accounts")).Result;
}
}
</code></pre>
<p>I retrieve an access token successfully but when I try to do a httprequest to CRM I always get a <strong>401 - Unauthorized status code</strong>. What am I missing?</p>
| 0 |
Android project build successfully but ran failed with error: java.util.zip.ZipException: duplicate entry
|
<p>I have update my android studio and SDK and some package dependencies on grade of the project and since then I have faced with a lot of problem that I think the reason is incompatibility between dependencies. </p>
<p>As I researched I found that many people have same problems and it is not rare. I have solved some of the error but problems just appears one after another and I am just confused. hope you can help me find out the problem and its solution.</p>
<p>Code works well on new android versions ! (a little strange) and I can compile and run the app on android 21+. but when I try to run it on below 21 android version it give me an error. Every thing was ok before I migrate to Android studio 2.</p>
<p>Here is the error code I get now :</p>
<blockquote>
<pre><code>FAILURE: Build failed with an exception.
</code></pre>
<ul>
<li><p>What went wrong: Execution failed for task ':transformClassesWithJarMergingForDebug'.</p>
<blockquote>
<p>com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry:
android/support/annotation/WorkerThread.class</p>
</blockquote></li>
<li><p>Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.</p></li>
</ul>
</blockquote>
<p>here is the project grade file :</p>
<pre><code>task wrapper(type: Wrapper) {
gradleVersion = '2.2'
}
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
classpath 'com.google.gms:google-services:2.1.0'
}
}
apply plugin: 'com.android.application'
allprojects {
repositories {
jcenter()
flatDir {
dirs 'libs'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile(name: 'aescrypt-0.0.1', ext: 'aar')
compile project(':viewmover-1.1.0 (1)')
compile project(':fab-1.1.2')
compile files('libs/slf4j-api-1.7.18.jar')
compile project(':uitools-1.1.0')
compile('com.android.support:appcompat-v7:23.4.0') {
exclude group: 'com.google.android', module: 'support-v4'
}
compile 'com.android.support:design:23.4.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.github.paolorotolo:appintro:3.4.0'
compile ('com.google.android.gms:play-services-gcm:8.1.0') {
exclude group: 'com.google.android', module: 'support-v4'
}
}
android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
configurations{
all*.exclude module: 'annotation'
}
defaultConfig {
applicationId "co.goldentime"
multiDexEnabled true
minSdkVersion 16
targetSdkVersion 23
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['submodules/linphone/mediastreamer2/java/src', 'submodules/linphone/java/j2se', 'submodules/linphone/java/common', 'submodules/linphone/java/impl', 'submodules/externals/axmlrpc/src/main/java', 'submodules/linphone/coreapi/help/java', 'src']
resources.srcDirs = ['submodules/linphone/mediastreamer2/java/src', 'submodules/linphone/java/j2se', 'submodules/linphone/java/common', 'submodules/linphone/java/impl', 'submodules/externals/axmlrpc/src/main/java', 'submodules/linphone/coreapi/help/java', 'src']
aidl.srcDirs = ['submodules/linphone/mediastreamer2/java/src', 'submodules/linphone/java/j2se', 'submodules/linphone/java/common', 'submodules/linphone/java/impl', 'submodules/externals/axmlrpc/src/main/java', 'submodules/linphone/coreapi/help/java', 'src']
renderscript.srcDirs = ['submodules/linphone/mediastreamer2/java/src', 'submodules/linphone/java/j2se', 'submodules/linphone/java/common', 'submodules/linphone/java/impl', 'submodules/externals/axmlrpc/src/main/java', 'submodules/linphone/coreapi/help/java', 'src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
jniLibs.srcDir 'libs'
java.exclude '**/mediastream/MediastreamerActivity.java'
}
// Move the tests to tests/java, tests/res, etc...
instrumentTest.setRoot('tests')
// Move the build types to build-types/<type>
// For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
// This moves them out of them default location under src/<type>/... which would
// conflict with src/ being used by the main source set.
// Adding new build types or product flavors should be accompanied
// by a similar customization.
debug.setRoot('build-types/debug')
release.setRoot('build-types/release')
}
}
apply plugin: 'com.google.gms.google-services'
</code></pre>
<p>I find out there is problem with different version of support-v4 but I do not know which one should be exclude. I have a "android-support-v4.jar" in the <strong>libs</strong>. </p>
<p>let me know if it is needed some other information.</p>
<p>thank you.</p>
| 0 |
Why is accessing an element of a dictionary by key O(1) even though the hash function may not be O(1)?
|
<p>I see how you can access your collection by key. However, the hash function itself has a lot of operations behind the scenes, doesn't it?</p>
<p>Assuming you have a nice hash function which is very efficient, it still may take many operations.</p>
<p>Can this be explained?</p>
| 0 |
fatal: Failed to resolve HEAD as a valid ref
|
<p>I am getting fatal: Failed to resolve HEAD as a valid ref. whenever I try to commit.</p>
<p>I have tried </p>
<pre><code>echo ref: refs/heads/master >.git/HEAD
</code></pre>
<p>but its not working</p>
<p>Also tried</p>
<pre><code>git commit
</code></pre>
<p>its not working either from below sources</p>
<p><a href="https://stackoverflow.com/questions/4848607/git-fatal-no-such-ref-head">Git 'fatal: No such ref: HEAD'</a>
<a href="https://stackoverflow.com/questions/19116545/git-tag-fatal-failed-to-resolve-head-as-a-valid-ref">git tag: fatal: Failed to resolve 'HEAD' as a valid ref</a></p>
<p>Please help in..All my commit history is also gone</p>
| 0 |
FireBase Cloud Messaging Not Working
|
<p>I am trying to use FireBase Cloud Messaging. I am receiving a token but its not getting any notifications from console.
Here is my Manifest:</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="careerage.jobseeker.app"
android:hardwareAccelerated="true"
android:versionCode="1"
android:versionName="0.0.1">
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="23" />
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:resizeable="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
<android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:hardwareAccelerated="true"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:supportsRtl="true">
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale"
android:label="@string/activity_name"
android:launchMode="singleTop"
android:theme="@android:style/Theme.DeviceDefault.NoActionBar"
android:windowSoftInputMode="adjustResize">
<intent-filter android:label="@string/launcher_name">
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".TokenService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service
android:name=".NotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</code></pre>
<p></p>
<p>And My Code is almost the same as from the sample:</p>
<pre><code>public class NotificationService extends FirebaseMessagingService {
private void sendNotification(String messagebody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("Notified")
.setContentText(messagebody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 , notificationBuilder.build());
}
private void sendSnackbar(String messagebody)
{
Toast.makeText(this,"Notified",Toast.LENGTH_LONG).show();
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Toast.makeText(this,"Message Received",Toast.LENGTH_LONG).show();
Log.d("Notification Received",remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
sendSnackbar(remoteMessage.getNotification().getBody());
}
}
</code></pre>
<p>I checked the Question here <a href="https://stackoverflow.com/questions/37351354/firebase-cloud-messaging-notification-not-received-by-device">Firebase cloud messaging notification not received by device</a>
but still it is not working.</p>
| 0 |
ASP.NET MVC: Link to another page with different Controller does not work
|
<p>I am developing a dashboard with rendering different KPI's. There is also an interaction with a tool, that's why I have chosen MVC.</p>
<p>Now I have a layout page with a navigation bar. In the Navigation bar I am linking with @Url.Action.
So far so good. Every page is working, and if a link is done where exists an other Controller, it works, too. Only in one link I have a problem - I get always the "resource not found" errorpage.</p>
<p>The page LockedOrder is not working.</p>
<p>My layout view looks like this:</p>
<pre><code><ul class="treeview-menu">
<li>
<a href="@Url.Action("Index", "Home")"><i class="fa fa-circle-o text-yellow"></i>Lab Dashboard<i class="fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li><a href="@Url.Action("Index", "Home")"><i class="fa fa-circle-o"></i>Home</a></li>
<li><a href="@Url.Action("Load" , "LockedOrder")"><i class="fa fa-circle-o"></i>Locked Order</a></li>
</ul>
</li>
<li><a href="@Url.Action("Index","DashboardXY" )"><i class="fa fa-circle-o text-blue"></i>DashboardXY</a></li>
</ul>
</code></pre>
<p>Here is my LockedOrder Controller:</p>
<pre><code>public class LockedOrderController : Controller
{
List<string> table = new List<string>();
// GET: LockedOrder
public ActionResult Load()
{
table = LoadTable(table);
return View();
}
}
</code></pre>
<p>A view Load.cshtml exists on the correct view folder.</p>
<p>My RouteConfig file:</p>
<pre><code>public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Locked Order
routes.MapRoute(
name: "LockedOrder",
url: "LockedOrder/{Load}/{id}",
defaults: new { controller = "LockedOrder", action = "Load" }
);
// Dashboard Resources Department Route
routes.MapRoute(
name: "DashboardXY",
url: "dashboard/{ departmentchooser}",
defaults: new { controller = "DashboardXY", action = "depchooser" }
);
routes.MapRoute(
name: "Default",
url: "Home/{action}/{id}",
defaults: new { controller = "Home", action = "Index" }
);
}
</code></pre>
<p>So why are all links working and only the link of LockedOrder not?</p>
<p>Please help me.
I'm really new in ASP.Net MVC, so if something is not clear, just ask me :)</p>
<p>Thanks!</p>
<p>Update: This is my errormessage which I get (I'm sorry, its in German, but may be it can help you to help me :) )</p>
<p><strong>Update 2</strong>
Now my code looks like this:
<a href="http://i.stack.imgur.com/mfbt6.png" rel="nofollow">RouteConfig</a>
<a href="http://i.stack.imgur.com/NBk1f.png" rel="nofollow">LockedOrderController</a></p>
| 0 |
Modules are installed using pip on OSX but not found when importing
|
<p>I successfully install different modules using pip and they are shown in the </p>
<pre><code>pip list
</code></pre>
<p>such as:</p>
<pre><code>beautifulsoup4 (4.4.1)
requests (2.10.0)
Scrapy (1.1.0)
</code></pre>
<h3>From Terminal</h3>
<p>However, whenever I try to import it</p>
<p><code>import beautifulsoup4</code> / <code>import bs4</code> or <code>import Scrapy</code> or <code>import requests</code></p>
<p>the following error is shown:</p>
<pre><code>$ python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named requests
</code></pre>
<p><em>Update:</em> if I launch python when I am at the correct site-packages directory</p>
<pre><code>$ pwd
/usr/local/lib/python2.7/site-packages
$ python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
>>> import requests
>>> import bs4
>>> import scrapy
</code></pre>
<p>Then it works. This would solve the issue if writing directly on the Terminal. However, I have no clue about how to make it work inside a file.py, which will be the normal use.</p>
<p>As far as I know, I only have Python2.7 installed.</p>
<h3>From file.py</h3>
<p>If I have a file.py saved in some local folder. This contains, for instance</p>
<pre><code>import requests
from bs4 import BeautifulSoup
</code></pre>
<p>when I try</p>
<pre><code>python file.py
</code></pre>
<p>I get the same error.</p>
<h1>Approach</h1>
<p>Same happens with any other module from the list.
I would think pip is installing them in a directory that Python is not reading, but as per what I read, it is the correct one.</p>
<p>They are all installed here:</p>
<pre><code>/usr/local/lib/python2.7/site-packages
</code></pre>
<p>Output requested by Padraic Cunningham:</p>
<pre><code>$ which -a pip
/usr/local/bin/pip
$ which -a python
/usr/bin/python
/usr/local/bin/python
</code></pre>
<p>Output requested by leovp:</p>
<pre><code>$ pip -V
pip 8.1.2 from /usr/local/lib/python2.7/site-packages (python 2.7)
</code></pre>
<h3>Threads already checked</h3>
<p>I have checked the following threads, but unfortunately they did not help me to solve the issue:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/33899996/installing-pyside-using-pip-nmake-not-found">installing pyside using PIP - nmake not found</a></li>
<li><a href="https://stackoverflow.com/questions/10569846/pip-installs-but-module-is-not-found">PIp installs but module is not found</a> ==> might have provided the right answer, but the links given do not work anymore</li>
<li><a href="https://stackoverflow.com/questions/28802358/google-protobuf-installed-but-module-not-found">google.protobuf installed, but module not found</a></li>
<li><a href="https://stackoverflow.com/questions/15052206/python-pip-install-module-is-not-found-how-to-link-python-to-pip-location">Python pip install module is not found. How to link python to pip location?</a></li>
</ul>
<p>Any ideas of what the problem is?</p>
| 0 |
HTTP requests without waiting for response
|
<p>Is it possible to send an HTTP request without waiting for a response?</p>
<p>I'm working on an IoT project that requires logging of data from sensors. In every setup, there are many sensors, and one central coordinator (Will mostly be implemented with Raspberry Pi) which gathers data from the sensors and sends the data to the server via the internet.</p>
<p>This logging happens every second. Therefore, the sending of data should happen quickly so that the queue does not become too large. If the request doesn't wait for a response (like UDP), it would be much faster.</p>
<p>It is okay if few packets are dropped every now and then.</p>
<p>Also, please do tell me the best way to implement this. Preferably in Java.</p>
<p>The server side is implemented using PHP.</p>
<p>Thanks in advance!</p>
<p>EDIT:
The sensors are wireless, but the tech they use has very little (or no) latency in sending to the coordinator. This coordinator has to send the data over the internet. But, just assume the internet connection is bad. As this is going to be implemented in a remote part of India.</p>
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.