title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
WooCommerce third-party gateway isn't working on order-pay page
|
<p>I have a third-party payment gateway which works fine on the Checkout page. When the user clicks the Pay button, it actually returns a Javascript command as the redirect, which then opens up a modal iframe to my payment gateway, like so:</p>
<pre><code>public function process_payment( $order_id ): array {
include_once dirname( __FILE__ ) . '/includes/flywire-payment-gateway-request.php';
$FW_request = new WC_Gateway_Flywire_Request( $this, $order_id );
try {
$config= $FW_request->get_config();
} catch ( Exception $e ) {
wc_add_notice( $e->getMessage(), 'error' );
return array(
'result' => 'failure',
'redirect' => ''
);
}
// TODO: add optional call to Google Tag action
$return_array = array(
'result' => 'success',
'redirect' => 'javascript:window.flywire.WooCommerce.show(' . json_encode($config) . ')'
);
$logger = wc_get_logger();
$context = array( 'source' => 'flywire' );
$log = "Initializing Checkout with JSON:\n" . json_encode($return_array) . "\n";
$logger->info( $log, $context );
return $return_array;
}
</code></pre>
<blockquote>
<p>2022-02-17T11:16:19+00:00 INFO Initializing Checkout with JSON:
{"result":"success","redirect":"javascript:window.flywire.WooCommerce.show("{\"provider\":\"woocommerce\",\"env\":\"demo\",\"locale\":\"en\",\"recipient\":\"\",\"amount\":1800,\"return_url\":\"http:\\\/\\\/localhost:8888\\\/checkout\\\/order-received\\\/58\\\/?key=wc_order_2jw2UT4xADHU3\",\"callback_id\":58,\"callback_url\":\"http:\\\/\\\/localhost:8888\\\/wc-api\\\/WC_Gateway_Flywire\\\/\",\"sender_country\":\"US\",\"sender_first_name\":\"Test\",\"sender_last_name\":\"Testing\",\"sender_address1\":\"1 Test\",\"sender_phone\":\"000000000\",\"sender_city\":\"Town\",\"sender_zip\":\"94043\",\"sender_email\":\"admin@example.com\",\"student_first_name\":\"Test\",\"student_last_name\":\"Testing\",\"student_email\":\"admin@example.com\"}")"}</p>
</blockquote>
<p>On the order-pay endpoint, clicking the Pay button generates the exact same button, but the JS does not fire or trigger the breakpoint I put in it. If I manually try to call the JS from the Dev Tools Console, like below, it triggers the breakpoint:</p>
<pre><code>window.flywire.WooCommerce.show('foo')
</code></pre>
<p>So, I know that the JS script has been enqueued properly and is included in the page. I also know that the <code>process_payment</code> function is returning the correct redirect value. And yet, nothing happens.</p>
<p>As far as I can tell, function <code>process_order_payment</code> in class-wc-checkout.php is what actually takes the return value from my gateway's <code>process_payment</code> function and does its magic. I added logging there too and can see it fire when I click Pay from the Checkout page. But, nothing happens from the Order Pay page.</p>
<p><strong>UPDATE:</strong> No solution yet but found some more information. <code>process_payment</code> is called in two places. For checkout, it is called by <code>class-wc-checkout.php</code>. For the order payment page, it is called by <code>class-wc-form-handler.php</code>. The code is in both places is <em>almost</em> the same.</p>
<p>Code on <code>class-wc-checkout.php</code>:</p>
<pre><code>// Process Payment.
$result = $available_gateways[ $payment_method ]->process_payment( $order_id );
// Redirect to success/confirmation/payment page.
if ( isset( $result['result'] ) && 'success' === $result['result'] ) {
$result['order_id'] = $order_id;
$result = apply_filters( 'woocommerce_payment_successful_result', $result, $order_id );
if ( ! wp_doing_ajax() ) {
// phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
wp_redirect( $result['redirect'] );
exit;
}
wp_send_json( $result );
}
</code></pre>
<p>Code on <code>class-wc-form-handler.php</code>:</p>
<pre><code>$result = $payment_method->process_payment( $order_id );
// Redirect to success/confirmation/payment page.
if ( isset( $result['result'] ) && 'success' === $result['result'] ) {
$result['order_id'] = $order_id;
$result = apply_filters( 'woocommerce_payment_successful_result', $result, $order_id );
wp_redirect( $result['redirect'] ); //phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
exit;
}
</code></pre>
<p>In the checkout version (which works), it does not call <code>wp_redirect()</code> if WP is doing AJAX and instead sends the JSON to the AJAX. In the order payment page version, it always just redirects with <code>wp_redirect()</code>. It's the <code>wp_send_json()</code> that allows the "Javascript:" protocol to work, but I don't understand why paying from the checkout page works differently from the order payment page.</p>
| 3 | 2,072 |
Laravel post form error
|
<p>I'm having a problem for the first time when i submit a form.</p>
<p>When i submit the form it doesn't go to post route and i don't know why.</p>
<p>my post route is that:</p>
<pre><code> Route::post('/app/add-new-db', function()
{
$rules = array(
'name' => 'required|min:4',
'file' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
// redirect our user back to the form with the errors from the validator
return Redirect::to('app/add-new-db')
->withErrors($validator);
}
else
{
$name = Input::get('name');
$fname = pathinfo(Input::file('file')->getClientOriginalName(), PATHINFO_FILENAME);
$fext = Input::file('file')->getClientOriginalExtension();
echo $fname.$fext;
//Input::file('file')->move(base_path() . '/public/dbs/', $fname.$fext);
/*
DB::connection('mysql')->insert('insert into databases (name, logotipo) values (?, ?)',
[$name, $fname.$fext]);
*/
//return Redirect::to('app/settings/');
}
});
</code></pre>
<p>And my html:</p>
<pre><code> <div class="mdl-cell mdl-cell--12-col content">
{!! Form::open(['url'=>'app/add-new-db', 'files'=>true]) !!}
<div class="mdl-grid no-verticall">
<div class="mdl-cell mdl-cell--12-col">
<h4>Adicionar Base de Dados</h4>
<div class="divider"></div>
</div>
<div class="mdl-cell mdl-cell--6-col">
<div class="form-group">
{!! Form::label('name', 'Nome: ') !!}
{!! Form::text('name', null, ['id'=> 'name', 'class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('image', 'Logotipo:') !!}
{!! Form::file('image', ['class'=>'form-control']) !!}
@if ($errors->has('image'))
<span class="error">{{ $errors->first('image') }}</span>
@endIf
</div>
<div class="form-group">
{!! Form::submit('Adicionar', ['id'=>'add-new-db', 'class'=>'btn btn-default']) !!}
<p class="text-success"><?php echo Session::get('success'); ?></p>
</div>
</div>
</div>
{!! Form::close() !!}
</div>
</code></pre>
<p>I'm loading this from from a jquery get:</p>
<pre><code> function addDB()
{
$( "#settings-new-db" ).click(function(e)
{
$.get('/app/add-new-db', function(response)
{
$('.content-settings').html("");
$('.content-settings').html(response);
componentHandler.upgradeDom();
});
e.preventDefault();
});
}
</code></pre>
<p>When i try to submit the form i'm getting 302 found in network console from chrome.</p>
<p>I'm doing forms at this way and it is happens for the first time. Anyone can help me?</p>
<p>Thanks</p>
| 3 | 1,457 |
Reproduce OxMetrics' ARFIMA model in R
|
<p>I am working to reproduce some results from OxMetrics (<a href="http://www.timberlake.co.uk/software/oxmetrics.html#ox-pro" rel="nofollow">Ox Professional version 7.10</a>) in R, but I am having a hard time figuring out exactly I get the right specification in R. I do not expect to get identical estimates, but somewhat similar estimates should be possible (see below for estimates from OxMetrics and from R).</p>
<p>Can anyone here help me figuring out how I do what OxMetrics does in R?</p>
<p>I've tried using <code>forecast::arfima</code>, <code>forecast::Arima</code>, <code>fracdiff::fracdiff</code>, and <code>arfima::arfima</code> So far I came closest with the latter.</p>
<p>Below is data and code,</p>
<p>The blow results is from is from OxMetrics ARFIMA(2,0,2) model estimated using Maximum likelihood and from R using <code>arfima</code> from the <code>arfima</code> package (code blow the longer data string).</p>
<pre><code> OxMetrics R (using arfima()]
AR 1.41763 1.78547
AR -0.51606 -0.79782
MA -0.89892 -0.08406
MA 0.30821 0.48083
Constant -0.09382 -0.09423
y <- c(-0.0527281830620101, -0.0483283435220523,
-0.0761110069836706, -0.0425588714546148,
-0.0629789511239869, -0.118944956578757,
-0.156545103342326, -0.138106089421937,
-0.107335059908618, -0.145013381825552,
-0.100753517322066, -0.0987268545186417,
-0.0454663306471916, -0.0404439816954447,
-0.110574863632305, -0.0933955365797221,
-0.0915045759209185, -0.110397691370645,
-0.0944201704700927, -0.121257467376357,
-0.109785472344257, -0.0890776818684245,
-0.0554059943242384, -0.0700566531543618,
-0.0366694695635905, -0.0687369752462432,
-0.0651380598746858, -0.134224646388692,
-0.0670924768348229, -0.0835771023087037,
-0.0709997877276756, -0.116003735777656,
-0.0794873243023737, -0.067057402058551,
-0.0698663891865543, -0.0511133873895728,
-0.0513203609998669, -0.0894001277309737,
-0.0398284483421012, -0.0514468502511471,
-0.0599700163953942, -0.0661889418696937,
-0.079516218903545, -0.0685966077135509,
-0.0861445337428064, -0.0923966209966709,
-0.133444703431511, -0.131567692883267,
-0.127157375630663, -0.136327904368355,
-0.102133208996487, -0.109453799095327,
-0.103333580486325, -0.0982528240902063,
-0.139243862997714, -0.112067682286408,
-0.0741501704478233, -0.0885574830826608,
-0.0819203358523941, -0.0891168040724528,
-0.0331415164887199, -0.038039022334333,
0.000471320939768205, -0.0250547289467331,
-0.0411983586070352, -0.0463752713008887,
-0.0184870766950889, -0.0318185253129144,
-0.0623828610377037, -0.0718563679309012,
-0.0635702270765757, -0.0929728977267059,
-0.0894248292570765, -0.0919046741661464,
-0.0844700793317346, -0.112800098282505,
-0.141344968548085, -0.127965917566584,
-0.143980868315393, -0.154901662762077,
-0.130634570152671, -0.150417664726561,
-0.163723312802416, -0.146099566906346,
-0.14837251795191, -0.144887288973472,
-0.14232221415307, -0.142825446351853,
-0.158838097005599, -0.14340614330986,
-0.118935233992604, -0.109627188482776,
-0.120889714109902, -0.119484146944083,
-0.0950435556738212, -0.134667374330086,
-0.155051119642286, -0.134094795193097,
-0.128627607285988, -0.133954472488274,
-0.119286541395138, -0.135714339904381,
-0.0903767618937357, -0.109592987693797,
-0.0770998518949151, -0.108375176935532,
-0.136901231908067, -0.0856673865524131,
-0.108854388315838, -0.0708359081737591,
-0.106961434062811, -0.0429126711978416,
-0.0550592121225453, -0.0715845951018634,
-0.0509376225313689, -0.0570175197192393,
-0.0724229547086495, -0.0867303057832318,
-0.089712447506396, -0.125158029708487,
-0.122260116350003, -0.0905629436620448,
-0.090357598491857, -0.097173095034008,
-0.0674973361276239, -0.12411935716644,
-0.0957789729967162, -0.088838044599159,
-0.110065127067576, -0.108172925482296)
# install.packages(c("arfima"), dependencies = TRUE)
# library(arfima)
arfima::arfima(y, order = c(2, 0, 2))
</code></pre>
| 3 | 2,002 |
JS/jQuery: When prepending a dynamic element, how to force the container div to extend upwards instead of downwards?
|
<p>If you've noticed, it seems that when <code>prepend()</code> is used, the additional elements get piled at the top but the container div is extended downwards. </p>
<p>Comparing with FB's load previous message, you will notice that elements are loaded on top of each other but your <strong>view does not change</strong>. It is like <code>append()</code> except the container div "seems" to extend upwards. </p>
<p><strong>I've tried doing this to <em>simulate the div extending upwards</em> but failed</strong></p>
<pre><code>var scrolldif = $('#response')[0].scrollHeight-$('#response').scrollTop();
$('#response').scrollTop(scrolldif);
</code></pre>
<p>Here is the sample html to try. Just copy/paste/run in browser.</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<style type="text/css">
.chatbox div{
height: 100%;
}
#response{
height: 300px;
overflow-y: scroll;
overflow-wrap: break-word;
}
</style>
<script type="text/javascript">
function appendMessage()
{
var data = 'test';
var message = document.createElement('p');
message.innerHTML = data;
$('#response').append(message);
}
function prependMessage()
{
var data = 'test'+Math.floor((Math.random() * 10) + 1);
var message = document.createElement('p');
message.innerHTML = data;
console.log(message.innerHTML);
$('#response').prepend(message);
}
</script>
<body>
<div class="container">
<div class="chatbox">
<div class="col-sm-8 rightP">
<div class="row contents">
<a onclick="return appendMessage()" class="load btn btn-default">Append</a>
<a onclick="return prependMessage()" class="load2 btn btn-default">Prepend</a>
<div class="row msg">
<div id="response" class="msg form-group">
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p>Thank you!</p>
| 3 | 1,263 |
How can I save to file label() output in R?
|
<p>There is a list of objects, in data variable.</p>
<p>I call (library: Hmisc):</p>
<p><code>label(data)</code></p>
<p>Output: </p>
<pre><code>$SubsID
NULL
$SubsID_RN
NULL
$responseid
NULL
$Wave
2014 2013 2012
"2014" "2013" "2012"
$Country
Hong Kong Taiwan Chile Singapore New Zealand
"46" "45" "44" "43" "42"
Finland Saudi Arabia Israel Netherlands Belgium
"41" "40" "39" "38" "37"
Tunisia South Africa Malaysia Mexico Canada
"36" "35" "34" "33" "32"
Portugal Switzerland Columbia Venezuela Brazil
"31" "30" "29" "28" "27"
Argentina UAE Turkey India Austria
"26" "25" "24" "23" "22"
Japan China Australia Ireland UK (Welsh)
"21" "20" "19" "18" "17"
Thailand South Korea Russia Poland Czech Republic
"16" "15" "14" "13" "12"
Hungary Greece Norway Denmark Sweden
"11" "10" "9" "8" "7"
Spain Germany Italy France USA
"6" "5" "4" "3" "2"
UK
"1"
</code></pre>
<p>And a want to write it to file. With this command: </p>
<pre><code>write.table(label(data), "labels.txt")
</code></pre>
<p>And i get an error.</p>
<pre><code>Error in data.frame(SubsID = NULL, SubsID_RN = NULL, responseid = NULL, :
arguments imply differing number of rows: 0, 46, 3, 9, 18, 13, 50, 5, 23, 2,
12, 7, 8, 4, 6, 20, 11, 10
</code></pre>
<p>Any idea?
Thanks!</p>
| 3 | 1,209 |
Bundle install failure for an existing ruby app. I suspect libv8
|
<p>I have the rather unfortunate position of inheriting a rails app from a previous developer. I have the joy of both trying to learn ruby and picking apart the old code to fix what's broken. I don't have any means for contacting the former developer, nor do I have much knowledge of the app other than that it uses ruby on rails. I'm much more familiar with the .net environment, so getting RoR up and running is proving to be a bit of a challenge. </p>
<p>I'm simply trying to clone their code repo locally and try to run their code on a local rails server. I was able to clone, the next thing I tried was to run bundle install and I got this massive block of text that I can't make heads or tails of.</p>
<p><strong>Massive wall of text below</strong></p>
<pre><code>Justin@JVB-MBP /c/Sites/mymouthworks (master)
$ bundle install
DL is deprecated, please use Fiddle
Fetching gem metadata from https://rubygems.org/.........
Resolving dependencies...
Using rake 10.1.1
Using i18n 0.6.9
Using minitest 4.7.5
Using multi_json 1.8.4
Using atomic 1.1.14
Using thread_safe 0.1.3
Using tzinfo 0.3.38
Using activesupport 4.0.2
Using builder 3.1.4
Using erubis 2.7.0
Using rack 1.5.2
Using rack-test 0.6.2
Using actionpack 4.0.2
Using mime-types 1.25.1
Using polyglot 0.3.4
Using treetop 1.4.15
Using mail 2.5.4
Using actionmailer 4.0.2
Using activemodel 4.0.2
Using activerecord-deprecated_finders 1.0.3
Using arel 4.0.2
Using activerecord 4.0.2
Using bcrypt-ruby 3.1.2
Using sass 3.2.14
Using bootstrap-sass 3.1.1.1
Using will_paginate 3.0.4
Using bootstrap-will_paginate 0.0.9
Using bundler 1.7.7
Using chunky_png 1.3.0
Using coffee-script-source 1.7.0
Using execjs 2.0.2
Using coffee-script 2.2.0
Using thor 0.18.1
Using railties 4.0.2
Using coffee-rails 4.0.1
Using commonjs 0.2.7
Using fssm 0.2.10
Using compass 0.12.3
Using hike 1.2.3
Using tilt 1.4.1
Using sprockets 2.11.0
Using compass-rails 1.1.7
Using date_validator 0.7.0
Using jbuilder 1.5.3
Using jquery-rails 3.1.0
Using json 1.8.1
Using less 2.4.0
Using less-rails 2.4.2
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
c:/RailsInstaller/Ruby2.1.0/bin/ruby.exe -r ./siteconf20150212-3448-1yjlu6v.
rb extconf.rb
creating Makefile
The system cannot find the path specified.
The system cannot find the path specified.
The system cannot find the path specified.
c:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/libv8 3.16.14.3/ext/libv8/builder.rb:58:in `setup_python!': libv8 requires python 2 to be installed in order to build, but it is currently not available (RuntimeError)
from c:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/libv8-3.16.14.3/ext/libv8/builder.rb:42:in `block in build_libv8!'
from c:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/libv8-3.16.14.3/ext/libv8/builder.rb:40:in `chdir'
from c:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/libv8-3.16.14.3/ext/libv8/builder.rb:40:in `build_libv8!'
from c:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/libv8-3.16.14.3/ext/libv8/location.rb:24:in `install!'
from extconf.rb:7:in `<main>'
extconf failed, exit code 1
Gem files will remain installed in c:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/libv8-3.16.14.3 for inspection.
Results logged to c:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/extensions/x86-mingw32/2.1.0/libv8-3.16.14.3/gem_make.out
An error occurred while installing libv8 (3.16.14.3), and Bundler cannot continue.
Make sure that `gem install libv8 -v '3.16.14.3'` succeeds before bundling.
Justin@JVB-MBP /c/Sites/mymouthworks (master)
$
</code></pre>
<p>To me, it looks like there's an issue with libv8, but there is also a warning about python 2 not being installed, which it is, along with being added to the path variable. I should add my dev environment is 64-bit Windows 8.1. Has anyone got this working? </p>
<p>Thank you.</p>
| 3 | 1,488 |
Mobile got hanged while uploading images from gallery in android
|
<p>I want to upload images from gallery to make it as my profile image.But my mobile got hanged for few seconds and after that, it comes to normal mode and uploads the image with some delay.Can anyone please help me to avoid hanging and upload the image quickly.</p>
<p>Here is my code.</p>
<pre><code>public void res() {
System.out.println("res method for jscript");
webView.loadUrl("javascript:callFromActivity(\"" + msgToSend + "\")");
}
public void showCustomAlert() {
// TODO Auto-generated method stub
Context context = getApplicationContext();
// Create layout inflator object to inflate toast.xml file
LayoutInflater inflater = getLayoutInflater();
// Call toast.xml file for toast layout
View toastRoot = inflater.inflate(R.layout.toast, null);
Toast toast = new Toast(context);
// Set layout to toast
toast.setView(toastRoot);
toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data!=null)
{
if (requestCode == CAM_REQUREST) {
Bundle extras = data.getExtras();
if (extras != null) {
bitmap_profile_image = extras.getParcelable("data");
bitmap_profile_image = (Bitmap) data.getExtras().get("data");
imagepath = ImageWrite(bitmap_profile_image);
}
}
else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imagepath = ImageWrite(BitmapFactory.decodeFile(picturePath));
} else {
}
}
Imageuploading();
}
public String ImageWrite(Bitmap bitmap1) {
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "selectimage.PNG");
try {
outStream = new FileOutputStream(file);
bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outStream);`enter code here`
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String imageInSD = "/sdcard/selectimage.PNG";
return imageInSD;
}
protected void Imageuploading() {
// TODO Auto-generated method stub
try {
Log.e("imageuploading", "dfdf");
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = (String) imagepath;
// String urlServer =
// "http://demo.cogzideltemplates.com/client/snapchat-clone/index.php/user/image_upload";
String urlServer = Liveurl+"mobile/image_upload";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
// Toast.makeText(getApplicationContext(), serverResponseMessage,
// Toast.LENGTH_LONG).show();
System.out.println("image" + serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
DataInputStream inputStream1 = null;
inputStream1 = new DataInputStream(connection.getInputStream());
String str = "";
String Str1_imageurl = "";
while ((str = inputStream1.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
Str1_imageurl = str;
Log.e("Debug", "Server Response String imageurl" + str);
}
inputStream1.close();
System.out.println("image url inputstream1 " + Str1_imageurl);
// Toast.makeText(getApplicationContext(), Str1_imageurl,
// Toast.LENGTH_LONG).show();
msgToSend = Str1_imageurl.trim();
System.out.println("message to send "+msgToSend);
} catch (Exception e) {
e.printStackTrace();
}
res();
}
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
System.out.println("application dir"+appDir);
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
Intent i=new Intent(Profile_settings.this,splash.class);
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// clearApplicationData();
startActivity(i);
}
}
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
private void loadSavedPreferences() {
//User has successfully logged in, save this information
// We need an Editor object to make preference changes.
SharedPreferences settings = getSharedPreferences(index.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.clear();`enter code here`
editor.commit();
}
</code></pre>
<p>Thanks in advance.</p>
| 3 | 3,861 |
How can have multirows Footer in Datatables?
|
<p>I want make two rows at my footer datatables. First row of footer for sum columns and second row of footer for search columns.</p>
<p>This is my code in javascript</p>
<pre><code>$(function () {
$('#ntable1 tfoot th').each( function () { //for search columns in footer
var title = $(this).text();
$(this).html( '<input type="text" placeholder="'+title+'"/>' );
} );
var table = $("#ntable1").DataTable({
"responsive": false, "scrollX": true, "lengthChange": true, "autoWidth": false,
"buttons": [
{
extend: 'copy',
exportOptions: {
columns: [':visible' ]
}
},
{
extend: 'excel',
exportOptions: {
columns: [':visible' ]
},
messageBottom: textTop,
},
{
extend: 'print',
footer: true,
exportOptions: {
columns: [':visible' ]
},
messageTop: textTop
},
{
extend: 'colvis',
exportOptions: {
columns: [':visible' ]
}
}
],
footerCallback: function (row, data, start, end, display) { //for sum of columns in footer
var api = this.api();
// Remove the formatting to get integer data for summation
var intVal = function (i) {
return typeof i === 'string' ? i.replace(/[\$,]/g, '') * 1 : typeof i === 'number' ? i : 0;
};
// Total over all pages
total = api
.column(3)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
// Total over this page
pageTotal = api
.column(3, { page: 'current' })
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
// Update footer
$('tr:eq(0) td:eq(3)', api.table().footer()).html(format('$' + pageTotal + ' ( $' + total + ' total)')); //not work
// $(api.column(3).footer()).html('$' + pageTotal + ' ( $' + total + ' total)'); //not work
},
initComplete: function () {
// Apply the search
this.api().columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change clear', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
}
}).buttons().container().appendTo('#ntable1_wrapper .col-md-6:eq(0)');
});
</code></pre>
<p>Datatables code in html</p>
<pre><code><table id="ntable1" class="table table-bordered table-striped">
<thead> ... </thead>
<tbody> ... </tbody>
<tfoot>
<tr> <!-- for sum columns -->
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr> <!-- for search columns -->
<th>No</th>
<th>Nama Program</th>
<th>Tahun</th>
<th>Jumlah Kota</th>
<th>Nama Kota</th>
<th>Jumlah Sekolah</th>
<th>Jumlah Siswa</th>
<th>Pre Test</th>
<th>Post Test</th>
<th>%</th>
<th>Tingkat Kepuasan</th>
<th>Tabungan Pelajar (Account)</th>
</tr>
</tfoot>
</table>
</code></pre>
<p>If I add row in footer, my search column doesn't work. My problem only how to have multiple rows in footer datatables, which first row for calculate sum and second row for search column. Hope anyone can help.</p>
| 3 | 2,798 |
connect signal emitted from c++ to qml Connections
|
<p>I am emitting a signal from c++ and trying to fetch the values using Connections in qml. The codes are compiling however, due to some unknown reason qml is not able to recognise "<strong>OnSomethingHappened</strong>" and signal emitted from c++ is "<strong>somethingHappened</strong>".</p>
<p>I know there can be other solutions but i need to use connections in qml. This is because of architecture used in qml. </p>
<p>qmlclient.h</p>
<pre><code>#ifndef QMLMQTTCLIENT_H
#define QMLMQTTCLIENT_H
#include <QtCore/QMap>
#include <QtMqtt/QMqttClient>
#include <QtMqtt/QMqttSubscription>
class QmlMqttClient;
class QmlMqttSubscription : public QObject
{
Q_OBJECT
Q_PROPERTY(QMqttTopicFilter topic MEMBER m_topic NOTIFY topicChanged)
public:
QmlMqttSubscription(QMqttSubscription *s, QmlMqttClient *c);
~QmlMqttSubscription();
Q_SIGNALS:
void topicChanged(QString);
void messageReceived(QString &msg);
void somethingHappened(QString text);
public slots:
void handleMessage(const QMqttMessage &qmsg);
private:
Q_DISABLE_COPY(QmlMqttSubscription)
QMqttSubscription *sub;
QmlMqttClient *client;
QMqttTopicFilter m_topic;
};
class QmlMqttClient : public QMqttClient
{
Q_OBJECT
public:
QmlMqttClient(QObject *parent = nullptr);
QmlMqttSubscription *subscribe(const QString &topic);
void sub();
private:
Q_DISABLE_COPY(QmlMqttClient)
};
#endif // QMLMQTTCLIENT_H*/
</code></pre>
<p>qmlmqttclient.cpp</p>
<pre><code>#include "qmlmqttclient.h"
#include <QDebug>
QmlMqttClient::QmlMqttClient(QObject *parent)
: QMqttClient(parent)
{
}
QmlMqttSubscription* QmlMqttClient::subscribe(const QString &topic)
{
auto sub = QMqttClient::subscribe(topic, 0);
auto result = new QmlMqttSubscription(sub, this);
return result;
}
QmlMqttSubscription::QmlMqttSubscription(QMqttSubscription *s, QmlMqttClient *c)
: sub(s)
, client(c)
{
connect(sub, &QMqttSubscription::messageReceived, this, &QmlMqttSubscription::handleMessage);
// m_topic = sub->topic();
}
QmlMqttSubscription::~QmlMqttSubscription()
{
}
void QmlMqttSubscription::handleMessage(const QMqttMessage &qmsg)
{
//emit messageReceived(qmsg.payload());
emit somethingHappened(qmsg.payload());
qDebug() << "value -> " + qmsg.payload();
}
</code></pre>
<p>main.cpp</p>
<pre><code>int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QmlMqttClient *client = new QmlMqttClient();
client->setHostname("127.0.0.1");
client->setPort(1883);
client->connectToHost();
qDebug() << client->state();
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [client]() {client->subscribe("/root/temp");});
timer.setSingleShot(true);
timer.start(5000);
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("myModel",client);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
</code></pre>
<p>main.qml</p>
<pre><code>Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle {
id: sensor
color: "#ffffff"
radius: 10
x: 10
y: 10
property string address
property string title
property string unit
Text{
id: textField
property var value : 0
text: sensor.title + " " + value + " " + sensor.unit
y:50
font.family: "Helvetica"
font.pointSize: 24
anchors.horizontalCenter: parent.horizontalCenter
}
Connections
{
target: myModel
onSomethingHappened: {
console.log(" something happened " +text);
}
}
}
}
</code></pre>
<p>On running the above codes console shows </p>
<pre><code>QML debugging is enabled. Only use this in a safe environment.
1
qrc:/main.qml:33:9: QML Connections: Cannot assign to non-existent property "onSomethingHappened"
"value -> -50"
"value -> -50"
"value -> -50"
</code></pre>
| 3 | 1,855 |
Object TypeScript
|
<p>I want to send data from a form in VueJS with Axios.
But i don't know how to write my object before send it</p>
<p><strong>View :</strong></p>
<pre><code> methods: {
createPost() {
let autorData = {
nom: this.nom,
}
let postData = {
titre: this.titre,
auteur: autorData,
contenu: this.contenu,
};
this.__submitToServer(postData);
},
__submitToServer(data) {
axios.post(`${server.baseURL}/post/create`, data).then(data => {
router.push({ name: "home" });
});
}
}
</code></pre>
<p><strong>Controller :</strong></p>
<pre><code>
import { Controller, Get, Res, HttpStatus, Param, Post, Body, NotFoundException } from '@nestjs/common';
import { PostService } from './post.service';
import { CreatePostDTO } from './dto/create-post.dto';
@Controller('post')
export class PostController {
constructor(private readonly postService: PostService) { }
...
@Post('/create')
async addPost(@Res() res, @Body() createPostDTO: CreatePostDTO) {
const post = await this.postService.addPost(createPostDTO);
return res.status(HttpStatus.OK).json({
message: "Post has been created successfully",
post
})
}
}
</code></pre>
<p><strong>Model : CreatePostDTO</strong></p>
<pre><code>
import { User } from 'src/user/interfaces/user.interface';
export class CreatePostDTO {
readonly titre: string;
readonly auteur: User;
readonly contenu: string;
}
</code></pre>
<p><strong>Model : interface User</strong></p>
<pre><code> export interface User extends Document {
readonly nom: string;
}
</code></pre>
<p>How can I make it understand that's the "author" data is a sub-object of my "post" ?</p>
<p><strong>EDIT</strong></p>
<p><strong>Error from the server</strong></p>
<pre><code>
ValidationError: Post validation failed: auteur: Cast to ObjectID failed for value "{}" at path "autor"
...
at PostService.addPost (C:\Users\me\Desktop\Try\VueJS_NestJS_MongoDB\diy\customer-list-app-backend\src\post\post.s at C:\Users\yann.surzur\Desktop\Try\VueJS_NestJS_MongoDB\diy\customer-list-app-backend\src\post\post.controller.ts:19:71
message: 'Cast to ObjectID failed for value "{}" at path "autor"', name: 'CastError',
stringValue: '"{}"',
kind: 'ObjectID',
value: {},
path: 'autor',
reason: [MongooseError] } },
_message: 'Post validation failed',
name: 'ValidationError'
</code></pre>
<p>The problem is there : 'Cast to ObjectID failed for value "{}" at path "autor"'.
That's why i think i made a mistake when i wrote the data before sent it.</p>
| 3 | 1,275 |
DELETE ROW command is getting skipped without any ERROR
|
<p>I have two tables, table1 has multiple rows with data, while table2 is empty.</p>
<p>I m trying to perform a simple INSET into and DELETE command in php to add the selected row from table1 to table2 and at the same time DELETE the selected row from table1</p>
<p>But here, it gets inserted to table 2 and doesn't get deleted from table 1 but returns to main page without any error.</p>
<p>My code as follows:</p>
<p>Calling row content from table1 to user page:</p>
<pre><code><?php
$sql2 = "SELECT * FROM apromocode ";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
?>
<tr >
<form id="promocodesub" action="apromocodesubdelete.php" method="post">
<td>
<?php echo ($row2["id"]); ?>
</td>
<td>
<?php echo ($row2["code"]); ?>
</td>
<input type="hidden" form="promocodesub" name="code" value="<?php echo ($row2["code"]); ?>"/>
<td>
<?php echo ($row2["occation"]); ?>
</td>
<input type="hidden" form="promocodesub" name="occation" value="<?php echo ($row2["occation"]); ?>"/>
<td>
<?php echo ($row2["about"]); ?>
</td>
<input type="hidden" form="promocodesub" name="about" value="<?php echo ($row2["about"]); ?>"/>
<td>
<?php echo ($row2["discount"]); ?>
</td>
<input type="hidden" form="promocodesub" name="discount" value="<?php echo ($row2["discount"]); ?>"/>
<td>
<?php echo ($row2["date"]); ?>
</td>
<td>
<button form="promocodesub" type="submit" name="deleteId" value="<?php echo ($row2["id"])?>"class="promocodedelete">Delete</button>
</td>
</form>
</tr>
<?php
}
} else {
echo "0 results";
}
?>
</code></pre>
<p>So, when user open the page, he will see all row contents lined up in sequence along with "delete" button for each. When the user presses the delete button for that particular row, it will get inserted to table2 and should get deleted from the table1 with the following script:</p>
<pre><code><?php include('amerchantassign.php'); ?>
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "";
$code = $_POST['code'];
$occation = $_POST['occation'];
$about = $_POST['about'];
$discount = $_POST['discount'];
$date = date_default_timezone_set('Asia/Kolkata');
$date = date('M-d,Y H:i:s');
enter code here
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$deleteId= $_POST['deleteId'];
$sql="INSERT INTO apromocodehistory (code, occation, about, discount, date)
SELECT code, occation, about, discount, date
FROM apromocode
WHERE id= $deleteId";
if ($conn->query($sql) === TRUE) {
$sql4 = "DELETE FROM feedback WHERE id = '$deleteId' ";
if ($conn->query($sql4) === TRUE) {
echo '<a href="amerchantassign.php"></a>';
} else {
echo "ERROR" . $sql4;
}
} else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</code></pre>
<p>Any Suggestions are appreciated...</p>
| 3 | 1,825 |
Multiple different calls to same activity issue
|
<p>I have a simple application with which iam displaying weblinks in webviews.
i have two webViews one for links i want to open in portrait or in landscape</p>
<p>my code works well when i have only a single intent call and handling only one in the requested activity</p>
<p>now from my mainActivty i am sending the intent calls on the button click
here's the code </p>
<pre><code> protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button intra = (Button) findViewById(R.id.buttonIntra);
intra.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchactivity = new Intent(MainActivity.this,
potraitWebview.class);
launchactivity
.putExtra("QI",
"https://TEST.COM");
launchactivity.putExtra("viewport", t);
launchactivity.putExtra("overviewmode", t);
startActivity(launchactivity);
finish();
}
});
Button chat = (Button) findViewById(R.id.buttonChat);
chat.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchactivity = new Intent(MainActivity.this,
potraitWebview.class);
launchactivity.putExtra("chat",
"http://CHAT.COM");
launchactivity.putExtra("viewport", t);
launchactivity.putExtra("overviewmode", t);
startActivity(launchactivity);
finish();
}
});
}
</code></pre>
<p>Now the activity i am calling im using this code to handle these requests and display the webpages</p>
<pre><code> protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.potraitlayout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
R.layout.customtitlebar);
web = (WebView) findViewById(R.id.webViewPotrait);
// Handling incoming activity requests
Bundle intraExtras = getIntent().getExtras();
if (intraExtras != null) {
String value = intraExtras.getString("QI");
viewport = intraExtras.getBoolean("viewport", false);
overviewmode = intraExtras.getBoolean("overviewmode", false);
url = value.trim();
Toast.makeText(getApplicationContext(), value+" "+viewport+" "+overviewmode, Toast.LENGTH_SHORT)
.show();
}
Bundle chat = getIntent().getExtras();
if (chat != null) {
String value = chat.getString("chat");
viewport = chat.getBoolean("viewport", false);
overviewmode = chat.getBoolean("overviewmode", false);
url = value.trim();
Toast.makeText(getApplicationContext(), value+" "+viewport+" "+overviewmode, Toast.LENGTH_SHORT)
.show();
}
</code></pre>
<blockquote>
<p><em>the issue here is <strong>getIntent().getExtras();</strong> which i am using if it is null for any of the activity requests which has not been currently
called the application crashes</em></p>
</blockquote>
<p>logcat</p>
<pre><code> 05-02 11:33:49.153: E/AndroidRuntime(19950): FATAL EXCEPTION: main
05-02 11:33:49.153: E/AndroidRuntime(19950): Process: com.android.qintra, PID: 19950
05-02 11:33:49.153: E/AndroidRuntime(19950): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.qintra/com.android.qintra.potraitWebview}: java.lang.NullPointerException
05-02 11:33:49.153: E/AndroidRuntime(19950): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
05-02 11:33:49.153: E/AndroidRuntime(19950): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
05-02 11:33:49.153: E/AndroidRuntime(19950): at android.app.ActivityThread.access$800(ActivityThread.java:139)
05-02 11:33:49.153: E/AndroidRuntime(19950): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
05-02 11:33:49.153: E/AndroidRuntime(19950): at android.os.Handler.dispatchMessage(Handler.java:102)
05-02 11:33:49.153: E/AndroidRuntime(19950): at android.os.Looper.loop(Looper.java:136)
05-02 11:33:49.153: E/AndroidRuntime(19950): at android.app.ActivityThread.main(ActivityThread.java:5102)
05-02 11:33:49.153: E/AndroidRuntime(19950): at java.lang.reflect.Method.invokeNative(Native Method)
05-02 11:33:49.153: E/AndroidRuntime(19950): at java.lang.reflect.Method.invoke(Method.java:515)
05-02 11:33:49.153: E/AndroidRuntime(19950): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
05-02 11:33:49.153: E/AndroidRuntime(19950): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
05-02 11:33:49.153: E/AndroidRuntime(19950): at dalvik.system.NativeStart.main(Native Method)
05-02 11:33:49.153: E/AndroidRuntime(19950): Caused by: java.lang.NullPointerException
05-02 11:33:49.153: E/AndroidRuntime(19950): at com.android.qintra.potraitWebview.onCreate(potraitWebview.java:54)
05-02 11:33:49.153: E/AndroidRuntime(19950): at android.app.Activity.performCreate(Activity.java:5248)
05-02 11:33:49.153: E/AndroidRuntime(19950): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
05-02 11:33:49.153: E/AndroidRuntime(19950): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
05-02 11:33:49.153: E/AndroidRuntime(19950): ... 11 more
</code></pre>
<p><strong>line 54 is
<a href="http://i.stack.imgur.com/5Ctse.png" rel="nofollow">http://i.stack.imgur.com/5Ctse.png</a></strong></p>
| 3 | 2,241 |
Linked List, Stuck on file management
|
<p>I am trying to read from a file called data.txt. and store it into a LL which looks like this</p>
<pre><code>Quanta 2
New 2
Ready 2
A 1 3
B 3 4
C 5 6
D 7 9
</code></pre>
<p>I would like to read that file, one line at a time, storing each line at a node in a LL, e.g A 1 3, will be at one node.</p>
<p>The desired layout is this </p>
<pre><code>Name Value
Quanta 2
New 2
Ready 2
-------------------------
Process NUT AT
A 1 3
B 3 4
C 5 6
D 7 9
</code></pre>
<p>I have wrote the following code, which does read from the file and displays results for name and value correctly, however I do not understand how can I make it so it reads one line at a time and stores that one line into specific node. </p>
<p>This is what my code Currently displays:</p>
<h2> Name | Value|</h2>
<pre><code>3 1
4 3
6 5
9 7
A 1
B 3
C 5
D 7
New 2
Quanta 2
Ready 2
</code></pre>
<p>I have tried to solve this for quiet a while now, I have officially hit a mental block, I would appreciate any help you can offer. </p>
<p>Code:</p>
<pre><code> #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define NAME_LENGTH 20
#define PROCESS_LENGTH 20
//create quanta structure.
typedef struct Quanta
{
char* name;
int Value;
struct Quanta *next;
}Quanta;
Quanta* new_Q(char*, int);
Quanta* insert_by_Q(Quanta*, Quanta*);
void print_list(Quanta*);
int main()
{
FILE *in;
char* name = (char*)malloc(sizeof(char*) * NAME_LENGTH);
char filename[25];
int Value = 0;
//1. --------------Error Checking-----------------
printf("File name please:\n");
gets(filename);
in = fopen(filename, "rb");
if (in == NULL)
{
printf("The input file failed to open.\n");
printf("Program cannot continue. Exiting. . .\n");
return 1; //Exit Program
}
//2. ------Linked List Operations------
Quanta* head = NULL; //Create Empty Linked List
Quanta* current = NULL;
while(!feof(in)) //Check for file end
{
//Read first data value to kickstart.
if(fscanf(in, "%s %d ", name,&Value) == EOF)
{
break;
}
Quanta* hold = new_Q(name, Value);
head = insert_by_Q(head, hold);
}
//3. ------Print the new List------
print_list(head);
return 1; //Exit Success
}
Quanta* new_Q(char* name, int Value) {
//Create new Quanta and malloc space
Quanta* new = (Quanta*)malloc(sizeof(struct Quanta));
new->name = (char*)malloc(sizeof(char) * NAME_LENGTH);
//Set data
strcpy(new->name, name);
new->Value = Value;
new->next = NULL;
//Retun a pointer to the node
return new;
}
//Inserts new node into an alphabetically sorted linked list.
Quanta* insert_by_Q(Quanta* head, Quanta* new)
{
Quanta* current = NULL;
current = head;
if(current == NULL || strcmp(current->name, new->name) > 0)
{
new->next = current;
return new;
} else
{
while(current->next != NULL && strcmp(current->next->name, new->name) < 0)
{
current = current->next;
}
}
new->next = current->next;
current->next = new;
return head;
}
void print_list(Quanta* head)
{
Quanta* current;
current = head;
char p[] = "Name";
char c[] = "Value";
//Header
printf("\n\n|%10s | %10s| \n", p, c);
printf("-----------------------------------------------------------------------\n");
while(current != NULL)
{
printf("|%10s |%10d|\n", current->name, current->Value);
current = current->next;
}
printf("-----------------------------------------------------------------------\n");
return;
}
</code></pre>
| 3 | 2,791 |
VBA No resultset from stored procedure that backups database
|
<p>I need to execute a stored procedure that make some changes to a specific database and back it up at the same time. For some reason, when the backup code is active, in VBA's recordset I don't get any row but the backup is effectively created. </p>
<p>The recordset comes closed and Err.Description is "Operation is not allowed when the object is closed." If I comment the backup code in the stored procedure, the recordset comes opened I get the 1 row with the results.</p>
<p>In the vb code I am calling the stored procedure with adAsyncExecute and waiting using the following code:</p>
<p>Any Idea why the recordset comes closed and does not return 1 row when executing successfully the sp? </p>
<p><strong>Edit:</strong>
If I execute the sp in SSMS with exec, it works and I can see the row with the values.
<img src="https://i.stack.imgur.com/0LsUu.png" alt="enter image description here"></p>
<p><strong>12.01.2015</strong></p>
<ul>
<li><p>I found exactly the same issue for another user but no solution
<a href="https://social.msdn.microsoft.com/Forums/sqlserver/en-US/7e05bc02-4681-4d08-9c21-b90d5730c7e6/receiving-recordsetresultset-from-sql-server?forum=sqlexpress" rel="nofollow noreferrer">https://social.msdn.microsoft.com/Forums/sqlserver/en-US/7e05bc02-4681-4d08-9c21-b90d5730c7e6/receiving-recordsetresultset-from-sql-server?forum=sqlexpress</a></p></li>
<li><p>I tried to execute the sp in synchronous mode and I face the same issue</p></li>
<li><p>It is not a timeout problem. Currently command's timeout is 180 seconds and the sp takes around 40 seconds to finish.</p></li>
</ul>
<p><strong>VB code:</strong></p>
<pre><code> sDB = "master"
TrustedConnection = True
ReDim arrPara(1, 2)
arrPara(0, 1) = sStandardDatabaseSTR: arrPara(1, 1) = "@DATABASE"
arrPara(0, 2) = 1: arrPara(1, 2) = "@STEP"
Set rs = ADO_OpenParameterQuerySTR("dbo.Frozen_Generation", adCmdStoredProc, arrPara, , True)
Do While rs.ActiveCommand.State = adStateExecuting 'or 4
'sleep 1000
DoEvents
Loop
rs.MoveFirst <-- Here I got the closed recordset when using the backup block
</code></pre>
<p><strong>ADO_OpenParameterQuerySTR code:</strong></p>
<pre><code>Function ADO_OpenParameterQuerySTR(ByVal sSQL As String, CommandType As CommandTypeEnum, Optional arrParameter As Variant, Optional iQueryTimeout As Variant, Optional async As Boolean = False) As ADODB.Recordset
On Error GoTo errHandler
LogToFile currentModule, "ADO_OpenParameterQuerySTR", "exec " & sSQL & " " & SerializeArray(arrParameter)
Dim cmd As New ADODB.Command
Dim para As ADODB.Parameter
Dim blFound As Boolean
Dim i As Variant, j As Variant, iType As Variant
Start:
cmd.ActiveConnection = DBconnSTR
cmd.CommandType = CommandType
cmd.CommandText = sSQL
cmd.CommandTimeout = 180
If Not IsMissing(iQueryTimeout) Then
cmd.CommandTimeout = iQueryTimeout
End If
If blDebugSTR Then Debug.Print sSQL
If CommandType = 4 Then
If Not IsMissing(arrParameter) Then
blFound = False
For i = 0 To cmd.Parameters.Count - 1
If cmd.Parameters(i).Name <> "@RETURN_VALUE" Then
For j = 0 To UBound(arrParameter, 2)
If cmd.Parameters(i).Name = arrParameter(1, j) Then
cmd.Parameters(i) = IIf(arrParameter(0, j) = "", Null, arrParameter(0, j))
#If DEBUG_MODUS = 1 Then
Debug.Print cmd.Parameters(i).Name & " - " & cmd.Parameters(i).value
#End If
blFound = True
End If
Next
End If
Next
If cmd.Parameters.Count = 0 And UBound(arrParameter, 2) >= 0 Then
For i = 0 To UBound(arrParameter, 2)
If Not IsNumeric(arrParameter(0, i)) Then
'adVarBinary
If TypeName(arrParameter(0, i)) = "Byte()" Then
iType = adLongVarBinary
Else
iType = adVarChar
End If
Else
iType = adInteger
End If
Set para = cmd.CreateParameter(arrParameter(1, i), iType, adParamInput, 250)
cmd.Parameters.Append para
cmd.Parameters(arrParameter(1, i)) = arrParameter(0, i)
Next
End If
End If
End If
If InStr(1, sSQL, "?", vbTextCompare) > 0 Then
For i = 0 To UBound(arrParameter, 2)
cmd.Parameters(i) = arrParameter(0, i)
Next
End If
Set ADO_OpenParameterQuerySTR = New ADODB.Recordset
If (async) Then
ADO_OpenParameterQuerySTR.Open cmd, , adOpenStatic, adLockOptimistic, adAsyncExecute
Else
ADO_OpenParameterQuerySTR.Open cmd, , adOpenStatic, adLockOptimistic
End If
exit_me:
On Error GoTo 0
Exit Function
errHandler:
LogToFile currentModule, "ADO_OpenParameterQuerySTR", Err.Number & ", " & Err.Description
Debug.Print Err.Number & ", " & Err.Description
If Err.Number = -2147467259 Then
Set m_ADO_STR = Nothing
Application.Wait (Now + TimeValue("0:00:01"))
Resume Start
End If
If Err.Number = 3709 Then Resume Start
If Err.Number = -2147217911 Then
'No Rights to Execute
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure ADO_OpenParameterQuerySTR of Modul mdlDatabase"
End If
If Err.Number = -2147217871 Then
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure ADO_OpenParameterQuerySTR of Modul mdlDatabase"
End If
Resume exit_me
Resume
End Function
</code></pre>
<p><strong>SP code:</strong></p>
<pre><code>ALTER PROCEDURE [dbo].[Frozen_Generation]
(
@DATABASE as varchar(100),
@STEP as int
)
AS
--general
DECLARE @ParmDefinition NVARCHAR(500);
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @now DateTime
DECLARE @resStep1_1 int
DECLARE @resStep1_2 int
DECLARE @resStep1_1_ERR varchar(200)
DECLARE @resStep1_2_ERR varchar(200)
--backup
DECLARE @fileName VARCHAR(90);
DECLARE @db_name VARCHAR(20);
DECLARE @fileDate VARCHAR(20);
BEGIN
SET NOCOUNT ON;
SET @now = GETDATE()
if (@STEP=1) begin
SET @ParmDefinition = N'@SettingsValueBIT int, @SettingsName varchar(100), @UpdatedOn smalldatetime';
SET @SQLQuery =
N'use ' + @DATABASE + ';
UPDATE dbo.A_ConfigSettings set SettingsValueBIT=@SettingsValueBIT, UpdatedOn=@UpdatedOn where SettingsName=@SettingsName'
EXECUTE @resStep1_1 = sp_executesql @SQLQuery, @ParmDefinition, @SettingsValueBIT=0, @SettingsName='APP_Status',@UpdatedOn=@now;
-- Make backup (If I comment this block, I got 1 row in the recordset)
BEGIN TRY
SET @fileName = 'E:\backups\'; -- change to the relevant path
SET @db_name = 'frozenwizard'; -- change to the relevant database name
SET @fileDate = CONVERT(VARCHAR(20), GETDATE(),112);
SET @fileName = @fileName + @db_name + '_' + RTRIM(@fileDate) + '.bak';
SET @SQLQuery = N'BACKUP DATABASE '+@DATABASE+' TO DISK = ''' + @fileName + ''''
EXECUTE @resStep1_2 = sp_executesql @SQLQuery
END TRY
BEGIN CATCH
SELECT @resStep1_2=ERROR_NUMBER(), @resStep1_2_ERR=ERROR_MESSAGE();
END CATCH
SELECT
@resStep1_1 as resStep1_1, coalesce(@resStep1_1_ERR,'') as resStep1_1_ERR
@resStep1_2 as resStep1_2, coalesce(@resStep1_2_ERR,'') as resStep1_2_ERR
end
END
</code></pre>
| 3 | 3,484 |
plotting input data in simmr and being able to change colors of food sources and consumer group data
|
<p>regarding stable isotope analysis based on package simmr. I am interested in plotting the input data but chosing my own colors for food sources and consummer data. The example for multiple groups in the help section automatically choses the colors.</p>
<p>I would like to know if anyone can help me understand how to modify the command plot(simmr_4,group=1:8,title='Isospace plot of Inger et al Geese data') in the example so that I can choose my own colors for both food sources and consumer group data.</p>
<p>right now I dont have any data, but expecting data collection in the future. I am currently working on the data and example from the simmr author, the one thing I need is to be able to change the points colors</p>
<p>here's the authors data and example which can be found be simple using help on r for plot.simmr</p>
<pre><code>mix = matrix(c(-11.36, -11.88, -10.6, -11.25, -11.66, -10.41,
-10.88, -14.73, -11.52, -15.89, -14.79, -17.64, -16.97, -17.25,
-14.77, -15.67, -15.34, -15.53, -17.27, -15.63, -15.94, -14.88,
-15.9, -17.11, -14.93, -16.26, -17.5, -16.37, -15.21, -15.43,
-16.54, -15, -16.41, -15.09, -18.06, -16.27, -15.08, -14.39,
-21.45, -22.52, -21.25, -21.84, -22.51, -21.97, -20.23, -21.64,
-22.49, -21.91, -21.65, -21.37, -22.9, -21.13, -19.33, -20.29,
-20.56, -20.87, -21.07, -21.69, -21.17, -21.74, -22.69, -21.06,
-20.42, -21.5, -20.15, -21.99, -22.3, -21.71, -22.48, -21.86,
-21.68, -20.97, -21.91, -19.05, -22.78, -22.36, -22.46, -21.52,
-21.84, -21.3, -21.39, -22.1, -21.59, -20.14, -20.67, -20.31,
-20.07, -21.2, -20.44, -22.06, -22.05, -21.44, -21.93, -22.47,
-22.27, -22.19, -22.81, -20.48, -22.47, -18.06, -20.72, -20.97,
-19.11, -18.4, -20.45, -21.2, -19.74, -20.48, -21.48, -17.81,
-19.77, -22.56, -14.72, -12.21, -12.35, -13.88, -14.43, -14.65,
-13.9, -14.12, -10.88, -10.44, -15.33, -13.78, -13.98, -15.22,
-15.25, -15.76, -15.78, -15.49, -13.02, -15.3, -15.55, -14.35,
-14.99, -14.83, -16.18, -15.01, -12.87, -14.67, -13.84, -14.89,
-13.33, -15.04, -14.29, -15.62, -13.99, -15.06, -15.06, -15,
-14.55, -13.32, -14.34, -14.47, -14.31, -14.18, -16.18, -16.25,
-15.92, -15.35, -14.29, -15.92, -15.35, -20.22, -21.4, -19.97,
-20.78, -20.61, -20.58, -20.19, -20.71, -20.59, -20.09, -19.37,
-20.41, -20.84, -20.75, -20.29, -20.89, -19.69, -20.41, -21.24,
-19.33, -25.87, -25.4, -27.23, -27.52, -24.55, -17.36, -24.7,
-27.76, -28.92, -25.98, -26.77, -28.76, -27.7, -24.75, -25.47,
-26.58, -28.94, -29.13, -26.65, -28.04, -27.5, -29.28, -27.85,
-27.41, -27.57, -29.06, -25.98, -28.21, -25.27, -14.43, -27.4,
-27.76, -28.45, -27.35, -28.83, -29.39, -28.86, -28.61, -29.27,
-20.32, -28.21, -26.3, -28.27, -27.75, -28.55, -27.38, -29.13,
-28.66, -29.02, -26.04, -26.06, -28.52, -28.51, -27.93, -29.07,
-28.41, -26.42, -27.71, -27.75, -24.28, -28.43, -25.94, -28,
-28.59, -22.61, -27.34, -27.35, -29.14, 10.22, 10.37, 10.44,
10.52, 10.19, 10.45, 9.91, 11.27,
9.34, 11.68, 12.29, 11.04, 11.46, 11.73, 12.29, 11.79, 11.49,
11.73, 11.1, 11.36, 12.19, 11.03, 11.21, 10.58, 11.61, 12.16,
10.7, 11.47, 12.07, 11.75, 11.86, 12.33, 12.36, 11.13, 10.92,
12.42, 10.95, 12.28, 11.04, 10.76, 10.99, 10.78, 11.07, 10.2,
11.67, 7.53, 10.65, 10.58, 11.13, 7.73, 10.79, 10.47, 10.82,
10.41, 11.1, 10.95, 10.76, 10.83, 10.25, 10.52, 9.94, 9.94,
11.61,
10.65, 10.76, 11.11, 10.2, 11.27, 10.21, 10.88, 11.21, 11.36,
10.75, 12.38, 11.16, 11.57, 10.79, 11.13, 10.72, 10.99, 10.38,
10.95, 10.75, 10.75, 11.05, 10.66, 10.61, 10.9, 11.14, 10.33,
10.83, 10.75, 9.18, 9.03, 9.05, 8.6, 8.29, 10.32, 10.28, 6.47,
11.36, 10.75, 11.13, 11.37, 10.86, 10.54, 10.39, 10.66, 9.99,
11.65, 11.02, 10.67, 8.15, 11.12, 10.95, 11.2, 10.76, 11.32,
10.85, 11.74, 10.46, 10.93, 12.3, 10.67, 11.51, 10.56, 12.51,
13.51, 11.98, 12.2, 10.48, 12.4, 13, 11.36, 12.08, 12.39, 12.28,
12.6, 11.3, 11.1, 11.42, 11.49, 12, 13.35, 11.97, 13.35, 12.75,
12.55, 12.3, 12.51, 12.61, 10.98, 11.82, 12.27, 12.11, 12.11,
12.89, 12.99, 12.29, 11.89, 12.74, 12.29, 11.89, 10.56, 9.27,
10.54, 10.97, 10.46, 10.56, 10.86, 10.9, 11.06, 10.76, 10.64,
10.94, 10.85, 10.45, 11.15, 11.23, 11.16, 10.94, 11.2, 10.71,
9.55, 8.6, 9.67, 8.17, 9.81, 10.94, 9.49, 9.46, 7.94, 9.77,
8.07,
8.39, 8.95, 9.83, 8.51, 8.86, 7.93, 8, 8.33, 8, 9.39, 8.01,
7.59,
8.26, 9.49, 8.23, 9.1, 8.21, 9.59, 9.37, 9.47, 8.6, 8.23, 8.39,
8.24, 8.34, 8.36, 7.22, 7.13, 10.64, 8.06, 8.22, 8.92, 9.35,
7.32, 7.66, 8.09, 7.3, 7.33, 7.33, 7.36, 7.49, 8.07, 8.84,
7.93,
7.94, 8.74, 8.26, 9.63, 8.85, 7.55, 10.05, 8.23, 7.74, 9.12,
7.33, 7.54, 8.8), ncol=2, nrow=251)
colnames(mix) = c('d13C','d15N')
s_names = c("Zostera", "Grass", "U.lactuca", "Enteromorpha")
s_means = matrix(c(-11.17, -30.88, -11.17,
-14.06, 6.49, 4.43, 11.19, 9.82), ncol=2, nrow=4)
s_sds = matrix(c(1.21, 0.64, 1.96, 1.17, 1.46, 2.27, 1.11, 0.83), ncol=2, nrow=4)
c_means = matrix(c(1.63, 1.63, 1.63, 1.63, 3.54, 3.54, 3.54, 3.54), ncol=2, nrow=4)
c_sds = matrix(c(0.63, 0.63, 0.63, 0.63, 0.74, 0.74, 0.74, 0.74), ncol=2, nrow=4)
conc = matrix(c(0.36, 0.4, 0.21, 0.18, 0.03, 0.04, 0.02, 0.01), ncol=2, nrow=4)
grp = as.integer(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8))
# Load this in:
simmr_4 = simmr_load(mixtures=mix,
source_names=s_names,
source_means=s_means,
source_sds=s_sds,
correction_means=c_means,
correction_sds=c_sds,
concentration_means = conc,
group=grp)
# Print
simmr_4
# Plot
plot(simmr_4,group=1:8,title='Isospace plot of Inger et al Geese data')
</code></pre>
<p>any help is appreciated as I have tried various things but none work </p>
| 3 | 4,746 |
"Standard" Windows fix does not resolve SSL issue. Why?
|
<p>I am having issues running a app locally with gcloud on a windows 10 machine. I get the following error:</p>
<pre><code>C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:933:in `connect_nonblock': SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (Faraday::SSLError)
from C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:933:in `connect'
from C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:863:in `do_start'
from C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:852:in `start'
from C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:1398:in `request'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/faraday-0.9.2/lib/faraday/adapter/net_http.rb:82:in `perform_request'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/faraday-0.9.2/lib/faraday/adapter/net_http.rb:40:in `block in call'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/faraday-0.9.2/lib/faraday/adapter/net_http.rb:87:in `with_net_http_connection'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/faraday-0.9.2/lib/faraday/adapter/net_http.rb:32:in `call'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/faraday-0.9.2/lib/faraday/request/url_encoded.rb:15:in `call'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/faraday-0.9.2/lib/faraday/rack_builder.rb:139:in `build_response'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/faraday-0.9.2/lib/faraday/connection.rb:377:in `run_request'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/faraday-0.9.2/lib/faraday/connection.rb:177:in `post'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/signet-0.7.2/lib/signet/oauth_2/client.rb:960:in `fetch_access_token'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/signet-0.7.2/lib/signet/oauth_2/client.rb:998:in `fetch_access_token!'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/googleauth-0.5.1/lib/googleauth/signet.rb:69:in `fetch_access_token!'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/gcloud-0.7.2/lib/gcloud/credentials.rb:58:in `initialize'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/gcloud-0.7.2/lib/gcloud/credentials.rb:84:in `new'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/gcloud-0.7.2/lib/gcloud/credentials.rb:84:in `default'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/gcloud-0.7.2/lib/gcloud/datastore.rb:62:in `datastore'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/gcloud-0.7.2/lib/gcloud.rb:106:in `datastore'
from app.rb:21:in `<main>'
</code></pre>
<p>I have searched for the answer to this question. Here is a good example of an answer to this question:
<a href="https://github.com/lostisland/faraday/issues/392" rel="nofollow">https://github.com/lostisland/faraday/issues/392</a></p>
<p>The answer boils down to I need to have a pem file and tell Ruby where it is with the environment variable SSL_CERT_FILE.</p>
<p>In my case it is not working.</p>
<p>How would I fix this???</p>
| 3 | 1,357 |
Zxing QR Reader doesn't take focus again
|
<p>I have made an App using <strong>zxing library for QR reader</strong>.</p>
<p><strong>My problem is</strong> When the SCAN activity starts it takes focus of whatever is in the view finder and then refuses to take focus again if placed on anything else. Please help.</p>
<h2>main class</h2>
<pre><code>public class main extends Activity {
final Context context = this;
final Activity activity = this;
Button scanButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
scanButton = (Button) findViewById(R.id.button1);
scanButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
// IntentIntegrator integrator = new IntentIntegrator(activity);
// integrator.initiateScan();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// IntentResult scanResult =
// IntentIntegrator.parseActivityResult(requestCode, resultCode,
// intent);
// if (scanResult != null) { // handle scan result
// String contents=scanResult.getContents();
// }
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Scan Result");
// set dialog message
alertDialogBuilder.setMessage(contents).setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked,
// close
// current activity
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
}
</code></pre>
<h2>manifest.xml</h2>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.scanner.demo" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.CAMERA" />
<application android:icon="@drawable/launch_icon"
android:label="@string/app_name">
<activity android:name=".main" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.google.zxing.client.android.CaptureActivity"
android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="com.google.zxing.client.android.SCAN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
<p>I need the camera to take focus again after some time. Where do i make the necessary changes ?</p>
| 3 | 2,690 |
Errors during bundle install
|
<p>All of a sudden I've been getting the following error when trying to do a bundle install.</p>
<pre><code>/Users/Ken/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': /Users/Ken/.rvm/gems/ruby-1.9.2-p290@global/gems/bundler-1.0.21/lib/bundler/vendor/thor/core_ext/hash_with_indifferent_access.rb:76: syntax error, unexpected $end, expecting keyword_end (SyntaxError)
from /Users/Ken/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/Ken/.rvm/gems/ruby-1.9.2-p290@global/gems/bundler-1.0.21/lib/bundler/vendor/thor/base.rb:1:in `<top (required)>'
from /Users/Ken/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/Ken/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/Ken/.rvm/gems/ruby-1.9.2-p290@global/gems/bundler-1.0.21/lib/bundler/vendor/thor.rb:1:in `<top (required)>'
from /Users/Ken/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/Ken/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/Ken/.rvm/gems/ruby-1.9.2-p290@global/gems/bundler-1.0.21/lib/bundler/vendored_thor.rb:6:in `<top (required)>'
from /Users/Ken/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/Ken/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/Ken/.rvm/gems/ruby-1.9.2-p290@global/gems/bundler-1.0.21/lib/bundler/cli.rb:1:in `<top (required)>'
from /Users/Ken/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/Ken/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/Ken/.rvm/gems/ruby-1.9.2-p290@global/gems/bundler-1.0.21/bin/bundle:12:in `<main>'
</code></pre>
| 3 | 1,031 |
Trie Tree. Unable to access memory
|
<p>I am a beginner at C++ and am have some issues with 2 separate errors. Unable to access memory and stack overflow.</p>
<p>This is my implementation for a Trie Tree, using pointers, of words containing characters a-z. When running tests, I can successfully add several hundred, or even thousands of nodes without issue, until it eventually crashes. Error: Unable to access memory. I more often get this error when I am trying to run a query and use the "isAWord" function. I also get a stack overflow when I try to run the deconstructor. Any help is appreciate, as I've spent 2 days trying to debug with little success.</p>
<pre><code>#include "Trie.h"
#include <iostream>
#include <iterator>
#include <sstream>
using namespace std;
//sets up tree
Trie::Trie()
{
for (int i = 0; i < ALPH; i++)
this->childs[i] = nullptr;
endNode = false;
}
//add 'userInput' string to trie
void Trie::addAWord(std::string userInput)
{
Trie* start = this;
for (int i = 0; i < userInput.length(); i++)
{
int index = userInput[i] - 'a';
if (start->childs[index] == nullptr)
start->childs[index] = new Trie();
start = start->childs[index];
}
start->endNode = true;
}
//returns true if 'wordFind' is in tree
bool Trie::isAWord(std::string wordFind)
{
if (this == nullptr)
return false;
Trie* start = this;
for (int i = 0; i < wordFind.length(); i++)
{
int index = wordFind[i] - 'a';
start = start->childs[index];
if (start == nullptr)
return false;
}
return start->endNode;
}
//returns a vector containing the words in tree with prefix 'prefFind'
vector<std::string> Trie::allWordsStartingWithPrefix(std::string prefFind)
{
string pres = PrefixRec(prefFind,*this);
stringstream preStream(pres);
istream_iterator<std::string> begin(preStream), end;
vector<std::string> stringSet(begin, end);
copy(stringSet.begin(), stringSet.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
return stringSet;
}
//helper method for AllWordsStartingWithPrefix
std::string Trie::PrefixRec(std::string& key, Trie const temp)
{
if (temp.endNode)
return(key + " ");
for (char index = 0; index < ALPH; ++index)
{
index = key[index] - 'a';
Trie const* curChild = temp.childs[index];
if (curChild)
{
key.push_back(index);
PrefixRec(key, *curChild);
key.pop_back();
}
}
}
//copy cons and assignment op
Trie& Trie::operator=(const Trie& other)
{
Trie* newPtr = new Trie(other);
other.~Trie();
return *newPtr;
}
//deconstructor
Trie::~Trie()
{
if (this == nullptr)
return;
for (int i = 0; i < ALPH; i++)
{
if (childs[i] != nullptr)
childs[i]->~Trie();
}
delete this;
return;
}
#include <iostream>
#include <vector>
#include <string>
#define ALPH 26
class Trie
{
public:
bool endNode;
Trie* childs[ALPH];
Trie();
void addAWord(std::string key);
bool isAWord(std::string key);
std::vector<std::string> allWordsStartingWithPrefix(std::string key);
Trie& operator=(const Trie& other);
std::vector<std::string> wordsWithWildcardPrefix(std::string);
std::string PrefixRec(std::string& key, Trie const temp);
~Trie();
};
</code></pre>
| 3 | 1,490 |
Twisted upload muliple files key error
|
<p>I'm attempting to write a Twisted Webserver in Python 3.6 that can upload multiple files but being fairly new to both Python and things Web I have ran into an issue I don't understand and I also do not find any good examples relating to multiple file upload.</p>
<p>With the following code I get</p>
<pre><code>from twisted.web import server, resource
from twisted.internet import reactor, endpoints
import cgi
class Counter(resource.Resource):
isLeaf = True
numberRequests = 0
def render_GET(self, request):
print("GET " + str(self.numberRequests))
self.numberRequests += 1
# request.setHeader(b"content-type", b"text/plain")
# content = u"I am request #{}\n".format(self.numberRequests)
content = """<html>
<body>
<form enctype="multipart/form-data" method="POST">
Text: <input name="text1" type="text" /><br />
File: <input name="file1" type="file" multiple /><br />
<input type="submit" />
</form>
</body>
</html>"""
print(request.uri)
return content.encode("ascii")
def render_POST(selfself, request):
postheaders = request.getAllHeaders()
try:
postfile = cgi.FieldStorage(
fp=request.content,
headers=postheaders,
environ={'REQUEST_METHOD': 'POST',
# 'CONTENT_TYPE': postheaders['content-type'], Gives builtins.KeyError: 'content-type'
}
)
except Exception as e:
print('something went wrong: ' + str(e))
filename = postfile["file"].filename #file1 tag also does not work
print(filename)
file = request.args["file"][0] #file1 tag also does not work
endpoints.serverFromString(reactor, "tcp:1234").listen(server.Site(Counter()))
reactor.run()
</code></pre>
<p>Error log</p>
<pre><code>C:\Users\theuser\AppData\Local\conda\conda\envs\py36\python.exe C:/Users/theuser/PycharmProjects/myproject/twweb.py
GET 0
b'/'
# My comment POST starts here
Unhandled Error
Traceback (most recent call last):
File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\http.py", line 1614, in dataReceived
finishCallback(data[contentLength:])
File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\http.py", line 2029, in _finishRequestBody
self.allContentReceived()
File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\http.py", line 2104, in allContentReceived
req.requestReceived(command, path, version)
File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\http.py", line 866, in requestReceived
self.process()
--- <exception caught here> ---
File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\server.py", line 195, in process
self.render(resrc)
File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\server.py", line 255, in render
body = resrc.render(self)
File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\resource.py", line 250, in render
return m(request)
File "C:/Users/theuser/PycharmProjects/myproject/twweb.py", line 42, in render_POST
filename = postfile["file"].filename #file1 tag also does not work
File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\cgi.py", line 604, in __getitem__
raise KeyError(key)
builtins.KeyError: 'file'
</code></pre>
<p>I don't understand how to get hold of the file or files so I can save them uploaded after the form Submit in render_POST. This post <a href="https://stackoverflow.com/questions/11553751/twisted-web-keep-request-data-after-responding-to-client">SO</a> appears to not have this problem. The final app should be able to do this asynchronous for multiple users but before that I would be happy to get just a simple app working.</p>
<p>Using conda on Windows 10 with Python 3.6</p>
| 3 | 1,645 |
Shift contents of array using parameters in C++
|
<p>I have been playing around with a bit of code for the past few weeks. The code is a display of the number 1. I want to essentially create a dot matrix style print out, where the 1 is continuously shifted to the right.
Here is where I am so far:</p>
<pre><code>#include <iostream>
using namespace std;
/* use function to shift all characters one place to the right */
/* use a function to declare the characters of the fiqure */
int i, j;
int matrix([int i][int j]);//dont think this is right
</code></pre>
<p>I have declared my variables, and the matrix with the parameters I and j </p>
<pre><code>int main()
{
//should the matrix be a global function, therefore can be accessed by the move function?
/* the matrix is contained within the matrix function. The goal of main, is to manipulate
the matrix to transponse the elements to the next column*/
// 8 rows and 13 columns
for (i = 0; i < 8; i++)
{
int p = (j + 3)%13;
for (j = p; j < 13 ; j++)
{
matrix[i][j] = matrix[i][j + 3];
//priting out the matrix
cout << matrix[i][j];
}
cout << "\n";
}
cout << endl;
}
int matrix(int i, int j)
/* this function sets up the matrix and returns the value of the matrix.
this function should simply be a display function */
{
int matrix[8][13] = { { 0,1,1,1,1,1,0,0,0,0,0,0,0 },
{ 1,1,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 } };
//display the elements
for (i = 0; i < 8; i++)
{
for (j = 0; j < 13; j++)
{
//priting out the matrix
cout << matrix[i][j];
}
cout << "\n";
}
cout << endl;
return matrix[i][j];
}
</code></pre>
<p>Here is the main function, where I attempt to assign actual parameters for the matrix and pass them to the matrix display. The main function specifically defines a variable ‘p’ which (the plan is anyway) to use this variable to cause a shift to the right.
I am using the modulo 13 operator to attempt to clear (or return to 0) values after the shift, so the 1 appears to move across the matrix</p>
<p>In addition to the functions above, I have included the last bits from my code which are essentially notes and ideas that I am attempting now. </p>
<pre><code>/*
int array_size = sizeof(matrix) / sizeof(matrix[0]);
for (i = 0; i < 8; i++)
{
for (j = array_size-1; j > 0; j--)
{
matrix[j] = matrix[j - 1];
}
matrix[0]=
cout << "\n";
}
}
*/
/*
int x = i;
int p = (j + 3) % 13;
int matrix(x, p);
return 0;
*/
</code></pre>
<p>thanks in advance for any help or guidance :)</p>
| 3 | 1,285 |
C++ on Solaris: How to cope with "Formal argument" wrongly passed error?
|
<p>I am trying to compile the SMT solver Z3 (Version 4.5.0) from Microsoft Research on a Solaris 10 (Sparc) with Solaris Studio 12.3 (and this is due to constraints that I cannot change, so please do not hint to gcc/g++).</p>
<p>I already had to make some (more or less trivial) code changes in order to come to the error I am opposed with now:</p>
<pre><code>"../src/util/map.h", line 54: Error: Formal argument p of type const std::pair<expr*, int>& in call to pair_hash<obj_ptr_hash<expr>, int_hash>::operator()(const std::pair<expr*, int>&) const is being passed const std::pair<expr*, bool>.
"../src/util/hashtable.h", line 155: Where: While instantiating "table2map<default_map_entry<std::pair<expr*, bool>, bool>, pair_hash<obj_ptr_hash<expr>, int_hash>, default_eq<std::pair<expr*, bool>>>::entry_hash_proc::operator()(const _key_data<std::pair<expr*, bool>, bool>&) const".
"../src/util/hashtable.h", line 155: Where: Instantiated from core_hashtable<default_map_entry<std::pair<expr*, bool>, bool>, table2map<default_map_entry<std::pair<expr*, bool>, bool>, pair_hash<obj_ptr_hash<expr>, int_hash>, default_eq<std::pair<expr*, bool>>>::entry_hash_proc, table2map<default_map_entry<std::pair<expr*, bool>, bool>, pair_hash<obj_ptr_hash<expr>, int_hash>, default_eq<std::pair<expr*, bool>>>::entry_eq_proc>::get_hash(const _key_data<std::pair<expr*, bool>, bool>&) const.
"../src/util/hashtable.h", line 350: Where: Instantiated from non-template code.
1 Error(s) and 33 Warning(s) detected.
*** Error code 2
The following command caused the error:
CC -D_MP_INTERNAL -DNDEBUG -D_EXTERNAL_RELEASE -xldscope=hidden -c -xarch=sse2 -xvector=simd -D_NO_OMP_ -D _EXTERNAL_RELEASE -xO3 -xregs=frameptr -D_SUNOS_ -KPIC -xalias_level=any -features=zla -I../src/ast/rewriter/bit_blaster -I../src/ast/rewriter -I../src/ast -I../src/util -I../src/math/polynomial -I../src/math/automata -I../src/ast/simplifier -I../src/ast/macros -I../src/ast/normal_forms -I../src/cmd_context -I../src/solver -I../src/model -I../src/tactic -I../src/interp -I../src/smt/proto_model -I../src/smt/params -I../src/ast/pattern -I../src/parsers/smt2 -I../src/parsers/util -I../src/ast/substitution -I../src/math/grobner -I../src/math/euclid -I../src/math/simplex -I../src/ast/proof_checker -I../src/ast/fpa -osmt/smt_quick_checker.o ../src/smt/smt_quick_checker.cpp
make: Fatal error: Command failed for target `smt/smt_quick_checker.o'
bash-3.2$
</code></pre>
<p>The code causing the error can be found <a href="https://github.com/Z3Prover/z3/blob/z3-4.5.0/src/util/map.h" rel="nofollow noreferrer">here</a> at line 54.</p>
<p>I already poked around with a cast to <code>std::pair<expr*, int></code>, but as this is code used with different types, this lead to a similar error with <code>unsigned</code>.</p>
<p>Can anybody help me with this error?</p>
| 3 | 1,245 |
what's wrong with this simple code(objective c)?
|
<p>i want to download some webpages ,but this example code seems doesn't work.
it prints "begin download" and then exits,why the delegates method does not be executed?
what's wrong in the example code?
thanks</p>
<pre><code>main.m
#import <Foundation/Foundation.h>
#import "Test.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Test * test = [[Test alloc]init];
[test downloadData];
}
[NSThread sleepForTimeInterval:21.0f];
return 0;
}
Test.h
#import <Foundation/Foundation.h>
@interface Test : NSObject <NSURLConnectionDelegate,NSURLConnectionDataDelegate,NSURLConnectionDownloadDelegate>
@property (retain) NSMutableData * receivedData;
@property (retain) NSURLConnection * theConnection;
- (void) downloadData;
@end
Test.m
#import "Test.h"
@implementation Test
- (void) downloadData
{
NSURLRequest *theRequest=
[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.sf.net/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
_receivedData = [NSMutableData dataWithCapacity: 0];
[NSURLConnection sendSynchronousRequest:theRequest
returningResponse:nil
error:nil];
NSLog(@"begin download");
if (!_theConnection) {
_receivedData = nil;
// Inform the user that the connection failed.
}
}
enter code here
#pragma mark -
#pragma mark NSURLConnectionDataDelegateenter code here methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"1");
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"2");
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
NSLog(@"3");
_theConnection = nil;
_receivedData = nil;
// inform the user
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"4");
NSLog(@"Succeeded! Received %lu bytes of data",(unsigned long)[_receivedData length]);
_theConnection = nil;
_receivedData = nil;
}
-(void) connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
{
NSLog(@"5");
}
@end
</code></pre>
| 3 | 1,037 |
Wcf request is always coming with null parameters
|
<p>I am trying to call through a REST request in SOAPUI a WCF service running in localhost from Visual Studio.
My problem is that the request is coming with its properties to null.
Here is the JSON of the request:</p>
<pre><code> {
"request":{
"order":{
"uuid":"FEAEBDE7-8328-4E39-99F3-CD83F7405573",
"created":"2019-06-06T00:47:05+0200",
"created_from_client_timezone":"2019-06-05T23:47:05+0100",
"amount":1,
"currency":"978",
"paid":true,
"status":"SUCCESS",
"safe":true,
"refunded":0,
"additional":"Additional",
"service":"REDSYS",
"antifraud":"",
"customer":"IDInterno",
"transactions":[
{
"uuid":"168A6B19-2F9A-4367-A1E6-3E382CBCA3B3",
"created":"2019-06-06T00:54:52+0200",
"created_from_client_timezone":"2019-06-05T23:54:52+0100",
"operative":"AUTHORIZATION",
"amount":1,
"authorization":"188426",
"status":"SUCCESS",
"error":"NONE",
"source":{
"object":"CARD",
"uuid":"15DAE75D-121C-4396-AEB4-988B8455E103",
"type":"CREDIT",
"token":"ebc9b5ffa2efcf74197734a071192817e6f2a3fc15f49c4b1bdb6edc46b16e3ab4109498bff8e6ba00fb6d2bd1838afbea67095c4caaa2f46e4acf4d5851884c",
"brand":"VISA",
"country":"ES",
"holder":"teste",
"bin":454881,
"last4":"0004",
"expire_month":"12",
"expire_year":"20",
"additional":"",
"bank":"SERVIRED, SOCIEDAD ESPANOLA DE MEDIOS DE PAGO, S.A."
}
}
],
"token":"971857af7a43f021059fb2c7f62cb90e601fafe9a133062d0bca224bf6fc33899b68092288772331f33c310e422c51b0ca9bfb7bf7a6cad3af30473c992a7776",
"ip":"82.154.162.202"
},
"client":{
"uuid":"756CC6A3-933F-424B-B53B-39EC52118E7D"
}
}
}
</code></pre>
<p>This is my data contract in C #, drawn up by mapping JSON2CHARP:</p>
<pre><code>[Serializable, JsonObject, DataContract]
public partial class Request
{
[DataMember]
[JsonProperty("order", Required = Required.Always)]
public Order Order { get; set; }
[DataMember]
[JsonProperty("client", Required = Required.Always)]
public Client Client { get; set; }
}
[Serializable, JsonObject, DataContract]
public partial class Client
{
[DataMember]
[JsonProperty("uuid", Required = Required.Always)]
public string Uuid { get; set; }
}
[Serializable, JsonObject, DataContract]
public partial class Order
{
[DataMember]
[JsonProperty("uuid", Required = Required.Always)]
public string Uuid { get; set; }
[DataMember]
[JsonProperty("created", Required = Required.Always)]
public string Created { get; set; }
[DataMember]
[JsonProperty("created_from_client_timezone", Required = Required.Always)]
public string CreatedFromClientTimezone { get; set; }
[DataMember]
[JsonProperty("amount", Required = Required.Always)]
public long Amount { get; set; }
[DataMember]
[JsonProperty("currency", Required = Required.Always)]
[JsonConverter(typeof(ParseStringConverter))]
public long Currency { get; set; }
[DataMember]
[JsonProperty("paid", Required = Required.Always)]
public bool Paid { get; set; }
[DataMember]
[JsonProperty("status", Required = Required.Always)]
public string Status { get; set; }
[DataMember]
[JsonProperty("safe", Required = Required.Always)]
public bool Safe { get; set; }
[DataMember]
[JsonProperty("refunded", Required = Required.Always)]
public long Refunded { get; set; }
[DataMember]
[JsonProperty("additional", Required = Required.Always)]
public string Additional { get; set; }
[DataMember]
[JsonProperty("service", Required = Required.Always)]
public string Service { get; set; }
[DataMember]
[JsonProperty("antifraud", Required = Required.Always)]
public string Antifraud { get; set; }
[DataMember]
[JsonProperty("customer", Required = Required.Always)]
public string Customer { get; set; }
[DataMember]
[JsonProperty("transactions", Required = Required.Always)]
public List<Transaction> Transactions { get; set; }
[DataMember]
[JsonProperty("token", Required = Required.Always)]
public string Token { get; set; }
[DataMember]
[JsonProperty("ip", Required = Required.Always)]
public string Ip { get; set; }
}
[Serializable, JsonArray, DataContract]
public partial class Transaction
{
[DataMember]
[JsonProperty("uuid", Required = Required.Always)]
public string Uuid { get; set; }
[DataMember]
[JsonProperty("created", Required = Required.Always)]
public string Created { get; set; }
[DataMember]
[JsonProperty("created_from_client_timezone", Required = Required.Always)]
public string CreatedFromClientTimezone { get; set; }
[DataMember]
[JsonProperty("operative", Required = Required.Always)]
public string Operative { get; set; }
[DataMember]
[JsonProperty("amount", Required = Required.Always)]
public long Amount { get; set; }
[DataMember]
[JsonProperty("authorization", Required = Required.Always)]
[JsonConverter(typeof(ParseStringConverter))]
public long Authorization { get; set; }
[DataMember]
[JsonProperty("status", Required = Required.Always)]
public string Status { get; set; }
[DataMember]
[JsonProperty("error", Required = Required.Always)]
public string Error { get; set; }
[DataMember]
[JsonProperty("source", Required = Required.Always)]
public Source Source { get; set; }
}
[Serializable, JsonObject, DataContract]
public partial class Source
{
[DataMember]
[JsonProperty("object", Required = Required.Always)]
public string Object { get; set; }
[DataMember]
[JsonProperty("uuid", Required = Required.Always)]
public string Uuid { get; set; }
[DataMember]
[JsonProperty("type", Required = Required.Always)]
public string Type { get; set; }
[DataMember]
[JsonProperty("token", Required = Required.Always)]
public string Token { get; set; }
[DataMember]
[JsonProperty("brand", Required = Required.Always)]
public string Brand { get; set; }
[DataMember]
[JsonProperty("country", Required = Required.Always)]
public string Country { get; set; }
[DataMember]
[JsonProperty("holder", Required = Required.Always)]
public string Holder { get; set; }
[DataMember]
[JsonProperty("bin", Required = Required.Always)]
public long Bin { get; set; }
[DataMember]
[JsonProperty("last4", Required = Required.Always)]
public string Last4 { get; set; }
[DataMember]
[JsonProperty("expire_month", Required = Required.Always)]
[JsonConverter(typeof(ParseStringConverter))]
public long ExpireMonth { get; set; }
[DataMember]
[JsonProperty("expire_year", Required = Required.Always)]
[JsonConverter(typeof(ParseStringConverter))]
public long ExpireYear { get; set; }
[DataMember]
[JsonProperty("additional", Required = Required.Always)]
public string Additional { get; set; }
[DataMember]
[JsonProperty("bank", Required = Required.Always)]
public string Bank { get; set; }
}
</code></pre>
<p>This is my interface:</p>
<pre><code>[ServiceContract(Namespace = "Satellise.Integration.CardRegistrationWS", Name = "PGQCRMRegistrarTarjeta")]
public interface ICreditCardRegistration
{
[OperationContract(Name = "RegistrarTarjeta")]
[WebInvoke(UriTemplate = "RegistrarTarjeta/", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
ResponsePagaqui RegistrarTarjeta(Request request);
}
</code></pre>
<p>And this is my web.config file: </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<!-- SERVIDOR <add key="directoryLogPagaqui" value="C:\IntegrationLogEstacion\REST\" /> -->
<!-- PRUEBAS MI MÁQUINA--> <add key="directoryLogPagaqui" value="C:\Users\A753752\OneDrive - Atos\Documents\S A T E L I S E\prueba" />
<add key="saveAlwaysLog" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<system.serviceModel>
<services>
<service name="Satellise.Integration.CardRegistrationWS.PagaquiService" behaviorConfiguration="ServiceBehavior">
<endpoint binding="webHttpBinding" contract="Satellise.Integration.CardRegistrationWS.ICreditCardRegistration"
behaviorConfiguration="webHttp"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior" >
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
<behavior>
<!-- Para evitar revelar información de los metadatos, establezca los valores siguientes en false antes de la implementación -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- Para recibir detalles de las excepciones en los fallos, con el fin de poder realizar la depuración, establezca el valor siguiente en true. Para no revelar información sobre las excepciones, establézcalo en false antes de la implementación -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
Para examinar el directorio raíz de la aplicación web durante la depuración, establezca el valor siguiente en true.
Establézcalo en false antes de la implementación para evitar revelar información sobre la carpeta de aplicación web.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy autoDetect="True" bypassonlocal="False" />
</defaultProxy>
</system.net>
</configuration>
</code></pre>
<p>What am I doing wrong? I am not able to find why the request message is coming with both Order and Client null. </p>
| 3 | 6,139 |
function getClientOriginalName() on null Laravel
|
<p>Im trying to use Dropzone in my french laravel app (latest version) When I save my form I get the error</p>
<blockquote>
<p>Call to a member function getClientOriginalName() on null
I try to see if my request sent something with dd() but I get null</p>
</blockquote>
<p>This is my function on the controller</p>
<pre class="lang-php prettyprint-override"><code>public function enregistrer(Request $request){
$photo = $request->file('file');
$imageName = $photo->getClientOriginalName();
$image->move(public_path('images'),$imageName);
$demande = new Demande();
$demande->filename = $imageName;
$demande->cin= $request('cin');
$demande->apoge=$request('apoge');
$demande->generatedCode= uniqid();
$demande->save();
return redirect('/demande');
}
</code></pre>
<p>And this is my view</p>
<pre><code><!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- All for dropzone -->
<meta name="_token" content="{{csrf_token()}}" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js"></script>
<title>Submission E-Docs</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<!-- Styles -->
<style>
html, body {
background-color: #fff;
color: #636b6f;
font-family: 'Nunito', sans-serif;
font-weight: 200;
height: 100vh;
margin: 0;
}
.full-height {
height: 100vh;
}
.flex-center {
align-items: center;
display: flex;
justify-content: center;
}
.position-ref {
position: relative;
}
.top-right {
position: absolute;
right: 10px;
top: 18px;
}
.content {
text-align: center;
}
.title {
font-size: 84px;
}
.links > a {
color: #636b6f;
padding: 0 25px;
font-size: 13px;
font-weight: 600;
letter-spacing: .1rem;
text-decoration: none;
text-transform: uppercase;
}
.m-b-md {
margin-bottom: 30px;
}
</style>
</head>
<body>
<div class="flex-center position-ref full-height">
@if (Route::has('login'))
<div class="top-right links">
@auth
<a href="{{ url('/home') }}">Home</a>
@else
<a href="{{ route('login') }}">Login</a>
@if (Route::has('register'))
<a href="{{ route('register') }}">Register</a>
@endif
@endauth
</div>
@endif
<div class="content">
<form role="form" action="{{url('demande/store')}}" method="POST" enctype="multipart/form-data" class="dropzone" id="dropzone">
@csrf
<label> Votre CIN:</label>
<input type="text" name="cin"/>
<label> Votre Apogée:</label>
<input type="text" name="apoge"/>
<!-- <input name="file" type="file" multiple /> -->
<br>
<input type="submit" class="btn btn-outline-primary btn-lx" style="font-family:'Quicksand', sans-serif; font-size:20px "value="Créer">
</form>
</div>
</div>
<script type="text/javascript">
Dropzone.options.dropzone =
{
maxFilesize: 10,
renameFile: function (file) {
var dt = new Date();
var time = dt.getTime();
return time + file.name;
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 60000,
success: function (file, response) {
console.log(response);
},
error: function (file, response) {
return false;
}
};
</script>
</body>
</html>
</code></pre>
<p>I thought It was due the </p>
| 3 | 3,035 |
Changing launcher activity when the app is launched second time onwards android
|
<p>I am developing an android app where I have a launcher activity that takes the user's email id. When the user enters his email id he is redirected to another activity that asks for another user authentication in a <code>WebView</code>. After the user is successfully authenticated from this activity, the further execution starts. </p>
<p>Now, I want that after the user is authenticated on the second activity and he closes the app. Next time when he starts the app he should not see the launcher activity and get redirected to the second activity.</p>
<p>Is there any way to do this?
Thanks</p>
<p>My code:-</p>
<pre><code>Animation animTranslate = AnimationUtils.loadAnimation(Login.this, R.anim.translate);
animTranslate.setAnimationListener(new AnimationListener()
{
@Override
public void onAnimationStart(Animation arg0) { }
@Override
public void onAnimationRepeat(Animation arg0) { }
@Override
public void onAnimationEnd(Animation arg0)
{
if(LoadUserEmail()==null)
{
LoginBox.setVisibility(View.VISIBLE);
Animation animFade = AnimationUtils.loadAnimation(Login.this, R.anim.fade);
LoginBox.startAnimation(animFade);
}
else
{
Intent myIntent = new Intent(Login.this, Details1.class);
startActivity(myIntent);
}
}
});
public void onClick(View v)
{
// TODO Auto-generated method stub
// username, deviceId, deviceName parameters
boolean didItWork =true;
username = editUser.getText().toString().trim();
if(username.length()==0)
{
Toast.makeText(getApplicationContext(), "Please enter a valid email address", Toast.LENGTH_LONG).show();
didItWork = false;
}
else
{
isUserSaved = true;
didItWork = true;
SaveUsersEmail(username);
checkUsername = LoadUserEmail();
}
public void SaveUsersEmail(String username)
{
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("Username",
username).commit();
}
public String LoadUserEmail()
{
String username = PreferenceManager.getDefaultSharedPreferences(this).getString("Username",
"Please login");
return username;
}
</code></pre>
| 3 | 1,218 |
Why is my modified Pol01 running in batch mode works for all polarized photon states except for left circularly polarized photons?
|
<p>I am attempting to use Pol01 example to examine the angular distribution of initially polarized photons Compton scattering off G4_Si.<br />
I have had to include several lines of code in the SteppingAction.cc which will print out information like, for example, the Compton scattering angle and the photon's final kinetic energy.</p>
<p>The simulations seems to work well for horizontally and vertically polarized photons, linear polarized +- 45 degrees and right circularly polarized (RCP) photons. But when I try and run the simulation for left circuarly polarized (LCP) photons I get a segmentation fault part way through the printing of the information to my terminal window.</p>
<p>In macro code this is what I found</p>
<pre><code>### RCP (works)
# /gun/polarization 0. 0. 1.
### LCP ( Segmentation fault )
/gun/polarization 0. 0. -1.
### vertical ( works )
# /gun/polarization -1. 0. 0.
### horizontal ( works )
# /gun/polarization 1. 0. 0.
### LP ( 45 degrees ) (works)
# /gun/polarization 0. 1. 0.
### LP ( -45 degrees ) ( works )
# /gun/polarization 0. -1. 0.
/gun/particle gamma
#
/gun/energy 511 keV
</code></pre>
<p>However, above this code there is the following instruction</p>
<p><code>/polarization/volume/set theBox 0. 0. 0.08</code></p>
<p>If I set <code>0.08</code> to <code>0.</code> , then I do not get the segmentation fault. I would like help in figuring out why only LCP photons cause the segmentation fault?</p>
<p>FYI, the only extra code I included into Pol01 (in SteppingAction.cc) is the following</p>
<pre><code> // Inside this method you should access the track from the step object:
G4Track *aTrack = aStep->GetTrack();
// Then you should get the KineticEnergy of the track if the process is
// "Compton scattering" and if the volume remains the same in the next step.
// See the code lines below:
G4StepPoint* preStepPoint = aStep->GetPreStepPoint();
const G4VProcess* CurrentProcess = preStepPoint->GetProcessDefinedStep();
if (CurrentProcess != 0)
{
// To implement the next line, one needs to include " #include "G4VProcess.hh" "
// (See SteppingAction.cc in TestEm6)
const G4String & StepProcessName = CurrentProcess->GetProcessName();
// Get track ID for current processes
G4double TrackID = aStep->GetTrack()->GetTrackID();
if( (StepProcessName == "pol-compt")&&(TrackID==1) )
{
// processing hit when entering the volume
G4double kineticEnergy = aStep->GetTrack()->GetKineticEnergy();
auto EkinUnits = G4BestUnit(kineticEnergy, "Energy");
// Get energy in units of keV
G4double En = kineticEnergy/keV;
// Determine angle in radians
G4double thetaRad = std::acos( 2- 511/En );
// Place condition to reject Compton scattering at 0 rad.
// (This is to avoid nan results when dividing through by 2pisin(theta))
if ( (thetaRad > 0) && (thetaRad < pi))
{
// fill histogram id = 13 (angular spread (in radians) as a function of scattering angle)
// analysisManager->FillH1(13, thetaRad);
// get particle name that's undergone the Compton scattering
G4String ParticleName = aStep->GetTrack()->GetParticleDefinition()->GetParticleName();
// Find position (c.f. /examples/extended/medical/GammaTherapy) in CheckVolumeSD.cc
// G4ThreeVector pos = aStep->GetPreStepPoint()->GetPosition();
// G4double z = pos.z();
// Check if volume is sensitive detector
G4String fromVolume = aTrack->GetNextVolume()->GetName();
// see https://geant4-forum.web.cern.ch/t/get-particle-info-in-steppingaction-if-particle-pass-through-specific-volume/2863/2
// for possible solution for finding which volume the gamma is in
// G4String SDname = aStep->GetPostStepPoint()->GetSensitiveDetector()->GetName();
// FOR CHECKING
std::cout << "fromVolume: " << fromVolume
<< " Particle: " << ParticleName
<< " Process: " << StepProcessName
<< " Energy: " << EkinUnits
<< " Angle: " << thetaRad/degree << " deg." << std::endl;
}
}
}
</code></pre>
<p>Thank you for your time.
Peter</p>
| 3 | 1,803 |
How to open an uploaded file in another template - Django?
|
<p>my django app acts as an emailing service, emails that are sent are view-able and it's possible to send html emails. How do I display the html emails on the view-mail page rather than just displaying the name of the file ? (the following is the mail-view for an html email): <a href="https://i.stack.imgur.com/Pzdt4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pzdt4.png" alt="enter image description here"></a></p>
<p>How would I display the actual html in the body of this page?</p>
<p>This is my views.py:</p>
<pre><code>def outbox(request):
#Mail_Item.objects.all().delete()
if request.method == "POST" and request.POST.get('Username', False)!=False:
username = request.POST.get('Username')
password = request.POST.get('Password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
print(username + " has logged in")
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
else:
return render(request, '404.html')
elif request.POST.get('Username', False) == False and request.POST.get('mail_body_field', False) == False:
pass
elif request.method == "POST" and request.POST.get('mail_subject_field')!=False:
subject = request.POST.get('mail_subject_field')
body = request.POST['mail_body_field']
file = ""
try:
file = request.FILES['filename']
except:
pass
print("sending mail:")
for i in range(1, len(Res)+1):
y = Res['ID' + str(i)].email
print("sent to " + y )
msg = EmailMessage(subject, body, 'email@example.com', [y])
msg.content_subtype = "html"
if (str(file)) != "" and (str(file))[-4:] != 'html':
msg.attach_file(str(file))
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name=(str(file)))
obj.save()
print("email stored in database")
elif (str(file)) != "" and (str(file))[-4:] == 'html' :
uploaded_file = file
fs = FileSystemStorage()
fs.save((str(file)), uploaded_file)
html_message = render_to_string((str(file)), {'context': 'values'})
plain_message = strip_tags(html_message)
from_email = 'From <email2@example.com>'
mail.send_mail(subject, plain_message, from_email, [y], html_message=html_message)
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name=(str(file)))
obj.save()
else:
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name='None')
obj.save()
print("email stored in database")
#msg.send()
i += 1
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return HttpResponseRedirect('../templates/outbox.html', args, request)
else:
print("pleeeeeaassee")
return render(request, '404.html')
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
def login_page(request):
if request.method == "POST":
username = request.POST['sign-up-name']
email = request.POST['sign-up-email']
password = request.POST['sign-up-password']
user = User.objects.create_user(username, email, password)
user.save()
print(username + " has been added to the user database.")
else:
pass
return render(request, 'login.html')
def signup_page(request):
return render(request, 'signup.html')
def mail_view(request, id=None):
if id:
email = Mail_Item.objects.get(id=id)
args = {'email':email}
else:
pass
return render(request, 'mail-view.html', args)
def log_out(request):
logout(request)
return render(request, 'log-out.html')
def delete(request):
Mail_Item.objects.filter(id=id).delete()
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
</code></pre>
<p>This is the code for my mail-view template where I'd like to place the html that is being sent: </p>
<pre><code><div class="mail-view">
<h4 class="m-0">{{ email.subject }}</h4>
<div class="divid"></div>
<div class="media">
<div class="media-left">
<div class="avatar avatar-lg avatar-circle">
<img class="img-responsive" src="{% static '../static/assets/images/221.jpg' %}" alt="avatar"/>
</div><!-- .avatar -->
</div>
<div class="media-body">
<div class="m-b-sm">
<h4 class="m-0 inline-block m-r-lg">
<a href="#" class="title-color">Access Bank</a>
</h4>
</div>
<p><b>Attachment: </b>{{ email.file_name }}</p>
</div>
</div>
<div class="divid"></div>
<div class="row">
<div class="col-md-12">
<div class="m-h-lg lh-xl">
<p>{{ email.body }}</p>
</div>
</div>
</div>
</div>
</code></pre>
<p>Models.py: </p>
<pre><code> from django.db import models
class Details(models.Model):
email = models.CharField(max_length=200)
def __str__(self):
return self.email
class Mail_Item(models.Model):
subject = models.CharField(max_length=200)
body = models.CharField(max_length=300)
time = models.DateTimeField(auto_now=True)
user = models.CharField(max_length=15)
file_name = models.CharField(max_length=100, null=True, default=None)
def __str__(self):
template = '{0.subject} {0.body} {0.time} {0.user} {0.file_name}'
return template.format(self)
</code></pre>
| 3 | 3,097 |
Reaching the end of an array with a sequence of odd/even jumps
|
<p>I'm trying to understand a Python solution to a programming puzzle that seems to use dynamic programming. I am able to follow most of the solution, but I'm struggling a bit to really formalize the solution.</p>
<p>The problem is stated as follows:</p>
<blockquote>
<p>You are given an integer array <code>A</code>. From some starting index, you can
make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series
are called "odd" numbered jumps, and the (2nd, 4th, 6th, ...) jumps in
the series are called even numbered jumps. </p>
<p>You may jump <strong>forward</strong> from index <code>i</code> to index j (with <code>i < j</code>) in the following way: </p>
<ul>
<li><p>During <strong>odd</strong> numbered jumps (ie. jumps 1, 3, 5, ...), you jump to the index <code>j</code> such
that <code>A[i] <= A[j]</code> and <code>A[j]</code> is the <strong>smallest</strong> possible value. If there
are multiple such indexes <code>j</code>, you can only jump to the smallest such
index j. </p></li>
<li><p>During <strong>even</strong> numbered jumps (ie. jumps 2, 4, 6, ...), you jump
to the index <code>j</code> such that <code>A[i] >= A[j]</code> and <code>A[j]</code> is the <strong>largest</strong> possible
value. If there are multiple such indexes <code>j</code>, you can only jump to the
<strong>smallest</strong> such index <code>j</code>.</p></li>
<li><p>It may be the case that for some index <code>i</code> are <strong>no legal</strong> jumps.</p></li>
</ul>
<p>A starting index is <strong>good</strong> if, starting from that index, you can reach the end of the array by jumping some number of times (possibly 0 or more than once.) </p>
<p>We ask that you return the number of <strong>good starting</strong> indices.</p>
</blockquote>
<p>Below I show a solution in Python to this problem that a few authors have published. I understand how it builds <code>oddnext</code> and <code>evennext</code> and what these arrays technically hold (the index location one jumps to from that index with an odd or even jump). What I don't understand is how the last loop works, and what's the precise dynamic programming formulation behind it.</p>
<pre><code>def odd_even_jumps(self, A):
N = len(A)
def make(B):
ans = [None] * N
stack = [] # invariant: stack is decreasing
for i in B:
while stack and i > stack[-1]:
ans[stack.pop()] = i
stack.append(i)
return ans
B = sorted(range(N), key = lambda i: A[i])
oddnext = make(B)
B.sort(key = lambda i: -A[i])
evennext = make(B)
odd = [False] * N
even = [False] * N
odd[N-1] = even[N-1] = True
# Why does this loop start from the end?
for i in range(N-2, -1, -1):
if oddnext[i] is not None:
odd[i] = even[oddnext[i]]
if evennext[i] is not None:
even[i] = odd[evennext[i]]
return sum(odd)
</code></pre>
| 3 | 1,103 |
NoMethodError in Admin::ApartmentPostsController#create
|
<p>I am using active admin for my admin panel in Ruby on Rails website. I have this code on my ApartmentPost resource.</p>
<pre><code>ActiveAdmin.register ApartmentPost do
permit_params :title, :max_stay, :min_stay, :bed_configuration, :number_of_guests,
:features, :description, :admin_user_id, :apartment_number,:latitude, :longitude, :clean_fee, :country, :location, photos: []
form(html: { multipart: true }) do |f|
f.inputs do
f.input :title
f.input :max_stay
f.input :min_stay
f.input :bed_configuration
f.input :number_of_guests
f.input :features
f.input :description
f.input :country
f.input :location
f.input :apartment_number
f.input :latitude
f.input :longitude
f.input :clean_fee
f.input :admin_user_id, as: :hidden, input_html: {value: current_admin_user.id}
f.file_field :photos, multiple: true
end
f.actions
end
</code></pre>
<p>So the error I am getting is while creating a new ApartmentPost. The error is:</p>
<p><a href="https://i.stack.imgur.com/Lpvl2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lpvl2.png" alt="enter image description here"></a></p>
<p>I had created a column called rate in AparmentPost but now it is already removed. Still it gives this error.</p>
<p>Here's the table from schema.rb:</p>
<pre><code>create_table "apartment_posts", force: :cascade do |t|
t.integer "admin_user_id", null: false
t.integer "max_stay", null: false
t.string "bed_configuration", null: false
t.integer "number_of_guests", null: false
t.string "features", null: false
t.string "description", null: false
t.json "photos"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "title", null: false
t.string "country", null: false
t.string "apartment_number", null: false
t.string "latitude"
t.string "longitude"
t.integer "min_stay", null: false
t.string "location", null: false
t.integer "clean_fee", default: 100, null: false
t.integer "property_type_id"
t.index ["admin_user_id"], name: "index_apartment_posts_on_admin_user_id", using: :btree
t.index ["property_type_id"], name: "index_apartment_posts_on_property_type_id", using: :btree
end
</code></pre>
<p>Here's the code in routes.rb</p>
<pre><code>devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
</code></pre>
<p>I am new in Rails and Active Admin. I tried searching the solution everywhere even tried uninstalling active_admin gem and installing again and removing apartment_post resource and generating it again but none og them worked. </p>
| 3 | 1,202 |
Recursive join count - Oracle
|
<p>I have this Oracle db structure (something like forum, ok):</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE sections
(
section_id INTEGER NOT NULL ,
parent_section INTEGER NULL ,
section_name VARCHAR2(256) NOT NULL ,
section_desc VARCHAR2(1024) NULL
);
</code></pre>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE topics
(
topic_id INTEGER NOT NULL ,
topic_name VARCHAR2(256) NOT NULL ,
section_id INTEGER NOT NULL
);
</code></pre>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE messages
(
msg_id INTEGER NOT NULL ,
msg_text CLOB NOT NULL ,
topic_id INTEGER NULL ,
msg_date DATE NOT NULL ,
user INTEGER NOT NULL
);
</code></pre>
<p>As you can see, <code>sections</code> have hierarchical structure (by <code>parent_section</code> column).</p>
<p>I want to make two queries:</p>
<ol>
<li>Get topics count in section by section id, considering all child sections.</li>
<li>Same with messages instead of topics.</li>
</ol>
<p>Ok, I'm trying to write first query, but even it doesn't work (return wrong count without errors), I have no idea why:
</p>
<pre><code>SELECT si, t.TOPIC_ID, COUNT(*)
FROM (
SELECT s.SECTION_ID si
FROM SECTIONS s
START WITH SECTION_ID = :sectionId
CONNECT BY PRIOR SECTION_ID = PARENT_SECTION
)
LEFT JOIN TOPICS t ON t.SECTION_ID = si
GROUP BY t.TOPIC_ID, si
</code></pre>
<p><strong>EDIT:</strong>
While I'm setting up SQL Fiddle, I got some solution.</p>
<p>Firstly, we should use <code>INNER JOIN</code> instead of <code>LEFT JOIN</code>, because we don't need records with <code>null</code> <code>topic_id</code>.</p>
<p>Secondly, query with <code>COUNT()</code> was wrong, it just returns same records with additional column <code>COUNT</code> with <code>1</code> value. Now I just use <code>SUM(1)</code>:
</p>
<pre><code>SELECT SUM(1)
FROM (
SELECT s.SECTION_ID si
FROM SECTIONS s
START WITH SECTION_ID = :sectionId
CONNECT BY PRIOR SECTION_ID = PARENT_SECTION
)
INNER JOIN TOPICS t ON t.SECTION_ID = si
GROUP BY 1
</code></pre>
<p><strong>But it still not ideal solution</strong>, if we pass section without topics as <code>START WITH SECTION_ID =</code> argument, we will get nothing as answer. It requires additional check in program for prevent <code>NullPointerException</code>.</p>
<p>Maybe someone know, how can we get <code>0</code> as answer in this case?</p>
<p>SQLFiddle: <a href="http://sqlfiddle.com/#!4/8c093/21" rel="nofollow">http://sqlfiddle.com/#!4/8c093/21</a></p>
| 3 | 1,082 |
How pagination works which is fetch from api in Nativescript
|
<p>I am not getting the concepts of how pagination works in load more requested data from json api. Even i am getting the data of first page but for remaining pages not getting. If I am using the two api for paging and fetching data but still not getting. Any one help me clear this concepts please..</p>
<p>main-view-model.js</p>
<pre><code>const httpModule = require("tns-core-modules/http");
var observableModule = require("tns-core-modules/data/observable");
function RegisterViewModel() {
var viewModel = observableModule.fromObject({
_sourceDataItems: [],
initDataItems: function () {
//This url for the pagination
var url1 = "https://example.org/api.php?action=query&gcmtitle=Category:xyz&pilimit=max&prop=pageimages&pithumbsize=200&generator=categorymembers&format=json&gcmcontinue=";
httpModule.getJSON(url1).then((r) => {
id = r.continue.gcmcontinue
gcm.push(id)
console.log(gcm)
var pageid = [];
for (var id in r.query.pages) {
pageid.push(id);
}
for (var i = 0; i < pageid.length; i++) {
if (r.query.pages[pageid[i]].thumbnail == null) {
let abc = {
ttt: r.query.pages[pageid[i]].title,
path1: "~/images/xyz.png"
}
this._sourceDataItems.push(abc)
}
else {
let aaa = {
ttt: r.query.pages[pageid[i]].title,
path1: r.query.pages[pageid[i]].thumbnail.source
}
this._sourceDataItems.push(aaa)
}
}
}, (e) => {
});
var gcm = [];
//This url for the fetching the data on scroll
for (var i = 0; i < gcm.length; i++) {
var url2 = "https://example.org/api.php?action=query&gcmtitle=Category:xyz&pilimit=max&prop=pageimages&pithumbsize=200&generator=categorymembers&format=json&gcmcontinue=" + gcm[i];
httpModule.getJSON(url2).then((r) => {
id= r.continue.gcmcontinue)
gcm.push(id)
console.log(r.continue.gcmcontinue)
var pageid = [];
for (var id in r.query.pages) {
pageid.push(id);
}
for (var i = 0; i < pageid.length; i++) {
//placeholder Image
if (r.query.pages[pageid[i]].thumbnail == null) {
let abc = {
ttt: r.query.pages[pageid[i]].title,
path1: "~/images/xyz.png"
}
this._sourceDataItems.push(abc)
}
else {
let aaa = {
ttt: r.query.pages[pageid[i]].title,
path1: r.query.pages[pageid[i]].thumbnail.source
}
this._sourceDataItems.push(aaa)
}
}
}, (e) => {
});
}
},
_DataItems: [],
addMoreItemsFromSource: function (chunkSize) {
let newItems = this._sourceDataItems.splice(0, chunkSize);
this._DataItems = this._DataItems.concat(newItems);
},
onLoadMoreItemsRequested: function (args) {
console.log("---load item called----");
const that = new WeakRef(this);
const listView = args.object;
if (this._sourceDataItems.length > 0) {
setTimeout(function () {
that.get().addMoreItemsFromSource(5);
listView.notifyLoadOnDemandFinished();
}, 100);
args.returnValue = true;
} else {
args.returnValue = false;
}
},
});
return viewModel;
}
exports.RegisterViewModel = RegisterViewModel;
</code></pre>
<p>Even loading of the data is working fine for page one. While passing the gcm continue id it wont take that please help me to clear this concept</p>
| 3 | 1,773 |
FTPS connection not closing properly (powershell script)
|
<p>I use <a href="https://gist.github.com/pbrumblay/6551936" rel="nofollow noreferrer">this function</a> to send a file via FTPS with a PowerShell script. It is a Filezilla Server.
It works fine, the file is written on the server, but the connection is not closed properly.</p>
<p>I get the following error :</p>
<pre><code>Exception when calling "Close" with "0" argument(s): "The remote server returned an error:
(425) Unable to open data connection."
At character C:\...\transfer.ps1:57: 3
+ $ftpStream.Close();
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Exception when calling "GetResponse" with "0" argument(s): "The remote server returned an error
: (425) Cannot open data connection."
At character C:\...\transfer.ps1:58 : 3
+ $resp = $req.GetResponse();
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Impossible to call a method in a Null expression.
At character C:\...\transfer.ps1:60 : 3
+ $resp.Close();
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation : (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
</code></pre>
<p>And on the server side :</p>
<pre><code>2022-02-08T11:32:42.864Z II [FTP Session 11 147.128.66.87] Session 0x1ab850b0090 with ID 11 created.
2022-02-08T11:32:42.864Z >> [FTP Session 11 147.128.66.87] AUTH TLS
2022-02-08T11:32:42.880Z << [FTP Session 11 147.128.66.87] 234 Using authentication type TLS.
2022-02-08T11:32:42.880Z II [FTP Session 11 147.128.66.87] TLS Handshake successful
2022-02-08T11:32:42.880Z II [FTP Session 11 147.128.66.87] Protocol: TLS1.2, Key exchange: ECDHE-X25519-ECDSA-SHA256, Cipher: AES-256-GCM, MAC: AEAD
2022-02-08T11:32:42.880Z >> [FTP Session 11 147.128.66.87] USER uploaduser
2022-02-08T11:32:42.880Z << [FTP Session 11 147.128.66.87] 331 Please, specify the password.
2022-02-08T11:32:42.880Z >> [FTP Session 11 147.128.66.87] PASS ****
2022-02-08T11:32:42.942Z << [FTP Session 11 147.128.66.87 uploaduser] 230 Login successful.
2022-02-08T11:32:42.942Z >> [FTP Session 11 147.128.66.87 uploaduser] PBSZ 0
2022-02-08T11:32:42.942Z << [FTP Session 11 147.128.66.87 uploaduser] 200 PBSZ=0
2022-02-08T11:32:42.942Z >> [FTP Session 11 147.128.66.87 uploaduser] PROT P
2022-02-08T11:32:42.942Z << [FTP Session 11 147.128.66.87 uploaduser] 200 Protection level set to P
2022-02-08T11:32:42.942Z >> [FTP Session 11 147.128.66.87 uploaduser] OPTS utf8 on
2022-02-08T11:32:42.942Z << [FTP Session 11 147.128.66.87 uploaduser] 202 UTF8 mode is always enabled. No need to send this command
2022-02-08T11:32:42.942Z >> [FTP Session 11 147.128.66.87 uploaduser] PWD
2022-02-08T11:32:42.942Z << [FTP Session 11 147.128.66.87 uploaduser] 257 "/" is current directory.
2022-02-08T11:32:42.942Z >> [FTP Session 11 147.128.66.87 uploaduser] TYPE I
2022-02-08T11:32:42.942Z << [FTP Session 11 147.128.66.87 uploaduser] 200 Type set to I
2022-02-08T11:32:42.942Z >> [FTP Session 11 147.128.66.87 uploaduser] PASV
2022-02-08T11:32:42.942Z << [FTP Session 11 147.128.66.87 uploaduser] 227 Entering Passive Mode (147,128,66,56,222,117)
2022-02-08T11:32:43.021Z >> [FTP Session 11 147.128.66.87 uploaduser] STOR test.txt
2022-02-08T11:32:43.021Z << [FTP Session 11 147.128.66.87 uploaduser] 150 Starting data transfer.
2022-02-08T11:32:43.036Z II [FTP Session 11 147.128.66.87 uploaduser] TLS Handshake successful
2022-02-08T11:32:43.036Z II [FTP Session 11 147.128.66.87 uploaduser] TLS Session resumed
2022-02-08T11:32:43.036Z II [FTP Session 11 147.128.66.87 uploaduser] Protocol: TLS1.2, Key exchange: ECDHE-X25519, Cipher: AES-256-GCM, MAC: AEAD
2022-02-08T11:32:43.036Z !! [FTP Session 11 147.128.66.87 uploaduser] GnuTLS error -110 in gnutls_record_recv: The TLS connection was non-properly terminated.
2022-02-08T11:32:43.036Z == [FTP Session 11 147.128.66.87 uploaduser] Client did not properly shut down TLS connection
2022-02-08T11:32:43.036Z << [FTP Session 11 147.128.66.87 uploaduser] 425 Error while transfering data: ECONNABORTED - Connection aborted
2022-02-08T11:32:43.036Z !! [FTP Session 11 147.128.66.87 uploaduser] GnuTLS error -110 in gnutls_record_recv: The TLS connection was non-properly terminated.
2022-02-08T11:32:43.036Z == [FTP Session 11 147.128.66.87 uploaduser] Client did not properly shut down TLS connection
2022-02-08T11:32:43.036Z !! [FTP Session 11 147.128.66.87 uploaduser] Control channel closed with error from source 0. Reason: ECONNABORTED - Connection aborted.
2022-02-08T11:32:43.036Z !! [FTP Server] Session 11 ended with error from source 0. Reason: ECONNABORTED - Connection aborted.
2022-02-08T11:32:43.036Z II [FTP Session 11 147.128.66.87] Session 0x1ab850b0090 with ID 11 destroyed.
</code></pre>
<p>Tried different things on the server firewall, even disabled it, does not change anything.</p>
<p>Changed "keep alive" to $False, tried to disable passive mode on both server side and changing in the script to $False, without success.</p>
<p>Am I missing something ?</p>
| 3 | 2,062 |
pyzmq Segmentation fault on large .recv()
|
<ul>
<li>edited - I think I wrongly pointed the blame at pyzmq - I actually was running in a QThread and upon suggestion worked on a full working example - not using QThread and I do not see any issues. I'm going to drop my working example for anyone who may want to reference this example. </li>
</ul>
<p>I'm attempting to publish data on a <strong><code>pyzmq</code></strong> socket. I have experience here but never for larger data. On occasion, I'm getting a seg fault or at other times a message about <strong><code>free()</code></strong>. This happens more often for larger data sets, up to a point where it never actually works (depending on size). </p>
<p>subscriber code:</p>
<pre><code>import zmq
from time import sleep
from threading import Thread
class ZmqListener(Thread):
def __init__(self, addr, port):
Thread.__init__(self)
self.addr = addr
self.port = port
def run(self):
socket = zmq.Context().socket(zmq.SUB)
socket.connect("tcp://%s:%s" % (self.addr, self.port))
socket.setsockopt(zmq.SUBSCRIBE, "test:".encode('utf-8'))
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
self.running = True
while self.running:
print(socket.recv())
s = dict(poller.poll(1000))
if s:
if s.get(socket) == zmq.POLLIN:
msg = socket.recv()
print(msg)
socket.close()
th = ZmqListener('localhost', IMG_BASE_PORT)
th.start()
while True:
try:
sleep(1)
except KeyboardInterrupt:
break
th.running = False
th.join()
</code></pre>
<p>QThread subscriber code that breaks at random:</p>
<pre><code>class ZmqListener(QtCore.QThread):
message = QtCore.Signal(object)
def __init__(self, addr, port, parent=None):
QtCore.QThread.__init__(self, parent)
self.addr = addr
self.port = port
def run(self):
socket = zmq.Context().socket(zmq.SUB)
socket.connect("tcp://%s:%s" % (self.addr, self.port))
socket.setsockopt(zmq.SUBSCRIBE, "{}:".format(IMG_SUBS_HEAD).encode('utf-8'))
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
self.running = True
while self.running:
s = dict(poller.poll(1000))
if s:
if s.get(socket) == zmq.POLLIN:
msg = socket.recv()
self.message.emit(msg[len(IMG_SUBS_HEAD)+1::])
socket.close()
</code></pre>
<p>publisher code:</p>
<pre><code>#include <zmq.hpp>
#include <string>
#include <sstream>
#include <cstdlib>
#include <ios>
#include <thread>
#include <chrono>
#define PORT 13600
#define PUBS "test:"
#define NBYT 256 * 1024 * 1024 * 1024
int main()
{
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_PUB);
std::string rep_head;
char bytes[NBYT];
std::string zaddr("tcp://*:");
zaddr += std::to_string(PORT);
socket.bind(zaddr.c_str());
rep_head = std::string(PUBS);
int idx = 0;
while (1) {
for (int i = 0; i < NBYT; i++)
bytes[i] = rand(); // sleazy
std::stringstream ss;
ss << rep_head << std::hex << (int)idx << ":";
zmq::message_t msg(ss.str().length() + NBYT);
memcpy((char*)msg.data(), ss.str().data(), ss.str().length());
memcpy(((char*)msg.data())+ss.str().length(), bytes, NBYT);
socket.send(msg);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
socket.close();
return 0;
}
</code></pre>
<p>I've recently updated my OS (Ubuntu 18.04) and this was not a problem in the past.</p>
| 3 | 1,730 |
Excel (macro): understanding code - get unique values (rows & cols) to use in macro
|
<p>(First, I understand that <a href="https://stackoverflow.com/questions/15799172/use-vba-to-get-unique-values-for-use-within-vba">this</a> may work well for me - I'm trying to understand what's going on with a piece of code from somewhere else.)</p>
<p>I have a macro connected to buttons to hide columns and rows in range "rHFilter" that do not contain the value I want (whatever is in the drop-down in cell "M2"). To get the values for the drop-down, I am trying to check all the values in my range "rHFilter".
<a href="https://i.stack.imgur.com/PMsDz.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I'm getting <s>duplicates in my code</s> <em>multiple instances of values in my "strFilter" variable</em>, though, and I don't understand what this bit is doing, exactly, that it allows duplicates:</p>
<pre><code> For Each c In Range("rHFilter").Cells
If Application.CountIf(Range(Cells(3, 2), c), c.Value) = 1 Then
strFilter = strFilter & "," & c.Value
End If
Next c
</code></pre>
<p>That seems to be the smallest way to get unique values from a range to use in my macro - but if I can't make it work, I'm looking at trying the "collection" code from the other page. Can anyone help me?</p>
<p>As an aside, I don't understand what this is doing, either:</p>
<pre><code>'=========
'What is this statement supposed to do?
'If Application.CountIf(ThisWorkbook.Sheets(1).Columns(2), "-") _
= Range("rHFilter").Rows.Count Then Exit Sub
'=========
</code></pre>
<p>Here's the larger bit of code (for anyone interested):</p>
<pre><code> Sub SetrHFilterRange()
On Error Resume Next
Application.ScreenUpdating = False
strSN = ActiveSheet.name
Set ws = Sheets(strSN)
' Get the Last Cell of the Used Range
' Set lastCell = ThisWorkbook.Sheets(1).usedRange.SpecialCells(xlCellTypeLastCell)
Set lastCell = ws.Columns("B:G").Find("*", ws.[B3], xlValues, , xlByRows, xlPrevious)
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Set usedRange = Range("B3:G" & lastRow)
' Reset Range "rHFilter" from Cell C2 to last cell in Used Range
ThisWorkbook.Names.Add name:="rHFilter", RefersTo:=usedRange
' Set filtering cell value and formatting
With Cells(2, 13)
.Value = "-"
.FormatConditions.Delete
.FormatConditions.Add Type:=xlCellValue, Operator:=xlNotEqual, Formula1:="=""-"""
.FormatConditions(1).Interior.ColorIndex = 44
.Interior.ColorIndex = 17
End With
strFilter = "-"
For Each c In Range("rHFilter").Cells
If Application.CountIf(Range(Cells(3, 2), c), c.Value) = 1 Then
strFilter = strFilter & "," & c.Value
End If
Next c
With Cells(2, 13).Validation
.Delete
.Add Type:=xlValidateList, Formula1:=strFilter & ",Blank Cells"
.InCellDropdown = True
End With
strFilter = ""
Application.ScreenUpdating = True
On Error GoTo 0
End Sub
Sub SetrHFilter()
strSN = ActiveSheet.name
Set ws = Sheets(strSN)
If lastCell Is Nothing Then
Set lastCell = ws.Columns("B:G").Find("*", ws.[B3], xlValues, , xlByRows, xlPrevious)
End If
On Error Resume Next
'=========
'What is this statement supposed to do?
'If Application.CountIf(ThisWorkbook.Sheets(1).Columns(2), "-") _
= Range("rHFilter").Rows.Count Then Exit Sub
'=========
' reset unhide in case the user didn't clear
ThisWorkbook.Sheets(1).Columns.Hidden = False
ThisWorkbook.Sheets(1).Rows.Hidden = False
eName = Cells(2, 13).Value
If eName = "-" Then Exit Sub
' Speed the code up changing the Application settings
With Application
lCalc = .Calculation
.Calculation = xlCalculationManual
.EnableEvents = False
.ScreenUpdating = False
End With
FilterRowsNCols:
' Hide columns if cells don't match the values in filter cell
If eName <> "Blank Cells" Then
For Each hFilterCol In Range("rHFilter").Columns
Set fName = hFilterCol.Find(what:=eName, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False)
If fName Is Nothing Then 'not found
hFilterCol.EntireColumn.Hidden = True
End If
Next hFilterCol
Else
'Do something if the user selects blank - but what??
End If
If eName <> "Blank Cells" Then
For Each hFilterRow In Range("rHFilter").Rows
Set fName = hFilterRow.Find(what:=eName, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, MatchCase:=False)
If fName Is Nothing Then 'not found
hFilterRow.EntireRow.Hidden = True
End If
Next hFilterRow
Else
'Do something if the user selects blank - but what??
End If
Set lastCell = Nothing
If bFilter = False Then
bFilter = True
GoTo FilterRowsNCols
End If
' Change the Application settings back
With Application
.Calculation = lCalc
.EnableEvents = True
.ScreenUpdating = True
End With
On Error GoTo 0
End Sub
Sub ResetrHFilter()
On Error Resume Next
ThisWorkbook.Sheets(1).Columns.Hidden = False
ThisWorkbook.Sheets(1).Rows.Hidden = False
SetrHFilterRange
On Error GoTo 0
End Sub
</code></pre>
<p>==================================</p>
<h1>Edit</h1>
<p><em>Added the following edit after reading & testing Scott's answer:</em></p>
<p>I changed my code from:</p>
<pre><code>strFilter = "-"
For Each c In Range("rHFilter").Cells
If Application.CountIf(Range(Cells(3, 2), c), c.Value) = 1 Then
strFilter = strFilter & "," & c.Value
End If
Next c
With Cells(2, 13).Validation
.Delete
.Add Type:=xlValidateList, Formula1:=strFilter & ",Blank Cells"
.InCellDropdown = True
End With
</code></pre>
<p>To this:</p>
<pre><code>strFilter = "-"
Set uniqCol = New Collection
For Each c In Range("rHFilter").Cells
If Not IsNumeric(c.Value) And Not IsDate(c.Value) Then
uniqCol.Add c.Value, CStr(c.Value)
End If
Next c
For Each itmVal In uniqCol
strFilter = strFilter & "," & itmVal
Next
With Cells(3, 34).Validation
.Delete
.Add Type:=xlValidateList, Formula1:=strFilter & ",Blank Cells"
.InCellDropdown = True
End With
</code></pre>
<p>Thank you, Scott</p>
| 3 | 2,689 |
php mail attachment - error - how to debug
|
<p>I search and try different methods to produce a php mail with an attachment, which is saveable with the Client (Outlook). It doesn't work porper and I don't know why?</p>
<p>If the script send the mail with this code:</p>
<pre><code> $result = mail($mail_to, $subject, $headers);
</code></pre>
<p>I got an email with an inline base64 coded attachment and if use it in this way:</p>
<pre><code> $result = mail($mail_to, $subject, "", $headers);
</code></pre>
<p>or</p>
<pre><code> $result = mail($mail_to, $subject, $text, $headers);
</code></pre>
<p>I got the PHP Error: "false" - the mail could not send.</p>
<p>So it isn't and Mailserverproblem, I think and from headersview I think, it should work and I get no mail error on the Linux site.</p>
<p>A part from the mail coming with the attachment inline:</p>
<pre><code> MIME-Version: 1.0
From: user@nowhere.xyz
Content-Type: multipart/mixed; boundary="F34A3E8D822EE5A70EEDE9C3C143243C"
--F34A3E8D822EE5A70EEDE9C3C143243C
Content-Type: multipart/alternative; boundary="A0403290562B2A2F19FB62E48C51BE33"
--A0403290562B2A2F19FB62E48C51BE33
Content-Type: text/plain
Content-Transfer-Encoding: 8bit
Hello Mr. Xyz,
Some stupid text as an example.
--A0403290562B2A2F19FB62E48C51BE33--
--F34A3E8D822EE5A70EEDE9C3C143243C
Content-Type: application/CSV; charset="ISO-8859-1"; name="trouble.csv"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="trouble.csv"
...
YWNodW5nIG5pY2h0IGVyZm9yZGVybGljaCAvIG3DtmdsaWNoIjsiIjsiIjsK
--F34A3E8D822EE5A70EEDE9C3C143243C--
</code></pre>
<p>The matching PHP code:</p>
<p><pre></p>
<code> $text = "Hello Mr. Xyz," . $nl . "Some stupid text as an example." . $nl;
$content = chunk_split(base64_encode($file));
$headers = "MIME-Version: 1.0" . $nl;
$headers .= "From: " . $mail_from . $nl;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $boundary1 . "\"" . $nl . $nl;
$headers .= "--" . $boundary1 . $nl;
$headers .= "Content-Type: multipart/alternative; boundary=\"" . $boundary2 . "\"" . $nl . $nl;
$headers .= "--" . $boundary2 . $nl;
$headers .= "Content-Type: text/plain" . $nl;
$headers .= "Content-Transfer-Encoding: 8bit" . $nl . $nl;
$headers .= $text . $nl;
$headers .= "--" . $boundary2 . "--" . $nl . $nl;
$headers .= "--" . $boundary1 . $nl . $nl;
$headers .= "Content-Type: application/excel; charset=\"ISO-8859-1\"; name=\"xyz.csv\"" . $nl;
$headers .= "Content-Transfer-Encoding: base64" . $nl;
$headers .= "Content-Disposition: attachment; filename=\"xyz.csv\"" . $nl . $nl;
$headers .= $content . $nl;
$headers .= "--" . $boundary1 . "--" . $nl;
</code></pre>
<p></p>
<p>So, where is the bug? How can I debug such a Situation?
Thx in advance...</p>
| 3 | 1,298 |
Procedure don´t run correctly
|
<p>I create simple procedure who insert data from one table to another table. When I press execute It only mark as successfull but it don´t do any. But If I get a piece of code and press executed, it runs correctly: there are an images of what occur:<a href="https://i.stack.imgur.com/CCULh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CCULh.png" alt="enter image description here"></a>
and If I select piece of code:</p>
<p><a href="https://i.stack.imgur.com/GqA8o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GqA8o.png" alt="it runs correctly so something with m"></a> I think try catch is wrong. Can anyone help me? Regards</p>
<p><strong>Store:</strong></p>
<pre><code> BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION;
--Delete all registers of Proceso.srcUnidadesPresupuestadas
DELETE FROM Proceso.srcUnidadesPresupuestadas
--Insert in table Proceso.srcUnidadesPresupuestadas
INSERT INTO Proceso.srcUnidadesPresupuestadas (
IdCliente,IdCentro,IdNumeroParte,keyNumeroParte,keyCliente,
keyCentro,Periodo,Mes,UnidadesPresupuestadas,
mdOrigenCarga,mdUsuarioCarga,mdFechaCarga,bActivo)
SELECT
keyCliente,keyCentro,keyMaterial,keyCliente,keyCliente,
keyCentro,Periodo,Mes,UnidadesPresupuestadas,
mdOrigenCarga,mdUsuarioCarga,mdFechaCarga,bActivo FROM Proceso.tmpUnidadesPresupuestadas
--FROM
-- #tmpUnidadesPresupuestadas
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
DECLARE
@ERROR_SEVERITY INT,
@ERROR_STATE INT,
@ERROR_NUMBER INT,
@ERROR_LINE INT,
@ERROR_MESSAGE NVARCHAR(4000);
SELECT
@ERROR_SEVERITY = ERROR_SEVERITY(),
@ERROR_STATE = ERROR_STATE(),
@ERROR_NUMBER = ERROR_NUMBER(),
@ERROR_LINE = ERROR_LINE(),
@ERROR_MESSAGE = ERROR_MESSAGE();
RAISERROR('Msg %d, Line %d, :%s',
@ERROR_SEVERITY,
@ERROR_STATE,
@ERROR_NUMBER,
@ERROR_LINE,
@ERROR_MESSAGE);
END CATCH
END
</code></pre>
| 3 | 1,040 |
firestore can't get doc id QuerySnapshot.docChanges has been changed
|
<p>I'm trying to get doc id. I can't find any other way to get this data except for
snapshotChanges() method which is throwing me error. I don't see any mistakes in code and I can't find any similar problems on forums. When I use valueChanges() there is no problem with getting data. </p>
<p>Error in console</p>
<p><a href="https://i.stack.imgur.com/Iyyve.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Iyyve.png" alt="enter image description here"></a></p>
<p>Base structure</p>
<p><a href="https://i.stack.imgur.com/GnWl8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GnWl8.png" alt="enter image description here"></a></p>
<p>service.ts</p>
<pre><code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { IGallery } from '../interfaces/igallery';
import { timestamp } from 'rxjs/operator/timestamp';
@Injectable()
export class GalleriesService {
GalleriesCol: AngularFirestoreCollection<IGallery>;
galleriesObservable: Observable<any[]>;
// some code
constructor(private db: AngularFirestore) {
db.firestore.settings({ timestampsInSnapshots: true });
this.galleriesObservable = this.db.collection('galleries').snapshotChanges().map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as IGallery;
data.galleryId = a.payload.doc.id;
console.log(data);
return data;
});
});
}
getGalleries() {
return this.galleriesObservable;
}
// some code
}
</code></pre>
<p>app.component.ts</p>
<pre><code> getGalleries() {
this.galleriesService.getGalleries()
.subscribe(
data => {
this.galleries = data;
this.galleriesStatic = this.galleries;
this.setNumberOfPages();
this.setYearList();
this.setCurrentPage();
this.setTags();
console.log(this.galleries);
}
);
this.currentPage = parseInt(localStorage.getItem('galleryPage'), 10) || 0;
this.setCurrentPage(this.currentPage);
}
ngOnInit() {
this.getGalleries();
}
</code></pre>
<p>package.json</p>
<pre><code>{
"name": "angular-uczelnia",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^5.2.0",
"@angular/cdk": "^5.2.0",
"@angular/common": "^5.2.0",
"@angular/compiler": "^5.2.11",
"@angular/core": "^5.2.0",
"@angular/forms": "^5.2.0",
"@angular/http": "^5.2.0",
"@angular/material": "^5.2.0",
"@angular/platform-browser": "^5.2.0",
"@angular/platform-browser-dynamic": "^5.2.0",
"@angular/router": "^5.2.0",
"@firebase/app": "^0.1.6",
"@types/jquery": "^3.3.4",
"angular2-lightbox": "^1.3.0",
"angular5-toaster": "^1.0.2",
"angularfire2": "5.0.0-rc.7",
"core-js": "^2.4.1",
"firebase": "^5.2.0",
"hammerjs": "^2.0.8",
"jquery": "^3.3.1",
"lightbox2": "^2.10.0",
"ng-tags-input": "^3.2.0",
"ng2-order-pipe": "^0.1.5",
"ng2-toastr": "^4.1.2",
"ng2-truncate": "^1.3.11",
"ng4-tag-input": "^1.0.5",
"ngx-chips": "^1.9.2",
"ngx-order-pipe": "^2.0.1",
"npm-check-updates": "^2.14.2",
"rxjs": "^5.5.6",
"uuid": "^3.2.1",
"webpack": "^3.1.0",
"zone.js": "^0.8.19"
},
"devDependencies": {
"@angular/cli": "1.7.3",
"@angular/compiler-cli": "^5.2.0",
"@angular/language-service": "^5.2.0",
"@types/jasmine": "~2.8.3",
"@types/jasminewd2": "~2.0.2",
"@types/node": "~6.0.60",
"codelyzer": "^4.0.1",
"jasmine-core": "~2.8.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~2.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.2",
"ts-node": "~4.1.0",
"tslint": "~5.9.1",
"typescript": "~2.5.3"
}
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>I was trying to workaround the problem by updating "angularfire2@5.0.0-rc.7" to "5.0.0-rc.11".</p>
<p>After update:</p>
<pre><code>npm WARN angularfire2@5.0.0-rc.11 requires a peer of @angular/common@^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN angularfire2@5.0.0-rc.11 requires a peer of @angular/core@^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN angularfire2@5.0.0-rc.11 requires a peer of @angular/platform- browser@^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN angularfire2@5.0.0-rc.11 requires a peer of @angular/platform- browser-dynamic@^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN angularfire2@5.0.0-rc.11 requires a peer of rxjs@^6.0.0 but none is installed. You must install peer dependencies yourself.
</code></pre>
<p>Browser console:</p>
<pre><code>ERROR Error: Uncaught (in promise): TypeError: app.firestore is not a function
TypeError: app.firestore is not a function
</code></pre>
<p>So I did: </p>
<pre><code>npm install rxjs@6 rxjs-compat@6 --save
</code></pre>
<p>But then I got this:</p>
<pre><code>npm WARN @angular/core@4.4.7 requires a peer of rxjs@^5.0.1 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/http@4.4.7 requires a peer of rxjs@^5.0.1 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/router@4.4.7 requires a peer of rxjs@^5.0.1 but none is installed. You must install peer dependencies yourself.
</code></pre>
<p>I don't know why warnings concerns "4.4.7" versions if in my package.json I got "^5.2.0". I deleted \node_modules\@angular and package-lock.json then </p>
<pre><code>npm install
</code></pre>
<p>Dependencies warnings still appears as well as error in browser console:</p>
<pre><code>ERROR Error: Uncaught (in promise): TypeError: app.firestore is not a function
TypeError: app.firestore is not a function
</code></pre>
<p>This also didn't help:</p>
<pre><code>npm uninstall -g @angular/cli@1.7.3
npm cache clear
npm install -g @angular/cli@1.7.3
</code></pre>
<p>I got problems with both versions and now I'm not sure problems of which version I should trying to fix...</p>
| 3 | 2,803 |
Trying to match email address and error message in non-delivery report
|
<p>I'm attempting to write a csharp app which parses NDRs (non-delivery reports) sent when an email is un-deliverable. The goal is to unsubscribe email addresses from our mailing lists which are no longer valid.</p>
<p>I've managed to write code which connects to our exchange server using the exchange web services API (EWS). Grabs the message body and what I want to do is match the email address and error code so that we can generate a report of email addresses and errors for manual review.</p>
<p>The content of the body of a message appears as such:</p>
<pre><code> <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<p><b><font color="#000066" size="3" face="Arial">Delivery has failed to these recipients or groups:</font></b></p>
<font color="#000000" size="2" face="Tahoma">
<p><a href="mailto:email@domain.com">email@domain.com</a><br>
A communication failure occurred during the delivery of this message. Please try resending the message later. If the problem continues, contact your helpdesk.<br>
</p>
</font><br>
<br>
<br>
<br>
<br>
<br>
<font color="#808080" size="2" face="Tahoma">
<p><b>Diagnostic information for administrators:</b></p>
<p>Generating server: WEB16.domain.net</p>
<p>email@domain.com<br>
#&lt; #5.5.0 smtp;554 Sending address not accepted due to spam filter&gt; #SMTP#</p>
<p>Original message headers:</p>
<pre>Received: from WEB12 ([192.168.33.64]) by WEB16.domain.net with Microsoft
SMTPSVC(7.5.7601.17514); Sun, 8 Jul 2012 09:27:42 -0400
Thread-Topic: domain.com order 178014 has been received and is pending
thread-index: Ac1dDXyHxyN&#43;loq8SeaIzTsVoLE/3g==
From: &lt;sender@domain.com&gt;
To: &lt;recipient@domain.com&gt;
CC:
BCC:
Subject: domain.com order 178014 has been received and is pending
Date: Sun, 8 Jul 2012 09:27:56 -0400
Message-ID: &lt;22C1C2F24E1744D4B51C1A5EF9DE3E50@domain.net&gt;
MIME-Version: 1.0
Content-Type: text/plain
Content-Transfer-Encoding: 7bit
X-Mailer: Microsoft CDO for Windows 2000
Content-Class: urn:content-classes:message
Importance: normal
Priority: normal
X-MimeOLE: Produced By Microsoft MimeOLE V6.1.7601.17609
Return-Path: sender@domain.com
X-OriginalArrivalTime: 08 Jul 2012 13:27:42.0955 (UTC) FILETIME=[743A53B0:01CD5D0D]
</pre>
</font>
</body>
</html>
</code></pre>
<p>I am trying to come up with a regular expression that will match the email address that was sent to, and the accompanying error message.</p>
<pre><code> // First we set the input string.
string body = message.Body.Text;
// Regex string
Regex emailregex = new Regex("^<p>(.+?)</a><br>$");
var match = emailregex.Match(body);
if (match.Success)
Console.WriteLine(match.Groups[1].Value);
// Regex string
Regex errorregex = new Regex("</a><br>\n(.+?)<br>$");
match = errorregex.Match(body);
if (match.Success)
Console.WriteLine(match.Groups[1].Value);
</code></pre>
<p>Neither of the regular expressions I setup appear to not be working. I'm not much of a regular expression guru. Can anyone point me in the direction of what I'm doing wrong? </p>
<p>Thanks
Brad</p>
| 3 | 1,606 |
How do I add transitions between images in an array
|
<p>Just wanted to know how I could add any transitions, like crossfade or slider, between each image in the array when I click the next button and the previous button. I thought of using JQuery but I've no idea how to implement it into this script was given this and told to add transitions between images for homework. Searched all over the internet but most of them are overlaying images and fading the top into the other and none of them uses array so I didn't know how to integrate it into this code would be nice if someone can give some advice :D<br>
<strong>HTML</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Project</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="javascript.js"></script>
</head>
<body>
<div id="container">
<h1>Computer Accessories</h1>
<div id="container_thumbnail">
<img id="thumbnail_razer" src="images/razer/razer_logo.jpg" onclick="previewRazer();" alt="Razer Logo">
<img id="thumbnail_steelseries" src="images/steelseries/Steelseries_logo.png" onclick="previewSteelseries();" alt="SteelSeries Logo">
<img id="thumbnail_logitech" src="images/logitech/logitech_logo.png" onclick="previewLogitech();" alt="Logitech Logo">
<img id="thumbnail_corsair" src="images/corsair/corsair_logo.jpg" onclick="previewCorsair();" alt="Corsair Logo">
</div>
<h1 id="pageHeader"></h1>
<div id="container_slider">
<img id="slider" src="images/menu_preview.jpeg" alt="Menu Preview">
<div id="previousPosition">
<a href="#" onclick="return previous();" class="previous round">&#8249;</a>
</div>
<div id="nextPosition">
<a href="#" onclick="return next();" class="next round">&#8250;</a>
</div>
<div id="startStopBut" class="playpause">
<input type="checkbox" class="SSbuttons" name="check" id="playpause" value="None" onclick="startSlideShow();">
<label for="playpause" tabindex=1></label>
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>/* CSS Document */
#cotainer {
width: 1200px;
margin-left: auto;
margin-right: auto;
}
#container_thumbnail {
width: 702px;
margin-left: auto;
margin-right: auto;
}
#thumbnail_razer {
margin: 30px;
width: 100px;
height: 100px;
border: 5px solid #17D76B;
}
#thumbnail_steelseries {
margin: 30px;
width: 100px;
height: 100px;
border: 5px solid #fc8403;
}
#thumbnail_logitech {
margin: 30px;
width: 100px;
height: 100px;
border: 5px solid #3483eb;
}
#thumbnail_corsair {
margin: 30px;
width: 100px;
height: 100px;
border: 5px solid #fbff0f;
}
h1 {
color: #2A2929;
text-align: center;
}
#container_slider {
width: 800px;
height: 400px;
margin-left: auto;
margin-right: auto;
}
#slider {
width: 800px;
height: 400px;
}
a {
text-decoration: none;
display: inline-block;
padding: 8px 16px;
}
a:hover {
background-color: #ddd;
color: black;
}
.previous {
background-color: #ef42f5;
color: black;
}
.next {
background: #ef42f5;
color: black;
}
.round {
border-radius: 50%;
}
#nextPosition {
position: relative;
left: 94%;
bottom: 63%;
}
#previousPosition {
position: relative;
left: 1%;
bottom: 55%;
}
#startStopBut {
position: relative;
top: -15%;
left: 13%;
width: 230px;
margin-left: auto;
margin-right: auto;
}
.SSbuttons {
height: 25px;
width: 100px;
border-radius: 8px;
margin: 5px;
}
/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 3s;
animation-name: fade;
animation-duration: 3s;
}
@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
.container {
position: relative;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
flex-wrap: nowrap;
justify-content: center;
align-items: center;
}
.playpause label {
display: block;
box-sizing: border-box;
width: 0;
height: 74px;
border-color: transparent transparent transparent #202020;
transition: 100ms all ease;
cursor: pointer;
border-style: solid;
border-width: 37px 0 37px 60px;
}
.playpause input[type="checkbox"] {
position: absolute;
left: -9999px;
}
.playpause input[type="checkbox"]:checked + label {
border-style: double;
border-width: 0px 0 0px 60px;
}
</code></pre>
<p><strong>JAVASCRIPT</strong></p>
<pre><code>var index, timer, currentBrand;
index = 0;
currentBrand = 0;
var gallery = new Array();
function loadImagesRazer() {
gallery[0] = "images/razer/razer_1.png";
gallery[1] = "images/razer/razer_2.jpg";
gallery[2] = "images/razer/razer_3.jpg";
gallery[3] = "images/razer/razer_4.png";
}
function loadImagesSteelseries() {
gallery[0] = "images/steelseries/SS_1.jpg";
gallery[1] = "images/steelseries/SS_2.jpg";
gallery[2] = "images/steelseries/SS_3.jpg";
gallery[3] = "images/steelseries/SS_4.png";
}
function loadImagesLogitech() {
gallery[0] = "images/logitech/logitech_1.jpg";
gallery[1] = "images/logitech/logitech_2.jpg";
gallery[2] = "images/logitech/logitech_3.jpg";
gallery[3] = "images/logitech/logitech_4.jpg";
}
function loadImagesCorsair() {
gallery[0] = "images/corsair/corsair_1.jpg";
gallery[1] = "images/corsair/corsair_2.jpg";
gallery[2] = "images/corsair/corsair_3.jpg";
gallery[3] = "images/corsair/corsair_4.jpg";
}
function loadCurrentBrandImages() {
if(currentBrand == "Razer") {
loadImagesRazer();
}
if(currentBrand == "Steelseries") {
loadImagesSteelseries();
}
if(currentBrand == "Logitech") {
loadImagesLogitech();
}
if(currentBrand == "Corsair") {
loadImagesCorsair();
}
}
function startRazer() {
clearTimeout(timer);
loadImagesRazer();
document.body.style.backgroundColor = "#47e10c";
currentBrand = "Razer";
document.getElementById("pageHeader").innerHTML = "Razer";
document.getElementById('slider').src = gallery[index];
document.getElementById('slider2').src = gallery[index+1];
index = index + 1;
if(index >= gallery.length) {
index = 0;
}
timer = setTimeout("startRazer();", 5000);
}
function startSteelseries() {
clearTimeout(timer);
loadImagesSteelseries();
document.body.style.backgroundColor = "#da680f";
currentBrand = "Steelseries";
document.getElementById("pageHeader").innerHTML = "Steelseries";
document.getElementById('slider').src = gallery[index];
index = index + 1;
if(index >= gallery.length) {
index = 0;
}
timer = setTimeout("startSteelseries();", 5000);
}
function startLogitech() {
clearTimeout(timer);
loadImagesLogitech();
document.body.style.backgroundColor = "#0064ff";
currentBrand = "Logitech";
document.getElementById("pageHeader").innerHTML = "Logitech";
document.getElementById('slider').src = gallery[index];
index = index + 1;
if(index >= gallery.length) {
index = 0;
}
timer = setTimeout("startLogitech();", 5000);
}
function startCorsair() {
clearTimeout(timer);
loadImagesCorsair();
document.body.style.backgroundColor = "#fffeba";
currentBrand = "Corsair";
document.getElementById("pageHeader").innerHTML = "Corsair";
document.getElementById('slider').src = gallery[index];
index = index + 1;
if(index >= gallery.length) {
index = 0;
}
timer = setTimeout("startCorsair();", 5000);
}
function previewRazer() {
clearTimeout(timer);
document.getElementById("pageHeader").innerHTML = "Razer";
var element = document.getElementById("slider");
element.classList.add("fade");
document.body.style.backgroundColor = "#47e10c";
document.getElementById('slider').src = "images/razer/razer_1.png";
currentBrand = "Razer";
}
function previewSteelseries() {
clearTimeout(timer);
document.getElementById("pageHeader").innerHTML = "Steelseries";
var element = document.getElementById("slider");
element.classList.add("fade");
document.body.style.backgroundColor = "#da680f";
document.getElementById('slider').src = "images/steelseries/SS_1.jpg";
currentBrand = "Steelseries";
}
function previewLogitech() {
clearTimeout(timer);
document.getElementById("pageHeader").innerHTML = "Logitech";
var element = document.getElementById("slider");
element.classList.add("fade");
document.body.style.backgroundColor = "#0064ff";
document.getElementById('slider').src = "images/logitech/logitech_1.jpg";
currentBrand = "Logitech";
}
function previewCorsair() {
clearTimeout(timer);
document.getElementById("pageHeader").innerHTML = "Corsair";
var element = document.getElementById("slider");
element.classList.add("fade");
document.body.style.backgroundColor = "#fffeba";
document.getElementById('slider').src = "images/corsair/corsair_1.jpg";
currentBrand = "Corsair";
}
function previous() {
loadCurrentBrandImages();
clearTimeout(timer);
if(currentBrand == 0) {
previewRazer();
} else {
index = index - 1;
if(index < 0) {
index = gallery.length - 1;
}
document.getElementById('slider').src = gallery[index];
}
}
function next() {
loadCurrentBrandImages();
clearTimeout(timer);
if(currentBrand == 0) {
previewCorsair();
} else {
index = index + 1;
if(index >= gallery.length) {
index = 0;
}
document.getElementById('slider').src = gallery[index];
}
}
function stopSlideShow() {
document.getElementById("playpause").setAttribute("onclick", "javascript: startSlideShow();");
clearTimeout(timer);
}
function startSlideShow() {
document.getElementById("playpause").setAttribute("onclick", "javascript: stopSlideShow();");
if(currentBrand == 0) {
startRazer();
}
if(currentBrand == "Razer") {
startRazer();
}
if(currentBrand == "Steelseries") {
startSteelseries();
}
if(currentBrand == "Logitech") {
startLogitech();
}
if(currentBrand == "Corsair") {
startCorsair();
}
}
</code></pre>
| 3 | 5,244 |
Unity IAP - how to restore my Android purchases
|
<p>I made an Android payment system with IAP and it is currently registered in the App Store. However, a customer paid for the product and used it, but when I turned on the app again, the payment disappeared and the payment was proceeded again, and the window said, "It's an item I already have," and I couldn't pay.</p>
<p>So we need to add payment restoration function, but the official document and googling don't have an accurate restoration method. The only way to find it is old ways and errors I need to add a restoration function as soon as possible. How can I do this? I added the corresponding payment code below UNI.T version is 2021.3.3f1</p>
<p>Also, I added a script to the IAP button using OnPurchaseComplete without IStoreListener and proceeded with the payment, and I would like to recover it. They're all non-consumable products.</p>
<p>IAPScript:</p>
<pre><code>using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.UI;
using UnityEngine.Purchasing.Security;
public class IAPScript : GenericSingleton<IAPScript>
{
public string ChapterID_01 = "hisshow_vr_ani_01";
public string ChapterID_02 = "hisshow_vr_ani_02";
public string ChapterID_03 = "hisshow_vr_ani_03";
public string ChapterID_04 = "hisshow_vr_ani_04";
public string ChapterID_05 = "hisshow_vr_ani_05";
public string ChapterID_06 = "hisshow_vr_ani_06";
public string AllChapterID = "hisshow_vr_ani_package";
public string PilgrID = "hisshow_vr_360_package";
//Code for activating the corresponding commodity button
public AdventurePurchaseManager AdventurePurchaseManager;
public PilgrimagePurchassManager PilgrimagePurchassManager;
//
private void Start()
{
/*PlayerPrefs.DeleteKey("Cash1900_01");
PlayerPrefs.DeleteKey("Cash1900_02");
PlayerPrefs.DeleteKey("Cash1900_03");
PlayerPrefs.DeleteKey("Cash1900_05");
PlayerPrefs.DeleteKey("Cash1900_06");
PlayerPrefs.DeleteKey("Cash7900");
PlayerPrefs.DeleteKey("Cash3900");*/
Debug.Log("IAPScript");
GameObject obj = GameObject.Find("Canvas");
AdventurePurchaseManager = obj.transform.GetChild(1).GetChild(0).GetChild(1).GetComponent<AdventurePurchaseManager>();
PilgrimagePurchassManager = obj.transform.GetChild(1).GetChild(1).GetChild(3).GetComponent<PilgrimagePurchassManager>();
}
public void OnPurchaseComplete(Product product)
{
if (product.definition.id == ChapterID_01)
{
Debug.Log("챕터1 결제 완료");
PlayerPrefs.SetString("Cash1900_01", "buy");
AdventurePurchaseManager.SelectOpen_Chapter();
}
if (product.definition.id == ChapterID_02)
{
Debug.Log("챕터2 결제 완료");
PlayerPrefs.SetString("Cash1900_02", "buy");
AdventurePurchaseManager.SelectOpen_Chapter();
}
if (product.definition.id == ChapterID_03)
{
Debug.Log("챕터3 결제 완료");
PlayerPrefs.SetString("Cash1900_03", "buy");
AdventurePurchaseManager.SelectOpen_Chapter();
}
if (product.definition.id == ChapterID_04)
{
/*Debug.Log("챕터3 결제 완료");
PlayerPrefs.SetString("Cash1900_04", "buy");
AdventurePurchaseManager.SelectOpen_Chapter();
CodelessIAPStoreListener.Instance.StoreController.InitiatePurchase(ChapterID_04);*/
}
if (product.definition.id == ChapterID_05)
{
Debug.Log("챕터5 결제 완료");
PlayerPrefs.SetString("Cash1900_05", "buy");
AdventurePurchaseManager.SelectOpen_Chapter();
}
if (product.definition.id == ChapterID_06)
{
Debug.Log("챕터6 결제 완료");
PlayerPrefs.SetString("Cash1900_06", "buy");
AdventurePurchaseManager.SelectOpen_Chapter();
}
if (product.definition.id == AllChapterID)
{
PlayerPrefs.SetString("Cash7900", "buy");
Debug.Log("올 챕터 결제 완료");
AdventurePurchaseManager.AllChapter();
}
if (product.definition.id == PilgrID)
{
PlayerPrefs.SetString("Cash3900", "buy");
Debug.Log("성지순례 모든 챕터 결제 완료");
PilgrimagePurchassManager.Opne_All();
}
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason reason)
{
Debug.Log("결제 실패");
}
}
</code></pre>
<p>AdventurePurchaseManager:</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Purchasing;
public class AdventurePurchaseManager : MonoBehaviour
{
public AdventureChapter[] chapters;
public GameObject Package;
public IAPButton iAPButton;
private void Awake()
{
chapters = GetComponentsInChildren<AdventureChapter>();
Package = transform.parent.Find("Package").gameObject;
iAPButton = Package.GetComponent<IAPButton>();
if (transform.parent.parent.name != "SelectVr")
{
iAPButton = Package.GetComponent<IAPButton>();
iAPButton.onPurchaseComplete.AddListener(IAPScript.Instance.OnPurchaseComplete);
iAPButton.onPurchaseFailed.AddListener(IAPScript.Instance.OnPurchaseFailed);
}
}
private void Start()
{
if (PlayerPrefs.HasKey("Cash7900"))
{
Open_AllChapter();
Debug.Log("PlayerPrefs.HasKey(Cash7900)");
}
else
{
SelectOpen_Chapter();
}
}
private void OnEnable()
{
StartCoroutine("delay_OnEnable");
}
public void AllChapter()
{
StartCoroutine("delay_OnEnable");
}
public void SelectOpen_Chapter()
{
StartCoroutine("delay_SelectOpenChapter");
}
IEnumerator delay_OnEnable()
{
yield return new WaitForSeconds(0.02f);
if (PlayerPrefs.HasKey("Cash7900"))
{
Open_AllChapter();
}
else
{
SelectOpen_Chapter();
}
}
IEnumerator delay_SelectOpenChapter()
{
yield return new WaitForSeconds(0.02f);
bool[] checkBuyChapter = new bool[6];
chapters[3].SetFree();
checkBuyChapter[3] = true;
if (PlayerPrefs.HasKey("Cash1900_01"))
{
chapters[0].SetPurchase();
checkBuyChapter[0] = true;
}
else
{
chapters[0].SetLock();
checkBuyChapter[0] = false;
}
if (PlayerPrefs.HasKey("Cash1900_02"))
{
chapters[1].SetPurchase();
checkBuyChapter[1] = true;
}
else
{
chapters[1].SetLock();
checkBuyChapter[1] = false;
}
if (PlayerPrefs.HasKey("Cash1900_03"))
{
chapters[2].SetPurchase();
checkBuyChapter[2] = true;
}
else
{
chapters[2].SetLock();
checkBuyChapter[2] = false;
}
/* if (PlayerPrefs.HasKey("Cash1900_04"))
{
chapters[4].SetPurchase();
checkBuyChapter[4] = true;
}
else
{
chapters[4].SetLock();
checkBuyChapter[4] = false;
}*/
/* if (PlayerPrefs.HasKey("Cash1900_04"))
{
chapters[3].SetFree();
checkBuyChapter[3] = true;
}*/
if (PlayerPrefs.HasKey("Cash1900_05"))
{
chapters[4].SetPurchase();
checkBuyChapter[4] = true;
}
else
{
chapters[4].SetLock();
checkBuyChapter[4] = false;
}
if (PlayerPrefs.HasKey("Cash1900_06"))
{
chapters[5].SetPurchase();
checkBuyChapter[5] = true;
}
else
{
chapters[5].SetLock();
checkBuyChapter[5] = false;
Debug.Log("test");
}
bool check = true;
for (int i = 0; i < checkBuyChapter.Length; i++)
{
if (checkBuyChapter[i] == false)
{
check = false;
}
}
if (check)
{
Package.gameObject.SetActive(false);
}
else
{
Package.gameObject.SetActive(true);
}
}
public void Open_AllChapter()
{
foreach (var chapter in chapters)
{
if (chapter.myIndex == 3)
{
chapter.SetFree();
}
else
{
chapter.SetPurchase();
}
}
Package.gameObject.SetActive(false);
}
}
</code></pre>
<p>AdventureChapter:</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Purchasing;
public class AdventureChapter : MonoBehaviour
{
public int myIndex;
[SerializeField] private GameObject dim;
[SerializeField] private GameObject paid;
[SerializeField] private GameObject sell;
[SerializeField] private GameObject free;
[SerializeField] private GameObject locked;
[SerializeField] private Button button;
[SerializeField] private IAPButton IAPButton;
private void Awake()
{
myIndex = transform.GetSiblingIndex();
dim = transform.Find("Dim").gameObject;
paid = transform.Find("Paid").gameObject;
sell = transform.Find("Sell").gameObject;
free = transform.Find("Free").gameObject;
locked = transform.Find("Locked").gameObject;
button = GetComponent<Button>();
if (transform.parent.parent.parent.name != "SelectVr")
{
IAPButton = locked.GetComponent<IAPButton>();
IAPButton.onPurchaseComplete.AddListener(IAPScript.Instance.OnPurchaseComplete);
IAPButton.onPurchaseFailed.AddListener(IAPScript.Instance.OnPurchaseFailed);
}
}
private void OnEnable()
{
}
public void SetFree()
{
dim.SetActive(false);
paid.SetActive(false);
sell.SetActive(false);
free.SetActive(true);
locked.SetActive(false);
button.interactable = true;
}
public void SetLock()
{
dim.SetActive(true);
paid.SetActive(false);
sell.SetActive(true);
free.SetActive(false);
locked.SetActive(true);
button.interactable = false;
}
public void SetPurchase()
{
dim.SetActive(false);
paid.SetActive(true);
sell.SetActive(false);
free.SetActive(false);
locked.SetActive(false);
button.interactable = true;
}
}
</code></pre>
<p>PilgrimagePurchassManager:</p>
<pre><code> using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.U2D;
using UnityEngine.Purchasing;
public class PilgrimagePurchassManager : MonoBehaviour
{
[SerializeField] private Image[] pgImages;
[SerializeField] private Button[] pgButtons;
[SerializeField] private GameObject Package;
[SerializeField] private string[] pgWordIndex;
public SpriteAtlas Pilgrimage;
private IAPButton IAPButton;
private void Awake()
{
pgImages = new Image[transform.childCount];
pgButtons = new Button[transform.childCount];
for (int i = 0; i < transform.childCount; i++)
{
pgImages[i] = transform.GetChild(i).GetComponent<Image>();
pgButtons[i] = transform.GetChild(i).GetComponent<Button>();
}
Package = transform.parent.GetChild(4).gameObject;
if (transform.parent.parent.parent.name != "VideoExit")
{
IAPButton = Package.GetComponent<IAPButton>();
IAPButton.onPurchaseComplete.AddListener(IAPScript.Instance.OnPurchaseComplete);
IAPButton.onPurchaseFailed.AddListener(IAPScript.Instance.OnPurchaseFailed);
}
pgWordIndex = new string[] {"02","05","04","03","16", "18", "22", "21", "19", "20", "10", "11" ,"09", "07" ,"23" ,"08", "06", "12", "13", "14", "15", "17" };
}
private void OnEnable()
{
if (PlayerPrefs.HasKey("Cash3900"))
{
Opne_All();
}
else
{
for (int i = 0; i < pgButtons.Length; i++)
{
if (i < 4)
{
pgButtons[i].enabled = true;
pgButtons[i].interactable = true;
pgImages[i].sprite = Pilgrimage.GetSprite($"Pilgrimage_spot_{pgWordIndex[i]}_unlock");
}
else
{
pgButtons[i].enabled = false;
pgButtons[i].interactable = false;
pgButtons[i].enabled = true;
pgButtons[i].enabled = false;
pgImages[i].sprite = Pilgrimage.GetSprite($"Pilgrimage_spot_{pgWordIndex[i]}_lock");
}
}
Package.gameObject.SetActive(true);
}
}
public void Opne_All()
{
StartCoroutine("Delay_OPenAll");
}
IEnumerator Delay_OPenAll()
{
yield return new WaitForSeconds(0.02f);
for (int i = 0; i < pgButtons.Length; i++)
{
pgButtons[i].enabled = true;
pgButtons[i].interactable = true;
pgImages[i].sprite = Pilgrimage.GetSprite($"Pilgrimage_spot_{pgWordIndex[i]}_unlock");
}
Package.gameObject.SetActive(false);
}
}
</code></pre>
| 3 | 7,101 |
asmack-android-8-4.0.6.jar issue for XMPP connection
|
<p>I am using asmack-android-8-4.0.6.jar as library for xmpp ,i was able to connect with earlier versions of asmack lib ,but with this new latest lib i am getting below exception,please help me out how to enable SSL authentication using latest asmack lib ,
I don't find connConfig.setSASLAuthenticationEnabled(true); method in latest lib</p>
<pre><code> ConnectionConfiguration connConfig = new ConnectionConfiguration(HOST,PORT);
//connConfig.setSASLAuthenticationEnabled(true);
// connConfig.setCompressionEnabled(true);
connConfig.setSecurityMode(SecurityMode.enabled);
connConfig.setDebuggerEnabled(true);
connConfig.setSocketFactory(new DummySSLSocketFactory());
connection = new XMPPTCPConnection(connConfig);
try {
connection.connect();
Log.i(TAG, "Connected to " + connection.getServiceName());
} catch (XMPPException ex) {
Log.e(TAG, "Failed to connect to " + connection.getHost());
Log.e(TAG, ex.toString());
return null;
//setConnection(null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
</code></pre>
<p>Below is the stack trace am getting </p>
<pre><code>12-02 12:56:14.612: W/System.err(23797): javax.net.ssl.SSLException: Connection closed by peer
12-02 12:56:14.622: W/System.err(23797): at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
12-02 12:56:14.622: W/System.err(23797): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:378)
12-02 12:56:14.622: W/System.err(23797): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl$SSLInputStream.<init>(OpenSSLSocketImpl.java:649)
12-02 12:56:14.622: W/System.err(23797): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.getInputStream(OpenSSLSocketImpl.java:620)
12-02 12:56:14.622: W/System.err(23797): at org.jivesoftware.smack.tcp.XMPPTCPConnection.initReaderAndWriter(XMPPTCPConnection.java:507)
12-02 12:56:14.622: W/System.err(23797): at org.jivesoftware.smack.tcp.XMPPTCPConnection.initConnection(XMPPTCPConnection.java:457)
12-02 12:56:14.622: W/System.err(23797): at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectUsingConfiguration(XMPPTCPConnection.java:440)
12-02 12:56:14.622: W/System.err(23797): at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectInternal(XMPPTCPConnection.java:811)
12-02 12:56:14.622: W/System.err(23797): at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:396)
12-02 12:56:14.622: W/System.err(23797): at com.mydoc.pro.messenger.net.XMPPConnectAsyncTask.setXMPPConnection(XMPPConnectAsyncTask.java:92)
12-02 12:56:14.622: W/System.err(23797): at com.mydoc.pro.messenger.net.XMPPConnectAsyncTask.doInBackground(XMPPConnectAsyncTask.java:61)
12-02 12:56:14.622: W/System.err(23797): at com.mydoc.pro.messenger.net.XMPPConnectAsyncTask.doInBackground(XMPPConnectAsyncTask.java:1)
12-02 12:56:14.622: W/System.err(23797): at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-02 12:56:14.622: W/System.err(23797): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-02 12:56:14.622: W/System.err(23797): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-02 12:56:14.622: W/System.err(23797): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-02 12:56:14.622: W/System.err(23797): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-02 12:56:14.622: W/System.err(23797): at java.lang.Thread.run(Thread.java:856)
12-02 12:56:14.622: I/XMPPConnectAsyncTask(23797): No connection to server null
12-02 12:56:14.622: W/System.err(23797): org.jivesoftware.smack.SmackException$NotConnectedException
12-02 12:56:14.632: W/System.err(23797): at org.jivesoftware.smack.XMPPConnection.sendPacket(XMPPConnection.java:584)
12-02 12:56:14.632: W/System.err(23797): at com.mydoc.pro.messenger.net.XMPPConnectAsyncTask.setXMPPConnection(XMPPConnectAsyncTask.java:117)
12-02 12:56:14.632: W/System.err(23797): at com.mydoc.pro.messenger.net.XMPPConnectAsyncTask.doInBackground(XMPPConnectAsyncTask.java:61)
12-02 12:56:14.632: W/System.err(23797): at com.mydoc.pro.messenger.net.XMPPConnectAsyncTask.doInBackground(XMPPConnectAsyncTask.java:1)
12-02 12:56:14.632: W/System.err(23797): at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-02 12:56:14.632: W/System.err(23797): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-02 12:56:14.632: W/System.err(23797): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-02 12:56:14.632: W/System.err(23797): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-02 12:56:14.632: W/System.err(23797): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-02 12:56:14.632: W/System.err(23797): at java.lang.Thread.run(Thread.java:856)
</code></pre>
| 3 | 2,021 |
JQuery Ajax data sent time 500 Internal Server Error
|
<p>index.php</p>
<pre><code><?php
$path = "uploads/";
$image = "";
?>
<html>
<head>
<title></title>
</head>
<link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" />
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.imgareaselect.pack.js"></script>
<script type="text/javascript">
function getCropImage(im,obj)
{
var x_axis = obj.x1;
var x2_axis = obj.x2;
var y_axis = obj.y1;
var y2_axis = obj.y2;
var thumb_width = obj.width;
var thumb_height = obj.height;
$.ajax({
type:"GET",
url:"flipimage.php?t=ajax&img="+$("#image_name").val()+"&w="+thumb_width+"&h="+thumb_height+"&x1="+x_axis+"&y1="+y_axis,
cache:false,
success:function(response)
{
//$("#cropimage").hide();
$("#thumbs").html("");
$("#thumbs").html("<img src='uploads/"+response+"' width='700px' height='400px'/>");
}
});
}
$(document).ready(function () {
$('img#photo').imgAreaSelect({
maxWidth: 1,
// maxHeight: 1,
onSelectEnd: getCropImage
});
});
</script>
<?php
$valid_formats = array("jpg", "jpeg", "png", "gif", "bmp","JPG", "PNG", "GIF", "BMP", "JPEG");
$maxImgSize = 5*1024*1024;
$randomName = md5(uniqid().date("Y-m-d H:i:s"));
if(isset($_POST['submit']))
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats) && $size < $maxImgSize)
{
$randomImageName = $randomName.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$randomImageName))
{
$image="<div>Please select the portion</div><img src='uploads/".$randomImageName."' id=\"photo\" >";
}
else {
if ($_FILES["photoimg"]["error"] > 0)
{
echo "Error: " . $_FILES["photoimg"]["error"] . "<br>";
}
}
}
else
{
if($_FILES["photoimg"]["size"] > $maxImgSize)
echo "Maximum file size exceeded";
else
echo "Invalid file";
}
}
else
echo "Please select a image";
}
?>
<body>
<div>
<div>
<form id="cropimage" method="post" enctype="multipart/form-data">
Upload your image
<input type="file" name="photoimg" id="photoimg" />
<input type="hidden" name="image_name" id="image_name" value="<?php echo($randomImageName)?>" />
<input type="submit" name="submit" value="Submit" />
</form>
</div>
<div>
<div>
<?php if($image != ''){ echo $image; }?>
</div>
<div id="thumbs" style="margin-top:40px;"></div>
<div>
</div>
</body>
</html>
</code></pre>
<p>flipimage.php</p>
<pre><code><?php
$path = "uploads/";
function flip($image,$h=1,$v=0,$wid)
{
$width = imagesx($image);
$height = imagesy($image);
$temp = imagecreatetruecolor($width,$height);
imagecopy($temp,$image,0,0,0,0,$width,$height);
$image1 = imagecreatetruecolor($width,$height);
imagecopy($image1,$image,0,0,0,0,$width,$height);
$leftwidth = 2*$wid;
$totWid = (2*$width);
$finalImage = imagecreatetruecolor($totWid,$height);
if ($h==1) {
for ($x=0 ; $x<$width ; $x++)
{
imagecopy($image1, $temp, $width-($x)-1, 0, $x, 0, 1, $height);
}
}
for ($x=0 ; $x<=$wid ; $x++)
{
imagecopy($finalImage, $image, $x, 0, $x, 0, 1, $height);
imagecopy($finalImage, $image1, $leftwidth-($x), 0, $width-($x), 0, 1, $height);
}
$rightWidth = $totWid-$leftwidth;
for ($x=0; $x<=$width-$wid; $x++)
{
imagecopy($finalImage, $image, $totWid-$x, 0, $width-$x, 0, 1, $height);
imagecopy($finalImage, $image1, $leftwidth+$x, 0, $x, 0, 1, $height);
}
return $finalImage;
}
if(isset($_GET['t']) and $_GET['t'] == "ajax")
{
extract($_GET);
$extension = strtolower(strrchr($img, '.'));
$file = $path.$img;
switch ($extension) {
case '.jpg':
$image = imagecreatefromjpeg($file);
break;
case '.gif':
$image = imagecreatefromgif($file);
break;
case '.png':
$image = imagecreatefrompng($file);
break;
default:
$image = false;
break;
}
$new_name = "flip".$img;
$image = flip($image,1,0,$x1);
header("Content-type: image/jpeg");
imagejpeg($image,$path.$new_name,90);
echo $new_name.'?'.time();
exit;
}
?>
</code></pre>
<p>I am trying to perform this AJAX post but for some reason I am getting a server 500 error. So the problem seems to be on the calltime. but it's working fine in localhost. but in live error occur.</p>
| 3 | 3,031 |
i need to output the final part of my JAVA program which is just a game over string , how can i insert it?
|
<p>these is my program i need to output "game over" if the user enter the string no instead of yes, right now it only works with the yes but i dont know how to add the other option the game is suppose to ask the user for a seed , then for a number from 1 to 100 and then the user has to guees the number, once the user guesses the number it asks if it wants to play again, with option of yes or no, i have the yes but i dont know how to output the no.</p>
<pre><code>import java.util.Random;
import java.util.Scanner;
public class GuessANumber_part2 {
public static void main(String[] args) {
//Method generates a random number and per user's
//input it prints if is to low, to high or the
//correct number
guessNumber();
}
public static void guessNumber() {
//Generating a seed number
System.out.println("Enter a seed:\n");
Scanner scanner = new Scanner(System.in);
int seed = scanner.nextInt();
//variable counts number of guesses
int guess;//variable holds user's guess
boolean play = true;//variable to run while
//Generating random object
Random random = new Random(seed);
int correctNum = random.nextInt(100) + 1;
//Outer loop count the amount of guesses
//Prompts user to play the game again
while(play) {
//welcome statement, getting the initial input
System.out.println("Welcome!\n"
+ "Please enter a number between 1 and 100:");
//variables
guess = scanner.nextInt();//saves the initial input
int count = 1;//count the number of guesses
//Inner loop outputs if the number given by the user
//is either to high, to low or if is the correct number
while( guess != correctNum) {
if(guess < correctNum) {
System.out.println("Too low. Guess again:");
}else if(guess > correctNum) {
System.out.println("Too high. Guess again:");
}
count++;// keeps count of N of guesses
//welcome message and input statement
System.out.println("Welcome!\n"
+ "Please enter a number between 1 and 100:");
guess = scanner.nextInt();
}
//outer loop statement,Prompts the user to run or
//not run game again
System.out.println("Congratulations. You guessed correctly!\n"
+ "You needed " + count + " guesses.\n");
System.out.println("Do you want to play again? Answer \"yes\""
+ " or \"no\":");
//Output statement sets play to answer "yes"
play = scanner.next().toLowerCase().equals("yes");
}
}
}
</code></pre>
| 3 | 1,412 |
Extract data from Wikidata using PHP
|
<p>I have used Faker to generate persons and I want to do the same thing using Wikidata. By getting names, date of birth, gender, first paragraph and other specified similar data. In addition being able to avoid duplicates by checking existing persons (e.g Q4926) I have fetched before. Wikidata Query = <a href="https://w.wiki/5LUr" rel="nofollow noreferrer">https://w.wiki/5LUr</a></p>
<p>Is it possible to use <a href="https://github.com/freearhey/wikidata" rel="nofollow noreferrer">freearhey/wikidata</a> or <a href="https://github.com/addwiki/wikibase-api" rel="nofollow noreferrer">addwiki/wikibase-api</a> or should <a href="https://query.wikidata.org/sparql" rel="nofollow noreferrer">query.wikidata.org/sparql</a> be used diretly</p>
<p>Code snippet currently used</p>
<pre><code>if ($s == 'generate_fake_users') {
require "assets/libraries/fake-users/vendor/autoload.php";
$faker = Faker\Factory::create();
if (empty($_POST['password'])) {
$_POST['password'] = '123456789';
}
$count_users = $_POST['count_users'];
$password = $_POST['password'];
$avatar = $_POST['avatar'];
ob_end_clean();
header("Content-Encoding: none");
header("Connection: close");
ignore_user_abort();
ob_start();
header('Content-Type: application/json');
echo json_encode(array(
'status' => 200
));
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
session_write_close();
if (is_callable('fastcgi_finish_request')) {
fastcgi_finish_request();
}
for ($i=0; $i < $count_users; $i++) {
$genders = array_keys($wo['genders']);
$random_keys = array_rand($genders, 1);
$gender = array_rand(array("male", "female"), 1);
$gender = $genders[$random_keys];
$re_data = array(
'email' => Site_Secure(str_replace(".", "_", $faker->userName) . '_' . rand(111, 999) . "@domain.com", 0),
'username' => Site_Secure($faker->userName . '_' . rand(111, 999), 0),
'password' => Site_Secure($password, 0),
'email_code' => Site_Secure(md5($faker->userName . '_' . rand(111, 999)), 0),
'src' => 'Fake',
'gender' => Site_Secure($gender),
'lastseen' => time(),
'active' => 1,
'first_name' => $faker->firstName($gender),
'last_name' => $faker->lastName
);
if ($avatar == 1) {
$urls = array("http://lorempixel.com/".$wo['profile_picture_width_crop']."/".$wo['profile_picture_height_crop']."/people","https://placeimg.com/".$wo['profile_picture_width_crop']."/".$wo['profile_picture_height_crop']."/people");
$rand = rand(0,1);
$url = $urls[$rand];
$a = Site_ImportImageFromFile($url,'_url_image','avatar');
if (!empty($a)) {
$re_data['avatar'] = $a;
}
}
$add_user = Site_RegisterUser($re_data);
}
header("Content-type: application/json");
echo json_encode($data);
exit();
}
</code></pre>
| 3 | 1,576 |
All words used to used to train Doc2Vec model appear as unknown
|
<p>I'm trying to make an unsupervised text classifier using Doc2Vec. I am getting the error message of "The following keywords from the 'keywords_list' are unknown to the Doc2Vec model and therefore not used to train the model: sport". The rest of the error message is super long but eventually ends with "cannot compute similarity with no input" which leads me to believe that all of my keywords are not accepted.</p>
<p>The portion of code where I create the Lbl2Vec model is</p>
<pre><code> Lbl2Vec_model = Lbl2Vec(keywords_list=list(labels["keywords"]), tagged_documents=df_pdfs['tagged_docs'], label_names=list(labels["class_name"]), similarity_threshold=0.43, min_num_docs=10, epochs=10)
</code></pre>
<p>I've been following this tutorial <a href="https://towardsdatascience.com/unsupervised-text-classification-with-lbl2vec-6c5e040354de" rel="nofollow noreferrer">https://towardsdatascience.com/unsupervised-text-classification-with-lbl2vec-6c5e040354de</a> but using my own dataset that I load from JSON.</p>
<p>The entire code is posted below:</p>
<pre><code>#imports
from ast import keyword
import tkinter as tk
from tkinter import filedialog
import json
import pandas as pd
import numpy as np
from gensim.utils import simple_preprocess
from gensim.parsing.preprocessing import strip_tags
from gensim.models.doc2vec import TaggedDocument
from lbl2vec import Lbl2Vec
class DocumentVectorize:
def __init__(self):
pass
#imports data from json file
def import_from_json (self):
root = tk.Tk()
root.withdraw()
json_file_path = filedialog.askopenfile().name
with open(json_file_path, "r") as json_file:
try:
json_load = json.load(json_file)
except:
raise ValueError("No PDFs to convert to JSON")
self.pdfs = json_load
if __name__ == "__main__":
#tokenizes documents
def tokenize(doc):
return simple_preprocess(strip_tags(doc), deacc=True, min_len=2, max_len=1000000)
#initializes document vectorization class and imports the data from json
vectorizer = DocumentVectorize()
vectorizer.import_from_json()
#converts json data to dataframe
df_pdfs = pd.DataFrame.from_dict(vectorizer.pdfs)
#creates data frame that contains the keywords and their class names for the training
labels = {"keywords": [["sport"], ["physics"]], "class_name": ["rec.sport", "rec.physics"]}
labels = pd.DataFrame.from_dict(labels)
#applies tokenization to documents
df_pdfs['tagged_docs'] = df_pdfs.apply(lambda row: TaggedDocument(tokenize(row['text_clean']), [str(row.name)]), axis=1)
#creates key for documents
df_pdfs['doc_key'] = df_pdfs.index.astype(str)
print(df_pdfs.head())
#Initializes Lbl2vec model
Lbl2Vec_model = Lbl2Vec(keywords_list=list(labels["keywords"]), tagged_documents=df_pdfs['tagged_docs'], label_names=list(labels["class_name"]), similarity_threshold=0.43, min_num_docs=10, epochs=10)
#Fits Lbl2vec model to data
Lbl2Vec_model.fit()
</code></pre>
| 3 | 1,276 |
Pass data recycler adapter to other activity using Firebase
|
<p>Image : </p>
<p><img src="https://i.stack.imgur.com/sCByV.jpg" alt="enter image description here"></p>
<p>I am using Firebase for video status android application, and using recycler view but Firebase daat will not pass first activity to another (second) activity, how I can solve this problem (error)<br>
error Model.videolink' on a null object reference.</p>
<p><strong>App Adepter</strong></p>
<pre><code>public class App_Adepter extends RecyclerView.Adapter<App_Adepter.ViewHolder> {
Model model;
private Context context;
private ArrayList<Model> uploads;
private ProgressDialog pDialog;
private MediaController mediaController;
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public VideoView videoView;
public TextView textView;
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.rImageView);
videoView = (VideoView) itemView.findViewById(R.id.test_video);
textView = (TextView) itemView.findViewById(R.id.text11);
}
}
public App_Adepter(Context context, ArrayList<Model> uploads) {
this.uploads = uploads;
this.context = context;
}
@Override
public App_Adepter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row, parent, false);
return new App_Adepter.ViewHolder(v);
}
@Override
public void onBindViewHolder(final App_Adepter.ViewHolder holder, final int position) {
final Model upload = uploads.get(position);
/*Video Click*/
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, Full_video.class);
intent.putExtra("posss", model.image);
intent.putParcelableArrayListExtra("Category", uploads);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
final MediaController mediaController = new MediaController(context);
String uriPath = upload.getImage(); //update package name
Uri uri = Uri.parse(uriPath);
holder.textView.setText(upload.getVideolink());
Glide.with(context).load(upload.getImage()).into(holder.imageView);
holder.videoView.setVideoURI(uri);
holder.videoView.start();
holder.videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return true;
}
});
holder.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
@Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
/**** Media control coding ****///
holder.videoView.setMediaController(mediaController);
mediaController.setAnchorView(holder.videoView);
mp.setVolume(0, 0);
}
});
}
});
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return uploads.size();
}
}
</code></pre>
<p><strong>Model Class</strong></p>
<pre><code>String image;
String videolink;
public Model() {
}
public static Creator<Model> getCREATOR() {
return CREATOR;
}
public Model(String image,String videolink) {
this.videolink = videolink;
this.image = image;
}
protected Model(Parcel in) {
image = in.readString();
videolink = in.readString();
}
public static final Creator<Model> CREATOR = new Creator<Model>() {
@Override
public Model createFromParcel(Parcel in) {
return new Model(in);
}
@Override
public Model[] newArray(int size) {
return new Model[size];
}
};
public String getVideolink() {
return videolink;
}
public void setVideolink(String videolink) {
this.videolink = videolink;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(image);
dest.writeString(videolink);
}
</code></pre>
<p><strong>Other (Second) Activity</strong></p>
<pre><code> Bundle extra = getIntent().getExtras();
String value = extra.getString("posss");
videoView.setVideoURI(Uri.parse(value));
</code></pre>
<p><strong>First Activity</strong></p>
<pre><code> mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
progressDialog.dismiss();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Model upload = postSnapshot.getValue(Model.class);
app_models.add(upload);
}
adapter = new App_Adepter(App_screen.this, app_models);
recyclerView.setAdapter(adapter);
if (app_models.size() <= 0) {
textView.setVisibility(View.VISIBLE);
} else {
textView.setVisibility(View.GONE);
}
}
</code></pre>
| 3 | 2,199 |
Initialize values of an array that is within a struct
|
<p>I have a struct called <code>member</code>. Within <code>member</code> I have a <code>std::string</code> array called <code>months</code> that I would like to initialize to default values. This is how I am doing it currently:</p>
<pre><code>template <typenameT>
struct member
{
std::string months[12];
std::string name;
T hours_worked[12];
T dues[12];
member() : months{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} {};
};
</code></pre>
<p>However, whenever I compile I get this warning message:</p>
<pre><code>warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x
</code></pre>
<p>How can I do the initialization properly and get rid of this error message?</p>
<p><strong>Edit:</strong></p>
<p>I should of made my question more clear. I need compile this program on a older compiler and the <code>-std=c++0x</code> flag option will not be available to me. How can I do this correctly without using the flag.</p>
| 3 | 1,043 |
I have a Verilog code and the issue is that I need to C bit to go HIGH at the same time as B_G2 and that is done at the else statement
|
<p>The issue is that I need C bit to go HIGH at the same time as B_G2 and that it is done at the else statement.</p>
<p>Here is the code that I have so far:</p>
<pre><code>module lightcontrol(clk, R,C, A_CAR, B_CAR, lightsA, lightsB, cnt);
`define A_G2 3'b000
`define A_Y 3'b001
`define B_G1 3'b010
`define B_G2 3'b110
`define B_Y 3'b101
`define A_G1 3'b100
`define RED 3'b100
`define YELLOW 3'b010
`define GREEN 3'b001
input clk;
input A_CAR;
input B_CAR;
input R ;
output [2:0] lightsA;
output [2:0] lightsB;
output [3:0] cnt;
output C;
reg [3:0] cnt = 0;
reg [2:0] state;
reg C = 0;
always @(posedge clk)
begin
if (R==0 && C==1)
begin
if((state == `B_G2)&&(A_CAR == 1'b1))
state=`B_Y;
C=0;
end
else if ((R==1 &&C==0) | (R==1 && C==1))
state = `A_G2;
else
case(state)
`A_G2: state = B_CAR ? `A_Y : `A_G2;
`A_Y: state = `B_G1;
`B_G1:
begin
state = `B_G2;
C=1;
end
`B_G2: state = A_CAR ? `B_Y : `B_G2 ;
`B_Y: state = `A_G1 ;
`A_G1: state = `A_G2 ;
endcase
end
assign lightsA = ((state == `A_G2)|(state == `A_G1)) ? `GREEN: (state == `A_Y) ? `YELLOW : `RED;
assign lightsB = ((state == `B_G2)|(state == `B_G1)) ? `GREEN: (state == `B_Y) ? `YELLOW : `RED;
endmodule
</code></pre>
| 3 | 1,231 |
Asymmetrik FHIR mongo: partial patient stored
|
<p>I'm running <code>node-fhir-server-mongo</code>.</p>
<p>I'm trying to create a patient:</p>
<pre><code>curl -X PUT "http://localhost:3000/4_0_0/Patient/example1" -H "application/fhir+json" --data "@patient.json"
</code></pre>
<p>My <code>patient.json</code> is:</p>
<pre class="lang-json prettyprint-override"><code>{
"resourceType": "Patient",
"id": "example",
"text": {
"status": "generated",
"div": "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t\t<table>\n\t\t\t\t<tbody>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>Name</td>\n\t\t\t\t\t\t<td>Peter James \n <b>Chalmers</b> (&quot;Jim&quot;)\n </td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>Address</td>\n\t\t\t\t\t\t<td>534 Erewhon, Pleasantville, Vic, 3999</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>Contacts</td>\n\t\t\t\t\t\t<td>Home: unknown. Work: (03) 5555 6473</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>Id</td>\n\t\t\t\t\t\t<td>MRN: 12345 (Acme Healthcare)</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</tbody>\n\t\t\t</table>\n\t\t</div>"
},
"identifier": [
{
"use": "usual",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "MR"
}
]
},
"system": "urn:oid:1.2.36.146.595.217.0.1",
"value": "12345",
"period": {
"start": "2001-05-06"
},
"assigner": {
"display": "Acme Healthcare"
}
}
],
"active": true,
"name": [
{
"use": "official",
"family": "Chalmers",
"given": [
"Peter",
"James"
]
},
{
"use": "usual",
"given": [
"Jim"
]
},
{
"use": "maiden",
"family": "Windsor",
"given": [
"Peter",
"James"
],
"period": {
"end": "2002"
}
}
],
"telecom": [
{
"use": "home"
},
{
"system": "phone",
"value": "(03) 5555 6473",
"use": "work",
"rank": 1
},
{
"system": "phone",
"value": "(03) 3410 5613",
"use": "mobile",
"rank": 2
},
{
"system": "phone",
"value": "(03) 5555 8834",
"use": "old",
"period": {
"end": "2014"
}
}
],
"gender": "male",
"birthDate": "1974-12-25",
"_birthDate": {
"extension": [
{
"url": "http://hl7.org/fhir/StructureDefinition/patient-birthTime",
"valueDateTime": "1974-12-25T14:35:45-05:00"
}
]
},
"deceasedBoolean": false,
"address": [
{
"use": "home",
"type": "both",
"text": "534 Erewhon St PeasantVille, Rainbow, Vic 3999",
"line": [
"534 Erewhon St"
],
"city": "PleasantVille",
"district": "Rainbow",
"state": "Vic",
"postalCode": "3999",
"period": {
"start": "1974-12-25"
}
}
],
"contact": [
{
"relationship": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0131",
"code": "N"
}
]
}
],
"name": {
"family": "du Marché",
"_family": {
"extension": [
{
"url": "http://hl7.org/fhir/StructureDefinition/humanname-own-prefix",
"valueString": "VV"
}
]
},
"given": [
"Bénédicte"
]
},
"telecom": [
{
"system": "phone",
"value": "+33 (237) 998327"
}
],
"address": {
"use": "home",
"type": "both",
"line": [
"534 Erewhon St"
],
"city": "PleasantVille",
"district": "Rainbow",
"state": "Vic",
"postalCode": "3999",
"period": {
"start": "1974-12-25"
}
},
"gender": "female",
"period": {
"start": "2012"
}
}
],
"managingOrganization": {
"reference": "Organization/1"
}
}
</code></pre>
<p>However, when I'm trying to look at mongo collections, I'm only getting:</p>
<pre><code>> db.Patient_4_0_0.find();
{ "_id" : "example", "id" : "example", "meta" : { "versionId" : "1", "lastUpdated" : "2021-04-22T12:35:57+00:00" }, "resourceType" : "Patient" }
</code></pre>
<p>Any other data is stored.</p>
<p>Any ideas?</p>
| 3 | 3,892 |
Filtering a dataframe based on numerical values in a column
|
<p>I am trying to filter the rows in a dataframe based on the values of a column. If the numerical value is above 2, then it takes those rows, if it is below 2 it should not take those rows.
Sample dataframe</p>
<pre><code>| Number | Machine Name | Number of jobs|
|:-------|:------------:| -------------:|
| One | Power Drill | 1 |
| Two | Wench | 3 |
|Three | Screwdriver | 9 |
</code></pre>
<p>Desired outcome: The code should look at the third column "Number of jobs" and see if the number is greater than 2 then it should take it, else it should ignore it.
This is my code:</p>
<pre><code>import pandas as pd
import openpyxl
import glob
import os
source_folder = r'C:\Users\Ahmed_Abdelmuniem\Desktop\YYY'
file_names = glob.glob(os.path.join(source_folder, '*.xlsm'))
target_file = 'XXX.xlsm'
table_2 = pd.read_excel(target_file)
job_list = [3,4,5,6,7,8,9,10]
new_df = table_2['Number of jobs'].isin(job_list)
</code></pre>
<p>I am getting the following error:</p>
<pre><code>C:\Users\Ahmed_Abdelmuniem\AppData\Local\Programs\Python\Python39\python.exe "C:/Users/Ahmed_Abdelmuniem/PycharmProjects/Rig Visualisation/main.py"
Traceback (most recent call last):
File "C:\Users\Ahmed_Abdelmuniem\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Number of jobs'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Ahmed_Abdelmuniem\PycharmProjects\Rig Visualisation\main.py", line 57, in <module>
new_df = table_2['Number of jobs'].isin(job_list)
File "C:\Users\Ahmed_Abdelmuniem\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\frame.py", line 3024, in __getitem__
indexer = self.columns.get_loc(key)
File "C:\Users\Ahmed_Abdelmuniem\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3082, in get_loc
raise KeyError(key) from err
KeyError: 'Number of jobs'
Process finished with exit code 1
</code></pre>
<p>Edit: Upon further investigation I discovered the following:</p>
<pre><code> Unnamed: 0 Unnamed: 1 Unnamed: 2 Unnamed: 3
0 NaN Number Machine Name Jobs
1 NaN 1 Power Drill 1
2 NaN 2 Wench 4
3 NaN 3 Screwdriver 5
</code></pre>
<p>It seems that pandas is not reading the column names, but rather it is reading them as unnamed, why is that?</p>
| 3 | 1,260 |
How to use Big Decimal in Jav ATW
|
<pre><code>package SI;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import java.math.*;
import java.math.BigDecimal;
import static oracle.jrockit.jfr.events.Bits.doubleValue;
import static oracle.jrockit.jfr.events.Bits.floatValue;
import static oracle.jrockit.jfr.events.Bits.intValue;
public class SI extends Frame implements ActionListener{
TextField ptf,rtf,ttf,sitf,atf,citf,atf1;
Button ab,sib,cib,ab1;
Label pl,rl,tl,sil,al,cil,al1;
SI(){
pl=new Label("Principal:");
pl.setBounds(15,50,50,20);
ptf=new TextField();
ptf.setBounds(150, 50, 150, 20);
rl=new Label("Rate:");
rl.setBounds(15,100,50,20);
rtf=new TextField();
rtf.setBounds(150, 100, 150, 20);
tl=new Label("Time:");
tl.setBounds(15,150,50,20);
ttf=new TextField();
ttf.setBounds(150, 150, 150, 20);
sil=new Label("Simple Interest:");
sil.setBounds(15,200,150,20);
sitf=new TextField();
sitf.setBounds(150, 200, 150, 20);
sitf.setEditable(false);
sib=new Button("Simple Interest");
sib.setBounds(120,400,100,50);
sib.addActionListener(this);
cil=new Label("Compound Interest:");
cil.setBounds(15,250,200,20);
citf=new TextField();
citf.setBounds(150, 250, 150, 20);
citf.setEditable(false);
cib=new Button("Compound Interest");
cib.setBounds(240,400,130,50);
cib.addActionListener(this);
al=new Label("Amount of SI:");
al.setBounds(15,300,200,20);
atf=new TextField();
atf.setBounds(150,300,150,20);
atf.setEditable(false);
ab=new Button("Amount of SI");
ab.setBounds(20,400,80,50);
ab.addActionListener(this);
al1=new Label("Amount of CI:");
al1.setBounds(300,300,200,20);
atf1=new TextField();
atf1.setBounds(390, 300, 150, 20);
atf1.setEditable(false);
ab1=new Button("Amount of CI");
ab1.setBounds(390,400,80,50);
ab1.addActionListener(this);
add(pl);
add(ptf);
add(rtf);
add(rl);
add(ttf);
add(tl);
add(sitf);
add(sil);
add(sib);
add(ab);
add(atf);
add(al);
add(ab1);
add(atf1);
add(al1);
add(cib);
add(citf);
add(cil);
setSize(600,600);
setLayout(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String s1=ptf.getText();
String s2=rtf.getText();
String s3=ttf.getText();
BigDecimal p=new BigDecimal("s1");
BigDecimal r=new BigDecimal("s2");
BigDecimal t=new BigDecimal("s3");
BigDecimal si=new BigDecimal("0");
BigDecimal a1=new BigDecimal("0");
BigDecimal a11=new BigDecimal("0");
BigDecimal b=new BigDecimal("");
BigDecimal h=new BigDecimal("100");
BigDecimal c=new BigDecimal("");
BigDecimal i=new BigDecimal("1");
BigDecimal d=new BigDecimal("0");
BigDecimal j=new BigDecimal("0");
BigDecimal g=d.subtract(p);
if(e.getSource()==sib){
b=p.multiply(r).multiply(t).divide(h);
}else if(e.getSource()==cib){
c=i.add(r).divide(h);
j=c.pow(intValue(t));
d=p.multiply(j);
si=p.multiply(t).multiply(r).divide(h);
a1=p.add(d);
}else if(e.getSource()==ab){
si=p.multiply(t).multiply(r).divide(h);
a1=p.add(d);
}else if(e.getSource()==ab1){
c=i.add(r).divide(h);
j=c.pow(intValue(t));
d=p.multiply(j);
si=p.multiply(t).multiply(r).divide(h);
a1=p.add(d);
a11=d.subtract(p);
}
String sit=String.valueOf(si);
sitf.setText(String.valueOf(si));
String at=String.valueOf(a1);
atf.setText(at);
String at1=String.valueOf(a11);
atf1.setText(String.valueOf(a11));
String cit=String.valueOf(d);
citf.setText(String.valueOf(d));
}
public static void main(String[] args) {
// TODO code application logic here
new SI();
}
}
</code></pre>
<p>This Applet is not working. When I click the button, it throws an error. this error started after I changed all double to BigDecimal. Please help me out. I am stuck here from many days. What is the mistake here. I do not have much idea about BigDecimal. I am new to it. please help me out. Why does it throw an error?</p>
| 3 | 2,418 |
ListView Renderer view cell text moves towards right on grouping
|
<p>I have used a renderer for my listview because groupheader used to get stuck on scrolling. After using the rendered the scroll issue got fixed but </p>
<ul>
<li>The viewcell text got aligned towards the right on Load.</li>
<li>As you scroll the aligning issue did not appear.</li>
</ul>
<p>How to align the viewcell text in the correct way (towards left, how it appears when scrolling)</p>
<p>This is my code in renderer</p>
<pre><code>public class CustomListviewEventDetailsRenderer : ListViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
{
base.OnElementChanged(e);
if (this.Control != null && e.NewElement != null)
{
var frame = CoreGraphics.CGRect.Empty;
var tbl = new UITableView(frame, UITableViewStyle.Grouped)
{
Source = this.Control.Source
};
this.SetNativeControl(tbl);
}
}
}
</code></pre>
<p>XAML:</p>
<pre><code> <local1:CustomListviewEventDetails x:Name="lstItems" HasUnevenRows="True" SeparatorVisibility="None" BackgroundColor="#EEEEEE" ItemsSource="{Binding lstViewItemSource}" ItemSelected="lstItems_ItemSelected" VerticalOptions="FillAndExpand" HeightRequest="{Binding LtHeight}"
IsGroupingEnabled="True" >
<local1:CustomListviewEventDetails.GroupHeaderTemplate>
<DataTemplate>
<local1:CustomViewCellFS Height="30" >
<StackLayout Padding="20,0,0,0" VerticalOptions="CenterAndExpand" BackgroundColor="Green">
<Label Text="{Binding SectionName}" FontSize="15" FontAttributes="Bold" TextColor="Gray" VerticalOptions="CenterAndExpand" VerticalTextAlignment="Center" />
</StackLayout>
</local1:CustomViewCellFS>
</DataTemplate>
</local1:CustomListviewEventDetails.GroupHeaderTemplate>
<local1:CustomListviewEventDetails.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout Padding="0,0,0,0" Margin="0,0,0,0">
<Grid RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="5"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.1*"></ColumnDefinition>
<ColumnDefinition Width="0.9*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Text="{Binding PackageQuantity}" FontSize="15" TextColor="Black" HorizontalOptions="Start" IsVisible="{Binding PackageNameVisibility}" FontAttributes="Bold" >
</Label>
<Label Grid.Row="0" Grid.Column ="1" Text="{Binding PackageName}" FontSize="15" TextColor="Black" HorizontalOptions="Start" HorizontalTextAlignment="Start" IsVisible="{Binding PackageNameVisibility}" FontAttributes="Bold" ></Label>
<Label Grid.Row="1" Grid.Column="0" Text="{Binding Quantity}" FontSize="15" TextColor="Black" HorizontalOptions="Start" HorizontalTextAlignment="Start" IsVisible="{Binding PackageNameVisibility}" >
</Label>
<Label Grid.Row="1" Grid.Column="1" Text="{Binding Item}" FontSize="15" TextColor="Black" HorizontalOptions="StartAndExpand" HorizontalTextAlignment="Start" IsVisible="{Binding PackageNameVisibility}">
</Label>
<Label Grid.Row="2" Grid.Column="0" Text="{Binding SectionQuantity}" FontSize="15" TextColor="Black" HorizontalOptions="Start" HorizontalTextAlignment="Start" IsVisible="{Binding SectionItemVisibility}" >
</Label>
<Label Grid.Row="2" Grid.Column="1" Text="{Binding SectionItem}" FontSize="15" TextColor="Black" HorizontalOptions="StartAndExpand" HorizontalTextAlignment="Start" IsVisible="{Binding SectionItemVisibility}" >
</Label>
<BoxView x:Name="txt" Grid.Row="3" Grid.ColumnSpan="2" HeightRequest="5" ></BoxView>
</Grid>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</local1:CustomListviewEventDetails.ItemTemplate>
</local1:CustomListviewEventDetails>
</code></pre>
| 3 | 3,897 |
How to automatically call for a next iterator inside a loop
|
<p>I recently started scripting and am having difficulties with nested loops. I'm not getting the first iterator object from the first loop as an input to the second to run properly.</p>
<p>The problem itself is quite simple. I would like to change the second item (‘20’) on row 1 in my data to a number from the range and create a file.
So if the first number from the range is 14 then the first line of the file is (L,14,0,0,0,0) and gets a name data1.txt.</p>
<p><strong>Data:</strong></p>
<p>L,1,5.827,20,-4.705,0<br>
L,20,0,0,0,0<br>
L,12,15,0,-6,0</p>
<p><strong>Original Script:</strong></p>
<pre><code>import re
from itertools import islice
import numpy as np
x = np.arange(14,30.5,0.5)
size = x.size
with open('data.txt', 'r') as line:
for line in islice(line, 1, 2):
re.sub(r'\s', '', line).split(',')
nline = line[:2] + line[3:]
x = iter(x)
y = next(x)
for i in x:
nline = nline[:2] + str(y)+ nline[3:]
with open('data.txt', 'r') as file:
data = file.readlines()
data[1] = nline
for i in range(1,size):
with open('data%i.txt' %i, 'w') as file:
file.writelines(data)
</code></pre>
<p>EDITED:</p>
<p>Ive made some progress with my script and Im almost there. </p>
<p>After the first loop I have the output that I need (33 cases). All I would like to do now is to write them to a 33 unique files, named data1 to data33. What seems to happen however is that the second loop iterates through the first loop another 33 times and creates 1089 cases. So what ends up in the files is only the last line of the first loop. </p>
<p>Any suggestions how to allow the second loop for file creation but disable it for data? </p>
<p><strong>Updated Script:</strong></p>
<pre><code>import re
from itertools import islice
import numpy as np
x = np.arange(14,30.5,0.5)
size = x.size
with open('data.txt', 'r') as line:
for line in islice(line, 1, 2):
re.sub(r'\s', '', line).split(',')
for i in x:
y=str(i)
nline = line[:2] + y + line[4:]
with open('data.txt', 'r') as file:
data = file.readlines()
data[1] = nline
for i in range(1,size+1):
with open('data%i.txt' %i, 'w') as file:
file.writelines(data)
print data
</code></pre>
| 3 | 1,159 |
Why the params go through the function when i use junit?
|
<p>I want to test the controller of java-end,so I need a params from web which is request for the controller.But I am confused of map&json,and the params I made is cannot use.</p>
<p>the key code:</p>
<pre><code>public Object updateListLoggerUser(@RequestBody Map<String, Object> params, Model model, HttpServletRequest request)
throws IOException {
if (params.get("statusEvents") == null) {
model.addAttribute(ReturnMessage.STATUS, ReturnMessage.STATUS_NOT_OK);
model.addAttribute(ReturnMessage.ERROR_CODE, ReturnMessage.ERROR_CODE_MESSAGE.ERROR_CODE_500);
model.addAttribute(ReturnMessage.ERROR_MESSAGE, "No statusEvents parameter");
}
List<HOSStatusEvent> statusEvents = JSON.parseArray(JSON.toJSONString(params.get("statusEvents")),
HOSStatusEvent.class);//I need make a params whose key is "statusEvent"
UserSessionDto usDto = ControllerUtils.getCurrentClientAdminInfo(request);
hourOfServiceService.generateOneDayStatusEventForUser(usDto.getUserId(), statusEvents.get(0).getShortDate(),
statusEvents);
try {
hourOfServiceService.reCal(usDto.getUserId(), statusEvents.get(0).getShortDate(), 0);
} catch (Exception e) {
model.addAttribute(ReturnMessage.STATUS, ReturnMessage.STATUS_NOT_OK);
model.addAttribute(ReturnMessage.ERROR_CODE, ReturnMessage.ERROR_CODE_MESSAGE.ERROR_CODE_500);
model.addAttribute(ReturnMessage.ERROR_MESSAGE, ReturnMessage.ERROR_CODE_MESSAGE.ERROR_MESSAGE_500);
}
model.addAttribute(ReturnMessage.STATUS, ReturnMessage.STATUS_OK);
return model;
}
</code></pre>
<p>and what fields is the HOSStatusEvent model have:</p>
<pre><code>private String userId;//"Jo"
private String devId;//"car123"
private Integer shortDate;//20160615
private Integer startTime;//1412
private Integer endTime;//1425
private Integer duration;//13
private String comments;//"some comments"
private String location;//"Hubei China"
private Integer status;//3
private Integer specialType;//1
</code></pre>
<p>My params which is incorrect:</p>
<pre><code>statusEvent=[{'userId': 'jo','shortDate': '20160615','startTime': '1400','endTime': '1406','duration': '6','status': '3', 'comments': 'testlistupdate','location': 'sz'},{'userId': 'jo','shortDate: '20160615','startTime': '1412','endTime': '1525','duration': '13','status': '3','comments': 'testsingleupdate','location': 'Hubei China'}]
</code></pre>
<p>this is my relevant test Code(this part only show how I mock the param):</p>
<pre><code> params.put("statusEvents", "[{'userId':'jo','shortDate':'20160615','startTime':'1400','endTime':'1406','duration':'6','status': '3','comments':'testlistupdate','location':'sz'},{'userId':'jo','shortDate':'20160615','startTime':'1412','endTime':'1525','duration':'13','status':'3','comments':'testsingleupdate','location':'HubeiChina'}]");
//params.put("type", "S");
String content = JSON.toJSONString(params);
String contentType = "application/json";
String charset = "utf-8";
RequestEntity requestEntity = new StringRequestEntity(content, contentType, charset);
postMethod.setRequestEntity(requestEntity);
httpClient.getState().addCookies(cookies);
int status = httpClient.executeMethod(postMethod);
</code></pre>
<p>I test the function updateListLoggerUser() in the first block in this page with Junit.
but when i debug it ,it will print an exception while in this line:</p>
<pre><code>List<HOSStatusEvent> statusEvents = JSON.parseArray(JSON.toJSONString(params.get("statusEvents")),
HOSStatusEvent.class);
</code></pre>
| 3 | 1,271 |
Issue while making HTTPs request from Hololens to Azure OCR service
|
<p>We are migrating an application from UWP to Unity, in which we are trying to access azure OCR services from Unity . While making a https request from unity we are getting the below error
(Filename: C:\buildslave\unity\build\Runtime/Export/Debug.bindings.h Line: 45)</p>
<pre><code>Exception thrown at 0x7787A0CB in EyeTrackingCus01.exe: Microsoft C++ exception:
Il2CppExceptionWrapper at memory location 0x156DEEC0.
Exception thrown at 0x7787A0CB in EyeTrackingCus01.exe: Microsoft C++ exception:
Il2CppExceptionWrapper at memory location 0x156DF048.
Exception thrown at 0x7787A0CB in EyeTrackingCus01.exe: Microsoft C++ exception:
Il2CppExceptionWrapper at memory location 0x031AE3C8.
The thread 0x1410 has exited with code 0 (0x0).
</code></pre>
<p>The code snippet used is as follows:</p>
<pre><code>static async Task MakeOCRRequest(string imageFilePath)
{
Debug.Log("MakeOCRRequest Function Called");
string subscriptionKey = "xxxxxxxxxxxxx";
string endpoint = “https://hololensxxxx.cognitiveservices.azure.com/”;
// the OCR method endpoint
string uriBase = endpoint + "vision/v2.1/ocr";
string requestParameters = "language=unk&detectOrientation=true";
string uri = uriBase + "?" + requestParameters;
byte[] data = GetImageAsByteArray(imageFilePath);
Debug.Log("Image File Path: "+imageFilePath);
Debug.Log("Image File Size: "+data.Length.ToString());
Debug.Log("Response: Image Converted into byte Array");
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
Debug.Log("Request object:" + req);
req.Method = "POST";
req.ContentType = "application/octet-stream";
req.ContentLength = data.Length;
req.Expect = "application/json";
req.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
req.GetRequestStream().Write(data, 0, data.Length);
Debug.Log("Before the Response");
HttpWebResponse response = (HttpWebResponse)req.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
Debug.Log("Response:"+json);
}
catch (Exception e)
{
Debug.log("Error" + e.Message);
}
}
</code></pre>
| 3 | 1,422 |
Storing HTML Form input as an Object using a Constructor class and a dynamic variable name (Plain JS)
|
<pre><code><form id="projectForm" onsubmit="return ptitle.value = new Project(this);">
<div class="form-row">
<label for="ptitle">Title: </label>
<input type="text" id="ptitle" name="ptitle"><br>
</div>
<div class="form-row">
<label for="pdescription">Discription: </label>
<input type="text" id="pdescription" name="pdescription"><br>
</div>
<div class="form-row">
<label for="pdueDate">Due Date</label>
<input type="date" id="pdueDate" name="pdueDate"><br>
</div>
<div class="form-row">
<label for="high">High</label>
<input type="radio" id="high" name="priority">
<label for="low">Low</label>
<input type="radio" id="low" name="priority"><br>
<input id="submit" type="submit" value="submit">
</div>
</form>
</code></pre>
<p>So I would like to take the data submitted from this form and call a constructor method within the Projects class. I'd also like to be able to dynamically generate the variable name from the title value of the form. Here's the JavaScript code. I'll need to use plain JS as that is what's required for the project! We're also required to use a constuctor class or factory function to generate the projects. As you can see I've tried to take a stab at it but unfortunately it hasn't worked. Thanks in advance.</p>
<pre><code>class Project {
constructor(form) {
this.title = form.ptitle.value;
this.description = form.pdescription.value;
this.dueDate = form.pdueDate.value;
this.priority = form.priority.value;
}
todoList = {};
addTodoList(value, description) {
this.todoList[value] = description;
}
removeTodoList(key) {
delete this.todoList[key];
}
}
</code></pre>
<p>Thanks again!!!</p>
| 3 | 1,047 |
Exception Unhandle System.IndexOutOfRangeException
|
<p>This code is about viewing a published consultation schedule. Unfortunately I'm stuck with the if statement. The error occurs at line : If dr("Lecturer") = ComboBox2.SelectedItem Then || I'm using a combobox to display the data from a database, which means there is a list of items in the combobox, and I will select any lecturer so it will display into the form. I have a database that contained the published schedule inside as shown at the pic. And all data stored in here(database) are actually unavailable(declared as red=unavailable, lime=available), except for the available does not stored into the database. So, what I'm doing now is to read and match the "Time", "Available" and "Lecturer" from the database, and change it to (red color) into the respective label(in lime colored).</p>
<p><a href="https://i.stack.imgur.com/Imy2q.png" rel="nofollow noreferrer">Database</a></p>
<p><a href="https://i.stack.imgur.com/vJejJ.png" rel="nofollow noreferrer">The Form</a></p>
<pre><code> Imports System.Data.OleDb
Public Class viewconsultationschedule
Dim time1 As String = "8.00am-10.00am"
Dim time2 As String = "10.00am-12.00pm"
Dim time3 As String = "12.00pm-2.00pm"
Dim time4 As String = "2.00pm-4.00pm"
Dim time5 As String = "4.00pm-6.00pm"
Dim day1 As String = "Monday"
Dim day2 As String = "Tuesday"
Dim day3 As String = "Wednesday"
Dim day4 As String = "Thursday"
Dim day5 As String = "Friday"
Dim conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=sdpdatabase.accdb;Persist Security Info=False;")
Dim cmd As OleDbCommand
Dim cmd2 As OleDbCommand
Dim dr As OleDbDataReader
Dim sql As String
Dim sql2 As String
Private Sub ToolStrip1_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs) Handles ToolStrip1.ItemClicked
End Sub
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
'If (ComboBox2.SelectedIndex = 3) Then
Dim time1 As String = "8.00am-10.00am"
Dim time2 As String = "10.00am-12.00pm"
Dim time3 As String = "12.00pm-2.00pm"
Dim time4 As String = "2.00pm-4.00pm"
Dim time5 As String = "4.00pm-6.00pm"
Dim day1 As String = "Monday"
Dim day2 As String = "Tuesday"
Dim day3 As String = "Wednesday"
Dim day4 As String = "Thursday"
Dim day5 As String = "Friday"
Dim conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=sdpdatabase.accdb;Persist Security Info=False;")
sql = "Select * FROM consultationschedule WHERE Lecturer=@Lecturer" ' And [Time]=@Time AND weekDay=@weekDay "
sql2 = "Select COUNT (*) FROM consultationschedule WHERE Lecturer=@lecturer"
conn.Open()
cmd = New OleDbCommand(sql, conn)
cmd2 = New OleDbCommand(sql2, conn)
cmd.Parameters.AddWithValue("@lecturer", ComboBox2.SelectedItem)
'cmd.Parameters.AddWithValue("@[Time]", time1)
'cmd.Parameters.AddWithValue("@weekDay", day1)
cmd2.Parameters.AddWithValue("@lecturer", ComboBox2.SelectedItem)
'cmd2.Parameters.AddWithValue("@[Time]", time2)
'cmd2.Parameters.AddWithValue("@weekDay", day2)
Dim count As Integer = cmd2.ExecuteScalar()
dr = cmd.ExecuteReader
dr = cmd2.ExecuteReader
If (dr.HasRows) Then
For i = 1 To count
If (i = 1) Then
dr.Read()
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label11.BackColor = Color.Red
Else
Label11.BackColor = Color.Lime
End If
ElseIf (i = 2) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label12.BackColor = Color.Red
Else
Label12.BackColor = Color.Lime
End If
ElseIf (i = 3) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label13.BackColor = Color.Red
Else
Label13.BackColor = Color.Lime
End If
ElseIf (i = 4) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label14.BackColor = Color.Red
Else
Label14.BackColor = Color.Lime
End If
ElseIf (i = 5) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label15.BackColor = Color.Red
Else
Label15.BackColor = Color.Lime
End If
ElseIf (i = 6) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label16.BackColor = Color.Red
Else
Label16.BackColor = Color.Lime
End If
ElseIf (i = 7) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label17.BackColor = Color.Red
Else
Label17.BackColor = Color.Lime
End If
ElseIf (i = 8) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label18.BackColor = Color.Red
Else
Label18.BackColor = Color.Lime
End If
ElseIf (i = 9) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label19.BackColor = Color.Red
Else
Label19.BackColor = Color.Lime
End If
ElseIf (i = 10) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label20.BackColor = Color.Red
Else
Label20.BackColor = Color.Lime
End If
ElseIf (i = 11) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label21.BackColor = Color.Red
Else
Label21.BackColor = Color.Lime
End If
ElseIf (i = 12) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label22.BackColor = Color.Red
Else
Label22.BackColor = Color.Lime
End If
ElseIf (i = 13) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label23.BackColor = Color.Red
Else
Label23.BackColor = Color.Lime
End If
ElseIf (i = 14) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label24.BackColor = Color.Red
Else
Label24.BackColor = Color.Lime
End If
ElseIf (i = 15) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label25.BackColor = Color.Red
Else
Label25.BackColor = Color.Lime
End If
ElseIf (i = 16) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label26.BackColor = Color.Red
Else
Label26.BackColor = Color.Lime
End If
ElseIf (i = 17) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label27.BackColor = Color.Red
Else
Label27.BackColor = Color.Lime
End If
ElseIf (i = 18) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label28.BackColor = Color.Red
Else
Label28.BackColor = Color.Lime
End If
ElseIf (i = 19) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label29.BackColor = Color.Red
Else
Label29.BackColor = Color.Lime
End If
ElseIf (i = 20) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label30.BackColor = Color.Red
Else
Label30.BackColor = Color.Lime
End If
ElseIf (i = 21) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label33.BackColor = Color.Red
Else
Label33.BackColor = Color.Lime
End If
ElseIf (i = 22) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label34.BackColor = Color.Red
Else
Label34.BackColor = Color.Lime
End If
ElseIf (i = 23) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label35.BackColor = Color.Red
Else
Label35.BackColor = Color.Lime
End If
ElseIf (i = 24) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label36.BackColor = Color.Red
Else
Label36.BackColor = Color.Lime
End If
ElseIf (i = 25) Then
If dr("Lecturer") = ComboBox2.SelectedItem Then
If dr("Available") = "1" Then
Label37.BackColor = Color.Red
Else
Label37.BackColor = Color.Lime
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
Next
End If
</code></pre>
| 3 | 16,151 |
Why am I getting "Document is empty" when I preview in Jasper studio book mode?
|
<p>I use Jasper Report studio to design the report using the book template, I'm sure a single report is ok, but when I preview the merged report, I found that an empty document is returned, showing "Document is empty", the following is the code of the main page. Please help me!</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.19.1.final using JasperReports Library version 6.19.1-867c00bf88cd4d784d404379d6c05e1b419e8a4c -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="healthdoc" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" sectionType="Part" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="30" bottomMargin="30" whenResourceMissingType="Empty" uuid="d2716064-8ae4-40cf-a575-33afba400e3a">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="business"/>
<property name="net.sf.jasperreports.print.create.bookmarks" value="true"/>
<property name="com.jaspersoft.studio.data.sql.tables" value=""/>
<property name="com.jaspersoft.studio.book.group.cover.header" value="Cover and Contents"/>
<property name="com.jaspersoft.studio.book.group.cover.footer" value="Backcover"/>
<property name="ireport.jasperserver.url" value="http://10.0.1.33:8188/jasperserver/"/>
<property name="ireport.jasperserver.user" value="jasperadmin"/>
<property name="ireport.jasperserver.report.resource" value="/reports/hms/hms_doc_files/main_jrxml"/>
<property name="ireport.jasperserver.reportUnit" value="/reports/hms/hms_doc"/>
<style name="Title" forecolor="#FFFFFF" fontName="stsong" fontSize="50" isBold="false" pdfFontName="stsong"/>
<style name="SubTitle" forecolor="#CCCCCC" fontName="stsong" fontSize="18" isBold="false" pdfFontName="stsong"/>
<style name="Column header" forecolor="#666666" fontName="stsong" fontSize="14" isBold="true" pdfFontName="stsong"/>
<style name="Detail" mode="Transparent" fontName="stsong" pdfFontName="stsong"/>
<parameter name="id" class="java.lang.Integer">
<defaultValueExpression><![CDATA[1317]]></defaultValueExpression>
</parameter>
<queryString language="SQL">
<![CDATA[select 1 FROM mem_guest t]]>
</queryString>
<group name="cover">
<groupHeader>
<part uuid="48cb43f5-1d78-4a4e-94c7-bc80581e2049">
<property name="net.sf.jasperreports.bookmarks.data.source.parameter" value="REPORT_DATA_SOURCE"/>
<p:subreportPart xmlns:p="http://jasperreports.sourceforge.net/jasperreports/parts" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/parts http://jasperreports.sourceforge.net/xsd/parts.xsd">
<subreportParameter name="guestId">
<subreportParameterExpression><![CDATA[$P{id}]]></subreportParameterExpression>
</subreportParameter>
<subreportExpression><![CDATA["cover.jasper"]]></subreportExpression>
</p:subreportPart>
</part>
<part evaluationTime="Report" uuid="bf47c82d-6bc2-422e-97e2-dfa09e013bdb">
<property name="net.sf.jasperreports.bookmarks.data.source.parameter" value="REPORT_DATA_SOURCE"/>
<p:subreportPart xmlns:p="http://jasperreports.sourceforge.net/jasperreports/parts" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/parts http://jasperreports.sourceforge.net/xsd/parts.xsd">
<subreportParameter name="guestId">
<subreportParameterExpression><![CDATA[$P{id}]]></subreportParameterExpression>
</subreportParameter>
<subreportExpression><![CDATA["content.jasper"]]></subreportExpression>
</p:subreportPart>
</part>
</groupHeader>
</group>
</jasperReport>
</code></pre>
| 3 | 2,493 |
Node.js ffmetadata incorrect codec parameters
|
<p>I'm making a song downloader app in Node.js. I managed to get everything to work, the app downloads the song and downloads its artwork (image). So I have the mp3 file and jpg file. The only problem is attaching the jpg file to the mp3 file.</p>
<p>I'm using the ffmetadata node.js module. I downloaded and installed its dependency "ffmpeg" cli.</p>
<p>Now when I try to write the metadata to the mp3 file and attach the artwork it spits this error:</p>
<pre><code>Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
</code></pre>
<p>My code:</p>
<pre class="lang-js prettyprint-override"><code>ffmetadata.write('test.mp3', {}, {attachments: ['test.jpg']}, function(err) {
if (err) console.error(err);
});
</code></pre>
<p>The error:</p>
<pre><code>[Error: ffmpeg version N-73872-g6b96c70 Copyright (c) 2000-2015 the FFmpeg developers
built with gcc 4.9.2 (GCC)
configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libdcadec --enable-libfreetype --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-aacenc --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-lzma --enable-decklink --enable-zlib
libavutil 54. 28.100 / 54. 28.100
libavcodec 56. 50.101 / 56. 50.101
libavformat 56. 40.101 / 56. 40.101
libavdevice 56. 4.100 / 56. 4.100
libavfilter 5. 25.100 / 5. 25.100
libswscale 3. 1.101 / 3. 1.101
libswresample 1. 2.101 / 1. 2.101
libpostproc 53. 3.100 / 53. 3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'songs/Irresistible - Fall Out Boy (Lyrics).mp3':
Metadata:
major_brand : dash
minor_version : 0
compatible_brands: iso6mp41
creation_time : 2015-04-03 10:45:25
Duration: 00:03:26.94, start: 0.000000, bitrate: 128 kb/s
Stream #0:0(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 125 kb/s (default)
Metadata:
creation_time : 2015-04-03 10:45:25
handler_name : SoundHandler
Input #1, image2, from 'songs/albumart/Irresistible - Fall Out Boy (Lyrics).jpg':
Duration: 00:00:00.04, start: 0.000000, bitrate: 24578 kb/s
Stream #1:0: Video: mjpeg, yuvj444p(pc, bt470bg/unknown/unknown), 640x640 [SAR 300:300 DAR 1:1], 25 tbr, 25 tbn, 25 tbc
[mp3 @ 0000000004865d80] Invalid audio stream. Exactly one MP3 audio stream is required.
Output #0, mp3, to 'songs\Irresistible - Fall Out Boy (Lyrics).ffmetadata.mp3':
Metadata:
major_brand : dash
minor_version : 0
compatible_brands: iso6mp41
dryRun : true
encoder : Lavf56.40.101
Stream #0:0(und): Audio: aac (mp4a / 0x6134706D), 44100 Hz, stereo, 125 kb/s (default)
Metadata:
creation_time : 2015-04-03 10:45:25
handler_name : SoundHandler
Stream #0:1: Video: mjpeg, yuvj444p, 640x640 [SAR 300:300 DAR 1:1], q=2-31, 25 tbr, 25 tbn, 25 tbc
Stream mapping:
Stream #0:0 -> #0:0 (copy)
Stream #1:0 -> #0:1 (copy)
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
]
</code></pre>
| 3 | 1,436 |
change JDK version in octave on mac
|
<p>Octave 3.8.2, OS X 10.10.4</p>
<p>I used</p>
<pre><code>ml_jar_version=javaMethod('getProperty','java.lang.System','java.version');
ml_jar_version=['Java ' ml_jar_version];
</code></pre>
<p>to check the java version and I got</p>
<pre><code>ml_jar_version = Java 1.6.0_65
</code></pre>
<p>However, I want Octave to use JDK 1.7 and so I typed</p>
<pre><code>setenv("JAVA_HOME","/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home");
</code></pre>
<p>but <code>ml_jar_version</code> did not change.</p>
<p><strong>My question</strong> is: how to make Octave to use JDK 1.7?</p>
<p><strong>Edit 1</strong>: my Octave was installed through homebrew. I believe homebrew just downloaded precompiled binaries. The following is the configuration of my Octave installation:</p>
<pre><code>homebrew/science/octave: stable 3.8.2 (bottled), HEAD
a high-level interpreted language for numerical computations.
https://www.gnu.org/software/octave/index.html
/usr/local/Cellar/octave/3.8.2_1 (2111 files, 54M)
Poured from bottle
/usr/local/Cellar/octave/3.8.2_2 (2111 files, 54M) *
Poured from bottle
From: https://github.com/homebrew/homebrew-science/blob/master/octave.rb
==> Dependencies
Build: pkg-config ✔, gnu-sed ✘
Required: pcre ✔, qscintilla2 ✔, qt ✔, pstoedit ✔
Recommended: gnuplot ✔, suite-sparse421 ✔, readline ✔, arpack ✔, fftw ✔, glpk ✔, gl2ps ✔, graphicsmagick ✔, hdf5 ✔, qhull ✔, qrupdate ✔, epstool ✔, ghostscript ✔
Optional: openblas ✘
==> Options
--with-jit
Use the experimental JIT support (not recommended)
--with-native-graphics
Use native OpenGL/FLTKgraphics (does not work with the GUI)
--with-openblas
Use OpenBLAS instead of native LAPACK/BLAS
--without-arpack
Build without arpack support
--without-check
Skip build-time tests (not recommended)
--without-curl
Do not use cURL (urlread/urlwrite/@ftp)
--without-docs
Don't build documentation
--without-epstool
Build without epstool support
--without-fftw
Do not use FFTW (fft,ifft,fft2,etc.)
--without-ghostscript
Build without ghostscript support
--without-gl2ps
Build without gl2ps support
--without-glpk
Do not use GLPK
--without-gnuplot
Do not use gnuplot graphics
--without-graphicsmagick
Build without graphicsmagick support
--without-gui
Do not build the experimental GUI
--without-hdf5
Do not use HDF5 (hdf5 data file support)
--without-java
Build without java support
--without-qhull
Do not use the Qhull library (delaunay,voronoi,etc.)
--without-qrupdate
Do not use the QRupdate package (qrdelete,qrinsert,qrshift,qrupdate)
--without-readline
Build without readline support
--without-suite-sparse421
Do not use SuiteSparse (sparse matrix operations)
--without-zlib
Do not use zlib (compressed MATLAB file formats)
--HEAD
Install HEAD version
</code></pre>
| 3 | 1,049 |
Element type is invalid. Expected string
|
<p><a href="https://i.stack.imgur.com/NqNVk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NqNVk.png" alt="enter image description here"></a></p>
<p>When I try this code it shows this strange error. And most interesting part is that there was not any change in render method. It worked perfectly unless I add mapvew inside the view. Here is the code:</p>
<pre><code>import React, {Component} from "react";
import {View, Image, MapView} from "react-native";
import {
Container,
Header,
Content,
Footer,
FooterTab,
Button,
Icon,
Text,
Left,
Right,
Body,
Title,
Thumbnail,
Grid,
Row,
Col,
} from "native-base";
import typographystyles from '../styles/typographystyles';
import { primary, secondary } from '../styles/variables';
class PostScreen extends Component {
render() {
return (
<Container style={styles.container}>
<Content>
<View>
<Grid>
<Row>
<Col style={styles.col} >
<Text style={typographystyles.heading1}> Jennifer </Text>
<Text style={{marginTop:-20, fontSize:16, marginLeft:15}}> Vew and Edit Profile </Text>
</Col>
<Col style={styles.col}>
<Thumbnail style={{marginTop:20}} source={require("../img/profile2.jpg")}/ >
</Col>
</Row>
</Grid>
</View>
<View style={{marginLeft:15, marginBottom:20}}>
<Text style={{marginTop:10,marginBottom:10, fontSize:18}}> 90 EUR per night </Text>
</View>
<Text style={{marginLeft:5, marginRight:5}}>
Lorem ipsum dolor sit amet, eum iisque accommodare cu, ex enim eligendi appareat nec. Magna quando aliquid mel ea, exerci nonumes maiestatis eum ei, harum possim sed ut. Mea omnis bonorum posidonium ne, pri ne illud suavitate assentior. His choro numquam ad, mei te integre vituperatoribus. An vim nobis similique theophrastus, mazim mandamus assentior pro id.
Ad bonorum senserit postulant eum, quo et virtute feugiat. Reque laudem referrentur ex mei. Eu vel dico sonet iudicabit. Eos et falli fabulas, eam quis timeam voluptatum ea. Nullam persequeris ne nec. Reque error vivendum sit id, te sit partem aeterno feugait.
</Text>
<View style={{flex: 1}}>
<MapView
style={styles.map}
showsUserLocation={true}/>
</View>
</Content>
</Container>
);
}
}
const styles = {
img: {
height:200,
width: null,
flex:1,
},
col:{
marginTop:30,
justifyContent: "center",
alignItems: "center",
},
map:{
flex:1
},
}
export default PostScreen;
</code></pre>
<p>What is wrong with this code? How can it be fixed?
As I said it was caused only after trying to add mapvew.</p>
<p>Thanks in advance :)</p>
| 3 | 1,208 |
how to code to get facebook friend list in ios7
|
<p>Hi am using following code</p>
<pre><code>-(IBAction)FacebookFriendBtnClk:(id)sender
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
__block ACAccount *facebookAccount = nil;
ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// Specify App ID and permissions
NSDictionary *options = @{
ACFacebookAppIdKey: @"743178525726332",
ACFacebookPermissionsKey: @[@"publish_stream", @"publish_actions",@"read_friendlists"],
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[accountStore requestAccessToAccountsWithType:facebookAccountType
options:options completion:^(BOOL granted, NSError *error)
{
if (granted)
{
NSArray *accounts = [accountStore accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
}
else {
NSLog(@"error.localizedDescription======= %@", error.localizedDescription);
}
}];
NSArray *accounts = [accountStore accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
//NSString *acessToken = [NSString stringWithFormat:@"%@",facebookAccount.credential.oauthToken];
//NSDictionary *parameters = @{@"access_token": acessToken};
NSDictionary *param=[NSDictionary dictionaryWithObjectsAndKeys:@"picture,id,name,link,gender,last_name,first_name,username",@"fields", nil];
NSURL *feedURL = [NSURL URLWithString:@"https://graph.facebook.com/me/friends"];
SLRequest *feedRequest = [SLRequest
requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:feedURL
parameters:param];
feedRequest.account = facebookAccount;
[feedRequest performRequestWithHandler:^(NSData *responseData,
NSHTTPURLResponse *urlResponse, NSError *error)
{
if(!error)
{
id json =[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(@"Dictionary contains data: %@", json );
if([json objectForKey:@"error"]!=nil)
{
//[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
//nameLabel.text = [json objectForKey:@"username"];
});
}
else{
//handle error gracefully
NSLog(@"error from get%@",error);
//attempt to revalidate credentials
}
}];
</code></pre>
<p>}</p>
<p>Am getting following error in log</p>
<pre><code> 2014-04-04 16:49:04.098 ImageProcessingDemo[4791:3c0b] error.localizedDescription======= (null)
2014-04-04 16:49:34.964 ImageProcessingDemo[4791:3f07] Dictionary contains data: {
error = {
code = 2500;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
}
</code></pre>
| 3 | 1,307 |
Bluehost MySQL and phpmyadmin select sql service.php running slow while insert, delete, and update commands works instantly
|
<p>I am using crud commands in an app and my commands for insert, delete and update in sql work instantly. The select query in my php file called service loads in a few hours. I was wondering what was causing this. It doesn't really make since to me considering the other commands work instantly. Besides it not loading in my app I have it in a website where I can view my table with the php file. This does not load either...</p>
<p>I have my service on a website secured with HTTPS, is there anything on bluehost that I need to change in settings? I also posted my code below for my php file. I've tried a few other coded formats and commented these out of which none work anyway. This leads me to believe this is some setting in bluehost. Anyone else with the same problems and found a solution they could share or any ideas of why this is happening?</p>
<pre><code><?php
$start = microtime(TRUE);
error_log('Connecting');
// Create connection
$connection=mysqli_connect("localhost","mlbroadv_admin","DpApp&483",
"mlbroadv_PlantAssistDB");
// Check connection
if ($connection == false) {
die("ERROR: Could not connect. "
.mysqli_connect_error());
}
// This SQL statement selects ALL from the table 'Locations'
error_log('Connection took' . microtime(TRUE) - $start);
// Check connection
// if ($connection == false) {
// die("ERROR: Could not connect. " .mysqli_connect_error());
// }
// This SQL statement selects ALL from the table 'Locations'
//$sql = "SELECT * FROM Notes";
$sql = "SELECT * FROM Notes";
error_log('Running select');
if ($result = mysqli_query($connection, $sql)){
error_log('Select took' . microtime(TRUE) - $start);
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
// Loop through each row in the result set
error_log('looping fetch');
while($row = $result->fetch_object())
{
error_log('Fetch is running at ' . microtime(TRUE) - $start);
// Add each row into our results array
$resultArray[] = $row;
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
error_log('Fetch is done at ' . microtime(TRUE) - $start);
// Close connections
mysqli_close($connection);
error_log('Connection closed at ' . microtime(TRUE) - $start);
?>
</code></pre>
<p>EDIT</p>
<p>Results for time</p>
<pre><code>[27-Jul-2022 07:17:15 America/Boise] Connecting
[27-Jul-2022 07:17:15 America/Boise] Connection took0.010892868041992
[27-Jul-2022 07:17:15 America/Boise] Running select
[27-Jul-2022 07:17:15 America/Boise] Select took0.012121915817261
[27-Jul-2022 07:17:15 America/Boise] looping fetch
[27-Jul-2022 07:17:15 America/Boise] Fetch is running at 0.012276887893677
[27-Jul-2022 07:17:15 America/Boise] Fetch is running at 0.012364864349365
[27-Jul-2022 07:17:15 America/Boise] Fetch is running at 0.012436866760254
[27-Jul-2022 07:17:15 America/Boise] Fetch is running at 0.012504816055298
[27-Jul-2022 07:17:15 America/Boise] Fetch is done at 0.012606859207153
[27-Jul-2022 07:17:15 America/Boise] Connection closed at 0.012848854064941
</code></pre>
| 3 | 1,136 |
Why gstreamer with vaapih264enc shows "context pad peer query failed"?
|
<p>I would like to use hardware encoding to compress a raw video file using gstreamer and vaapi. I am getting <code>Could not initialize supporting library</code>, which does not allow encoder to open. Possibly <code>context pad peer query failed</code> is the root cause for this. But I am not sure. I use the following pipeline:</p>
<pre><code>gst-launch-1.0 -v filesrc location=input.raw ! videoparse width=1280 height=1024 format=yuy2 framerate=20/1 ! vaapih264enc ! h264parse ! qtmux ! filesink location=compressed.mov
</code></pre>
<p>Pipeline fails with message:</p>
<pre><code>Setting pipeline to PAUSED ...
ERROR: Pipeline doesn't want to pause.
ERROR: from element /GstPipeline:pipeline0/GstVaapiEncodeH264:vaapiencodeh264-0: Could not initialize supporting library.
Additional debug info:
gstvideoencoder.c(1534): gst_video_encoder_change_state (): /GstPipeline:pipeline0/GstVaapiEncodeH264:vaapiencodeh264-0:
Failed to open encoder
Setting pipeline to NULL ...
Freeing pipeline ...
</code></pre>
<p>What am I doing wrong?</p>
<p>Using <code>GST_DEBUG=3 gst-launch-1.0 --gst-debug-level=4</code> to start the pipeline gives me this:</p>
<pre><code>INFO GST_STATES gstbin.c:2316:gst_bin_element_set_state:<vaapiencodeh264-0> current NULL pending VOID_PENDING, desired next READY
INFO GST_CONTEXT gstvaapivideocontext.c:106:context_pad_query:<vaapiencodeh264-0:src> context pad peer query failed
INFO GST_CONTEXT gstvaapivideocontext.c:106:context_pad_query:<vaapiencodeh264-0:sink> context pad peer query failed
INFO GST_CONTEXT gstvaapivideocontext.c:180:_gst_context_query:<vaapiencodeh264-0> posting `need-context' message
INFO vaapi gstvaapidisplay.c:119:libgstvaapi_init_once: gstreamer-vaapi version
WARN videoencoder gstvideoencoder.c:1534:gst_video_encoder_change_state:<vaapiencodeh264-0> error: Failed to open encoder
INFO GST_ERROR_SYSTEM gstelement.c:1879:gst_element_message_full:<vaapiencodeh264-0> posting message: Could not initialize supporting library.
INFO GST_ERROR_SYSTEM gstelement.c:1902:gst_element_message_full:<vaapiencodeh264-0> posted error message: Could not initialize supporting library.
INFO GST_STATES gstelement.c:2657:gst_element_change_state:<vaapiencodeh264-0> have FAILURE change_state return
INFO GST_STATES gstelement.c:2247:gst_element_abort_state:<vaapiencodeh264-0> aborting state from NULL to READY
INFO GST_STATES gstbin.c:2780:gst_bin_change_state_func:<pipeline0> child 'vaapiencodeh264-0' failed to go to state 2(READY)
</code></pre>
<p>My hardware should support this and driver seems to be installed properly:</p>
<pre><code>shell:~$ vainfo
libva info: VA-API version 0.39.0
libva info: va_getDriverName() returns 0
libva info: Trying to open /usr/lib/x86_64-linux-gnu/dri/i965_drv_video.so
libva info: Found init function __vaDriverInit_0_39
libva info: va_openDriver() returns 0
vainfo: VA-API version: 0.39 (libva 1.7.0)
vainfo: Driver version: Intel i965 driver for Intel(R) Skylake - 1.7.0
vainfo: Supported profile and entrypoints
VAProfileMPEG2Simple : VAEntrypointVLD
VAProfileMPEG2Simple : VAEntrypointEncSlice
VAProfileMPEG2Main : VAEntrypointVLD
VAProfileMPEG2Main : VAEntrypointEncSlice
VAProfileH264ConstrainedBaseline: VAEntrypointVLD
VAProfileH264ConstrainedBaseline: VAEntrypointEncSlice
VAProfileH264Main : VAEntrypointVLD
VAProfileH264Main : VAEntrypointEncSlice
VAProfileH264High : VAEntrypointVLD
VAProfileH264High : VAEntrypointEncSlice
VAProfileH264MultiviewHigh : VAEntrypointVLD
VAProfileH264MultiviewHigh : VAEntrypointEncSlice
VAProfileH264StereoHigh : VAEntrypointVLD
VAProfileH264StereoHigh : VAEntrypointEncSlice
VAProfileVC1Simple : VAEntrypointVLD
VAProfileVC1Main : VAEntrypointVLD
VAProfileVC1Advanced : VAEntrypointVLD
VAProfileNone : VAEntrypointVideoProc
VAProfileJPEGBaseline : VAEntrypointVLD
VAProfileJPEGBaseline : VAEntrypointEncPicture
VAProfileVP8Version0_3 : VAEntrypointVLD
VAProfileVP8Version0_3 : VAEntrypointEncSlice
VAProfileHEVCMain : VAEntrypointVLD
VAProfileHEVCMain : VAEntrypointEncSlice
</code></pre>
<p>vaapi plugin seems to be properly installed as well:</p>
<pre><code>gst-inspect-1.0 vaapih264enc
Factory Details:
Rank primary (256)
Long-name VA-API H.264 encoder
Klass Codec/Encoder/Video
Description A VA-API based H.264 video encoder
Author Wind Yuan <feng.yuan@intel.com>
Plugin Details:
Name vaapi
Description VA-API based elements
Filename /usr/lib/x86_64-linux-gnu/gstreamer-1.0/libgstvaapi.so
Version 1.8.3
License LGPL
Source module gstreamer-vaapi
Source release date 2016-06-09
Binary package gstreamer-vaapi
Origin URL http://bugzilla.gnome.org/enter_bug.cgi?product=GStreamer
...
</code></pre>
<p>Thank you for any suggestions.</p>
| 3 | 2,405 |
Find how many times "Index" appers in array
|
<p>I'm trying to find out if "Index" exist in my array, and second then count how many time it does appear.</p>
<p>Nothing of what I'm trying is working, this is the best attempt i've made, but cant turn my head around this.</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 arr = {"__metadata":{"id":"a5e55ca2-c574-434e-8ec3-1b9cd4595bcb","uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)","etag":"\"2\"","type":"SP.Data.SalesListItem"},"FirstUniqueAncestorSecurableObject":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/FirstUniqueAncestorSecurableObject"}},"RoleAssignments":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/RoleAssignments"}},"Activities":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/Activities"}},"AttachmentFiles":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/AttachmentFiles"}},"ContentType":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/ContentType"}},"GetDlpPolicyTip":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/GetDlpPolicyTip"}},"FieldValuesAsHtml":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/FieldValuesAsHtml"}},"FieldValuesAsText":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/FieldValuesAsText"}},"FieldValuesForEdit":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/FieldValuesForEdit"}},"File":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/File"}},"Folder":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/Folder"}},"ParentList":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/ParentList"}},"Properties":{"__deferred":{"uri":"https://lavanet.sharepoint.com/sites/devcla/_api/Web/Lists(guid'cc4de542-1c06-4f53-b787-b8a2d42fe21e')/Items(1)/Properties"}},"FileSystemObjectType":0,"Id":1,"ServerRedirectedEmbedUri":null,"ServerRedirectedEmbedUrl":"","ContentTypeId":"0x010048CF0CAB992F7B409B79C034586FFB7E","Title":"Test data 1","Date":"2017-01-01T08:00:00Z","Index":20,"Index2":15,"ID":1,"Modified":"2017-04-18T12:27:19Z","Created":"2017-02-03T10:02:10Z","AuthorId":17,"EditorId":17,"OData__UIVersionString":"1.0","Attachments":false,"GUID":"d87fa9d2-c81e-4dfd-b568-c8a300fc12d8"}
function containsObject(obj, list) {
var x;
for (x in list) {
if (list.hasOwnProperty(x) && list[x] === obj) {
return true;
}
}
return false;
}
console.log(containsObject("index", arr));</code></pre>
</div>
</div>
</p>
<p>Would love if someone could help a bit</p>
| 3 | 1,557 |
Heroku database error on production: PG::UndefinedTable Error
|
<p>Every time I run the app on Heroku, this is what comes out of the logs:</p>
<pre><code>2018-04-15T22:51:12.806576+00:00 app[web.1]: I, [2018-04-15T22:51:12.806420 #4] INFO -- : [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] Started GET "/patients" for 112.205.217.139 at 2018-04-15 22:51:12 +0000
2018-04-15T22:51:12.808307+00:00 app[web.1]: I, [2018-04-15T22:51:12.808235 #4] INFO -- : [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] Processing by PatientsController#index as HTML
2018-04-15T22:51:12.811835+00:00 app[web.1]: I, [2018-04-15T22:51:12.811756 #4] INFO -- : [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] Rendering patients/index.html.erb within layouts/application
2018-04-15T22:51:15.563600+00:00 heroku[router]: at=info method=GET path="/patients" host=jdent-patrec.herokuapp.com request_id=cd1ed367-c720-4568-ac03-a3b1bec4fc1b fwd="112.205.217.139" dyno=web.1 connect=0ms service=2757ms status=500 bytes=1827 protocol=https
2018-04-15T22:51:15.557887+00:00 app[web.1]: D, [2018-04-15T22:51:15.557726 #4] DEBUG -- : [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] [1m[36mPatient Load (2.7ms)[0m [1m[34mSELECT "patients".* FROM "patients"[0m
2018-04-15T22:51:15.558988+00:00 app[web.1]: I, [2018-04-15T22:51:15.558899 #4] INFO -- : [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] Rendered patients/index.html.erb within layouts/application (2747.0ms)
2018-04-15T22:51:15.559386+00:00 app[web.1]: I, [2018-04-15T22:51:15.559271 #4] INFO -- : [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] Completed 500 Internal Server Error in 2751ms (ActiveRecord: 2589.2ms)
2018-04-15T22:51:15.560650+00:00 app[web.1]: F, [2018-04-15T22:51:15.560581 #4] FATAL -- : [cd1ed367-c720-4568-ac03-a3b1bec4fc1b]
2018-04-15T22:51:15.560736+00:00 app[web.1]: F, [2018-04-15T22:51:15.560661 #4] FATAL -- : [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] ActionView::Template::Error (PG::UndefinedTable: ERROR: relation "patients" does not exist
2018-04-15T22:51:15.560739+00:00 app[web.1]: LINE 1: SELECT "patients".* FROM "patients"
2018-04-15T22:51:15.560741+00:00 app[web.1]: ^
2018-04-15T22:51:15.560742+00:00 app[web.1]: : SELECT "patients".* FROM "patients"):
2018-04-15T22:51:15.561063+00:00 app[web.1]: F, [2018-04-15T22:51:15.560972 #4] FATAL -- : [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] 22: </thead>
2018-04-15T22:51:15.561066+00:00 app[web.1]: [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] 23:
2018-04-15T22:51:15.561067+00:00 app[web.1]: [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] 24: <tbody>
2018-04-15T22:51:15.561069+00:00 app[web.1]: [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] 25: <% @patients.each do |patient| %>
2018-04-15T22:51:15.561071+00:00 app[web.1]: [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] 26: <tr>
2018-04-15T22:51:15.561072+00:00 app[web.1]: [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] 27: <td><%= patient.id %></td>
2018-04-15T22:51:15.561074+00:00 app[web.1]: [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] 28: <td><%= patient.first_name %></td>
2018-04-15T22:51:15.561133+00:00 app[web.1]: F, [2018-04-15T22:51:15.561061 #4] FATAL -- : [cd1ed367-c720-4568-ac03-a3b1bec4fc1b]
2018-04-15T22:51:15.561200+00:00 app[web.1]: F, [2018-04-15T22:51:15.561139 #4] FATAL -- : [cd1ed367-c720-4568-ac03-a3b1bec4fc1b] app/views/patients/index.html.erb:25:in `_app_views_patients_index_html_erb___2618543925626266733_38249580'
</code></pre>
<p>Error pic:</p>
<p><a href="https://i.stack.imgur.com/Kn0lS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kn0lS.png" alt="enter image description here"></a></p>
<p>I've been trying to look for the problem for days but to no avail.</p>
| 3 | 1,925 |
Python Crash Course -Alien Invasion -Game Ending Error
|
<p>I am working on the Alien Invasion project at the end of Python Crash Course 2nd Edition and I am having a problem with my game ending after the user runs out of lives. The game is supposed to end after all 3 lives are lost but when that happens for mine the aliens continue to move off the bottom of the screen. There are no error messages and from my many checks through the code I have entered it word for word from the book. I have worked up to the section where the scoreboard is added but now I am resetting the scoreboard which requires the game to end properly. Below is a copy of all the necessary code files that would apply to this issue. Each separate file is indicated by #filename.py and the code for said file follows. If there is anything else needed to check through this please let me know.</p>
<pre><code># Project Qapla'
# Matthew Moore
# alien_invasion.py
import sys
from time import sleep
import pygame
from settings import Settings
from game_stats import GameStats
from scoreboard import Scoreboard
from button import Button
from ship import Ship
from bullet import Bullet
from alien import Alien
class AlienInvasion:
"""Overall class to manage assets and behaviour."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.settings = Settings()
#Partial screen play control
self.screen = pygame.display.set_mode(
(self.settings.screen_width,self.settings.screen_height))
#Full screen play control
#self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
#self.settings.screen_width = self.screen.get_rect().width
#self.settings.screen_height = self.screen.get_rect().height
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.sb = Scoreboard(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._create_fleet()
#Make the play button
self.play_button = Button(self, "Play")
def run_game(self):
"""Start the main loop for the game."""
while True:
self._check_events()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
#Make the most recently drawn screen visible.
pygame.display.flip()
def _check_events(self):
"""Respond to keypresses abd mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
self._check_play_button(mouse_pos)
def _check_keydown_events(self,event):
"""Respond to key presses."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self,event):
"""Respond to key releases."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _check_play_button(self, mouse_pos):
"""Starts new game when player clicks play button"""
button_clicked = self.play_button.rect.collidepoint(mouse_pos)
if button_clicked and not self.stats.game_active:
#Reset the game statistics
self.settings.initialize_dynamic_settings()
self.stats.game_active = True
#Get rid of any remaining aliens and bullets.
self.aliens.empty()
self.bullets.empty()
#create a new fleet and center the ship
self._create_fleet()
self.ship.center_ship()
#Hide Mouse cursor
pygame.mouse.set_visible(False)
def _fire_bullet(self):
"""Create a new bullet and add it to the bullets group."""
if len(self.bullets) < self.settings.bullets_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_bullets(self):
"""Update postiion of bullets and get rid of old bullets."""
#Update bullet positions
self.bullets.update()
#Get rid of bullets that have disappeared
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
#print(len(self.bullets))
self._check_bullet_alien_collision()
def _check_bullet_alien_collision(self):
"""Responds to bullet-alien collisions"""
#Check for any bullets that have hit aliens
#If so, get rid of alien and bullet
collisions = pygame.sprite.groupcollide(
self.bullets, self.aliens, True, True)
if collisions:
self.stats.score += self.settings.alien_points
self.sb.prep_score()
if not self.aliens:
#Destroy existing bullets and create a new fleet
self.bullets.empty()
self._create_fleet()
self.settings.increase_speed()
def _update_aliens(self):
"""Update the positions of all alliens in the fleet/Check if
fleet is on an edge"""
self._check_fleet_edges()
self.aliens.update()
#look for alien-ship collisions
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_alien_bottom()
def _ship_hit(self):
"""Responds to a ship being hit by an alien"""
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
self.aliens.empty()
self.bullets.empty()
self._create_fleet()
self.ship.center_ship()
sleep(0.5)
else:
self.stats.game_active_ = False
pygame.mouse.set_visible(True)
def _create_fleet(self):
"""create the fleet of aliens"""
#create an alien and find the number of aliens in a row.
#Spacing between each alien is equal to one alien width.
alien = Alien(self)
alien_width, alien_height = alien.rect.size
avaliable_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = avaliable_space_x // (2*alien_width)
#determine th enumber of rows of aliens that fit on the screen
ship_height = self.ship.rect.height
avaliable_space_y = (self.settings.screen_height-
(3*alien_height) - ship_height)
number_rows = avaliable_space_y // (2 * alien_height)
#Create the full fleet of aliens
for row_number in range(number_rows):
for alien_number in range(number_aliens_x):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
#create an alien and [place it in the row
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien.x = alien_width + 2*alien_width * alien_number
alien.rect.x = alien.x
alien.rect.y = alien_height + 2 * alien.rect.height * row_number
self.aliens.add(alien)
def _check_fleet_edges(self):
"""Respond approprietly if any aliens have touched an edge"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _check_alien_bottom(self):
"""Checks if aliens have reached the bottom of the screen"""
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
#treats it the same as ship getting hit
def _change_fleet_direction(self):
"""Drop the fleet and change direction"""
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_direction *= -1
def _update_screen(self):
"""Update images on the screen, and flip to the new screen."""
# Redraw the screen during each pass
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
#Draw the score information
self.sb.show_score()
#draw the button if game is inactive
if not self.stats.game_active:
self.play_button.draw_button()
pygame.display.flip()
if __name__ == '__main__':
# Make a game instance, and run the game.
ai = AlienInvasion()
ai.run_game()
#alien.py
import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
"""A class to represent a single alien in the fleet"""
def __init__(self, ai_game):
"""Initialize the alien and its starting position"""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
#Load the alien image and set its rect attribute
self.image = pygame.image.load('images/alien.bmp')
self.rect = self.image.get_rect()
#Start each new alien near the top left of the screen
self.rect.x = self.rect.width
self.rect.y = self.rect.height
#store the aliens exact horizontal position
self.x = float(self.rect.x)
def update(self):
"""Move alien to the right or left"""
self.x += (self.settings.alien_speed * self.settings.fleet_direction)
self.rect.x = self.x
def check_edges(self):
"""Returns true if alien is at edge of the screen"""
screen_rect = self.screen.get_rect()
if self.rect.right >= screen_rect.right or self.rect.left <= 0:
return True
# settings.py
class Settings:
"""A class to store all settings for Alien Invasion."""
def __init__(self):
"""Initialize the game's static settings."""
# Screen settings
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
#Ship settings
self.ship_speed = 3
self.ship_limit = 3
#Bullet settings
self.bullet_speed = 2.0
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = (60, 60, 60)
self.bullets_allowed = 3
#Alien settings
self.alien_speed = 1.0
self.fleet_drop_speed = 10
#fleet_direction of 1 represents right; -1 represents left
self.fleet_direction = 1
#How quickly the game speeds up
self.speedup_scale = 1.1
self.initialize_dynamic_settings()
def initialize_dynamic_settings(self):
"""Initialize settings that change throughout the game"""
self.ship_speed = 1.5
self.bullet_speed = 3.0
self.alien_speed = 1.0
self.fleet_direction = 1
#Scoring
self.alien_points = 50
def increase_speed(self):
"""Increases speed settings"""
self.ship_speed *= self.speedup_scale
self.bullet_speed *= self.speedup_scale
self.alien_speed *= self.speedup_scale
#game_stats.py
class GameStats:
"""Track statistics of alien invasion"""
def __init__(self, ai_game):
"""Initialize stats"""
self.settings = ai_game.settings
self.reset_stats()
self.game_active = False
def reset_stats(self):
"""Initialize stats that can change during the game"""
self.ships_left = self.settings.ship_limit
self.score = 0
#ship.py
import pygame
class Ship:
"""A class to manage the ship."""
def __init__(self, ai_game):
"""Initiatilize the ship and set its starting position."""
self.screen = ai_game.screen
self.settings = ai_game.settings
self.screen_rect = ai_game.screen.get_rect()
# Load the ship image and get its rect.
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
#Start each new ship at the bottom center of the screen.
self.rect.midbottom = self.screen_rect.midbottom
#Store a decimal value for the ships horizontal position.
self.x = float(self.rect.x)
#Movement flag
self.moving_right = False
self.moving_left = False
def update(self):
"""Update the ship's position based on the movement flags."""
#Update the ships x value, not th erect.
if self.moving_right and self.rect.right < self.screen_rect.right:
self.x += self.settings.ship_speed
if self.moving_left and self.rect.left > 0:
self.x -= self.settings.ship_speed
#Update rect object from self.x.
self.rect.x = self.x
def blitme(self):
""""Draw the ship at its current location."""
self.screen.blit(self.image, self.rect)
def center_ship(self):
self.rect.midbottom = self.screen_rect.midbottom
self.x = float(self.rect.x)
</code></pre>
| 3 | 7,883 |
Finding all object indices satisfying testing function, like array.findIndex() but more than first index
|
<p>I have an array of objects:</p>
<pre><code>var data = [{"district":"201","date":"Wed Apr 01 2020","paper":671.24,"mgp":36.5},
{"district":"202","date":"Wed Apr 01 2020","paper":421.89,"mgp":44.2},
{"district":"203","date":"Wed Apr 01 2020","paper":607.85,"mgp":67.36},
{"district":"201","date":"Sun Mar 01 2020","paper":571.24,"mgp":38.8},
{"district":"202","date":"Sun Mar 01 2020","paper":421.89,"mgp":36.6},
{"district":"203","date":"Sun Mar 01 2020","paper":607.85,"mgp":69.36},
{"district":"201","date":"Sat Feb 01 2020","paper":571.24,"mgp":38.8},
{"district":"202","date":"Sat Feb 01 2020","paper":421.89,"mgp":22.2},
{"district":"203","date":"Sat Feb 01 2020","paper":607.85,"mgp":59.66},
{"district":"201","date":"Wed Jan 01 2020","paper":571.24,"mgp":38.8},
{"district":"202","date":"Wed Jan 01 2020","paper":421.89,"mgp":22.2},
{"district":"203","date":"Wed Jan 01 2020","paper":607.85,"mgp":89.26}]
</code></pre>
<p>For each <code>district</code> I would like to take the values of <code>paper</code> and <code>mgp</code> for February, March, and April and divide each month's values by their January values to measure % change. </p>
<p>Using Array.findIndex() and reduce() (like <a href="https://stackoverflow.com/questions/30667121/javascript-sum-multidimensional-array">here</a>) I can match the districts and return the correct value, but that only returns the first index of the match, and there are repeat indices because there are subsequent months. I've tried wrapping a loop of months around the findIndex() to no avail: <code>console.log(result)</code> returns nothing</p>
<pre><code>var result = data.reduce((a, b) => {
var months = [...new Set(a.map(m => a.date))];
for (var month of months){
var idx = a.findIndex(e => e.district == b.district && e.date == month)
if (~idx && b.date === "Wed Jan 01 2020") {
a[idx].paper = a[idx].paper/b.paper;
a[idx].mgp = a[idx].mgp/b.mgp}
else {
a.push(JSON.parse(JSON.stringify(b)));
}
return a
}, []);
</code></pre>
<p>Result should look like this:</p>
<pre><code>[{"district":"201","date":"Wed Apr 01 2020","paper":1.17,"mgp":0.94},
{"district":"202","date":"Wed Apr 01 2020","paper":1,"mgp":1.99},
{"district":"203","date":"Wed Apr 01 2020","paper":1,"mgp":0.75},
{"district":"201","date":"Sun Mar 01 2020","paper":1,"mgp":1},
{"district":"202","date":"Sun Mar 01 2020","paper":1,"mgp":1.64},
{"district":"203","date":"Sun Mar 01 2020","paper":1,"mgp":0.77},
{"district":"201","date":"Sat Feb 01 2020","paper":1.17,"mgp":1},
{"district":"202","date":"Sat Feb 01 2020","paper":1,"mgp":1},
{"district":"203","date":"Sat Feb 01 2020","paper":1,"mgp":0.67]
</code></pre>
| 3 | 1,132 |
Can anyone help to open this word file please
|
<p>I am getting some problem to open a word file which showing corrupted, I recovered file but it also giving me unreadable format. Anyone please help me on this issue.</p>
<p>It showing this format
ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ</p>
| 3 | 1,150 |
Woocommerce product subtitle is misplaced
|
<p>Hey everyone I hope you can help me with this.
I created 2 subtitles with ACF for my products (subtitle and subtitle_2)
I want them to appear underneath my Product title (duh!!) on both my product page, and my homepage/shop (in the product "little box").</p>
<p>So far I managed to have them appear on the product page, by editing my single-product.php file but they're not in the right spot and I have no idea how to move them to where I want. I think they're considered as subtitles of the Page title rather than subtitles if the Product title.
(and as for the homepage, they don't appear at all but let's sort out 1 problem at a time)</p>
<p>Here is what I get and the actual code :
<a href="https://i.stack.imgur.com/MwKbG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MwKbG.png" alt="subtitles misplaced"></a></p>
<pre><code><?php
/**
* The Template for displaying all single products.
*
* Override this template by copying it to yourtheme/woocommerce/single-product.php
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
get_header( 'shop' ); ?>
<?php
/**
* woocommerce_before_main_content hook
*
* @hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content)
* @hooked woocommerce_breadcrumb - 20
*/
do_action( 'woocommerce_before_main_content' );
?>
<?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>
<div id="page-title">
<div class="width-container">
<h3><?php woocommerce_page_title(); ?></h3>
<?php if(function_exists('bcn_display')) {
echo '<div id="bread-crumb">';
bcn_display();
echo '</div>';
}?>
<div class="clearfix"></div>
</div>
</div><!-- close #page-title -->
<?php endif; ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php the_field('subtitle'); ?>
<?php the_field('subtitle_2'); ?>
<?php wc_get_template_part( 'content', 'single-product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php
/**
* woocommerce_after_main_content hook
*
* @hooked woocommerce_output_content_wrapper_end - 10 (outputs closing divs for the content)
*/
do_action( 'woocommerce_after_main_content' );
?>
</div>
<?php
/**
* woocommerce_sidebar hook
*
* @hooked woocommerce_get_sidebar - 10
*/
do_action( 'woocommerce_sidebar' );
?>
<div class="clearfix"></div>
</div>
</code></pre>
<p>and here is a link to the corresponding product page : <a href="http://tinyurl.com/pzum42k" rel="nofollow noreferrer">http://tinyurl.com/pzum42k</a></p>
<p>Any help would be much appreciated !!
Thanks in advance,
G</p>
| 3 | 1,266 |
django DB2 inspectdb failure :'NoneType' object is not subscriptable
|
<p>my dev environment is in python 3.6 and virtualenv(virtualenv 15.1.0) and with dependencies below:
django 2.2
ibm-db 3.0.1
ibm-db-django 1.2.0.0</p>
<p>as i used "(env_django2) λ python manage.py check", it return "System check identified no issues (0 silenced)." that is no problom.</p>
<p>however, when i used "python manage.py inspectdb --database db2 DEMO.DEMOUSER", it return like these below:</p>
<pre><code>(env_django2) λ python manage.py inspectdb --database db2 DEMO.DEMOUSER
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
# Unable to inspect table 'DEMO.DEMOUSER'
# The error was: 'NoneType' object is not subscriptable
</code></pre>
<p>this is my db2 setting:</p>
<pre><code> DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'db2':{
'ENGINE': 'ibm_db_django',
'NAME': 'test',
'USER': 'db2inst1',
'PASSWORD': 'XXXXXX',
'HOST': 'XX.XXX.XXX.XXX',
'PORT': 'XXXXX',
'PCONNECT':True,
}
}
</code></pre>
<p>and i had test it by coding like these below, and that is no problom.</p>
<pre><code>with connections['db2'].cursor() as cursor:
cursor.execute("""
select * from DEMO.DEMOUSER
""")
columns = [col[0] for col in cursor.description]
listResult = [dict(zip(columns, row)) for row in cursor.fetchall()]
print(listResult)
</code></pre>
<p>so my question is how can i make the inspectdb work?</p>
<p>i have check inspectdb.py, and i found that </p>
<pre><code>table_description = connection.introspection.get_table_description(cursor, table_name)
except Exception as e:
yield "# Unable to inspect table '%s'" % table_name
</code></pre>
<p>func get_table_description will invole the code below:</p>
<pre><code>sql = "SELECT TYPE FROM SYSIBM.SYSTABLES WHERE CREATOR='%(schema)s' AND NAME='%(table)s'" % {'schema': schema.upper(), 'table': table_name.upper()}
</code></pre>
<p>it seem i didn't set the table and schema name right.</p>
<p>ok, i have to go to sleep, very tired.</p>
<p>2020.3.13 update........</p>
<p>so when i readed the code in ibm_db_django\introspection.py, i found that below:</p>
<pre><code>schema = cursor.connection.get_current_schema()
</code></pre>
<p>that mean, ibm_db_django will get the schema by default, which is your user name setted in django's setting file. so it will always set the table name like 'db2inst1.DEMO.DEMOUSER' in my case. u can't change the schema by yourself.</p>
<p>as i know, setting the schema immutable is unreasonable,because the schema and user was different things in db2 unlike oracle. everyone can use the granted schema.</p>
<p>hence, i had to change the code like these,so that i can set my schema correctly:</p>
<pre><code># change the code below
#schema = cursor.connection.get_current_schema()
print( '-----------change by HK 20200313-----------------')
if len(table_name.split('.')) == 2:
cursor.connection.set_current_schema(table_name.split('.')[0].upper())
table_name = table_name.split('.')[1]
schema = cursor.connection.get_current_schema()
print('----------------- HK TEST schema:%s'%schema)
# change the code below
#cursor.execute( "SELECT * FROM %s FETCH FIRST 1 ROWS ONLY" % qn( table_name ) )
sql = "SELECT * FROM %s FETCH FIRST 1 ROWS ONLY" % ( schema+'.'+table_name )
print('------------ HK TEST LOG:%s'%sql)
cursor.execute( sql )
</code></pre>
<p>so the problem had been solved,however,another emerged !!
when i typed the command "python manage.py inspectdb --database db2 DEMO.DEMOUSER", it show below:</p>
<pre><code>class DemoDemouser(models.Model):
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "D:\MyProject\python\django-sample\env_django2\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "D:\MyProject\python\django-sample\env_django2\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\MyProject\python\django-sample\env_django2\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "D:\MyProject\python\django-sample\env_django2\lib\site-packages\django\core\management\base.py", line 364, in execute
output = self.handle(*args, **options)
File "D:\MyProject\python\django-sample\env_django2\lib\site-packages\django\core\management\commands\inspectdb.py", line 34, in handle
for line in self.handle_inspection(options):
File "D:\MyProject\python\django-sample\env_django2\lib\site-packages\django\core\management\commands\inspectdb.py", line 102, in handle_inspection
column_name = row.name
AttributeError: 'list' object has no attribute 'name'
</code></pre>
<p>checking inspectdb.py,i find out the answer. the description of specified table ,returned from the func in introspection.py implemented by ibm_db_django, is different from inspectdb.py in django 2.2.</p>
<p>so check it with django release history and ibm_db_ango.
ibm_db_ango 1.2 released in 2018.4.3, django 2.2 released in 2019.3.</p>
<p>it seem django 2.2 dont support the ibm_db_ango 1.2(the latest version)</p>
<p>therefore i had to install django 2.0 instead. </p>
<p>finally it work!!!.</p>
| 3 | 2,186 |
How to maintain script tag position on webpage?
|
<p>I am using a script tag to add a widget to my Next.js app. I have create a section component for this widget but when I run the app it renders below my footer but it is supposed to render above as a section component. Can someone help me out with this, please?</p>
<p>Below you will see the screenshot of the issue, my <code>index.js</code>, the script component and the component where I hope it would be rendered.
Another user asked a <a href="https://stackoverflow.com/questions/70118835/nextjs-script-tag-how-to-maintain-position-on-webpage-see-example">question related to the same issue</a>. Is there anyone that knows how to fix it?</p>
<p><a href="https://i.stack.imgur.com/eq2ts.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eq2ts.jpg" alt="enter image description here" /></a></p>
<pre><code>import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.scss'
import Header from './src/components/Header'
import Services from './src/components/Services'
import Portfolio from './src/components/Portfolio'
import ContactCard from './src/components/ContactCard'
import Booking from './src/components/Booking'
export default function Home() {
return (
<div className="container-fluid">
<Head>
<title>Dr Cut TheBarber Show</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="main">
<Header />
<Services />
<Portfolio />
<ContactCard />
<Booking />
</main>
<footer className="footer text-center">
<a
className="text-decoration-none text-dark"
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
<span className={styles.logo}>
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
</span>
</a>
</footer>
</div>
)
}
</code></pre>
<p><code>Booksy.js</code></p>
<pre><code>import script from 'next/script';
//import Script from 'next/script'
import { useEffect } from 'react';
const Booksy = () =>{
useEffect(() => {
const script = document.createElement('script');
script.src="https://booksy.com/widget/code.js?id=17618&country=es&lang=es";
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, [])
return script
}
export default Booksy;
</code></pre>
<p><code>Booking.js</code></p>
<pre><code>import Booksy from "./Booksy";
function Booking () {
return (
<div className="page-section">
<Booksy />
</div>
)
}
export default Booking;
</code></pre>
| 3 | 1,423 |
How to make images fill my carousel slides
|
<p>I am trying to fit my images into the slides.</p>
<p>Below is my example code and screenshots:</p>
<pre><code><div className="relative h-24 w-20 sm:h-44 sm:w-100 md:h-44 md:w-60 flex-shrink-0">
<Carousel showThumbs={false}>
{imgSrc?.map((url, index) => (
<div className="h-24 w-20 sm:h-44 sm:w-100 md:h-44 md:w-60 flex-shrink-0" >
<img class="object-fill rounded-md" src={`${url}`} />
</div>
))}
</Carousel>
</div>
</code></pre>
<p><a href="https://i.stack.imgur.com/CbOSb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CbOSb.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/Yhscz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yhscz.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/s6Wjo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s6Wjo.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/g38KW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g38KW.png" alt="enter image description here" /></a></p>
<p>What I have done is:</p>
<ol>
<li><p>Set the first block into fix size. This is the size I want every image will be constrained into.</p>
</li>
<li><p>Inside the Carousel: Since the <code><div></code> and <code><img></code> tags are the protocol in this library. So I'm just following it.</p>
</li>
<li><p>To make sure everything will be constrained into fixed length. I set same CSS rule to every tag.</p>
</li>
</ol>
<p>The result is that not all images display the same size. Some have some empty space which I don't want to see.</p>
<p>May I know how to fix it? Isn't this the way of this CSS is intended to be used?</p>
<hr />
<p>[updated with Ed Lucas's code]</p>
<p>In MD setting, all the images in thumbnail are perfectly fitted into the box.</p>
<p>However, when screen shrinks, some images suddenly <strong>shrink smaller than</strong> the thumbnail while some could still align with the box size. Do you know any ideas?</p>
<pre><code><div className="relative h-30 w-40 sm:h-44 sm:w-100 md:h-44 md:w-60 flex-shrink-0">
<Carousel showThumbs={false}>
{imgSrc?.map((url, index) => (
<div className="h-30 w-40 sm:h-44 sm:w-100 md:h-44 md:w-60 flex-shrink-0" >
<img class="object-cover h-full w-full rounded-md" src={`${url}`} />
</div>
))}
</Carousel>
</div>
</code></pre>
<p>Here is example in small screen size</p>
<p>normal:</p>
<p><a href="https://i.stack.imgur.com/qFHIB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qFHIB.png" alt="enter image description here" /></a></p>
<p>abnormal pictures</p>
<p><a href="https://i.stack.imgur.com/EM3sQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EM3sQ.png" alt="enter image description here" /></a></p>
| 3 | 1,236 |
Plotly animation with factors
|
<p>Converting a num vector to factors yields unexpected results in a plot_ly animation.</p>
<blockquote>
<p>If frame is a numeric variable (or a character string), frames are always ordered in increasing (alphabetical) order; but for factors, the ordering reflects the ordering of the levels <a href="https://plotly-book.cpsievert.me/key-frame-animations.html" rel="nofollow noreferrer">plotly book</a></p>
</blockquote>
<p>With the data set: </p>
<pre><code>>str(genTotal)
data.frame': 1620 obs. of 4 variables:
$ generation: int 0 0 0 0 0 0 0 0 0 0 ...
$ fitness : num 2.38 2.38 2.38 2.38 21.82 ...
$ x : num 0.946 0.946 0.946 0.946 -2.26 ...
$ x2 : num -0.0686 -0.0686 -0.0686 -0.0686 2.0935 ...
</code></pre>
<p>As expected the keyframes are sorted alphabetically:
<a href="https://i.stack.imgur.com/5w3mF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5w3mF.png" alt="enter image description here"></a></p>
<hr>
<p>When converting <em>generation</em> to a factor as suggested, suddenly all frames are drawn on top of each other:</p>
<pre><code>genTotal$generation <- factor(genTotal$generation, ordered = TRUE)
'data.frame': 1620 obs. of 4 variables:
$ generation: Factor w/ 81 levels "0","50","100",..: 1 1 1 1 1 1 1 1 1 1 ...
$ fitness : num 2.38 2.38 2.38 2.38 21.82 ...
$ x : num 0.946 0.946 0.946 0.946 -2.26 ...
$ x2 : num -0.0686 -0.0686 -0.0686 -0.0686 2.0935 ...
</code></pre>
<p><a href="https://i.stack.imgur.com/iT0vJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iT0vJ.png" alt="enter image description here"></a></p>
<p>With the code </p>
<pre><code>plot_ly(data = df, x = ~ x, y = ~y, z = ~rastrigin, type = "contour") %>%
colorbar(title = "Value") %>%
add_trace(data = genTotal,x=~x,y=~x2,type = "scatter", mode = "markers",
frame = genTotal$generation,
inherit = FALSE,
marker = list(size = 10,
color = 'rgba(255, 182, 193, .7)',
line = list(color = 'rgba(152, 0, 0, 1)',width = 2))
)
</code></pre>
<p><strong>Questions:</strong>
Why are suddenly all frames drawn on top of each other? </p>
<p>How can I correctly (ordered) animate a plot_ly plot with a numeric frame vector?</p>
<p>Updated: as requested the dput of <a href="https://pastebin.com/ytB1xkMG" rel="nofollow noreferrer">genTotal</a> and <a href="https://pastebin.com/uejWJ6p5" rel="nofollow noreferrer">df</a></p>
| 3 | 1,032 |
Android expandable list: how to add different layout for layout groups
|
<p>My problem is while clicking on the groups at first position it shows the child properly but when I click next group item the application crashes.</p>
<pre><code>@Override
public View getChildView(final int i, int i2, boolean b, View v, ViewGroup viewGroup) {
if (v==null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int itemType = getChildType(i, i2);
int grup_pos = (int) getGroupId(i);
switch (itemType`enter code here`) {
case 0:
v = inflater.inflate(R.layout.child_contact, null);
Toast.makeText(context.getApplicationContext(), "position is" + grup_pos, Toast.LENGTH_SHORT).show();
break;
case 1:
v = inflater.inflate(R.layout.child_faq_answer, null);
Toast.makeText(context.getApplicationContext(), "position is" + grup_pos, Toast.LENGTH_SHORT).show();
break;
case 2:
v = inflater.inflate(R.layout.child_main_contact, null);
Toast.makeText(context.getApplicationContext(), "position is" + grup_pos, Toast.LENGTH_SHORT).show();
break;
case 3:
v = inflater.inflate(R.layout.child_events_items, null);
Toast.makeText(context.getApplicationContext(), "position is" + grup_pos, Toast.LENGTH_SHORT).show();
break;
case 4:
v = inflater.inflate(R.layout.child_program, null);
Toast.makeText(context.getApplicationContext(), "position is" + grup_pos, Toast.LENGTH_SHORT).show();
break;
case 5:
v = inflater.inflate(R.layout.item_faq_answer, null);
Toast.makeText(context.getApplicationContext(), "position is" + grup_pos, Toast.LENGTH_SHORT).show();
break;
case 6:
v = inflater.inflate(R.layout.child_program, null);
Toast.makeText(context.getApplicationContext(), "position is" + grup_pos, Toast.LENGTH_SHORT).show();
break;
}
}
v.invalidate();
return v;
}
</code></pre>
<p><strong>This is the error what I get</strong></p>
<pre><code>E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
at android.widget.AbsListView$RecycleBin.addScrapView(AbsListView.java:6773)
at android.widget.ListView.layoutChildren(ListView.java:1602)
at android.widget.AbsListView.onLayout(AbsListView.java:2056)
at android.view.View.layout(View.java:14118)
at android.view.ViewGroup.layout(ViewGroup.java:4467)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1670)
at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1659)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1443)
at android.view.View.layout(View.java:14118)
at android.view.ViewGroup.layout(ViewGroup.java:4467)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1021)
at android.view.View.layout(View.java:14118)
at android.view.ViewGroup.layout(ViewGroup.java:4467)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14118)
at android.view.ViewGroup.layout(ViewGroup.java:4467)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:493)
at android.view.View.layout(View.java:14118)
at android.view.ViewGroup.layout(ViewGroup.java:4467)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14118)
at android.view.ViewGroup.layout(ViewGroup.java:4467)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1670)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1528)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1441)
at android.view.View.layout(View.java:14118)
at android.view.ViewGroup.layout(ViewGroup.java:4467)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14118)
at android.view.ViewGroup.layout(ViewGroup.java:4467)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2202)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1966)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1158)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4914)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
at android.view.Choreographer.doCallbacks(Choreographer.java:579)
at android.view.Choreographer.doFrame(Choreographer.java:548)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
| 3 | 2,612 |
How to redirect to new screen for each dynamic grid view content?
|
<p>I have one grid view, and i am showing data from my database. So like say, if I have 6 titles.Then my grid view will be 6 (boxes ). Whenever I press each grid view title [ box ]. I need to redirect to separate 6 screen. How to do that?</p>
<p>So if I press my first title in my grid view. That is <code>Orders</code> I need to redirect to <code>order.html</code>, and if I press <code>Delivery</code> I need to redirect them to <code>Delivery.html</code>. How to do that?</p>
<p>Is that any way to check with id or name 0r any idea.</p>
<p>Updated :</p>
<pre><code> .controller('MydashCtrl', function($scope, $state, $window) {
$scope.Data = [{
"id" : "1",
"name" : "Orders",
"Image" : "http://img.21food.com/20110609/product/1306576307495.jpg"
},{
"id" : "2",
"name" : "Delivery",
"Image" : "https://www.wildflavors.com/NA-EN/assets/Image/bakery.png"
},{
"id" : "3",
"name" : "Collections",
"Image" : "http://royalnutrimakmur.com/img/productImg02.jpg"
},
{
"id" : "4",
"name" : "Payments",
"Image" : "http://royalnutrimakmur.com/img/productImg02.jpg"
},
{
"id" : "5",
"name" : "Purchase",
"Image" : "http://royalnutrimakmur.com/img/productImg02.jpg"
},
{
"id" : "6",
"name" : "Re-Orders",
"Image" : "http://royalnutrimakmur.com/img/productImg02.jpg"
}]
$scope.changestate= function(name) {
if(name="Orders"){
$state.go('reorder', { details : JSON.stringify(name) });
}else if(name="Delivery"){
$state.go('dashboarddetail', { details : JSON.stringify(name) });
}
}
})
</code></pre>
<p><strong>My Html code :</strong></p>
<p></p>
<pre><code> <div class="item item-body no-padding scroll" style="border-width: 0px !important;">
<div class="row no-padding" ng-repeat="mydash in Data" ng-if="$index % 2 === 0">
<div class="col col-50 custom-design2" style="background: url({{Data[$index].Image}}) no-repeat center;background-size: cover; " ng-click="changestate(Data[$index].name)" ng-if="$index < Data.length">
<div class="custom-design1"><span class="grid-title">{{Data[$index].name}}</span></div>
</div>
<div class="col col-50 custom-design2" style="background: url({{Data[$index + 1].Image}}) no-repeat center;background-size: cover; " ng-click="changestate(Data[$index + 1].name)" ng-if="$index + 1 < Data.length">
<div class="custom-design1"><span class="grid-title">{{Data[$index + 1].name}}</span></div>
</div>
</div>
</div>
</div>
</code></pre>
<p>Okay its redirecting . but now in my redirecting screen. the content name .Title is not showing ??</p>
<p><strong>Here my code of one redirect screen for my order title :</strong></p>
<p>My screen html code :</p>
<pre><code><ion-view cache-view="false" title= {{singleDetail.name}} hide-nav-bar="false" class=" ">
</code></pre>
<p>Controller code for this html :</p>
<pre><code>.controller('reorderCtrl', function($scope, $state, $window, $ionicPopup, $stateParams, $ionicLoading, $timeout, $ionicHistory){
$scope.singleDetail = JSON.parse($stateParams.details);
})
</code></pre>
<p>May be this is becasuse of my home grid view controller or not ?</p>
<pre><code>.controller('MydashCtrl', function($scope, $state, $window) {
$scope.Data = [{
"id" : "1",
"name" : "Orders",
"Image" : "http://img.21food.com/20110609/product/1306576307495.jpg"
},{
"id" : "2",
"name" : "Delivery",
"Image" : "https://www.wildflavors.com/NA-EN/assets/Image/bakery.png"
},{
"id" : "3",
"name" : "Collections",
"Image" : "http://royalnutrimakmur.com/img/productImg02.jpg"
},
{
"id" : "4",
"name" : "Payments",
"Image" : "http://royalnutrimakmur.com/img/productImg02.jpg"
},
{
"id" : "5",
"name" : "Purchase",
"Image" : "http://royalnutrimakmur.com/img/productImg02.jpg"
},
{
"id" : "6",
"name" : "Re-Orders",
"Image" : "http://royalnutrimakmur.com/img/productImg02.jpg"
}]
$scope.changestate= function(name) {
if(name=="Orders"){
$state.go('dashboarddetail', { details : JSON.stringify(name) });
}else if(name=="Re-Orders"){
$state.go('reorder', { details : JSON.stringify(name) });
}
}
})
</code></pre>
| 3 | 1,952 |
Scrapy Xpath construction producing empty brackets on dynamic site
|
<p>I am trying to create a spider via scrapy to crawl a website and extract all links for specific stores. Ultimately, the spider would then use those store links to extract pricing information. The site is designed to break down store information into States and Regions. I have been able to extract all sub links for the States/regions, but I cannot seem to extract the specific information for the stores, that information being the store links. </p>
<p>I thought it had to do with the page not being loaded long enough for those store links to display. So I used selenium and delayed the timing by 20 seconds to allow appropriate time for the webpage to load. An example link would be <a href="https://weedmaps.com/dispensaries/in/united-states/colorado" rel="nofollow">https://weedmaps.com/dispensaries/in/united-states/colorado</a> and as you can see on the left hand side there is information for specific stores. A snippet using the inspect element yields the following HTML: </p>
<pre><code><li class="ng-scope" ng-repeat="listing in listings" wm-listing-detail="" role="listing">
<div ng-class="{unpublished: !listing.published}">
<div class="listing feature-1 recreational dispensary" ng- class="featureClassesFor(listing)" ng-click="setActiveMarker(listing)">
<img class="avatar" ng-src="https://d2kxqxnk1i5o9a.cloudfront.net/uploads/avatars/dispensaries/5566/square_10569095_10152344322971376_2924814837799131094_n.jpg" src="https://d2kxqxnk1i5o9a.cloudfront.net/uploads/avatars/dispensaries/5566/square_10569095_10152344322971376_2924814837799131094_n.jpg"/>
<div>
<div class="name hovers">
<a class="ng-binding" href="/dispensaries/organic-alternatives" role="listing url" ng-bind-html="listing.name">Organic Alternatives</a>
</div>
</div>
<div class="address ng-binding">
<div class="wm_map_inactive_rating">
</code></pre>
<p>I am looking to extract the information following the @href.</p>
<p>I have the following python code in the spider section of the scrapy project:</p>
<pre><code>import scrapy
from scrapy.spider import BaseSpider
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
class scrapybotspider(scrapy.Spider):
name = "scrapybot_spider"
start_urls = ['https://weedmaps.com/dispensaries/in/united-states/colorado']
delay = 20
def __init__(self):
self.driver = webdriver.Firefox()
def parse(self, response):
self.driver.get(response.url)
while True:
StateCountyURL = response.xpath("//*[@id='wm-listings']/div/li[2]/div/div/div[1]/div/@href").extract()
print StateCountyURL
</code></pre>
<p>This produces empty brackets and I have tried a number of different xpath constructions.</p>
| 3 | 1,043 |
Making WebMQ Synchronous
|
<p>I'm trying to make WebMQ act synchronously in MULE in order to turn the message queue into a REST api for an internal project. Unfortunately, I know very little about MULE.</p>
<p>After a good bit of work, I started understanding the Request-Reply scope and tried to use the WMQ Connector with it, only to find out that WMQ only sends once the flow has ended.</p>
<p>I've tried putting the request into a different flow using VM to trigger it<br>
<img src="https://i.imgur.com/PpLnNKu.png" alt=""></p>
<p>but so far that just leads to it waiting forever on WMQ that will never happen.</p>
<p>I've also tried using VMs for back and forth:<br>
<img src="https://i.imgur.com/yv4r9FB.png" alt=""></p>
<p>But it seems to do the same thing as without, where it just ignores the input.</p>
<p>Now I know the input and output for the WMQ are working, as I previously setup a flow that used http to communicate with itself and let it know when a message went through.</p>
<p><img src="https://i.imgur.com/aFOZYAE.png" alt=""></p>
<p>What I essentially want is this, but using HTTP instead of AJAX</p>
<p><img src="https://i.imgur.com/hXPLGAR.png" alt=""></p>
<p>My latest, and perhaps closest attempt looks like thus:
<img src="https://i.imgur.com/h2dPM3q.png" alt=""></p>
<p>The XML being:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:vm="http://www.mulesoft.org/schema/mule/vm" xmlns:http="http://www.mulesoft.org/schema/mule/http" version="EE-3.6.0" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:ajax="http://www.mulesoft.org/schema/mule/ajax" xmlns:core="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:stdio="http://www.mulesoft.org/schema/mule/stdio" xmlns:test="http://www.mulesoft.org/schema/mule/test" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns:wmq="http://www.mulesoft.org/schema/mule/ee/wmq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ajax http://www.mulesoft.org/schema/mule/ajax/current/mule-ajax.xsd
http://www.mulesoft.org/schema/mule/ee/wmq http://www.mulesoft.org/schema/mule/ee/wmq/current/mule-wmq-ee.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
http://www.mulesoft.org/schema/mule/stdio http://www.mulesoft.org/schema/mule/stdio/current/mule-stdio.xsd
http://www.mulesoft.org/schema/mule/test http://www.mulesoft.org/schema/mule/test/current/mule-test.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd">
<wmq:connector channel="MAGENTO.SVRCONN" doc:name="WMQ Connector" hostName="[ip]" name="wmqConnector" port="1414" queueManager="MAGENTO" transportType="CLIENT_MQ_TCPIP" validateConnections="true" />
<vm:connector name="VM" validateConnections="true" doc:name="VM">
<vm:queue-profile maxOutstandingMessages="500">
<default-persistent-queue-store/>
</vm:queue-profile>
</vm:connector>
<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>
<flow name="Input">
<http:listener config-ref="HTTP_Listener_Configuration" path="/mq" doc:name="HTTP"/>
<set-payload value="#[message.inboundProperties.'http.query.params'.xml]" doc:name="Set Payload"/>
<logger message="Entering Request-Reply Payload: #[payload]" level="INFO" doc:name="Logger"/>
<request-reply doc:name="Request-Reply">
<vm:outbound-endpoint exchange-pattern="one-way" path="mq" connector-ref="VM" doc:name="VM_TriggerSend" />
<vm:inbound-endpoint exchange-pattern="request-response" path="mq-return" connector-ref="VM" doc:name="VM_Receive" />
</request-reply>
<logger message="Request-Reply has ended. Payload: #[payload]" level="INFO" doc:name="Logger"/>
</flow>
<flow name="Send_Message">
<vm:inbound-endpoint exchange-pattern="one-way" path="mq" connector-ref="VM" doc:name="VM_Send"/>
<logger message="(Preparing to Dispatch) Payload: #[payload]" level="INFO" doc:name="Logger"/>
<wmq:outbound-endpoint queue="PUT_QUEUE" connector-ref="wmqConnector" doc:name="WMQ"/>
<logger message="Message presumably being dispatched after this log" level="INFO" doc:name="Logger"/>
</flow>
<flow name="Receive_Message">
<wmq:inbound-endpoint queue="GET_QUEUE" connector-ref="wmqConnector" doc:name="WMQ_Receive" />
<logger message="Triggering Receive" level="INFO" doc:name="Logger"/>
<vm:outbound-endpoint exchange-pattern="request-response" path="mq-return" connector-ref="VM" doc:name="VM_TriggerReceive" />
</flow>
</mule>
</code></pre>
<p>Which almost works, but it hangs indefinitely without sending a response back to the HTTP server. Setting the vm:inbound-endpoint in the Request-Reply flow to one-way keeps it from hanging, but doesn't send the new payload that's been received, but instead the previous payload (as if it's being skipped over).</p>
<p>Any help at all would be greatly appreciated!</p>
| 3 | 2,401 |
How many iterations of the Mandelbrot set for an accurate picture at a certain zoom?
|
<p>I have implemented the mandelbrot set algorithm in Java which I am using to make an animation of zooming into the set. My problem is that the algorithm is performing very slowly since I have it set such that the maximum number of iterations is high (1000) so that clarity will be preserved when zooming in closely. However, when on a more zoomed-out picture, only around 100 iterations are required to have an accurate picture.</p>
<p><a href="https://media.giphy.com/media/C9lNldSBctIFpvmGXY/giphy-downsized-large.gif" rel="nofollow noreferrer"><img src="https://media.giphy.com/media/C9lNldSBctIFpvmGXY/giphy-downsized-large.gif" alt="The Mandelbrot set" /></a></p>
<p>My question is: is there some function <code>f(x)</code> such that for x screen width, clarity will be acceptable? (This only needs to be approximate since the definition of "clear" isn't itself very clear, but the trendline should follow the rate of increase of accuracy which follows the set itself)</p>
<p>Here is my current implementation of the algorithm:</p>
<pre class="lang-java prettyprint-override"><code> private double[] target = {-1.256640565451168862869, -0.382386428889165027247};
// Returns an integer RGB value (0xRRGGBB) representing the colour which should be drawn at a certain position on the screen
private int getMandleRGB(int x, int y, int w, int h) {
Complex c = new Complex();
c.r = lerp(lerp(-2, target[0], 1-zoom), lerp(1, target[0], 1-zoom), x/(double) w);
c.i = lerp(lerp(-1.5, target[1], 1-zoom), lerp(1.5, target[1], 1-zoom), y/(double) h);
Complex z = new Complex();
z.r = c.r;
z.i = c.i;
int i = 0;
for (i = 0; i < 1000; i++) {
z = Complex.add(Complex.multiply(z, z), c);
if (z.i*z.i+z.r*z.r > 4) {
double t = Math.log(i)/Math.log(1000d);
return (int) lerp((gradient[0] & 0xff0000) >> 16,
(gradient[1] & 0xff0000) >> 16, t)*0x10000
+ (int) lerp((gradient[0] & 0xff00) >> 8,
(gradient[1] & 0xff00) >> 8, t)*0x100
+ (int) lerp((gradient[0] & 0xff),
(gradient[1] & 0xff), t);
}
}
return 0x000000; // black
}
</code></pre>
| 3 | 1,067 |
Java: Setting TLSv1.2 in https.protocols not working
|
<p>I am using <code>Java 7</code> with tomcat and trying to make an API call to paypal which only support <code>TLSv1.2</code> . Since <code>java 7</code> doesn't use <code>TLSv1.2</code> by default, I read somewhere and add <code>-Dhttps.protocols=TLSv1.2</code> in command line parameters in <code>catalina.sh</code>.</p>
<p>But it is still giving Handshake failure exception and debug info giving following text</p>
<pre><code>%% No cached client session
*** ClientHello, TLSv1
RandomCookie: GMT: 1441341367 bytes = { 196, 47, 204, 27, 84, 46, 183, 9, 117, 144, 240, 242, 25, 235, 124, 81, 157, 216, 189, 225, 53, 58, 41, 88, 47, 68, 172, 189 }
Session ID: {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods: { 0 }
Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1}
Extension ec_point_formats, formats: [uncompressed]
Extension server_name, server_name: [host_name: api-3t.sandbox.paypal.com]
***
http-bio-8081-exec-10, WRITE: TLSv1 Handshake, length = 197
http-bio-8081-exec-10, READ: TLSv1 Alert, length = 2
http-bio-8081-exec-10, RECV TLSv1 ALERT: fatal, handshake_failure
http-bio-8081-exec-10, called closeSocket()
http-bio-8081-exec-10, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
http-bio-8081-exec-10, called close()
http-bio-8081-exec-10, called closeInternal(true)
http-bio-8081-exec-10, called close()
http-bio-8081-exec-10, called closeInternal(true)
http-bio-8081-exec-10, called close()
http-bio-8081-exec-10, called closeInternal(true)
</code></pre>
<p>Using <code>org.apache.commons.httpclient.HttpClient.executeMethod()</code> to make post call. Why the api call still not working?</p>
| 3 | 1,288 |
Calculate Balance in Date range - PouchDB
|
<p>i am working on small billing application<br>
i want to calculate the opening balance for the date range</p>
<p>i have following fields in docs of pouch db data base</p>
<p>date:2021-08-01 <br>
sale:800<br>
invest:500<br>
expense: 100<br></p>
<p>i want to calculate the opening balance by date range using pouchdb</p>
<p>opening balance will be previous date closing balance</p>
<p>calculation will be -> <strong>closing = ( opening+investment+sale ) - exp</strong></p>
<p>This table is example to calculate the balance for each day</p>
<pre><code>date opening sale invest exp closing
2020-03-01 0 100.00 10.00 0 90.00
2020-03-02 90.00 50.00 20.00 0 120.00
2020-03-02 120.0 100.00 0.00 0 220.00
2020-03-03 220.00 200.00 20.00 0 400.00
2020-03-04 400.00 110.00 10.00 10 110.00
</code></pre>
<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>// onchange function
function getday(){
// ---------------------------------------------opening---------------------------------------------
var opening_balance = 0
function daysale(n){
daybook.find({
selector: {
Date:n ,
}
}).then(function(result) {
//chenking the data is present in the selected date
if(result.docs.length>0){
result.docs.forEach((element, ) => {
saletotal = (isNaN(element.TotalAmount) ? 0: parseInt(element.TotalAmount));
Totalinvest = (isNaN(element.TotalInvestment) ? 0: parseInt(element.TotalInvestment));
Totalexp = (isNaN(element.TotalExpenses) ? 0: parseInt(element.TotalExpenses));
opening_balance+=saletotal+Totalinvest-Totalexp
document.getElementById('open-balance').value=opening_balance
});
}
// if there is no data on particular date subtracting one day from date from date and calling the
//get day function with yesterday value as parameter to check if the data is present in previos date
else{
let d = new Date(n);
d.setDate(d.getDate() - 1);
var daybeforedate = d.toISOString().split('T')[0];
//recursion function to calculate the previous date if there is no data in particular date
daysale(daybeforedate)
}
});
}
// get date value and minus one day
var TodayDate = document.getElementById('daybook-firstdate').value;
let d = new Date(TodayDate);
d.setDate(d.getDate() - 1);
var yesterdaydate = d.toISOString().split('T')[0];
// function call for current date
daysale(yesterdaydate)
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>input{
display:block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="daybookhandle">
<label>From<input type="date" name="daybook" id="daybook-firstdate" onchange="getday()" ></label>
<label>To<input type="date" name="daybook" id="daybook-firstdate" onchange="getday()" ></label>
<label>Opening Balance:</label>
<input type="text" name="balnce" id="open-balance" >
<label >Investment : </label>
<input type="text" name="ivest" id="invest-ment">
<label >Expenses : </label>
<input type="text" name="Exp" id="Expense_Total">
<label >Total Sales : </label>
<input type="text" name="sale" id="Sales_total">
<label >Closing Balance :</label>
<input type="text" name="cbalance" id="closing_balance">
</div></code></pre>
</div>
</div>
</p>
<p>any one help me with a code
if there is any more doubt please feel free to ask</p>
| 3 | 1,979 |
Product Combination of variables by loop in R with data table
|
<p>I have an initial table in R including 7 variables as shown below:</p>
<pre><code>library(data.table)
Data<-data.frame(
ID=c(1,1,1,2,2,2,3,3,3,4,4,4),
CP1 =c(1,0,0,1,0,0,1,0,0,1,0,0),
CP2 =c(0,1,1,0,0,1,0,1,0,0,0,0),
CP3 =c(0,0,0,0,0,0,0,0,0,0,0,1),
PR1 =c(1,1,0,0,0,0,0,0,0,0,0,0),
PR2=c(0,0,1,0,0,0,0,0,0,0,0,0),
PR3=c(0,0,0,0,1,0,0,0,0,0,0,1)
)
Data
> Data
ID CP1 CP2 CP3 PR1 PR2 PR3
1 1 1 0 0 1 0 0
2 1 0 1 0 1 0 0
3 1 0 1 0 0 1 0
4 2 1 0 0 0 0 0
5 2 0 0 0 0 0 1
6 2 0 1 0 0 0 0
7 3 1 0 0 0 0 0
8 3 0 1 0 0 0 0
9 3 0 0 0 0 0 0
10 4 1 0 0 0 0 0
11 4 0 0 0 0 0 0
12 4 0 0 1 0 0 1
</code></pre>
<p>I want to create all the product combination of CP1, CP2 and CP3 with the PR1, PR2 and PR3 variables, with the following names CP1_PR1, CP1_PR2, CP1_PR3, CP2_PR1, CP2_PR2, CP2_PR3, CP3_PR1, CP3_PR2 and CP3_PR3.</p>
<p><em><strong>But I want to use a condition for doing this product. When both CP and PR variable are equal to 1 I want to create the CP_PR variable which will be equal to 1 and also to make zero the initial CP variable.</strong></em></p>
<p>I make a vector with the names of the CP variables and a vector of the PR variables:</p>
<pre><code>ListCP<-colnames(Data)[2:4]
ListPr<-colnames(Data)[5:7]
</code></pre>
<p>And then I use a double for loop in order to create the needed product combination Variables which correct creates the combinations I want:</p>
<pre><code>for (i in ListPr) {
for (j in ListCP) {
Data<-Data[,paste0(j,"_",i) := ifelse(get(i)==1 & get(j)==1,1,0)]
}
}
> Data
> Data
ID CP1 CP2 CP3 Pr1 Pr2 Pr3 CP1_Pr1 CP2_Pr1 CP3_Pr1 CP1_Pr2 CP2_Pr2 CP3_Pr2 CP1_Pr3 CP2_Pr3 CP3_Pr3
1: 1 1 0 0 1 0 0 1 0 0 0 0 0 0 0 0
2: 1 0 1 0 1 0 0 0 1 0 0 0 0 0 0 0
3: 1 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0
4: 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
5: 2 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0
6: 2 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
7: 3 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
8: 3 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
9: 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
10: 4 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
11: 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
12: 4 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1
</code></pre>
<p>Then when I am trying to make zero the initial CP vars in case that I said above I am getting an error.</p>
<pre><code>> for (i in ListCP) {
+
+ for (j in ListPr) {
+
+ Data<-Data[paste0(j,"_",i)==1,.(j) := 0]
+
+
+ }
+
+ }
Error in `[.data.table`(Data, paste0(j, "_", i) == 1, `:=`(.(j), 0)) :
LHS of := must be a symbol, or an atomic vector (column names or positions).
</code></pre>
<p>My question here is if I can combine both double for loops into one without getting an error.
Also, because my dataset is bigger, any other faster implementation would be greatly appreciated.</p>
<p>Thank you.</p>
| 3 | 2,306 |
deletes everything from the database,the getRef() method does not work because i cant put my dialog inside the FirebaseRecyclerAdapter
|
<p>RETRIEVADATA CLASS</p>
<p>package com.dikolobe.salesagent;</p>
<p>public class RetrieveData extends AppCompatActivity implements View.OnClickListener,OnNoteClickListener{</p>
<p>private static final String TAG = "";</p>
<pre><code>private FirebaseRecyclerAdapter<Product, ViewHolder> firebaseRecyclerAdapter;
//FirebaseRecyclerAdapter adapter;
FirebaseDatabase mDatabase;
DatabaseReference mRef;
FirebaseStorage mStorage;
ItemsAdapter itemsAdapter;
List<Product> productList=new ArrayList<>();
RecyclerView recyclerView;
TextView phone_num;
ViewHolder viewHolder;
private static final int PERMISSION_REQUEST_CODE = 1;
ImageView img;
OnNoteClickListener onNoteClickListener;
Context context;
private List<Product> listItems= new ArrayList<>();
private List<Product> listItemsFull;
public ArrayList<Product> filterList = new ArrayList<>();
private int progressStatus = 0;
private Handler handler = new Handler();
String imageUrl = null;
SearchView searchView;
//ImageView delete;
String productId;
String image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve_data);
// delete =findViewById(R.id.delete);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.SEND_SMS)
== PackageManager.PERMISSION_DENIED) {
Log.d("permission", "permission denied to SEND_SMS - requesting it");
String[] permissions = {Manifest.permission.SEND_SMS};
requestPermissions(permissions, PERMISSION_REQUEST_CODE);
}
}
searchView=findViewById(R.id.search);
FirebaseRecyclerOptions<Product> options = new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(FirebaseDatabase.getInstance().getReference()
.child("Items"),Product.class)
.build();
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference().child("Items");
mStorage = FirebaseStorage.getInstance();
recyclerView = findViewById(R.id.recyclerview_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<Product>();
itemsAdapter = new ItemsAdapter(RetrieveData.this, productList,this,options);
recyclerView.setAdapter(itemsAdapter);
mRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
Product product = dataSnapshot.getValue(Product.class);
productList.add(product);
itemsAdapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
protected void onStart(){
super.onStart();
FirebaseRecyclerOptions<Product> options = new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(FirebaseDatabase.getInstance()
.getReference().child("Items"), Product.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull com.dikolobe.salesagent.ViewHolder holder, final int
</code></pre>
<p>position, @NonNull Product product) {</p>
<pre><code> }
@NonNull
@Override
public com.dikolobe.salesagent.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
</code></pre>
<p>viewType) {</p>
<pre><code> View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.design_row_for_recyclerview, parent, false);
return new com.dikolobe.salesagent.ViewHolder(view,onNoteClickListener);
}
public void deleteProduct(int position) {
try{
FirebaseDatabase.getInstance().getReference().child("Items")
.child(getRef(position).getKey())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(context,"Deleted succesfully",Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e){
Log.e("error", e.getMessage());
}
}
};
firebaseRecyclerAdapter.startListening();
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
</code></pre>
<p>@Override</p>
<p>protected void onStop() {</p>
<pre><code>super.onStop();
</code></pre>
<p>firebaseRecyclerAdapter.stopListening();</p>
<p>}</p>
<pre><code>@Override
</code></pre>
<p>public boolean onCreateOptionsMenu(Menu menu) {</p>
<pre><code>MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
MenuItem menuItem=menu.findItem(R.id.search);
SearchView searchView=(SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
search_product(query);
// itemsAdapter.getFilter().filter(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
search_product(newText);
//itemsAdapter.getFilter().filter(newText.toString());
return false;
}
});
return true;
</code></pre>
<p>}</p>
<p>@Override</p>
<p>public boolean onOptionsItemSelected(MenuItem item) {</p>
<pre><code> if (item.getItemId() == R.id.add_product) {
startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "post a product", Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.tutorial) {
// startActivity(new Intent(this, AddRider.class));
// Toast.makeText(this,"Add a rider to an Event",Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.logOut) {
startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "bye", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
</code></pre>
<p>}</p>
<p>ItemTouchHelper.SimpleCallback simpleCallback=new</p>
<p>ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {</p>
<pre><code> @Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, Re
</code></pre>
<p>cyclerView.ViewHolder target) {</p>
<pre><code> return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
removeItem((long) viewHolder.itemView.getTag());
productList.remove(viewHolder.getAdapterPosition());
itemsAdapter.notifyDataSetChanged();
}
private void removeItem(long id) {
}
};
private boolean updateItem(String seller, String description, String price,String location,String
</code></pre>
<p>phone,String productId,String image,String posted_date) {</p>
<pre><code> //getting the specified product reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Items").child(productId);
//updating product
Product product = new Product(productId, seller,
</code></pre>
<p>description,price,phone,location,image,posted_date);</p>
<pre><code> dR.setValue(product);
Toast.makeText(getApplicationContext(), "Product Updated", Toast.LENGTH_LONG).show();
return true;
}
@Override
public void onNoteClick(final int position) {
CharSequence[] items = {"Update", "Delete"};
AlertDialog.Builder dialog = new AlertDialog.Builder(RetrieveData.this);
dialog.setTitle("Choose Action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Intent update_activty = new Intent(getApplicationContext(),Update_Product.class);
startActivity(update_activty);
}
if (i==1){
Product product=productList.get(position);
productId =product.getProductId();
image =product.getImage();
final AlertDialog.Builder dialogdelete = new
</code></pre>
<p>AlertDialog.Builder(RetrieveData.this);</p>
<pre><code> dialogdelete.setTitle("Warning");
dialogdelete.setMessage("Are You Sure You Want to Delete?");
dialogdelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Query mQuery = mRef.orderByChild("productId").equalTo(productId);
mQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
ds.getRef().removeValue();
}
</code></pre>
<p>Toast.makeText(RetrieveData.this,"deleted..!",Toast.LENGTH_SHORT).show();</p>
<pre><code> }
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
</code></pre>
<p>Toast.makeText(RetrieveData.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();</p>
<pre><code> }
});
Query mPictureReference =
</code></pre>
<p>FirebaseDatabase.getInstance().getReference("Items").orderByChild("image").equalTo(image);</p>
<pre><code> mPictureReference.getRef().removeValue().addOnSuccessListener(new
</code></pre>
<p>OnSuccessListener() {
@Override</p>
<pre><code> public void onSuccess(Void aVoid) {
Toast.makeText(RetrieveData.this,"Image
</code></pre>
<p>deleted",Toast.LENGTH_SHORT).show();</p>
<pre><code> }
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(RetrieveData.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
dialogdelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialogdelete.show();
}
}
});
dialog.show();
// Toast.makeText(getApplicationContext(),"cliked",Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v) {
}
public static String getTimeDate(long timestamp){
try{
DateFormat dateFormat = getDateTimeInstance();
Date netDate = (new Date(timestamp));
return dateFormat.format(netDate);
} catch(Exception e) {
return "date";
}
}
</code></pre>
<p>}</p>
<p>ADAPTER CLASS</p>
<p>package com.dikolobe.salesagent;</p>
<p>public class ItemsAdapter extends RecyclerView.Adapter implements Filterable {</p>
<pre><code>public ArrayList<Product> filterList = new ArrayList<>();
private int progressStatus = 0;
private Handler handler = new Handler();
private OnNoteClickListener onNoteClickListener;
Context context;
private List<Product> listItems;
private List<Product> listItemsFull;
private Product product;
FirebaseRecyclerOptions<Product> options;
String imageUrl = null;
public ItemsAdapter(Context context, List<Product> listItems,OnNoteClickListener
</code></pre>
<p>onNoteClickListener,FirebaseRecyclerOptions options) {</p>
<pre><code> this.context = context;
this.listItems = listItems;
listItemsFull = new ArrayList<>(listItems);
this.onNoteClickListener = onNoteClickListener;
this.options=options;
}
public ItemsAdapter(FirebaseRecyclerOptions<Product> options) {
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v =
</code></pre>
<p>LayoutInflater.from(parent.getContext()).inflate(R.layout.design_row_for_recyclerview,parent,false);</p>
<pre><code> return new ViewHolder(v,onNoteClickListener);
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
product = listItems.get(position);
holder.seller.setText(listItems.get(position).getSeller());
holder.desc.setText(listItems.get(position).getDescription());
holder.price.setText(listItems.get(position).getPrice());
holder.location.setText(listItems.get(position).getLocation());
holder.phone.setText(listItems.get(position).getPhone());
holder.time.setText((CharSequence) listItems.get(position).getPosted_date());
holder.progress_Bar = new ProgressBar(context);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
handler.post(new Runnable() {
public void run() {
holder.progressBar.setProgress(progressStatus);
holder.textView.setText(progressStatus+"/"+holder.progressBar.getMax());
}
});
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
imageUrl = product.getImage();
Picasso.get().load(imageUrl).into(holder.imageView, new Callback() {
@Override
public void onSuccess() {
holder.image_layout.setVisibility(View.INVISIBLE);
}
@Override
public void onError(Exception e) {
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
holder.phone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int id=v.getId();
if (id==R.id.phoneTv){
String phoneNumber = product.getPhone();
String message = "I am interested";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(context,"Interest message sent successfully",
</code></pre>
<p>Toast.LENGTH_LONG).show();</p>
<pre><code> }
}
});
holder.call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int id=v.getId();
if(id==R.id.call){
String phoneNumber = product.getPhone();
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phoneNumber));
context.startActivity(intent);
}
}
}); }
@Override
public int getItemCount() {
return listItems.size();
}
@Override
public Filter getFilter() {
return filterProducts;
}
private Filter filterProducts = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
///*to delete*/String search_text = constraint.toString().toLowerCase();
List<Product> productFiltrate = new ArrayList<>();
if (constraint.length()==0 ){
productFiltrate.addAll(listItemsFull);
}else
{
String pattern = constraint.toString().toLowerCase().trim();
for (Product product:listItemsFull){
if(product.getSeller().toLowerCase().contains(pattern)){
productFiltrate.add(product);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = productFiltrate;
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterList.clear();
filterList.addAll((List) results.values);
notifyDataSetChanged();
}
};
</code></pre>
<p>}</p>
<p>INSERT DATA/MAIN_ACTIVITY</p>
<p>package com.dikolobe.salesagent;</p>
<p>public class MainActivity extends AppCompatActivity {</p>
<pre><code>FirebaseRecyclerAdapter firebaseRecyclerAdapter;
</code></pre>
<p>ItemsAdapter itemsAdapter;</p>
<pre><code>FirebaseDatabase mDatabase;
DatabaseReference mRef;
FirebaseStorage mStorage;
EditText seller_name,desc,price,location,phone;
Button btnInsert,list;
ImageButton imageButton,take_Photo;
ProgressBar progressBar;
private ProgressDialog mProgress;
Uri imageUri = null;
final int REQUEST_CODE_IMAGE=999;
static final int REQUEST_IMAGE_CAPTURE = 1;
private int progressStatus = 0;
private TextView textView;
private Handler handler = new Handler();
ViewHolder holder;
FrameLayout image_layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seller_name = findViewById(R.id.seller_nameEt);
desc = findViewById(R.id.descEt);
price = findViewById(R.id.priceEt);
location = findViewById(R.id.locationEt);
phone = findViewById(R.id.phoneEt);
btnInsert = findViewById(R.id.save);
//list = findViewById(R.id.list);
imageButton = findViewById(R.id.imageButton);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textView = (TextView) findViewById(R.id.textView);
image_layout = (FrameLayout) findViewById(R.id.layout_image);
take_Photo = (ImageButton) findViewById(R.id.take_pic);
take_Photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int id = v.getId();
if (id==R.id.take_pic){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
});
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference().child("Items");
mStorage = FirebaseStorage.getInstance();
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_IMAGE);
}
});
progressBar = new ProgressBar(MainActivity.this);
image_layout.setVisibility(View.INVISIBLE);
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
image_layout.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
//current value in the text view
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
try {
// Sleep for 200 milliseconds.
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
final String seller = seller_name.getText().toString().trim();
final String fn = desc.getText().toString().trim();
final String ln = price.getText().toString().trim();
final String place = location.getText().toString().trim();
final String phon = phone.getText().toString().trim();
final String id = mRef.push().getKey();
if (!(seller.isEmpty() && fn.isEmpty() && ln.isEmpty() && place.isEmpty() &&
</code></pre>
<p>phon.isEmpty() && imageUri!=null)){</p>
<pre><code> StorageReference filepath =
</code></pre>
<p>mStorage.getReference().child("images").child(imageUri.getLastPathSegment());</p>
<pre><code> filepath.putFile(imageUri).addOnSuccessListener(new
</code></pre>
<p>OnSuccessListener<UploadTask.TaskSnapshot>() {</p>
<pre><code> @Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
image_layout.setVisibility(View.INVISIBLE);
Task<Uri> downloadUrl =
</code></pre>
<p>taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener() {</p>
<pre><code> @Override
public void onComplete(@NonNull Task<Uri> task) {
String t=task.getResult().toString();
final DatabaseReference newPost=mRef.push();
newPost.child("seller").setValue(seller);
newPost.child("description").setValue(fn);
newPost.child("price").setValue(ln);
newPost.child("location").setValue(place);
newPost.child("phone").setValue(phon);
newPost.child("productId").setValue(id);
newPost.child("image").setValue(task.getResult().toString());
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String strDate = dateFormat.format(date).toString();
newPost.child("posted_date").setValue(strDate);
Toast.makeText(MainActivity.this,"successfully uploaded",
</code></pre>
<p>Toast.LENGTH_SHORT).show();</p>
<pre><code> seller_name.setText("");
desc.setText("");
price.setText("");
location.setText("");
phone.setText("");
imageButton.setImageURI(null);
goToRetrieveDataClass();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Failed to
</code></pre>
<p>upload..!",Toast.LENGTH_LONG).show();</p>
<pre><code> }
});
}
});
}else Toast.makeText(MainActivity.this,"Please write all your
</code></pre>
<p>details..!",Toast.LENGTH_LONG).show();</p>
<pre><code> }
});
if (!hasCamera())
take_Photo.setEnabled(false);
}
@Override
protected void onStart() {
super.onStart();
// firebaseRecyclerAdapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
// firebaseRecyclerAdapter.stopListening();
}
private Boolean hasCamera() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
public void launchCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
</code></pre>
<p>grantResults) {</p>
<pre><code> if (requestCode == REQUEST_CODE_IMAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
gallery.setType("image/*");
startActivityForResult(gallery, REQUEST_CODE_IMAGE);
} else {
Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
imageUri = data.getData();
CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1).start(this);
imageButton.setImageURI(imageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
}
else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Exception error = result.getError();
}
}
super.onActivityResult(requestCode, resultCode,data);
}
</code></pre>
<p>}</p>
| 3 | 12,521 |
cannot generate sources after switching os
|
<p>i recently switched from Ubuntu to Windows 10 and i can't generate sources any more. the relevant section of my pom.xml is as follows</p>
<pre><code><plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf-codegen-plugin.version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${project.build.directory}/generated/cxf</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${basedir}/src/main/resources/postcode/find_1_10.wsdl</wsdl>
<wsdlLocation>classpath:postcode/find_1_10.wsdl</wsdlLocation>
<extraargs>
<extraarg>-p</extraarg>
<extraarg>uk.co.postcodeanywhere.services.find</extraarg>
</extraargs>
</wsdlOption>
<wsdlOption>
<wsdl>${basedir}/src/main/resources/postcode/postzon_1_40.wsdl</wsdl>
<wsdlLocation>classpath:postcode/postzon_1_40.wsdl</wsdlLocation>
<extraargs>
<extraarg>-p</extraarg>
<extraarg>uk.co.postcodeanywhere.services.postzon</extraarg>
</extraargs>
</wsdlOption>
<wsdlOption>
<wsdl>${basedir}/src/main/resources/postcode/retrievebyaddress_1_20.wsdl</wsdl>
<wsdlLocation>classpath:postcode/retrievebyaddress_1_20.wsdl</wsdlLocation>
<extraargs>
<extraarg>-p</extraarg>
<extraarg>uk.co.postcodeanywhere.services.retrievebyaddress</extraarg>
</extraargs>
</wsdlOption>
<wsdlOption>
<wsdl>${basedir}/src/main/resources/postcode/retrievebyid_1_30.wsdl</wsdl>
<wsdlLocation>classpath:postcode/retrievebyid_1_30.wsdl</wsdlLocation>
<extraargs>
<extraarg>-p</extraarg>
<extraarg>uk.co.postcodeanywhere.services.retrievebyid</extraarg>
</extraargs>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
</code></pre>
<p>the error during the maven build is as follows</p>
<pre><code>[WARNING] The POM for com.sun.xml.bind:jaxb-xjc:jar:2.2.11 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
[INFO] Running code generation in fork mode...
[INFO] The java executable is C:\Java\jdk-11.0.1_windows-x64_bin\jdk-11.0.1\bin\java.exe
[INFO] Building jar: C:\Users\MATTHE~1\AppData\Local\Temp\cxf-tmp-819761540992222663\cxf-codegen12512113659748193013.jar
[INFO] Error occurred during initialization of boot layer
[INFO] java.lang.module.FindException: Module java.xml.ws not found
</code></pre>
<p>i tried to test with jdk 8 but it seems to only download a JRE from the oracle website</p>
| 3 | 2,185 |
Exit code -11 after installation of Vim auto completion plugin YouCompleteMe with MacVim (Vim version 8.1)
|
<p>I'd like to install the auto completion plugin YouCompleteMe for Vim.</p>
<p>I followed the instructions of the installation guide at <a href="https://github.com/Valloric/YouCompleteMe/blob/master/README.md#full-installation-guide" rel="nofollow noreferrer">https://github.com/Valloric/YouCompleteMe/blob/master/README.md#full-installation-guide</a></p>
<p>I chose the simpler option without semantic completion support for C-family languages.</p>
<p>Executing
<code>vim --version</code>
returns</p>
<pre><code>VIM - Vi IMproved 8.1 (2018 May 18, compiled Feb 19 2019 12:07:03)
macOS version
Included patches: 1-950
Compiled by Homebrew
Huge version with MacVim GUI. Features included (+) or not (-):
+acl -farsi +mouse_sgr -tag_any_white
+arabic +file_in_path -mouse_sysmouse -tcl
+autocmd +find_in_path +mouse_urxvt +termguicolors
+autochdir +float +mouse_xterm +terminal
-autoservername +folding +multi_byte +terminfo
+balloon_eval -footer +multi_lang +termresponse
+balloon_eval_term +fork() -mzscheme +textobjects
+browse +fullscreen +netbeans_intg +textprop
++builtin_terms -gettext +num64 +timers
+byte_offset -hangul_input +odbeditor +title
+channel +iconv +packages +toolbar
+cindent +insert_expand +path_extra +transparency
+clientserver +job +perl +user_commands
+clipboard +jumplist +persistent_undo +vartabs
+cmdline_compl +keymap +postscript +vertsplit
+cmdline_hist +lambda +printer +virtualedit
+cmdline_info +langmap +profile +visual
+comments +libcall -python +visualextra
+conceal +linebreak +python3 +viminfo
+cryptv +lispindent +quickfix +vreplace
+cscope +listcmds +reltime +wildignore
+cursorbind +localmap +rightleft +wildmenu
+cursorshape +lua +ruby +windows
+dialog_con_gui +menu +scrollbind +writebackup
+diff +mksession +signs -X11
+digraphs +modify_fname +smartindent -xfontset
+dnd +mouse +startuptime +xim
-ebcdic +mouseshape +statusline -xpm
+emacs_tags +mouse_dec -sun_workshop -xsmp
+eval -mouse_gpm +syntax -xterm_clipboard
+ex_extra -mouse_jsbterm +tag_binary -xterm_save
+extra_search +mouse_netterm +tag_old_static
system vimrc file: "$VIM/vimrc"
user vimrc file: "$HOME/.vimrc"
2nd user vimrc file: "~/.vim/vimrc"
user exrc file: "$HOME/.exrc"
system gvimrc file: "$VIM/gvimrc"
user gvimrc file: "$HOME/.gvimrc"
2nd user gvimrc file: "~/.vim/gvimrc"
defaults file: "$VIMRUNTIME/defaults.vim"
system menu file: "$VIMRUNTIME/menu.vim"
fall-back for $VIM: "/Applications/MacVim.app/Contents/Resources/vim"
Compilation: clang -c -I. -Iproto -DHAVE_CONFIG_H -DFEAT_GUI_MACVIM -Wall -Wno-unknown-pragmas -pipe -DMACOS_X -DMACOS_X_DARWIN -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: clang -L. -L. -L/usr/local/lib -o Vim -framework Cocoa -framework Carbon -lm -lncurses -liconv -framework AppKit -L/usr/local/opt/lua/lib -llua5.3 -fstack-protector -L/System/Library/Perl/5.18/darwin-thread-multi-2level/CORE -lperl -L/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/config-3.7m-darwin -lpython3.7m -framework CoreFoundation -framework Ruby
</code></pre>
<p>I added the line</p>
<p><code>Plugin 'Valloric/YouCompleteMe'</code></p>
<p>to my .vimrc, afterwards the Vim command</p>
<p><code>:PluginInstall</code></p>
<p>executes without errors.</p>
<p>If I then start Vim the following error message is displayed:</p>
<p><code>The ycmd server SHUT DOWN (restart with ':YcmRestartServer'). Unexpected exit code -11. Type ':YcmToggleLogs ycmd_62275_stderr_menu0zqa.log' to check the logs.</code></p>
<p>The here mentioned log file is empty. Does anyone know what's the problem here?</p>
<p>I know there are a lot of other questions on StackOverflow and Github regarding very similar problems. But since I've spent the last 3 hours going through these and trying to get the plugin to work without success, I'd be happy if this won't be marked as duplicate and am very grateful for every response.</p>
| 3 | 2,266 |
Returning customize Array value
|
<p>I have a sample of code that returns each value in an array, in order. I have used <code>forEach()</code>. Is there any way to return value in customize array. </p>
<p>I made some function for split <code>text-area</code> value to all textarea and query using text string. I am able to success. But Some Problem. Below Example.</p>
<ol>
<li><p>Type to <code>Filed1</code> string like:
<br> <code>GFSD</code><br><code>65897542</code></p></li>
<li><p>Then Click Split Button. Output: part all value to reaming text area.</p></li>
<li><p>Put <strong>GF</strong> value to <strong>Input Character</strong> Filed. Output: <strong>6589</strong></p></li>
<li>My Question is When i put value like <strong>GF</strong> then output <strong>6589</strong>. And when put <strong>FG</strong> then also same output <strong>6589</strong> instead of <strong>8965</strong>. If any solution Pls help me out. I wish to the Character strictly follow number.</li>
</ol>
<p>Sample of Code:</p>
<pre><code>$('#output1').focus(()=>{
var a=document.querySelectorAll('textarea');
var str = $('#ccMain').val();
var first = str[0];
var second = str[1];
console.log(first," ", second)
var str='';
a.forEach(e=>e.value.includes(first)||e.value.includes(second)?str+=e.value.substr(1,e.value.length):false)
$('#output1').val(str);
})
</code></pre>
<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> function splitText() {
var textAreas = [];
//Put all of the textareas into an array for easy access
for(let i = 1; i <= 4; i++) {
textAreas.push(document.getElementById(`value${i}`));
}
//Read the text from text1 and split it at a new line
var text = textAreas[0].value;
var [line1, line2] = text.split(/\r?\n/)
for(let i = 0; i < 4; i++) {
var combinedText = line1.substring(i, i+1) + line2.substring(i*2, (i+1)*2)
textAreas[i].value = combinedText;
}
}
$('#output').focus(()=>{
var a=document.querySelectorAll('textarea');
var str = $('#ccMain').val();
var first = str[0];
var second = str[1];
console.log(first," ", second)
var str='';
a.forEach(e=>e.value.includes(first)||e.value.includes(second)?str+=e.value.substr(1,e.value.length):false)
$('#output').val(str);
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Test Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<label>Filed1 </label>
<textarea id="value1"></textarea>
<label>Filed2:</label>
<textarea id="value2"></textarea>
<label>Filed3:</label>
<textarea id="value3"></textarea>
<label>Filed4:</label>
<textarea id="value4"></textarea>
<button onclick="splitText()">Split!</button>
<br>
<label>Input Character:</label>
<br>
<input type="text" id="ccMain" >
<textarea id="output"></textarea>
</body>
</html></code></pre>
</div>
</div>
</p>
| 3 | 1,559 |
How to reference more than one controller in one view (CakePHP)
|
<p>I am building an application in CakePHP (I have been using this for a couple of months in a new job, and took over this project from the previous employee, so my understanding is limited).</p>
<p>This application has several database tables, the ones involved in this problem are Centres, Softwares and Categories.</p>
<p>To give you a brief, hat I need, is when a user visits the 'Centres' view, to be able to have a list of all of the software below, and tick which the centres have access to.</p>
<p>To view a list of software, my SoftwaresController uses the function:</p>
<pre><code>public function view() {
$categories = $this->Software->Category->find ('list');
array_unshift ($categories, array('any' => 'Any'));
$this->set ('categories', $categories);
$this->Software->hasMany['Version']['limit'] = 1;
$this->Software->hasMany['Version']['fields'] = array('Version.id', 'Version.version_number', 'Version.created');
if ($this->request->is ('post') && $this->request->data) {
$conditions = array();
$filters = $this->request->data['Software'];
if (!empty($filters['name'])) {
$conditions['Software.name'] = $filters['name'];
}
if ($filters['category'] > 0) {
$conditions['Category.id'] = $filters['category'];
}
$this->paginate = array(
'conditions' => $conditions,
'order' => array(
'Software.latest_released' => 'desc',
'Software.name' => 'asc'
)
);
$this->set ('softwares', $this->paginate ());
$this->set ('paging', false);
} else {
$this->paginate = array(
'order' => array(
'Software.latest_released' => 'desc',
'Software.name' => 'asc'
)
);
$this->set ('paging', true);
$this->set ('softwares', $this->paginate ());
}
// This allows the user software page to show.
}
</code></pre>
<p>In the CentresController function, in which I want to be able to also view the data (as extracted above), looks like this:</p>
<pre><code>public function admin_view($id = null)
{
/* Centres */
$this->Centre->recursive = 0;
$this->Centre->id = $id;
if (!$this->Centre->exists()) {
throw new NotFoundException(__('This centre ID does not exist.'));
}
$centre = $this->Centre->read(null, $id);
$this->request->data = $centre;
$this->set('centre', $centre);
}
</code></pre>
<p>I have tried to combine the above two functions by adding the inside of view() into admin_view(). The view for admin_view() looks like this:</p>
<p>
Assign Software Access</p>
<pre><code> <div class="row-fluid">
<div class="span12">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Version Number</th>
<th>Created</th>
<th>Modified</th>
<th>Released</th>
<th>Grant Permission</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach ($software['Version'] as $version):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="even"';
} else {
$class = ' class="odd"';
}
?>
<tr<?php echo $class;?>>
<td><?php echo $version['version_number']; ?>&nbsp;</td>
<td>
<?php
echo $this->Time->format (Configure::read ('Format.time'), $version['created']);
?>&nbsp;
</td>
<td>
<?php
echo $this->Time->format (Configure::read ('Format.time'), $version['modified']);
?>&nbsp;
</td>
<td>
<?php
echo $this->Time->format (Configure::read ('Format.time'), $version['released']);
?>&nbsp;
</td>
<td class="actions" style="text-align: center;">
<?php
echo $this->Html->link (
'<i class="fa fa-cloud-download"></i>&nbsp;Download',
array(
'controller' => 'versions',
'action' => 'view',
$version['id']
),
array('escape' => false)
);
?>&nbsp;
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
</fieldset>
<div class="col-sm-12 col-md-5 col-lg-4 padding-right-0">
<div class="panel panel-default">
<div class="panel-heading"><span class="fa fa-cog"></span>&nbsp;Actions</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-4 padding-bottom-10">
<?php
echo $this->Form->button(
'<i class="fa fa-pencil"></i>&nbsp;Update',
array(
'type' => 'submit',
'class' => 'btn btn-success btn-sm btn-block',
'escape' => false
)
);
echo $this->Form->end();
?>
</div>
<!-- /.col-sm-4 padding-bottom-10 -->
<div class="col-sm-4 padding-bottom-10">
<a class="btn btn-danger btn-sm btn-block" href="#modal-dialog"
data-toggle="modal"
data-target="#modal-dialog"><i class="fa fa-trash"></i>&nbsp;Delete</a>
</div>
<!-- /.col-sm-4 padding-bottom-10 -->
<div class="col-sm-4 padding-bottom-10">
<?php
echo $this->Html->link(
"<span class='fa fa-times'></span>&nbsp;Cancel",
array(
'action' => 'index'
),
array(
'escape' => false,
'class' => 'btn btn-default btn-sm btn-block'
)
);
?>
</div>
<!-- /.col-sm-4 padding-bottom-10 -->
</div>
<!-- /.row -->
</div>
</code></pre>
<p>The error I am getting is:</p>
<blockquote>
<p>Error: Call to a member function find() on null
File: /Applications/XAMPP/xamppfiles/htdocs/licensemanagementsite/app/Controller/CentresController.php
Line: 87</p>
</blockquote>
<p>I have also included at the top of the CentresController and the Centres model:
App::uses('AppController', 'Controller', 'SoftwaresController');</p>
<p>Any assistance you can give me would be really appreciated. No one in my office knows anything about CakePHP (including me, I guess!).</p>
<p>Thanks!</p>
| 3 | 6,103 |
Method not found: GraphQL.ExecutionOptions.set_NameConverter in netcoreapp2.2
|
<p>I need to integrate GraphQL in NetCoreApp 2.2 <code><TargetFramework>netcoreapp2.2</TargetFramework></code> (I can't upgrade to NetCore 3 for other reasons).</p>
<p>PS. We have another project in .Net Core 3.1 and we can use <em>GraphQL.Server.Transports.AspNetCore.SystemTextJson</em> and we don't have any problem. Everything works as expected in that project.</p>
<p>I am getting the following error at the moment:</p>
<pre><code>System.MissingMethodException: Method not found: 'Void GraphQL.ExecutionOptions.set_NameConverter(GraphQL.Conversion.INameConverter)'.
at GraphQL.Server.Internal.DefaultGraphQLExecuter`1.GetOptions(String operationName, String query, Inputs variables, IDictionary`2 context, IServiceProvider requestServices, CancellationToken cancellationToken)
at GraphQL.Server.Internal.DefaultGraphQLExecuter`1.ExecuteAsync(String operationName, String query, Inputs variables, IDictionary`2 context, IServiceProvider requestServices, CancellationToken cancellationToken) in /_/src/Core/Internal/DefaultGraphQLExecuter.cs:line 45
at GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware`1.InvokeAsync(HttpContext context) in /_/src/Transports.AspNetCore/GraphQLHttpMiddleware.cs:line 144
at Microsoft.AspNetCore.Builder.Extensions.UsePathBaseMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
</code></pre>
<p>If I am not wrong, I am getting this error because I'm using the different combination of Nuget Packages and one of the assemblies is missing that required method.</p>
<p>This is my current setup in csproj and I tried to swap with other versions (Eg. GraphQL 4.0) and I still couldn't make it work.</p>
<pre><code><PackageReference Include="GraphQL" Version="4.2.0" />
<PackageReference Include="GraphQL.MicrosoftDI" Version="4.2.0" />
<PackageReference Include="GraphQL.Server.Transports.AspNetCore.NewtonsoftJson" Version="4.4.1" />
<PackageReference Include="GraphQL.Server.Ui.Playground" Version="4.4.1" />
</code></pre>
<p>my Startup.cs - <strong>ConfigureServices</strong> method</p>
<pre><code>services.AddSingleton<ISchema, MyDataSchema>(serviceProvider => new MyDataSchema(new SelfActivatingServiceProvider(serviceProvider)));
services.AddGraphQL(options =>
{
options.EnableMetrics = true;
})
.AddNewtonsoftJson()
.AddErrorInfoProvider(opt => opt.ExposeExceptionStackTrace = true);
</code></pre>
<p><strong>Configure</strong> method</p>
<pre><code>app.UseGraphQL<ISchema>();
app.UseGraphQLPlayground();
</code></pre>
<p>Could you please suggest me how I can use GraphQL in .Net Core 2.2?</p>
<p>If you know the right combination of the assemblies / codes / documentations which I can reference to make it work in .Net Core 2.2, please help me. I couldn't find the old documentations and it's always for the latest version.</p>
| 3 | 1,060 |
Getting errors when concatenating features to Keras Functional API with multiple inputs
|
<p>Where would I insert features I've extracted from the training set to use in the model? Would I just concatenate with layers.concatenate([])?
EX: I've calculated the semantic similarity of headline and document. I want to that feature as an input in the model.</p>
<p><strong>Info:</strong></p>
<pre><code>embedded_sequences_head: Tensor w/shape (None, 15, 300) #Glove300D
embedded_sequences_body: Tensor w/shape (None, 150, 300) # Glove 300D
sequence_input_head: Tensor w/shape (None, 15)
sequence_input_body: Tensor w/shape (None, 150)
sequence_input_body: Tensor w/shape (None, 26784)
headline_pad: ndarray w/shape (26784, 15), dtype=int32
art_body_pad: ndarray w/shape (26784, 150), dtype=int32
y_train_cat: ndarray w/shape (26784, 4), dtype=float32
semantic_x_tr = np.array(x_train['semantic_sim_70'].to_list()) # ndarray (26784,)
</code></pre>
<hr />
<p><strong>Model</strong></p>
<pre><code>semantic_feat = Input(shape=(len(semantic_x_tr),), name ="semantic")
x1 = Conv1D( FILTERS, kernel_size = KERNEL, strides = STRIDE, padding='valid', activation = 'relu')(embedded_sequences_head)
x11 = GlobalMaxPooling1D()(x1)
x2 = Conv1D( FILTERS, kernel_size = KERNEL, strides = STRIDE, padding='valid', activation = 'relu')(embedded_sequences_body)
x22 = GlobalMaxPooling1D()(x2)
x = concatenate([x11,x22, semantic_feat], axis=1)
x = Dense(UNITS, activation="relu")(x)
x = Dropout(0.5)(x)
preds = Dense(4, activation="softmax", name = 'predic')(x)
</code></pre>
<hr />
<p><strong>Train Model</strong></p>
<pre><code>model = Model(inputs = [sequence_input_head, sequence_input_body, semantic_feat], outputs = [preds],)
history = model.fit({'headline':headline_pad, 'articleBody':art_body_pad, 'semantic': semantic_x_tr},
{'predic':y_train_cat},
epochs=100,
batch_size= BATCH__SIZE,
shuffle= True,
validation_data = ([headline_padded_validation, art_body_padded_validation, semantic_x_val], y_val_cat),
callbacks = [es]
)
</code></pre>
<p>This <strong>Model</strong> block compiles with seemingly no errors, but when I go to run the <strong>Train Model</strong> block of code it returns a warning and error:</p>
<blockquote>
<p>WARNING: tensorflow:Model was constructed with shape (None, 26784) for
input Tensor("semantic_6:0", shape=(None, 26784), dtype=float32), but
it was called on an input with incompatible shape (None, 1).</p>
</blockquote>
<blockquote>
<p>ValueError: Input 0 of layer dense_16 is incompatible with the layer:
expected axis -1 of input shape to have value 26804 but received input
with shape [None, 21]</p>
</blockquote>
<p><strong>UPDATE 9/25/2020</strong></p>
<hr />
<p>I believe the issue was due to a syntax error on my part in the x = concatenate() function.</p>
<pre><code>x = tf.keras.layers.Concatenate(axis=1)([x11, x22, semantic_feat])
</code></pre>
| 3 | 1,172 |
Google App Engine and Java org.reflection library - Error during the scan procedure
|
<p>I'm trying to setup a <code>ConfigurationBuilder</code> for the library <code>Reflections</code>, which use the following configuration:</p>
<p>I'm using the library through a <a href="http://mvnrepository.com/artifact/org.reflections/reflections/0.9.10" rel="nofollow">Maven dependency</a></p>
<pre><code><dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.10</version>
</dependency>
</code></pre>
<p>with the last available version, 0.9.10</p>
<p>Here is the 3 constraints which I need to apply to the scanner:</p>
<ul>
<li>annotated with <code>@Annotation1</code> or <code>@Annotation2</code></li>
<li>declared in the package <code>package1</code>, <code>package2</code> or <code>package3</code></li>
<li>an extension of the class <code>SuperClass.class</code></li>
</ul>
<p>All the code is executed in a <code>ServletContextListener</code> (triggered and the start of the instance, of dev-server if localhost)</p>
<p>This is the code I managed to create</p>
<pre><code>ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
// Package filter
FilterBuilder scannerFilter = new FilterBuilder();
scannerFilter.includePackage("com.mypackage1");
scannerFilter.includePackage("com.mypackage2");
scannerFilter.includePackage("com.mypackage3");
configurationBuilder.filterInputsBy(scannerFilter);
// Select the proper location to scan
configurationBuilder.setUrls(Arrays.asList(ClasspathHelper.forClass(SuperClass.class)));
Reflections reflections = new Reflections(configurationBuilder);
// Get all the classes with annotation @Annotation1 or @Annotation2
Set<Class<?>> annotation1Classes = reflections.getTypesAnnotatedWith(Annotation1.class);
Set<Class<?>> annotation2Classes = reflections.getTypesAnnotatedWith(Annotation2.class);
</code></pre>
<p>but it does not works. This line</p>
<pre><code>Reflections reflections = new Reflections(configurationBuilder);
</code></pre>
<p>triggers the following error:</p>
<pre><code>ago 26, 2015 1:22:22 PM com.google.appengine.tools.development.agent.impl.Transformer transform
GRAVE: Unable to instrument javassist.bytecode.annotation.ShortMemberValue. Security restrictions may not be entirely emulated.
java.lang.RuntimeException
at com.google.appengine.repackaged.org.objectweb.asm.MethodVisitor.visitParameter(MethodVisitor.java:114)
at com.google.appengine.repackaged.org.objectweb.asm.ClassReader.readMethod(ClassReader.java:959)
at com.google.appengine.repackaged.org.objectweb.asm.ClassReader.accept(ClassReader.java:693)
at com.google.appengine.repackaged.org.objectweb.asm.ClassReader.accept(ClassReader.java:506)
at com.google.appengine.tools.development.agent.impl.Transformer.rewrite(Transformer.java:146)
at com.google.appengine.tools.development.agent.impl.Transformer.transform(Transformer.java:113)
at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:424)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:199)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at javassist.bytecode.AnnotationsAttribute.getAnnotations(AnnotationsAttribute.java:227)
at org.reflections.adapters.JavassistAdapter.getAnnotationNames(JavassistAdapter.java:156)
at org.reflections.adapters.JavassistAdapter.getClassAnnotationNames(JavassistAdapter.java:50)
at org.reflections.adapters.JavassistAdapter.getClassAnnotationNames(JavassistAdapter.java:24)
at org.reflections.scanners.TypeAnnotationsScanner.scan(TypeAnnotationsScanner.java:12)
at org.reflections.scanners.AbstractScanner.scan(AbstractScanner.java:35)
at org.reflections.Reflections.scan(Reflections.java:250)
at org.reflections.Reflections.scan(Reflections.java:204)
at org.reflections.Reflections.<init>(Reflections.java:129)
at it.noovle.ape.core.persistence.objectify.ObjectifyManager.getClassesToRegister(ObjectifyManager.java:107)
at it.noovle.ape.core.listener.ObjectifyServantLoader.contextInitialized(ObjectifyServantLoader.java:51)
at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:548)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:136)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:266)
at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:288)
at com.google.appengine.tools.development.AutomaticInstanceHolder.startUp(AutomaticInstanceHolder.java:26)
at com.google.appengine.tools.development.AbstractModule.startup(AbstractModule.java:87)
at com.google.appengine.tools.development.Modules.startup(Modules.java:105)
at com.google.appengine.tools.development.DevAppServerImpl.doStart(DevAppServerImpl.java:258)
at com.google.appengine.tools.development.DevAppServerImpl.access$000(DevAppServerImpl.java:47)
at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:213)
at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:211)
at java.security.AccessController.doPrivileged(Native Method)
at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:211)
at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:270)
at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:218)
at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:209)
</code></pre>
<p>I should mention that I'm working on a Google App Engine project</p>
<p>I also tried starting from the sample provided in the <a href="https://github.com/ronmamo/reflections" rel="nofollow">home page</a></p>
<pre><code>//scan urls that contain 'my.package', include inputs starting with 'my.package', use the default scanners
Reflections reflections = new Reflections("my.package");
//or using ConfigurationBuilder
new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("my.project.prefix"))
.setScanners(new SubTypesScanner(),
new TypeAnnotationsScanner().filterResultsBy(optionalFilter), ...),
.filterInputsBy(new FilterBuilder().includePackage("my.project.prefix"))
...);
</code></pre>
<p>but I'm unable to create a working code.</p>
<hr>
<h2>EDIT</h2>
<p>Starting from the provided sample in the website (and through the use of JavaDoc) I managed to create another code</p>
<pre><code>Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(
// Select the proper location to scan
ClasspathHelper.forClass(SuperClass.class)
)
.setScanners(
// Scan only the subtype of SuperClass
new SubTypesScanner().filterResultsBy(
new FilterBuilder()
.include(SuperClass.class.getName())
),
// Scan only the types which have the required annotations
new TypeAnnotationsScanner().filterResultsBy(
new FilterBuilder()
.include(Annotation1.class.getName())
.include(Annotation2.class.getName())
)
)
.filterInputsBy(
// Include only 3 package in the analysis
new FilterBuilder()
.includePackage("com.my.package1")
.includePackage("com.my.package2")
.includePackage("com.my.package3")
)
);
Set<Class<?>> annotation1Classes = reflections.getTypesAnnotatedWith(Annotation1.class);
Set<Class<?>> annotation2Classes = reflections.getTypesAnnotatedWith(Annotation2.class);
</code></pre>
<p>This code works, as long as I use a <code>main</code> method to test the code (which I did to quickly test various lines of code instead of run every time the App Engine dev-server).</p>
<p>But the same code, executed by the App Engine dev-server triggers the exception error that I already posted above.</p>
<p>Then... the problem seems to be related to the App Engine server and not strictly to the Reflection code.</p>
<hr>
<h2>EDIT2</h2>
<p>It is true that during the scan (with the App Engine environment) there is the exception throwned (many times I need to add, so many that the Eclipse console log cannot contains all the lines and it remove the oldest ones).</p>
<p>But those exception are not really thrown (a catch clause will be pointless) and at the end the scanner provides the correct classes.</p>
<p>At this point those exception seems to be only severe logs thrown by the <code>Reflections</code> constructor but they don't stop the execution of the server.</p>
<p>It remains only to understand why those exception are thrown, maybe it is related to the App Engine environment which block some inside feature of Java.</p>
<hr>
<h2>EDIT3</h2>
<p>I tried to deploy the application to see what kind of behaviour there is on the production enviroment.
Unlike the development environment (which logs a lot of severe exceptions) online there isn't any error logged but the scan result is 0 classes.</p>
| 3 | 3,794 |
R: Cleaning up a wide and untidy dataframe
|
<p>I have a data frame that looks like: </p>
<pre><code>d<-data.frame(id=(1:9),
grp_id=(c(rep(1,3), rep(2,3), rep(3,3))),
a=rep(NA, 9),
b=c("No", rep(NA, 3), "Yes", rep(NA, 4)),
c=c(rep(NA,2), "No", rep(NA,6)),
d=c(rep(NA,3), "Yes", rep(NA,2), "No", rep(NA,2)),
e=c(rep(NA, 7), "No", NA),
f=c(NA, "No", rep(NA,3), "No", rep(NA,2), "No"))
>d
id grp_id a b c d e f
1 1 1 NA No <NA> <NA> <NA> <NA>
2 2 1 NA <NA> <NA> <NA> <NA> No
3 3 1 NA <NA> No <NA> <NA> <NA>
4 4 2 NA <NA> <NA> Yes <NA> <NA>
5 5 2 NA Yes <NA> <NA> <NA> <NA>
6 6 2 NA <NA> <NA> <NA> <NA> No
7 7 3 NA <NA> <NA> No <NA> <NA>
8 8 3 NA <NA> <NA> <NA> No <NA>
9 9 3 NA <NA> <NA> <NA> <NA> No
</code></pre>
<p>Within each group (grp_id) there is only 1 "Yes" or "No" value associated with each of the columns a:f.</p>
<p>I'd like to create a single row for each grp_id to get a data frame that looks like the following: </p>
<pre><code>grp_id a b c d e f
1 NA No No <NA> <NA> No
2 NA Yes <NA> Yes <NA> No
3 NA <NA> <NA> No No No
</code></pre>
<p>I recognize that the tidyr package is probably the best tool and the 1st steps are likely to be</p>
<pre><code>d %>%
group_by(grp_id) %>%
summarise()
</code></pre>
<p>I would appreciate help with the commands within summarise, or any solution really. Thanks. </p>
| 3 | 1,041 |
Issues populating dictionary with float values from Excel Pandas
|
<p>I'm using an excel spreadsheet to populate a dictionary. Then I'm using those values to multiply the values of another data frame by reference, but it gives me errors when I try. I decided to make the excel spreadsheet out my dictionary to avoid errors, but I haven't been successful. I'm doing this because the dictionary eventually gets long and it's too tedious to edit the keys and its values. I'm using Python 2.7</p>
<pre><code>import pandas as pd
#READ EXCEL FILE
df = pd.read_excel("C:/Users/Pedro/Desktop/dataframe.xls")
#Store the keys with its value in a dictionary. This will become df2
d = {"M1-4":0.60,"M1-5/R10":0.85,"C5-3":0.85,"M1-5/R7-3":0.85,"M1-4/R7A":0.85,"R7A":0.85,"M1-4/R6A":0.85,"M1-4/R6B":0.85,"R6A":0.85,"PARK":0.20,"M1-6/R10":0.85,"R6B":0.85,"R9":0.85,"M1-5/R9":0.85}
#Convert the dictionary to an Excel spreadsheet
df5 = pd.DataFrame.from_dict(d, orient='index')
df5.to_excel('bob_dict.xlsx')
#populatethe dictionary from the excel spreadsheet
df2 = pd.read_excel("C:/Users/Pedro/Desktop/bob_dict.xlsx")
#Convert dtframe back to a dictionary
dictionary = df2.to_dict(orient='dict')
#Pass the dictionary as reference
b = df.filter(like ='Value').values
c = df.filter(like ='ZONE').replace(dictionary).astype(float).values
df['pro_cum'] = ((c * b).sum(axis =1))
</code></pre>
<p>When run this I get ValueError: could not convert R6B string to float.</p>
<pre><code>c = df.filter(like ='ZONE').replace(d).astype(float).values
</code></pre>
<p>but if I replace the zone values by the original dictionary it runs without errors.</p>
<p>Input : df</p>
<pre><code>HP ZONE Value ZONE1 Value1
3 R7A 0.7009 M1-4/R6B 0.00128
2 R6A 0.5842 M1-4/R7A 0.00009
7 M1-6/R10 0.1909 M1-4/R6A 0.73576
9 R6B 0.6919 PARK 0.03459
6 PARK 1.0400 M1-4/R6A 0.33002
9.3 M1-4/R6A 0.7878 PARK 0.59700
10.6 M1-4/R6B 0.0291 R6A 0.29621
11.9 R9 0.0084 M1-4 0.00058
13.2 M1-5/R10 0.0049 M1-4 0.65568
14.5 M1-4/R7A 0.0050 C5-3 0.00096
15.8 M1-5/R7-3 0.0189 C5-3 1.59327
17.1 M1-5/R9 0.3296 M1-4/R6B 0.43918
18.4 C5-3 0.5126 R6B 0.20835
19.7 M1-4 0.5126 PARK 0.22404
</code></pre>
| 3 | 1,171 |
Doing a jQuery Ajax submit, but it doesn't work
|
<p>I am trying to do a ajax post request, to also read a JSON response from the URL, but if I click the button nothing happens. What could be wrong with my HTML code or is it the Javascript? The function <code>submitRegister</code> is empty at the moment.</p>
<p>Javascript:</p>
<pre><code>$('#registerForm').submit(function(event){
event.preventDefault();
submitRegister();
});
function submitRegister(){
console.log("Test");
}
</code></pre>
<p>HTML</p>
<pre><code><div id="RegisterM" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Register</h4>
</div>
<div id='notification'>
</div>
<div class="modal-body">
<form role="form" id="registerForm">
<div class="form-group">
<label for="Username">Username:</label>
<input type="Username" class="form-control" id="username">
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="form-group">
<label for="confirmpwd">Confirm Password:</label>
<input type="confirmpwd" class="form-control" id="confirmpwd">
</div>
<button type="button" class="btn btn-default" id='register-submit'>Register</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</code></pre>
| 3 | 1,335 |
ABAddressBookGetPersonWithRecordID return nil
|
<p>My app stores the AddressBook recordIds of Contacts with the same name and later tries to present the addresses to the user to select the desired person. However, when I use the stored recordIds with ABAddressBookGetPersonWithRecordID, it returns nil.
The code below represents the code project - I have "copied" the code that later tries to retrieve the Contact immediately below the code that stores the recordIds.</p>
<pre><code>NSString *full = person.compositeName;
CFArrayRef contacts = ABAddressBookCopyPeopleWithName(addressBook, (__bridge CFStringRef)(full));
CFIndex nPeople = CFArrayGetCount(contacts);
if (nPeople)
{
NSMutableArray *rIds = [[NSMutableArray alloc] init];
int numberOfContactsMatchingName = (int)CFArrayGetCount(contacts);
if (numberOfContactsMatchingName>1)
{
for ( int i=0; i<numberOfContactsMatchingName; ++i)
{
ABRecordID thisId = ABRecordGetRecordID(CFArrayGetValueAtIndex(contacts, i));
NSNumber *rid = [NSNumber numberWithInteger:thisId];
FLOG(@"%d Matched, this ID = %@", numberOfContactsMatchingName, rid);
[rIds addObject:rid];
}
for (int i=0; i<rIds.count; ++i)
{
//contactRecord = ABAddressBookGetPersonWithRecordID(addressBook, (ABRecordID)recId);
ABRecordRef contactRecord;
contactRecord = ABAddressBookGetPersonWithRecordID(addressBook, rIds[i]);
if (contactRecord)
{
}
else
{
FLOG (@"Noone found with recordId %@", rIds[i]);
}
}
</code></pre>
<p>So, for example, I just ran this, and it found two Contacts in the address book with the same name - with ids 143 and 305, but when I then tried ABAddressBookGetPersonWithRecordID with ids 143 and 305, both returned nil.
What have I got wrong here?</p>
| 3 | 1,204 |
Complicated Query + Pagination Script
|
<p>Problem 1: Pagination on my script is not working. After 20 entries, it only shows the most recent 20 entries and doesn't split them into different pages. Code is below:</p>
<p>Problem 2: I am using the same pagination script for something else and over there it splits correctly but on the next page it shows the same results from page 1. I am using the same script except for the second script the:</p>
<pre><code> $query = "SELECT COUNT(*) as num FROM table where id =
'$uid' ORDER BY id DESC";
</code></pre>
<p>and the SQL for that is:</p>
<pre><code> $sql="SELECT table_one.field_id, table_constant.field_name,
table_one.field_2, table_one.field_3 FROM table_one LEFT
JOIN table_constant ON table_one.common_field
= table_constant.common_field WHERE table_constant.u_id = '$uid'";
</code></pre>
<p>Code: </p>
<pre><code> <?php
$tbl_name=""; //not using this since i am doing a union
$adjacents = 3;
$query = "SELECT COUNT(*) as num
from table_one LEFT JOIN table_constant on table_one.c_id
= table_constant.c_id
where table_constant.user_id = '$uid'
UNION
SELECT COUNT(*) as num
from table_two LEFT JOIN table_constant on table_two.c_id
= table_constant.c_id
where table_two.added_by = '$uid'
UNION
SELECT COUNT(*) as num
from table_three LEFT JOIN table_constant ON table_three.c_id
= table_constant.c_id
where table_constant.user_id = '$uid'
UNION
SELECT COUNT(*) as num
from table_four LEFT JOIN table_constant ON table_four.c_id
= table_constant.c_id
where table_constant.user_id = '$uid'
ORDER BY date_time_added DESC";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];
$targetpage = "page.php";
$limit = 20;
$page = $_GET['page'];
if($page)
$start = ($page - 1) * $limit; //first item to display on this page
else
$start = 0; //if no page var is given, set start to 0
$sql = "select table_one.field1, table_constant.field1,
table_one.field2, table_one.field3, table_one.field4,
table_one.field5, table_constant.c_id
from table_one LEFT JOIN table_constant on table_one.field1
= table_constant.c_id
where table_constant.user_id = '$uid'
UNION
select table_two.field1, table_constant.field1, table_two.field2,
table_two.field3, table_two.field4, table_two.field5, table_constant.c_id
from table_two LEFT JOIN table_constant on table_two.c_id
= table_constant.c_id
where table_two.added_by = '$uid'
UNION
select table_three.field1, table_constant.field1, table_three.field2,
table_three.field3, table_three.field4, table_three.field5,
table_constant.c_id
from table_three LEFT JOIN table_constant ON table_three.c_id
= table_constant.c_id
where table_constant.user_id = '$uid'
UNION
select table_four.field1, table_constant.field1, table_four.field2,
table_four.field3, table_four.field4, table_four.field5,
table_constant.c_id
from table_four LEFT JOIN table_constant ON table_four.c_id
= table_constant.c_id
where table_constant.user_id = '$uid'
ORDER BY date DESC LIMIT $start, $limit";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$result = mysql_query($sql);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
print("");
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$fields = $row['field']; //Table one Field 1
$fields2 = $row['field']; //Table Constant Field 1
$fields3 = $row['field'];// Table One field 4
$fields4 = $row['field'];//Table Constant Field 2
print("$fields<br>$fields2<br>$fields3<br>$fields4");
}
}
if(mysql_num_rows($result) < 1) {
echo "";
}
/* Setup page vars for display. */
if ($page == 0) $page = 1; //if no page var is given, default to 1.
//next page is page + 1
$lastpage = ceil($total_pages/$limit);
//lastpage is = total pages / items per page,
rounded up.
$lpm1 = $lastpage - 1; //last page minus 1
/*
Now we apply our rules and draw the pagination object.
We're actually saving the code to a variable in case we
want to draw it more than once.
*/
$pagination = "";
if($lastpage > 1)
{
$pagination .= "<div class=\"pagination\"></div>";
//previous button
if ($page > 1)
$pagination.= "";
else
$pagination.= "";
//pages
if ($lastpage < 7 + ($adjacents * 2))
//not enough pages to bother breaking it up
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter &nbsp</span>";
else
$pagination.= "<a id=\"numberhighlighter\" href=\"$targetpage?page=$counter\">$counter &nbsp</a>";
}
}
elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if($page < 1 + ($adjacents * 2))
{
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter &nbsp</span>";
else
$pagination.= "<a href=\"$targetpage?page=$counter\">$counter &nbsp </a>";
}
$pagination.= "...";
$pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
$pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
}
//in middle; hide some front and some back
elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
{
$pagination.= "<a href=\"$targetpage?page=1\">1</a>";
$pagination.= "<a href=\"$targetpage?page=2\">2</a>";
$pagination.= "...";
for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
}
$pagination.= "...";
$pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
$pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
}
//close to end; only hide early pages
else
{
$pagination.= "<a href=\"$targetpage?page=1\">1</a>";
$pagination.= "&nbsp &nbsp &nbsp<a href=\"$targetpage?page=2\">2&</a>";
$pagination.= "...";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
}
}
}
//next button
if ($page < $counter - 1)
$pagination.= "";
else
$pagination.= "";
}
?>
<div id="page">
<?php
print("$pagination");
?>
</code></pre>
<p>Thanks!</p>
| 3 | 3,808 |
Combining PCH, PDB, and Zi leads to puzzling C2859 compile error with VS2017
|
<p>I have a project that doesn't currently use precompiled headers, but I'd like to make it do so, as I've demonstrated that it leads to real compilation speed improvements in the project.</p>
<p>I'd also like to use <code>/Zi</code>, so I can capitalize on the parallel build benefits associated with <code>/Zf</code>, which is implied by <code>/Zi</code>.</p>
<p>I'm using the VS2017 C++ compiler, but I'm using a build system that is not Visual Studio, so answers relating to configuring VS aren't helpful. </p>
<p>What I'm finding is that I can set up the build to use precompiled headers just fine, or I can set it up to use <code>/Zi</code> just fine, but I can't seem to form a proper series of invocations to do both. When I try to do what I think is correct, I end up with error <code>C2958</code> stopping the build, and I don't see what I'm doing wrong.</p>
<p>I've built a toy project to demonstrate what I'm seeing. The <code>pch.hpp</code> header looks like this:</p>
<pre><code>#pragma once
#include <vector>
</code></pre>
<p>And we make a short mainline in <code>main.cpp</code>:</p>
<pre><code>int main() {
std::vector<int> xs = { 1, 2, 3 };
return xs.size();
}
</code></pre>
<p>Note that this is the complete file contents for <code>main.cpp</code>: I haven't omitted anything. I am intentionally <em>not</em> including <code>pch.hpp</code> here, because we are going to force inject it with <code>/Fi</code> later. The real project doesn't have include lines for a precompiled header in all the right places, and there would be thousands of files to update to do so. Note that the approach using <code>/Fi</code> does appear to work in the command lines below, and has the advantage that a forceincludes based mechanism can work with GCC style precompiled headers as well.</p>
<p>If we build things without <code>/Zi</code>, everything goes fine:</p>
<pre><code>cl /Fobuild\pch.obj /TP /nologo /EHsc /errorReport:none /MD /O2 /Oy- /Zc:rvalueCast /Zc:strictStrings /volatile:iso /Zc:__cplusplus /permissive- /std:c++17 /Zc:inline /c pch.hpp /Yc /Fpbuild\pch.pch
pch.hpp
cl /Fobuild\main.obj /c main.cpp /TP /nologo /EHsc /errorReport:none /MD /O2 /Oy- /Zc:rvalueCast /Zc:strictStrings /volatile:iso /Zc:__cplusplus /permissive- /std:c++17 /Zc:inline /FIpch.hpp /Yupch.hpp /Fpbuild/pch.pch
main.cpp
</code></pre>
<p>We find the files we would expect to find under the build directory:</p>
<pre><code>main.obj pch.obj pch.pch
</code></pre>
<p>However, if we try to use <code>/Fi</code> and <code>/Fd</code> to generate a per-file <code>.pdb</code> and control its name, it doesn't work at all:</p>
<p>We can compile the precompiled header that way OK:</p>
<pre><code>cl /Fobuild\pch.obj /TP /nologo /EHsc /errorReport:none /MD /O2 /Oy- /Zc:rvalueCast /Zc:strictStrings /volatile:iso /Zc:__cplusplus /permissive- /std:c++17 /Zc:inline /c pch.hpp /Yc /Fpbuild\pch.pch /Zi /Fdbuild\pch.pch.pdb
</code></pre>
<p>And things look OK in the <code>build</code> directory so far:</p>
<pre><code>pch.obj pch.pch pch.pch.pdb
</code></pre>
<p>But when we try to build the object file for main, it all falls apart:</p>
<pre><code>cl /Fobuild\main.obj /c main.cpp /TP /nologo /EHsc /errorReport:none /MD /O2 /Oy- /Zc:rvalueCast /Zc:strictStrings /volatile:iso /Zc:__cplusplus /permissive- /std:c++17 /Zc:inline /FIpch.hpp /Yupch.hpp /Fpbuild/pch.pch /Zi /Fdbuild\main.obj.pdb
main.cpp
main.cpp: error C2859: Z:\data\acm\src\example\build\main.obj.pdb is not the pdb file that was used when this precompiled header was created, recreate the precompiled header.
</code></pre>
<p>This is a very puzzling error, because the error message suggests that <code>main.obj.pdb</code> is being treated as an <em>input</em> somehow, but in fact it is intended to be the name of the <code>.pdb</code> file generated as <em>output</em>, per the value of the <code>/Fd</code> flag for the build of <code>main.obj</code>.</p>
<p>Googling hasn't resulted in much useful guidance, with a lot of hints about reconfiguring VS settings, which isn't really useful in the case of a build driven by something else.</p>
<p>I've also verified that my trickery with the <code>/Fi</code> of <code>pch.hpp</code> isn't the issue. If I update <code>main.cpp</code> to <code>#include pch.hpp</code> and remove the <code>/Fipch.hpp</code> from the compile line for <code>main.obj</code>, the same <code>C2859</code> error still occurs.</p>
<p>I realize there are a lot of flags to get right when using precompiled headers, among them the <code>/Yc</code> and <code>/Yu</code> and <code>/Fp</code> flags, but I think I've got those handled correctly.</p>
<p>Does anyone see where I've got things wrong?</p>
<p><strong>Edit 1 - Demonstrating that /Fd can name different PDB files</strong> </p>
<p>In response to the comment below, it doesn't actually appear to be the case that all targets must share the <code>/Fd</code> argument. Here is an example without the use of precompiled headers that demonstrates that:</p>
<p>Here, I've needed to add <code>common.cpp</code> and create a <code>main1.cpp</code> and <code>main2.cpp</code> which both link it:</p>
<p>The <code>common.hpp</code> header looks like:</p>
<pre><code>#pragma once
int common(int arg);
</code></pre>
<p>With a trivial implementation in <code>common.cpp</code>:</p>
<pre><code>#include "common.hpp"
int common(int arg) {
return arg + 42;
}
</code></pre>
<p>Then introduce two different mainlines:</p>
<p><code>main1.cpp</code>:</p>
<pre><code>#include "common.hpp"
int main() {
std::vector<int> xs = { 1, 2, 3 };
return common(xs.size());
}
</code></pre>
<p>And <code>main2.cpp</code>:</p>
<pre><code>#include "common.hpp"
int main() {
std::vector<int> xs = { 1, 2, 3, 4};
return common(xs.size());
}
</code></pre>
<p>Then compile all three object files. Note that we still have the <code>/Fipch.hpp</code> here to make the includes work right, but we aren't using any of the actual PCH machinery:</p>
<pre><code>cl /Fobuild\common.obj /c common.cpp /TP /nologo /EHsc /errorReport:none /MD /O2 /Oy- /Zc:rvalueCast /Zc:strictStrings /volatile:iso /Zc:__cplusplus /permissive- /std:c++17 /Zc:inline /FIpch.hpp /Zi /Fdbuild\common.obj.pdb
cl /Fobuild\main1.obj /c main1.cpp /TP /nologo /EHsc /errorReport:none /MD /O2 /Oy- /Zc:rvalueCast /Zc:strictStrings /volatile:iso /Zc:__cplusplus /permissive- /std:c++17 /Zc:inline /FIpch.hpp /Zi /Fdbuild\main1.obj.pdb
cl /Fobuild\main2.obj /c main2.cpp /TP /nologo /EHsc /errorReport:none /MD /O2 /Oy- /Zc:rvalueCast /Zc:strictStrings /volatile:iso /Zc:__cplusplus /permissive- /std:c++17 /Zc:inline /FIpch.hpp /Zi /Fdbuild\main2.obj.pdb
</code></pre>
<p>And we find what we would expect in the <code>build</code> directory:</p>
<pre><code>common.obj common.obj.pdb main1.obj main1.obj.pdb main2.obj main2.obj.pdb
</code></pre>
<p>Then we can go ahead and link:</p>
<pre><code>link /nologo /DEBUG /INCREMENTAL:NO /LARGEADDRESSAWARE /OPT:REF /OUT:build\main1.exe /PDB:build\main1.pdb build\common.obj build\main1.obj
link /nologo /DEBUG /INCREMENTAL:NO /LARGEADDRESSAWARE /OPT:REF /OUT:build\main2.exe /PDB:build\main2.pdb build\common.obj build\main2.obj
</code></pre>
<p>And we find that we get both executables and PDB files for those executables in the <code>build</code> directory:</p>
<pre><code>common.obj main1.exe main1.obj.pdb main2.exe main2.obj.pdb
common.obj.pdb main1.obj main1.pdb main2.obj main2.pdb
</code></pre>
| 3 | 2,841 |
How to keep the rails nested resource route url when model save fails?
|
<p><strong>Summary:</strong></p>
<p>I have a nested attribute. I go to route:</p>
<pre><code>/customers/:id/credit_cards/new
</code></pre>
<p>On the create action, save fails, code does </p>
<pre><code>render :new
</code></pre>
<p>This pushes the URL to:</p>
<pre><code>/credit_cards/new
</code></pre>
<p>How do I make sure the url stays with the customer route?</p>
<p><strong>Details:</strong></p>
<p>I want to use the following routes:</p>
<pre><code># Credit cards should be associated with a customer except
# potentially on initial creation:
resources :customers do
resources :credit_cards, only: [:index, :show, :new, :create, :edit, :update, :destroy, :show]
end
# Allow creating a credit card but selecting
resources :credit_cards, only: [:new, :create]
</code></pre>
<p>Basically a nested route for when a customer exists and a non-nested route for when I can create and assign a customer in the same view.</p>
<p>I have a single controller at</p>
<pre><code>app/controller/credit_cards_controller.rb
</code></pre>
<p>In the new and create action I check if I have a customer ID or not</p>
<pre><code>before_action :set_credit_card, only: [:show, :edit, :update, :destroy]
before_action :set_customer, only: [:index, :show, :create, :new, :edit, :update]
# GET /credit_cards/new
def new
@credit_card = if @customer
@customer.credit_cards.build rescue CreditCard.new
else
CreditCard.new
end
end
def create
@credit_card = CreditCard.new(credit_card_params)
respond_to do |format|
if @credit_card && @credit_card.save
format.html { redirect_to on_new_or_update_redirect_location, notice: 'Credit card was successfully created.' }
else
# HERE IS THE ISSUE: Figure out how to make sure the url stays as /customers/:id/credit_cards/new instead of /credit_cards/new
format.html { render :new }
end
end
end
</code></pre>
<p>When there is a validation failure, it re-renders the view, but pushes the URL to</p>
<pre><code>credit_cards/new
</code></pre>
<p>So I no longer am in the correct URL and customer_id is no longer a parameter. I assume if I can pass the customer_id it will do the right thing, but I have not found how to do that.</p>
| 3 | 1,029 |
UICollectionView How to implement horizontal align scrolling
|
<p>I have a <code>UICollection</code> which is implemented and works, however I cannot achieve the scrolling I want.</p>
<p>Here is a picture of my <code>UICollectionView</code>, I have resized the grey cell to <code>250</code> by <code>250</code>. </p>
<p><a href="https://i.stack.imgur.com/QHoWc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QHoWc.png" alt="enter image description here"></a></p>
<p>My issue is, when I start scrolling, this is what happens. </p>
<p>My cell first starts off on the far left, but notice what happens if I start to scroll horizontally.</p>
<p><a href="https://i.stack.imgur.com/AN1f4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AN1f4.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/aACAg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aACAg.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/Ygh2K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ygh2K.png" alt="enter image description here"></a></p>
<p>As you can see, the seam between the cells moves over to the left the more I scroll through the cells. This is not what I want. </p>
<p>What I want to achieve is: the cell is aligned to the center, and when you scroll, instead of the center of the cells moving to the left more and more, I want the cell to stay in the middle. Much like a <code>PageViewController</code> does except I want it to be <code>UICollectionViewCells</code>. </p>
<p>I have tried adding in the following code for example:</p>
<pre><code> - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
float pageWidth = 210;
float currentOffset = scrollView.contentOffset.x;
float targetOffset = targetContentOffset->x;
float newTargetOffset = 0;
if (targetOffset > currentOffset)
newTargetOffset = ceilf(currentOffset / pageWidth) * pageWidth;
else
newTargetOffset = floorf(currentOffset / pageWidth) * pageWidth;
if (newTargetOffset < 0)
newTargetOffset = 0;
else if (newTargetOffset > scrollView.contentSize.width)
newTargetOffset = scrollView.contentSize.width;
targetContentOffset->x = currentOffset;
[scrollView setContentOffset:CGPointMake(newTargetOffset, 0) animated:YES];
}
</code></pre>
<p>Which achieves the even scrolling, however I want to have <code>paging</code> enabled aswell as <code>bounce</code>. </p>
<p><a href="https://i.stack.imgur.com/ilEqE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ilEqE.png" alt="enter image description here"></a></p>
<p>Because if I enable <code>paging</code> and <code>bounce</code>, the scrolling is very smooth and elegant, however If I use the code up above the scrolling is very rugged and mechanical.</p>
<p>So How can I achieve even scrolling that is smooth like apples default scrolling, with my <code>UICollectionViewCell</code> being centred in the middle?</p>
<p>If I didn't explain the problem well enough, this post <a href="https://stackoverflow.com/questions/13228600/uicollectionview-align-logic-missing-in-horizontal-paging-scrollview">here</a> explains my problem except I am using one cell instead of three, and I want the scrolling to be smooth and bounce etc.</p>
| 3 | 1,147 |
Is there any way to stop and then start a discord.py bot without having to restart the whole py file?
|
<p>According to discord.py's discord server as well as their docs you'd need to restart the whole py file after using 'bot.close()' since it disconnects from their api. Unfortunately I'm trying to create a launcher and it wouldn't really be ideal to restart the whole launcher to restart the bot, does anyone know any 'hacky' ways of starting up a discord.py bot after using 'bot.close()'? it doesn't have to be pretty, just needs to remotely work. Any suggestions/tips would be greatly appreciated.</p>
<pre><code> @asyncSlot()
async def on_btnStartBot_clicked(self):
self.pushButton_startBot.setEnabled(False)
if self.isBotRunning == False:
self.statusbar.showMessage("Starting Bot...")
try:
if isinstance(cfg["bot"]["token"], str) and cfg["bot"]["token"] != "":
await bot.start(cfg["bot"]["token"])
elif isinstance(cfg["bot"]["token"], list) and not all(token == "" for token in cfg["bot"]["token"]):
def first_token():
for t in cfg["bot"]["token"]:
if t != "":
return t
await bot.start(first_token())
else:
terminal.log("CRITICAL", f"No token was provided in '{utils.config.CONFIG_PATH}'")
except Exception as e:
self.statusbar.showMessage(str(e))
else:
self.statusbar.showMessage("Stopping Bot...")
await bot.close()
self.plainTextEdit_botTerminal.clear()
while not bot.is_closed():
print('Not Yet Closed')
if bot.is_closed():
print("Closed")
self.statusbar.showMessage("Bot Has Been Stopped...")
self.pushButton_startBot.setText("Start Bot")
self.isBotRunning = False
await asyncio.sleep(1)
self.pushButton_startBot.setEnabled(True)
</code></pre>
| 3 | 1,096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.