id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_3500
|
require(['$api/models','$api/library#Library'], function(models,Library) {
console.log("country=" + models.session.country);
});
It is 'undefined'
What am I doing wrong?
I use api :
"api": "1.38.0"
"views": "1.18.1"
A: With very few exceptions, you need to load properties for them to be available on your Spotify object. This is done for performance reasons.
Load the country property on the session object like so:
require(['$api/models'], function(models) {
var session = models.session;
session.load("country").done(function() {
console.log("country=" + session.country);
});
});
The load function is documented briefly here.
| |
doc_3501
|
authContext.AcquireTokenAsync("https://database.windows.net/", certCred).Result;
I believe this is causing problems because the following steps result in the access token request timing out -
1). Start the application, request an access token in thread #1. Success
2). Increase my computer's time by one day, request an access token again in thread #1. The old token is deleted and the library attempts to acquire another token. Success
3). Increase my computer's time by one day, request an access token again in thread #2. This time the token is deleted and it tries to get another token by sending a request. Unfortunately the request ends up timing out after 30 seconds.
Interestingly, if I inspect the requests in Charles or Fiddler the request in #2 looks fine - it's a POST to the correct endpoint. #3 results in a CONNECT request to "https://login.microsoftonline.com/" with no relevant headers or body content. I've looked at the requests in the debugger and #3 seems to be created just like the request in #2.
I haven't been able to reproduce it in a smaller project unfortunately. Thanks for your time.
A: Turns out this is a problem with the way I'm using async/await, not a problem with the ADAL library. I'll close and create a new question.
| |
doc_3502
|
cudaEventRecord(start, 0);
/* creates 1D FFT plan */
cufftPlan1d(&plan, NX, CUFFT_C2C, BATCH);
/* executes FFT processes */
cufftExecC2C(plan, devPtr, devPtr, CUFFT_FORWARD);
cudaEventRecord(stop, 0);
cudaEventSynchronize(stop);
measures both the time required by the cuFFT to create a plan and the execution time.
How to measure only the execution time without including also the time needed for the creation of the plan?
A: The time needed to calculate the execution time without the plan creation time can be measured with the following snippet. Its just the rearranging your lines in the question.
cufftResult cuRet ;
/* creates 1D FFT plan */
cuRet = cufftPlan1d(&plan, NX, CUFFT_C2C, BATCH);
if (CUFFT_SUCCESS != cuRet)
{
printf ("Failed in plan creation\n") ;
return ;
}
cudaEventRecord(start, 0);
/* executes FFT processes */
cuRet = cufftExecC2C(plan, devPtr, devPtr, CUFFT_FORWARD);
if (CUFFT_SUCCESS != cuRet)
{
printf ("Failed in FFT execution\n") ;
return ;
}
if (cudaThreadSynchronize() != cudaSuccess)
{
printf("Failed to synchronize\n");
return;
}
cudaEventRecord(stop, 0);
cudaEventSynchronize(stop);
Do remember to check the return values of the cudaEventRecord and cudaEventSynchronize for errors which I have not shown but you can find the proper way to check the errors here.
| |
doc_3503
|
export async function main (event, context, callback) {
try {
let user, User
User = models.User
console.log('before insert',new Date())
user = await User.create({
name: event.request.userAttributes.name,
lastName: event.request.userAttributes.family_name,
email: event.request.userAttributes.email,
organizationId: event.request.userAttributes['custom:organizationId'],
roleId: event.request.userAttributes['custom:roleId']
})
console.log('after insert', new Date())
callback(null, event)
console.log('after callback',new Date())
} catch (e) {
console.error(e)
callback(e, event)
}
}
log
According to the logs as you can see this function respect the 5 seconds of execution, so why never ended? and why cognito make 3 attempts?
A: so finally i found that context.callbackWaitsForEmptyEventLoop (-- default true) must be set it to false for those cases where you want the Lambda function to return immediately after you call the callback, regardless of what's happening in the event loop, as i have my db connection object in a global variable, so thats is the reason of this behavior
| |
doc_3504
|
*
*Per Call
*Per Session
*Singleton
I know that in the case of option 1 the instance will be disposed of as soon as the service completes the call.
My question is what about the other 2 options? When and how are service instances that were created per session or as singleton disposed?
| |
doc_3505
|
select tos.source_system_order_id , tos.TOS_Date, tos.TOS_Final_Charge_Amt_Sum , oes.OES_Final_Charge_Amt_Sum
first query:
SELECT tos1.source_system_order_id,
tos1.tos_date,
SUM(tos1.tos_final_charge_amt_sum)
FROM (SELECT source_system_order_id,
source_system_cd,
To_char(billing_month_dt, 'YYYYMM') AS TOS_Date,
tos_final_charge_amt_sum
FROM tl_ov_stage
ORDER BY source_system_order_id) TOS1
GROUP BY tos1.source_system_order_id,
tos1.tos_date
2ndquery
SELECT OES1.source_system_order_id,
oes1.oes_date,
SUM(oes1.oes_final_charge_amt_sum) AS OES_Final_Charge_Amt_Sum
FROM (SELECT To_char("date", 'YYYYMM') AS OES_Date,
To_char("service order id") AS SOURCE_SYSTEM_ORDER_ID,
oes_final_charge_amt_sum
FROM v_ord_valuation_detail@prodr_link) OES1
GROUP BY OES1.source_system_order_id,
oes1.oes_date,
oes1.order_status
A: Try using CTE to combine the two select queries. I find CTE is more readable in such cases
with tos
as
(
SELECT tos1.source_system_order_id,
tos1.tos_date,
SUM(tos1.tos_final_charge_amt_sum)
FROM (SELECT source_system_order_id,
source_system_cd,
To_char(billing_month_dt, 'YYYYMM') AS TOS_Date,
tos_final_charge_amt_sum
FROM tl_ov_stage
ORDER BY source_system_order_id) TOS1
GROUP BY tos1.source_system_order_id,
tos1.tos_date
),
OES as
(
SELECT OES1.source_system_order_id,
oes1.oes_date,
SUM(oes1.oes_final_charge_amt_sum) AS OES_Final_Charge_Amt_Sum
FROM (SELECT To_char("date", 'YYYYMM') AS OES_Date,
To_char("service order id") AS SOURCE_SYSTEM_ORDER_ID,
oes_final_charge_amt_sum
FROM v_ord_valuation_detail@prodr_link) OES1
GROUP BY OES1.source_system_order_id,
oes1.oes_date,
oes1.order_status
)
select tos.source_system_order_id,
tos.TOS_Date,
tos.TOS_Final_Charge_Amt_Sum,
oes.OES_Final_Charge_Amt_Sum
from tos
inner join oes
on tos.source_system_order_id = oes.source_system_order_id
AND tos.tos_date = oes.oes_date -- Remove if this is not needed
| |
doc_3506
|
The code is
rectangle( frameSequence, Point( x-20, y+20), Point( x+20, y-20), Scalar( 0, 55, 255 ), +1, 4 );
A: frameSequence is already a type of cv::mat (presumably) that means it is already "saved" in terms of stored within your program.
If you want to "save" this to an external file (.jpg etc) then you will need to use imwrite:
imwrite( "../../images/rectangle.jpg",frameSequence);
In order to save only the rectangle to a mat you need to simply create a blank matrix and then pass that to rectangle(). THis will mean that the only data within this new matrix will be the coordinates of the rectangle.
cv::Mat newRectMat;
rectangle( newRectMat, Point( x-20, y+20), Point( x+20, y-20), Scalar( 0, 55, 255 ), +1, 4 );
A: just get a submatrix or roi. You may want a deep copy
cv::Mat frame;
//get the frame ...
cv::Mat subFrame = frame(cv::Rect(x, y, w, h).clone();
or
cv::Mat subFrame;
frame(cv::Rect(x, y, w, h)).copyTo(subFrame);
imwrite(filename, subframe);
| |
doc_3507
|
<head>
<meta http-equiv="Refresh" content="s" />
</head>
But it doesn't look like a good choice so I though that I can use javascript and read data from the file. Unfortunately this function works only once no matter what I change in .txt file and refresh the web, output is still the same (looks like it save previous data to some kind of the global variable).
function readTextFile()
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", 'text.txt', true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
On the left side at this picture there are data from the txt file (using php), and at the alert handler are data using javascript and submit button. These data should be the same.
So the question is: Can I read from a .txt file when its dynamicly change? And if so, how can I do it or what function use to do it? I don't know javascript very well.
I will be very grateful for help.
A: Using XHR to fetch records in a defined interval is not a good solution. I would recommend you to use JavaScript EventSource API. You can use it to receive text/event-stream at a defined interval. You can learn more about it here -
https://developer.mozilla.org/en-US/docs/Web/API/EventSource
For your application, you can do this -
JavaScript -
var evtSource = new EventSource('PATH_TO_PHP_FILE');
evtSource.onmessage = function(e) {
//e.data contains the fetched data
}
PHP Code -
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$myfile = fopen("FILE_NAME.txt", "r");
echo "data:". fread($myfile,filesize("FILE_NAME.txt"))."\n\n";
fclose($myfile);
flush();
?>
A: you need update your .txt file in some interval, for save changes,
after set attribute id="textarea"
//use jOuery
var interval = setInterval(function(){ myFunction() },5*60*1000); // 1000=1 second
function myFunction(){
$.get('server_address',{param1:1,param2:2},function(response){
//if is textarea or input
$('#textarea').val(response);
//if is block div, span or something else
//$('#textarea').text(response);
});
}
server_address - is page where you read file content, and print them .... if it is php, then file "write.php" with code like
<?php
echo(file_get_contents('some.txt'));
{param1:1,param2:2} - is object, with params, what you send to "server_address", like {action:'read',file:'some.txt'} or something other
response - is text what is print in page on "server_address"
| |
doc_3508
|
This project is using docker which python:3.9 image. I have got this error since 17,Aug.
2021-10-13 17:22:29.654 JSTGET504717 B899.9 sGoogleStackdriverMonitoring-UptimeChecks(https://cloud.google.com/monitoring) https://xxxx/
The request has been terminated because it has reached the maximum request timeout. To change this limit, see https://cloud.google.com/run/docs/configuring/request-timeout
and also this error occur on all my pages. However when I open my pages myself, I can see my pages. It means I can't see 504 error and I can only check that it happens from server log.
I added a line in admin.py at 17, Aug. I didn't think this line is no related with this error. Because this change is only effect in admin page. I had rollback my code before the error. Now I'm still can't fix this error.
Builded docker image is different size before after error. And Vulnerability has decreased. I think this is caused by some small change on python image. In this case, how can I solve this problem?
What I did
I changed docker image to python:3.8 and python:3.9.6-buster. I couldn't fix the error.
A: I solved this problem. I changed socket to port connection.
This is my settings.
uwsgi.ini
[uwsgi]
# this config will be loaded if nothing specific is specified
# load base config from below
ini = :base
# %d is the dir this configuration file is in
http = 127.0.0.1:8000
master = true
processes = 4
max-requests = 1000 ; Restart workers after this many requests
max-worker-lifetime = 3600 ; Restart workers after this many seconds
reload-on-rss = 512 ; Restart workers after this much resident memory
threaded-logger = true
[dev]
ini = :base
# socket (uwsgi) is not the same as http, nor http-socket
socket = :8001
[local]
ini = :base
http = :8000
# set the virtual env to use
home = /Users/you/envs/env
[base]
# chdir to the folder of this config file, plus app/website
chdir = %dapp/
# load the module from wsgi.py, it is a python path from
# the directory above.
module = website.wsgi:application
# allow anyone to connect to the socket. This is very permissive
chmod-socket = 666
nginx-app.conf
# the upstream component nginx needs to connect to
upstream django {
# server unix:/code/app.sock; # for a file socket
server 127.0.0.1:8000; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on, default_server indicates that this server block
# is the block to use if no blocks match the server_name
listen 8080;
# the domain name it will serve for
server_name MY_DOMAIN.COM; # substitute your machine's IP address or FQDN
charset utf-8;
# max upload size
client_max_body_size 10M; # adjust to taste
# set timeout
uwsgi_read_timeout 900;
proxy_read_timeout 900;
# Django media
location /media {
alias /code/app/media; # your Django project's media files - amend as required
}
location /static {
alias /code/app/static; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
include /code/uwsgi_params; # the uwsgi_params file you installed
}
}
| |
doc_3509
|
<IfModule rewrite_module>
RewriteEngine On
RewriteRule ^(.*)$ /Symfony/web/app_dev.php [QSA,L]
</IfModule>
When I enter http://localhost/hello/testingonly, what will it be redirected to?
EDIT:
I am currently trying to use Symfony Framework and trying out the online tutorials.
http://localhost/Symfony/web/app_dev.php/hello/testingonly actually displays a page that says "Hello $name" and $name in this case refers to "testingonly".
So if you visit this page http://localhost/Symfony/web/app_dev.php/hello/matthew, the page will say "Hi mathew".
The next thing I wanted to do was to remove Symfony/web/app_dev.php from the URL and I copied and paste the rewrite rule above and it just worked well.
What I wanted to know is how does it interpret which one is name parameter.
If I were to visit http://localhost/hello/mathew, and based on the rewrite rule, it should just be http://localhost/Symfony/web/app_dev.php and the parameter should be lost. But how come it managed to display "Hello mathew" ?
A: This rule redirect everything to /Symfony/web/app_dev.php.
^(.*)$ match everything (start, any char 0~n times, end)
/
RewriteRule ^(.*)$ /Symfony/web/app_dev.php [QSA,L]
/ /
[QSA] keep GET parameters in the URL /
/
[L] mean "if match, does not read next rules"
As you don't have he [R=301] flag, this redirection is transparent.
So :
*
*http://localhost/hello/testingonly redirect to :
http://localhost/Symfony/web/app_dev.php, but URL remains the same.
*http://localhost/hello/testingonly?foo=bar redirect to :
http://localhost/Symfony/web/app_dev.php?foo=bar, but URL remains the same.
| |
doc_3510
|
std::unique_ptr<std::vector<pqxx::result::tuple>>
filteredRowsPtr = getFilteredAssignmentRowsPtr(unfilteredRows);
std::vector<pqxx::result::tuple> filteredRows = *filteredRowsPtr;
for(int i = 0; i < filteredRows.size(); i++)
{
returnMap[occurenceStudentIdStr] = returnMap[occurenceStudentIdStr] + 1;
pqxx::result::tuple currRow = filteredRows[i];
for(int j = 0; j < currRow.size(); j++)
{
std::cout << "j = " << currRow[j] << endl;
}
}
filteredRowsPtr is a unique_ptr to a vector<pqxx::result::tuple> which is produced by the following method:
std::unique_ptr<std::vector<pqxx::result::tuple>>
CompletedExcersisesPerStudent::getFilteredAssignmentRowsPtr(pqxx::result unfilteredRows)
{
std::vector<pqxx::result::tuple> rowsFilteredOnGradePercentile = filter.getRowsWithValidGradePercentile(unfilteredRows);
std::vector<pqxx::result::tuple> filteredRows = filter.getRowsWithValidAssignmentTimes(rowsFilteredOnGradePercentile);
return std::make_unique<std::vector<pqxx::result::tuple>>(filteredRows);
}
The vector is filled (since calling size() on it returns a positive number) and I can iterate over it fine, but when I try to actually access the elements contained in the row using
currRow[j]
I get a segmentation fault.
However: When I replace the call to getFilteredAssignmentsRowPtr() with the following, thusly replacing the contents of that method:
std::vector<pqxx::result::tuple> rowsFilteredOnGradePercentile = filter.getRowsWithValidGradePercentile(unfilteredRows);
std::vector<pqxx::result::tuple> filteredRows = filter.getRowsWithValidAssignmentTimes(rowsFilteredOnGradePercentile);
The expected result is outputted without any segfaults.
What am I doing wrong? Thanks in advance!
A: Your error appears not reproducible (as you failed to provide a Minimal Verifiable Complete Example), but your design is flawed anyway: don't use a std::unique_ptr<std::vector>. std::vector already supports memory management, so you don't need to add that with a unique_ptr. IHMO, the correct design would be more like
std::vector<pqxx::result::tuple>
getFilteredAssignmentRowsPtr(pqxx::result unfilteredRows)
{
return filter.getRowsWithValidAssignmentTimes(
filter.getRowsWithValidGradePercentile(unfilteredRows));
}
auto filteredRows = getFilteredAssignmentRowsPtr(unfilteredRows);
for(int i = 0; i < filteredRows.size(); i++)
{
returnMap[occurenceStudentIdStr] = returnMap[occurenceStudentIdStr] + 1;
auto currRow = filteredRows[i];
for(int j = 0; j < currRow.size(); j++)
{
std::cout << "j = " << currRow[j] << endl;
}
}
A: I fixed the issue by changing getFilteredAssignmentRows to return a vector instead of a unique ptr like you suggested, as well as passing a reference to a pqxx::result to getFilteredAssignmentRows like so:
std::vector<pqxx::result::tuple> CompletedExcersisesPerStudent::getFilteredAssignmentRowsPtr(pqxx::result& unfilteredRows)
{
std::vector<pqxx::result::tuple> rowsFilteredOnGradePercentile = filter.getRowsWithValidGradePercentile(unfilteredRows);
return filter.getRowsWithValidAssignmentTimes(rowsFilteredOnGradePercentile);
}
This works since filter.getRowsWithValidGradePercentile is defined to take a reference to pqxx::result instead of a pqxx::result itself.
I must have accidentaly mis-read this.
Thanks a lot all the same!
| |
doc_3511
|
In theory it must be called only one time if i'm pressing the key without doing onKeyUp, but it is getting called a lot of times until I do keyUp.
What is wrong? this is the code:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
int factor = GameState.getInstance().getSpaceship().getSpeedFactorCorrespondence();
int movementRange = sh/factor;
switch (keyCode) {
case KeyEvent.KEYCODE_W:
Log.d("XX_KEYBOARD","onKeyDown KEYCODE_W "+keyCode);
GameState.getInstance().setJoyY(movementRange);
return true;
case KeyEvent.KEYCODE_A:
Log.d("XX_KEYBOARD","onKeyDown KEYCODE_A "+keyCode);
GameState.getInstance().setJoyX(-movementRange);
return true;
case KeyEvent.KEYCODE_S:
Log.d("XX_KEYBOARD","onKeyDown KEYCODE_S "+keyCode);
GameState.getInstance().setJoyY(-movementRange);
return true;
case KeyEvent.KEYCODE_D:
Log.d("XX_KEYBOARD","onKeyDown KEYCODE_D "+keyCode);
GameState.getInstance().setJoyX(movementRange);
return true;
case KeyEvent.KEYCODE_J:
Log.d("XX_KEYBOARD","onKeyDown KEYCODE_J "+keyCode);
touchX=sw/2;
touchY=sh/2;
LaserManager.getInstance().startLaserThread();
return true;
default:
Log.d("XX_KEYBOARD","onKeyDown default "+keyCode);
return super.onKeyDown(keyCode, event);
}
}
| |
doc_3512
|
package org.apache.camel.processor;
import org.apache.camel.AsyncCallback;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.processor.loadbalancer.LoadBalancerSupport;
public class CustomLoadBalanceTest extends ContextTestSupport {
protected MockEndpoint x;
protected MockEndpoint y;
protected MockEndpoint z;
@Override
protected void setUp() throws Exception {
super.setUp();
x = getMockEndpoint("mock:x");
y = getMockEndpoint("mock:y");
z = getMockEndpoint("mock:z");
}
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
// START SNIPPET: e1
from("direct:start")
// using our custom load balancer
.loadBalance(new MyLoadBalancer())
.to("mock:x", "mock:y", "mock:z");
// END SNIPPET: e1
}
};
}
public void testCustomLoadBalancer() throws Exception {
x.expectedBodiesReceived("x", "x", "x");
y.expectedBodiesReceived("y", "y");
z.expectedBodiesReceived("foo", "bar", "baz");
template.sendBody("direct:start", "x");
template.sendBody("direct:start", "y");
template.sendBody("direct:start", "foo");
template.sendBody("direct:start", "bar");
template.sendBody("direct:start", "y");
template.sendBody("direct:start", "x");
template.sendBody("direct:start", "x");
template.sendBody("direct:start", "baz");
assertMockEndpointsSatisfied();
}
// START SNIPPET: e2
public static class MyLoadBalancer extends LoadBalancerSupport {
public boolean process(Exchange exchange, AsyncCallback callback) {
String body = exchange.getIn().getBody(String.class);
try {
if ("x".equals(body)) {
getProcessors().get(0).process(exchange);
} else if ("y".equals(body)) {
getProcessors().get(1).process(exchange);
} else {
getProcessors().get(2).process(exchange);
}
} catch (Throwable e) {
exchange.setException(e);
}
callback.done(true);
return true;
}
}
// END SNIPPET: e2
}
This code is for performing a custom load balance using apache camel.
I want apache camel to listen to local host and to a port and balance the load among servers specified via IPaddress and port no. The server side has tomcat installed and it would listen to the request.
So how can i modify the below code to meet my requirements.
I am kinda new to camel.Any help would be very much appreciated.
Thank a ton in advance.
Cheers!!
A: Here's some route code to make the load balancer work
However, I've not checked the internals of your custom load balancing class, but that should be rather straight forward.
from("jetty://http://0.0.0.0:8080/test")
.loadBalance(new MyLoadBalancer())
.to("http://tcserver1:8080/hello","http://tcpserver2:8080/hello","http://tcpserver3:8080/hello");
| |
doc_3513
|
40+ views, and only one is able to help, isn't that question worth the upvote ? ;)
/edit
again I've some issues with socket programming in c#.
I've set up a little server with selfmade console ( richTextBox ) and it's listening for multiple connections.
well everything works fine except that if i close one of the connected clients, the programm will give me an async error and on the console it continuously writes a blank message from the client ( event:ClientReceivedHandler )
so can anyone help me finding the problem ??
my code :
SERVER - Form1.cs :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
namespace GameServer {
public partial class Form1 : Form {
// ### MAIN
public bool serverRunning = false;
public int serverListenPort = 6666;
static Listener l;
public Form1() {
InitializeComponent();
l = new Listener( serverListenPort );
l.SocketAccepted += new Listener.SocketAcceptedHandler( l_SocketAccepted );
}
void l_SocketAccepted( Socket e ) {
Client client = new Client( e );
client.Received += new Client.ClientReceivedHandler( client_Received );
client.Disconnected += new Client.ClientDisconnectedHandler( client_Disconnected );
Invoke( ( MethodInvoker )delegate {
dataGridViewConnections.Rows.Add( client.ID, client.EndPoint.ToString() );
consoleWrite( DateTime.Now + " - " + client.EndPoint + " connected to server.\n\n", Color.Lime );
} );
}
void client_Received( Client sender, byte[] data ) {
Invoke( ( MethodInvoker )delegate {
consoleWrite( DateTime.Now + "-" + sender.EndPoint + " :\n" + Encoding.Default.GetString( data ) + "\n\n", Color.White );;
} );
}
void client_Disconnected( Client sender ) {
Invoke( ( MethodInvoker )delegate {
for( int i = 0; i < dataGridViewConnections.Rows.Count; i++ ) {
if( dataGridViewConnections.Rows[i].Cells[0].Value.ToString() == sender.ID.ToString() ) {
dataGridViewConnections.Rows.RemoveAt( i );
consoleWrite( DateTime.Now + " - " + sender.EndPoint + " disconnected from server.\n\n", Color.OrangeRed );
break;
}
}
} );
}
private void checkBox1_Click(object sender, EventArgs e) {
checkBox1.Enabled = false;
if( !serverRunning ) {
consoleWrite( DateTime.Now + " " + markerSystem + "start\n", Color.White );
ServerStart();
checkBox1.Text = "Stop";
} else {
consoleWrite( DateTime.Now + " " + markerSystem + "stop\n", Color.White );
ServerStop();
checkBox1.Text = "Start";
}
checkBox1.Enabled = true;
}
private void ServerStart() {
if( !serverRunning ) {
consoleWrite( "* Starting server . . .\n", Color.Orange );
// Start Server
l.Start();
serverRunning = true;
consoleWrite( "* Server started !\n", Color.Lime );
consoleWrite("Listening on port " + serverListenPort + ".\n\n", Color.White );
} else {
consoleWrite( "* ERROR: Server already started !\n\n", Color.Red );
}
}
private void ServerStop() {
if( serverRunning ) {
consoleWrite( "* Stopping server . . .\n", Color.Orange );
// Stop Server
l.Stop();
serverRunning = false;
consoleWrite( "* Server stopped !\n\n", Color.Lime );
} else {
consoleWrite( "* ERROR: Server already stopped !\n\n", Color.Red );
}
}
private string markerSystem = "@System -> ";
private string marker = "-> ";
private void consoleWrite( string text, Color color ) {
consoleText.SelectionStart = consoleText.Text.Length;
consoleText.SelectionLength = 0;
consoleText.SelectionColor = color;
consoleText.AppendText( text );
}
}
}
SERVER - Listener.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace GameServer {
class Listener {
Socket s;
public bool Listening {
get;
private set;
}
public int Port {
get;
private set;
}
public Listener( int port ) {
Port = port;
s = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
}
public void Start() {
if( Listening ) {
return;
}
s.Bind( new IPEndPoint( 0, Port ) );
s.Listen(0);
s.BeginAccept( callback, null );
Listening = true;
}
public void Stop() {
if( !Listening ) {
return;
}
s.Close();
s.Dispose();
s = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
}
void callback( IAsyncResult ar ) {
try {
Socket s = this.s.EndAccept( ar );
if( SocketAccepted != null ) {
SocketAccepted( s );
}
this.s.BeginAccept( callback, null );
} catch( Exception ex ) {
MessageBox.Show( ex.Message );
}
}
public delegate void SocketAcceptedHandler( Socket e );
public event SocketAcceptedHandler SocketAccepted;
}
}
SERVER - Client.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace GameServer {
class Client {
public string ID {
get;
private set;
}
public IPEndPoint EndPoint {
get;
private set;
}
Socket sck;
public Client( Socket accepted ) {
sck = accepted;
ID = Guid.NewGuid().ToString();
EndPoint = ( IPEndPoint )sck.RemoteEndPoint;
sck.BeginReceive( new byte[] { 0 }, 0, 0, 0, callback, null );
}
void callback( IAsyncResult ar ) {
try {
sck.EndReceive( ar );
byte[] buf = new byte[8192];
int rec = sck.Receive( buf, buf.Length, 0 );
if( rec < buf.Length ) {
Array.Resize<byte>( ref buf, rec );
}
if( Received != null ) {
Received( this, buf );
}
sck.BeginReceive( new byte[] { 0 }, 0, 0, 0, callback, null );
} catch( Exception ex ) {
MessageBox.Show( ex.Message );
Close();
if( Disconnected != null ) {
Disconnected( this );
}
}
}
public void Close() {
sck.Close();
sck.Dispose();
}
public delegate void ClientReceivedHandler( Client sender, byte[] data );
public delegate void ClientDisconnectedHandler( Client sender );
public event ClientReceivedHandler Received;
public event ClientDisconnectedHandler Disconnected;
}
}
CLIENT - Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace GameClient {
public partial class Form1:Form {
Socket sck;
public Form1() {
InitializeComponent();
sck = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
sck.Connect( "127.0.0.1", 6666 );
}
private void button1_Click( object sender, EventArgs e ) {
int s = sck.Send( Encoding.Default.GetBytes( textBox1.Text ) );
if( s > 0 ) {
textBox1.Text = "";
}
}
private void button2_Click( object sender, EventArgs e ) {
sck.Close();
sck.Dispose();
}
}
}
i would be really really glad to make this server stable so i can start implementing multiplayer game server logics :D
thanks everyone who can help me out.
P.S. If anyone needs to see the problem in action, i can upload the VS project files or the .exe files of server and client.
UPDATE :
the first problem ( async error ) appears in the Listener.cs file in the try-catch. the messagebox in the catch section gives this text :
"IAsyncResult object was not returned from the corresponding asynchronous method. parameter : asyncResult"
this comes when the "ServerStop()" method is called.
the second problem is anywhere in the client_Received() method in the SERVER-Form1.cs.
it seems that it continuously receives blank data, so it outputs a blank message in the console/richTextBox
I'm not familiar with the socket-logic in c#, so i can't figure out where in the code the locig-error happens.
hope that anyone has found it.
EDIT :
project files in zip file
http://ace-acid.no-ip.org/GameServer/
(c)
A:
the first problem ( async error ) appears in the Listener.cs file in the try-catch. the messagebox in the catch section gives this text :
"IAsyncResult object was not returned from the corresponding
asynchronous method. parameter : asyncResult"
In Listener.cs - GameServer, This error may be safely ignored. I believe that ignoring the error will not cause problems during starting / stopping the socket. The problem is that you forgot to add Listening = false; at the end of Stop() so that the application can call Start() once again to start the socket. Otherwise, the socket will never start if stopped.
Example
public void Stop()
{
if (!Listening)
{
return;
}
s.Close();
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Listening = false; //Set Listening to False to start the socket again
}
Though setting Listening = false; will resolve restarting the socket, it will not stop you from getting the exception you mentioned above because the exception does not depend on Listening.
I've tried fixing this but it always told me that it was impossible to access the disposed object s(socket) so that I think that the exception is based on this line s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);.
The exception can be safely ignored anyways, I've ignored it and it worked perfectly. To ignore it, simply create a try/catch block getting the exception, if the exception message contained asyncResult then, ignore popping out a box with the exception.
Example
void callback(IAsyncResult ar)
{
try
{
Socket s = this.s.EndAccept(ar);
if (SocketAccepted != null)
{
SocketAccepted(s);
}
this.s.BeginAccept(callback, null);
}
catch (Exception ex)
{
if (!ex.Message.Contains("asyncResult")) //Proceed only if the exception does not contain asyncResult
{
MessageBox.Show(ex.Message);
}
}
}
it seems that it continuously receives blank data, so it outputs a blank message in the console/richTextBox
Yes, it will always receive a blank data since there's a connection. You can see this in the following screenshot
To solve this, you'll first need to check that the returned string using Encoding from the byte[] data is not blank. Then, you can write a new line in the console/richtextbox
Example
In Form1.cs - GameServer
Replace client_Received(Client sender, byte[] data) with the following code
void client_Received(Client sender, byte[] data)
{
if (Encoding.Default.GetString(data) != "") //Proceed only if data is not blank
{
Invoke((MethodInvoker)delegate
{
consoleWrite(DateTime.Now + "-" + sender.EndPoint + " :\n" + Encoding.Default.GetString(data) + "\n\n", Color.White); ;
});
}
}
}
After applying the fix, here's the output
There's another problem that you might have forgot to mention, under Connections tab, the list is never cleared even after the server disconnects. Simply call dataGridViewConnections.Rows.Clear(); to clear the connections list when ServerStop() is called.
Example
In Form1.cs - GameServer
Replace ServerStop() with the following code
private void ServerStop()
{
if (serverRunning)
{
consoleWrite("* Stopping server . . .\n", Color.Orange);
l.Stop();
serverRunning = false;
consoleWrite("* Server stopped !\n\n", Color.Lime);
dataGridViewConnections.Rows.Clear(); // Clear connections
}
else
{
consoleWrite("* ERROR: Server already stopped !\n\n", Color.Red);
}
}
That's all I could detect at the moment, I'll keep you updated if I find anything relevant.
Alternatively, you can find the project files that belongs to the namespace GameServer here
Thanks,
I hope you find this helpful :)
| |
doc_3514
|
I tried using OneDrive API, went through http://msdn.microsoft.com/en-us/library/dn631819.aspx, also http://isdk.dev.live.com/dev/isdk/Default.aspx but found nothing related to it.
Or maybe there is any other, undocumented way? Any ideas?
A: Unfortunately, we don't expose recycle bin functionality through the OneDrive developer APIs today. Any items you delete through the developer APIs, though, will wind up in the user's recycle bin.
| |
doc_3515
|
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[alertView show];
UILabel *lbladdblock=[[UILabel alloc] initWithFrame:CGRectMake(100,25,100,30)];
[alertView addSubview:lbladdblockname];
A: 1.include your .h file : UIAlertViewDelegate
2.please follow below implementation...
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[alertView show];
UILabel *lbladdblock=[[UILabel alloc] initWithFrame:CGRectMake(100,25,100,30)];
[alertView addSubview:lbladdblockname];
[self performSelector:@selector(dismiss:) withObject:alert1 afterDelay:1.0];
the dismiss method will be...
-(void)dismiss:(UIAlertView*)alert
{
[alert dismissWithClickedButtonIndex:0 animated:YES];
}
Or you wants to custom view than use
UIAlertView*testAlert=[[UIAlertView alloc] initWithFrame:CGRectMake(0, 0, 140, 140)];
UIButton*testButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[testButton setFrame:CGRectMake(20, 20, 40, 40)];
[testButton setTitle:@"Hello" forState:UIControlStateNormal];
[testButton addTarget:self action:@selector(someAction) forControlEvents:UIControlEventTouchUpInside];
[testAlert addSubview:testButton];
[testAlert show];
-(void)someAction
{
[testAlert removeFromSuperView];
}
A: If your class is subclass of UIAlertView then you can dismiss it by calling this method.
[alert dismissWithClickedButtonIndex:0 animated:TRUE];
you can use self in place of alert if you are using this method inside of class.
A: To work around this issue, you do like this:
define alertView in header, then:
- (void)viewDidLoad
{
alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
UILabel *lbladdblock=[[UILabel alloc] initWithFrame:CGRectMake(0,0,20,30)];
[lbladdblock setText:@"custom Message"];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:@"Dismiss!" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(dismissMe) forControlEvents:UIControlEventTouchUpInside];
[alertView addSubview:lbladdblock];
[alertView addSubview:btn];
[alertView show];
}
-(void)dismissMe
{
[alertview dismissWithClickedButtonIndex:0 animated:YES];
}
Also, AFAIK addSubView to alertView is impossible in ios7 so your code will work for previous versions only. See this thread.
Since you are not using built in features of UIAlertView (passing nil in all params)You should prefer some custom alert view. See the sample alert views in link.
Hope it helps!
| |
doc_3516
|
To give a concrete example: in our system one person, represented by an email address, can have multiple user ids that they may wish to operate under. Assume my email address is tregan@domain.com, and I have 3 user ids to choose from: treganCat, treganDog, treganMouse. When I hit a Controller action that is decorated with the [Authorize] attribute I first go through OpenIdConnect authentication, and one of the claims returned is an email address.
Using that email address, I want the application to prompt me to select the identity that I want to run under (treganDog, treganCat, or treganMouse).
From there, I want the application to take the user id that I selected, interrogate a database for the roles that go along with the selected user id, and load those roles as claims to my identity.
Finally, I want the application to send me on to my desired page (which is the protected Controller method that I originally attempted to visit).
Is this possible?
I'm using an Owin Startup class; the code below "works" except for the fictional line "var identityGuid = [return value from the prompt];" ("fictional" because it represents what I would like to occur, but in fact a series of redirects would be needed).
My example below uses the OnTicketReceived event, but that selection is arbitrary, I would be willing to do this in any event.
services.AddAuthentication(authenticationOptions =>
{
authenticationOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
authenticationOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(openIdConnectOptions =>
{
openIdConnectOptions.Authority = Configuration["PingOne:Authority"];
openIdConnectOptions.CallbackPath = "/Callback";
openIdConnectOptions.ClientId = Configuration["PingOne:ClientId"];
openIdConnectOptions.ClientSecret = Configuration["PingOne:ClientSecret"];
openIdConnectOptions.ResponseType = "code";
openIdConnectOptions.Events.OnTicketReceived = (ticketReceivedContext) =>
{
var emailClaim =
ticketReceivedContext.Principal.Claims.FirstOrDefault(o =>
o.Type == ClaimTypes.Email);
string emailAddress = emailClaim.Value;
//here is where I would like to prompt the user to select an identity based on the email address
//the selected identity is represented by a guid
var identityGuid = [return value from the prompt];
var roles = new MyRepository(myContext).GetRolesForUserId(identityGuid);
var claims = new List<Claim>();
foreach (string role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
ticketReceivedContext.Principal.AddIdentity(new ClaimsIdentity(claims));
return Task.CompletedTask;
};
});
A: This is impersonation where there is a real user and you need to identify the impersonated user after login.
You will need to complete the login first, return to the app and configure the principal. Then render a UI and receive the selected choice.
You then need your UI to call the back end and tell it to update claims in the auth cookie. Not sure if you'll get this to work though - the impersonated user may need separate storage - such as a second cookie.
This highlights that it can be useful to separate the token / credential the UI receives from the claims the back end works with.
I use the below design a lot for REST APIs that serve UIs directly - though it may be overkill for your solution:
https://authguidance.com/2017/10/03/api-tokens-claims/
A: I think what I want to do is simply not possible without either figuring out a way to do it inside PingOne or writing my own IdentityServer and taking care of the extra steps there.
I decided to instead write a custom middleware that fires after the Authentication middleware, as described in this SO question: In asp.net core, why is await context.ChallengeAsync() not working as expected?
| |
doc_3517
|
(c) 2019 Microsoft Corporation. All rights reserved.
(base) C:\Users\tanis>conda activate tf_gpu
C:\Users\tanis>python C:\Users\tanis\anaconda3\envs\tf_gpu\etc\keras\load_config.py 1>temp.txt
C:\Users\tanis>set /p KERAS_BACKEND= 0<temp.txt
C:\Users\tanis>del temp.txt
C:\Users\tanis>python -c "import keras" 1>nul 2>&1
C:\Users\tanis>if errorlevel 1 (
ver 1>nul
set "KERAS_BACKEND=theano"
python -c "import keras" 1>nul 2>&1
)
C:\Users\tanis>SET DISTUTILS_USE_SDK=1
C:\Users\tanis>SET MSSdk=1
C:\Users\tanis>SET "VS_VERSION=15.0"
C:\Users\tanis>SET "VS_MAJOR=15"
C:\Users\tanis>SET "VS_YEAR=2017"
C:\Users\tanis>set "MSYS2_ARG_CONV_EXCL=/AI;/AL;/OUT;/out"
C:\Users\tanis>set "MSYS2_ENV_CONV_EXCL=CL"
C:\Users\tanis>set "PY_VCRUNTIME_REDIST=\bin\vcruntime140.dll"
C:\Users\tanis>set "CXX=cl.exe"
C:\Users\tanis>set "CC=cl.exe"
C:\Users\tanis>set "VSINSTALLDIR="
C:\Users\tanis>for /F "usebackq tokens=*" %i in (`vswhere.exe -nologo -products * -version [15.0,16.0) -property installationPath`) do (set "VSINSTALLDIR=%i\" )
C:\Users\tanis>if not exist "" (for /F "usebackq tokens=*" %i in (`vswhere.exe -nologo -products * -requires Microsoft.VisualStudio.Component.VC.v141.x86.x64 -property installationPath`) do (set "VSINSTALLDIR=%i\" ) )
C:\Users\tanis>if not exist "" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\" )
C:\Users\tanis>if not exist "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\" )
C:\Users\tanis>if not exist "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\" )
C:\Users\tanis>if not exist "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\" )
C:\Users\tanis>IF NOT "" == "" (
set "INCLUDE=;"
set "LIB=;"
set "CMAKE_PREFIX_PATH=;"
)
C:\Users\tanis>call :GetWin10SdkDir
C:\Users\tanis>call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node 1>nul 2>&1
C:\Users\tanis>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node 1>nul 2>&1
C:\Users\tanis>if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE 1>nul 2>&1
C:\Users\tanis>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE 1>nul 2>&1
C:\Users\tanis>if errorlevel 1 exit /B 1
C:\Users\tanis>exit /B 0
C:\Users\tanis>for /F %i in ('dir /ON /B "\include\10.*"') DO (SET WindowsSDKVer=%~i )
The system cannot find the file specified.
C:\Users\tanis>if errorlevel 1 (echo "Didn't find any windows 10 SDK. I'm not sure if things will work, but let's try..." ) else (echo Windows SDK version found as: "" )
Windows SDK version found as: ""
C:\Users\tanis>IF "win-64" == "win-64" (
set "CMAKE_GEN=Visual Studio 15 2017 Win64"
set "BITS=64"
) else (
set "CMAKE_GEN=Visual Studio 15 2017"
set "BITS=32"
)
C:\Users\tanis>pushd C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>CALL "VC\Auxiliary\Build\vcvars64.bat" -vcvars_ver=14.16
The system cannot find the path specified.
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>popd
C:\Users\tanis>IF "" == "" SET "CMAKE_GENERATOR=Visual Studio 15 2017 Win64"
C:\Users\tanis>call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node 1>nul 2>&1
C:\Users\tanis>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node 1>nul 2>&1
C:\Users\tanis>if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE 1>nul 2>&1
C:\Users\tanis>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE 1>nul 2>&1
C:\Users\tanis>if errorlevel 1 exit /B 1
C:\Users\tanis>exit /B 0
(tf_gpu) C:\Users\tanis>
I have no clue how to fix this. When I go to load_config it already shows backend as TensorFlow. I have visual studio 2019 installed. Is there any way I can change SET "VS_YEAR=2017" to "VS_YEAR=2019" or do I need to install visual studio 2017? I have installed the TensorFlow GPU version and keras. I have also installed Cuda 11.0 drivers with cuDnn v8.0.
A: Follow the below mentioned steps to install tensorflow and keras in conda virtual environment on Windows OS.
(base) C:\Users\xyz>conda create -n tf_gpu
(base) C:\Users\xyz>conda env list
# conda environments:
#
base *C:\Users\xyz\Anaconda3
tf_gpu C:\Users\xyz\Anaconda3\envs\tf_gpu
(base) C:\Users\xyz>conda activate tf_gpu
(tf_gpu) C:\Users\xyz>pip install tensorflow
(tf_gpu) C:\Users\xyz>python
>>> import tensorflow
>>> form tensorflow import keras
| |
doc_3518
|
Here is the code:
expect(chrome.tabs.update).toHaveBeenCalledAfter(chrome.cookies.set);
But Typescript throws the following error:
error TS2345: Argument of type 'MockedFunction<(details: SetDetails,
callback?: (cookie: Cookie) => void) => void>' is not assignable to
parameter of type 'Mock<any, any>'.
Converting to any:
expect(chrome.tabs.update).toHaveBeenCalledAfter(chrome.cookies.set as any);
solves the problem and everything works as expected.
Is there a better way to make Typescript compile this code (without converting to any)?
| |
doc_3519
|
Entity Models.Servers' has a property
'Columns' with an unsupported type
When I created a simple ASP.NET application with VS2008, added the reference to SubSonic, created the connection string, and dragged the Active Record files over into the project everything went well. I could compile. Then I added a Domain Service class and referenced the Models namespace and created a GetServers Method with the following code:
public IQueryable<Server> GetServers() { return Server.All() }
Again I compiled and NO problems. I thought great now I will create a Silverlight project and do the same thing. I created a hosted SilverLight project and did the same thing within the web project.
This time a compile resulted in the error above. I'm not sure what the difference between the two projects except maybe for the default References that are loaded.
Thoughts?
A: This isn't an error thrown by SubSonic (which I think you know) and I'll guess that there's some kind of serialization happening here that doesn't like the interfaces we use. Either that or there's a namespace collision.
| |
doc_3520
| ||
doc_3521
|
function exe_map(){
alert(vid);
}
var timer = setTimeout(exe_map,10000);
}
this is my javascript code. i want alert(vid) to execute every 10000 milisec without using setIntrval and inner map_vehicle function.
thank you.
A:
i want alert(vid) execute every 10000 milisec without using
setIntrval and inner map_vehicle function.
Just call the same setTimeout again within exe_map
function map_vehicle(vid)
{
function exe_map()
{
alert(vid);
setTimeout(exe_map,10000);//observe this line
}
setTimeout(exe_map,10000);
}
Demo
function map_vehicle(vid)
{
function exe_map()
{
alert(vid);
setTimeout(exe_map,3000);//observe this line
}
setTimeout(exe_map,3000);
}
map_vehicle("10");
| |
doc_3522
|
(note: func and func2 is not typo)
struct S
{
void func2() {}
};
class O
{
public:
inline S* operator->() const;
private:
S* ses;
};
inline S* O::operator->() const
{
return ses;
}
int main()
{
O object;
object->func();
return 0;
}
there is a compile error reported:
D:\code>g++ operatorp.cpp -S -o operatorp.exe
operatorp.cpp: In function `int main()':
operatorp.cpp:27: error: 'struct S' has no member named 'func'
it seems that invoke the overloaded function of "operator->" is done during compile time? I'd added "-S" option for compile only.
A: In struct S you declared func2(), but in main,you try to call func().
try
int main()
{
O object;
object->func2();
return 0;
}
A: Yes, the compiler checks operators by it's result as any other function.
In this case if you had, for example,
S* foo() { ... }
(foo())->func();
the result would be the same.
A: In C++ language you cannot select a class member by name at run-time. Class member selection (by immediate member name) is always done at compile-time. There's no way around it.
If you want to implement member selection at run-time, the only thing you can use is operators .* and ->* (the former - non overloadable). However, these operators in their built-in form expect pointers-to-members as their right-hand operands. If you want to select something by name (as a string) you can overload ->* to make it take a different argument type, but in any case you'll have to implement the mapping from string to actual member manually. However, for member functions (as opposed to data members) this is usually pretty tricky.
A: Yes, it's treated like an ordinary function call, it's just called by an overloaded operator. The compiler checks everything is valid at compile time. C++ is not like dynamic languages where it waits until runtime to work out if p->mynonexistantfunction() is a valid name for a function or not, the compiler will reject the code at compile time if the function name does not exist.
In this case it looks like a typo, S has a function func2() but your code calls func().
A: object->func() is just syntactic sugar for object->operator->()->func() for user-defined types. Since O::operator->() yields an S*, this requires the existence of the method S::func() at compile time.
| |
doc_3523
|
.h file:
@interface Menu : NSObject
@property (strong) Forme *forme;
@property (strong) NSString *imageButtonName;
@property (strong) UIButton *button;
- (id) initWithClef:(int)clef hauteur:(int)hauteur largeur:(int)largeur posY:(int)posY posX:(int)posX alpha:(float)alpha imageButtonName:(NSString*)imageButtonName button:(UIButton*)button;
@end
.m file:
#import "Menu.h"
@implementation Menu
@synthesize forme = _forme;
@synthesize button = _button;
@synthesize imageButtonName = _imageButtonName;
- (id) initWithClef:(int)clef hauteur:(int)hauteur largeur:(int)largeur posY:(int)posY posX:(int)posX alpha:(float)alpha imageButtonName:(NSString *)imageButtonName button:(UIButton *)button
{
if ((self = [super init]))
{
NSLog (@"test2");
self.forme =[[Forme alloc]initWithClef:clef hauteur:hauteur largeur:largeur posY:posY posX:posX alpha:alpha];
self.button = button;
[button setFrame:CGRectMake(largeur, hauteur, posX, posY)];
[button setBackgroundImage:[UIImage imageNamed:imageButtonName] forState:UIControlStateNormal];
}
return self;
}
I want to automatically display created Buttons to the ViewController view. Is someone can help me please?
A: I think you should read some manuals and tutorials
Just add this button to viewcontroller's view in the init method:
[button setBackgroundImage:[UIImage imageNamed:imageButtonName] forState:UIControlStateNormal];
[self.view addSubview:button];
A: I think that simply adding a button to the view should do the trick,
call:
[self.view addSubview:button]
After the initialization of your button you still need to 'add' the button to the view with addSubview or else your button wont be drawn on the screen.
A: and add onView parameter to your initClef....
- (id) initWithClef:(int)clef hauteur:(int)hauteur largeur:(int)largeur posY:(int)posY posX:(int)posX alpha:(float)alpha imageButtonName:(NSString *)imageButtonName button:(UIButton *)button onView:(UIView *)view
{
if ((self = [super init]))
{
NSLog (@"test2");
// self.forme =[[Forme alloc]initWithClef:clef hauteur:hauteur largeur:largeur posY:posY posX:posX alpha:alpha];
self.button = button;
[button setFrame:CGRectMake(largeur, hauteur, posX, posY)];
[button setBackgroundImage:[UIImage imageNamed:imageButtonName] forState:UIControlStateNormal];
[view addSubview:button];
}
return self;
}
call it in viewController
Menu * menu2=[[Menu alloc] initWithClef:1 hauteur:30 largeur:30 posY:30 posX:30 alpha:1 imageButtonName:@"arti.png" button:b onView:self.view];
| |
doc_3524
|
I have an "HTML Form" with some fields which the user needs to fill out, there are a lot of input elements so I need a scroll bar for that. At the end of the form I have a submit button, when the user hits submit I want the complete form to scroll up and then a new div should show up which has all of the information the user has entered.
I don't want this div to be seen before the user clicks submit i.e the scroll function should only be limited to the "HTML form" and the user should not be able to scroll down to this section (The section should only be visible by clicking on the submit button)
How can I do that using jQuery or any other jQuery library?
A: You can use preventDefault to stop the form from submitting, find the values of each input, return them in a hidden container then slide back up to view:
JS
$("input[type=submit]").click(function(e){
e.preventDefault()
var input1 = $("#field1").val();
var input2 = $("#field2").val();
var input3 = $("#field3").val();
var input4 = $("#field4").val();
var input5 = $("#field5").val();
var input6 = $("#field6").val();
$(".info").html("field 1: " + input1 + " field 2: " + input2 + " field 3: " + input3 + " field 4: " + input4 + " field 5: " + input5 + " field 6: " + input6).show();
$("html,body").animate({ scrollTop: 0 });
});
HTML
<div class="info"></div>
<form>
<input type="text" id="field1"/>
<input type="text" id="field2"/>
<input type="text" id="field3"/>
<input type="text" id="field4"/>
<input type="text" id="field5"/>
<input type="text" id="field6"/>
<input type="submit"/>
</form>
FIDDLE
UPDATE
Here is a new fiddle that hides the form after submit, displays the info with a "edit" button and shows the form again to edit:
NEW FIDDLE
A: Well, to start with something, the jQuery you want to use to scroll up/down and hide/show a div when clicking on the submit button is the following:
jQuery
$(document).ready(function(){
$(function(){
$('a[href*=#]:not([href=#])').click(function(){
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname){
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if(target.length){
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
$(".hidden").hide(); // Hide all elements you want to be hidden until you send the form
$(".submit").click(function(){
$(".hidden").fadeIn(400); // Show hidden items when click on submit button. You may also use show() function if you don't want it to fade in. Change the 400 for the time you want it to take to fade in (in miliseconds). 400 is default so you may just delete the 400.
});
});
This is the supposed HTML you want to use
HTML
<div class="hidden">
<!-- The div you want to hide and then put all the sent info to show when click on sent -->
</div>
<div class="scroll-section">
<form method="post" action="" id="form">
<!-- Your form here -->
<a href="#form"><input type="submit" value="Submit info" class="submit"/></a>
</form>
</div>
A recommendation I can give you with CSS if you want to make the hidden div cover everything and be on top is that you set z-index to a high value and position:fixed; height:100%; width:100%;. I usually set a div like that and add a table in it and set it as wide and tall as the div so that I can style one td to look like a div in the center of the screen.
EDIT:
I forgot to explain you the scroll thing, you see that I covered the submit button with an a tag that points to an id="form".. basically, the jQuery up there works with any given ID. So just set a link pointing to the ID of the element and there you go.
Also, in CSS:
.scroll-section {
overflow-y:scroll;
height:600px; // Give it a height
}
| |
doc_3525
|
In ViewModel:
...
private val _eventDataState = MutableStateFlow<EventDataState>(EventDataState.Loading)
val eventDataState: StateFlow<EventDataState> = _eventDataState
...
In Fragment:
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
...
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.eventDataState.collect { eventDataState ->
when (eventDataState) {
is EventDataState.Loading -> {}
is EventDataState.Success -> onEventDataUpdated(data = eventDataState)
is EventDataState.Deleted -> onEventDataDeleted()
}
}
}
}
viewModel.getEventData()
}
...
All seems to work well:
2022-04-15 17:57:20.352 5251-5251/ ... E/EVENT: Data state: Success(...)
But when I switch to another Fragment through Activity's SupportFragmentManager and then hit Back button I get multiple responses from StateFlow:
2022-04-15 17:57:30.358 5251-5251/ ... E/EVENT: Data state: Success(...)
2022-04-15 17:57:30.362 5251-5251/ ... E/EVENT: Data state: Success(...)
So the more times I switch to another Fragment and back - the more copies of response I get from StateFlow (this is not initial StateFlow value).
My guess is that when another Fragment are called the first one destroys its view but subscription to Flow is still exists, and when returning back from another Fragment the first one calls its onViewCreated and so creating another copy of subscription to this Flow. Nevertheless I was unable to find any solution to my case on stackoverflow or any other resources.
What have I missed?
A: You should use viewLifecycleOwner.lifecycleScope.launch in fragments. viewLifecycleOwner.lifecycleScope and all its jobs will be cancelled when the view is destroyed.
| |
doc_3526
|
I thought this would output the last 8 characters but the output seems to be blank
foreach($line in $Texfile)
{
$line[-8..-1]-join ''
}
A: There's any number of ways to do this, but I opted to pipe Get-Content to ForEach-Object.
Get-Content -Path <Path\to\file.txt> | ForEach-Object {
$_.Substring($_.Length - 8)
}
In your example, you'd use $Line in place of $_ and not pipe to ForEach-Object, and instead, use the Foreach language construct as you've done.
Foreach ($Line in $TextFile) {
$Line.Substring($Line.Length - 8)
}
A: Try this:
foreach ($Line in $Texfile) {
$Line.Remove(0, ($Line.Length - 8))
}
A: That works fine. You misspelled $textfile though, with no "t". Maybe that's why you had no output.
Or (-join on the left side):
'1234567890
1234567890
1234567890' | set-content file
$textfile = cat file
foreach($line in $textfile)
{
-join $line[-8..-1]
}
34567890
34567890
34567890
| |
doc_3527
|
Firebase Database
The user can then add more posts, of which are saved to the database then displayed on a ListView.
My Code
final DatabaseReference room = FirebaseDatabase.getInstance().getReference().getRoot();
chatRoomAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, chatList);
lvChatRoom.setAdapter(chatRoomAdapter);
btnAddChatRoomMa.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
strChatRoomName = etChatRoom.getText().toString();
etChatRoom.setText("");
Map<String, Object> chatMap = new HashMap<>();
chatMap.put(strChatRoomName + " -TYPEA", "");
room.updateChildren(chatMap);
}
});
room.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator iterator = dataSnapshot.getChildren().iterator();
Set<String> set = new HashSet<>();
while (iterator.hasNext()) {
set.add(((DataSnapshot) iterator.next()).getKey());
}
chatList.clear();
chatList.addAll(set);
chatRoomAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
I only want to show for instance, TYPEA (on the database), without displaying the rest. How can I achieve this?
A: If you want to display only the value of the property TYPEA, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("fruit-TYPEA");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String fruitTYPEA = dataSnapshot.getValue(String.class);
Log.d("TAG", fruitTYPEA);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The output will be: orange.
| |
doc_3528
|
order
o1
o2
o3
I have orderItem collection :
OrderItem orderId
oitem1 o1
oitem2 o1
oitem3 o1
oitem4 o2
oitem5 o3
now I am selecting orders with line, but how do I skip/avoid/ignore the child collection from LINQ
I don't want orderItems with my orders .
| |
doc_3529
|
And I've never used cmd other than to check my ip.
My problem is I don't know where to save the files, and how to run them from cmd with node. The tutorials I've found seem to assume I should know all this without explaining it, and jumps straight to the code.
So, how do I actually run something in node? This is what I've done sofar:
*
*Downloaded the windows installer from nodejs.org.
*Installed nodejs in the default directory: C:\Program Files (x86)\nodejs.
*Made sure I have Python and Microsoft Visual Studio.
And this is where I'm stuck, how do I test this?
*
*It wont let me save files in the nodejs directory (even as
administrator). Where do I save my files?
*What would be the correct command and path in cmd to start node and run my files?
A: Save your files wherever you want and run them from the cmd prompt as node yourfile.js.
| |
doc_3530
|
now the images that are put on this field should be able to be dragged around everywhere in the div field and I cant quite figure out how to do this while also making it so you can put more images in the div.
const insertImage = (line) => {
var container = document.getElementById("field");
var childElemnent = document.createElement("img");
var div = document.createElement('div');
childElemnent.src = line.src
childElemnent.id = line.alt
childElemnent.tabindex = 1
childElemnent.onkeypress = function() { removeAddedElement(this.id) }
container.appendChild(childElemnent);
document.body.veld.appendChild(div);
}
A: i found a solution
const insertImage = (line) => {
var container = document.getElementById("veld");
var childElemnent = document.createElement("img");
var div = document.createElement('div');
childElemnent.src = line.src
childElemnent.id = line.alt
childElemnent.className = line.alt
// childElemnent.tabindex = 1
container.appendChild(childElemnent);
$( ".Matje" ).draggable()
}
| |
doc_3531
|
for i in range(1000):
df2=df.sample(n=size_of_N, replace=False,random_state=i)
treatment_group=df2.iloc[:size_of_n]
control_group=df2.iloc[size_of_n:]
significance_list=[]
for column in list_of_columns:
significance=mannwhitneyu(treatment_group[column],
control_group[column])
significance_list.append(significance)
min_p_value = min(significance_list)
min_p_value_list.append(min_p_value)
but the code breaks in the line significance=mannwhitneyu(treatment_group[column],control_group[column]) with the following error message "ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''"
I've checked and all my data types are numeric and non-null, with no commas or percentage signs or anything.
| |
doc_3532
|
A simple example like I use libtorch, the torch/torch.h header file contains all headers the package needed, and don't need specifying any other related header. Just like the pictures below:
The completion works well, but after I use space select the completion, the unwanted header torch/nn/module.h> was added automatically.
I want to get a configure to disable automatically adding header files like this.
Any reply will be appreciated!
A: I stumbled upon this problem when I switched from libclang based YCM to clangd based. The guys on the community chat helped to figure out the solution: you can add the following line into your ~/.vimrc file:
let g:ycm_clangd_args=['--header-insertion=never']
Read :help g:ycm_clangd_args and ./clangd --help-list for details on these options. It turns out there are plenty of cool configuration tweaks for clangd.
| |
doc_3533
|
(TF31002: Unable to connect to this Team Foundation Server).
The Server's IP is working, so the server is online, I've tried things such as turning off Firewall, starting VS as Administrator and it doesn't seem to work.
It's the first time I'm working with TFS, am I missing something?
Thanks in advance.
A: Try connecting via telnet, e.g telnet yourserver 8080 at the command prompt: this checks if the client has TCP/IP connectivity. Telnet client is not installed by default in Windows, so you may have to turn the corresponding Windows Feature on.
If previous check passes, open the Home page in a browser, e.g. http://yourserver:8080/tfs. If the browser is not configured for Integrated authentication, you will receive a prompt for credential. Insert a valid user and the home page should appear.
Consider which credential you are using: if TFS server is in workgroup, use an account defined on the TFS server; if TFS server is joined to Active Directory, use an account from the same domain. In any case the account must be part of TFS Valid Users group.
| |
doc_3534
|
captcha.php
<?php
session_start();
$string = '';
for ($i = 0; $i < 5; $i++) {
$string .= chr(rand(97, 122));
}
$_SESSION['random_number'] = $string;
$dir = 'fonts/';
$image = imagecreatetruecolor(165, 50);
// random number 1 or 2
$num = rand(1,2);
if($num==1)
{
$font = "PT_SANS-BOLD_1.TTF"; // font style
}
else
{
$font = "PT_SANS-ITALIC_1.TTF";// font style
}
// random number 1 or 2
$num2 = rand(1,2);
if($num2==1)
{
$color = imagecolorallocate($image, 113, 193, 217);// color
}
else
{
$color = imagecolorallocate($image, 163, 197, 82);// color
}
$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, $dir.$font, $_SESSION['random_number']);
header("Content-type: image/png");
imagepng($image);
?>
in html file
<img src="<?= base_url();?>files/captcha.php" alt="" id="captcha" />
A: This is not an answer to your question but alternative you could opt for.
So many captcha scripts are already available may be you can use some of that instead of coding it again.
Check this
If you do go for this option then do make sure that fonts are placed in right places.
| |
doc_3535
|
anywhere in video then popups open automatic or how to click on X icon to close banner ad.
.iframe{
width: 100%;
float: left;
margin-top: 5px;
}
<div class="iframe">
<iframe width="1000" height="600" src="https://www.youtube.com/embed/Sb_60g3u1LU" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe>
</div>
I am using other third party websites to host videos like vidzi.tv & openload.co and these sites are full with pop ups and banner ads in video player.
A: I used sandbox function in this code on my Streaming Site where i Embed 3rd Party iframe and they also have sandbox protection check but for that iv'e added removeAttribute in my JS so if you change src of the iframe from some other button you can click this button to add sandbox attribute to your iframe or you can also add the click function in your code where you get your iframe successfully.
//JS
window.onload = function(){
var button = document.getElementsByName("sandbox")[0]
var iframe = document.getElementsByName("framez")[0]
button.addEventListener('click',sndbx,false);
function sndbx(){
var nibba = document.getElementById("framez").src;
if(iframe.sandbox == 'allow-forms allow-pointer-lock allow-same-origin allow-scripts allow-top-navigation'){
document.getElementById("framez").removeAttribute("sandbox");
}
frames['framez'].location.href=nibba;
iframe.sandbox = 'allow-forms allow-pointer-lock allow-same-origin allow-scripts allow-top-navigation';
}
}
<!--HTML-->
<button name="sandbox">SandBox</button>
<iframe name="framez" id="framez" src="YOUR_SOURCE" allowfullscreen="true"></iframe>
A: You can add sandbox attribute in your iframe. Only the values you add to the attribute will be allowed. Any value you do not add in the sandbox attribute will not be allowed by browser.
Sandbox attribute has following values:
allow-forms
allow-pointer-lock
allow-popups
allow-same-origin
allow-scripts
allow-top-navigation
I have modified your code to include sandbox option, but have NOT added allow-popups, so popups will not be allowed in this iframe.
<div class="iframe">
<iframe sandbox = "allow-forms allow-pointer-lock allow-same-origin allow-scripts allow-top-navigation" width="1000" height="600" src="https://www.youtube.com/embed/Sb_60g3u1LU" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe>
</div>
You can find more about sandbox attribute here. Please note that this attribute is new in HTML5.
| |
doc_3536
|
I was recently introduced to localstack and started thinking maybe a local S3 bucket would serve for this. I have a configuration where builds (yarn build) are automatically published to an s3 bucket running on localstack. But when I try to load the root config index.html from the bucket I get the following JS error:
Unable to resolve bare specifier '@myorg/root-config'
I can access the JS files for each parcel and the root-config just fine via curl, so I suppose this would be a problem with any http server used in the same way. I can flip the root config to use the standard webpack-dev-server instead (on port 9000) and it works okay. So I'm guessing there's a difference between how a production build resolves these modules vs. the local build.
Has anyone tried something like this and got it working?
A: I had a similar issue that I got to work with http-server by adding each child .js file to a sub-folder in the root-config directory and launching the web server at the root-config directory level.
"imports": {
"@myorg/root-config": "http://someserver.com/root-config.js",
"@myorg/moduleA": "http://someserver.com/modules/moduleA/myorg-modulea.js",
"@myorg/moduleB": "http://someserver.com/modules/moduleB/myorg-moduleb.js",
"@myorg/moduleC": "http://someserver.com/modules/moduleC/myorg-modulec.js",
}
Note: By default, Single-SPA has an "isLocal" check before the current import mappings. You'll need to remove this if using a production build or it won't load the correct mappings.
<% if (isLocal) { %>
In my case, I was using localhost instead of someserver so I could navigate into the 'repository' folder and run npx http-server to get everything to run correctly.
I was hung up on this for a little while so hopefully this leads you in the right direction.
A: For the record, after trying several approaches to hosting a repository as described above, I found the unresolved bare specifier problem went away. So I have to chalk that up as just not having the right URL in the import map. Measure twice, cut once.
| |
doc_3537
|
Does this make sense?
Sorry I can't provide any code because I dont know where to start.
A: in iOS6, a new UITableViewDelegate function was introduced that does just this:
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath;
You can use this something like this:
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([tableView.indexPathsForVisibleRows indexOfObject:indexPath] == NSNotFound)
{
// This indeed is an indexPath no longer visible
// Do something to this non-visible cell...
}
}
A: If you are using UITableView properly and dequeueing cells using the method...
[tableView dequeueCellWithReuseIdentifier:@"blah" indexPath:indexPath];
then this will already be happening.
The tableview manages which cells are on screen. If you have 1000 rows in your table but only 10 rows on screen at a time then you will only ever have 10 cell objects in memory as those ten are reused for the rows that come onto the screen when others are scrolled off the screen.
| |
doc_3538
|
Here is my template:
{% extends 'base/formbase.html' %}
{% block title %}Login{% endblock title %}
{% block menuid %}menu-login{% endblock menuid %}
{% block submitname %}Login{% endblock submitname %}
{% block extra %}
<div class="alert alert-danger">
<a href="{% url 'password_reset' %}"> Forgot Your Password? </a>
</div>
<div class="alert alert-secondary">
Don't have an account? <a href="{% url 'signup' %}"> Sign Up! </a>
</div>
{% endblock extra %}
base/formbase.html:
{% extends 'base/base.html' %}
{% load crispy_forms_tags %}
{% block body %}
<div class="row justify-content-center">
<div class="col-6">
<div class="card">
<div class="card-body">
{% block form %}
<h2>{% block title %}{% endblock title %}</h2>
<form method="post" novalidate>
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-primary">{% block submitname %}{% endblock submitname %}
</button>
</form>
{% endblock form %}
</div>
{% block extra %}{% endblock extra %}
</div>
</div>
</div>
{% endblock body %}
base/base.html:
<!DOCTYPE html>
{% load base_extra %}
<html lang="en">
<head>
{% settings gamename "GAME_NAME" %}
<meta charset="UTF-8">
<title>{{ gamename }} - {% block title %}{% endblock title %}</title>
{% block head %}{% endblock head %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
{% settings debug "DEBUG" %}
{% if debug %}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/latest/css/bootstrap.css">
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://unpkg.com/@popperjs/core/dist/umd/popper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/latest/js/bootstrap.js"></script>
{% else %}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://unpkg.com/@popperjs/core/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/latest/js/bootstrap.min.js"></script>
{% endif %}
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="{% url 'index' %}">{{ gamename }}</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item" id="menu-home">
<a class="nav-link" href="{% url 'index' %}">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item" id="menu-gamelist">
<a class="nav-link" href="{% url 'game:game_list' %}">Game List</a>
</li>
<li class="nav-item" id="menu-leaderboard">
<a class="nav-link" href="{% url 'user_list' %}">Leaderboard</a>
</li>
{% if request.user.is_staff %}
<li class="nav-item" id="menu-admin">
<a class="nav-link" href="{% url 'admin:index' %}">Admin</a>
</li>
{% endif %}
</ul>
<!--
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
-->
<ul class="navbar-nav ml-auto">
{% if request.user.is_authenticated %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
{{ request.user }}
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{% url 'user' user.pk %}">Profile</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="{% url 'logout' %}">Log out</a>
</div>
</li>
<li class="nav-item">
<div class="nav-link">${{ request.user.gameinfo.money }}</div>
</li>
{% else %}
<li class="nav-item" id="menu-signup">
<a class="nav-link" href="{% url 'signup' %}">Sign Up</a>
</li>
<li class="nav-item" id="menu-login">
<a class="nav-link" href="{% url 'login' %}">Log In</a>
</li>
{% endif %}
</ul>
</div>
</nav>
<div class="mx-3 mt-2">
<script>
try {
document.getElementById("{% block menuid %} {% endblock menuid %}").classList.add("active");
}
catch {}
</script>
{% block body %}
{% endblock body %}
</div>
</body>
</html>
Adding the @csrf_protect decorator does not solve the problem.
A: This may occur if you have CSRF_COOKIE_SECURE = True explanation in the docs Or if you have CSRF_COOKIE_HTTPONLY = True explanation or if you wish to just disable the csrf token you can add the @csrf_exempt decorator to the view
| |
doc_3539
|
how to avoid it? Or any other way to get har file from pcap file which containing https?
Thank you.
A: HTTPS is HTTP inside a TLS tunnel. If you look at the pcap all you can see is the encrypted traffic inside the TLS tunnel but you cannot extract the HTTP requests from it to create the HAR because you would need the decrypted traffic for this.
| |
doc_3540
|
func createPhotoURL() -> URL {
let fileName = "tempImage_wb.jpg"
let documentsDirectories = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = documentsDirectories.first!
let pdfPageURL = documentDirectory.appendingPathComponent("\(fileName)")
return pdfPageURL
}
When I call the function I get the full length URL:
let imageURL = createPhotoURL() // CORRECT URL FOR FILE UPLAOD
print("imageURL: \(imageURL)")
Console:
file:///var/mobile/Containers/Data/Application/CDDE2FED-5AAB-4960-9ACF-33E7B42D05AE/Documents/tempImage_wb.jpg
Save above URL to local folder and the retrieve it:
UserDefaults.standard.set(imageURL, forKey: "URL_IMAGE")
guard let retrievedURL = UserDefaults.standard.string(forKey: "URL_IMAGE") else{return}
print("retrievedURL: \(retrievedURL)")
Console:
retrievedURL: ~/Documents/tempImage_wb.jpg
A: To answer your question, use UserDefaults.standard.url instead of UserDefaults.standard.string
guard let retrievedURL = UserDefaults.standard.url(forKey: "URL_IMAGE") else{return}
But this will work only if you save the path and retrieve it in the same session. If you use the above code and run the app multiple times, you will get non-truncated urls (like you want). But if you check it properly you can see you are actually getting different urls in different sessions.
So you shouldn't save it as a URL, instead you should save it as string. For that you can use absoluteString property of URL
let imageURL = createPhotoURL()
print("imageURL: \(imageURL)")
UserDefaults.standard.set(imageURL.absoluteString, forKey: "URL_IMAGE")
And to retrieve, you will first retrieve the saved string from UserDefaults and then convert that into a URL
if let urlString = UserDefaults.standard.string(forKey: "URL_IMAGE"),
let retrievedURL = URL(string: urlString) {
print("retrievedURL: \(retrievedURL)")
}
| |
doc_3541
|
When I enter a codespace, either on the web or from VSCode the dotfiles have no effect. No error message either.
Here's what I've done
*
*Created a public dotfiles repo on GitHub, containing .zshrc and setup.sh (contents below). Added the files directly via the "add file" on github.com, then copy/paste.
*Enabled auto-run dotfiles in Codespaces via github.com > settings > codespaces > use dotfiles = true (checkbox)
*VSCode > settings > linux default shell > zsh
setup.sh
#!/bin/bash
git clone git://github.com/zsh-users/zsh-autosuggestions $ZSH_CUSTOM/plugins/zsh-autosuggestions
git clone https://github.com/zsh-users/zsh-history-substring-search ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-history-substring-search
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
cat .zshrc > $HOME/.zshrc
.zshrc
export ZSH="${HOME}/.oh-my-zsh"
ZSH_THEME="robbyrussell"
DISABLE_UNTRACKED_FILES_DIRTY="true"
plugins=(zsh-autosuggestions history-substring-search zsh-syntax-highlighting)
source $ZSH/oh-my-zsh.sh
PROMPT="*** zsh *** %~ "
A: I have noticed that dotfiles don't get applied to the zsh shell that first comes up right after re-building the codespace. I'm still looking into this to understand it better. Starting a new zsh shell fixes the issue for me -- the dotfiles get applied. Does that fix the issue for you?
Also, I recommend doing a symlink instead of cat, in the setup.sh. See my blog post for more details: https://bea.stollnitz.com/blog/codespaces-terminal/
| |
doc_3542
|
foreach (var propertyInfo in this.GetType().GetProperties()
.Where(xx => xx.GetCustomAttributes(typeof(SearchMeAttribute), false).Any()))
{
if (propertyInfo.PropertyType.GetInterfaces().Any(xx => xx == typeof(IAmSearchable)))
{
// the following doesn't work, though I hoped it would
return ((IAmSearchable)propertyInfo).SearchMeLikeYouKnowIAmGuilty(term);
}
}
Unfortunately, I get the error:
Unable to cast object of type 'System.Reflection.RuntimePropertyInfo' to type 'ConfigurationServices.ViewModels.IAmSearchable'.
How can I get the actual object, rather than the RuntimePropertyInfo?
A: You need to get the value from the property with the GetValue method:
object value = propertyInfo.GetValue(this, null);
The this is the "target" of the property, and the null indicates that you're expecting just a parameterless property, not an indexer.
| |
doc_3543
|
Wordpress as it does in HTML. The CSS is correct (did allot of troubleshooting to root that out). This is the HTML:
<div class="navbar-wrapper">
<div class="navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only"> Toggle navigation </span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/"><img src="assets/img/Logo%20BY.png" alt="Logo" height="75" width="75"></a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="/">Home</a></li>
<li><a href="onzediensten.html">Onze diensten</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
</div>
</div>
</div>
And this is the Wordpress way i am trying to implement:
<div class="navbar-wrapper">
<div class="navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only"> Toggle navigation </span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">
<img src="<?php bloginfo('stylesheet_directory'); ?>/assets/img/Logo%20BY.png" alt="Logo" height="75" width="75">
</a>
</div>
<?php
wp_nav_menu( array(
'theme_location' => 'primary',
'container' => 'nav',
'container_class' => 'navbar-collapse collapse',
'menu_class' => 'nav navbar-nav navbar-right'
));
?>
</div>
</div>
</div>
Thanks in advance for the help!
A: I suspect you are missing the container div. Right click and inspect on the badly formatted menu and see if the (container) div is there
<div class="navbar-collapse collapse">
You have
'container' => 'nav'
should be
'container' => 'div'
| |
doc_3544
|
Average/Maximum Read/Write I/O Waits in ms per database file
for sliding time window.
That is: 4 numbers per database file: avg read wait, max read wait, avg write wait, max write wait. All in ms, and all for some sane (or even better configurable) sliding time window.
How can I do that?
PS: I have the VIEW SERVER STATE permission and can read sys.dm_os_performance_counters, sys.database_files, sys.dm_io_virtual_file_stats etc etc
PS2: At least 1 tool (Quest Spotlight 7 for SQL Server) is able to provide Max I/O Wait in ms per database file. So there has to be some way ..
A: Below is the query that SSMS's Activie Monitor uses. They label the io_stall field as total wait time. You could add the fs.io_stall_read_ms and fs.io_stall_write_ms fields to get the read/write specific numbers.
SELECT
d.name AS [Database],
f.physical_name AS [File],
(fs.num_of_bytes_read / 1024.0 / 1024.0) [Total MB Read],
(fs.num_of_bytes_written / 1024.0 / 1024.0) AS [Total MB Written],
(fs.num_of_reads + fs.num_of_writes) AS [Total I/O Count],
fs.io_stall AS [Total I/O Wait Time (ms)],
fs.size_on_disk_bytes / 1024 / 1024 AS [Size (MB)],
fs.io_stall_read_ms
FROM sys.dm_io_virtual_file_stats(default, default) AS fs
INNER JOIN sys.master_files f ON fs.database_id = f.database_id AND fs.file_id = f.file_id
INNER JOIN sys.databases d ON d.database_id = fs.database_id;
This query only gives you the totals. You'd have to run it at some interval and record the results in a temp table with a time stamp. You could then query this table to get your min/max/avg as needed. The sliding time window would just be a function of how much data you keep in that table and what time period you query.
A: The problem you are going to have is that SQL doesn't necessarily track the level of detail you are looking to get per file. You are probably going to have to use Performance monitor as well. You will have to use a combination approach looking at both performance monitor for details on I/O on the disk over the course of time. As well as the aforementioned SQL monitoring techniques to see get a more complete complete picture. I hope that helps.
A: You can use a few scripts to pull the metrics. I have enebled the Data Collection/Data Collection server built in to SQL Server 8. It collects the metrics from multiple instances and stores them in a mssql server you designate as the collector. The reports provided for each instance are adequate for most purposes. I am sure there are 3rd party tools that go beyond the capabilities of the data collector as it just reports on performance/disk usage/and query statistics without performance hints.
This gives you a data file growth projection and growth event summary for both logs and data files, however, I do not know if it will give you the metrics you are looking for per file or filegroup:)
NOTE: If you use the data collection warehouse you should consider rebuilding indexes periodically as the size grows. It collects approx. 20 MB/day of data in my senario.
A: See the following for collecting per file wait statistics http://msdn.microsoft.com/en-us/library/ms187309(v=sql.105).aspx
| |
doc_3545
|
case class CacheEntry(source: String, destination: String, hops: Int)
class CacheTable(tag: Tag) extends Table[CacheEntry](tag, "cache") {
def source = column[String]("source")
def destination = column[String]("dest")
def hops = column[Int]("hops")
def timestamp = column[LocalDateTime]("ts", O.DBType("timestamp default now"))
def * = (source, destination, hops) <> ((CacheEntry.apply _).tupled, CacheEntry.unapply)
}
How can we convince Slick to create the timstamp column with TableQuery[CacheTable].ddl.create?
Are we approaching this in the wrong way? We definately do NOT want the ts to show up in the CacheEntry (we could live with it in this case, but we have more complicated cases where this is not desirable)
A: You could define something like a case class TimestampedEE](entry: E, timestamp: LocalDateTime), and change your CacheTable to a Table[Timestamped[CacheEntry]]. The def * projection is probably going to look ugly (if don't rely on some shapeless magic), but that's one way to do it.
| |
doc_3546
|
import folium
map = folium.Map(location=[25.747608, 89.268044])
map.save("Map2.html")
When i add two more parameters like (tiles="Mapbox Bright") and (zoom_start=6) my code looks like this and the map does not work :
import folium
map = folium.Map(location=[25.747608, 89.268044], zoom_start=6, tiles="Mapbox Bright")
map.save("Map2.html")
What can i do with my code so that i see the map in my browser
A: I've just tried it too, neither the Mapbox Bright or Mapbox Control Room tiles seem to work, I don't think they're supported anymore. Try any of the other tiles or don't specify a tile parameter and it should work fine.
Here's a list of available tiles:
https://leaflet-extras.github.io/leaflet-providers/preview/
A: You have to add an API_key to view the map in your browser. Or you can use other tiles like 'Stamen Toner', 'OpenStreetMap', 'Stamen Toner', 'Stamen Watercolor'.
A: You can use HTML in your map in order to add any text in the map
legend_html = '''
<div style="position: fixed;
bottom: 50px; right: 50px; width: 150px; height: 90px;
border:2px solid grey; z-index:9999; font-size:14px;
"> Legend <br>
Origin <i class="fa fa-map-marker fa-2x" style="color:green"></i><br>
Destination <i class="fa fa-map-marker fa-2x" style="color:blue"></i>
</div>
'''
map_m.get_root().html.add_child(folium.Element(legend_html))
| |
doc_3547
|
Ideally I'd like to call it direct from RPG? is that possible? or do I have to create a java program to run on the iSeries and use RMI or something to call the remote java program.
We aren't keen on calling the extenral webservice direct as it means opening path from otherside world direct to iSeries.
I'm not an RPG programmer, just looking for something to point our guys in the right direction or anything I need to enable to make the java programs more consumable for the RPG folks.
Thanks,
Scott
A: Since the program is running on a remote server, you can't call it directly from RPG. Given that it's a web service, I would create a Java program to run on the iSeries and call that Java program from within RPG. Nowaday's, RPG can interface directly with Java. You have to create some D-specs to declare the class and prototype out the method calls. In the following example, assume a Java class exists called ServiceCaller in the package 'tools'. It has a single method called getServiceReply which accepts three character fields and returns an integer.
*Define the Java class locally.
DServiceCaller S O CLASS(*JAVA:'tools.ServiceCaller')
*Class constructor. No parameters.
DnewServiceCaller PR O EXTPROC(*JAVA:
D 'tools.ServiceCaller':
D *CONSTRUCTOR)
D CLASS(*JAVA:'tools.ServiceCaller')
*GetServiceReply.
*public int getServiceReply(byte[] parm1, byte[] parm2, byte[] parm3)
DgetServiceReply PR 10I 0 EXTPROC(*JAVA:
D 'tools.ServiceCaller':
D 'getServiceReply')
D Parm1 400A CONST
D Parm2 400A CONST
D Parm3 400A CONST
Your RPG calc specs will look something like this free-form example:
/free
ServiceCaller = newServiceCaller();
iReply = getServiceReply(ServiceCaller:'Parm1':'Parm2':'Parm3');
/end-free
Inside the java code, within the getServiceReply method, convert those byte arrays to strings like this:
sParm1 = new String(parm1);
sParm2 = new String(parm2);
sParm3 = new String(parm3);
Granted, this is an oversimplified example and your application needs will be slightly different. You will want to add error handling code in case the web service doesn't reply. You may also want to use getters and setters in your class. It all depends on your application needs and the requirements of the remote web service.
Some notes on RPG types to Java types:
RPG Type Java Type
10I 0 int
3I 0 byte
5I 0 short
20I 0 long
N boolean
A byte[]
If you are feeling particularly ambitious, you can call the native Java HTTP classes from within your RPG. But I've found that a custom Java program to act as an in-between that is written specifically to talk to RPG is an easier way to go. Although RPG can talk to Java, it's not as pretty as Java talking to Java.
Additional information on calling Java from RPG can be found in the ILE RPG Programmer's guide. The V5R4 version can be found here: http://publib.boulder.ibm.com/infocenter/iseries/v5r4/topic/books/sc092507.pdf
A: Since the is a web service, another solution would be to use Scott Klement's HTTP API. It's available on his website at http://www.scottklement.com/httpapi/.
One of the big benefits for me is this is entirely RPG and doesn't use any Java which can be a bit sluggish sometimes. I'm not real familiar with how web services work in Java but it appears that you don't have to form all of the XML and it's done for you. With the HTTP API you would need to do that yourself.
Also Scott Klement has several other useful things on his website. Another site with some neat tools is http://www.think400.dk/downloads.htm.
| |
doc_3548
|
Input :
["Anne", "Jane", "John", "Jane", "Ivan", "Peter", "Anne"]
Output:
["Anne","Jane","John","Ivan","Peter"]
It seems no langlib function to achieve this directly.
How to remove duplicate strings in an array using Ballerina?
A: Here are two ways of removing duplicates from a string array.
Method 1: Using indexOf method of lang.array
Method 2: Using keys method of lang.map
Sample code is as follows.
import ballerina/io;
// Method 1
function getUniqueValues(string[] names) returns string[] {
string[] uniqueNames = [];
foreach string name in names {
if uniqueNames.indexOf(name) is () {
uniqueNames.push(name);
}
}
return uniqueNames;
}
//Method 2
function getUniqueValuesUsingMap(string[] names) returns string[] {
map<()> mapNames = {};
foreach var name in names {
mapNames[name] = ();
}
return mapNames.keys();
}
public function main() {
string[] duplicatedStrings = ["Anne", "Jane", "John", "Jane", "Ivan", "Peter", "Anne"];
//Using Method 1
io:println(getUniqueValues(duplicatedStrings));
//Using Method 2
io:println(getUniqueValuesUsingMap(duplicatedStrings));
}
A: Using the .some() langlib function of Ballerina arrays, this could be achieved as following.
public function main() {
string[] strArr = ["Anne", "Jane", "John", "Jane", "Ivan", "Jane", "Peter", "Anne"];
_ = strArr.some(function (string s) returns boolean {
int? firstIndex = strArr.indexOf(s);
int? lastIndex = strArr.lastIndexOf(s);
if (firstIndex != lastIndex) {
_ = strArr.remove(<int>lastIndex);
}
// Returning true, if the end of the array is reached.
if (firstIndex == (strArr.length() - 1)) {
return true;
}
return false;
});
io:println(strArr);
}
Since the .some() langlib function is used to check if at least a single member in the array follows the given condition, it could be used to determine if we've reached the end of the array and prevent the Index Out of Bound Exception.
Within the function that is passed as the parameter of the .some() langlib function, we'd be removing only the last instance of any duplicate value. When reached to the end of the array, all the duplicate values would be removed.
| |
doc_3549
|
IronPython: https://ironpython.codeplex.com/releases/view/62475
IronLab: https://code.google.com/p/ironlab/downloads/detail?name=ironlab%201.1.2.0.zip&can=2&q=
When I run the 3 getting started commands that IronLab recommends
import numpy as np
import ironplot as ip
ip.plot(np.sin(np.arange(0, 10, 0.1)))
via IronPythonConsole located in the IronLab directory, they work fine.
After importing the libraries into IronPython via IronLab in the ipy IronPython console,
import sys, clr
sys.path = ['.', 'C:\\Program Files (x86)\\IronLab 1.1.2.0\\Lib', 'C:\\Program Files (x86)\\IronLab 1.1.2.0\\DLLs', 'C:\\Program Files (x86)\\IronLab 1.1.2.0\\lib\\site-packages'] + sys.path
clr.AddReference("mtrand.dll")
the first two imports work fine, however the ip.plot command gives me MemoryError: Exception of type 'System.InsufficientMemoryException' was thrown.
After researching this exception online, I saw that it could be a problem with my system running out of physical memory. However, I have 8 GB of RAM on 64 bit Windows and I have only noticed 45% being used in Task Manager when I am running this command. Others recommended changing code so less memory would be used, but as this is one of the "starting" commands, I am uncertain what to do. Would anyone have any advice on how I could get IronPlot to work in IronPython?
| |
doc_3550
|
The configuration is :
checkstyle {
configFile = new File("${project.projectDir}/config/checkstyle/sun_checks.xml")
showViolations = false
}
checkstyleMain {
doLast{
println("checkstyle main")
project.ext.checkType = "main"
tasks.checkstyleReport.execute()
}
}
checkstyleTest {
doLast{
println("checkstyle test")
project.ext.checkType = "test"
tasks.checkstyleReport.execute()
}
}
task checkstyleReport{
checkstyleReport.outputs.upToDateWhen { false }
}
checkstyleReport << {
logger.info("Producing checkstyle html report")
final source = "${project.projectDir}/build/reports/checkstyle/${project.checkType}.xml"
final xsl = "${project.projectDir}/config/checkstyle/checkstyle-simple.xsl"
final output = "$buildDir/reports/checkstyle/${project.checkType}.html"
println(source)
println(xsl)
println(output)
ant.xslt(in: source,
style: xsl,
out: output
)
}
When I invoke :
gradle --daemon clean checkstyleMain checktyleTest
The output is :
...
:clean
:compileJava
:processResources
:classes
:checkstyleMain
checkstyle main
/<root_path_here>/build/reports/checkstyle/main.xml
/<root_path_here>/config/checkstyle/checkstyle-simple.xsl
/<root_path_here>/build/reports/checkstyle/main.html
:compileTestJava
:processTestResources
:testClasses
:checkstyleTest
checkstyle test
As you see, the checkstyleReport task is invoked twice, but produces output only once. I even tried outputs.upToDateWhen { false } but it doesn't work.
Thank you in advance for help.
A: A Gradle task will execute at most once. Also, invoking tasks explicitly is not supported, and will lead to all sorts of problems. The correct approach is to declare a report task per Checkstyle task (e.g. using a task configuration rule), and make it depend on that Checkstyle task (or use mustRunAfter).
| |
doc_3551
|
var len = 5
var wid = 5
var g = "aaaaa" +
"aaaaa" +
"aaaaa" +
"aaaaa" +
"aaaaa";
for (var x = 0; x < len; x++) {
for (var y = 0; y < wid; y++) {
var yC = x % len
var xC = Math.floor(x / len)
console.log(x + y * xC)
}
}
this code is just a mockup of what im trying to do. currently, if you were to check the console after running this, it would log the numbers 0-4 5 times each, but what i am trying to do i output the numbers 0-24 1 time each.
note that i cant simply just loop the length of the string and output the current character index as i need to use the x and y for something else that is not present here.
https://jsfiddle.net/g19bmnsh/
A: I guess this is what you want.
var len = 5
var wid = 5
var g = "aaaaa" +
"aaaaa" +
"aaaaa" +
"aaaaa" +
"aaaaa";
for (var x = 0; x < len; x++) {
for (var y = 0; y < wid; y++) {
var yC = x % len
var xC = Math.floor(x / len)
console.log("x: " + x, "y: " + y, "k: " + (x + y * xC), "i:" + (y + (x * len)))
}
}
| |
doc_3552
|
The curl statement looks like this:
curl -X PUT "http://localhost:8080/EAIConfig/ri/media" --data-binary img019.png
And this is my resource implementation:
@Override
protected Representation put(Representation entity) throws ResourceException {
try {
InputStream in = entity.getStream();
OutputStream out = new FileOutputStream("/Temp/media-file.png");
IOUtils.copy(in,out);
out.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new EmptyRepresentation();
}
This runns without errors. But the resulting /Temp/media-file.png does contain the name of the sent file instead of the sent image data.
Any idea how to get the file contents?
A: I don't think it's a problem in your Restlet code but rather in the way you call it using curl.
You forget the '@' in the parameter --data-binary. You should use something like that:
curl -X PUT "http://localhost:8080/EAIConfig/ri/media" --data-binary "@img019.png"
I made a try with your code and it works for me. I suppose that you the class IOUtils from Commons IO.
One small comment. Your method put needs to be defined as public and with annotation @Put to be directly called by Restlet ;-)
Hope it helps you,
Thierry
| |
doc_3553
|
How can I store this in my database?
Let’s say the user has chosen to pay using his IBAN, assuming this picture is the current database, do I fill the fields associated with the IBAN option and set the others to Null? Or is there a more professional way to store the data without having these Null values?
UPDATE
I found a solution to this problem in the answer to this question, however, the answer is still not sufficient. If anybody has a link to a more detailed documents please let me know.
A: As @philipxy noted, you're asking about representing inheritance in a RDBMS. There are a few different ways to do this:
*
*Have all of your attributes in one table (which, based on your screenshot, is what you have now). With this approach, it would be best to store NULLs in non-applicable columns---if nothing else, the default settings for InnoDB tables uses the compact row format, which means NULL columns don't take up extra storage. Of course, your queries can get complex, and maintaining these tables can become cumbersome.
*Have child tables to store your details:
*
*Payments (PaymentID, PaymentDate, etc.)
*CashPaymentDetails(PaymentID, Cash_Detail_1, Cash_Detail_2, etc.)
*IBANPaymentDetails(PaymentID, IBAN_Detail_1, etc.)
*You can get the information for each payment by joining the base payment table with one of the "subsidiary" tables:
SELECT *
FROM Payments P INNER JOIN CashPaymentDetails C ON
C.PaymentID = P.PaymentID
*Your third option is to use the entity-attribute-value (EAV) model. Like with Option 2, you have a base Payment table. However, instead of having one table for each payment method, you have one subsidiary table that contains the payment details. For more information, here's the Wiki page, and here's a blog with some additional information.
| |
doc_3554
|
This is my Java code:
@ManagedBean
public abstract class FooController {
protected <type> prop;
public void setProp(<type> prop) {
this.prop = prop;
}
public <type> getProp() {
return this.prop;
}
}
@ManagedBean
public class Foo1Controller extends FooController {
private <otherType> myProp;
@PostConstructor
public void init {
myProp = prop.getProp().getOtherTypeProp();
}
}
[here I have more FooControllers Foo2Controller, Foo3Controller, Foo4Controller...]
@ManagedBean
public class MainController {
// all props have getters and setters
private FooController fooController;
private int controllerType;
private List<SelectItem> myTypes;
private <type> prop;
@PostConstructor
public void init {
// init myTypes here
// init prop here
}
public static Object getBean(String s) {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().evaluateExpressionGet(context, "#{" + s + "}", Object.class);
}
public void controllerTypeChange (ValueChangeEvent event) {
controllerType = Integer.valueOf(event.getNewValue().toString());
if (controllerType == 1)
fooController = (Foo1Controller) getBean("foo1Controller");
else if (controllerType == 2)
fooController = (Foo2Controller) getBean("foo2Controller");
....
fooController.setProp(this.prop);
}
}
And this is the XHTML:
<o:SelectOneMenu id="fooType"
value = #{"MainController.controllerType"}
valueChangeListener = "#{MainController.controllerTypeChange}"
styleClass = "dropdown">
<o:ajax action = "#{MainController.controllerTypeChange}">
<f:selectItems value = "MainController.myTypes">
</o:selectOneMenu>
<h:panelGroup id="component1" rendered="#{MainController.controllerType == 1}">
<!-- some component here that uses foo1Controller as it's controller -->
</h:panelGroup>
<h:panelGroup id="component2" rendered="#{MainController.controllerType == 2}">
<!-- some component here that uses foo2Controller as it's controller -->
</h:panelGroup>
The thing is that when i'm creating the foo1Controller in the MainController bean, it's already uses the prop attribute in the foo1Controller @postConstructor but this attribute is NULL because it wasn't yet initialized and i have no idea how to do it before the post constructor is called.
The concept behind what i'm tring to do is that MainController can and should have only one child component and they all have a lot in common so it's a must to do here inheritance.
When the user select some value in the drop down the relative component should be displayd while the MainController should have a refrence to the component controller.
Any help will be very appreceated.
Thanks!
A: define servlet which should GenericServlet in your application do whatever you want. and define it in web.xml set load-on-startup tag.
Sample code for servlet
public class ResourceInitializer extends GenericServlet {
@Override
public void init(final ServletConfig config) throws ServletException {
super.init(config);
// YOUR APPLICATION INIT CODE
}
@Override
public void service(final ServletRequest req, final ServletResponse res)
throws ServletException {
}
@Override
public void destroy() {
// tell the ResourceManager to cleanup and remove the resouces
LibraOfficeService.getInstance().closeConnection();
super.destroy();
}
}
in the web.xml
<servlet>
<description>Initializes Resources</description>
<servlet-name>ResourceInitializer</servlet-name>
<servlet-class>packageNAME.ResourceInitializer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
| |
doc_3555
|
I've been doing it manually for a while, pulling an IP address, then using a web based whois utility to find the range it's in, then manually adding the range to the blocked IP list for the site. It's a pain.
Now I'm parsing the logfile to find the IP address of suspicious entry attempts with a Perl script, and I want to find the IP address range to which that IP address belongs, and maybe pull some other descriptive information that will quickly tell me if this is a range I want to block.
I know it can be done because the web utilities provide the information. Here's an example
.
I can run gethostbyaddr on them, but that's not what I need.
I've seen some whois modules that had some information, but could not find access to the range to which the IP address belongs. I'm hoping there is a module I can use to pull the address range from to help me speed up the security process.
A: I suggest that you make use of the Net::Whois::Raw module. It returns just a block of text, and you will have to use regex patterns to extract the information that you need
Here's an example that displays the IP range for the same address as you use in your example. Just print $info to see the whole thing
use strict;
use warnings 'all';
use feature 'say';
use Net::Whois::Raw;
my $info = whois('95.137.240.189');
say $info =~ /NetRange:\s*(.+)/;
output
95.0.0.0 - 95.255.255.255
| |
doc_3556
|
A: I have solved the problem. I ran a troubleshooting through the control panel on my wifi and it showed that the windows was not able to identify the proxy settings, so I went to the internet explorer and in it's advanced settings unchecked the box which said Use Proxy Server. My Android studio is working fine now. Thank You!
| |
doc_3557
|
I write this query:
SELECT *
FROM OPENROWSET('MSDASQL', 'Driver=Microsoft Visual FoxPro Driver;
SourceDB=D:\DB\;
SourceType=DBF',
'SELECT * FROM MyTable')
Also I installed 'VFPOLEDB' provider to run the query. But it does not run and I got this error:
Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "MSDASQL" for linked server "(null)" reported an error. The provider did not give any information about the error.
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider "MSDASQL" for linked server "(null)".
I ran this query correct before,but it does not run now,I don't know why!I Google that but it doesn't helpful.
How can I read DBF files using SQL Server 2008 R2? My DBMS are running on Windows 7 OS, and also Windows 2003 Server.
Thanks in advance,
Mohsen.
A: This is a problem with SQL Server 2008 R2. You can downgrade to SQL Server 2005 or SQL Server 2008 to get this working again.
| |
doc_3558
|
Sheets("Sheet1").PivotTables("PivotTable" & pivot_counter).PivotFields( _
"[year].[year].[year]").VisibleItemList = Array("")
My questions are:
1- Why do we use PivotFields("[year].[year].[year]") when using VisibleItemList? Why do we have to repeat it and what's the meaning of it, couldn't anything about it anywhere.
2- What is supposedly wrong with this code? My pivot table has a field called "year" and the filter is set for a specific year (let's say 2013) and i wanted it change for all possible years.
A: Sub Tester()
ShowAll ActiveSheet.PivotTables("PivotTable1").PivotFields("Year")
End Sub
Sub ShowAll(pf As PivotField)
Dim pi As PivotItem
Application.ScreenUpdating = False
For Each pi In pf.PivotItems
pi.Visible = True
Next pi
Application.ScreenUpdating = True
End Sub
| |
doc_3559
|
var Employees = db.EmployeeMasterAs
.Where(x => x.SystemCode == SysCode && x.EmployeeCode == EmpCode)
.ToList();
the above query works fine if all values in the where clause are provided. If EmpCode is supplied a value, it returns the corresponding data, which works fine. However, I've no idea about how to return all rows if EmpCode is not supplied.
If I were to use SQL, I would have done it this way :
SELECT * FROM EmployeeMasterAs
WHERE SystemCode == @SysCode AND (EmployeeCode == @EmpCode or '')
I've no idea how to translate the above query into linq syntax. Any Help will be deeply appreciated, Thanks in Advance :)
A: you can even write something like this
...&& (EmpCode == null || x.EmployeeCode == EmpCode) )
which i find simplier than @Dr Ivol
| |
doc_3560
|
I have installed postgresql, psycopg2 and Django.
my code :
settings.py :
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.path.join(BASE_DIR, 'db.psycopg3'),
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
and to python manage.py shell :
from django.db import connection
cursor = connection.cursor()
Errors :
FATAL: password authentication failed for user "root"
Please help...
A: The database name in your settings.py should be modified. Actually you had entered the format used for sqlite db. For postgres, it should be
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbname',
'USER': 'root',
'PASSWORD': 'rootXXX',
'HOST': '',
'PORT': '',
}
}
Create the Database 'dbname' in your postgres before synchronizing it with your app
| |
doc_3561
|
private void uploadVideoTwo(String filePath){
AsyncHttpClient client = new AsyncHttpClient();
File myFile = new File(filePath);
RequestParams params = new RequestParams();
try {
params.put("file", myFile);
} catch (FileNotFoundException e) {
Log.e(TAG, "Params Exception: " + e.getMessage());
}
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d(TAG, "Success: " + String.valueOf(statusCode));
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d(TAG, "Failure: " + String.valueOf(statusCode));
}
});
}
My PHP code looks like this:
<?php
$result = array("success" => $_FILES["file"]["name"]);
$name= $_FILES['file']['name'];
$tmp_name= $_FILES['file']['tmp_name'];
$path= "uploads/";
if (isset($name)) {
if (empty($name))
{
$result = array("success" => "error uploading file");
}
else
{
if (move_uploaded_file($tmp_name, $path . $name)) {
$result = array("success" => "File successfully uploaded");
}
}
}
echo json_encode($result);
?>
Android Studio logcat shows progress percentage during upload of video file but gives error response after it gets to 100%. I am using an intent to open the camera to capture a video with a limit of 30 seconds and a size limit of 5 mb. I have no idea why uploading an image works fine but not a video using the same script.
A: It looks like either a timeout or a filesize issue. Default execution time of a php script is 30 seconds. Change it to i.e. 300 (5 minutes) in your php.ini file.
; Maximum execution time of each script, in seconds
max_execution_time=300
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize=32M
Also, enable error reporting by putting the following in the very beginning of your php script. It will give you a more detailed description of what is going wrong.
error_reporting(E_ALL);
ini_set('display_errors', 1);
A: Check the value of post_max_size and upload_max_filesize in your php.ini file. Default value is only 2 megabytes, so you should change it to something more appropriate.
To find out the location of php.ini on your own host just insert a call to phpinfo() inside any available script on your site and see the output in your browser.
For popular cloud platforms:
On Google Cloud Engine (standard or flexible environments) put php.ini file to your project's root (alongside app.yaml) with these lines inside:
post_max_size = 128M
upload_max_filesize = 128M
On Heroku put .user.ini file with the same content as above in your app's root directory.
| |
doc_3562
|
data
SYMBOL TIMESTAMP STAMP PRICE SIZE EXCHANGE BID BIDEX BIDSIZE ASK ASKEX ASKSIZE
1 SPXU 1330938005 1330938005000000 NA NA 9.99 PSE 5 10.10 PSE 6
2 SPXU 1330938221 1330938221000000 NA NA 9.99 PSE 5 10.19 PSE 1
3 SPXU 1330938221 1330938221000001 10.1000 600 PSE NA NA NA NA
4 SPXU 1330938392 1330938392000000 NA NA 10.00 PSE 174 10.19 PSE 1
5 SPXU 1330938431 1330938431000000 NA NA 10.00 PSE 175 10.19 PSE 1
6 SPXU 1330938468 1330938468000000 NA NA 10.00 PSE 1 10.19 PSE 1
7 SPXU 1330938736 1330938736000000 NA NA 10.04 PSE 46 10.19 PSE 1
8 SPXU 1330938843 1330938843000000 NA NA 10.04 PSE 47 10.19 PSE 1
9 SPXU 1330939576 1330939576000000 NA NA 10.04 PSE 1 10.19 PSE 1
10 SPXU 1330939615 1330939615000000 NA NA 10.05 PSE 100 10.19 PSE 1
11 SPXU 1330939615 1330939615000001 NA NA 10.05 PSE 100 10.19 PSE 101
12 SPXU 1330939621 1330939621000000 NA NA 10.04 PSE 1 10.19 PSE 101
13 SPXU 1330939621 1330939621000001 NA NA 10.04 PSE 1 10.19 PSE 1
14 SPXU 1330939623 1330939623000000 NA NA 10.05 PSE 46 10.19 PSE 1
15 SPXU 1330939623 1330939623000001 NA NA 10.05 PSE 46 10.18 PSE 46
16 SPXU 1330939638 1330939638000000 NA NA 10.04 PSE 1 10.18 PSE 46
17 SPXU 1330939686 1330939686000000 NA NA 10.04 PSE 1 10.19 PSE 1
18 SPXU 1330939825 1330939825000000 NA NA 10.05 PSE 100 10.19 PSE 1
19 SPXU 1330939825 1330939825000001 NA NA 10.05 PSE 100 10.19 PSE 101
20 SPXU 1330939833 1330939833000000 NA NA 10.04 PSE 1 10.19 PSE 101
21 SPXU 1330939833 1330939833000001 NA NA 10.04 PSE 1 10.19 PSE 1
22 SPXU 1330939833 1330939833000002 NA NA 10.04 PSE 101 10.19 PSE 1
23 SPXU 1330939833 1330939833000003 NA NA 10.04 PSE 101 10.19 PSE 101
24 SPXU 1330939941 1330939941000000 NA NA 10.04 PSE 101 10.19 PSE 102
25 SPXU 1330940041 1330940041000000 NA NA 10.04 PSE 1 10.19 PSE 102
I want to be able to have zoo objects created keeping the millisecond granularity. I'm unable to transform the "data$STAMP" into a date. How can I do this?
working:
> as.POSIXlt(data2$TIMESTAMP[3], origin="1970-01-01", tz="EST")
[1] "2012-03-05 04:01:36 EST"
not working:
> as.POSIXlt(data2$STAMP[3], origin="1970-01-01", tz="EST")
[1] "))0'-06-03 15:45:52 EST"
A: That's essentially a FAQ -- you need options("digits.secs"=6) to default to displaying sub-second time information.
Witness:
R> Sys.time() # using defaults: no milli or micros
[1] "2012-07-15 12:51:17 CDT"
R> options("digits.secs"=6) # changing defaults: presto!
R> Sys.time()
[1] "2012-07-15 12:51:30.218308 CDT"
R>
Now combine this with suitable numeric vector, suitably converted to R's datetime types:
R> vec <- 1330938005000000 + cumsum(runif(1:5)*10)
R> vec
[1] 1.331e+15 1.331e+15 1.331e+15 1.331e+15 1.331e+15
R> as.POSIXct(vec/1e6, origin="1970-01-01")
[1] "2012-03-05 09:00:05.000004 CST"
[2] "2012-03-05 09:00:05.000006 CST"
[3] "2012-03-05 09:00:05.000016 CST"
[4] "2012-03-05 09:00:05.000021 CST"
[5] "2012-03-05 09:00:05.000029 CST"
R>
| |
doc_3563
|
cat <<EOF >> .bashrc
export JAVA_HOME=/opt/jdk
export GRADLE_HOME=/mnt/c/Zi/gradle
export GRADLE_OPTS="-Xmx2g -Xms512m -XX:MaxMetaspaceSize=384m"
export GRADLE_USER_HOME=/mnt/c/Z
export PATH="${JAVA_HOME}/bin:$PATH"
After this i get a warning:
-bash: warning: here-document at line 21 delimited by end-of-file (wanted `EOF')
Can someone give me a hint?
Thank you,
Lisa
A: The input redirection <<EOF means to read everything until a line with EOF on it, and use that as the input to the command; this is called a here-doc.
You're missing the EOF line.
cat <<'EOF' >> .bashrc
export JAVA_HOME=/opt/jdk
export GRADLE_HOME=/mnt/c/Zi/gradle
export GRADLE_OPTS="-Xmx2g -Xms512m -XX:MaxMetaspaceSize=384m"
export GRADLE_USER_HOME=/mnt/c/Z
export PATH="${JAVA_HOME}/bin:$PATH"
EOF
Also, quote the EOF token in <<'EOF' to indicate that variables should not be expanded in the here-doc. In the last line ${JAVA_HOME} and $PATH should be expanded when .bashrc is being loaded, not when you're adding to it.
| |
doc_3564
|
This is my code
public class PlayThisVideo extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
mediaController=new MediaController(PlayThisVideo.this);
Uri videoURI=Uri.parse("android.resource://com.VideoAppProject/"+R.raw.baa_baaa_blacksheep);
videoview.setMediaController(mediaController);
videoview.setVideoURI(videoURI);
videoview.requestFocus();
videoview.start();
videoview.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
Uri videoURI=Uri.parse("android.resource://com.VideoAppProject/"+R.raw.ding_dong_bell);
videoview.setMediaController(mediaController);
videoview.setVideoURI(videoURI);
videoview.requestFocus();
videoview.start();
}
});
}
}
I need to loop videos so that they play one after another
A: Try this:
videoView = (VideoView) findViewById(R.id.v);
setup();
videoView.setOnCompletionListener(completionListener);
setup Function:
public void setup() {
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/"
+ R.raw.test);
videoView.setVideoURI(uri);
videoView.start();
}
implement onCompletionListener as:
OnCompletionListener completionListener=new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.stop();
setup();
}
};
A: private int[] ids = {R.raw.vid1, R.raw.vid2, R.raw.vid3, R.raw.vid4, R.raw.vid5};
private int index = 1;
private VideoView myVideo1;
OnCreate
//Video Field
myVideo1 = (VideoView) findViewById(R.id.myvideoview);
myVideo1.requestFocus();
myVideo1.setVideoURI(getPath(index));
index++;
myVideo1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
myVideo1.start();
}
});
myVideo1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (index == ids.length) index = 1;
index++;
myVideo1.setVideoURI(getPath(index));
}
});
private Uri getPath(int id) {
return Uri.parse("android.resource://" + getPackageName() + "/raw/vid" + id);
}
We asume that your videos are on raw folder and with name vid1 vid2 etc..
| |
doc_3565
|
I'm creating an R package. All dependencies are installed. The source code is (as far as I can tell) correctly annotated for roxygen2.
Within the package root, the following commands are successful:
Documenting the package works:
> devtools::document()
Building the package works:
> devtools::build()
Installing the package fails:
> devtools::install()
** R
** data
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec, :
line 1 did not have 18 elements
ERROR: installing package indices failed
I'm at a loss at to why. Are there any troubleshooting tips for this?
| |
doc_3566
|
try_files $uri/index.html $uri @app;
location @app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://app
}
When I create a file at foo/bar/baz.txt it works but if 'bar' is a symlink, it stops working. Anyone know how to solve this as I need to use symlinks.
A: I was being daft, there was not executable rights for all on one of the parent directories.
| |
doc_3567
|
I'm using Eclipse as my IDE and export a runnable jar through it. Everything's worked before except now that I have a ComboBox and load it with an array (FX.Collections-thing). I run it on my Windows 7 computer where I do my development, then I move it over to my Windows 10 computer where I test to make sure things run alright, but it isn't in this case.
OutOfBoundsException are usually simple to deal with, but I'm at a loss on how to deal with this exception since it works on one computer (there is no runtime exception) and in the other there's this exception(s):
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$159(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at com.sun.javafx.collections.ObservableListWrapper.get(ObservableListWrapper.java:89)
at my.pages.giftcertmaker.MainGiftCertPage.start(MainGiftCertPage.java:52)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$166(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$179(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$177(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$178(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$152(WinApplication.java:177)
... 1 more
Exception running application my.pages.giftcertmaker.MainGiftCertPage
Edit: Forgive me for not doing my due diligence below are lines 51 and 52
ArrayList<Integer> certNumbersFound = workbook.getCertNumbers();
int lastNumber = certNumbersFound.get(certNumbersFound.size()-1);
Which begs the questions what's in getCertNumbers()
public ArrayList<Integer> getCertNumbers()
{
ArrayList<Integer> numbersUsed = new ArrayList<Integer>();
/*
* Code reads from an excel file column of doubles and converts
* the doubles to ints and adds them to numbersUsed with a for-loop
*/
return numbersUsed;
I've tried 4 different Java versions (1.8.0_181, _192, _201,_202). I've tried changing the double types read from the excel file at different parts of the code. I've tried changing the type of the ArrayList from , , and . I've changing the location of code loaded. It always goes to this part:
certNumbersFound.get(certNumbersFound.size()-1)
I always thought this was ok, but what is a better way? Or am I just unlucky? And I've also System.out.println-ed the ArrayList before the launch(args) method in the main and made certNumbersFound.size()-1 into it's own object before putting into the get method of the ArrayList.
And all the libraries have worked previously, but adding this ComboBox and the ArrayList (rather the FX.Collections-thing) ruins it.
I'm truly dumbfounded.
A: ArrayList.get throws IndexOutOfBoundsException if the index is out of range. In your case probably less than zero.
To avoid that add a check to your code:
ArrayList<Integer> certNumbersFound = workbook.getCertNumbers();
if (certNumbersFound.size() >= 1) {
int lastNumber = certNumbersFound.get(certNumbersFound.size()-1);
//more code
}
else {
//handle situation according to your needs
//e.g. throw exception, log something or write to err:
System.err.println("Invalid size: " + certNumbersFound.size());
}
When reading data from external sources (like an Excel file in this case) it is always a good idea to introduce safety checks.
An even better idea is to put exception handling (or: expect the unexpected handling code) inside getCertNumbers which is the method where you read a (potentially unreliable) external source. External source in this context means: not controlled by Java compiler.
A: Credit to JB Nizet for helping me work through this one.
I had checks for if the file wasn't there, a new file would be created with the proper template as a redundancy. But! That didn't mean there were any values within the template to load the ArrayList.
The only reason why it worked on my Windows 7 computer (development computer) was because it had a test file with figures already in the template, so it had never ran from scratch like it was doing on my Windows 10 (testing computer).
I have to add a method or an if statement saying:
if(certNumbersFound != null && certNumbersFound.size() > 0)
{
//Write code that can use the ArrayList certNumbersFound
//because there's values in the file
}
else
{
//Write code that doesn't use the ArrayList certNumbersFound
//because there's no values in the file.
}
I feel so dumb. Thanks everyone. I'm sorry for wasting your time.
| |
doc_3568
|
I followed 'ac3-state-management-examples' for solve this problem, but still couldn't find any problem.
This is my client-side code.
export const DELETE_ITEM_IN_CART = gql`
mutation DeleteItemInCart($cartItemId: String!) {
DeleteItemInCart(cartItemId: $cartItemId)
}
`;
export function useDeleteItemInCart() {
console.log(`DELETION START! ${Date()}`);
const [mutate, { data, error }] = useMutation<
DeleteItemInCartType.DeleteItemInCart,
DeleteItemInCartType.DeleteItemInCartVariables
>(DELETE_ITEM_IN_CART, {
update(cache, { data }) {
const deletedCartItemId = data?.DeleteItemInCart;
const existingCartItems = cache.readQuery<myCart>({
query: MY_CART,
});
if (existingCartItems && deletedCartItem && existingCartItems.myCart) {
cache.writeQuery({
query: MY_CART,
data: {
myCart: {
cartItem: existingCartItems.myCart.cartItem.filter(
t => t.id !== deletedCartItemId,
),
},
},
});
console.log(`DELETION OVER! ${Date()}`);
}
},
});
return { mutate, data, error };
}
And here's my server-side mutation
export const DeleteItemInCart = mutationField('DeleteItemInCart', {
args: {cartItemId: nonNull('String')},
type: nonNull('String'),
description: 'Delete an item in my cart',
resolve: (_, {cartItemId}, ctx) => {
const {prisma} = ctx;
try {
prisma.cartItem.delete({
where: {
id: cartItemId,
},
});
return cartItemId;
} catch (error) {
return cartItemId;
}
},
});
This is an example of Apollo-remote-state-mananagement
export const DELETE_TODO = gql`
mutation DeleteTodo ($id: Int!) {
deleteTodo (id: $id) {
success
todo {
id
text
completed
}
error {
... on TodoNotFoundError {
message
}
}
}
}
`
export function useDeleteTodo () {
const [mutate, { data, error }] = useMutation<
DeleteTodoTypes.DeleteTodo,
DeleteTodoTypes.DeleteTodoVariables
>(
DELETE_TODO,
{
update (cache, { data }) {
const deletedTodoId = data?.deleteTodo.todo?.id;
const allTodos = cache.readQuery<GetAllTodos>({
query: GET_ALL_TODOS
});
cache.writeQuery({
query: GET_ALL_TODOS,
data: {
todos: {
edges: allTodos?.todos.edges.filter((t) => t?.node.id !== deletedTodoId)
},
},
});
}
}
)
return { mutate, data, error };
}
Any advice?
1 second delay is inevitable using apollo cache?
*
*I took a short video of my issue. i dont think it's inevitable...
| |
doc_3569
|
Flat file 1 has 10 records, Flat file 2 has 5 records. I want 4 different targets :
*
*10 records from file 1
*5 records from file 2
*15 records from both the files
*50 records (like cross join)
A: I am attaching a hand-drawn picture.
*
*10 records from file 1 - Straight from SQ 1 to target 1 5 records
*5 from file 2 - Straight from SQ 2 to target 2
*15 records from both the
files - UNION SQ1 and SQ2 and push to target 3
*50 records (like cross
join) - Use a joiner to join SQ1 and SQ2 and push to target 4. Join
condition will be a dummy column with same value.
| |
doc_3570
|
I put the following code in the overridden touchesBegan of the MainMenu Scene to present the GameScene:
let reveal = SKTransition.fade(withDuration: 0.5)
let NextScene = GameScene(size: self.size)
NextScene.scaleMode = SKSceneScaleMode.aspectFill
self.view?.presentScene(NextScene, transition:reveal)
But if I test it I get the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
I just don't understand why because in the GameScene I have the follow code in the GameOver function which works perfectly fine:
let reveal = SKTransition.fade(withDuration: 0.5)
let MainMenuScene = MainMenu(size: self.size)
MainMenuScene.scaleMode = SKSceneScaleMode.aspectFill
self.view?.presentScene(MainMenuScene, transition:reveal)
They are the exact same but only the one in the GameOver Function works, why?
| |
doc_3571
|
<!-- Add mousewheel plugin (this is optional) -->
<script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<!-- Add fancyBox -->
<link rel="stylesheet" href="{{ STATIC_URL }}/static/fancybox/source/jquery.fancybox.css?v=2.1.7" type="text/css" media="screen" />
<script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/jquery.fancybox.pack.js"></script>
<!-- Optionally add helpers - button, thumbnail and/or media -->
<link rel="stylesheet" href="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script>
<link rel="stylesheet" href="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" />
<script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".fancybox").fancybox();
});
</script>
Rendered Code :
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- Add mousewheel plugin (this is optional) -->
<script type="text/javascript" src="/static/fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<!-- Add fancyBox -->
<link rel="stylesheet" href="/static/fancybox/source/jquery.fancybox.css?v=2.1.7" type="text/css" media="screen" />
<script type="text/javascript" src="/static/fancybox/source/jquery.fancybox.pack.js"></script>
<!-- Optionally add helpers - button, thumbnail and/or media -->
<link rel="stylesheet" href="/static/fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="/static/fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript" src="/static/fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script>
<link rel="stylesheet" href="/static/fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" />
<script type="text/javascript" src="/static/fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".fancybox").fancybox();
});
</script>
This is my settings.py file and url.py file from project :
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/var/www/static/',
]
CRISPY_TEMPLATE_PACK = 'bootstrap3'
Expected OutCome:
Real Outcome:
debugger
| |
doc_3572
|
from django.db import models
class Topping(models.Model):
# ...
price = models.IntegerField()
class Pizza(models.Model):
# ...
toppings = models.ManyToManyField(Topping)
I need to get following query:
my_query = Pizza.objects.all().annotate(
topping_with_min_price="get id of topping with the minimal price")
So, how to get that?
A: You can work with a Subquery:
from django.db.models import OuterRef, Subquery
my_query = Pizza.objects.annotate(
topping_with_min_price=Subquery(
Topping.objects.filter(
pizza=OuterRef('pk')
).order_by('price').values('pk')[:1]
)
)
| |
doc_3573
|
Possible Duplicate:
Update a list of a list of elements in a single list?
I have a list of values as shown below:
[ ["Off","Off","Off"],
["Off","Off","Off"],
["Off","Off","Off"] ]
and would like to return the following:
[ ["Off","Off","Off"],
["Off",*"On"*,"Off"],
["Off","Off","Off"] ]
I have the following function which works just for an individual list by itself:
replaceAll 0 newValue (x:xs) = newValue:xs
replaceAll b newValue (x:xs) = x:replaceAll (b-1) newValue xs
However, I seem to be having trouble working with these multiple lists within a list. How would I devise a function to deal with these two lists (i.e. a list inside another list)?
Still trying to get my head around the whole (x:xs) thing.
A: Lists aren't the best structure for this sort of thing. But let's work with lists anyway.
We'll tweak your replaceAll so that instead of you providing the replacement value, you provide a function that specifies how to replace the old one with the new one.
replaceAll 0 f (x:xs) = f x:xs -- Here's where we transform x using f
replaceAll b f (x:xs) = x:replaceAll (b-1) f xs
Now we can use replaceAll on itself to perform the replacement we want on a specific row of the matrix:
test = replaceAll 1 (replaceAll 1 (const "On")) yourList
The const "On" function is used because when we get to our specific element we no longer want to transform it, we just want to replace it with "On". Bit for each individual row we do want to transform it.
| |
doc_3574
|
class IExample { ~IExample(); //pure virtual methods ...};
a class inheriting the interface like
class CExample : public IExample { protected: CExample(); //implementation of pure virtual methods ... };
and a global function to create object of this class -
createExample( IExample *& obj ) { obj = new CExample(); } ;
Now, I am trying to get Java API wrapper using SWIG, the SWIG generated interface has a construcotr like - IExample(long cPtr, boolean cMemoryOwn) and global function becomes createExample(IExample obj )
The problem is when i do,
IExample exObject = new IExample(ExampleLibraryJNI.new_plong(), true /*or false*/ );
ExampleLibrary.createExample( exObject );
The createExample(...) API at C++ layer succesfully gets called, however, when call returns to Java layer, the cPtr (long) variable does not get updated. Ideally, this variable should contain address of CExample object.
I read in documentation that typemaps can be used to handle output parameters and pointer references as well; however, I am not able to figure out the suitable way to use typemaps to resolve this problem, or any other workaround.
Please suggest if i am doing something wrong, or how to use typemap in such situation?
A: I don't know how you'd solve this problem with typemaps; Java doesn't support reference parameters so the conversion would be very complicated.
Why not just have createExample() return an IExample*? If you need the return value for something else, I recommend returning std::pair<IExample*,OtherThing>, or some similar structured type.
| |
doc_3575
|
.item:not(:last-child) {
margin-bottom: 12px;
}
<fieldset class="form-group">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<span class="error-messages"></span>
<span class="help-block"></span>
</fieldset>
In my mind, the expected behavior of this is to select every element besides the last element with the .item class name. However, it's not doing that unless I delete the two span elements at the bottom of fieldset.
When I place the above CSS selector into Chrome's Developer Tools, it selects the last-child as intended but doesn't actually do anything - it's greyed out for some reason.
Can anyone assist me with a solution for selecting all but the last .item element?
A: You need to use last-of-type instead of last-child:
.item:not(:last-of-type) {
margin-bottom: 12px;
border-bottom: 1px solid #999; /*Just to make sure*/
}
<fieldset class="form-group">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<!-- Just to make sure -->
<span class="error-messages">Error Messages Here</span>
<span class="help-block">Help Block Here</span>
</fieldset>
A: Usage of :last-of-type instead of :last-child will resolve your problem. This happens when you wrap elements of other types inside the same parent. In the case of :last-child compiler checks until the end of the file if there's any other element with class .item. So according to the TopDown approach, the code doesn't work as expected. :last-child should maximum be used with elemental styling. Like li:last-child
So Try this:
.item:not(:last-of-type) {
margin-bottom: 12px;
border:2px solid black;
}
<fieldset class="form-group">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<span class="error-messages">It works as expected</span>
<span class="help-block">Now</span>
</fieldset>
| |
doc_3576
|
I want to write a new function:
def some_plot(parameter):
array = []
for n in range(100):
array.append(F(parameter = n))
# make some plot using array
And then I want to make some plot by calling some_plot('par1') (or some_plot(par1)) which both split errors.
Is it possible to pass the name of the parameter as an argument?
A: You can do this by constructing a dictionary and passing it using the ** syntax.
def loop_through(arg_name):
for n in range(100):
F(**{arg_name: n})
A: Supposing that you pass the name of the argument as a string, you can use keyword argument expansion:
def loop_through(parameter):
for n in range(100):
kwargs = {parameter: n}
F(**kwargs)
| |
doc_3577
|
update card_order set valid_until = to_date('23/12/17,Σαβ 11:00πμ', 'YYYY-MM-DD,Day HH:MIa');
But I get the error:
ERROR: invalid value "Σαβ 11" for "Day"
DETAIL: The given value did not match any of the allowed values for this field.
I have setup my db with
*
*Encoding UTF8
*Collation Greek_Greece.1253
*Character type Greek_Greece.1253
A: You'd need to set lc_time to a Greek locale and use the TM modifier as in TMDY.
But that still won't help, because, as the documentation says:
to_timestamp and to_date ignore the TM modifier.
| |
doc_3578
|
#include <dos.h>
#include <conio.h>
void interrupt (*oldTimer)();
void interrupt (*oldKey)();
void interrupt newTimer();
void interrupt newKey();
char far *scr = (char far*) 0xB8000000;
int i, t=0, m=0;
char charscr[4000];
void main()
{
oldTimer=getvect(8);
oldKey=getvect(9);
setvect(8,newTimer);
setvect(9,newKey);
getch();
keep (0,1000);
}
void interrupt newTimer()
{
t++;
if((t>=182)&&(m==0))
{
for (i=0;i<4000;i++)
charscr [i]=*(scr+i);
for (i=0;i<=4000;i+=2)
{
*(scr+i)=0x20;
*(scr+i+1)=0x07;
}
t=0; m=1;
}
(*oldTimer)();
}
void interrupt newKey()
{
int w;
if(m==1)
{
for (w=0; w<4000;w++)
*(scr+w)=charscr[w];
m=0;
}
(*oldKey)();
}
Sorry for my poor indentation. I find it very hard on this site to indent the code.
| |
doc_3579
|
I have a async web api which updates certain fields of a mongo document. It first retrieves the document updates the fields and then saves the document asynchronously to the database. How do I ensure that if the api is called multiple times in succession, one call will not overwrite the results of a previous call ?
public async Task<ActionResult> UpdateAsync(string id , string b)
{
//this queries the mongo db and returns the document
var q = await _mongoService.FindAsync(id);
q.someField = b;
await _mongoService.UpdateAsync(q);
}
When called multiple times, I first get q, then when one of the calls saves q, but then another call to the api can overwrite the first q.
How do i synchronize the finds and updates ?
The following solution works but i am afraid that this is not scalable
static object _locker = new object();
public async Task<ActionResult> UpdateAsync(string id , string b)
{
await Task.Run(() =>
lock (_locker) {
var q = _mongoService.Find(id);
q.someField = b;
_mongoService.Update(q);
}
}
Another option is using a semaphore
private static SemaphoreSlim _mutex = new SemaphoreSlim(1);
public async Task<ActionResult> UpdateAsync(string id , string b)
{
_mutex.WaitAsync();
//this queries the mongo db and returns the document
var q = await _mongoService.FindAsync(id);
q.someField = b;
await _mongoService.UpdateAsync(q);
_mutex.Release()
}
Not sure if these are the best solutions
| |
doc_3580
|
<%= link_to "Link", {:controller => "home", :action => "index", :link=> "www.google.com" }%>
when i press the link i continue to the following action
> def index
> @link = params[:link]
> if @link.present?
> return redirect_to @link
> end
> end
but the action don't redirect me to www.google.com just go to this direction
localhost:3000/?link=www.google.com
how can i go to www.google.com and redirect well ?
A: I just need to specified the protocol in this case http
Now is working with this
<%= link_to "Link", {:controller => "home", :action => "index", :link => "http://www.google.cl" }%>
A: I think that you are looking for this:
<%= link_to "Link", "http://www.google.com" %>
Hope I could help.
| |
doc_3581
|
var filename = "settings.dat";
window.resolveLocalFileSystemURL(cordova.file.dataDirectory + filename, function(f){
f.file(function(file){
var reader = new FileReader();
reader.onloadend = function(){
var data = this.result;
alert("ok");
};
reader.readAsText(file);
}, function(res){
alert(JSON.stringify(res));
});
}, function(res){
alert(JSON.stringify(res));
});
I have no idea why. I tried checking the permission and I have it. The URL is also well formed
| |
doc_3582
|
If I have two columns, and I want to add them together and see if the result is more than something else, how would I do this?
What I have so far:
SELECT COUNT(id)
FROM routes
WHERE destination = :airport
AND end_time+turn_around > :start_time
AND end_time < :start_time
| |
doc_3583
|
Thanks for any help.
A: It depends where you have your grails libraries. If they are part of another application WAR file you will not have issues as you can pack your own libraries in your application WAR. Each application will use it's own copy of grail libraries.
But if you have your grial libraries as a part of system libraries of tomcat (eg. tomcat/lib ) you can have issues as those libraries are added in classpath for all applications.
| |
doc_3584
|
What is the Gradle artifact dependency graph command?
but with a narrower scope. I'm wondering about functionality that Maven has for analyzing dependencies, and whether or not Gradle includes something similar. Specifically, Maven can scan your source code and then compare that to your declared dependencies, and determine (roughly) if you have dependencies declared that you aren't using and/or if you're using dependencies that you haven't declared (due to issues related to Turing completeness, this analysis may include false positives/negatives, but I generally find it to be incredibly useful regardless). Does Gradle have anything similar? So far I haven't been able to find anything.
A: Such a thing is not shipped with Gradle at least as far as I know.
You best bet is to search through Google and / or plugins.gradle.org for finding a plugin that does what you want.
I for a short period did this for you and found this one which might be what you want: https://plugins.gradle.org/plugin/com.intershop.gradle.dependencyanalysis
I have no idea about its quality or anything, I just searched through plugins.gradle.org, I don't know or ever used that plugin.
| |
doc_3585
|
textView = [[UITextView alloc] initWithFrame: CGRectMake(0, 0, 513, 1024)];
It doesn't display any text anymore... 512 works, any size below that too, but anything greater than 512 and it stops displaying any text. The full code:
- (void)loadView {
self.navigationItem.hidesBackButton = YES;
self.view = [[UIView alloc] init];
self.view.backgroundColor = [UIColor blackColor];
RDLocalizedStrings * strings = [RDLocalizedStrings defaultLocalizedStrings];
NSString* message = [strings getStringWithKey: @"noUpdatesAvailableText"];
CGFloat messageFontSize;
RDRectCreate(message);
BOOL iPad = NO;
#ifdef UI_USER_INTERFACE_IDIOM
iPad = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);
#endif
if (iPad) {
RDRectWrite(message, 0, 100, 513, 200);
messageFontSize = 20.0;
} else {
RDRectWrite(message, 0, 0, 320, 480);
messageFontSize = 20.0;
}
textView = [[UITextView alloc] initWithFrame: messageRect];
textView.text = message;
textView.backgroundColor = [UIColor redColor];
textView.textAlignment = UITextAlignmentCenter;
textView.textColor = [UIColor whiteColor];
textView.font = [UIFont systemFontOfSize: messageFontSize];
textView.editable = NO;
[self.view addSubview: textView];
}
A: It seem UIViewAutoresizingFlexibleWidth make ipad's UITextView hide text. Resize with textView.frame=CGRectMake(0,0,768,21) can fix this.
| |
doc_3586
|
I'm learning HTML, CSS, and JS, and I decided to try to make a digital flipbook: a simple animation that would play (ie, load frame after frame) on the user's scroll.
I figured I would add all the images to the HTML and then use CSS to "stack them" in the same position, then use JS or jQuery to fade one into the next at different points in the scroll (ie, increasing pixel distances from the top of the page).
Unfortunately, I can't produce the behavior I'm looking for.
HTML (just all the frames of the animation):
<img class="frame" id="frame0" src="images/hand.jpg">
<img class="frame" id="frame1" src="images/frame_0_delay-0.13s.gif">
CSS:
body {
height: 10000px;
}
.frame {
display: block;
position: fixed;
top: 0px;
z-index: 1;
transition: all 1s;
}
#hand0 {
padding: 55px 155px 55px 155px;
background-color: white;
}
.frameHide {
opacity: 0;
left: -100%;
}
.frameShow {
opacity: 1;
left: 0;
}
JS:
frame0 = document.getElementById("frame0");
var myScrollFunc = function() {
var y = window.scrollY;
if (y >= 800) {
frame0.className = "frameShow"
} else {
frame0.className = "frameHide"
}
};
window.addEventListener("scroll", myScrollFunc);
};
A: One of your bigger problems is that setting frame0.className = "frameShow" removes your initial class frame, which will remove a bunch of properties. To fix this, at least in a simple way, we can do frame0.className = "frame frameShow", etc. Another issue is that frame0 is rendered behind frame1, which could be fixed a variety of ways. ie. Putting frame0's <img> after frame1, or setting frame0's CSS to have a z-index:2;, and then setting frame0's class to class="frame frameHide" so it doesn't show up to begin with. I also removed the margin and padding from the body using CSS, as it disturbs the location of the images. I have made your code work the way I understand you wanted it to, here is a JSFiddle.
A: It depends on your case, for example, in this jsFiddle 1 I'm showing the next (or previous) frame depending on the value of the vertical scroll full window.
So for my case the code is:
var jQ = $.noConflict(),
frames = jQ('.frame'),
win = jQ(window),
// this is very important to be calculated correctly in order to get it work right
// the idea here is to calculate the available amount of scrolling space until the
// scrollbar hits the bottom of the window, and then divide it by number of frames
steps = Math.floor((jQ(document).height() - win.height()) / frames.length),
// start the index by 1 since the first frame is already shown
index = 1;
win.on('scroll', function() {
// on scroll, if the scroll value equal or more than a certain number, fade the
// corresponding frame in, then increase index by one.
if (win.scrollTop() >= index * steps) {
jQ(frames[index]).animate({'opacity': 1}, 50);
index++;
} else {
// else if it's less, hide the relative frame then decrease the index by one
// thus it will work whether the user scrolls up or down
jQ(frames[index]).animate({'opacity': 0}, 50);
index--;
}
});
Update:
Considering another scenario, where we have the frames inside a scroll-able div, then we wrap the .frame images within another div .inner.
jsFiddle 2
var jQ = $.noConflict(),
cont = jQ('#frames-container'),
inner = jQ('#inner-div'),
frames = jQ('.frame'),
frameHeight = jQ('#frame1').height(),
frameWidth = jQ('#frame1').width() + 20, // we add 20px because of the horizontal scroll
index = 0;
// set the height of the outer container div to be same as 1 frame height
// and the inner div height to be the sum of all frames height, also we
// add some pixels just for safety, 20px here
cont.css({'height': frameHeight, 'width': frameWidth});
inner.css({'height': frameHeight * frames.length + 20});
cont.on('scroll', function() {
var space = index * frameHeight;
if (cont.scrollTop() >= space) {
jQ(frames[index]).animate({'opacity': 1}, 0);
index++;
} else {
jQ(frames[index]).animate({'opacity': 0}, 0);
index--;
}
});
** Please Note that in both cases all frames must have same height.
| |
doc_3587
|
bool OSXSpecifics::loadPNGOSX(const char *fileName, int &outWidth, int &outHeight, GLuint *outTexture) {
NSImage *image = [[NSImage alloc] initWithContentsOfFile:[NSString stringWithUTF8String: fileName]];
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithData:[image TIFFRepresentation]];
NSArray* imageReps = [image representations];
bool hasAlpha;
for (NSImageRep *imageRep in imageReps) {
if ([imageRep pixelsHigh] > outHeight) {
outHeight = [imageRep pixelsHigh];
}
if ([imageRep pixelsWide] > outWidth) {
outWidth = [imageRep pixelsWide];
}
}
if ([bitmap hasAlpha] == YES) {
hasAlpha = true;
} else {
hasAlpha = false;
}
glGenTextures(1, outTexture);
glBindTexture(GL_TEXTURE_2D, *outTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, hasAlpha ? 4 : 3, outWidth, outHeight, 0,
hasAlpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, [bitmap bitmapData]);
[bitmap release];
[image release];
return true;
}
Thanks to Instruments I have detected a memory leak every time this function is called. Instruments says [NSImage TIFFRepresentation] and [NSBitmapImageRep bitmapData] are using up a huge amount of memory.
It does not climb out of control but everytime this function is called the memory usage climbs a few hundred kilobytes.
My experience with objective-c is limited and so I do not know how to fix this as I thought release would work fine.
Just so you know the OpenGL texture is freed at a later point and I have confirmed it is not the source of the memory leak.
EDIT: After some further testing I have discovered this is not theoretically a memory leak as Instruments is not reporting a "memory leak" as such. But whenever this function is called the memory usage of the application goes up and never comes down. This function is called when scenes in the game are loaded, and so whenever a scene is loaded memory usage goes up several megabytes. How could this possibly be happening. I am sure it is this function that is using up all the memory.
A: First off: The code doesn't look like it is leaking. My guess is that NSImage is doing some harmless caching internally that ensures it can re-use the same NSImage if you ever load this image file a second time, and that's maybe what you're seeing. Or maybe it's the file system cache. If memory gets tight, these caches will probably get flushed and the freed memory becomes available to your application.
That said, your code seems overly complicated. You create an NSImage (which consists of NSImageReps, one of which is very likely an NSBitmapImageRep) then get its TIFFRepresentation (i.e. re-encode all that data to TIFF, possibly compressing it again), then create an NSBitmapImageRep from that (decompressing and decoding the TIFF again), and then getting its bitmapData.
At the least, you should probably create an NSData from the file and create your NSBitmapImageRep from that. That will skip the entire NSImage creation and TIFF steps.
Even better would probably be if you just went and used the lower-level ImageIO library. Create a CGImageRef from your file, then hand the image's raw, decompressed data off to OpenGL. I vaguely remember there might even be a better way to create an OpenGL texture if you go through CIImage or CoreVideo, but I may be mixing that up with the reverse (texture to CIImage).
| |
doc_3588
|
this is my text file
INFO http-bio-80-exec-1 root - Received data;863071018134228;12.964624;77.523682;NE;23.22376;3.82;0;2013-01-06^08:41:00;
INFO http-bio-80-exec-1 root - RxTracker; IMEINO is 863071018134228
INFO http-bio-80-exec-2 root - RxTracker Invoked. Reading Parameters
INFO http-bio-80-exec-2 root - Received data;863071018134228;12.964624;77.523682;NE;37.66936;3.82;0;2013-01-06^08:42:52;
INFO http-bio-80-exec-2 root - RxTracker; IMEINO is 863071018134228
INFO http-bio-80-exec-5 root - RxTracker Invoked. Reading Parameters
INFO http-bio-80-exec-5 root - Received data;863071018134228;12.964624;77.523682;NE;20.92728;3.82;0;2013-01-06^08:44:51;
INFO http-bio-80-exec-5 root - RxTracker; IMEINO is 863071018134228
INFO http-bio-80-exec-3 root - RxTracker Invoked. Reading Parameters
this is my java code
public void Insert1()
{
try{
File f=new File("E:/c.txt");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
int lineNum = 0;
String line = null;
while ( (line = br.readLine() ) != null ) {
lineNum++;
if(br.readLine().equalsIgnoreCase("RxTracker"))
{
System.out.println("ji");
}
else
{
System.out.println("ji");
}
//if ( lineNum %2 == 0 ) continue;
//else deal with it
System.out.println(br.readLine());
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e1){
e1.printStackTrace();
}
A: Try something like this. The code reads each line of a file and writes it to another file.Every time it checks if that line contains RxTracker If that line doesn't contain the RxTracker then it will write that line to the new file and if it contains that string then it will skip that line,
for eg
String lineToRemove = "RxTracker ;
if(!trimmedLine.contains(lineToRemove)) { // check if t he line does not contains it then write it to another file
writer.write(trimmedLine);
writer.newLine();
}
| |
doc_3589
|
When I receive multiple emails at the same time, it gives me a pathway error.
How do I fix this error so I don't miss emails?
Sub LSPrint(Item As Outlook.MailItem)
On Error GoTo OError
Dim oFS As FileSystemObject
Dim sTempFolder As String
Set oFS = New FileSystemObject
sTempFolder = oFS.GetSpecialFolder(TemporaryFolder)
cTmpFld = sTempFolder & "\OETMP" & Format(Now, "yyyymmddhhmmss")
MkDir (cTmpFld)
Dim oAtt As Attachment
For Each oAtt In Item.Attachments
FileName = oAtt.FileName
FullFile = cTmpFld & "\" & FileName
oAtt.SaveAsFile (FullFile)
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(0)
Set objFolderItem = objFolder.ParseName(FullFile)
objFolderItem.InvokeVerbEx ("print")
Next oAtt
If Not oFS Is Nothing Then Set oFS = Nothing
If Not objFolder Is Nothing Then Set objFolder = Nothing
If Not objFolderItem Is Nothing Then Set objFolderItem = Nothing
If Not objShell Is Nothing Then Set objShell = Nothing
OError:
If Err <> 0 Then
MsgBox Err.Number & " - " & Err.Description
Err.Clear
End If
Exit Sub
End Sub
A: I suppose the following line of code fails:
Set objFolderItem = objFolder.ParseName(FullFile)
Make sure the file path string is well-formed and doesn't contain forbidden symbols. Don't forget to specify the filename with an extension.
| |
doc_3590
|
0x21 0x32 0xCC 0x00 0x3A 0x98 0x02 0x12 0x03 0x21 0x33 0x01 0xC2
I initially believed that the first byte was the Magic Number and the second byte was the Key. So wouldn't that make the numbers 0xCC 0x00 0x3A 0x98 0x02 0x12 0x03 0x21 0x33 0x01 0xC2 the value that we're reading from the microcontroller which we just combined all of the numbers in order to get the following reading in decimal value: 204058... and on?
And for the time stamp don't we just convert the second byte which is 0x32 to decimal which is 50 unites of time?
A: Quoting comment:
on the documentation it mentioned that the payload was a key-value pair and 0x32 was for "timestamp, 4-byte integer, milliseconds since reset" and 0x33 "potentiometer reading, 2-byte integer A/D counts" so does that mean the next time I hit 0x32 which is the second number and since its a 4-byte integer we concatonate 0xCC and 0x00 0x3A and 0x98?
Quoting example data from question:
0x21 0x32 0xCC 0x00 0x3A 0x98 0x02 0x12 0x03 0x21 0x33 0x01 0xC2
So, key/value pairs, where the key is a single byte, and each key has values of differing length.
0x32 was for "timestamp, 4-byte integer, milliseconds since reset"
0x21 0x32 0xCC 0x00 0x3A 0x98 0x02 0x12 0x03 0x21 0x33 0x01 0xC2
^^^^ ^^^^^^^^^^^^^^^^^^^
key 4-byte integer
Those 4 bytes can be big-endian or little-endian, but big-endian is more common for devices, so:
0xCC003A98 = 3422567064 ms = 39 days 14 hrs 42 mins 47.064 secs
0x33 "potentiometer reading, 2-byte integer A/D counts"
0x21 0x32 0xCC 0x00 0x3A 0x98 0x02 0x12 0x03 0x21 0x33 0x01 0xC2
^^^^ ^^^^^^^^^
key 2-byte integer
0x01C2 = 450
| |
doc_3591
|
If I create a non TF-managed instance in a VPC (that I did create with terraform) and then do a terraform destroy TF hangs waiting.
I can then go to AWS console and manually delete the VPC and get a useful response from AWS as to why it cant be deleted and a list of the offending resources I can manually delete.
Is there a verbose switch where Terraform would spit out these messages from the AWS API? I assume the AWS API returns this info, but perhaps it only does that when deleting via the console?
I haven't found any info on how to make the TF destroy command return this info so assuming it's probably not possible but wanted to confirm.
A: You can get more information from terraform by setting the TF_LOG variable before executing terraform. There are a few levels of logging, which should look familiar if you are familiar with syslog severity levels (i.e. INFO, WARN, ERROR ,etc..). Setting this variable is a very useful debugging strategy.
Setting TF_LOG=DEBUG should at least let you determine which AWS api calls are being called. In my experience with terraform, it's not uncommon for an api call to fail; and terraform sometimes won't report an error, hangs, or does report an error but the information is archaic at best. This is something the terraform community is working on. And there are current github issues open to similar behavior
If after setting the TF_LOG environment variable, the api call is indeed failing, I suggest that you open a github issue with terraform; and please format it using the issues contributing guidelines
| |
doc_3592
|
Can it be done?
My XML
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".TeacherFullActivity"
tools:showIn="@layout/app_bar_teacher_full">
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
layout="@layout/listview_element_teachers"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/job_title"
style="@style/TitleMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/teacher_job_title" />
<android.support.v7.widget.RecyclerView
android:id="@+id/job_dynamic"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/subject_title"
style="@style/TitleMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/teacher_subject_title" />
<android.support.v7.widget.RecyclerView
android:id="@+id/subject_dynamic"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/workPlace_title"
style="@style/TitleMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/teacher_workplace_title" />
<android.support.v7.widget.RecyclerView
android:id="@+id/workplace_dynamic"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:paddingLeft="35dp"
android:paddingTop="5dp"
android:paddingRight="35dp"
android:paddingBottom="5dp">
<Button
android:id="@+id/teacher_external_link"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/btn_rounded"
android:text="@string/open_link"
android:textAllCaps="false"
android:textColor="@android:color/white"
android:textSize="17sp"
android:textStyle="bold"
/>
</FrameLayout>
</LinearLayout>
</ScrollView>
</android.support.constraint.ConstraintLayout>
A: You can use the android:fillViewport attribute of ScrollView to accomplish this.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
</FrameLayout>
</LinearLayout>
</ScrollView>
What this does is make it so that, in the case where the contents of the LinearLayout are not large enough to fill the screen, the LinearLayout is stretched to fill the screen anyway. That gives the FrameLayout room to grow (based on its layout_weight attribute), which in turn lets the Button float to the bottom of the screen (because of its layout_gravity attribute).
In cases where the contents of the LinearLayout are larger than the screen, no stretching happens. The button is pushed off-screen, but appears when you scroll down (with no space between it and the text).
A: You can try this code for your approach:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".TeacherFullActivity"
tools:showIn="@layout/app_bar_teacher_full">
<ScrollView
android:id="@+id/scrollview"
android:layout_width="0dp"
android:layout_height="0dp"
app:constraintTop_toTopOf="parent"
app:constraintStart_toStartOf="parent"
app:constraintEnd_toEndOf="parent"
app:constraintBottom_toTopOf="@id/frame">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
layout="@layout/listview_element_teachers"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/job_title"
style="@style/TitleMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/teacher_job_title" />
<android.support.v7.widget.RecyclerView
android:id="@+id/job_dynamic"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/subject_title"
style="@style/TitleMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/teacher_subject_title" />
<android.support.v7.widget.RecyclerView
android:id="@+id/subject_dynamic"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/workPlace_title"
style="@style/TitleMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/teacher_workplace_title" />
<android.support.v7.widget.RecyclerView
android:id="@+id/workplace_dynamic"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
</ScrollView>
<FrameLayout
android:id="@+id/frame"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingLeft="35dp"
android:paddingTop="5dp"
android:paddingRight="35dp"
android:paddingBottom="5dp"
app:constraintTop_toBottomOf="@id/scrollview"
app:constraintStart_toStartOf="parent"
app:constraintEnd_toEndOf="parent"
app:constraintBottom_toBottomOf="parent">
<Button
android:id="@+id/teacher_external_link"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/btn_rounded"
android:text="@string/open_link"
android:textAllCaps="false"
android:textColor="@android:color/white"
android:textSize="17sp"
android:textStyle="bold"
/>
</FrameLayout>
</android.support.constraint.ConstraintLayout>
Explaination:
What i did was took FrameLayout containing Button out side of ScrollView so that it can always be at bottom of the Container.
| |
doc_3593
|
I asked this question earlier this year, and I have tried using the upvoted answer to make a bucket policy, which is precisely as shown in that answer, as:
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"POST",
"GET",
"PUT",
"DELETE",
"HEAD"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]
When I try this, I get an error that says:
Ln 1, Col 0Data Type Mismatch: The text does not match the expected
JSON data type Object. Learn more
The Learn More link goes to a page that suggests I can resolve this error by updating text to use the supported data type. I do not know what that means in this context. I don't know how to find out which condition keys require which type of data.
Resolving the error
Update the text to use the supported data type.
For example, the Version global condition key requires a String data
type. If you provide a date or an integer, the data type won't match.
Can anyone help with current instructions for how to create the CORS permissions that are consistent with the spirit of the instructions in the github readme for the repo?
| |
doc_3594
|
However, I am encountering a problem when I try to print the name of the current user above the table in the web view.
Does anyone know how to do this in MVC 5 using the razor view?
This is the code I am using to get the current user from the system:
public string getUserName()
{
displayName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
return displayName;
}
And the view I am currently working on:
@model IEnumerable<BUUK.BSS.Models.User>
@{
ViewBag.Title = "MyTeam";
}
<h2>@ViewBag.Title</h2>
<h3>@ViewBag.Message</h3>
<p>
ViewBag.Title = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
@*<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>*@
</tr>
}
</table>
A: If you simply want to print the name in a view, you should do it like this:
<p>
@System.Security.Principal.WindowsIdentity.GetCurrent().Name
</p>
| |
doc_3595
|
EDIT: I really mean String.hashCode() rather than the more general Object.hashCode(), which of course can be overridden.
A: No. From http://tecfa.unige.ch/guides/java/langspec-1.0/javalang.doc1.html:
The general contract of hashCode is as
follows:
*
*Whenever it is invoked on the same object more than once during an
execution of a Java application,
hashCode must consistently return the
same integer. The integer may be
positive, negative, or zero. This
integer does not, however, have to
remain consistent from one Java
application to another, or from one
execution of an application to another
execution of the same application.
[...]
A: It depends on the type:
*
*If you've got a type which hasn't overridden hashCode() then it will probably return a different hashCode() each time you run the program.
*If you've got a type which overrides hashCode() but doesn't document how it's calculated, it's perfectly legitimate for an object with the same data to return a different hash on each run, so long as it returns the same hash for repeated calls within the same run.
*If you've got a type which overrides hashCode() in a documented manner, i.e. the algorithm is part of the documented behaviour, then you're probably safe. (java.lang.String documents this, for example.) However, I'd still steer clear of relying on this on general principle, personally.
Just a cautionary tale from the .NET world: I've seen at least a few people in a world of pain through using the result of string.GetHashCode() as their password hash in a database. The algorithm changed between .NET 1.1 and 2.0, and suddenly all the hashes are "wrong". (Jeffrey Richter documents an almost identical case in CLR via C#.) When a hash does need to be stored, I'd prefer it to be calculated in a way which is always guaranteed to be stable - e.g. MD5 or a custom interface implemented by your types with a guarantee of stability.
A: According to the docs: the hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
I am not certain whether this is a formal specification or just Sun's implementation. At the very least, it should be the same on all existing Sun VMs, regardless of platform or operating system.
A: No. Hash algorithms are not guaranteed, unless otherwise specified. So for instance, deserialisation of hash structures need to recalculate hash codes, and these values should not be stored in the serialised form.
A: I would like to add that you can override hashCode() (don't forget equals() if you do that) to make sure your business objects return the same hashCode everywhere. Those objects will then at least have a predictable hashCode.
| |
doc_3596
|
for (var i = 0; i <= intNum; i++) {
getData1(url1, true).then(function() {
getData2(url2, true).then(function() {
fnc1(i);
getData3(url3, true).then(function() {
getData4(url4, true).then(function() {
fnc2(i);
})
})
})
})
}
fnc3();
All four getData functions do some operations and then return a promise.
function getData() {
var oModel = new JSONModel();
return oModel.loadData(url, true); //asynchronous loading data and returns a promise
}
Any solution how can I make it work? Any help appreciated. Thanks
A: you are turning promises in a callback hell, return each promise and chain it with then properly. use let instead of var also at for loop, var is not block scoped. you could add an if statement at last then block to run fn3:
for (let i = 0; i <= intNum; i++) {
getData1(url1, true)
.then(() => getData2(url2, true))
.then(() => {
fnc1(i)
return getData3(url3, true)
})
.then(() => getData4(url4, true))
.then(() => {
fnc2(i)
if(i === intNum) fnc3()
})
}
| |
doc_3597
|
The queue is consumed by the application with other deferreds. The problem is I want to consume the queue elements not by order of addition but give higher priority to some elements based on the element field content.
My current (probably faulty) idea was to have a generator which executes a sql select which produces a results set with in the proper priority and iterate over this result to generate deferreds. The problem is, while the generator is iterating over the result set further elements may have been added to the queue by deferreds.
Is there a way to do this without executing a new select every time the generator is called? I.e. can the "result set" and the iterator cursor be automatically be "updated"?
If not, how would you implement this?
A: The Queue module has a PriorityQueue class which may meet your needs.
A: Why not use a Python list, using the module "heapq" from the stdlib to keep it in priority order? (Your list elements would be tuples with (priority, time_of_insertion, objects) - and since tthe data is kept in normal Python list, you can pass it around with no issues within a twisted app.
I think it would be easier than using sqlite if all that you need is sort by priority.
(In this answer I place an example usage of heapq that could help:
heapq with custom compare predicate )
| |
doc_3598
|
I have a .NET application which uses threads excessively. At the time of exit the process does not kill itself. Is there is any tool that can show what is causing the problem? although I have checked thoroughly but was unable to find the problem.
Abdul Khaliq
A: See: Why doesn't my process terminate even after main thread terminated
A: That means you have some foreground thread running. A .net application will not terminate unless all the foreground threads complete execution.
You can mark threads as Background Threads and then check (Thread.IsBackground property). Please note that all background threads terminate immediately when application exits. If you are doing some important work in those threads like serializing data to database then you should keep them as foreground threads only. Background threads are good for non critical things like spell cheker etc.
A: Normally, attaching with a debugger should tell you what threads are still active and what code is running on them.
| |
doc_3599
|
It's a generic implementation of System.Configuration.ConfigurationElementCollection
It's stored in our solutions', Project.Utility.dll but I've defined it as being part of the System.Configuration namespace
namespace System.Configuration
{
[ConfigurationCollection(typeof(ConfigurationElement))]
public class ConfigurationElementCollection<T> :
ConfigurationElementCollection where T : ConfigurationElement, new()
{
...
}
}
Is putting classes in the System.* namespaces considered bad practice when they aren't part of the System.* Base Class Libraries ?
On the face of it, it seems to make sense, as it keeps similar classes with similar functionality in the same place. However it could cause confusion for someone who didn't realise it was actually part of a non .net BCL as they wouldn't know where to go hunting for the reference.
A: While your class is similar it is still not part of the BCL. I would not put it in System.* because of this. It will cause confusion especially when one goes to use it and they have System.* referenced and then get a nasty can't find message when they go to use your class.... :-)
A: I'd recommend either replacing System by your company/project name or prefixing the namespace with your company/project name.
That way you make it clear that it's not part of the BCL, but exactly how it's related to them.
Also in the (admittedly unlikely) event Microsoft ever implement these classes/methods with exactly the same names you won't get a clash.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.