input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Page Transformer animation like Google Play Books app <p>I want to implement <code>animation</code> when change the page in <code>ViewPager</code>, I know that I must use <code>PageTransformer</code>. I want to create an <code>animation</code> as <code>Play Books</code> app from google (like <a href="https://www.youtube.com/watch?v=gOJ15ysPsRo" rel="nofollow">this</a>).
I had searched a lot but no answer was accepted.
Any one can help?</p>
| <p>There are many page curl libraries:</p>
<p><a href="https://github.com/emilsjolander/android-FlipView" rel="nofollow">android-FlipView</a></p>
<p><a href="https://github.com/SalmanJawed/transitionviewpager" rel="nofollow">transitionviewpager</a></p>
<p><a href="https://github.com/openaphid/android-flip" rel="nofollow">android-flip</a></p>
<p><a href="https://github.com/alexvasilkov/FoldableLayout" rel="nofollow">FoldableLayout</a></p>
<p><a href="https://github.com/worldline/FoldableLayout" rel="nofollow">FoldableLayout2</a></p>
<p><a href="https://github.com/harism/android_page_curl" rel="nofollow">android_page_curl</a></p>
<p>I wish one of them fulfill your need</p>
|
How to understand call destructor method in CPP? <p>I am trying to understand the Destructor method in CPP.
I have known facts:
a. Destructor method would be automatically called when the instance ends.
b. If no explicit destructor methods defined, then compiler would create a default Destructor (though no specific task would be done such as no clean up user's dynamic memory.)</p>
<p>So Suppose A is a class name, I would like to know how many times class A's destructor would be called:</p>
<p>What I understand now is that the very last line of "delete []p" cannot be considered as a Destructor, it is just used to delete dynamic pointer p.
Since there is no information in A's class whether an explicitly destructor created, we think that a default class destructor created, thus twice called for p (because there are two elements in A[2]), and once for p2, total three times.</p>
<p>I am not sure whether above is correct or not. Hope CPP guru here could help me out. Thanks!!</p>
<pre><code>int main(){
A *p = new A[2];
A * p2 = new A;
A a;
delete []p;
}
</code></pre>
| <p>A destructor is going to get called exactly once for every instance of a class. I am excluding the marginal case of program termination making the entire process go away without invoking the oustanding objects' destructors (no point to it).</p>
<p>In your example, <code>p</code> is a pointer to an array containing two instances of a class. <code>delete[] p</code> is going to destroy two instances of the class. The class's destructor gets called once for each object getting destroyed, for a total of two times. <code>p2</code> is a pointer to one instance of the class, but since it is not explicitly <code>delete</code>d, that one falls into the marginal case. Finally, there's an instance of the class in function automatic scope. That instance gets destroyed when execution leaves the function scope, so that's another destructor call.</p>
<p>Whether or not a class has a default destructor, or an explicitly declared destructor, that makes no difference. Whatever destructor that class has, that destructor gets called.</p>
<p>Now, keep in mind that even though the destructor gets invoked multiple times here, it is being invoked exactly once for each instance of the class getting destroyed, and you have multiple instances.</p>
|
Getting current Date by CultureInfo <p>I'd like to get localized date in my Xamarin Forms app. I have tried two ways that work just fine in ASP.NET MVC, but I wonder why neither of them works in Xamarin.</p>
<pre><code>var currentDate DateTime.Now.ToString("yyyy/mm/dd", new CultureInfo("fa-IR"))
</code></pre>
<p>And by using culture info's calendar:</p>
<pre><code>var month = new CultureInfo("fa-IR").Calendar.GetMonth(DateTime.Now);
</code></pre>
<p>Both of these methods gave me the current date in <code>en-US</code>.</p>
<p>Apparently, <code>PersianCalendar</code> is <a href="https://developer.xamarin.com/api/type/System.Globalization.PersianCalendar" rel="nofollow">supposed</a> to be there. I can't understand what I'm missing?</p>
<p>I even tried NodaTime by, <code>SystemClock.Instance.Now.InZone(DateTimeZoneProviders.Tzdb["ââAsia/Tehran"]).Date.ââToString()</code> and the date is still in default culture!</p>
<p><strong>UPDATE</strong></p>
<p>Finally, <a href="https://www.nuget.org/packages/PersianCalendarPlus/" rel="nofollow">Persian Calendar Plus</a> did the job! But it would be very useful if someone could get the bottom of it!</p>
| <p>.Net framework doesnât support Persian calendar for the culture. This culture doesnât accept the calendar; therefore display of DateTime in this culture is impossible.</p>
<p>You need to create a custom <a href="http://stackoverflow.com/questions/15817348/how-to-customize-cultureinfos-default-calendar">helper</a> or some <a href="https://persianculture.codeplex.com/" rel="nofollow">extension</a> as mentioned here.</p>
<p>Using the above extension you can set like this,</p>
<pre><code>// create an instance of culture
CultureInfo info = new CultureInfo(âfa-Irâ);
//set Persian calendar to it without get exception
info.DateTimeFormat.Calendar = new PersianCalendar();
</code></pre>
|
Application all of a sudden crashing <p><strong>Background Info:</strong></p>
<p>I have been helping a friend of mine with an Android Application. He had the app built by some contractors who weren't very helpful. I told him I would help him out. </p>
<p>All of a sudden last week the app started crashing. </p>
<p>I am running this in Android Studio 2.1.3 on a Android 6.0 device.</p>
<p><strong>If I try to Sign Up I get:</strong></p>
<p><code>Unfortunately, myapp has stopped working.</code></p>
<p><strong>If I try to Login I get:</strong></p>
<p><code>Invalid Parameters
Please check the values entered and try again. Email and password cannot be blank.</code></p>
<p>I have tried debugging, however I am no Android professional. The closest I've come to is seeing that the pushToken has a length of 0. I don't really know if that means anything.</p>
<p>I'm not sure if you will need the entire Login class or not, if so please request it. I'm wondering if this is maybe just something simple or something to do with the newest Android updated.</p>
<p><strong>Here is the error:</strong></p>
<pre><code>10-07 23:46:19.440 17304-17304/com.myapp.myapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.myapp, PID: 17304
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.myapp.myapp/com.myapp.myapp.Register}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1885)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1579)
at android.app.Activity.startActivityForResult(Activity.java:3921)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
at android.app.Activity.startActivityForResult(Activity.java:3881)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:871)
at android.app.Activity.startActivity(Activity.java:4208)
at android.app.Activity.startActivity(Activity.java:4176)
at com.myapp.myapp.Login.signUp(Login.java:106)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
10-07 23:51:13.879 18211-18211/com.myapp.myapp E/linker: readlink('') failed: No such file or directory [fd=20]
10-07 23:51:13.879 18211-18211/com.myapp.myapp E/linker: warning: unable to get realpath for the library "/data/app/com.myapp.myapp-2/oat/arm64/base.odex". Will use given name.
</code></pre>
| <p>The problem and the solution for the crash are both in the error trace:</p>
<blockquote>
<p>Caused by: android.content.ActivityNotFoundException: Unable to find
explicit activity class {com.myapp.myapp/com.myapp.myapp.Register};
have you declared this activity in your AndroidManifest.xml?</p>
</blockquote>
<p>Open your <code>AndroidManifest.xml</code> file and make sure there's something like this in there:</p>
<pre><code> <activity android:name="com.myapp.myapp.Register">
</activity>
</code></pre>
|
Hiding the loader when updating kartik grid <p>I have a grid that gets updated every 3 seconds. Everything working fine but the problem is that the loader (showing...loading) keeps on poping up everytime the grid is updated. </p>
<p>This is what I have tried:</p>
<pre><code> echo DynaGrid::widget([
'columns' => $columns,
'showPersonalize' => true,
'options' => ['id' => 'trackyard'],
'gridOptions' => [
'options' => ['id' => 'assignsolicitation-inside'],
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'showPageSummary' => false,
'pager' => [
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last',
'maxButtonCount' => 10,
],
'toolbar' => [
['content' => '{dynagrid}'],
'{export}',
'{toggleData}'
],
'pjax' => true,
'pjaxSettings' => [
'options' => [
'id' => 'wod'
],],
'bordered' => false,
'striped' => true,
'condensed' => true,
'responsive' => true,
'responsiveWrap' => false,
'containerOptions' => ['style' => 'overflow:scroll'],
]
]);
?>
</code></pre>
<p>Then after the grid I have:</p>
<pre><code><?php
$script = <<< JS
function reloadgrid() {
var intervalID = setInterval(function() {
$.pjax.reload({container:'#trackyard-pjax'});
}, 3000);
setTimeout(function() {
clearInterval(intervalID);
}, 18000);
};
reloadgrid();
JS;
$this->registerJS($script, \yii\web\VIEW::POS_HEAD);
?>
</code></pre>
<p>How can i hide the loader?</p>
| <p>Use this in your widget</p>
<pre><code>'afterAjaxUpdate' => 'function(id) { $(\'.loader\').hide(); }'
</code></pre>
<p>Hope that will help you.</p>
|
Unable to parse through sqlite query using regular expressions <p>I am trying to figure out a way to iterate through a database and match all rows that have 02 in them using regular expressions. When a match is made the count should reset to 0 and when there is not a match the count should accumulate by negative 1. The code works when I use a list. </p>
<pre><code>import sqlite3
import re
conn = sqlite3.connect('p34.db')
c = conn.cursor()
r = re.compile(r'\b[5-9]*(?:0[5-9]?2|2[5-9]?0)[5-9]*\b')
q = "SELECT Number FROM 'Pick 3'"
c.execute(q)
rez = c.fetchall()
count = 0
for i in rez:
if i == r:
count = 0
else:
count = count -1
print(count)
conn.close()
print (rez)
</code></pre>
| <p>You probably want to use <a href="https://docs.python.org/3/library/re.html#re.search" rel="nofollow"><code>r.search()</code></a> to execute a regular expression search:</p>
<pre><code>for i in rez:
if r.search(i[0]):
count = 0
else:
count -= 1
</code></pre>
<p>Note the use of <code>i[0]</code> to get the first value from each tuple returned by the query.</p>
<p>Using <code>i == r</code> simply <em>compares</em> the tuple <code>i</code> (as returned by the query) to the compiled regular expression patter <code>r</code> and will never be true. It does not execute any of the search methods of the given pattern.</p>
|
why no tkinter distribution found <p>while installing tkinter i am having problem ,i have version 2.7.11. i have entered the <code>pip install tkinter</code> on dos but it shows the following message : </p>
<blockquote>
<p>collecting tkinter </p>
<p>Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter</p>
</blockquote>
<p>i have installed flask with the same procedure , it did but for tkinter it is showing problem .how can i get rid of this problem ?</p>
| <p>The Tkinter library comes in default with every Python installation</p>
<p>Try this:</p>
<pre><code>import Tkinter as tk
</code></pre>
|
xCode 8, swift 3, Facebook SDK login using LoginManager have to click twice to open FB login form <p>I'm using below function to login with Facebook, but I always have to click Login button twice to open the Facebook login page.</p>
<p>I already tested on simulator and device. The first time I click login button, the app goes to loginManager.logIn (...) function, but it never get into completion handler until 2nd click.</p>
<p>Anyone has this issue and solution for it? I'm using xCode 8 and Swift 3 </p>
<pre><code>private func loginWithFB(){
let loginManager = LoginManager()
loginManager.logIn([ .publicProfile, .userFriends, .email ], viewController: self) { loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login.")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
}
}
}
</code></pre>
| <p>This code works for me. The completion handler is called during each tap of the button.</p>
<p>Xcode version - 8.0</p>
<p>FBSDK version - 4.15.1</p>
<pre><code>@IBAction func loginTest(_ sender: UIButton) {
let loginManager = FBSDKLoginManager()
loginManager.logIn(withReadPermissions:["public_profile","user_friends","email"], from: self) {
loginResult,error in
print("completion handler called")
}
}
</code></pre>
|
Sir Trevor is not defined <p>I am new to Node.js. I wanted to use Sir Trevor Editor. So, I followed the following procedure.</p>
<p><code>npm install sir-trevor
cd node-modules/sir-trevor
npm install
npm run dev</code></p>
<p>Then I opened examples/index.html but page showed ordinary html textarea and following javascript errors were shown in the console</p>
<ul>
<li>file:///D:/node_modules/sir-trevor/sir-trevor.debug.css Failed to
load resource: net::ERR_FILE_NOT_FOUND</li>
<li>file:///D:/node_modules/sir-trevor/sir-trevor.debug.js Failed to load
resource: net::ERR_FILE_NOT_FOUND de.js:1 </li>
<li>Uncaught ReferenceError: SirTrevor is not defined index.html:47 </li>
<li>Uncaught ReferenceError: SirTrevor is not defined</li>
</ul>
<p>Can anyone please help me resolving this problem.</p>
| <p>Did you include the javascript and css files within node-modules/sir-trevor into your html page?</p>
|
Cofusing about lookup node with binary tree <p>I build a binary tree with python code, now I could print it in order with <code>testTree.printInorder(testTree.root)</code>. I have tried to lookup some node ,and the function <code>findNode</code> doesn't work anymore . <code>print testTree.findNode(testTree.root,20)</code> whatever I put in just return None.</p>
<pre><code>class TreeNode:
def __init__(self, value):
self.left = None;
self.right = None;
self.data = value;
class Tree:
def __init__(self):
self.root = None
def addNode(self,node,value):
if node == None:
self.root = TreeNode(value)
else:
if value < node.data:
if node.left == None:
node.left = TreeNode(value)
else:
self.addNode(node.left,value)
else:
if node.right == None:
node.right = TreeNode(value)
else:
self.addNode(node.right,value)
def printInorder(self,node):
if node != None:
self.printInorder(node.left)
print node.data
self.printInorder(node.right)
def findNode(self,node,value):
if self.root != None:
if value == node.data:
return node.data
elif value < node.data and node.left != None:
self.findNode(node.left,value)
elif value > node.data and node.right != None:
self.findNode(node.right,value)
else:
return None
testTree = Tree()
testTree.addNode(testTree.root, 200)
testTree.addNode(testTree.root, 300)
testTree.addNode(testTree.root, 100)
testTree.addNode(testTree.root, 30)
testTree.addNode(testTree.root, 20)
#testTree.printInorder(testTree.root)
print testTree.findNode(testTree.root,20)
</code></pre>
| <p>When you recurse to children in <code>findNode</code> you need to return the result, otherwise the function will implicitly return <code>None</code>:</p>
<pre><code>def findNode(self,node,value):
if self.root != None:
if value == node.data:
return node.data
elif value < node.data and node.left != None:
return self.findNode(node.left,value) # Added return
elif value > node.data and node.right != None:
return self.findNode(node.right,value) # Added return
else:
return None
</code></pre>
|
prototype function which will check all other function return true or false <pre><code>function checkname(){return false;}
function checkemail(){return false;}
//submit
function submitFormFunction(event){
//array validation function
var validators = [checkname, checkemail];
// bypass all function
var valid = validators.reduce(function(valid, validator){
return validator() && valid;
}, true);
if(valid){
$("#othersubmit-result").html('');
}else{
$("#othersubmit-result").css('color', 'red');
$("#othersubmit-result").html('sumbit not requirements.');
}
return valid;
}
</code></pre>
<p>this is my scrip , my intention is to make a function which will validation all other form function , so lets say if checkname function return = true and checkemail function return = true also, the function submitFormFunction will check this 2 functions , if all = true , it will pass the function and submit the form else let them know they the form is not finish.</p>
<pre><code>var ClassSignUpValidation = function (){};
ClassSignUpValidation.prototype.CheckName = function (_target)
{
return false;
}
ClassSignUpValidation.prototype.CheckEmail = function (_target)
{
return false;
}
</code></pre>
<p>but now i am using prototype js oop , this how my function looks like , how to do i make similar function like my old one and check all those function are they return true or false ?</p>
<p>error</p>
<pre><code>ClassSignUpValidation.prototype.CheckName = function (_target)
{
//set target id to jquery
_target = "#" + _target;
//set variable
var username_target = $(_target);
var username_value = username_target.val();
var username_errorspan = $("#user-errorResult");
****//here is the error****
if (username_value.length >= 4){
$.ajax({
type:"POST",
url:"/main/class/classvalidation.php",
async:false,
data:{
"username": username_value
},
success: function(data)
{
var usernameAvailable = JSON.parse(data);
var color = usernameAvailable.exists ? "#dfe0e6" : "red";
username_errorspan.html(usernameAvailable.message);
username_errorspan.css("color", color);
username_target.css("border-color", color);
if(usernameAvailable.exists === true){
return true;
}
}
});
};
return false;
}
</code></pre>
<p>error</p>
<pre><code>if (username_value.length >= 4){ here is the error point in
</code></pre>
| <p>you can still use your code and instead of giving reference as function name use instance.functionname for ex.</p>
<pre><code>submitFormFunction = function(event){
//array validation function
var validator = new ClassSignUpValidation
var validators = [validator.checkname, validator.checkemail];
// bypass all function
var valid = validators.reduce(function(valid, validator){
return validator() && valid;
}, true);
if(valid){
$("#othersubmit-result").html('');
}else{
$("#othersubmit-result").css('color', 'red');
$("#othersubmit-result").html('sumbit not requirements.');
}
return valid;
}
</code></pre>
<p>this should work.</p>
|
change cell value on button click <p>I have a table with the following.</p>
<pre><code> Table parts_stock
*--------------------*
| id | sku | stock |
| 1 | 101 | 2 |
| 2 | 102 | 3 |
*--------------------*
</code></pre>
<p>This is my code so far, i'm sure there are many ways to achieve this but ideally I want the qty <em>value</em> to change based on which button is clicked on without the page being refreshed (AJAX probably). </p>
<pre><code><tbody>
<?php
$query = 'SELECT stock_id, sku, in_stock ';
$query .= 'FROM parts_stock';
confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
if($num>0) {
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['stock_id'];
$sku = $row['sku'];
$qty = $row['in_stock'];
echo "<tr>";
echo "<td>".$sku."</td>";
echo "<td>".$qty."</td>";
echo "<td>
<a href='' onclick='rem_qty()' id='minus' name='minus' class='btn btn-warning'><span class='glyphicon glyphicon-minus'></span></a>
<a href='' onclick='add_qty()' id='plus' name='plus' class='btn btn-success'><span class='glyphicon glyphicon-plus'></span></a>
</td>";
</td>";
}
}?>
</tbody>
</code></pre>
<p>ajax_search.js</p>
<pre><code><script>
function rem_qty(){
$.ajax({
type: "POST",
url: "update_qty.php",
data: {id_m: stock_id}
});
}
function add_qty(){
$.ajax({
type: "POST",
url: "update_qty.php",
data: 'id_p: stock_id'
});
}
</script>
</code></pre>
<p>update_qty.php file</p>
<pre><code><?php
if (isset($_POST['id_m'])) {
$r = $_POST['id_m'];
echo $r;
$cur_inv = "SELECT in_stock FROM parts_stock WHERE stock_id = '".$r."'";
$cur_query = mysqli_query($connection, $cur_inv);
while ($row = mysqli_fetch_assoc($cur_query)) {
$rem_stock = $row['in_stock'];
$rem_stock -= 1;
}
$inv_update = "UPDATE parts_stock SET in_stock = '".$rem_stock."' WHERE stock_id = '".$value."'";
$inv_query = mysqli_query($connection, $inv_update);
}
if (isset($_POST['id_p'])) {
$a = $_POST['id_p'];
echo $a;
$cur_inv = "SELECT in_stock FROM parts_stock WHERE stock_id = '".$a."'";
$cur_query = mysqli_query($connection, $cur_inv);
while ($row = mysqli_fetch_assoc($cur_query)) {
$add_stock = $row['in_stock'];
$add_stock -= 1;
}
$inv_update = "UPDATE parts_stock SET in_stock = '".$add_stock."' WHERE stock_id = '".$value."'";
}
?>
</code></pre>
| <p>In your <code>HTML Button</code> to have a <code>onClick</code> event like this <code>onclick="buttonSubtract1('<?php if(isset($val['itm_code'])){echo $val['itm_code'];}?>')"</code><strong>(You can fetch the itm_code from your db)</strong>.Then Write your <code>AJAX</code> for <code>Request</code> and <code>Response</code>. And You need to Pass the <code>itm_code</code> through <code>var x</code>. e.g for like this <code>xmlhttp.open("POST", "ajax/get_items.php?val=" +x, true);</code></p>
<p>In AJAX file</p>
<pre><code>$item_cat = $_SESSION['item_cat']; // get a category from session
$iname=$_GET['val']; //get the value from main php file
if(!key_exists($item_cat)
{
$_SESSION['main'][$iname] = "1";
}
else
{
$_SESSION['main'][$item_cat][$iname]++;
}
echo "<pre>";
print_r($_SESSION['main']);
echo "</pre>";
</code></pre>
<p><strong>EDIT 1</strong></p>
<pre><code>function buttonSubtract1(x)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.location.assign('items.php');
}
}
xmlhttp.open("POST", "ajax/get_items.php?val=" +x, true);
xmlhttp.send();
}
</code></pre>
|
vb.net sql bulkcopy non string values issue <p>Can I use sqlbulkcopy to insert non string values from a csv file to an sql table?</p>
<p>I have the following code to create a datatable :</p>
<pre><code> Dim dt As New DataTable()
Dim line As String = Nothing
Dim i As Integer = 0
Using sr As StreamReader = File.OpenText("C:\Users\Administrator\Desktop\Sked Lente\Data\wingrd13.csv")
line = sr.ReadLine()
Do While line IsNot Nothing
Dim data() As String = line.Split(","c)
If data.Length > 0 Then
If i = 0 Then
For Each item In data
dt.Columns.Add(New DataColumn())
Next item
i += 1
End If
Dim row As DataRow = dt.NewRow()
row.ItemArray = data
dt.Rows.Add(row)
End If
line = sr.ReadLine()
Loop
End Using
</code></pre>
<p>I also have the following code to sqlbulkcopy :</p>
<pre><code> Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("SQLConnStr").ConnectionString)
cn.Open()
Using copy As New SqlBulkCopy(cn)
copy.ColumnMappings.Add(0, 0)
copy.ColumnMappings.Add(1, 1)
copy.ColumnMappings.Add(2, 2)
copy.ColumnMappings.Add(3, 3)
copy.ColumnMappings.Add(4, 4)
copy.ColumnMappings.Add(5, 5)
copy.ColumnMappings.Add(6, 6)
copy.DestinationTableName = "wingrd13"
copy.WriteToServer(dt)
End Using
End Using
</code></pre>
<p>I get an error at the line : copy.ColumnMappings.Add(6, 6)</p>
<p>The column in my database is of type real. </p>
<p>Regards</p>
| <p><code>SqlBulkCopy</code> will insert the data from your <code>DataTable</code> so if you want to insert data that is not text then your <code>DataTable</code> has to contain data that is not text. It's your responsibility to convert the data that you read from the CSV file into the appropriate data types before adding it to the <code>DataTable</code>. The conversion won't happen automatically.</p>
|
Displaying foreign key values using php mysql <p>I have 3 tables which are <code>states</code>, <code>cities</code>, <code>colleges</code>. All are contains id and corresponding names.
I have one more table <code>students</code> with column names are <code>id, studentname, state, city, college</code>.</p>
<p>Now i need to search how many students are from selected state/city/college, . sometimes i need to select multiple options like <strong>state</strong> and <strong>city</strong> but not <strong>college</strong> or state college but not city etc...</p>
<p>My query is: </p>
<pre><code>SELECT `state`, `city`, `college`, `student name` FROM `students` where `state`='1' AND `city`='4';
</code></pre>
<p>It returns records but <code>state</code> <code>city</code> <code>college</code> columns will be foreign keys, i need to see city name but not city id, state name but not state id, etc..</p>
| <p>use sql join assuming state_id, city_id, college_id are saved for each student for ex.</p>
<pre><code>SELECT `states.*`, `cities.*`, `colleges.*`, `students.*` FROM `students` left join states on states.id = students.state_id left join cities on cities.id = students.city_id left join colleges on colleges.id = students.id where `students.state`='1' AND `students.city`='4';
</code></pre>
|
When using PyMongo, No handlers could be found for logger "apscheduler.scheduler" <p>The code works fine printing to screen <code>hello</code> every second. This is done using the <code>bar</code> method, which is added to the scheduler as a job.</p>
<p><strong>Problem:</strong> However when the line <code>self.db.animals.insert_one({'name': 'lion'})</code> is added to the <code>bar</code> method, running the script gives an error</p>
<pre><code>No handlers could be found for logger "apscheduler.scheduler"
</code></pre>
<p>and the script stalls. Any idea what happened and how we can solve it?</p>
<pre><code>from apscheduler.schedulers.blocking import BlockingScheduler
import pymongo
class Foo(object):
def __init__(self, db, interval=1):
self.interval = interval
self.db = db
self.sched = BlockingScheduler()
self.sched.add_job(self.bar, 'interval', seconds = interval)
def start(self):
self.sched.start()
def stop(self):
self.sched.shutdown()
def bar(self):
print 'hello'
self.db.animals.insert_one({'name': 'lion'})
client = pymongo.MongoClient("localhost", 27017)
db = client.earth
foo = Foo(db, 0.2)
foo.start()
</code></pre>
| <p>That's not an error, but a warning. Python's logging system is trying to tell you that it has no outlet for logging output because you haven't configured it. Try using <code>logging.basicConfig(level=logging.DEBUG)</code>.</p>
|
get the value of the drop down in jquery on page load <p>I want to get the value of the dropdown on document ready but i am getting only the first value of the drop down
I have tried this</p>
<pre><code><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var car=$('.car').val();
alert(car);
});
</script>
</head>
<body>
<select class="car">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</body>
</html>
</code></pre>
| <p>try this</p>
<pre><code><script>
$(document).ready(function()
{
var car = $('.car :selected').val();
alert(car);
});
</script>
</code></pre>
|
How to stack + center two text views using programatic constraints? <p>I'm trying to achieve a hard coded layout where two text views should be stacked on top of each other and centered in a parent UICollectionViewCell:</p>
<pre><code>----------------------
| |
| This is text |
| Also text |
| |
----------------------
</code></pre>
<p>Due to various legacy/business reasons, I should be doing this using constraints hard coded in a subclass of UICollectionViewCell. The two text views can vary in length, but should be centered vertically in the parent view, while being on top of one another.</p>
<p>Is there an easy way to express this in constraints? I'm a bit new to this type of layout system, so any help is appreciated!</p>
<p>The app I am working with uses the Masonry (<a href="https://github.com/SnapKit/Masonry" rel="nofollow">https://github.com/SnapKit/Masonry</a>) library as well, if that makes things easier.</p>
| <p>Let's asume that the labels are named <code>textView1</code> and <code>textView2</code>.</p>
<p>What you need is to set a constraint for centering horizontally <code>textView1</code> to it's <code>superview</code>(the <code>UICollectionViewCell</code>), then center <code>textView2</code> with <code>textView1</code> (you can center to it's <code>superview</code> too) and you will have both centered.</p>
<p>For getting it on top of one another, you have to set a constraint for setting <code>textView2</code> top as the <code>textView1</code> bottom.</p>
<p>Never used Masonry, but looks like you need to have these constraints:</p>
<pre><code>[textView1 mas_makeConstraints:^(MASConstraintMaker *make) {
//Center first textView in the superview
make.centerX.equalTo(superview);
}];
[textView2 mas_makeConstraints:^(MASConstraintMaker *make) {
//Center second textView with the first one
make.centerX.equalTo(textView1);
//Set second textView to be below the first one
make.top.equalTo(textView1.mas_bottom);
}];
</code></pre>
|
Hide element on checkbox click/check, re-insert element on checkbox uncheck <p>Im learning Jquery so please bear with me here I would like to hide / remove a <code>DIVs</code> content if a checkbox is check></p>
<p>When checkbox is <strong>unchecked</strong> <strong>I would like the <code>DIVs</code> content to re-appear</strong>,(which was hidden on checkbox checked.)</p>
<p>I have managed to solve part 1 of the problem, hiding the content but Im stuck on getting content re-appear.</p>
<p><a href="https://jsfiddle.net/leela89/x44fjg7j/" rel="nofollow">YOU CAN VIEW MY JSFIDDLE HERE</a></p>
<p>Any help appreciated</p>
| <pre><code>$(function() {
$('.return_to_pickup_location').click(function() { //fire when the button is clicked
$('form input:checkbox').each(function() {
var checkbox = $(this);
if(checkbox.is(':checked'))
$('.returnLocation').hide("slow");
else
$('.returnLocation').show("slow");
});
});
});
</code></pre>
<p>Just add show to the element in else block.</p>
|
Upgrading OS, will it keep android packages? <p>I have android studio (I don't use it) installed in my windows 8.1 and I am upgrading my os to windows 10. Which folders should I backup to skip downloading the packages from Android SDK Manager in Windows 10. </p>
<p>I don't have knowledge of android studio yet and as it takes lot of time to download those packages, which folders should I backup to skip the fresh downloading again.</p>
<p>Thanks.</p>
| <ol>
<li>Open your user under the Users in C drive.</li>
<li>Go to the location \AppData\Local\Android and backup the entire sdk folder.
(Note the AppData folder might be hidden).</li>
<li>After upgrading, place the backup in exactly the same location as before.</li>
</ol>
<p>Happy Upgrading! :)</p>
|
"cannot find symbol" error in Java <p>I am new to Java, and trying out simple examples to get familiar with the basics. This is a program to see if three integers specified by the user are all equal.</p>
<pre><code>import java.lang.*;
import java.util.*;
public class CheckEqual{
public static void main(String [] args){
if (args.length != 5){
System.out.println("Please check the number of your integers!");
return;
}
try{
int firstInteger = Integer.parseInt(args[2]);
int secondInteger = Integer.parseInt(args[3]);
int thirdInteger = Integer.parseInt(args[4]);
}
catch(NumberFormatException e){
System.out.println("Make sure that all inputs are integers!");
return;
}
if (firstInteger == secondInteger && secondInteger == thirdInteger){
System.out.println("True");
return;
}
else{
System.out.println("False");
return;
}
}
}
</code></pre>
<p>During compilation, it gave me the error "cannot find symbols" on firstInteger,secondInteger, and thirdInteger. Why is this, and how can I solve it? </p>
| <p>Java uses a scope on every variable. Basically, if you create a variable in a if block, like the following :</p>
<pre><code>if(statement){
int x = 1;
}
x++;
</code></pre>
<p>The x variable only exists in the scope of the if block. It doesn't exist afterwards. Meaning that x++ will create an error because x doesn't exist in this scope. The same applies in the try block in your code. firstInteger, secondInteger and thirdInteger don't exist outside of the try block. You should change your code for the following:</p>
<pre><code>import java.lang.*;
import java.util.*;
public class CheckEqual{
public static void main(String [] args){
if (args.length != 5){
System.out.println("Please check the number of your integers!");
return;
}
try{
int firstInteger = Integer.parseInt(args[2]);
int secondInteger = Integer.parseInt(args[3]);
int thirdInteger = Integer.parseInt(args[4]);
if (firstInteger == secondInteger && secondInteger == thirdInteger){
System.out.println("True");
return;
}
else{
System.out.println("False");
return;
}
}
catch(NumberFormatException e){
System.out.println("Make sure that all inputs are integers!");
return;
}
}
}
</code></pre>
|
how to write findOneAndUpdate query in express.js? <p>i have shown my data , which is stored in database like this</p>
<pre><code>{
"_id": {
"$oid": "5799995943d643600fabd6b7"
},
"Username": "xx",
"Email": "xx@gmail.com",
"Info": "Deactivate",
"Description": "aajdjdjddjdkjddjdjdhdj",
"VerificationCode": "594565",
"VerificationExpires": {
"$date": "2016-10-07T10:20:20.077Z"
}
}
</code></pre>
<p>My controller: </p>
<p>if Username, Email, Info are matched I need to update " Info = 'Active' " this is working at the same time i need to delete 'VerificationCode' field and 'VerificationExpires' field how can i achieve this? </p>
<pre><code>exports.updatearticle = function(req, res) {
Article.findOneAndUpdate(
{ "Username":'xx', "Email":'xx@gmail.com', "Info": "Deactivate" },
{ "$set": { "Info": "Active" } },
{ "new": true }
function (err, doc) {
if (err) { // err: any errors that occurred
console.log(err);
} else { // doc: the document before updates are applied if `new: false`
console.log(doc); // , the document returned after updates if `new true`
console.log(doc.Info);
}
}
);
};
</code></pre>
<p>above condtion matched and info getting changed but i want to delete VerificationCode,VerificationExpires some one help me out</p>
| <pre><code> exports.updatearticle = function(req, res) {
Article.findOne( { "Username":'xx', "Email":'xx@gmail.com', "Info": "Deactivate" }, function(err, result){
if (!err && result) {
result.Info = "Active"; // update ur values goes here
result.VerificationCode = "";
result.VerificationExpires = {};
var article = new Article(result);
article.save(function(err, result2){
if(!err) {
res.send(result2);
} else res.send(err);
})
} else res.send(err);
});
}
home this may help
</code></pre>
|
change keyboard language in client-side programming languages <p>I want to focus in input element change keyboard language.<br>
is there a way to change keyboard language in client-side programming languages ?<br>
is there a way to change keyboard language in javascript ?<br></p>
| <p>With a Windows software for Windows, yes, for other OS with locally installed software, most likely yes, with javascript, no, assuming you mean running inside a web browser.</p>
|
jQuery storing attribute into an array or object between two classes <p>I have following markup.</p>
<pre><code><div class="block" my_id="1">1</div>
<div class="block first" my_id="2">2</div>
<div class="block" my_id="3">3</div>
<div class="block" my_id="4">4</div>
<div class="block last" my_id="5">5</div>
<div class="block" my_id="6">6</div>
</code></pre>
<p>I want to select the values for <code>my_id</code> in between the <code>first</code> and <code>last</code> classes and store them in an object. It will be 2,3,4,5 in this case.</p>
<pre><code> var number_store = [];
$('.first').nextUntil('last').attr('my_id')//??
</code></pre>
<p>How would I achieve this? </p>
<p>Thanks!</p>
| <p>you can use .each() and add the attribute value to array for ex.</p>
<pre><code>var number_store = [];
$('.first').nextUntil('last').each(function(){
number_store.push($(this).attr('my_id'));
});
</code></pre>
|
How to select current element by class inside in jQuery? <p>I have a loop that dynamically populates information.</p>
<pre><code><div class="main">
<div class="more">
more
</div>
<span></span>
....
<div class="more">
more
</div>
<span></span>
</div>
</code></pre>
<p>on clicking specific div I am calling "ajax" - on success I want to override that specific div's content and next span with some content.</p>
<pre><code> $(document).on("click", ".more", function (event) {
$.ajax({
url: '..',
datatype: 'application/json',
success: function (data) {
$(".more",this).html("Update Dev"); //update div
$(".more",this).find('span:first').text("Update Span"); //update span
},
error: function () { alert('something bad happened'); }
});
});
</code></pre>
<p>How would I access the element that was clicked.</p>
<p>Thanks</p>
| <p>You can use <code>$(this)</code> inside click handler to get the clicked button. Make sure to capture it in click handler, not in AJAX callback:</p>
<pre><code>$(document).on("click", ".more", function (event) {
var clickedDiv = $(this); // <- capture clicked div to variable
$.ajax({
url: '..',
datatype: 'application/json',
success: function (data) {
// use captured div to set the contents
clickedDiv.html("Update Dev");
// use captured div and function next() to get the span element
clickedDiv.next('span').html("Updated span"); // then update span
},
error: function () { alert('something bad happened'); }
});
});
</code></pre>
|
Create a rounded checkbox with boarder <p>This is how I create a rounded <code>checkbox</code> with boarder. But the boarder is in square shape,not circle. </p>
<p><strong>CheckBox</strong></p>
<pre><code><CheckBox
android:id="@+id/checkBox"
android:paddingTop="15dp"
android:paddingRight="25dp"
android:layout_width="25dp"
android:layout_marginLeft="320dp"
android:layout_height="25dp"
android:button="@drawable/xml_button"
android:background="@drawable/xml_background"/>
</code></pre>
<p><strong>xml_button</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape android:shape="oval">
<solid android:color="#00FF00" />
<size
android:width="24dp"
android:height="24dp" />
</shape>
</item>
<item android:state_checked="false">
<shape android:shape="oval">
<solid android:color="#AAA" />
<size
android:width="24dp"
android:height="24dp" />
</shape>
</item>
</selector>
</code></pre>
<p><strong>xml_background</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="3dp" />
<stroke
android:width="2dp"
android:color="#CCC" />
<padding
android:left="34dp"
android:top="5dp"
android:right="10dp"
android:bottom="5dp" />
</shape>
</code></pre>
<p><strong>Output</strong></p>
<p><a href="http://i.stack.imgur.com/DSSZr.png" rel="nofollow"><img src="http://i.stack.imgur.com/DSSZr.png" alt="enter image description here"></a></p>
<p>Any help would be greatly appreciated. Thanks. </p>
| <p>use this xml as background in your radio button .....</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<stroke android:color="#1E90FF" android:width="10dp" />
<solid android:color="#87CEEB"/>
</shape>
</item>
</selector>
</code></pre>
<p><strong>Note:- I think your issue happened because of padding in round.xml</strong></p>
<blockquote>
<p>Output when unchecked ...</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/7vE1Z.png" rel="nofollow"><img src="http://i.stack.imgur.com/7vE1Z.png" alt="e01"></a></p>
<blockquote>
<p>Output when checked ...</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/ZI6HL.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZI6HL.png" alt="gd"></a></p>
|
Excel: get the value of third column on the behalf of second column <p>i am not much familiar with excel formulas and i am trying to get the value of third column on the behalf of second column.
Example:</p>
<pre><code>|---------------------------------------------------------|
| A B C D E |
|-----|----------|----------|--------------|--------------|
|Sr.No| Bar Code | Cat Id | Org BarCode | Org Category |
|---------------------------------------------------------|
| 1 | 89457898 | | 85214784 | 2 |
| 2 | 87414714 | | 63247458 | 3 |
| 3 | 85214784 | | 89457898 | 4 |
| 4 | 63247458 | | ---- | --- |
-----------------------------------------------------------
</code></pre>
<p>i just want to update column <code>C</code> by column <code>E</code> on the behalf of column <code>D</code> and <code>B</code></p>
<p>can any one please tell me the formula, how i can do this?</p>
| <p>Use <code>VLOOKUP</code>. Enter the following formula into cell <code>C1</code> and then copy it down the <code>C</code> column:</p>
<pre><code>=VLOOKUP(B1, D$1:E$4, 2, FALSE)
</code></pre>
<p>To cover more than 4 rows, then just update the formula accordingly. If you want to display a certain placeholder value if a value in column <code>B</code> be not found, then you wrap the call to <code>VLOOKUP</code> as follows:</p>
<pre><code>=IFNA(VLOOKUP(B1, D$1:E$4, 2, FALSE), "Not found")
</code></pre>
|
how to receive JSON data from angularjs into laravel <p>Help me on this:</p>
<p>I am sending JSON data through angularjs to laravel :</p>
<p>My angularjs Json code like:</p>
<pre><code> $scope.addnew = {name:'',email:'',message:''};
$scope.addnew.name=$scope.name;
$scope.addnew.email=$scope.email;
$scope.addnew.message=$scope.message;
$http.post("url",$scope.addnew)
.then(function mysuccess(response) {
console.log(response.data);
});
</code></pre>
<p>Note: I have predefined url in my file.</p>
<p>And I want to receive this JSON file in my laravel controller so that all data can be saved in my mysql table "contactemail" and fields of table are named as name for name, email for email and message for message of user. As I am newbie in Laravel I am not able to do this correctly.Please Help me in this.</p>
| <p>You can retrieve your input at Laravel using <code>$request->input('your_json_key')</code>.</p>
<p>Example basic saving data:</p>
<pre><code>$post = new Post();
$post->title = $request->input('title');
$post->save();
</code></pre>
<p>Those above code will create new post and save it to <code>posts</code> table (depends on your model setup). </p>
<p>For more information: <a href="https://laravel.com/docs/5.3/requests#accessing-the-request" rel="nofollow">https://laravel.com/docs/5.3/requests#accessing-the-request</a></p>
|
Converting INT minutes to HOUR in SQL server <p>I'm writing a view to get hours of holiday count from the minutes.</p>
<p><strong>Minutes data type is INT in the data table</strong></p>
<p>I wrote this but it doesn't work:</p>
<pre><code>DATEPART(HOUR, CONVERT(DATETIME, '00:' + CAST(S.availablevacations AS NVARCHAR(5)) + ':00:000', 114))
</code></pre>
<blockquote>
<p>COMPILER ERROR: Create View failed because no column name was
specified for column 6.</p>
</blockquote>
| <p>you can try this</p>
<pre><code>SELECT CONVERT(NUMERIC(18, 2), `TotalMinutes`/ 60 + (`TotalMinutes`% 60) / 100.0)
</code></pre>
<p>this will convert you minutes to HH.MM format sql format</p>
|
Can a Finite Automata exist without any final state? <p>It doesn't make sense to construct a language acceptor which does not able to accept any language. I specifically talking about FA which accept languages not transducer or translator which translate languages. </p>
| <p>People build them all the time. You have a set of states, and each state is accessible ultimately from every other, and there is no final state, so it never halts, though it might get stuck in a cycling loop. No issue with that at all.</p>
<p>Do a search on "busy beaver".</p>
|
Azure Active Directory Users and SaaS Application using Microsoft Graph Api <p>I am developing a SaaS application that requires external organizations' AD users to sync appointments to Office 365 calendar event.</p>
<p>Admin user scenario:</p>
<ol>
<li>Admin imports all AD Users to the app.</li>
<li>The app redirects the admin to Microsoft login and request permissions.</li>
<li>Admin allows the app to access users' calendars.</li>
</ol>
<p>Normal usersScenario:</p>
<ol>
<li>User logs in to the app.</li>
<li>User creates an appointment and sync to Office 365 Calendar (without asking for permissions).</li>
</ol>
<p>I'm using the following endpoints in Microsoft Graph API:</p>
<pre><code>Authority = "https://login.microsoftonline.com/common/oauth2/authorize"
Resource = "https://graph.microsoft.com/"
</code></pre>
<p>If I wanted to give normal users access to their Microsoft data, do I need to change the tenant "common" to their tenant ids?</p>
<p>My other question is how does admin consent work based on my scenarios?</p>
| <p>First, I recommend against importing all users to your app. It is best to only provision the users you actually need, in a "just in time" manner as they sign in. If your app has scenarios where it's useful to list other users in the tenant (e.g. a "people picker"), you can use the Microsoft Graph API on-demand.</p>
<p>Next, to answer one of your questions: No, you should not switch the <code>Authority</code> endpoint to the tenant-specific endpoint. Keep using the <code>common</code> endpoint, which ensure you can authenticate any user from any tenant.</p>
<p>Admin consent can be requested explicitly, by making use of the <code>prompt=admin_consent</code> query parameter during the authentication request. One approach is for your app to perform a regular sign-in, and then, once the user is signed in, uses the Microsoft Graph API to check if the user is a tenant admin. If they are, you can redirect them to re-authenticate, but this time with the <code>prompt=admin_consent</code> option. Alternatively, you can have a "sign-up" flow for your application that uses <code>prompt=admin_consent</code> from the beginning (with the appropriate note that only tenant administrators can do that, since non-admins will get an error from Azure AD that they might not understand).</p>
|
change string in TASM <p>I'm try to write program for searching smallest word in the input string using this algorithm.</p>
<p>My Algorithm:</p>
<pre><code>Read character from input, but not echo
If character is space:
current_string_length = 0;
current_string = "";
echo character
Else If character belong to English alphabet:
current_string_length++;
current_string += character;
if current_string_length < max_string_length:
max_string = current_string;
max_string_length = current_length_string;
echo character
Else If character is "\n":
print max_string
</code></pre>
<p>But i'm new in assembly and can't find way to add character to string and clean string. How can i do this, or maybe i need to choose different algorithm for this task?</p>
<p>My code:</p>
<pre><code>.model small
.stack 100h ; reserves 100h bytes for stack
.data
;----------------------------------------------------------------------------------
; Variables
maxString db 128 dup('$')
currentString db 128 dup('$')
maxLength dw 0
currentLength dw 0
;----------------------------------------------------------------------------------
; Messages
helloMessage db 10,13,'Assembly Shortest Word Finder Version 1.0 Copyright (c) 2016 RodionSoft',10,13,10,13,'Usage: enter string with length of words not more then 128 characters',10,13,10,13,10,13,10,13,'Enter string: $'
resultMessage db 10,13,"Shortest word: $"
;----------------------------------------------------------------------------------
; Program
.code
start :
MOV AX, @data
MOV DS, AX
;----------------------------------------------------------------------------------
; Print helloMessage
lea dx, helloMessage ; LEA - Load Affective Address
mov ah, 9 ; print the string of the adress
int 21h ; present in DX register
;----------------------------------------------------------------------------------
; main loop
repeat:
; -------------------------------------------------------------------------
; Read character but not echo
mov ah, 08h
int 21h
mov ah, 0 ; ah = 0
cmp al, 13h ; if(al == enter)
jz printResult ; printResult()
cmp al, 20h ; if(al == enter)
jz spaceinput ; spaceInput()
; -------------------------------------------------------------------------
cmp al, 41h ; if(al < 'A')
jl badInput ; badInput()
cmp al, 7Ah ; if(al > 'z')
jg badInput ; badInput()
cmp al, 5Bh ; if(al < '[')
jg goodInput ; goodInput()
cmp al, 60h ; if(al > '`')
jg goodInput ; goodInput()
jmp badInput ; else badInput()
goodInput:
inc currentString
; currentString += al
badInput:
jmp repeat
spaceInput:
mov currentLength, 0
;clean currentString
endOfIteration:
mov ah, 2 ; echo
int 21h
jmp repeat ; loop
;----------------------------------------------------------------------------------
printResult:
lea dx, secondMessage
mov ah, 9
int 21h
lea dx, maxString
mov ah, 9
int 21h
;----------------------------------------------------------------------------------
exit:
MOV AX, 4c00h
INT 21h
StringComparison proc
push cx dx bx ax bp si di ; save general-purpose registers
mov cx, maxLength ; cx = maxLength
mov dx, currentLength ; dx = currentLength
cmp cx, dx ; if(currentLength > maxLength)
jl currentBigger ; currentBigger()
jmp return ; else return
currentBigger:
; maxString = currentString
return:
pop di si bp ax bx dx cx ; restore general-purpose registers
ret
endp
end start
</code></pre>
| <blockquote>
<p>can't find way to add character to string and clean string. </p>
</blockquote>
<p>Well, in the first place it depends on your definition of what is string (this is common theme in assembly, deciding how you store your data, ie. which bits/bytes are used for what and what meaning you give them).</p>
<p>Look for example at <code>resultMessage</code>. It's composed of consecutive bytes with ASCII encoded values, ending with value <code>'$'</code> used as terminator for the DOS service.</p>
<p>In C/C++ the classic string literal is similar, but for terminator the value <code>0</code> is used.</p>
<p>In (old 16b) Pascal the first byte contains length 0-255 of string, following "length" bytes contain the ASCII letters, there's no terminator at end.</p>
<p>In Linux the system call to display string to console takes the pointer to the letters as in DOS/C definitions, but without any terminator, the length of string has to be provided aside as second argument, and it's up to programmer how he will get it.</p>
<p>So, such simple thing as string, and you have already 4 different ways how to store it in memory.</p>
<p>But in your case you don't need to work only with final string, but build it up and alter it, so probably the easiest way is to allocate some memory byte array: <code>currentString db 128 dup('$')</code> </p>
<p>And to keep <code>end()</code> pointer in some register, let's say <code>si</code>.</p>
<p>Then common tasks can be achieved like this:</p>
<pre><code>; all callable subroutines bellow expect the register "si"
; to point beyond last character of currentString
; (except the clearString of course, which works always)
appendLetterInAL:
cmp si,OFFSET currentString+127 ; 127 to have one byte for '$'
jae appendLetterInAL_bufferIsFull_Ignore
mov [si],al ; store new letter after previous last
inc si ; update "si" to point to new end()
appendLetterInAL_bufferIsFull_Ignore:
ret
clearString: ; works also as INIT at the start of code
lea si,[currentString]
ret
prepareStringForDOSOutput:
mov BYTE PTR [si],'$' ; set terminator at end()
lea dx,[currentString] ; dx = pointer to string
ret
getLengthOfString: ; sets cx to length of current string
; lea cx,[si - currentString] ; probably not allowed in 16b?
; other variant
mov cx,si
sub cx,OFFSET currentString
ret
copyCurrentStringToDI:
; copies current string to buffer @di
; and also terminates it in DOS way with '$'
; upon return di contains original value
push bx
lea bx,[currentString]
push di
copyCurrentStringToDI_loop:
cmp bx,si ; all bytes copied
jae copyCurrentStringToDI_finish
mov al,[bx]
inc bx
mov [di],al
inc di
jmp copyCurrentStringToDI_loop
copyCurrentStringToDI_finish:
mov BYTE PTR [di],'$' ; set DOS terminator
pop di ; restore di to original value
pop bx ; restore also bx
ret
</code></pre>
<p>So basically two pointers (current end() in <code>si</code>, and the start of string being fixed at compile time as <code>currentString</code>) are enough to do many manipulations with it.</p>
<p>I hope the algorithms and used data structure is easy to understand from the code and comments.</p>
|
how to export environment variable using newman API <p>i'm running a postman test suit using newman api. Its executing properly as expected but i want to export environment variable generated during test execution in file, in command line it is possible using --export-environment:</p>
<pre><code>newman run collectionPreReq.json -e Environment.json -k --export-environment newmanExport.json
</code></pre>
<p>for the same i'm writing javascript to get environment exported by collectionPreReq but not getting what i'm looking for, the code is</p>
<pre><code>var newman = require('newman');
newman.run({
collection: require('./collectionPreReq.json'),
//reporters: 'cli',
environment: require('./Environment.json'),
insecure: true
}).on('start', function (err, args) {
console.log('running a collection...');
}).on('done', function (err, summary) {
if (err || summary.error) {
console.error('collection run encountered an error.');
}
else {
console.log('collection run completed.:');
console.log("summary environment :");
console.log(summary.environment);
}
});
</code></pre>
<p>Output:</p>
<pre><code>running a collection...
collection run completed.:
summary environment :
{ object: [Function], toJSON: [Function] }
</code></pre>
| <p>Not possible per <a href="https://nodejs.org/api/process.html#process_process_env" rel="nofollow">NodeJS documentation</a>.</p>
<blockquote>
<p>The process.env property returns an object containing the user
environment. See environ(7).</p>
<p>An example of this object looks like:</p>
</blockquote>
<pre><code>{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
</code></pre>
<blockquote>
<p>It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process. In other words, the following
example would not work:</p>
<p><code>$ node -e 'process.env.foo = "bar"' && echo $foo</code></p>
</blockquote>
|
Pygame: Collision of two images <p>I'm working on my school project for which im designing a 2D game.</p>
<p>I have 3 images, one is the player and the other 2 are instances (coffee and computer). What i want to do is, when the player image collides with one of the 2 instances i want the program to print something.</p>
<p>I'm unsure if image collision is possible. But i know rect collision is possible. However, after several failed attempts, i can't manage to make my images rects. Somebody please help me. Here is my source code:</p>
<pre><code>import pygame
import os
black=(0,0,0)
white=(255,255,255)
blue=(0,0,255)
class Player(object):
def __init__(self):
self.image = pygame.image.load("player1.png")
self.image2 = pygame.transform.flip(self.image, True, False)
self.coffee=pygame.image.load("coffee.png")
self.computer=pygame.image.load("computer.png")
self.flipped = False
self.x = 0
self.y = 0
def handle_keys(self):
""" Movement keys """
key = pygame.key.get_pressed()
dist = 5
if key[pygame.K_DOWN]:
self.y += dist
elif key[pygame.K_UP]:
self.y -= dist
if key[pygame.K_RIGHT]:
self.x += dist
self.flipped = False
elif key[pygame.K_LEFT]:
self.x -= dist
self.flipped = True
def draw(self, surface):
if self.flipped:
image = self.image2
else:
im = self.image
for x in range(0, 810, 10):
pygame.draw.rect(screen, black, [x, 0, 10, 10])
pygame.draw.rect(screen, black, [x, 610, 10, 10])
for x in range(0, 610, 10):
pygame.draw.rect(screen, black, [0, x, 10, 10])
pygame.draw.rect(screen, black, [810, x, 10, 10])
surface.blit(self.coffee, (725,500))
surface.blit(self.computer,(15,500))
surface.blit(im, (self.x, self.y))
pygame.init()
screen = pygame.display.set_mode((800, 600))#creates the screen
player = Player()
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
player.handle_keys() # movement keys
screen.fill((255,255,255)) # fill the screen with white
player.draw(screen) # draw the player to the screen
pygame.display.update() # update the screen
clock.tick(60) # Limits Frames Per Second to 60 or less
</code></pre>
| <p>Use <a href="http://pygame.org/docs/ref/rect.html" rel="nofollow">pygame.Rect()</a> to keep image size and position. </p>
<p>Image (or rather <code>pygame.Surface()</code>) has function <code>get_rect()</code> which returns <code>pygame.Rect()</code> with image size (and position).</p>
<pre><code>self.rect = self.image.get_rect()
</code></pre>
<p>Now you can set start position ie. <code>(0, 0)</code></p>
<pre><code>self.rect.x = 0
self.rect.y = 0
# or
self.rect.topleft = (0, 0)
# or
self.rect = self.image.get_rect(x=0, y=0)
</code></pre>
<p>(<code>Rect</code> use left top corner as (x,y)). </p>
<p>Use it to change position</p>
<pre><code>self.rect.x += dist
</code></pre>
<p>and to draw image</p>
<pre><code>surface.blit(self.image, self.rect)
</code></pre>
<p>and then you can test collision</p>
<pre><code>if self.rect.colliderect(self.rect_coffe):
</code></pre>
<hr>
<p>BTW: and now <code>class Player</code> looks almost like <a href="http://pygame.org/docs/ref/sprite.html" rel="nofollow">pygame.sprite.Sprite</a> :)</p>
|
how ot use (in_array) <p>I am using â âto pass my array value from one page to another. I have an array value that is doesnât have value always. How to put condition when it have value pass it but I donât have idea about (in array) in . </p>
<p>this is my passing code</p>
<pre><code>echo '<td ><a href="sessiondetails.php?'.htmlentities(http_build_query(array('docname'=>$key['DocName'],'HosName'=>$key['HosName'],'DoctorNotes',['DoctorNotes'])),ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE | ENT_DISALLOWED,'UTF-8',true).'">More>></a></font></td></tr>';
</code></pre>
<p>this is get query</p>
<pre><code>$DoctorNotes=$_GET ['DoctorNotes'];[enter image description here][1]
</code></pre>
<p>here is my result array</p>
<p>error msg
' Array to string conversion in.....'</p>
| <p><strong>in_array â Checks if a value exists in an array</strong></p>
<pre><code><?php
$names = array("VYSAKH", "DODESTINO", "CHOORAKKATT", "VYSU");
if (in_array("DODESTINO", $names)) {
echo "Got DODESTINO";
}
if (in_array("VYSU", $names)) {
echo "Got VYSU";
}
?>
</code></pre>
|
oracle rman duplicate database <p>I'm trying to duplicate from active database. I have configured everything according to oracle docs. still in the middle of the process I get the error </p>
<pre><code>RMAN-06025: no backup of archived log for thread 1 with sequence 58 and starting SCN of 2001221 found to restore
</code></pre>
<p>Does anyone know how to solve this? Thanks in advance.
ps: this is my rman configuration on the source database:</p>
<pre><code>RMAN configuration parameters for database with db_unique_name XE are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION OFF; # default
CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default
CONFIGURE CONTROLFILE AUTOBACKUP OFF;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT '/backup/ora_df%t_s%s_s%p';
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
CONFIGURE COMPRESSION ALGORITHM 'BASIC' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE ; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/u01/app/oracle/product/11.2.0/xe/dbs/snapcf_XE.f'; # default
</code></pre>
| <p>I solved the problem by switching to backup based duplication. at fist I got the same error, following instructions in here:
<a href="https://oracle-base.com/articles/11g/duplicate-database-using-rman-11gr2" rel="nofollow">https://oracle-base.com/articles/11g/duplicate-database-using-rman-11gr2</a></p>
<p>I did a point in time duplicate and it worked fine.</p>
|
I want to make effect to my photos.How can i Separating the image in pixels?(for image effect) <p>I want to separate the pixels of the image.Also i have a lot of picture.How do i do it serially?</p>
<p><a href="http://i.stack.imgur.com/IOJ32.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/IOJ32.jpg" alt="image comparison"></a></p>
| <p>This is just a sample code "not tested" in c#.</p>
<pre><code> private void ImageToPixcels()
{
Bitmap img = (Bitmap)Image.FromFile(@"D:\sample.jpg");
Color[,] pixels = new Color[img.Width, img.Height];
for (int x = 0; x < img.Width; x++)
{
for (int y = 0; y < img.Height; y++)
{
pixels[x, y] = img.GetPixel(x, y);
}
}
}
</code></pre>
|
I want to convert json according to my format <p>// I am converting sqlite data into json format </p>
<p>try</p>
<p>{</p>
<pre><code> SQLiteDatabase db;
String dbDir= Environment.getExternalStorageDirectory()+"/"+getResources().getString(R.string.folderName);;
db=getActivity().openOrCreateDatabase(dbDir + "/" + getResources().getString(R.string.dbName), Context.MODE_PRIVATE, null);
Cursor c = db.rawQuery("select * from products", null);
Log.e("fetch_category", "" + c.getCount());
if (c.getCount() == 0)
{
}
else
{
c.moveToFirst();
JSONObject rowObject = new JSONObject();
do
{
int totalColumn = c.getColumnCount();
for( int i=0 ; i< totalColumn ; i++ )
{
if( c.getColumnName(i) != null )
{
try
{
if( c.getString(i) != null )
{
Log.d("TAG_NAME", c.getString(i) );
rowObject.put(c.getColumnName(i) , c.getString(i) );
}
else
{
rowObject.put( c.getColumnName(i) , "" );
}
}
catch( Exception e )
{
Log.d("TAG_NAME", e.getMessage() );
}
}
}
// billsModel=new Bills_model();
resultSet.put(rowObject);
Log.d("resultset",resultSet.toString());
}
while (c.moveToNext());
}
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
</code></pre>
<p>//out put is coming like this </p>
<p>[{"key","value"},{"key","value"}....]</p>
<p>//but i want to like this is it possible</p>
<p>{"product"[{"key","value"},{"key","value"}....]}</p>
| <p>You can use Jackson library -</p>
<ol>
<li><p>Create a response class.</p></li>
<li><p>Use @JsonProperty annotation -</p></li>
</ol>
<p>@JsonProperty("product")
private String jsonArray;</p>
<p>//getter</p>
<p>//setter</p>
<ol start="3">
<li>Set your json response string in the response object.</li>
</ol>
|
pexpect not executing command by steps <p>I have this Python3 code which use Pexpect.</p>
<pre><code>import pexpect
import getpass
import sys
def ssh(username,password,host,port,command,writeline):
child = pexpect.spawn("ssh -p {} {}@{} '{}'".format(port,username,host,command))
child.expect("password: ")
child.sendline(password)
if(writeline):
print(child.read())
def scp(username,password,host,port,file,dest):
child = pexpect.spawn("scp -P {} {} {}@{}:{}".format(port,file,username,host,dest))
child.expect("password: ")
child.sendline(password)
try:
filename = sys.argv[1]
print("=== sendhw remote commander ===")
username = input("Username: ")
password = getpass.getpass("Password: ")
ssh(username,password,"some.host.net","22","mkdir ~/srakrnSRV",False)
scp(username,password,"some.host.net","22",filename,"~/srakrnSRV")
ssh(username,password,"some.host.net","22","cd srakrnSRV && sendhw {}".format(filename),True)
except IndexError:
print("No homework name specified.")
</code></pre>
<p>My aim is to:</p>
<ul>
<li>SSH into the host with the <code>ssh</code> function, create the directory <code>srakrnSRV</code>, then</li>
<li>upload a file into the <code>srakrnSRV</code> directory, which is previously created</li>
<li><code>cd</code> into <code>srakrnSRV</code>, and execute the <code>sendhw <filename></code> command. The <code>filename</code> variable is defined by command line parameteres, and print the result out.</li>
</ul>
<p>After running the entire code, Python prints out</p>
<pre><code>b'\r\nbash: line 0: cd: srakrnSRV: No such file or directory\r\n'
</code></pre>
<p>which is not expected, as the directory should be previously created.</p>
<p>Also, I tried manually creating the <code>srakrnSRV</code> folder in my remote host. After running the command again, it appears that <code>scp</code> function is also not running. The only runnning pexpect coomand was the last <code>ssh</code> function.</p>
<p>How to make it execute in order? Thanks in advance!</p>
| <p>You may lack permission for executing commands through ssh. Also there is possibility that your program sends scp before prompt occurs.</p>
|
Linux bash script to add data to database <p>I am trying to write a bash script that will pull data from a csv file and put it in a format where I can place it in a database. The csv file has about 1000 rows and 8 columns. When I use the command line I can get the data formatted exactly how I want. I am using the latest version of CentOS minimal install. </p>
<p>(edit) A sample of the csv file is:</p>
<pre><code>[root@node72 ~]# cat users72.csv | head
</code></pre>
<blockquote>
<p>msza907,Matyas Szabo,Men,Fencing,FE,germany</p>
<p>krut825,Kristian Ruth,Men,Sailing,SA,norway</p>
<p>sdon251,Samuil Donkov,Men,Shooting,SH,bulgaria</p>
<p>aroa777,Andres Roa,Men,Football,FB,colombia</p>
</blockquote>
<p>The code I use in the CLI is:</p>
<pre><code># cat users72.csv | awk -F',' '{ print "INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES (""\""$1"\""", ""\""$3"\""", ""\""$5"\""");"}'
</code></pre>
<p>A sample of the output looks like this:</p>
<blockquote>
<p>INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES ("gjan887", "Men", "AR");</p>
<p>INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES ("ifet740", "Women", "VO");</p>
<p>INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES ("apet755", "Men", "AT");</p>
<p>INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES ("fnep723", "Men", "SH");</p>
<p>INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES ("othi288", "Women", "BK");</p>
</blockquote>
<p>This syntax isn't exactly correct for mysql because I need an id number which was what I was using the script for. The id number has to increment by odd numbers so 1, 3, 5, ect, ect. The problem with my script is that when I run it and save it into a file I plan to use to import the data into a database it prints one line with the id and username then the next line has other data I don't need and I can figure it out.</p>
<p>Below is my script:</p>
<pre><code>#!/bin/bash
inputData=$(cat /root/users72.csv);
((id=1))
for athleteTable in $inputData
do
echo "$athleteTable" | awk -F',' '{ print "INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES ('$id', " "\""$1"\"" ", " "\""$3"\"" ", " "\""$5"\""");"}'
((id=id+2))
done > /root/users72.sql
</code></pre>
<p>a sample of the users72.sql file looks like this:</p>
<blockquote>
<p>INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES (1, "msza907", "", "");</p>
<p>INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES (3, "Szabo", "Fencing", "germany");</p>
<p>INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES (5, "krut825", "", "");</p>
<p>INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES (7, "Ruth", "Sailing", "norway");</p>
<p>INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES (9, "sdon251", "", "");</p>
<p>INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES (11, "Donkov", "Shooting", "bulgaria");</p>
</blockquote>
<p>I have been banging my head against the wall for the last 7 hours trying to get this to work, changing syntax going over other examples and I'm starting to think there is a glitch in the OS. I would love it if someone knows what is wrong or knows a simpler way to accomplish this task could help me out. Thank you in advance.</p>
| <p>I agree with @GhostCat for sure, parsing a CSV is much more complicated than just splitting on comma, though some trivial CSVs might work. Often, though, a CSV can contain commas within a field, so splitting on comma would break things.</p>
<p>That said, your problem here with why the script isn't doing what you want is you're letting word splitting happen on the contents of the file and trying to <code>awk</code> each "word". You should just increment the counter inside <code>awk</code> and let it handle reading the file for you. Assuming you were happy with the original <code>awk</code> command you could do it like:</p>
<pre><code> awk -F',' 'BEGIN {id=1} {print "INSERT INTO athletes (id, username, gender, sport_abbreviation) VALUES ( " id " \47"$1"\47, \47"$3"\47, \47"$5"\47);";id+=2}' users72.csv
</code></pre>
<p>Where we create a local <code>id</code> variable and increment it by 2 for each line. I also used the octal escape to print single quotes around each field instead of using lots of quotes and escapes as you had been doing. Feel free to go back to your way if you prefer it (or use <code>\42</code> for double quote if you want those instead). Finally, I changed it so <code>awk</code> just opens the file itself and we can avoid the <code>cat</code> and pipeline.</p>
|
command failed due to signal: Segmentation fault: 11 when swift 3 migration <p>my example code is <a href="https://drive.google.com/open?id=0B-bSY9YevABJZG9KaFJBSnQ5TXc" rel="nofollow">here</a>
and my fault is under the line
thanks for advices.</p>
<p><a href="http://i.stack.imgur.com/vWOHH.png" rel="nofollow"><img src="http://i.stack.imgur.com/vWOHH.png" alt="enter image description here"></a></p>
| <p>This issue is dynamic and each time there is something for which compiler will complain.</p>
<p>I think given line of code in <code>viewDidLoad</code> causing problem. Don't know compiler why complaining.</p>
<p>But if you comment this line of code then error will get removed.
Try once by removing this line.</p>
<p>If it works, then try to work around this line.</p>
<pre><code>currencyFormatter.currencyCode = (Locale.current as NSLocale).displayName(forKey: NSLocale.Key.currencySymbol, value: NSLocale.Key.currencyCode)
</code></pre>
<p>Here is <a href="http://stackoverflow.com/questions/26557581/command-failed-due-to-signal-segmentation-fault-11?rq=1">segmentation fault thread</a>, but each one has its own solution, there is no universal solution for this error.</p>
<p>Best luck!!!</p>
|
Exception from HRESULT: 0x80070005 (E_ACCESSDENIED) <p>I get a <strong>80070005 Access is denied</strong> error when attempting to deploy a Crystal Report to the server. I have tried every solution in this <a href="http://stackoverflow.com/questions/14019401/80070005-access-is-denied-when-asp-net-website-with-crystal-report-is-deployed-o">post</a> but nothing seems to work. How can I resolve this?</p>
| <p>Check this:</p>
<pre><code>1.)Goto inetmgr or IIS
2.)Application pools
3.).NET Framework Version.
</code></pre>
|
Give a sub-rectangle, how does one divide the remainder of a rectangle into two parts such that the two new rectangles are more "squarish"? <p>I have a rectangle R1, with width w1, height h1.</p>
<p>I am given a smaller rectangle R2 (w2,h2), whose origin is the same as R1 ie. (0,0).</p>
<p>How can I divide the remaining space into two rectangles, such that the difference between the length and width of each rectangle is as little as possible (more squarish)?</p>
<p>Here is what I have so far:
Given R2, there are four possibilities:</p>
<ol>
<li>R2 is the same dimensions as R1, in which case there are no sub rectangles.</li>
<li>R2 is as wide as R1, but not as tall, in which case there is just one sub rectangle possible.</li>
<li>R2 is as tall as R1, but not as wide - again there is just one sub rectangle possible, just like in case(2).</li>
<li>R2 is not as tall, and not as wide as R1. In this case two sub rectangles are possible.</li>
</ol>
<p>In case(4), there are two possible ways to partition the remaining space:</p>
<ol>
<li>R3(w,h) = (w1-w2,h2) and R4(w,h) = (w1,h1-h2)</li>
<li>R3(w,h) = (w1-w2,h1) and R4(w,h) = (w2,h1-h2)</li>
</ol>
<p>I figure that the ratio of the sides of a square is 1:1, so the smaller the ratio of the longer side to the shorter side, the closer to a square it is.</p>
<p>The problem is, there are TWO sub rectangles. So how do I decide which pair of rectangles is more square, since there are TWO of them ?</p>
<p>EDIT: If both R3 and R4's ratios in 1. are greater than in 2. , then obviously 2. is more square. But what if only one rect (example R3), has better ratios than in the other case, while the other rect (R4) has worse ratios ? Is that even possible ?</p>
<p>EDIT: Does it make sense to just sum the ratios of R3 and R4 in each case, and pick the case which has a smaller sum ?</p>
| <p>We have an L shape, so we want to know whether to cut it vertically or horizontally to make the rectangles more "square". By "more square" we mean minimising perimeter. So the answer is simple. Make the shorter of the two cuts.</p>
|
NodeJS, Express, why should I use app.enable('trust proxy'); <p>I was needed to redirect http to https and found this code:</p>
<pre><code>app.enable('trust proxy');
app.use((req, res, next) => {
if (req.secure) {
next();
} else {
res.redirect('https://' + req.headers.host + req.url);
}
});
</code></pre>
<p>I'm using heroku to host my project, I noticed that heroku as default issued <code>*.herokuapp.com</code> cert, so I can use http and https as well.</p>
<p>When looked at <code>req.secure</code> within <code>app.use</code> callback, without <code>app.enable('trust proxy')</code>, <code>req.secure</code> is always <code>false</code>, when I add <code>app.enable('trust proxy')</code> it's false for about 2 times and after the <code>https</code> redirection it's switches to <code>true</code>.</p>
<p><code>app.enable('trust proxy')</code>, <a href="http://expressjs.com/en/api.html#app.settings.table" rel="nofollow">the docs:</a></p>
<blockquote>
<p>Indicates the app is behind a front-facing proxy, and to use the
X-Forwarded-* headers to determine the connection and the IP address
of the client.</p>
</blockquote>
<p><strong>My question:</strong></p>
<p>Why would my server be behind a proxy?(is it relates to the issued <code>*.herokuapp.com</code> cert?), if someone could explain how all fits together, I mean, why my server is behind a proxy? and why without <code>app.enable</code> express won't identify(or accept) secure connection?</p>
| <p>If your not running behind a proxy, it's not required. Eg, if your running multiple websites on a server, chances are your using a Proxy. </p>
<p>X-Forwarded-For header attributes get added when doing this so that your proxy can see what the original url was, proxying in the end will be going to localhost you see. The reason why it's needed is that X-Forwared-For can be faked, there is nothing stopping the client adding these too, not just a proxy. So trust-proxy should only be enabled on the receiving end, that would be behind your firewall. Because you have control, you can trust this.</p>
<p>So in a nutshell, if your website is running behind a proxy, you can enable it. If you website is running direct on port 80, you don't want to trust it. As the sender could pretend to be coming from localhost etc.</p>
|
how to convert mongodb queries into java <p>how to convert mongodb queries into java</p>
<p>I want to convert following query into java</p>
<pre><code>db.Student.aggregate( {$group : {_id : "$prnno", x: {$push:"$name"} , st:{$push: "$per"} }},
{$sort:{st:-1} },{$limit:3});
</code></pre>
| <p>Try this one, I hope it helps:</p>
<pre><code>collection.aggregate(Arrays.asList({$or:[
new BasicDBObject("$match", new BasicDBObject("x", {$push:"$name"})),
new BasicDBObject("$match", new BasicDBObject("st", {$push: "$per"}))],
new BasicDBObject("$sort", new BasicDBObject("st", -1)),
new BasicDBObject("$limit", 3)))
</code></pre>
|
codeigniter session loading error: No such file or directory <p>I am following this <a href="https://www.formget.com/form-login-codeigniter/" rel="nofollow">tutorial</a>: </p>
<p>however when I access to</p>
<p><a href="http://localhost/index.php/user_authentication/" rel="nofollow">http://localhost/index.php/user_authentication/</a></p>
<p>I got this get warning and cannot get the code running:</p>
<pre><code>Warning: include(C:\xampp\htdocs\application\views\errors\html\error_php.php): failed to open stream: No such file or directory in C:\xampp\htdocs\system\core\Exceptions.php on line 269
Warning: include(): Failed opening 'C:\xampp\htdocs\application\views\errors\html\error_php.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\system\core\Exceptions.php on line 269
Warning: include(C:\xampp\htdocs\application\views\errors\html\error_php.php): failed to open stream: No such file or directory in C:\xampp\htdocs\system\core\Exceptions.php on line 269
Warning: include(): Failed opening 'C:\xampp\htdocs\application\views\errors\html\error_php.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\system\core\Exceptions.php on line 269
</code></pre>
<p>When I remove the <code>$this->load->library('session');</code></p>
<p>the warnings are gone so I am pretty sure I got the error in loading the session library.</p>
<p>I have read that the issue is fixed by changing $config['sess_save_path'] = sys_get_temp_dir();</p>
<p>but i still get the warning.</p>
<p>I even tried adding this code to my controller:
mkdir("/thisisthedirectory", 0700);</p>
<p>then changed my $config['sess_save_path'] = "/thisisthedirectory"; but it doesn't work</p>
<p>nor $config['sess_save_path'] = "C:\thisisthedirectory";</p>
<p>Can anybody tell me how to fix this problem?</p>
| <p>Make sure you have set your session save path something like</p>
<pre><code>$config['sess_save_path'] = APPPATH . 'cache/';
</code></pre>
<blockquote>
<p>Folder Permissions 0700</p>
</blockquote>
<p>Config.php</p>
<pre><code>$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = APPPATH . 'cache/';
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = TRUE;
</code></pre>
<p>Note: Make sure you have followed the Codeigniter Style Guide For <a href="http://www.codeigniter.com/user_guide/general/styleguide.html#file-naming" rel="nofollow">File Naming</a> and <a href="http://www.codeigniter.com/user_guide/general/styleguide.html#class-and-method-naming" rel="nofollow">Class Naming</a></p>
|
I have to create same Jhipster yo.rc.json as in my old project <p>I am working on rebuild the same jhipster application as previous one bcoz old project are having some problems.
The problem is that, project was created in version 2.1.27 and I have to create the same kind of project in 3.8.0. So, jhipster question and answer pattern is changed and I am confused what to answer to that question.</p>
<p>For Example : I had xauth authentication in my previous app. but while building new jhipster app I dont see any such kind of authentication there are three options: HTTP,OAUTH2 and JWT. what should I have to select. Further more I will share my old yo.rc.JSON can anybuddy guild me correct answer to build new jhipster yo.rc file</p>
<pre><code>{
"generator-jhipster": {
"baseName": "myApp",
"packageName": "com.myApp.app",
"packageFolder": "com/myApp/app",
"authenticationType": "xauth",
"hibernateCache": "no",
"clusteredHttpSession": "no",
"websocket": "no",
"databaseType": "sql",
"devDatabaseType": "mysql",
"prodDatabaseType": "mysql",
"searchEngine": "no",
"useSass": false,
"buildTool": "maven",
"frontendBuilder": "grunt",
"javaVersion": "7",
"enableTranslation": false,
"rememberMeKey": "c1a3776920bbeb376eeecd42e91cccdeaoada010"
}
}
</code></pre>
| <p>You should use JWT authentication. This was changed in 3.0 <a href="https://github.com/jhipster/generator-jhipster/commit/2f017636700790aa5b38554da71fc27801b67cd3" rel="nofollow">https://github.com/jhipster/generator-jhipster/commit/2f017636700790aa5b38554da71fc27801b67cd3</a></p>
<p>Regarding migration of your full yo-rc.json, you have to try by yourself by generating new projects.</p>
<p>Few hints:</p>
<pre><code>"frontendBuilder": "grunt", <-- we only support gulp now
"javaVersion": "7", <-- we only support java 8
"enableTranslation": false, <-- probably need to list languages
"rememberMeKey": "c1a3776920bbeb376eeecd42e91cccdeaoada010" <-- secret key maybe
</code></pre>
|
How to return from function with some error checking in Go <p>I have several data to load, and If one of them fails, I have to log error and not continue to run the code.<br>
Is this code OK? And how to do that?</p>
<pre><code>func (worker *Worker) GetData() error {
err := worker.LoadModelA()
if err != nil && worker.LogError() // LogError alway return true
return err
err = worker.LoadModelB()
if err != nil && worker.LogError() // LogError alway return true
return err
return err
}
</code></pre>
| <p>With error in A (try it on <a href="https://play.golang.org/p/5YnhFN0TMC" rel="nofollow">The Go Playground</a>), output:</p>
<pre><code>LoadModelA
2009/11/10 23:00:00 LogError
2009/11/10 23:00:00 Error LoadModelB
</code></pre>
<p>With error in B (try it on <a href="https://play.golang.org/p/-vZeZi5Moh" rel="nofollow">The Go Playground</a>), output:</p>
<pre><code>LoadModelA
LoadModelB
2009/11/10 23:00:00 LogError
2009/11/10 23:00:00 Error LoadModelB
</code></pre>
<p>Without error (try it on<a href="https://play.golang.org/p/T0It5A5cXS" rel="nofollow">The Go Playground</a>), output:</p>
<pre><code>LoadModelA
LoadModelB
Done.
main Done.
</code></pre>
<p>Here is the code:</p>
<pre><code>package main
import (
"fmt"
"log"
)
func (worker *Worker) GetData() error {
if err := worker.LoadModelA(); err != nil {
worker.LogError()
return err
}
if err := worker.LoadModelB(); err != nil {
worker.LogError()
return err
}
fmt.Println("Done.")
return nil
}
func main() {
w := &Worker{}
err := w.GetData()
if err != nil {
log.Fatal(err)
}
fmt.Println("main Done.")
}
type Worker struct{}
func (w *Worker) LoadModelA() error {
fmt.Println("LoadModelA")
return nil
//return fmt.Errorf("Error LoadModelB")
}
func (w *Worker) LoadModelB() error {
fmt.Println("LoadModelB")
return nil
//return fmt.Errorf("Error LoadModelB")
}
func (w *Worker) LogError() error {
log.Println("LogError")
return nil
}
</code></pre>
|
How to limit array depth in php <p>I want to get up to 10 level in multidimensional array. </p>
<p>Here is my code from which i get up-to infinite depth, but i want to limit this to 10 levels.</p>
<pre><code>function tree($parent){
global $db;
$sql = "SELECT * FROM clients WHERE parent_id = $parent ";
$users=$db->query($sql);
$return = array();
while($parent = $users->fetchObject()) {
$return[$parent->client_id] = $parent;
if(have_data($parent->client_id)){
$return[$parent->client_id]->subs = tree($parent->client_id);
}
}
return $return;
}
</code></pre>
<p>print_r(tree(1,0));</p>
<p>the output is:</p>
<pre><code> Array
(
[2] => stdClass Object
(
[client_id] => 2
[parent_id] => 1
[client_name] => TEST
[subs] => Array
(
[4] => stdClass Object
(
[client_id] => 4
[parent_id] => 2
[client_name] => TEST
[subs] => Array
(
[5] => stdClass Object
(
[client_id] => 5
[parent_id] => 4
[client_name] => ADAm
)
)
)
[6] => stdClass Object
(
[client_id] => 6
[parent_id] => 2
[client_name] => RAS
[subs] => Array
(
[7] => stdClass Object
(
[client_id] => 7
[parent_id] => 6
[client_name] => RAStest
)
)
)
)
)
[3] => stdClass Object
(
[client_id] => 3
[parent_id] => 1
[client_name] => ABC
)
)
</code></pre>
<p>How can i limit the child level to 10, Hope to get response from the experts boss.Thanks in advance.</p>
| <p>You can use <a href="http://php.net/manual/en/class.recursiveiteratoriterator.php" rel="nofollow">RecursiveIteratorIterator API</a> and use <a href="http://php.net/manual/en/recursiveiteratoriterator.setmaxdepth.php" rel="nofollow">setMaxDepth()</a> function and can get the maxDepth with this function <a href="http://php.net/manual/en/recursiveiteratoriterator.getmaxdepth.php" rel="nofollow">getMaxDepth()</a></p>
<pre><code>$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($myArray));
</code></pre>
|
Autobean returns an autobean after using as() <p>in my gwt project i am sending objects with the gwt channel api to the client and use Autobean to encode and decode those objects. everything works fine, i receive a valid json string on the client and can decode that json string to the AutoBean back again. only the autobean.as() does not return anything different than the autobean itself.</p>
<p>IContactDto and ContactDto just contain getters and setters. and this is the facbory i wrote</p>
<p><strong>AutoBeanFactory</strong></p>
<pre><code>public interface DtoFactory extends AutoBeanFactory{
AutoBean<IContactDto> contactDto(IContactDto contactDto);
}
</code></pre>
<p><strong>Server-side code</strong></p>
<pre><code>DtoFactory dtoFactory = AutoBeanFactorySource.create(DtoFactory.class);
AutoBean<IContactDto> iContactDto = dtoFactory.contactDto(contactDto);
String sJson = AutoBeanCodex.encode(autoBean).getPayload();
// sending this json to the client
</code></pre>
<p><strong>Client-side code</strong></p>
<p>this is the code i use for decoding the valid json string</p>
<pre><code>// sJson string looks like {"id":"6473924464345088", "lastUpdate":"1475914369346", "fullName":"testName1","givenName":"testName2"}
DtoFactory factory = GWT.create(DtoFactory.class);
AutoBean<IContactDto> autoBean = AutoBeanCodex.decode(factory, IContactDto.class, sJson); // debugger: IContactDtoAutoBean_1_g$
IContactDto iDto = autoBean.as(); // debugger still shows IContactDtoAutoBean$1_1_g$
</code></pre>
<p>i can actually use the getters and setters of this object, but as soon as i try continue to work this those objects i get a problem with the type signature.</p>
<p>any ideas how i can get the object i encoded back again?</p>
| <p><code>AutoBean#as()</code> returns a <em>âproxy implementation of the T interface which will delegate to the underlying wrapped object, if any.â</em> (source: <a href="http://www.gwtproject.org/javadoc/latest/com/google/web/bindery/autobean/shared/AutoBean.html#as()" rel="nofollow">javadoc</a>), it will never return the wrapped object itself.</p>
<p>Moreover, when deserializing from JSON, there's no wrapped object, a new autobean is created "from scratch" and then filled with JSON (it actually directly <em>wraps</em> a <code>Splittable</code> from the parsed JSON: super-lightweight, just a thin typesafe wrapper around a JS object âor a <code>org.json.JSONObject</code> when not in the browser.)</p>
|
Laravel modal loads only last entry <p>I have been trying to use modal to create and edit entries in Laravel. I am using simple modal instead of ajax. I can add entries, but when I try to edit an entry, it only loads the last entry in the modal.</p>
<p>Here is my index (from where I am calling modal)</p>
<pre><code>@foreach ($clients as $client)
<tr>
<td>{{ $client->name }}</td>
<td><button data-target="modal2" class="btn modal-trigger1"><a href="{{route('client.edit', $client->id)}}">Edit</a></button></td>
</tr>
@endforeach
</code></pre>
<p>Here is edit file (modal file)</p>
<pre><code><div id="modal2" class="modal">
<div class="panel panel-default">
<div class="modal-content">
<p class="flow-text">Edit client</p>
<form class="form" role="form" method="POST" action="{{ url('/client/'. $client->id) }}">
<input type="hidden" name="_method" value="patch">
{!! csrf_field() !!}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label class="control-label">Name</label>
<input type="text" class="form-control" name="name" value="{{ $client->name }}">
@if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
@endif
</div>
</form>
</div>
</div>
</div>
</code></pre>
<p>And the edit in controller is</p>
<pre><code>public function edit($id)
{
$clients = Client::findOrFail($id);
return view('client.edit', compact('clients'));
}
</code></pre>
<p>It only loading the last entry in the table, not the entry id in the row.</p>
<p>I am using Laravel 5.3. Please help</p>
| <p>Set data to your edit link </p>
<pre><code>@foreach ($clients as $client)
<tr>
<td>{{ $client->name }}</td>
<td><a href="#" class="edit-client-link" data-client-id="{{$client->id}}" data-client-name="{{$client->name}}">Edit</a></td>
</tr>
@endforeach
</code></pre>
<p>//On edit button click get data and set data to modal</p>
<pre><code>$(document).on('click', '.edit-city-link', function(){
var client_id = $(this).data('client-id');
var client_name = $(this).data('client-name');
$('#client-id').val(client_id);
$('#client-name').val(client_name);
$('#edit-client-modal').modal('show');
});
</code></pre>
<p>//This is modal </p>
<pre><code><div id="modal2" class="modal">
<div class="panel panel-default">
<div class="modal-content">
<p class="flow-text">Edit client</p>
<form id="edit-client-modal" class="form" role="form" method="POST" action="{{ url('/client/edit') }}">
<input type="hidden" name="_method" value="patch">
{!! csrf_field() !!}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label class="control-label">Name</label>
<input id="client-id" type="hidden" class="form-control" name="client-id">
<input id="client-name" type="text" class="form-control" name="name">
@if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
@endif
</div>
</form>
</div>
</div>
</div>
</code></pre>
<p>This is your controller method</p>
<pre><code>public function edit($request_data)
{
$obj_client = Client ::find($request_data['client-id']);
$obj_client = $request_data['client-name'];
$obj_client->save();
}
</code></pre>
|
Could not connect to MySQL: Access denied for user 'root'@'localhost' (using password: NO) I cannot access my databases. What I am supposed to do <blockquote>
<p>Could not connect to MySQL: Access denied for user 'root'@'localhost'
(using password: NO)</p>
</blockquote>
<p>I cannot access my databases using earlier <strong>username (root)</strong> and not any password. What am I supposed to do. I cannot access through mysql console too. I tried to configure config.inc.php file but didn't work.</p>
<p>Please let me know whato to do not to discard WAMP and install new one.</p>
<p>Regards,</p>
<p>Aleksandar</p>
| <p>It seems that you have forgotten your mysql root user password. I think you should reinstall WAMPP and then set the mysql root user password from command line. To set the mysql root user password you have to first login to mysql from command line using this command: mysql -u root. When it asks for password just enter. After that enter following commands:</p>
<pre><code>SET PASSWORD for 'root'@'localhost' = password('enteryourpassword');
SET PASSWORD for 'root'@'127.0.0.1' = password('enteryourpassword');
SET PASSWORD for 'root'@'::1' = password('enteryourpassword');
</code></pre>
|
Mapping string to int CPP - Output hangs during execution <p>I am currently doing a practice problem in hacker rank. The link is : <a href="https://www.hackerrank.com/challenges/linkedin-practice-dictionaries-and-maps" rel="nofollow">https://www.hackerrank.com/challenges/linkedin-practice-dictionaries-and-maps</a></p>
<pre><code>#include<cstdio>
#include<map>
#include<vector>
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;
map<std::string, int> dict;
map<std::string, int>::iterator k;
int i, j, temp, n;
long long num;
//char check[100][100];
std::string str, sea;
int main()
{
scanf("%d", &n);
j = n;
while(j--)
{
scanf("%s %d", &str, &num);
dict.insert(make_pair(str, num));
}
printf("finished\n");
printf("%s %d\n", "sam", dict["sam"]);
while(scanf("%s", str))
{
if(str.empty())
break;
//printf("k is %s\n",str);
k = dict.find(str);
if(k != dict.end())
{
printf("%s %d\n", str, dict[str]);
}
else
{
printf("Not found\n");
}
}
getch();
}
</code></pre>
<p>The program runs fine until the printf statement "finished". Then in the next output for the dict statement occurs as</p>
<pre><code>finished
sam 0
</code></pre>
<p>And in while statement, when it searches for string in map, the application hangs, and closes automatically. While inserting values I tried to use:</p>
<ol>
<li>dict[str] = num;</li>
<li>dict.insert(pair(str, num));</li>
<li>dict.insert(make_pair(str, num));</li>
</ol>
<p>Please mention if there is any corrections I need to do in the program. Any help is appreciated. Thanks!</p>
| <p>This statement,</p>
<pre><code>scanf("%s %d", &str, &num);
</code></pre>
<p>… is not a valid way to input a <code>std::string</code>. It has Undefined Behavior. All bets are off.</p>
<p>You can input to a <code>char</code> buffer, and conveniently <code>std::string</code> provides such a buffer. E.g.</p>
<pre><code>str.resize( max_item_length );
scanf("%s %d", &str[0], &num);
str.resize( strlen( &str[0] ) );
</code></pre>
<p>Of course you can just use C++ iostreams instead, throughout the code, e.g.</p>
<pre><code>cin >> str >> num;
</code></pre>
|
How can choose the five largest values âin an array and put them in a new array? <pre><code>int[] a = { 1, 2, 5, 2, 4, 6, 8, 9, 1, 19 };
int[] largestValues = new int[5];
for (int i=0; i < 5; i++ ) {
System.out.println(largestValues[i]);
}`
</code></pre>
| <p>You can use following code</p>
<p>For Eg.</p>
<pre><code>public static void main(String args[]) {
int i;
int large[] = new int[5];
int array[] = { 33, 55, 13, 46, 87, 42, 10, 34, 43, 56 };
int max = 0, index;
for (int j = 0; j < 5; j++) {
max = array[0];
index = 0;
for (i = 1; i < array.length; i++) {
if (max < array[i]) {
max = array[i];
index = i;
}
}
large[j] = max;
array[index] = Integer.MIN_VALUE;
System.out.println("Largest " + j + " : " + large[j]);
}
}
</code></pre>
|
Rails : How to accessing relation attributes from the view <p>I have the following rails code </p>
<p>Employee model: id | emp_name | emp_number</p>
<pre><code>class Employee < ActiveRecord::Base
has_many :visitors
end
</code></pre>
<p>Visitor Model:id|employee_id|visitor_name|vis_company|vis|email</p>
<pre><code> class Visitor < ActiveRecord::Base
belongs_to :employee
end
</code></pre>
<p>Employee Controller :</p>
<pre><code>class EmployeesController < ApplicationController
before_action :set_employee, only: [:show, :edit, :update, :destroy]
# GET /employees
# GET /employees.json
def index
@employees = Employee.all
end
# GET /employees/1
# GET /employees/1.json
def show
end
# GET /employees/new
def new
@employee = Employee.new
end
# GET /employees/1/edit
def edit
end
# POST /employees
# POST /employees.json
def create
@employee = Employee.new(employee_params)
respond_to do |format|
if @employee.save
format.html { redirect_to @employee, notice: 'Employee was successfully created.' }
format.json { render :show, status: :created, location: @employee }
else
format.html { render :new }
format.json { render json: @employee.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /employees/1
# PATCH/PUT /employees/1.json
def update
respond_to do |format|
if @employee.update(employee_params)
format.html { redirect_to @employee, notice: 'Employee was successfully updated.' }
format.json { render :show, status: :ok, location: @employee }
else
format.html { render :edit }
format.json { render json: @employee.errors, status: :unprocessable_entity }
end
end
end
# DELETE /employees/1
# DELETE /employees/1.json
def destroy
@employee.destroy
respond_to do |format|
format.html { redirect_to employees_url, notice: 'Employee was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_employee
@employee = Employee.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def employee_params
params.require(:employee).permit(:emp_id, :emp_name, :emp_email, :emp_phone, :emp_mobile)
end
end
</code></pre>
<p>Visitor Controller :</p>
<pre><code>class VisitorsController < ApplicationController
before_action :set_visitor, only: [:show, :edit, :update, :destroy]
# GET /visitors
# GET /visitors.json
def index
#@visitors = Visitor.find(:all, :order => 'emp_name')
#@visitors = Visitor.all.includes(:emp_name)
@visitors = Visitor.all
#@employees = @visitors.Employee.find(:all, :order => 'emp_name')
#@employees = @visitors.employee :include => [:emp_name]
end
# GET /visitors/1
# GET /visitors/1.json
def show
end
# GET /visitors/new
def new
@visitor = Visitor.new
end
# GET /visitors/1/edit
def edit
end
# POST /visitors
# POST /visitors.json
def create
@visitor = Visitor.new(visitor_params)
respond_to do |format|
if @visitor.save
format.html { redirect_to @visitor, notice: 'Visitor was successfully created.' }
format.json { render :show, status: :created, location: @visitor }
else
format.html { render :new }
format.json { render json: @visitor.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /visitors/1
# PATCH/PUT /visitors/1.json
def update
respond_to do |format|
if @visitor.update(visitor_params)
format.html { redirect_to @visitor, notice: 'Visitor was successfully updated.' }
format.json { render :show, status: :ok, location: @visitor }
else
format.html { render :edit }
format.json { render json: @visitor.errors, status: :unprocessable_entity }
end
end
end
# DELETE /visitors/1
# DELETE /visitors/1.json
def destroy
@visitor.destroy
respond_to do |format|
format.html { redirect_to visitors_url, notice: 'Visitor was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_visitor
@visitor = Visitor.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def visitor_params
params.require(:visitor).permit(:vis_id, :vis_name, :vis_email, :vis_company, :employee_id)
end
end
</code></pre>
<p>Now my main problem is that I cant access employee name from visitor view :</p>
<pre><code><p id="notice"><%= notice %></p>
<h1>Listing Visitors</h1>
<table>
<thead>
<tr>
<th>Vis</th>
<th>Vis name</th>
<th>Vis email</th>
<th>Vis company</th>
<th>Visitor Host</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @visitors.each do |visitor| %>
<tr>
<td><%= visitor.id %></td>
<td><%= visitor.vis_name %></td>
<td><%= visitor.vis_email %></td>
<td><%= visitor.vis_company %></td>
<td><%= visitor.employee.emp_name %></td>
<td><%= link_to 'Show', visitor %></td>
<td><%= link_to 'Edit', edit_visitor_path(visitor) %></td>
<td><%= link_to 'Destroy', visitor, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Visitor', new_visitor_path %>
</code></pre>
| <p>I created new project from the scratch and for some reason it started working. My mistake was that I didn't define the relation from the start. I added employee_id after everything else is created I think the rails didn't build the relation at that time. thanks everyone</p>
|
how to import dat file in R <p>I have a dat. file containing one really long line. I have the specific layout to read the data but I do not know how.</p>
<p>What I have done so far(based on searhes in other posts) is try to use readLines, read.fwf, and also I tried to copy that line into one vector which later to split according to the logic in the layout but with no success. All of the approaches seem to encounter a problem with the length of the line in question which composes the entire dat. file</p>
<p>Any suggestions are appreciated!</p>
<p>PS: I am a beginner in R</p>
<p>I think it will be good to add an example so here it comes:</p>
<p>If we have a text file containing a single line as follows:</p>
<p>1 a 5 2 b 6 3 c 7</p>
<p>and we have the layout, in this case we need three variables with length 1 - the first one numeric, the second - string and the third one - numeric again</p>
<p>the imported data frame should look like:</p>
<p>1 a 5</p>
<p>2 b 6</p>
<p>3 c 7</p>
<p>3 rows, 3 columns</p>
| <p>To read dat files you need to use the command <code>read.delim()</code>. See <code>?read.delim</code> for info on how to specify formatting. </p>
<p>EDIT:</p>
<p>Maybe after you read it as a single line you could do something like this:</p>
<pre><code># Creating sample data
data <- data.frame(x = c(1, 'a', 5, 2, 'b', 6, 3,'c', 7))
# Creating the columns
a <- as.numeric(data$x[seq(1,nrow(data), 3)])
b <- as.character(data$x[seq(2,nrow(data), 3)])
c <- as.numeric(data$x[seq(3, nrow(data), 3)])
# Putting it all together
data1 <- data.frame(a,b,c)
</code></pre>
<p>This works even if you want to create a lot of rows but gets tedious if you have a lot of columns. Honestly I have never had only a single line in a file so I don't know how to specify that directly when reading it. Hope that still helps though :)</p>
|
Shapes (1,) and () are not compatible on cond operator <p>I want to skip some data that have specific labels (like if <code>label</code> >= 7 or other). My code is here:</p>
<pre><code>true = tf.constant(True)
less_op = tf.less(label, tf.constant(delimiter))
label = tf.cast(
tf.slice(record_bytes, [0], [label_bytes]), tf.int32)
tf.cond(less_op, lambda: true, lambda: true)
</code></pre>
<p>and on the 4th line I have error: <code>ValueError: Shapes (1,) and () are not compatible</code>. My assumption that it's caused by less_op (if I substitute it with <code>true</code> code works). Also I investigated that there is some problem with <code>label</code>: code <code>less_op = tf.less(tf.constant(1), tf.constant(delimiter))</code> works perfectly.</p>
| <p>Tensorflow expects it to be of shape None or [] and not (1,). It's weird behavior that should be fixed in my opionion because tf.less returns a tensor of shape (1,) and not shape ().</p>
<p>Change this:</p>
<pre><code>tf.cond(less_op, lambda: true, lambda: true)
</code></pre>
<p>to this:</p>
<pre><code>tf.cond(tf.reshape(less_op,[]), lambda: true, lambda: true)
</code></pre>
|
jQuery - Add row to datatable without reloading/refreshing <p>I'm trying add data to DB and show these data in same page using ajax and jQuery datatable without reloading or refreshing page. My code is saving and retrieving data to/from database. But updated data list is not showing in datatable without typing in search box or clicking on table header. Facing same problem while loading page. </p>
<p>Here is my code</p>
<pre><code>//show data page onload
$(document).ready(function() {
catTable = $('#cat_table').DataTable( {
columns: [
{ title: "Name" },
{ title: "Level" },
{ title: "Create Date" },
{ title: "Status" }
]
});
get_cat_list();
});
//save new entry and refresh data list
$.ajax({
url: 'category_save.php',
type: 'POST',
data:{name: name,level: level},
success: function (data) {
get_cat_list();
},
error: function (data) {
alert(data);
}
});
//function to retrieve data from database
function get_cat_list() {
catTable.clear();
$.ajax({
url: 'get_category_list.php',
dataType: 'JSON',
success: function (data) {
$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
] );
});
}
});
}
</code></pre>
| <p>From the <a href="https://datatables.net/reference/api/row.add()" rel="nofollow">documentation</a>,</p>
<blockquote>
<p>This method will add the data to the table internally, but does not
visually update the tables display to account for this new data.</p>
</blockquote>
<p>In order to have the table's display updated, use the <a href="https://datatables.net/reference/api/draw()" rel="nofollow">draw()</a> method, which can be called simply as a chained method of the <strong>row.add()</strong> method's returned object.</p>
<p>So you success method would look something like this,</p>
<pre><code>$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
]).draw();
});
</code></pre>
|
Convert Picturebox Image to Transparent VB.Net <p>I'm having a problem when it comes to images with white background. How can I remove the white background or make the image transparent? </p>
<p>For now I'm using this code</p>
<pre><code>Dim _ms3 As New System.IO.MemoryStream()
pbSignCapture.Image.Save(_ms3, System.Drawing.Imaging.ImageFormat.Png)
Dim _arrImage3() As Byte = _ms3.GetBuffer()
_ms3.Close()
</code></pre>
<p>Also saving the image using the <code>_arrImage3</code>.</p>
<p>I want to convert the image in the PictureBox to turn the White Background into transparent.</p>
| <p>Consider using the <code>Bitmap</code> class to open your image files.</p>
<pre><code>Dim myImage as new Bitmap("C:\Image file.bmp")
</code></pre>
<p>And then you can use the <a href="https://msdn.microsoft.com/en-us/library/4zzst10b(v=vs.110).aspx" rel="nofollow">MakeTransparent()</a> or <a href="https://msdn.microsoft.com/en-us/library/8517ckds(v=vs.110).aspx" rel="nofollow">MakeTransparent(Color)</a> methods:</p>
<p>Get the color of a background pixel.</p>
<pre><code>Dim backColor As Color = myImage.GetPixel(1, 1)
</code></pre>
<p>Make backColor transparent for myBitmap.</p>
<pre><code>myImage.MakeTransparent(backColor)
</code></pre>
<p><strong>EDIT:</strong></p>
<p>As I understand from the new details you want to have a <code>PictureBox</code> to be transparent where the source image is transparent. Unfortunately this is not possible using <code>WinForms</code> because the transparency system is not cascading. You can set the <code>BackgroundColor</code>property of pictureBox to transparent, but this is going to act differently from what you may think. The free pixels of the PictureBox control will show the content of the <strong>parent control</strong>. </p>
<p>It means that if you have, for example, a label below your picurebox and set transparent background to the image; the label won't be shown because it is not theparent control of the picturebox.</p>
<p>A workaround is to manually draw the image in the <code>paint</code> event of the destination control.</p>
<p>Let's assume that you have a form with many controls and you want to draw ad image over a button (named btn). You'll have to override the form's paint event this way:</p>
<pre><code>Private Sub form_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles form.Paint
Dim g As Graphics = e.Graphics
g.DrawImage(Image.FromFile("C:/yourimage.png", btn.Location.X, btn.Location.Y)
End Sub
</code></pre>
|
Why is my JavaScript function not being called? <p>This JavaScript function used to work before until I made it more complicated as I try to push more error checking to the front end. </p>
<p>Here is the front end code just the important bits for brevity:</p>
<pre><code> <body>
<form id="form1" runat="server">
<div>
<script type = "text/javascript" >
function checkThings()
{
var jobSeekerFirstName = document.getElementsByName('txtJobSeekerFirstName')[0].value
var jobSeekerLastName = document.getElementsByName('txtJobSeekerLastName')[0].value
var jobSeekerUserName = document.getElementsByName('txtJobSeekerUserName')[0].value
var jobSeekerPassword = document.getElementsByName('txtJobSeekerPassword')[0].value
var jobSeekerPhoneNumber = document.getElementsByName('txtJobSeekerPhoneNumber')[0].value
var jobSeekerEmail = document.getElementsByName('txtJobSeekerEmailAddress')[0].value
var jobSeekerAnswer = document.getElementsByName('txtJobSeekersSecurityAnswer')[0].value
if ((jobSeekerFirstName != '') && (jobSeekerLastName != '') && (jobSeekerUserName != '') &&
(jobSeekerPassword != '') && (jobSeekerPhoneNumber != '') && (jobSeekerEmail != '') &&
(jobSeekerAnswer != '')) // First check all fields entered
{
if (jobSeekerUserName.length == 6) {
var emAddrCounter;
var emlength = jobSeekerEmail.length;
var emailCorrect = false;
for (emAddrCounter = 0; ((emAddrCounter < emlength) && (emailCorrect == false)) ; emAddrCounter++) {
var emChar = jobSeekerEmail.charAt(emAddrCounter);
if (emChar == '@') emailCorrect = true;
}
if (emailCorrect == false) {
var emailNoAtChar = " Email address must contain @ character. Please reenter";
document.getElementsById('txtMessageBox').Text = emailNoAtChar;
return false;
}
else {
return true;
}
}
else
{
var userNameNotSix = " User name must be exactly six characters long. Please reenter";
document.getElementsByName('txtMessageBox').Text = userNameNotSix;
return false;
}
}
else
{
var allElementsPresent = " All Fields must be filled in first. Please reenter all fields";
document.getElementsById('txtMessageBox').Text = allElementsPresent;
return false;
}
}
</script>
<asp:ScriptManager ID="scripman1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
</code></pre>
<p>calling line</p>
<pre><code> <asp:Button ID="btnNewJobSeekerRegistration" runat="server"
Text=" Register me as a new Job Seeker "
OnClientClick= "return checkThings();"
OnClick="btnNewJobSeekerRegistration_Click" />
</code></pre>
<p>I keep getting </p>
<blockquote>
<p>Operation Completed</p>
</blockquote>
<p>and it seems to have skipped all the JavaScript function and all the error checking therein. Any ideas?</p>
| <p>For those of you who want the full code:
ASP.NET Front End:</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JobSeekerRegistration.aspx.cs" Inherits="JobSearchWebsite.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title> Job Seeker Registration</title>
<style type="text/css">
.auto-style1 {
width: 394px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<script type = "text/javascript" >
function checkThings()
{
var jobSeekerFirstName = document.getElementsByName('txtJobSeekerFirstName')[0].value;
var jobSeekerLastName = document.getElementsByName('txtJobSeekerLastName')[0].value;
var jobSeekerUserName = document.getElementsByName('txtJobSeekerUserName')[0].value;
var jobSeekerPassword = document.getElementsByName('txtJobSeekerPassword')[0].value;
var jobSeekerPhoneNumber = document.getElementsByName('txtJobSeekerPhoneNumber')[0].value;
var jobSeekerEmail = document.getElementsByName('txtJobSeekerEmailAddress')[0].value;
var jobSeekerAnswer = document.getElementsByName('txtJobSeekersSecurityAnswer')[0].value;
if ((jobSeekerFirstName != '') && (jobSeekerLastName != '') && (jobSeekerUserName != '') &&
(jobSeekerPassword != '') && (jobSeekerPhoneNumber != '') && (jobSeekerEmail != '') &&
(jobSeekerAnswer != '')) // First check all fields entered
{
if (jobSeekerUserName.length == 6)
{
var emAddrCounter;
var emlength = jobSeekerEmail.length;
var emailCorrect = false;
for (emAddrCounter = 0; ((emAddrCounter < emlength) && (emailCorrect == false)) ; emAddrCounter++)
{
var emChar = jobSeekerEmail.charAt(emAddrCounter);
if (emChar == '@') emailCorrect = true;
}
if (emailCorrect == false)
{
var emailNoAtChar = " Email address must contain @ character. Please reenter";
document.getElementsById('txtMessageBox').Text = emailNoAtChar;
return false;
}
else { return true;}
}
else
{
var userNameNotSix = " User name must be exactly six characters long. Please reenter";
document.getElementsByName('txtMessageBox').Text = userNameNotSix;
return false;
}
}
else
{
var allElementsPresent = " All Fields must be filled in first. Please reenter all fields";
document.getElementsById('txtMessageBox').Text = allElementsPresent;
return false;
}
}
</script>
<asp:ScriptManager ID="scripman1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<table style="width: 807px; height: 249px;">
<tr>
<td class="auto-style1">
<asp:Label ID="lbJobSeekerFirstName" runat="server" Text="Job Seeker's First Name :"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtJobSeekerFirstName" runat="server" Width="227px" MaxLength="50"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbJobSeekerLastName" runat="server" Text="Job Seeker's Last Name :"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtJobSeekerLastName" runat="server" Width="227px" MaxLength="50"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbJobSeekersUname" runat="server" Text="Job Seeker's Username (Must be 6 Characters long) : "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtJobSeekerUserName" runat="server" MaxLength="6"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbJobSeekersPassword" runat="server" Text="Job Seeker's Password (Must be 8 long and be alphanumeric) : "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtJobSeekerPassword" runat="server" MaxLength="8" style="margin-bottom: 0px" Width="142px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbJobSeekersPhoneNumber" runat="server" Text="Job Seeker's Phone Number (Containing No spaces) : "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtJobSeekerPhoneNumber" runat="server" Width="143px" MaxLength="10"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbJobSeekersEmailAddress" runat="server" Text="Job Seeker's Email Address (Must Contain @ symbol) : "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtJobSeekerEmailAddress" runat="server" Width="275px" MaxLength="50"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbJobSeekersSecurityQuestion" runat="server" Text="Job Seeker's Security Question : "></asp:Label>
</td>
<td>
<asp:DropDownList ID="drpJobSeekerSecurityQuestion" runat="server" Height="18px" Width="390px">
<asp:ListItem>What is your Mother&#39;s Maiden Name?</asp:ListItem>
<asp:ListItem>In Which city were you born?</asp:ListItem>
<asp:ListItem>What is your favourite colour?</asp:ListItem>
<asp:ListItem>What is your favourite Sport?</asp:ListItem>
<asp:ListItem>In which suburb was your first house?</asp:ListItem>
<asp:ListItem>What was the name of the first street you lived in?</asp:ListItem>
<asp:ListItem>What was your first occupation?</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbJobSeekerSecurityAnswer" runat="server" Text="Job Seeker's Security Answer : "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtJobSeekersSecurityAnswer" runat="server" Width="380px" MaxLength="50"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnNewJobSeekerRegistration" runat="server" Text=" Register me as a new Job Seeker " OnClientClick= "return checkThings();" OnClick="btnNewJobSeekerRegistration_Click" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lbMessage" runat="server" Text="Message:"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtMessageBox" runat="server" Width="383px" MaxLength="400" ReadOnly="True"></asp:TextBox>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
</code></pre>
|
ezPlot overlapping error bar and data <p>I am using ezPlot from the ez package in R to plot results of a mixed within and between-ss design. The data point from the two groups I have overlap so that I would like to jitter both the data point and associated error bar. </p>
<pre><code>data<-structure(list(Sub = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("WW", "XX", "YY",
"ZZ"), class = "factor"), DepVar = c(0.67, 0.35, 0.09, 0.2, 0.19,
0.13, 0.45, 0.23, 0.08, 0.32, 0.17, 0.18, 0.67, 0.36, 0.55, 0.4,
0.37, 0.05, 0.26, 0.11, 0.08, 0.46, 0.29, 0.18, 0.16, 0, 0.38,
0.22, 0.08, 0.1, 0.54, 0.17, 0.07, 0.38, 0.75, 0.87, 0.27, 0.57,
0.31, 0.28, 0.07, 0.12, 0.75, 0.33, 0.23, 0.33, 0.26, 0.18),
Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", "B"), class = "factor"),
Con = structure(c(1L, 3L, 3L, 3L, 4L, 5L, 2L, 3L, 4L, 1L,
2L, 3L, 1L, 3L, 3L, 3L, 4L, 5L, 2L, 3L, 4L, 1L, 2L, 3L, 1L,
3L, 3L, 3L, 4L, 5L, 2L, 3L, 4L, 1L, 2L, 3L, 1L, 3L, 3L, 3L,
4L, 5L, 2L, 3L, 4L, 1L, 2L, 3L), .Label = c("C", "D", "E",
"F", "G"), class = "factor")), .Names = c("Sub", "DepVar",
"Group", "Con"), class = "data.frame", row.names = c(NA, -48L))
ezPlot( data,
dv = .(DepVar),
wid = .(Sub), # subject
within = .(Con),
between=.(Group),
split=.(Group),
do_bars=TRUE,
type = 2,
x = .(Con))
</code></pre>
<p><a href="http://i.stack.imgur.com/YwdWz.png" rel="nofollow"><img src="http://i.stack.imgur.com/YwdWz.png" alt="enter image description here"></a></p>
<p>A non elegant trick is so set scale-color manual white so that the underlying data points disappear and then using geom-point position dodge(0.4)) </p>
<pre><code>ezPlot( data,
dv = .(DepVar),
wid = .(Sub), # subject
within = .(Con),
between=.(Group),
split=.(Group),
do_bars=TRUE,
type = 2,
x = .(Con))+
scale_color_manual(values=c("white", "white"))+
geom_point(aes(fill=Group), color="black", pch= 21, size= 3, position=position_dodge(0.4))+
geom_line(aes(group = Group), lty = 3, lwd = 1.3, color='black')
</code></pre>
<p><a href="http://i.stack.imgur.com/EY0wX.png" rel="nofollow"><img src="http://i.stack.imgur.com/EY0wX.png" alt="enter image description here"></a></p>
<p>however, I would like to have the error bar plotted and I don't know how to achieve this or if other workarounds are possible. I would like to stick to ezplot. Thanks! </p>
| <p>One way is to use set <code>print_code = TRUE</code>, to produce data to be plotted, as well as the <code>ggplot</code> code:</p>
<pre><code>library(ggplot2)
stats <- ezPlot( data,
dv = .(DepVar),
wid = .(Sub), # subject
within = .(Con),
between=.(Group),
split=.(Group),
do_bars=TRUE,
type = 2,
x = .(Con),
print_code = TRUE)
</code></pre>
<p>Then, manually modify the code to add <code>position = position_dodge(0.4)</code> to each geom, then run the <code>ggplot</code> code.</p>
<p>A more efficient way to do the same thing would be to <code>capture.output</code> the code as a character vector, use <code>gsub</code> to add <code>position = position_dodge(0.4)</code>, then <code>eval(parse(text = ...))</code> the modified code:</p>
<pre><code>gg_code <- capture.output(stats <- ezPlot( data,
dv = .(DepVar),
wid = .(Sub), # subject
within = .(Con),
between=.(Group),
split=.(Group),
do_bars=TRUE,
type = 2,
x = .(Con),
print_code = TRUE))
gg_code <- gsub("alpha", "position = position_dodge(0.4), alpha", gg_code)
eval(parse(text = paste(gg_code, collapse = "")))
</code></pre>
<p>Output:</p>
<p><a href="http://i.stack.imgur.com/GHDNa.png" rel="nofollow"><img src="http://i.stack.imgur.com/GHDNa.png" alt="enter image description here"></a></p>
|
php creating file from another file <p>Im new to php and I'm just trying stuff out, and I was wondering if i could take text from one file then put it into another.<br>
For example have a .txt file that contains : </p>
<pre><code><?php
echo "Hello World";
?>
</code></pre>
<p>but then have a script run that takes that text and puts it into a new .php file.</p>
| <p>If I understand you correctly, what are you trying to achive is copying a content of a text file to a php file.</p>
<p>Simpliest way to do it:</p>
<pre><code><?php
$sourceFile = 'example.txt';
$destinyFile = 'example.php';
if (copy($sourceFile, $destinyFile))
echo "DONE";
</code></pre>
|
Bitbucket 443 Network is unreachable on different network <p>My git and Bitbucket connects and works just fine when I am in my office connected my laptop to wifi.</p>
<p>But when I get home and connect same laptop to my wifi and try to access bitbucket I get 443 error.</p>
<pre><code>git pull
fatal: unable to access 'https://xxxxx@bitbucket.org/xxxx/xxxx.git/': Failed to connect to bitbucket.org port 443: Network is unreachable
</code></pre>
| <p>As mentioned in <a href="https://bitbucket.org/site/master/issues/12184/failed-to-connect-to-bitbucketorg-port-443" rel="nofollow">this issue</a>, try and set GIT_CURL_VERBOSE=1 before executing the git clone: you might have more clues.</p>
<p>The standard advice is:</p>
<blockquote>
<p>"Failed to connect" errors could be anything from DNS issues to local network problems to ISPs that are incompletely routing Bitbucket traffic.<br>
Unfortunately, there isn't enough detail in any of these comments to diagnose the exact problems, which may or may not be related to each other. </p>
<p>If you could, please open a support ticket with the results of the following commands:</p>
<p>For OS X, Linux, and other UNIX-based operating systems:</p>
</blockquote>
<pre><code>ping -c10 bitbucket.org
ping6 -c10 bitbucket.org
traceroute bitbucket.org
traceroute6 bitbucket.org
GIT_CURL_VERBOSE=1 git ls-remote https://bitbucket.org/bitbucket/do_not_delete
</code></pre>
<blockquote>
<p>For Windows:</p>
</blockquote>
<pre><code>ping -n 10 bitbucket.org
ping -n 10 -6 bitbucket.org
tracert bitbucket.org
tracert -6 bitbucket.org
</code></pre>
<p>(To clarify: "<code>ping6</code>" and "<code>traceroute6</code>" are the <code>IPv6</code> equivalents of "<code>ping</code>" and "<code>traceroute</code>", respectively, and "<code>GIT_CURL_VERBOSE=1</code>" before any git command will detail all the HTTP-specific parts of the connection.<br>
On the Windows side of things, the "<code>-6</code>" in the command line specifies that your computer should use <code>IPv6</code> for the <code>ping</code> or <code>tracert</code>.)</p>
<blockquote>
<p>Additionally, if you suspect that your problem is related to Bitbucket's IPv6 support, then you should be able to test your overall IPv6 connectivity by opening the following links in your browser:</p>
</blockquote>
<pre><code>https://ipv6.google.com
https://www.v6.facebook.com
</code></pre>
<blockquote>
<p>Those links should not work at all if your IPv6 connection is disabled or misconfigured.<br>
If that's the case, as a <em>temporary</em> workaround (note the heavy emphasis on the word "temporary"!), you can add "<code>104.192.143.3 bitbucket.org</code>" to your hostfile while you work with your network administrators and/or ISP to fix IPv6 access on that system.</p>
</blockquote>
|
WPF: Stop Animation For Hidden Controls on Windows Load <p>I have a very simple fade in/out animation which works fine using data triggers. I have bind the data trigger to a bool property and inside trigger it set the opacity to 0 on false and vice versa.</p>
<p>Now the problem is the objects whose bool value is false upon loading, I don't expect them to show on load and then animate themselves to hide.</p>
<p>I have tried to set the opacity to 0 on style setter but no use</p>
<p>Here is the button style</p>
<pre><code> <Style x:Key="LocationPickerButtonStyle" TargetType="{x:Type Button}">
<Style.Setters>
<Setter Property="Height" Value="93"/>
<Setter Property="Width" Value="93"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid >
<Image x:Name="DefaultImage" Source="something.png"/>
<Ellipse x:Name="HitTest" Fill="Transparent" Height="93" Width="93" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding IsLocationVisible}" Value="true">
<DataTrigger.EnterActions>
<BeginStoryboard x:Name="showSelectedLocation">
<Storyboard Storyboard.TargetProperty="Opacity">
<DoubleAnimation Duration="0:0:1" From="0" To="1"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<StopStoryboard BeginStoryboardName="showSelectedLocation"></StopStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
<DataTrigger Binding="{Binding IsLocationVisible}" Value="false">
<DataTrigger.EnterActions>
<BeginStoryboard x:Name="hideSelectedLocation">
<Storyboard Storyboard.TargetProperty="Opacity" >
<DoubleAnimation Duration="0:0:1" From="1" To="0" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<StopStoryboard BeginStoryboardName="hideSelectedLocation"></StopStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
<Trigger Property="Opacity" Value="0">
<Setter Property="Visibility" Value="Collapsed"></Setter>
</Trigger>
<Trigger Property="Opacity" Value="1">
<Setter Property="Visibility" Value="Visible"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
</code></pre>
| <p>Do these changes in your XAML : </p>
<ol>
<li><p>Shift your <code>DataTriggers</code> from <code><ControlTemplate.Triggers></code> to <code>Style.Triggers</code>.</p></li>
<li><p>Set <code>Opacity = 0</code> in <code>Style Setter</code> as starting <code>Opacity</code> for every <code>Button</code>.</p></li>
<li><p>Remove <code>From = 1</code> in <code>false DataTrigger</code>.</p></li>
</ol>
<p>With all the changes, your <code>Style</code> would look like this : </p>
<pre><code> <Style x:Key="LocationPickerButtonStyle" TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsLocationVisible}" Value="true">
<DataTrigger.EnterActions>
<BeginStoryboard x:Name="showSelectedLocation">
<Storyboard Storyboard.TargetProperty="Opacity">
<DoubleAnimation Duration="0:0:1" From="0" To="1"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<StopStoryboard BeginStoryboardName="showSelectedLocation"></StopStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
<DataTrigger Binding="{Binding IsLocationVisible}" Value="false">
<DataTrigger.EnterActions>
<BeginStoryboard x:Name="hideSelectedLocation">
<Storyboard Storyboard.TargetProperty="Opacity" >
<DoubleAnimation Duration="0:0:1" To="0" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<StopStoryboard BeginStoryboardName="hideSelectedLocation"></StopStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
<Style.Setters>
<Setter Property="Height" Value="93"/>
<Setter Property="Width" Value="93"/>
<Setter Property="Opacity" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid >
<Image x:Name="DefaultImage" Source="something.png"/>
<Ellipse x:Name="HitTest" Fill="Transparent" Height="93" Width="93" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="Opacity" Value="0">
<Setter Property="Visibility" Value="Collapsed"></Setter>
</Trigger>
<Trigger Property="Opacity" Value="1">
<Setter Property="Visibility" Value="Visible"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
</code></pre>
|
Bootstrap Text Align Center Vertically <p>I want to make a text vertically center on 100vh height.
Here is what I've done</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.about-header {
height: 100vh;
background: #000;
}
.about-header p {
font-size: 5em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container-fluid about-header text-center">
<div class="row ">
<div class="col-md-12">
<p>Lorem Ipsum</p>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| <p>just add this below CSS:-</p>
<pre><code>.about-header{
height: 100vh;
background: #000;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
</code></pre>
<p>Your content will be vertically aligned.</p>
|
md-content does not consume full height of the parent element <pre><code><md-content flex class="md-padding page-content">
<div ui-view flex layout="column">
<div class="center" layout="row" flex>
<md-content layout="column" flex="30">
<md-list-item ng-repeat="entity in vm.entities">
<md-checkbox ng-model="entity.selected"></md-checkbox>
<p>{{entity.info}}</p>
<md-icon class="md-secondary"
ng-click="doSecondaryAction($event)" aria-label="Chat">message</md-icon>
</md-list-item>
</md-content>
<md-divider></md-divider>
<md-content layout="column" flex="70">
Details here!
</md-content>
</div>
</div>
</md-content>
</code></pre>
<p>In my code above, the outermost md-content occupies the complete page; however with the ui-view gived column layout and flex class, I expected it to occupy the complete height of the page, however it occupies the height consumed by the content only.</p>
<p>Can you please help with the error in the code, so ui-view can occupy the complete page?</p>
| <p>Here you go - <a href="http://codepen.io/camden-kid/pen/VKXWwX" rel="nofollow">CodePen</a></p>
<p>You need to utilise <code>layout-fill</code>. From the <a href="https://material.angularjs.org/latest/layout/options" rel="nofollow">docs</a></p>
<p><a href="http://i.stack.imgur.com/FeKaE.png" rel="nofollow"><img src="http://i.stack.imgur.com/FeKaE.png" alt="enter image description here"></a></p>
<p>In order for this to work an upper element must occupy the full screen. In the above example it is <code><body></code>.</p>
<p>Markup</p>
<pre><code><div ng-controller="AppCtrl as vm" ng-cloak="" ng-app="MyApp" layout-fill>
<md-content layout-fill flex class="md-padding page-content">
<div ui-view flex layout="column" layout-fill>
<div class="center" layout="row" flex>
<md-content id="list" layout="column" flex="30">
<md-list-item ng-repeat="entity in vm.entities" flex="none">
<md-checkbox ng-model="entity.selected"></md-checkbox>
<p>{{entity.info}}</p>
<md-icon class="md-secondary"
ng-click="doSecondaryAction($event)" aria-label="Chat">message</md-icon>
</md-list-item>
</md-content>
<md-divider></md-divider>
<md-content id="details" layout="column" flex="70">
Details here!
</md-content>
</div>
</div>
</md-content>
</div>
</code></pre>
<p>CSS</p>
<pre><code>.page-content {
background: yellow
}
#list {
overflow-y: auto;
overflow-x: hidden;
}
</code></pre>
|
unable to pass map to restful method <p>I am trying to call this api via postman</p>
<pre><code>@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void printDetails(final MultivaluedMap<String, String> formParams) {
for(String key : formParams.keySet()) {
System.out.println(key + " " + formParams.get(key));
}
}
</code></pre>
<p>But the map turns out to be empty. Please help me with the same. </p>
<p>PS: This is the first time I am trying to pass variable number of parameters to the api. I have referred to
<a href="http://stackoverflow.com/questions/8413608/sending-list-map-as-post-parameter-jersey">sending List/Map as POST parameter jersey</a> and <a href="http://stackoverflow.com/questions/8194408/how-to-access-parameters-in-a-restful-post-method">How to access parameters in a RESTful POST method</a>. </p>
<p>I think my mistake is in the way i am passing the parameters in postman: <a href="http://i.stack.imgur.com/OqukK.png" rel="nofollow">postman image</a></p>
<p>Please help me with the same. Also please help with how to call this api via an ajax (in js) call. Thank you</p>
| <p>Set the request header as <code>"application/x-www-form-urlencoded"</code>.</p>
<p><a href="http://i.stack.imgur.com/HrnFz.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/HrnFz.jpg" alt="Postman request header"></a></p>
<p>Request body - Select raw and provide values as mentioned below:-</p>
<pre><code>{
"LOCATION": "Singapore"
}
</code></pre>
<p><a href="http://i.stack.imgur.com/xfQ9W.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/xfQ9W.jpg" alt="enter image description here"></a></p>
|
Visual Studio 2015 Enterprise very slow startup <p>I have the same version of VS 2015 at home and work; at work on a win7 machine it starts very fast (even with a solution of more than 100 projects!), taking roughly 10-15 seconds.
At home on a win10, it starts very slow (around 2 mins) with a solution of only 20 projects. Once it starts, everything is fine; just the startup very slow.
I saw other posts talking about uninstalling Node.js tool which I did; but it makes no difference. I also disabled setting synchronisation.</p>
<p>Any other suggestion to fix this?</p>
| <p>Try deleting the <strong>.suo</strong> file in the project directory.
Then start it up.
I had that problem in MSVS 2010.</p>
|
Unable to find lmdb while installing caffe with make all <p><a href="http://i.stack.imgur.com/d9iAd.png" rel="nofollow">/usr/bin/ld: cannot find -lmdb
collect2: error: ld returned 1 exit status
Makefile:568: recipe for target '.build_release/lib/libcaffe.so.1.0.0-rc3' failed
make: *** [.build_release/lib/libcaffe.so.1.0.0-rc3] Error 1</a></p>
<p>How to get rid of this problem.</p>
| <p>Make sure that the library file your are trying to use while compiling is present in the path that your have given while compiling...</p>
|
Changing default keybinding in yhat's Rodeo IDE <p>To comment out a block in Rodeo the <a href="http://rodeo.yhat.com/docs/#keyboard-shortcuts" rel="nofollow">docs</a> state to do <code>ctrl + /</code>. But on my machine thats not working, so I want to change a single keysetting. Where I am able to do this in Rodeo?</p>
| <p>You can edit key-bindings in preferences <a href="http://rodeo.yhat.com/docs/#preferences" rel="nofollow">http://rodeo.yhat.com/docs/#preferences</a></p>
<p>Changing the key bindings should avoid the use of <code>ctrl + /</code>, but if you just want to change a single setting, as far as I know, it's not possible. It's hardwired in <a href="https://github.com/yhat/rodeo/tree/master/src/browser/ace" rel="nofollow">https://github.com/yhat/rodeo/tree/master/src/browser/ace</a> . You can write some code and build your own IDE if necessary.</p>
|
Search query doesn't return desired results <p>I have kind of advanced search function. All works fine except one <code>AND LIKE ...</code>.
There are two options <code>A</code> or <code>A, *AB</code>. I want when I choose <code>A</code> to return results only which are <code>A</code> in database and when I choose <code>A, *AB</code> to return results which are only <code>A, *AB</code>.</p>
<p>What is happening now is that when I choose <code>B, *AB</code> it returns results which for both</p>
<pre><code>A
A, *AB
</code></pre>
<p>My form is with action <code>get</code>. This is my query</p>
<pre><code> $couGe=($ge == "None") ? "" : "AND c.ge LIKE '".substr($ge, 0, 2)."%'";
$active = ($this->showCouCancelled) ? "AND (c.active=1 OR c.active=7)" : "";
$active = ($this->hideCouActive) ? "AND (c.active=1 OR c.active=3 OR c.active=4 OR c.active=7)" : "";
$couName = ($cName) ? "AND course_title LIKE '%$cName%'" : "";
$couDept = ($cDept) ? "AND s.dept='$cDeptArray[0]' AND s.dept_code='$cDeptArray[1]'" : "";
$iRes = _SQLQuery("
SELECT DISTINCT c.id,s.dept,s.dept_code,c.course_title,c.active,s.year,s.sem,c.ge,c.course_type
FROM courses AS c, sections AS s, teachers as t, tea_sec_rel as tsr
WHERE s.course_id_rel=c.id AND $curYr $curSem $active $couName $couDept $psSearch $couGe
ORDER BY s.dept,s.dept_code");
</code></pre>
<p>The html select option menu has</p>
<pre><code><select name="ge" id="ge">
<option value="None">All</option>
<option value="A">A</option>
<option value="A, *AB">A, *AB</option>
</select>
</code></pre>
<p>On the query this is the line which take <code>ge</code></p>
<pre><code>$couGe=($ge == "None") ? "" : "AND c.ge LIKE '".substr($ge, 0, 2)."%'";
</code></pre>
<p>When I <code>var_dump($_GET['ge']</code> I see that I get what I choose. I'm very confused and any help is appreciated.</p>
| <p>You need to change a bit your query and the way you assign <code>$couGe</code> where you took selected <code>ge</code>. Please try this way</p>
<pre><code>$couGe=($ge == "None") ? "" : "'".substr($ge, 0, 2)."'";
$active = ($this->showCouCancelled) ? "AND (c.active=1 OR c.active=7)" : "";
$active = ($this->hideCouActive) ? "AND (c.active=1 OR c.active=3 OR c.active=4 OR c.active=7)" : "";
$couName = ($cName) ? "AND course_title LIKE '%$cName%'" : "";
$couDept = ($cDept) ? "AND s.dept='$cDeptArray[0]' AND s.dept_code='$cDeptArray[1]'" : "";
$iRes = _SQLQuery("
SELECT DISTINCT c.id,s.dept,s.dept_code,c.course_title,c.active,s.year,s.sem,c.ge,c.course_type
FROM courses AS c, sections AS s, teachers as t, tea_sec_rel as tsr
WHERE s.course_id_rel=c.id AND $curYr $curSem $active $couName $couDept $psSearch $couTea AND c.ge LIKE $couGe
ORDER BY s.dept,s.dept_code");
</code></pre>
|
Calculate the distance of the robot using matlab <p><a href="http://i.stack.imgur.com/fgcle.jpg" rel="nofollow">Sample Picture to find the distance</a></p>
<p>We are currently working on the research based on slipping of the wheels in a mobile robot. We need to find the linear velocity of the robot for that purpose and we are using GoPro Hero4 in that progress. We were advised to get pictures from the camera and use that to find the distance travelled by the robot, from which velocity can be calculated.Here is a picture I have attached. I need to find the D so, that I can use the same algorithm to all my pictures, which I am planning to take while it moves from the start to end position in order to get the distance travelled. </p>
<p>The robot moves in a straight line towards the camera.The camera can also be mounted on top of the robot and pictures of a common object can be allowed to take too depending on the code</p>
<p>PS: From literature study, we learnt using a trajectory algorithm or corner detection method using Harris Detection will help, but since it has wide lens, we are confused. It would be a great help if you could help with this. Thank you </p>
| <p>You should first calibrate your camera as already suggested in the comments. There are lots of tutorials on the web (one tip: dont use loose paper).Then you can print out a marker like this:<a href="http://i.stack.imgur.com/llDNj.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/llDNj.jpg" alt="enter image description here"></a>
Measure out the rectangle and create a vector with the corner points. In this case the rectangle has a width/height of 98mm. You need to convert that unit into chessboard width from your calibration target. Assume your chessboard has 31mm squares. Your vector <code>objectPoints</code> would look like this: (0,0,0) , (3.16,0,0) , (0,3.16,0) , (0,0,3.16).</p>
<p>Then you have to find the corners im your image and store those positions in a vector too. For that you have to get the perspective transform of your marker and apply that to your marker image (read <a href="http://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html#getperspectivetransform" rel="nofollow">here</a>). Then find the corners (they have to be in the right order, i used the circle in the marker for that) and store them in the vector called <code>imagePoints</code>!</p>
<p>With <a href="http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#solvepnp" rel="nofollow">solvePnP</a> , your object and image points and the ouput from the calibration as input you get the pose of the marker. The third component of the translation vector is your distance ! </p>
<pre><code>solvePnP(object_points,image_points,Camera_Matrix, Distortion_Coefficients,
RotRodrigues,
Trans, 0);
</code></pre>
|
Source not found error in Eclipse while debugging <p>I get below error and while debugging. When I put a breakpoint and debugging throws a '<strong>source not found</strong>' error. </p>
<p>I already clicked on "Edit Source Lookup Path" in Eclipse and add my project. but its not working. Please suggest</p>
<pre><code>Exception in thread "main" java.lang.NullPointerException
error line String value = cell.getStringCellValue();
package ExcelPractice;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFEvaluationWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelTest {
public static void main(String[] args) throws IOException {
String value = getExcelData("sheet1",2,2);
System.out.println(" Cell Value " + value);
}
public static String getExcelData( String sheetName , int rowNum ,int cellNum) throws IOException{
FileInputStream fInput = new FileInputStream("C:\\Users\\xxxx\\Excel Data.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fInput);
XSSFSheet sheet = wb.getSheet(sheetName);
XSSFRow row = sheet.getRow(rowNum);
XSSFCell cell = row.getCell(cellNum);//breakpoint is here
String value = cell.getStringCellValue();
return value;
}
}
</code></pre>
<p>error screenshot
<a href="http://i.stack.imgur.com/xwKKf.png" rel="nofollow"><img src="http://i.stack.imgur.com/xwKKf.png" alt="enter image description here"></a> </p>
<p><a href="http://i.stack.imgur.com/oPoPu.png" rel="nofollow"><img src="http://i.stack.imgur.com/oPoPu.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/EwV3S.png" rel="nofollow"><img src="https://i.stack.imgur.com/EwV3S.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/pVZqr.png" rel="nofollow"><img src="https://i.stack.imgur.com/pVZqr.png" alt="enter image description here"></a></p>
| <p>For classes in the standard Java Runtime, the easiest, simplest answer is always going to be to install a JDK, and to compile and run your Java Applications using it. Your <code>Installed JREs</code> preference page should ideally only list JDKs.</p>
|
Python: How to convert google location timestaMps in a year-month-day-hour-minute-seconds format? <p>I am playing around with my google location data (which one can download here <a href="https://takeout.google.com/settings/takeout" rel="nofollow">https://takeout.google.com/settings/takeout</a>). </p>
<p>The location data is a json file, of which one variable is 'timestaMps' (e.g. one observation is "1475146082971"). How do I convert this into a datetime? </p>
<p>Thanks!</p>
| <p>Use <a href="https://docs.python.org/2/library/datetime.html#datetime.date.fromtimestamp" rel="nofollow">fromtimestamp</a> method from datetime module.
To convert your 'timestaMps' to timestamp you need to convert it to int(). Formating of timestamp is done with <a href="https://docs.python.org/2/library/time.html#time.strftime" rel="nofollow">strftime()</a>. </p>
<pre><code>from datetime import datetime
datetime.fromtimestamp(int("1475146082971")).strftime('%Y-%m-%d %H:%M:%S')
</code></pre>
|
How to stop this fancybox opening on load? <p>I'm trying to figure out why this jQuery code makes a fancybox image open on page load rather than waiting for the user to click on it. How do I have it open when it's clicked on? Here's a <a href="http://jsfiddle.net/jsykes/j14gf3sv/3/" rel="nofollow">fiddle</a>.</p>
<pre><code><a class="fancybox" id="single_image" href="http://fancyapps.com/fancybox/demo/1_b.jpg" title="title"
width="200">
<img src="http://fancyapps.com/fancybox/demo/1_b.jpg" width="300" alt=""></a>
</code></pre>
<p>Jquery</p>
<pre><code>$(document).ready(function() {
$("#single_image").fancybox({
onComplete: function () {
$("#fancybox-img").wrap($("<a />", {
href: this.href, //or your target link
target: "_blank"
}));
}
}).trigger("click");
});
</code></pre>
| <p>Remove the .trigger("click");</p>
<pre><code>$(document).ready(function() {
$("#single_image").fancybox({
onComplete: function () {
$("#fancybox-img").wrap($("<a />", {
href: this.href, //or your target link
target: "_blank"
}));
}
})
});
</code></pre>
<p>Fiddle:
<a href="http://jsfiddle.net/j14gf3sv/4/" rel="nofollow">http://jsfiddle.net/j14gf3sv/4/</a></p>
|
Why do i get an error no match for 'operator^' <p>I am getting an error </p>
<pre><code>10:13: error: no match for 'operator^' (operand types are 'std::basic_ostream<char>' and 'int')
10:13: note: candidates are:
In file included from /usr/include/c++/4.9/ios:42:0,
from /usr/include/c++/4.9/ostream:38,
from /usr/include/c++/4.9/iostream:39,
from 2:
/usr/include/c++/4.9/bits/ios_base.h:161:3: note: std::_Ios_Iostate std::operator^(std::_Ios_Iostate, std::_Ios_Iostate)
operator^(_Ios_Iostate __a, _Ios_Iostate __b)
^
</code></pre>
<p>the code is </p>
<pre><code>// Example program
#include <iostream>
#include <string>
int main()
{
int a=1;
int b=2;
std::cout<<a^b;
}
</code></pre>
<p>What are the operands that can be used with <code>operator ^</code> ?</p>
| <p>According to the <a href="http://en.cppreference.com/w/cpp/language/operator_precedence" rel="nofollow">Operator Precedence</a>, <code>operator<<</code> has higher precedence than <code>operator^</code>. So <code>std::cout<<a^b;</code> is equivalent with <code>(std::cout<<a)^b;</code>; <code>(std::cout<<a)</code> will return <code>std::cout</code> by reference, which is a <code>std::basic_ostream<char></code>; Just as the error message said, you can't call <code>operator^</code> with <code>std::cout</code>(<code>std::basic_ostream<char></code>) and <code>int</code>.</p>
<p>You could use parentheses to specify the precedence how the operands should be bound to operators.</p>
<pre><code>std::cout << (a^b);
// ~ ~
</code></pre>
|
Rails create join table object should not create but update in special case <p>In a webshop I have a booking that needs to know if a booking already exists in the order. I had the whole thing working, but then the details...</p>
<p>...now 'booking on a product' (or in normal English: Adding a product to your shopping-cart) adds a totally new booking on the order list in each case. It oughtn't when this product is already booked once, then it only should alter the quantity. </p>
<p>So easy right? Just one simple if-statement and the whole thing works. </p>
<p><strong>bookings_controller.rb</strong></p>
<pre class="lang-ruby prettyprint-override"><code> def create
@order = current_order
# If product has already been booked
if @order.bookings.where(product_id: params[:product_id]).exists?
# Then: Only alter the quantity in the booking.
@booking = @order.bookings.where(product_id: params[:product_id])
@booking.product_quantity = params[:product_quantity]
else
# Else: Make a new booking.
@booking = @order.bookings.new(booking_params)
@product = @booking.product
@booking.product_name = @product.name
@booking.product_price = @product.price
end
@order.sum_all_bookings
@order.save
end
# ...
def booking_params
params.require(:booking).permit(:product_quantity, :product_id)
end
</code></pre>
<p>Doesn't seem to work. </p>
<p>How do I make the check in the if-statement?
Or should I go about a whole different route to update the booking?</p>
<p><strong>Edit</strong></p>
<p>I've tried various combinations in this shape after gmcnaughton answer. I get either multiple entries still or no entries at all. This one gives me no entries at all.</p>
<p><strong>bookings_controller.rb</strong></p>
<pre class="lang-ruby prettyprint-override"><code> def create
@order = current_order
@booking = @order.bookings.find_or_create_by(product_id: params[:product_id])
product = @booking.product
if @booking.new_record?
@booking.product_name = product.name
@booking.product_price = product.price
else
@booking.product_quantity = params[:product_quantity]
@booking.save
@order.sum_all_bookings
@order.save
end
</code></pre>
<p>Should I also control the booking <code>id</code> maybe? But this makes no sense, because in the case of finding an existing booking it should be there already.</p>
<p>Is it maybe that I am firing the bookings through a <code>remote: true form</code>?</p>
<p><strong>Edit 2</strong></p>
<p>Also not working:</p>
<p><strong>bookings_controller.rb</strong></p>
<pre class="lang-ruby prettyprint-override"><code> def create
@order = current_order
@booking = @order.bookings.where(product_id: params[:product_id]).first_or_initialize
if @booking.new_record?
@booking.product_id = params[:product_id]
product = @booking.product
@booking.product_name = product.name
@booking.product_price = product.price
else
@booking.product_quantity = params[:product_quantity]
@booking.save
@order.sum_all_bookings
@order.save
end
</code></pre>
<p><strong>Edit 3</strong></p>
<p>Maybe this has got something to do with it:</p>
<p><strong>categories_controller.rb / Shop</strong></p>
<pre class="lang-ruby prettyprint-override"><code>def index
@categories = Category.all.order(name: :asc)
# Voor het inzien van wat al geselecteerd is.
@order = current_order
# Voor het aanslaan van een nieuwe booking.
@booking = current_order.bookings.new
end
</code></pre>
<p>Which basically lays out the whole initial shop. The @booking is there to build the form of every product. </p>
<p><strong>Following worked:</strong></p>
<pre class="lang-ruby prettyprint-override"><code> def create
@booking = @order.bookings.find_by(product_id: params[:booking][:product_id])
if @booking
@booking.product_quantity = params[:booking][:product_quantity]
@booking.save
else
@booking = @order.bookings.new(booking_params)
@product = @booking.product
@booking.product_name = @product.name
@booking.product_price = @product.price
end
@order.save
end
</code></pre>
<p>Apparently I needed to grab the params, by adding <code>[:booking]</code> like in <code>params[:booking][:product_id]</code>. Anybody knows why?</p>
| <p>The idea is right, but I think you're missing a call to <code>.first</code>:</p>
<pre><code>@booking = @order.bookings.where(product_id: params[:product_id])
=> #<ActiveRecord::Relation>
</code></pre>
<p>should be:</p>
<pre><code>@booking = @order.bookings.where(product_id: params[:product_id]).first
=> #<Booking>
</code></pre>
<p>...otherwise you're updating the relation and not a <code>Booking</code> model. You probably also want to call <code>@booking.save</code> after you modify it.</p>
<p>Separately, ActiveRecord also has <a href="http://apidock.com/rails/v4.2.7/ActiveRecord/Relation/first_or_initialize" rel="nofollow"><code>first_or_initialize</code></a> and <a href="http://apidock.com/rails/v4.2.7/ActiveRecord/Relation/first_or_create" rel="nofollow"><code>first_or_create</code></a> helpers which let you find a matching instance or build/create a new one:</p>
<pre><code>@booking = @order.bookings.where(product_id: params[:product_id]).first_or_initialize
if @booking.new_record?
@product = @booking.product
...other stuff for new record...
else
@booking.product_quantity = params[:product_quantity]
end
@booking.save
</code></pre>
|
jqGrid Custom Search Template <p>Using jqGrid 5.1.1</p>
<p>I'm attempting to use custom search filer to display in what I "request" in gTmpl, but it doesn't show me anything but default ones.</p>
<p>my gTmpl will always be different based on the GRID for certain data to be pulled, so this is one of few examples:</p>
<pre><code>$.extend($.jgrid.defaults,{
datatype:'json',jsonReader:{repeatitems:false},loadonce:true,jqModal:false,
viewrecords:true,altRows:true,hoverrows:false,hidegrid:false,
rowNum:500,rowList:[100,250,500,1000,2000,3000],autowidth:true,pager:'#InfViewP',
recordtext:'{0}/{2} Rec',emptyrecords:'No Rec Found',loadtext:'Loading...'
});
var gTmpl = {groupOp:'OR',rules:[{'field':'userName','op':'cn','data':''},{'field':'CityName','op':'cn','data':''}]};
$('#InfView').jqGrid({
url:url,
colModel:[
{label:'Player',name:'userName'},
{label:'City',name:'CityName',align:'right',width:350}
]
});
$('#InfView').navGrid('#InfViewP',{edit:false,add:false,del:false},{},{},{},gTmpl,{top:54,left:50,caption:'Search - Overview'});
</code></pre>
<p>I do not want to use tmplNames or tmplFilers (if at all possible). Is there any way around it? Lastly, without gTmpl, the search dialog would be properly located on browser, but when I have gTmpl in, the {top,left,caption...} is ignored and placed at 0,0.</p>
<p>Unless I have the parameters wrong, please do let me know.. Thanks!</p>
| <p>What you probably want to implement is displaying the specified filter on the first opening of the searching dialog. Do do this you should first specify <code>postData.filters</code> and seconds to use <code>multipleSearch:true</code> and optionally <code>multipleGroup:true</code> as the searching option:</p>
<pre><code>var myInitialFilter = {
groupOp:'OR',
rules: [
{'field':'userName','op':'cn','data':''},
{'field':'CityName','op':'cn','data':''}
]
};
$('#InfView').jqGrid({
url:url,
colModel:[
{label:'Player',name:'userName'},
{label:'City',name:'CityName',align:'right',width:350}
],
postData: {
filters: myInitialFilter
}
});
$('#InfView').navGrid('#InfViewP',{edit:false,add:false,del:false},{},{},{},
{multipleSearch:true, top:54, left:50, caption:'Search - Overview'});
</code></pre>
<p>Additionally I would recommend you to consider to use <a href="https://github.com/free-jqgrid/jqGrid" rel="nofollow">free jqGrid</a> instead of commercial Guriddo jqGrid JS (see the current prices <a href="http://guriddo.net/?page_id=103334" rel="nofollow">here</a>). Free jqGrid is the fork of jqGrid, which I develop and which can be used completely free of charge. It's compatible to jqGrid 4.7 (which features you use currently).</p>
<p>Free jqGrid has many new features, which can be helpful in some scenarios. For example, you load the data from the server and use <code>loadonce: true</code> option. It means that the server have to return <em>sorted data</em>. Free jqGrid has new option <code>forceClientSorting: true</code>, which can be used together with <code>loadonce: true</code> option. It force <em>initial sorting on the client side</em>. If you would add <code>search: true</code> option and would specify <code>postData.filter</code>, like in the above example, then the data returned from the server will be filtered and sorted <strong>locally</strong> before the first page of the data will be displayed. The user will be still able to change the filter and to display all the data.</p>
|
Creating datetime for ebay with php <p>I cannot create a valid datetime with php for ebay finding api. </p>
<p>According to their <a href="https://developer.ebay.com/devzone/finding/CallRef/types/simpleTypes.html#dateTime" rel="nofollow">api</a>, the datetime value should look like this</p>
<p>2004-08-04T19:09:02.768Z</p>
<p>I found in the php documentation that there is a special notation for ISO 8601 with <code>(new DateTime())->format('c')</code> but it does not give me the correct date. </p>
<p>Anyone know how to create one?</p>
| <p>Try This:</p>
<pre><code><?php
$time = microtime(true);
$tMicro = sprintf("%03d",($time - floor($time)) * 1000);
$tUtc = gmdate('Y-m-d\TH:i:s.', $time).$tMicro.'Z';
echo $tUtc;
?>
</code></pre>
|
Excel formula required....probably an array <p>Basically we have a table that includes staff who were ineligible for a bonus between certain dates and they might have had overlapping periods when they were ineligible. For our bonus, you can't be penalised twice for the same date. So....</p>
<ul>
<li>I have a table that includes an identifier plus 2 dates on each row. </li>
<li>Each identifier can occur any number of times.</li>
<li>The second date will always be greater than the first date on that row.</li>
<li>The first date on another row that shares the same identifier may or may not be greater than the second date of another row. Confusing but I have tried to make it clear - basically different rows with the same identifier may have dates that overlap, or they might not.</li>
<li>I can't assume that the rows will be in any particular order.</li>
<li>While not ideal, I could probably accept intermediate columns to assist a formula.</li>
</ul>
<p>I want to count all the days between all the dates for each identifier without counting any overlapping dates twice ie how many unique days are there between all the dates per identifier (not per row). I can accept an answer appearing on every row provided that the total can be deduced using a non-array formula eg SUMIF(S) or MATCH/INDEX.</p>
<p>Any suggestions? I thought that SUMPRODUCT might be the direction to go in but can't quite work out why.</p>
| <p>Posting as there are still no replies.. I tried to solve this a few days ago but got stuck on some excel limitations, my basic algorithm was:</p>
<p>for each row use REPT function to create bit string length 366 with 0's and 1's representing days off, bitwise OR this with all other rows with same identifier then just count the 1's. Problem is Excel only lets you do a bitwise OR with up to 15 bit numbers not 366 bit numbers :S</p>
<p>Guessing this is a uni assignment or something and that's why you are constrained to use excel formulas only, you could solve this very easily with some simple VBA code..</p>
|
Separate scrolling columns in a webpage <p>I'm trying to make a website similar to <code>www.the5th.co</code> where they have two independent columns. Both columns are scrollable but independently. How should I approach in developing a design like this? what languages would I need? I am trying to achieve this design in WordPress if that's possible.</p>
<p>Thanks for the help!</p>
| <p>First I think you should get basic information about programming languages for developing webpages and after this ask the question again but more accurate. For inspecting websites to check their design, there are several debugging and monitoring tools like <a href="https://addons.mozilla.org/de/firefox/addon/firebug/" rel="nofollow">FireBug</a> for Firefox. A simple way to do this seperate scrolling is to use simple HTML and CSS. However there are various techniques to implement this. One of them is shown here: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
padding: 0;
margin: 0;
}
#col_container {
position: absolute;
width: 100%;
height: 100%;
}
#col1 {
float: left;
}
#col2 {
overflow: hidden;
}
#col1, #col2 {
width: 50%;
height: 100%;
overflow: auto;
}
.col-content {
position: relative;
height: 2000px;
}
.col-content > div {
width: 60%;
margin: auto;
background-color: rgb(200,200,200);
}
.col-content p {
text-align: center;
margin: 0 auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div id="col_container">
<div id="col1">
<div class="col-content">
<div>
<p>Hallo World!</p>
</div>
</div>
</div>
<div id="col2">
<div class="col-content">
<div>
<p>Hallo World!</p>
</div>
</div>
</div>
</div>
</body></code></pre>
</div>
</div>
</p>
|
What is the practical case of the Immutable.js? <p>I understand the benefits of the immutability in JS. But cannot get any advantages of using a specific library for that.</p>
<p>Thereâs a good âThe case for Immutabilityâ paragraph at libraryâs homepage, but thereâs no clear answer to âThe case for Immutable.jsâ.</p>
<p>I mean to achieve immutability in JS app you should just to keep simple patterns like <code>Object.prototype.assign</code>, <code>Array.prototype.concat</code>, i.e. donât mutate data directly, but returning a new copy not touching the source.</p>
<p>Why should I prefer <code>Immutable.List</code> over the native array, <code>Immutable.Map</code> over the ES6 <code>Map</code> and so on?</p>
<p>Is this a question of self-constrains? If so, should I forget about native data structures in my app and use only Immutable.js alternative?</p>
<p>Is this a kind of overhead to achieve more productivity (in terms of speed and hardware resources)?</p>
<p>Is it an advanced tool to avoid errors and reducing the complexity of app state?</p>
| <blockquote>
<p>I mean to achieve immutability in JS app you should just to keep simple patterns like <code>Object.prototype.assign</code>, <code>Array.prototype.concat</code>, i.e. donât mutate data directly, but returning a new copy not touching the source.</p>
</blockquote>
<p>If it was only that simple. </p>
<h2>Arrays containing arrays being concatenated</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var a = [ [1] ];
var b = [ [2] ];
var c = a.concat(b);
c[0].push(42);
console.log("Array c contains", c);
console.log("Array a contains", a);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.as-console-wrapper { max-height: inherit; }</code></pre>
</div>
</div>
</p>
<h2>Arrays containing objects being concatenated</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var a = [ { name: "Alice" } ];
var b = [ { name: "Bob" } ];
var c = a.concat(b);
c[0].age = 42;
console.log("Array c is", c);
console.log("Array a is", a);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.as-console-wrapper { max-height: inherit; }</code></pre>
</div>
</div>
</p>
<h2>Objects containing arrays and other objects being composed together</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var a = {
name: "Alice"
}
var foods = {
favouriteFoods: [
"noodles",
"pancakes"
]
};
var seasons = {
thoughtsOnSeasons: {
spring: "Beautiful",
summer: "Too hot",
autumn: "Pretty",
winter: "Festive"
}
};
//this object is now entirely new
var alice = Object.assign({}, a, foods, seasons);
//let's manipulate one of the old objects
foods.favouriteFoods.length = 0;
foods.favouriteFoods.push("carrots");
//let's manipulate one of the properties of the new object
alice.thoughtsOnSeasons.spring = "boring";
alice.thoughtsOnSeasons.summer = "boring";
alice.thoughtsOnSeasons.autumn = "boring";
alice.thoughtsOnSeasons.winter = "boring";
//manipulated through the composed object
console.log(seasons);
//manipulated through the previous object
console.log(alice);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.as-console-wrapper { max-height: inherit; }</code></pre>
</div>
</div>
</p>
<p>So, this was actually an incredibly simple example that should tell you that your initial assumption is wrong - it's <em>not</em> a simple pattern. If your thought is "OK, I will just have to write my own functions that perform a deep clone of arrays and objects", then let's have a look at one more thing</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var bobby = { name: "Bobby Tables" };
var map = new Map();
map.set("student", bobby);
bobby.name = "Robert'); DROP TABLE Students; --";
console.log(map.get("student"));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.as-console-wrapper { max-height: inherit; }</code></pre>
</div>
</div>
</p>
<p>If you are still thinking "It's fine, I'll have my own Map clone utility", then you have just realised you need something that clones properties for you.</p>
<p>If your thought is then "I'll use a library that does that" then you've already made a point for Immutable.js.</p>
<p>But that hasn't even touched immutability yet, which is the main thing Immutable.js offers, not just a fancy cloning utilty. Fact is, that often you don't want or don't expect consuming code to manipulate your returns. You could be returning arrays containing arrays or objects containing objects and that's fine, but as you've seen, any change to <em>them</em> could result in a change to referenced data. Changes to results could also be undesirable otherwise, and it's as simple as a typo for that to happen. If you explicitly do not want results to be manipulated, then you can return an immutable view of it. In many ways, this is similar to just you making sure to make a deep clone when you receive data, but it just enforces that behaviour, making you aware if you haven't.</p>
<p>So, let me try to answer your questions in reverse order</p>
<blockquote>
<p>Is it an advanced tool to avoid errors and reducing the complexity of app state?</p>
</blockquote>
<p>Yes, you can use it to avoid problems and complexity. That is the main problem you are facing with shared mutable data, really - errors that stem from something unexpectedly modifying the data and complexity from having to account for it.</p>
<blockquote>
<p>Is this a kind of overhead to achieve more productivity (in terms of speed and hardware resources)?</p>
</blockquote>
<p>In terms of speed and hardware resources - hardly. There may be <em>some</em>, but I don't actually have any data on the performance of Immutable.js, however, I do know that immutable data structures can be more memory efficient in some ways, due to structural sharing. An immutable list can be appended to and you get a "new" list back, however, internally, the beginning of the list is shared between the instances, so you avoid some GC overhead. On the other hand, some other operations may take more CPU time with immutable data structures, for example, changing data on specific index. However, overall, I would not be too worried about performance.</p>
<p>What you gain most benefit in, is in terms of developer time and maintainability. </p>
<blockquote>
<p>Is this a question of self-constrains? If so, should I forget about native data structures in my app and use only Immutable.js alternative?</p>
</blockquote>
<p><em>Should</em> you? That's a whole different question altogether. You don't have to and you may not even need to. It depends on what project you are working on and how. It's entirely possible to work with Immutable.js in a small project and reap many benefits. It's entirely possible to work on a large project without Immutable.js and not suffer for it. In some ways, it's a personal choice. I'd say it's definitely useful to use immutability, so you get first hand experience with it. Whether you need to use it everywhere or not, cannot really be answered easily, but you will gain the means to assess that yourself.</p>
|
Replace string at a given position with PowerShell <p>I have a folder where stand 4000 csv files right now in production with a running incident.</p>
<p>With PowerShell I would like to replace:</p>
<pre><code>In all files => OK
In all lines => OK
</code></pre>
<p>All string from position start 9 to position end 18 without any consideration about current string content. I guess just a question of right regular expression to use but not able to.</p>
<pre><code>-replace 'WhatToUse','MyNewString'
</code></pre>
<p>Example: (All files contain different strings, 08.10.2016 is not a fixed string)</p>
<pre><code>3162498;08.10.2016;30.10.2016;CHN;
</code></pre>
<p>Would become</p>
<pre><code>3162498;MyNewString;30.10.2016;CHN;
</code></pre>
| <p>try this (verify if its ok)</p>
<pre><code> $pathwithfiles= "C:\temp"
$stringtosearh="toto"
$stringtoreplace="titi"
$delimitercsv=";"
$listfil=gci -Path $pathwithfiles -Recurse -File -Filter "*.csv"
foreach ($currentfile in $listfil)
{
$contentfile=get-content $currentfile.FullName
[string[]]$contentfileres=@()
$numline=0
foreach ($row in $contentfile)
{
$numline++
if ($numline -eq 1)
{
$contentfileres+=$row
continue
}
else
{
[string[]] $linearray=$row -split $delimitercsv
[string[]] $linearrayres=@()
for ($i = 0; $i -lt $linearray.Count; $i++)
{
if ($i -ge 9 -and $i -le 18)
{
$linearrayres+=$linearray[$i].Replace($stringtosearh, $stringtoreplace)
}
else
{
$linearrayres+=$linearray[$i]
}
}
$contentfileres+=($linearrayres -join $delimitercsv)
}
}
$contentfileres | out-file ($currentfile.FullName )
Write-Host "File $currentfile.FullName replaced"
}
</code></pre>
|
ReactJS: Returning a React Component in a loop <p>I'm trying to loop through an array and return a React Component on each element. The render functions are being called but nothing is showing up. </p>
<pre><code>class ListOfFoundPages extends Component {
constructor(props) {
super(props);
this._renderList = this._renderList.bind(this);
}
_renderList(data) {
if (data !== null) {
// eslint-disable-next-line
data.list.map( (obj) => {
return <ListItem obj={obj} />;
});
}
}
render() {
return (
<ul className="listOfFoundPages">
{this._renderList(this.props.list)}
</ul>
);
}
}
</code></pre>
<p>And this is the Component to be returned:</p>
<pre><code>const ListItem = (props) => {
return (
<li>
<div className="foundPagesItem">
<img role="presentation" className="searchPageImg" src={props.obj.picture.data.url} />
<span className="searchPageInfo">{props.obj.name} - {props.obj.category}</span>
</div>
<div className="seperator" />
</li>
);
};
export default ListItem;
</code></pre>
| <p><code>_renderList</code> function should return an array of components (the result of <code>data.list.map...</code>). Currently, it doesn't return anything. The code needs to look like:</p>
<pre><code>_renderList(data) {
if (data !== null) {
// eslint-disable-next-line
return data.list.map( (obj) => {
return <ListItem obj={obj} />;
});
}
}
</code></pre>
|
Why am I forced to use !! in a combination of null checks? <p>For this piece of code, Kotlin forces me to handle a null-check situation while on the other line it doesn't, despite being the same situation:</p>
<pre><code>if (r1 == null && r2 == null)
throw IllegalArgumentException("All nulls!")
else if (r1 == null)
return r2!!.reading // <----- I am forced to !! here
else if (r2 == null)
return r1.reading // <----- The compiler does not complain in this line
</code></pre>
<p>Is this a bug or a feature?</p>
| <p>The Kotlin compiler does not make logical inferences in the way you expect: "I have already checked that r1 == null and r2 == null, so now if I'm only checking for r1 == null, then it must recognize that r2 is not null". It doesn't. You haven't checked r2 in that branch, so it doesn't see that it is not null.</p>
<p>In the second case the situation is simpler: <code>if (r1 == null) { ... } else { ... }</code>. It doesn't matter that you have another check inside the <code>else</code>; the compiler sees that you're in the <code>else</code> branch of an <code>if (x == null)</code> check and understands that the value is not null.</p>
<p>There is an <a href="https://youtrack.jetbrains.com/issue/KT-10461">open feature request</a> for adding this kind of logic, however, it's not on the near term roadmap of the Kotlin team.</p>
|
MongoDB split data in more Collection <p>I have one collection (CollectionA) .
in this collection there are data of more experiment.</p>
<p>I want create one collection for each experiment:
Collection1, Collection2 ...</p>
<p>There is a mode? without losing data?</p>
<p>ps. I can interfacing MongoDB with php</p>
<hr>
<p>Add information:</p>
<p>I have a Collection with MANY MANY data of experiment (experimentA,ExperimentB,...).</p>
<p>I want split this collection in more collection one for each Experiment.</p>
<p>(a kind of partition)</p>
<hr>
<pre><code>Collection NAME = testCollection
</code></pre>
<p>in this Collection there is "experiment" field
(ex. ExperimentA , ExperimentB , ...)</p>
<p>COLLECTION OUTPUT REQUIRED : </p>
<pre><code>testCollection_ExperimentA
testCollection_ExperimentB
</code></pre>
<p>Need more information? </p>
| <p>MongoDB enables easy to use <strong>Split</strong> method.</p>
<p>While running the following command:</p>
<pre><code>db.runCommand( { split : "db.collectionName", find : { 'experimentName' : "A" } } )
</code></pre>
<p>The split command identifies the chunk in the db.collectionName. Then the command splits it into two chunks.
You can do it as many times as you need.</p>
<p>You can read the full documentation <a href="https://docs.mongodb.com/manual/reference/command/split/" rel="nofollow">here</a>.</p>
|
jtable won't update while the program is running <p><strong>okay i already posted this but i delete it because no one is answering for 24 hours already</strong></p>
<p>i don't really know what to do anymore. i have so many tables in my system and they all have the same codes but this is the only on that doesn't work. my problem is that every time i add candidate/data to the jtable, it won't appear. it will only appear if i terminate the program then run it again. here is my codes:</p>
<p><strong>This is the class that contains storing to file and jtable methods</strong></p>
<pre><code> public class DatabaseForCandidates {
String pres;
int resPres;
static Vector rowsPres;
static String [] columnPres={"PRESIDENTIAL CANDIDATES", "CURRENT NUMBER OF VOTES", ""};
static File filePres;
static FileWriter fileWrite;
static FileReader fileRead;
static Scanner read;
public DatabaseForCandidates() {
filePres=new File("President.txt");
fileWrite=null;
fileRead=null;
read=null;
}
public void setColumns(){
PresidentTable.tblModel=new DefaultTableModel();
PresidentTable.tblModel.setColumnIdentifiers(columnPres);
PresidentTable.tblNatPresident=new JTable(PresidentTable.tblModel);
}
public void storePresidentRecords(){
try {
fileWrite=new FileWriter(filePres,true);
getDataPres();
storeToTable();
//storing to a file
fileWrite.write("**"+pres+"**"); fileWrite.write(resPres+"**");
fileWrite.write("\r\n");
fileWrite.close();
JOptionPane.showMessageDialog(null, "Candidate is now nominated for President");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error: "+e.getMessage());
}
}
public void getDataPres(){
String linePres="";
try {
fileRead=new FileReader(Database.fileNew);
read=new Scanner(fileRead);
while(read.hasNext()){
linePres+=read.nextLine()+"\n";
}
read.close();
String [] infoPres=linePres.split("/");
pres=infoPres[4]+" "+infoPres[3];
resPres=0;
}catch(Exception e){}
}
public void storeToTable(){
rowsPres=new Vector();
rowsPres.add(pres); rowsPres.add(resPres);
PresidentTable.tblModel.addRow(rowsPres);
}
public void retrievePresidentRecords(){
String holdStr="";
try {
fileRead=new FileReader(filePres);
read=new Scanner(fileRead);
while(read.hasNext()){
holdStr+=read.nextLine()+"\n";
}
read.close();
StringTokenizer strToken=new StringTokenizer(holdStr, "**");
while(strToken.hasMoreElements()){
rowsPres=new Vector();
for(int i=0; i<columnPres.length; i++){
rowsPres.add(strToken.nextElement());
}
PresidentTable.tblModel.addRow(rowsPres);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p><strong>this is the class of jtable</strong></p>
<pre><code>public class PresidentTable extends JPanel{
static JTable tblNatPresident;
static DefaultTableModel tblModel;
DatabaseForCandidates data;
PresidentTable(){
setName("panelNatPres");
data=new DatabaseForCandidates();
data.setColumns();
data.retrievePresidentRecords();
PresidentTable.tblNatPresident=new JTable(PresidentTable.tblModel);
add(new JScrollPane(PresidentTable.tblNatPresident));
}
}
</code></pre>
<p><strong>this is the listener of the button if you will add candidate or not</strong></p>
<pre><code>if(e.getSource().equals(PresidentPanel.btnPresAdd)){
DatabaseForCandidates data=new DatabaseForCandidates();
boolean found=false;
try {
String add=PresidentPanel.txtVNum.getText();
String vnum=null;
for (int row=0; (row<ViewTablePanel.tblModel.getRowCount()) && (!found);row++) {
vnum=ViewTablePanel.tblModel.getValueAt(row, 1).toString();
if(vnum.equals(add)){
found=true;
data.storePresidentRecords();
}
}
if(!found){
JOptionPane.showMessageDialog(null, add+" is not found.");
}
} catch (Exception e1) {}
}
</code></pre>
<p>just ask me if you don't understand my code and if you have any clarification. please help thank you so much :)</p>
| <p>Without you posting the whole code it's hard to debug. However a few things that could be wrong come to mind:</p>
<ol>
<li><strong>You don't notify the JTable that the data has changed by calling:</strong> <code>.fireTableDataChanged()</code></li>
<li><strong>You don't update the frame with:</strong> <code>.repaint();</code> <strong>and</strong> <code>.revalidate();</code></li>
<li><strong>You update your file, but do not read the file updates or otherwise update the change to your JTable.</strong></li>
</ol>
|
Pointer conversion in c <p>I have the following lines: </p>
<pre><code>char *name = malloc(strsize + 1);
</code></pre>
<p>and </p>
<pre><code>uint8_t *data;
data = (uint8_t *)name;
</code></pre>
<p>It is correct? It doesn't exist a chance that the pointer *name will be interpreted bad when that conversion is done?</p>
| <p>That shouldn't be much of a problem, except that the <em>signedness</em> of the memory would be interpreted differently between access along <code>data</code> and <code>name</code>. In most of the practical platforms, the size of <code>char</code> and <code>uint8_t</code> in bits is the same.</p>
|
get last 10 items in dynamodb cross partions <p>I've a table containning blogs posted by different persons;primary key is author+time;
<strong>how to query last 4 blogs ordered by time?</strong>(get blog6,blog3,blog5,blog4)</p>
<p><a href="http://i.stack.imgur.com/quS1u.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/quS1u.jpg" alt="enter image description here"></a></p>
<p>If i create a global secondary index(i.e.:i create a new attribute calling status,setting all values to "ok"),set status+time as primary key</p>
<p><a href="http://i.stack.imgur.com/bhqe6.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/bhqe6.jpg" alt="enter image description here"></a>
i know i can resolve my question.But the result is:<strong>all data in index will be stored in only one partion</strong></p>
<p>will it casuse any weaknessï¼</p>
| <p>Adding a sparse index (for example, status) is similar to creating another table with only the recent blog posts. Make sure that you are using the Sparse functionality (<a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForGSI.html#GuidelinesForGSI.SparseIndexes" rel="nofollow">https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForGSI.html#GuidelinesForGSI.SparseIndexes</a>) that most of the blog posts will have 'null' as the value of this column. This way your index is going to be small and these lookups should be efficient. </p>
<p>One way to maintain the small size of this index is to set the "older" records status to 'null', either do it every day (using a scheduled Lambda function) or for every new insert to the table (again using a Lambda function that is listening to the Updates stream of the table).</p>
<p>The recommendation to use a cache for these frequent lookups (every view to your web site needs it), it a good one. If you have a high hit rate, you should cache it, like any other repeating query. </p>
|
Whats the best way to send XML data to Kafka topic? <p>I am trying to send a <code>XML data</code> to <code>Kafka topic</code> using <code>Kafka 0.9.0 version</code> Java API, because from <code>0.9.0 version</code> they are suggesting to use Java API instead Scala API to get better performance.</p>
<p><a href="http://kafka.apache.org/090/documentation.html#producerapi" rel="nofollow">http://kafka.apache.org/090/documentation.html#producerapi</a></p>
<p>My XML File has around <code>5 MB data</code>, what is the XML API i can use to read XML file and convert as String and then send that String to Kafka Topic.</p>
<p>Or can i convert that XML as <code>JSON</code> data and send it to Kafka? also should i consider splitting my XML data to multiple small amount of data and send to Kafka Topic?</p>
| <p>The API to read/write XML is up to the programmer/environment. Further, Apache Kafka does not enforce any particular format for event data beyond a simple key/value model. It will work equally well with XML, JSON,Avro or any other data format. It's recommended that any format, be it XML, JSON, provided it should be used in a consistent manner. if you are starting a new project with Kafka, there are things to consider like performance, ease of use, programming language support etc before selecting and use the correct serialise format etc. Avro is one of the most successful format for stream data.</p>
|
Angular2 template field issue <p>I am getting spacing issue with the template field in Angular2</p>
<p>This is my code. </p>
<pre><code>@Component({
selector: 'my-component',
template: ' <h1 class="test">
Angular 2 Template
</h1>',
styleUrls: ['./assets/style.css']
})
</code></pre>
<p>This does not work</p>
<pre><code>@Component({
selector: 'my-component',
template: ' <h1 class="test">Angular 2 Template</h1>',
styleUrls: ['./assets/style.css']
})
</code></pre>
<p>This works</p>
| <p>That's because you should use the ES6 backtick "`" for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals" rel="nofollow">template literals</a>:</p>
<pre><code>Component({
selector: 'my-component',
template: ` <h1 class="test">
Angular 2 Template
</h1>`,
styleUrls: ['./assets/style.css']
})
</code></pre>
|
On route change view doesn't scroll to top in the new page in angular2 <p>I have tried <code>autoscroll="false"</code> on the <code>router-outlet</code> but does't seem to work, is there any default method
of angular2 for doing the same without using any third party library? </p>
| <p>Yes, you can refer to <strong><a href="https://angular.io/docs/ts/latest/guide/router.html#!#fragment" rel="nofollow">fragments</a></strong> available in <strong>Angular2-router</strong>.</p>
|
How to determine gzfile size OR reading it raw in R? <p>Following <a href="http://stackoverflow.com/a/9069670/6817726">this</a> answer for reading a whole file, I need to determine the uncompressed file size of a gzfile.
It's saved at the last 4 bytes of the gzfile, but I couldn't find how to open the file without r will wrap it with an uncompressing layer, so I have no access to the raw gz file. I haven't found a method that provides this information as well.</p>
| <p>Provided you are sure this is a complete gzip'd file with a single stream and <2GB uncompressed:</p>
<pre><code>gz_size <- function(path) {
path <- path.expand(path)
f <- file(path, open="rb", raw=TRUE)
seek(f, -4L, "end", "read")
ret <- readBin(f, "integer", 1)
close(f)
return(ret)
}
</code></pre>
|
URL dwell time in any programming language? <p>Could you please give me some hints, websites, books or research papers that would explain how to calculate the URL dwell time.</p>
<p>in case you don't know what is dwell time : dwell time denotes the time which a user spends viewing a document after clicking a link on a search engine results page.</p>
<p>Thanks in advance</p>
| <p>One crude way to do this on a page would be to use a small GET request on a timer, going to a server - an "I'm still here". The frequency of this would be a trade off. This would be relatively easy to do with jquery or a similar framework.</p>
<p>You would not know if it is actually in an abandoned tab or that it is open but not actually being looked at.</p>
<p>A sample for the client end (using jquery):</p>
<pre><code>$session = Math.floor((1 + Math.random()) * 0x10000);
function still_alive() {
$url = $server_url + "/still_alive";
$.get($url, {location: location.href, session: $session});
}
// call it once to prime it
still_alive();
// Set it up on a timer
window.setTimeout(function() {
still_alive();
}, 1000);
</code></pre>
<p>1000 is the interval in milliseconds - so this is on a 1 second interval. $server_url is the server to register this at - I am adding "/still_alive" as an endpoint to register this at. $session - this can be some way of identifying the current session - set to something once when the page loads - it could be the result of a uuid function.</p>
<p>The next line is a Jquery GET request to that whole url. It is being passed a plain object - with the key location holding the url of the current location. It may be more appropriate to be a POST instead of a GET - but the principle is still the same.</p>
|
lua corona widget.newScrollView verticalScrollDisabled doesn't work <p>I have created a ScrollView with this code:</p>
<pre><code>local function BuildScrollView( )
scrollView = widget.newScrollView(
{
top = 0,
left = 0,
width = display.actualContentWidth,
height = display.actualContentHeight,
scrollWidth = 0,
scrollHeight = 0,
backgroundColor = { 0, 0, 0, 0.5},
verticalScrollDisabled=true;
})
end
</code></pre>
<p>this works fine :)</p>
<p>then upon a click I use this:</p>
<pre><code>scrollView:setIsLocked( true )
</code></pre>
<p>Then later I want to unlock the ScrollView with this code:</p>
<pre><code>function ResetPlanetTaps()
scrollView.verticalScrollDisabled=true;
scrollView:setIsLocked( false );
end
</code></pre>
<p>But the ScrollView still scrolls vertically.
How do i stop the vertical scrolling?</p>
<p>Cheers :)</p>
| <p>For this you should specify as a second parameter what axis you want to lock:</p>
<pre><code>scrollView:setIsLocked(true, "vertical")
</code></pre>
<p>The second parameter, <em>axis</em>, as stated from the docs:</p>
<blockquote>
<p>Directional axis upon which to lock or unlock the scroll view, either "horizontal" or "vertical".</p>
</blockquote>
<p>You can see scrollView <code>setIsLocked</code> <a href="https://docs.coronalabs.com/api/type/ScrollViewWidget/setIsLocked.html" rel="nofollow">documentation here</a>, and the open source code and relevant line <a href="https://github.com/coronalabs/framework-widget/blob/master/widgetLibrary/widget_scrollview.lua#L623" rel="nofollow">here on github</a>. </p>
|
Swift - UINavigationBar only sometimes included in screen height? <p>So I'm experiencing a bit of an odd (in my opinion) issue. I have a standard UINavigationController with a root UIViewController. </p>
<p>I'm adding a UITableView programatically to the view controller. When I set the frame of the table view, I set it as: </p>
<pre><code>tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
</code></pre>
<p>When I run the simulator, sometimes the tableview is positioned perfectly - sitting just under the navigation bar. However, sometimes (seemingly at random) the tableview is positioned at the top of the screen, beneath the navigation bar.</p>
<p>I've tried to change the Y coordinate of the tableview to be </p>
<pre><code>(self.navigationController?.navigationBar.frame.height)!
</code></pre>
<p>But now the reverse happens: sometimes the tableview is positioned correctly, but sometimes a navigation bar sized gap appears under the navigation bar, above the tableview.</p>
<p>I'm pretty lost as to what's happening - perhaps it's something to do with when the navigation bar is created?</p>
<p>Thanks in advance.</p>
| <p>Try the following code...tested in Xcode 8 it worked....You mentioned about a gap appears under the navBar.Because, you didn't put the statusBar height in your code.</p>
<pre><code> override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
yourTableView.frame = CGRect(x: 0, y: -(UINavigationController().navigationBar.frame.height + UIApplication.shared.statusBarFrame.size.height), width: view.frame.width, height: view.frame.height + (UINavigationController().navigationBar.frame.height + UIApplication.shared.statusBarFrame.size.height))
print((UINavigationController().navigationBar.frame.height)) // 44.0
print(UIApplication.shared.statusBarFrame.size.height) // 20.0
//You can include this code in viewDidAppears.if your view has a transition...
}
</code></pre>
<p>Above code will position your tableview just below navigationBar.Hope this helps...</p>
|
JSON sub for loop produces KeyError, but key exists <p>I'm trying to add the JSON output below into a dictionary, to be saved into a SQL database.</p>
<pre><code>{'Parkirisca': [
{
'ID_Parkirisca': 2,
'zasedenost': {
'Cas': '2016-10-08 13:17:00',
'Cas_timestamp': 1475925420,
'ID_ParkiriscaNC': 9,
'P_kratkotrajniki': 350
}
}
]}
</code></pre>
<p>I am currently using the following code to add the value to a dictionary:</p>
<pre><code>import scraperwiki
import json
import requests
import datetime
import time
from pprint import pprint
html = requests.get("http://opendata.si/promet/parkirisca/lpt/")
data = json.loads(html.text)
for carpark in data['Parkirisca']:
zas = carpark['zasedenost']
free_spaces = zas.get('P_kratkotrajniki')
last_updated = zas.get('Cas_timestamp')
parking_type = carpark.get('ID_Parkirisca')
if parking_type == "Avtomatizirano":
is_automatic = "Yes"
else:
is_automatic = "No"
scraped = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
savetodb = {
'scraped': scraped,
'id': carpark.get("ID_Parkirisca"),
'total_spaces': carpark.get("St_mest"),
'free_spaces': free_spaces,
'last_updated': last_updated,
'is_automatic': is_automatic,
'lon': carpark.get("KoordinataX_wgs"),
'lat': carpark.get("KoordinataY_wgs")
}
unique_keys = ['id']
pprint savetodb
</code></pre>
<p>However when I run this, it gets stuck at <code>for zas in carpark["zasedenost"]</code> and outputs the following error:</p>
<pre><code>Traceback (most recent call last):
File "./code/scraper", line 17, in <module>
for zas in carpark["zasedenost"]:
KeyError: 'zasedenost'
</code></pre>
<p>I've been led to believe that <code>zas</code> is in fact now a string, rather than a dictionary, but I'm new to Python and JSON, so don't know what to search for to get a solution. I've also searched here on Stack Overflow for <code>KeyErrror when key exist</code> questions, but they didn't help, and I believe that this might be due to the fact that's a sub for loop.</p>
<p>Update: Now, when I swapped the double quotes for single quotes, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "./code/scraper", line 17, in <module>
free_spaces = zas.get('P_kratkotrajniki')
AttributeError: 'unicode' object has no attribute 'get'
</code></pre>
| <p>I fixed up your code:</p>
<ol>
<li>Added required imports.</li>
<li>Fixed the <code>pprint savetodb</code> line which isn't valid Python.</li>
<li>Didn't try to iterate over <code>carpark['zasedenost']</code>.</li>
</ol>
<p>I then added another <code>pprint</code> statement in the <code>for</code> loop to see what's in <code>carpark</code> when the <code>KeyError</code> occurs. From there, the error is clear. (Not all the elements in the array in your JSON contain the <code>'zasedenost'</code> key.)</p>
<p>Here's the code I used:</p>
<pre><code>import datetime
import json
from pprint import pprint
import time
import requests
html = requests.get("http://opendata.si/promet/parkirisca/lpt/")
data = json.loads(html.text)
for carpark in data['Parkirisca']:
pprint(carpark)
zas = carpark['zasedenost']
free_spaces = zas.get('P_kratkotrajniki')
last_updated = zas.get('Cas_timestamp')
parking_type = carpark.get('ID_Parkirisca')
if parking_type == "Avtomatizirano":
is_automatic = "Yes"
else:
is_automatic = "No"
scraped = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
savetodb = {
'scraped': scraped,
'id': carpark.get("ID_Parkirisca"),
'total_spaces': carpark.get("St_mest"),
'free_spaces': free_spaces,
'last_updated': last_updated,
'is_automatic': is_automatic,
'lon': carpark.get("KoordinataX_wgs"),
'lat': carpark.get("KoordinataY_wgs")
}
unique_keys = ['id']
pprint(savetodb)
</code></pre>
<p>And here's the output on the iteration where the <code>KeyError</code> occurs:</p>
<pre><code>{u'A_St_Mest': None,
u'Cena_dan_Eur': None,
u'Cena_mesecna_Eur': None,
u'Cena_splosno': None,
u'Cena_ura_Eur': None,
u'ID_Parkirisca': 7,
u'ID_ParkiriscaNC': 72,
u'Ime': u'P+R Studenec',
u'Invalidi_St_mest': 9,
u'KoordinataX': 466947,
u'KoordinataX_wgs': 14.567929171694901,
u'KoordinataY': 101247,
u'KoordinataY_wgs': 46.05457609543313,
u'Opis': u'2,40 \u20ac /dan',
u'St_mest': 187,
u'Tip_parkirisca': None,
u'U_delovnik': u'24 ur (ponedeljek - petek)',
u'U_sobota': None,
u'U_splosno': None,
u'Upravljalec': u'JP LPT d.o.o.'}
Traceback (most recent call last):
File "test.py", line 14, in <module>
zas = carpark['zasedenost']
KeyError: 'zasedenost'
</code></pre>
<p>As you can see, the error is quite accurate. There's no key <code>'zasedenost'</code> in the dictionary. If you look through your JSON, you'll see that's true for a number of the elements in that array.</p>
<p>I'd suggest a fix, but I don't know what you want to do in the case where this dictionary key is absent. Perhaps you want something like this:</p>
<pre><code>zas = carpark.get('zasedenost')
if zas is not None:
free_spaces = zas.get('P_kratkotrajniki')
last_updated = zas.get('Cas_timestamp')
else:
free_spaces = None
last_updated = None
</code></pre>
|
PHP calling another PHP page for MySQL Query (returning JSON data) <p>I would like to find out how a PHP page calls another PHP page, which will return JSON data. </p>
<p>I am working with PHP (UsersView.php) files to display my contents of a website. However, I have separated the MySQL Queries in another PHP (Get_Users.php) file. </p>
<p>In the Get_Users.php, I will have a MySQL statement to query the database for data. It will then encode in JSON and be echo-ed out. </p>
<p>In the UsersView.php, I will call the Get_Users.php in order to retrieve the Users JSON data. The data will then be used to populate a "Users Table".</p>
<p>The thing is, I do not know how to call the "Get_Users.php" from the "UsersView.php" in order to get the data. </p>
<p><strong>Part of UserView.php</strong></p>
<pre><code>$url = "get_user.php?id=" . $id;
$json = file_get_contents($url);
$result = json_decode($json, true);
</code></pre>
<p>I am trying to call the file which is in the same directory, but this does not seem to work. </p>
<p><strong>Whole of Get_Users.php</strong></p>
<pre><code><?php
$connection = mysqli_connect("localhost", "root", "", "bluesky");
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}
$valid = true;
if (!isset($_GET['id'])) {
$valid = false;
$arr=array('success'=>0,'message'=>"No User ID!");
echo json_encode($arr);
}
$id = $_GET['id'];
if($valid == true){
$query = "SELECT * FROM user WHERE id = '$id'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Invalid User ID!");
echo json_encode($arr);
}
}
mysqli_close($connection);
?>
</code></pre>
| <p>You have a couple of different ways to accomplish this:</p>
<ul>
<li>You should be able to first set the actual <code>id</code> and then include the <code>Get_Users.php</code> file like this. Notice that you should <strong>not</strong> echo out the output from <code>Get_Users.php</code>, instead only return the encoded json data using <code>return json_encode($arr);</code>:</li>
</ul>
<hr>
<pre><code>// set the id in $_GET super global
$_GET['id'] = 1;
// include the file and catch the response
$result = include_once('Get_Users.php');
</code></pre>
<ul>
<li>You can also create a function that can be called from <code>UserView.php</code>:</li>
</ul>
<hr>
<pre><code>// Get_Users.php
<?php
function get_user($id) {
// connect to and query database here
// then return the result as json
return json_encode($arr);
}
?>
// In UserView.php you first include the above file and call the function
include_once('Get_Users.php');
$result = get_user(1);
</code></pre>
<ul>
<li>You could also use <code>file_get_contents()</code>. Notice that you need to make sure so that <code>allow_url_fopen</code> is enabled in your <code>php.ini</code> file for this to work:</li>
</ul>
<hr>
<pre><code>$result = file_get_contents('http://example.com/Get_Users.php?id=1');
</code></pre>
<p>To enable <code>allow_url_fopen</code> you need to open up your loaded configuration file and set <code>allow_url_fopen=1</code> and finally restart your webserver.</p>
<hr>
<ul>
<li>You could also use curl to achieve the same result:</li>
</ul>
<hr>
<pre><code>$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/Get_Users.php?id=1');
$result = curl_exec($ch);
curl_close($ch);
</code></pre>
<hr>
<ul>
<li>An ajax request could also be made to get the result. This example uses jQuery:</li>
</ul>
<hr>
<pre><code>$(document).ready(function() {
$.get({
url: 'Get_Users.php',
data: 'id=1',
success: function(response) {
// response contains your json encoded data
// in this case you **must** use echo to transfer the data from `Get_Users.php`
}
});
});
</code></pre>
|
SQL Server : string to rows with delimiter? <p>In SQL Server 2016 there is a function called <code>STRING_SPLIT</code> (Transact-SQL).</p>
<p>Answer to my question would work fine with this function.</p>
<p>Unfortunately we only have SQL Server 2012. </p>
<pre><code>SELECT
email,
[Special ftg],
[Special OrgCode],
[Special SalaryCode]
FROM
Employee
</code></pre>
<p>How can I get this?</p>
<p><a href="http://i.stack.imgur.com/62Uge.png" rel="nofollow"><img src="http://i.stack.imgur.com/62Uge.png" alt="enter image description here"></a></p>
<pre><code>email Special ftg Special OrgCode Special SalaryCode
-----------------------------------------------------------------------------------------
test@gmail.com 4;200;210;220;250;275;1100;1101;1102 14000000000 1
</code></pre>
<p>into this:</p>
<p><a href="http://i.stack.imgur.com/WLfxK.png" rel="nofollow"><img src="http://i.stack.imgur.com/WLfxK.png" alt="enter image description here"></a></p>
<p>The delimiter is semicolon and it should be that for all columns.</p>
| <p>You can convert <code>[Special ftg]</code> into XML ant then use OUTER APPLY:</p>
<pre><code>;WITH cte AS (
SELECT email,
CAST('<p>'+REPLACE([Special ftg],';','</p><p>')+'</p>'as xml) as [Special ftg],
[Special OrgCode],
[Special SalaryCode]
FROM Employee
)
SELECT c.email,
t.c.value('.','int') [Special ftg],
NULL [Special OrgCode],
NULL [Special SalaryCode]
FROM cte c
OUTER APPLY [Special ftg].nodes('/p') as t(c)
UNION ALL
SELECT c.email,
NULL,
c.[Special OrgCode],
NULL
FROM cte c
UNION ALL
SELECT c.email,
NULL,
NULL,
c.[Special SalaryCode]
FROM cte c
ORDER BY email,[Special SalaryCode],[Special OrgCode],[Special ftg]
</code></pre>
<p>Output:</p>
<pre><code>email Special ftg Special OrgCode Special SalaryCode
test@gmail.com 4 NULL NULL
test@gmail.com 200 NULL NULL
test@gmail.com 210 NULL NULL
test@gmail.com 220 NULL NULL
test@gmail.com 250 NULL NULL
test@gmail.com 275 NULL NULL
test@gmail.com 1100 NULL NULL
test@gmail.com 1101 NULL NULL
test@gmail.com 1102 NULL NULL
test@gmail.com NULL 14000000000 NULL
test@gmail.com NULL NULL 1
</code></pre>
|
Safe way to know if user is logged in client side with Django <p>My website project shows user specific data in almost every page (e.g. show username in topbar if logged which is existent in all pages), show liked items, etc...</p>
<p>I use AJAX to get html fragments depending if the user is authenticated or not (e.g. show username in topbar if authenticated, otherwise signup/login buttons).</p>
<p>My question is, the above method causes me to invoke AJAX GET request in almost all pages and subsequently at least doubles the HTTP requests & the server load, is it safe to add some cookie <code>logged_in: true</code> and check it so I invoke the AJAX GET request ONLY IF the user is logged in.</p>
<p>The convention in Django and modern webdev is to add only the session id in the cookies and everything is in the server side, is there a safe way to know if the user is logged in client side?</p>
| <p>In your template, use <code>is_authenticated</code> to conditionally make the ajax requests. </p>
<pre><code>{% if request.user.is_authenticated %}
<!-- make the ajax requests -->
{% endif %}
</code></pre>
|
Getting erorr on login with angular 2 google and firebase <p>I am using firebase 3 and ng 2.
My issue I am getting erorr when click on connect with google account.
My error is:</p>
<pre><code>Error: redirect_uri_mismatch
400. Thatâs an error.
Error: redirect_uri_mismatch
Application: Events Manager
You can email the developer of this application at: .....@gmail.com
The redirect URI in the request, https://......firebaseapp.com/__/auth/handler, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/......apps.googleusercontent.com?project=181586 to update the authorized redirect URIs.
</code></pre>
<p>my project runs on <a href="http://localhost:3000/#/login" rel="nofollow">http://localhost:3000/#/login</a></p>
<p>when I am going to console.developers.google.com Authorized redirect URIs-> <a href="http://localhost:3000/" rel="nofollow">http://localhost:3000/</a></p>
<p>Any idea whey is it happens?</p>
| <p>the issue was need to add to firebase auth link the correct host.</p>
<p>firebase-> OAuth redirect domains</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.