id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23538300
|
*
*I came to know that Babel is going to convert the ECMAScript2015+ code and the JSX code to ECMAScript2015 so that the browser will understand it. So does this translation will happen when we compile the React project using "npm"? And if it happens during the compilation, does the Babel will convert the entire code in the whole project at a time (or) will Babel converts the file which is requested by the client?
*Once after creating and developing the React code, we are using Node software to install all the required dependent libraries which are used in our React code and also "npm start" command to start the react application. So here I want to know if NodeJS is the server which runs the React applications and without NodeJS we cannot run React application as a standalone?
*When we take Java based web application, that Java application will be running in a server computer and Jboss or Websphere Application Server etc... are responsible of running the Java web application EAR project. Then when a client makes a request to any resource in the EAR, then the server will take the request and send the response as an HTML to the client.
In the same way I want to know how this request response cycle works in React Application? For example, if the react application is running in a server computer and NodeJS has started the React Application in the sever computer, then when the client invokes the React application using the URL corresponding to the React Project, then what the server is going to send back to the client/browser? As Babel will convert the React application to the plain JavaScript (which is understandable to the Browser) and so does the server will be returning the Javascript back to the client?
*If the server returns the Javascript code to the client/browser, will the server returns back the Javascript code of the entire React project (all files) to the client or will the server returns the Javascript version of ONLY the request file?
A: React is a front-end library, which runs in the browser. Like any other frontend library (jQuery, etc), it is happy to be served by any old webserver – Apache, NGINX.
The react application will communicate with the backend in the form of REST API calls, which will only produce the dynamic data rather than the HTML.
The HTML is drawn using the JSX on the frontend (https://reactjs.org/docs/introducing-jsx.html)
A: *
*The compilation happens every time you start your project (say npm start) or, if the project is already running, on any saved changes, it will recomplile every time as well as give you any errors found during compilation.
*Yes, the NodeJS will be the one serving content. Technically, you can still use React as standalone. See This tidbit in official ReactJS Documentation
*I'm not really great with technicalities behind React inner workings, so anyone competent feel free to correct me on this, but your server will serve JavaScript code to your browser already working and compiled fully so that even if the React server stops running (terminated or any other reason), you will still be able to work with most of the application since the data has been already loaded. There may be libraries/packages that allow lazy loading of components, but that depends on your usecase, I guess.
*See my final bits in the previous point.
Hope this helped you in some way
| |
doc_23538301
|
$('#gammaSlider').slider({
max: 125,
min: -125,
value: 0,
slide: function () {
//stuff to adjust gamma of image
},
change: function () {
//stuff to adjust gamma of image
}
});
However, when the user loads a different image, I want to programmatically set the slider to the value it should be at for the new image (a.k.a. allow flipping back and forth between multiple pages with separate gamma settings). To be clear, the newly loaded image's gamma is already at whatever value it was last set to. I am only seeking to adjust the UI to match the new image's value. For instance, if I increase page 2's gamma, then flip to page 1, I need to move the slider back to default from its increased position, and I need to do it without the code thinking I'm trying to decrease the gamma.
When I do this using the following, there's a problem:
$('#gammaSlider').slider('value', gamma);
The problem is that this is triggering the slide and change calls that I set up for the slider in the original declaration above, causing it to try to reload the image redundantly with new gamma values. Is there a way to change the slider programmatically WITHOUT triggering those calls?
A: You can use the fact that you can differentiate between a user change and a programmatic change via event.originalEvent. For example, you can have code that gets executed when the user makes a change, and different code that gets executed when you make a programmatic change like changing the value. Since changing the value will trigger the slider's change event, you can put your gamma change code within the block that only is triggered on a user's change, not a programmatic change:
change: function (event) {
if (event.originalEvent) {
//stuff to adjust gamma of image ONLY WHEN USER CHANGES THE SLIDER
console.log('user change');
}
}
You can see in this jsFiddle example that the slider's value is changed to 50, yet no log message is generated unless the user moves the slider. If you comment out the if condition you'll see the log message gets generated not only after the user changes the slider's value, but when you make a change to the value programmatically.
A: Maybe you can call the slider method passing a new configuration, which probably would be exactly the same object you are passing as parameter, but with the "value" field changed.
I have done a test in one of my old projects and it worked for me.
| |
doc_23538302
|
I did have Joomla 3 installed at example.com/joomla.
Now example.com/joomla loads a Wordpress 404 for some reason.
Even example.com/joomla/index.php loads a Wordpress 404.
I can see the Joomla files are intact in the /joomla folder, and configuration.php contains the correct db details. I can see in phpMyAdmin the db is intact.
When I checked .htaccess in the /joomla folder it was called htaccess.txt. Renaming this to .htaccess did not resolve the problem.
How can I ensure the Joomla 3 website runs properly again from a sub-directory where Wordpress is installed in the root domain?
Thanks in advance.
Update: this is the .htaccess in the web root. The /joomla-folder has a default Joomla .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/?wp\-content/+debug\.log$
RewriteRule .* - [F,L,NC]
</IfModule>
<IfModule !mod_rewrite.c>
<Files "debug.log">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
</Files>
</IfModule>
# BEGIN litespeed noabort
<IfModule rewrite_module>
RewriteEngine On
RewriteRule .* - [E=noabort:1]
</IfModule>
# END litespeed noabort
# Redirect HTTP to HTTPS
<IfModule rewrite_module>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>
# BEGIN W3TC Browser Cache
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/bmp application/java application/msword application/vnd.ms-fontobject application/x-msdownload image/x-icon image/webp application/json application/vnd.ms-access application/vnd.ms-project application/x-font-otf application/vnd.ms-opentype application/vnd.oasis.opendocument.database application/vnd.oasis.opendocument.chart application/vnd.oasis.opendocument.formula application/vnd.oasis.opendocument.graphics application/vnd.oasis.opendocument.presentation application/vnd.oasis.opendocument.spreadsheet application/vnd.oasis.opendocument.text audio/ogg application/pdf application/vnd.ms-powerpoint image/svg+xml application/x-shockwave-flash image/tiff application/x-font-ttf application/vnd.ms-opentype audio/wav application/vnd.ms-write application/font-woff application/font-woff2 application/vnd.ms-excel
<IfModule mod_mime.c>
# DEFLATE by extension
AddOutputFilter DEFLATE js css htm html xml
</IfModule>
</IfModule>
<FilesMatch "\.(html|htm|rtf|rtx|svg|txt|xsd|xsl|xml|HTML|HTM|RTF|RTX|SVG|TXT|XSD|XSL|XML)$">
<IfModule mod_headers.c>
Header append Vary User-Agent env=!dont-vary
</IfModule>
</FilesMatch>
<FilesMatch "\.(bmp|class|doc|docx|eot|exe|ico|webp|json|mdb|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|pot|pps|ppt|pptx|svg|svgz|swf|tif|tiff|ttf|ttc|_ttf|wav|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|BMP|CLASS|DOC|DOCX|EOT|EXE|ICO|WEBP|JSON|MDB|MPP|OTF|_OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|POT|PPS|PPT|PPTX|SVG|SVGZ|SWF|TIF|TIFF|TTF|TTC|_TTF|WAV|WRI|WOFF|WOFF2|XLA|XLS|XLSX|XLT|XLW)$">
<IfModule mod_headers.c>
Header unset Last-Modified
</IfModule>
</FilesMatch>
# END W3TC Browser Cache
# BEGIN W3TC Page Cache core
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^(.*\/)?w3tc_rewrite_test([0-9]+)/?$ $1?w3tc_rewrite_test=1 [L]
RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteRule .* - [E=W3TC_ENC:_gzip]
RewriteCond %{HTTP_COOKIE} w3tc_preview [NC]
RewriteRule .* - [E=W3TC_PREVIEW:_preview]
RewriteCond %{REQUEST_METHOD} !=POST
RewriteCond %{QUERY_STRING} =""
RewriteCond %{REQUEST_URI} \/$
RewriteCond %{HTTP_COOKIE} !(comment_author|wp\-postpass|w3tc_logged_out|wordpress_logged_in|wptouch_switch_toggle) [NC]
RewriteCond "%{DOCUMENT_ROOT}/wp-content/cache/page_enhanced/%{HTTP_HOST}/%{REQUEST_URI}/_index%{ENV:W3TC_PREVIEW}.html%{ENV:W3TC_ENC}" -f
RewriteRule .* "/wp-content/cache/page_enhanced/%{HTTP_HOST}/%{REQUEST_URI}/_index%{ENV:W3TC_PREVIEW}.html%{ENV:W3TC_ENC}" [L]
</IfModule>
# END W3TC Page Cache core
# BEGIN WordPress
<IfModule rewrite_module>
RewriteEngine On
RewriteRule ^(dynamic-keyword-plugin-joomla)($|/) - [L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>
# END WordPress
# Wordfence WAF
<IfModule LiteSpeed>
php_value auto_prepend_file '/home/doigwebsite/public_html/wordfence-waf.php'
</IfModule>
<Files ".user.ini">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
</Files>
# END Wordfence WAF
# BEGIN MainWP
# END MainWP
#<IfModule mod_fcgid.c>
#MaxRequestLen 31457280
#</IfModule>
FileETag None
Header unset ETag
Header unset Pragma
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
Update2: Joomla is now working. I believe it might be caused by my own confusion around hosting arrangements - there was a transfer of host recently.
Apologies.
A: Add the following to the .htaccess file in the root of your WordPress install, immediately after the line with RewriteEngine On:
RewriteRule ^(joomla)($|/) - [L]
For instance:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
...
Becomes
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(joomla)($|/) - [L]
...
This prevents WordPress from loading only when the requested path begins with /joomla/.
A: If you have installed the nginx on your server, you can use the following code and add it to your server block just before closing of server block.
location = / {
try_files $uri $uri/joomla-directory /joomla-directory/index.php?$args;
}
location /joomla-directory {
index index.php;
try_files $uri $uri/ /joomla-directory/index.php?$args;
}
Hope this will help.
If you are on shared hosting, please paste your htaccess in your WordPress root installation, and also the directory structure.
A: <IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(joomla)($|/) - [L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule> # END WordPress
| |
doc_23538303
|
Does anyone have any ideas on how to accomplish this? I am in a corporate environment and unfortunately cannot tinker with any config files.
If it matters, we are using Oracle RDS and Java.
Thanks
A: There is no way to do this without access to the RDS cli.
| |
doc_23538304
|
INTERNAL_STATES = (
('1', _('Live')),
('2', _('Coming soon')),
('3', _('Draft')),
)
View:
if request.user.is_staff is False and building.internal_state is not 1:
raise Http404
else:
pass
Can someone tell me why this code is landing me a 404 even if the building I am trying to view has internal_state = 1 when I am not logged in? Sorry for posting such an easy question but I just can't see what's wrong with it.
A: The type of internal_state is a string, not an integer.
Try this:
if not request.user.is_staff and building.internal_state != '1':
raise Http404
else:
pass
A: Comparing with 'is' operator can be dangerous even with integer numbers. In CPython realization, you can check that if you type:
a = 1
b = 1
a is b
#True
but if you type something like this:
a = -6
b = -6
a is b
#False
It a matter of fact that 'is' operator compares not values but the addresses in memory.
That's my 50 cent.
| |
doc_23538305
|
However, SpriteKit doesn't seem to expose a render method, so I'm trying to determine the best game-loop method for our custom rendering to occur in. As far as I can tell, the update method is the only gameloop method SpriteKit exposes.
A: Sprite Kit does not allow direct access to OpenGL so far. It is intended to be simple engine for beginners.
| |
doc_23538306
|
Background, I have a fairly complex query that users can build N times and then submit all of those queries at once. The N queries all return the same formatted result set but have wildly different WHERE clauses.
I could use an SPROC to generate dynamic sql statements based on their input or execute each query seperately and process it in the code, but there's got to be a better way to do it. Is there an optimal solution to this problem?
A: As long as the queries all return the same formatted result, you can just union them together and use order by to sort the result
select col1, col2, col3 from tablea where ...
union
select col1, col2, col3 from tablea where ...
order by col1, col2
If you care about knowing which query returned the result, you would need to add an extra column that indicated the query.
Depending on the size of the N number of queries that are generated, there could also be issues with the size of the total union query. I ran into issues with JDBC limiting the size of the query when trying to combine many queries this way and wound up doing individual database calls and merging the results in java code.
| |
doc_23538307
|
When I try to open this doc on my version of Lyx on my Mac, I get the error "[filename] is from a newer version of LyX and the lyx2lyx script failed to convert it."
I am not eager to update my version of Lyx because I'm worried all my older files won't be readable.
But perhaps reading older files is fine, it's just reading newer files that doesn't work.
Any advice would be appreciated.
Thanks,
N
A: The last version of a LyX major release can open files from the next LyX version. So LyX 2.0.8 can open LyX 2.1.x files. That might be a reasonable choice for you to make. If you do this, you should install 2.0.8.1. Upgrading from 2.a.x to 2.a.y, where y > x, will not give you any features or change any core thing in LyX (like the file format) but will give you bug fixes. The Mac download for 2.0.8.1 is here: ftp://ftp.lyx.org/pub/lyx/bin/2.0.8.1/LyX-2.0.8.1-B+qt4-carbon.dmg
You are right to be concerned about upgrading LyX versions. Upgrades bring features but also possibly bugs so it is good to be careful. However, when you are at a good point in your work you should consider upgrading from time to time. LyX can usually open older files in newer versions of LyX. There are some problems (if you find one, please report a bug), but most of the time it works. Although I use Linux, I imagine Mac is similar in that if you do not like the new version of a software it's very easy to reinstall the older version. Also I don't know for Mac, but on Linux it's straightforward to have parallel installs of multiple versions in a way that neither affects the other. I have 2.0.8.1, 2.1.2, and 2.2dev all installed.
If you and your friend are going to be trading files a lot (e.g. several revisions), I would recommend installing 2.1.3, which will be released in a week or two.
When posting about software, please always state their versions. Thanks for stating the OS, that's important too.
| |
doc_23538308
|
When button is clicked, menu should open and background change to red.
When button is clicked again, menu should close and background change to green.
http://test.bsley.com/rest/menu3/
Any help would be much appreciated!
jQuery:
$(document).ready(function() {
$("#trigger").click(function() {
if ($(this).css('background-color') == 'red') {
alert("test");
} else {
$("#panel").slideDown("fast");
$("body").css( "background-color", "red" );
}
});
});
HTML:
<div id="panel">Here is the menu</div> <div id="trigger">+ Menu</div>
A: this in click callback refer to button element, not body element.
try this code
$(document).ready(function() {
$("#trigger").click(function() {
var $btn = $(this);
if ($(this).hasClass('opened')) {
$('body').css("background-color", "green");
} else {
$('body').css("background-color", "red");
}
$('#panel').slideToggle('fast', function() {
$btn.toggleClass('opened');
});
});
});
http://jsfiddle.net/CthzA/6/
A: Simple reason is that the css method isn't returning the same as you set it too, it's returning and rgb value rather than the string "red".
Here's what I would have done:
$(document).ready(function() {
$("#trigger").click(function() {
if ( $('#panel').is(':visible') ) {
$("#panel").slideUp("fast");
$("body").css( "background-color", "white" );
} else {
$("#panel").slideDown("fast");
$("body").css( "background-color", "red" );
}
});
});
JSBin example
I'm not checking for the colour but whether the menu area is visible or not. Read about the is method here: jQuery docs
Also, it's worth mentioning you can just attach as many on event listeners to an element as you like - so you can do this and all of it will run when #trigger is clicked:
$('#trigger').on('click', function() { /*show/Hide the menu*/ })
$('#trigger').on('click', function() { /*change the background colour*/ })
$('#trigger').on('click', function() { /*do more stuff*/ })
Good luck getting it all working!
A: DEMO
var i = 0;
$('#trigger').click(function () {
var color;
if (i++ % 2 == 0) {
color = "red";
} else {
color = "green";
}
$('body').css('background-color', color);
$('#panel').slideToggle();
});
References
http://api.jquery.com/css/
http://api.jquery.com/toggle/
A: Try this code:
HTML
<div id="panel">Here is the menu</div> <div id="trigger">+ Menu</div>
JS
$(document).ready(function() {
$("#trigger").click(function() {
if ($(this).css('background-color') == 'red') {
alert("test");
} else {
$("#panel").slideDown("fast");
$("body").css( "background-color", "red" );
}
});
});
var i = 0;
$('#trigger').click(function () {
var color;
if (i++ % 2 == 0) {
color = "red";
} else {
color = "green";
}
$('body').css('background-color', color);
$('#panel').toggle();
});
| |
doc_23538309
|
I have tried following the answer provided by Victor in the following post:
How to change MySQL data directory?
(I have also edited the alias file as per the instruction from mak in the comments on Victor's answer).
BUT, I am getting the following terminal error when trying to start MySQL again:
mysql.serviceJob for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details.
When inspecting the log file using below command
tail -f /var/log/mysql/error.log
It shows the following:
2016-05-23T13:43:11.608141Z 0 [ERROR] Plugin 'InnoDB' init function returned error.
2016-05-23T13:43:11.608234Z 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2016-05-23T13:43:11.608252Z 0 [ERROR] Failed to initialize plugins.
2016-05-23T13:43:11.608260Z 0 [ERROR] Aborting
2016-05-23T13:43:11.608297Z 0 [Note] Binlog end
2016-05-23T13:43:11.608416Z 0 [Note] Shutting down plugin 'MyISAM'
2016-05-23T13:43:11.608469Z 0 [Note] Shutting down plugin 'CSV'
2016-05-23T13:43:11.609124Z 0 [Note] /usr/sbin/mysqld: Shutdown complete
My my.cnf file looks as follows (I omitted the initial comments ##):
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/
[mysqld]
datadir=/home/dev/Desktop/iiab/db/mysql
socket=/home/dev/Desktop/iiab/db//mysql.sock
My /etc/apparmor.d/usr.sbin.mysqld file looks as follows (I only included the parts which were affected by the instructions i.e. replace var/lib/mysql with the new path).
# Allow data dir access
/home/dev/Desktop/iiab/db/mysql/ r,
/home/dev/Desktop/iiab/db/mysql/** rwk,
# Allow data files dir access
/home/dev/Desktop/iiab/db-files/ r,
/home/dev/Desktop/iiab/db-files/** rwk,
# Allow keyring dir access
/home/dev/Desktop/iiab/db-keyring/ r,
/home/dev/Desktop/iiab/db-keyring/** rwk,
My /etc/apparmor.d/tunables/alias file looks as follows (I omitted initial comments ##):
# Or if mysql databases are stored in /home:
alias /var/lib/mysql/ -> /home/dev/Desktop/iiab/db/mysql/,
I am able to restart and reload apparmor successfully.
I'm using Ubuntu 16.04.
Anyone know what I am doing wrong?
| |
doc_23538310
|
import csv
import re
with open('alcohol_rehab_ltp.csv', 'rb') as csv_f, \
open('cities2.txt', 'rb') as cities, \
open('drug_rehab_city_state.csv', 'wb') as out_csv:
writer = csv.writer(out_csv, delimiter = ",")
reader = csv.reader(csv_f)
city_lst = cities.readlines()
for row in reader:
for city in city_lst:
city = city.strip()
match = re.search((r'\b{0}\b').format(city), row[0])
if match:
writer.writerow(row)
break
"alcohol_rehab_ltp.csv" has 145 lines, and "cities2.txt" has 18,895 lines (which becomes 18,895 when converted to the list). It takes a while for this process to run, I haven't timed but maybe around 5 minutes. Is there something simple (or more complex) that I am overlooking here, that could make this script run more quickly. I will be using other .csv files to run against the large text file of "cities.txt", and these csv files may have anywhere up to 1000 lines. Any ideas on how to speed things up would be appreciated!
Here is csv file:Keywords (144),Avg. CPC,Local Searches,Advertiser Competition
[alcohol rehab san diego],$49.54,90,High
[alcohol rehab dallas],$86.48,110,High
[alcohol rehab atlanta],$60.93,50,High
[free alcohol rehab centers],$11.88,110,High
[christian alcohol rehab centers],–,70,High
[alcohol rehab las vegas],$33.40,70,High
[alcohol rehab cost],$57.37,110,High
some lines from text file:
san diego
dallas
atlanta
dallas
los angeles
denver
A: I think you can use a set and indexing:
with open('alcohol_rehab_ltp.csv', 'rb') as csv_f, \
open('cities2.txt', 'rb') as cities, \
open('drug_rehab_city_state.csv', 'wb') as out_csv:
writer = csv.writer(out_csv, delimiter = ",")
space = ""
reader = csv.reader(csv_f)
# make set of all city names, lookups are 0(1)
city_set = {line.rstrip() for line in cities}
output_list = []
header = next(reader) # skip header
for row in reader:
try:
# names are either first or last with two words preceding or following
# so split twice on whitespace from either direction
if row[0].split(None,2)[-1].rstrip("]") in city_set or row[0].rsplit(None, 2)[0][1:] in city_set:
output_list.append(row)
except IndexError as e:
print(e,row[0])
writer.writerows(output_list)
Running time is now 0(n) as opposed to quadratic.
A: First, as @Shawn Zhang suggests (r'\b{0}\b').format(c.strip()) can be outside loop, and you can create result list, to avoid writing to file in each iteration.
Second, you might try re.compile to compile regular expression, that might improve your performance on regular expression.
Third, try to profile it a little bit to find the bottleneck, e.g. with timeit or other profiler like ica if you have SciPy.
Also, if city is always in first column, and I assume that it's named 'City' why don't you use csv.DictReader() to read csv? I'm sure it's faster than regular expression.
EDIT
As you provided example of your file I get rid of re (because it seems you really don't need them), and got that more than 10 time faster with code as below:
import csv
with open('alcohol_rehab_ltp.csv', 'rb') as csv_f, \
open('cities2.txt', 'rb') as cities, \
open('drug_rehab_city_state.csv', 'wb') as out_csv:
writer = csv.writer(out_csv, delimiter = ",")
output_list = []
reader = csv.reader(csv_f)
city_lst = cities.readlines()
for row in reader:
for city in city_lst:
city = city.strip()
if city in row[0]:
output_list.append(row)
writer.writerows(output_list)
A: Build a single regex with all the city names:
city_re = re.compile(r'\b('+ '|'.join(c.strip() for c in cities.readlines()) + r')\b')
and then do:
for row in reader:
match = city_re.search(row[0])
if match:
writer.writerow(row)
This will reduce the number of loop iterations from 18895 x 145 to only 18895 with the regex engine doing its best at string prefix matching on those 145 city names.
For your convenience and testing, here is the full listing:
import csv
import re
with open('alcohol_rehab_ltp.csv', 'rb') as csv_f, \
open('cities2.txt', 'rb') as cities, \
open('drug_rehab_city_state.csv', 'wb') as out_csv:
writer = csv.writer(out_csv, delimiter = ",")
reader = csv.reader(csv_f)
city_re = re.compile(r'\b('+ '|'.join(c.strip() for c in cities.readlines()) + r')\b')
for row in reader:
match = city_re.search(row[0])
if match:
writer.writerow(row)
A: Even though I don't think the loop/IO is big bottleneck,but still if you can try to start with them.
There two tips I could provide:
(r'\b{0}\b').format(c.strip()) can be in outside the loop ,that will increase some performance, because we don't have to strip(), format on in each loop.
also ,you don't have to write output result in each loop, instead, you can create a result list ouput_list save the result during the loop and write them once after the loop.
import csv
import re
import datetime
start = datetime.datetime.now()
with open('alcohol_rehab_ltp.csv', 'rb') as csv_f, \
open('cities2.txt', 'rb') as cities, \
open('drug_rehab_city_state.csv', 'wb') as out_csv:
writer = csv.writer(out_csv, delimiter = ",")
space = ""
reader = csv.reader(csv_f)
city_lst = [(r'\b{0}\b').format(c.strip()) for c in cities.readlines()]
output_list = []
for row in reader:
for city in city_lst:
#city = city.strip()
match = re.search(city, row[0])
if match:
output_list.append(row)
break
writer.writerows(output_list)
end = datetime.datetime.now()
print end - start
A: Please note that I assume that you can use a better way than using re.search for finding city in row, since generally the city will be separated by a delimiter like space. Otherwise it is a complexity greater than O(n*m)
One way could be to use a hashtable.
ht = [0]*MAX
Read all the cities (assuming these are in thousands) and fill up a hashtable
ht[hash(city)] = 1
Now when you iterate across each row in reader,
for row in reader:
for word in row:
if ht[hash(word)] == 1:
# found, do stuff here
pass
| |
doc_23538311
|
I'm asking because I need to know, if I have a site that has a timezone set as a site-wide variable, and I compare something to the $_SERVER['REQUEST_TIME'] to know if it's expired, I'm not sure whether a timezone mismatch is possible.
A: $_SERVER's 'REQUEST_TIME' is a Unix timestamp. That should be enough information, but if it isn't: Unix timestamps are always UTC-based.
PHP Example
The notation for Unix timestamps in DateTime is to prefix the number with the at-sign ("@"). Then the second $timeZone parameter is ingored and defaults to "UTC" because it is a Unix timestamp which are always UTC based:
$requestTime = new DateTime("@$_SERVER[REQUEST_TIME]");
Gives:
class DateTime#1 (3) {
public $date => string(19) "2013-06-23 07:45:44"
public $timezone_type => int(1)
public $timezone => string(6) "+00:00"
}
It is not even possible to force (by timestamp at construction) the DateTime object to a different timezone - only later on changing the timezone.
| |
doc_23538312
|
Here's the specific part of the code.
do
{
printf("\n\nAnswer: (y/n) ");
scanf("%c", &ans);
//printf("\n->%c<-\n", ans); //just for debugging
if (ans == 'y')
{
age += v[0];
}
else if (ans != 'n')
{
printf("\nI don't get it!\n");
}
} while (ans != 'y' && ans != 'n');
These are the declarations:
char v[64];
char ans;
(This do..while loop is inside a 'for')
What further puzzles me is the fact that the program compiles and runs exactly as I'd expect on Windows... (using MinGW)
I've tried using fflush(stdin) before and/or after the scanf, but it didn't help.
An important observation is that the first time it reaches this question it acts as expected.
(before the user answers)
Answer: (y/n)
I don't get it! // this gets written every time but the first
Answer: (y/n) n
You are 21 years old!
If the user writes invalid input:
Answer: (y/n) w
I don't get it!
Answer: (y/n) // this line and the next one should simply not be printed
I don't get it!
Answer: (y/n)
//(now it waits for user input)
Any ideas?
Edit
Fixed it:
(I declared an additional char buf[50])
do
{
printf("\n\nAnswer: (y/n) ");
fgets(buf, 50, stdin);
sscanf(buf, " %c", &ans);
if (ans == 'y')
{
age += v[0];
}
else if (ans != 'n')
{
printf("\nI don't get it!\n");
}
} while (ans != 'y' && ans != 'n');
Can someone tell me what is the problem with scanf?
A: Stop using scanf. Now.
Use fgets(buffer, BUFLEN, stdin) instead. Then use sscanf to parse the result. It will be more robust, and it will get rid of your problem.
I have heard it said that adding spaces around the format specifier can help too, because it gets rid of residual "whitespace". scanf(" %c", &ans); But I don't like it.
UPDATE here is a piece of code that I believe operates like you want it to (I replaced the innards with printf statements but you get the idea; I also replaced your ifs with a switch - I think it's cleaner):
#include <stdio.h>
#include <string.h>
#define N 100
int main(void) {
char buf[N];
char ans;
int ii;
for (ii = 0; ii < 10; ii++)
{
do
{
printf("\n\nAnswer: (y/n) ");
fgets(buf, N, stdin);
sscanf(buf, "%c", &ans);
printf("==%c==", ans);
switch(ans)
{
case 'y':
printf("\nYou said yes :-)\n");
break;
case 'n':
printf("\nYou said no :-(\n");
break;
default:
printf("\nI don't get it!\n");
}
} while (ans != 'y' && ans != 'n');
}
}
A: Follow @Floris answer about fgets().
If you must use scanf(), use
scanf(" %c", &ans);
The space preceding "%c" will consume any and all leading white-space including the previous line's Enter or '\n'.
One certainly does not want to add a following space as that causes scanf() to consume all white-space until another non-white-space is entered. Since stdin is usually buffered, them means an additional '\n' after the non-white-space is needed for the line to be given to scanf().
| |
doc_23538313
|
I have the code below but I can't get it to fire. Kindly help.
$rootScope.$on("$destroy", function() {
lockService.logout();
});
lockService.logout() holds the functionality that successfully logs out the user when they click logout button, including the Auth0 signout function.
Somewhere I read that I can use the $on.$destroy of the main Controller but I am not sure how to do this. The above code is in fact inside the mainController function but it still doesn't work.
This is where I found my answer: https://stackoverflow.com/a/36444134/1168597
A: You can add a directive like this to your body element.
<body body-unload></body>
app.directive('bodyUnload', [
function () {
return {
restrict: 'A',
replace: false,
link: function (scope, element) {
function cleanupApp(){
// do cleanup here
}
element[0].onbeforeunload = function() {
cleanupApp();
};
}
};
}
]);
A: I have found a much cleaner and more effective approach.
$rootScope.$on('$locationChangeStart', function () {
if (!($window.performance.navigation.type === 1) && lockService.isAuthenticated()) {
$rootScope.logout();
}
});
So here if window.performance.navigation.type is 1, it means the page was refresh-ed. What I do then is if it is not refreshed AND my lockService.isAuthenticated() returns true, I logout the user.
| |
doc_23538314
|
A: The whole of libav (and before ffmpeg) is wrapped by "gst-libav" (previously "gst-ffmpeg"). When you launch a pipeline with a playbin, it's this implementation that will get used, not your system-wide ffmpeg.
| |
doc_23538315
|
I have 6 input values that are randomly generated. The first 5 pull a random name from their respective list of names, the 6th pulls a random name from all of the lists combined. Should this be a separate array containing all the names or is there a way to combine the arrays?
The other issue is that the 6th input needs to keep randomizing until its input value is not equal to any of the first 5.
Please let me know how you would go about checking the 6th value against the other 5 and then keep getting a new value.
Thanks for all the help
function getRandom1()
{
var names = [
'Red1',
'Blue1',
'Green1'
];
return names[Math.floor(Math.random() * names.length)];
}
function getRandom2()
{
var names = [
'Red2',
'Blue2',
'Green2'
];
return names[Math.floor(Math.random() * names.length)];
}
function getRandom3()
{
var names = [
'Red3',
'Blue3',
'Green3'
];
return names[Math.floor(Math.random() * names.length)];
}
function getRandom4()
{
var names = [
'Red4',
'Blue4',
'Green4'
];
return names[Math.floor(Math.random() * names.length)];
}
function getRandom5()
{
var names = [
'Red5',
'Blue5',
'Green5'
];
return names[Math.floor(Math.random() * names.length)];
}
function getRandomX()
{
var names = [
'Red1',
'Blue1',
'Green1',
'Red2',
'Blue2',
'Green2',
'Red3',
'Blue3',
'Green3',
'Red4',
'Blue4',
'Green4',
'Red5',
'Blue5',
'Green5'
];
return names[Math.floor(Math.random() * names.length)];
}
function myFunction() {
document.getElementById("input_1").value =( getRandom1() );
document.getElementById("input_2").value =( getRandom2() );
document.getElementById("input_3").value =( getRandom3() );
document.getElementById("input_4").value =( getRandom4() );
document.getElementById("input_5").value =( getRandom5() );
document.getElementById("input_X").value =( getRandomX() );
}
<body onload="myFunction(), myFunction2()">
<select onchange="myFunction(), myFunction2()" id="select">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4 </option>
<option value="5"> 5 </option></select>
<br>
1 <input type="text" id="input_1"/><br>
2 <input type="text" id="input_2"/><br>
3 <input type="text" id="input_3"/><br>
4 <input type="text" id="input_4"/><br>
5 <input type="text" id="input_5"/><br>
X <input type="text" id="input_X"/>
A: This is not an elegant solution but you can do a "while" loop which will randomize the 6th input until it is different.
function myFunction() {
var input1 = getRandom1();
var input2 = getRandom2();
var input3 = getRandom3();
var input4 = getRandom4();
var input5 = getRandom5();
var input6 = getRandomX();
document.getElementById("input_1").value = input1;
document.getElementById("input_2").value = input2;
document.getElementById("input_3").value = input3;
document.getElementById("input_4").value = input4;
document.getElementById("input_5").value = input5;
while (input6==input1 || input6==input2 || input6==input3 || input6==input4 || input6==input5) {
input6 = getRandomX();
}
document.getElementById("input_X").value = input6;
}
A better way is to generate the names array of the 6th input after the first 5 are randomly chosen, so it will not contain previously chosen values.
| |
doc_23538316
|
this.state = {
attrValue: ''
};
The JSX checkbox:
<div className="col-md-4 col-sm-4">
<input
type="checkbox"
checked={this.state.attrValue === '1'}
value={this.state.attrValue}
onChange={this._handleInputChange}
name="attrValue"
/>
</div>
The on change handler:
_handleInputChange(e) {
const element = e.target;
const stateObject = {};
stateObject[element.name] = element.value;
this.setState(stateObject);
}
As of now, clicking the checkbox does not modify the state. Im not entirely sure if this is even possible. With radio buttons I would just render a true and false radio button with values set to 1 and 0. Any help is greatly appreciated!
A: You're not too far off in your code.
Take a look at this fiddle I created. Note that I made the initial state a simpler boolean rather than an empty string, and I set the state to the value of the checkbox on its onChange.
http://jsfiddle.net/tp3k4wpL/
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = {
attrValue: false
};
this._handleInputChange = this._handleInputChange.bind(this);
}
_handleInputChange(e) {
const element = e.target;
this.setState({attrValue: element.checked});
}
render() {
return (
<div className="col-md-4 col-sm-4">
<input
type="checkbox"
checked={this.state.attrValue}
onChange={this._handleInputChange}
name="attrValue"
/>
{`State of checkbox: ${this.state.attrValue}`}
</div>
);
}
}
React.render(<Foo />, document.body);
| |
doc_23538317
|
All urls that doesn't start by /fr/ or /en/ or /es/ have to be redirect to /fr/
I've try this :
RewriteCond %{REQUEST_URI} !^/fr(.*) [OR]
RewriteCond %{REQUEST_URI} !^/en(.*) [OR]
RewriteCond %{REQUEST_URI} !^/es(.*)
RewriteRule . /fr/? [R=301,L]
Placed just after this :
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
It seems to work, but my problem is all images, css, js are impacted by this redirect, and aren't loaded.
Is there a solution de make this redirect only on URLs, no on assets ?
A: You can use the following rule in .htaccess for redirects to make proper.
RewriteRule ^fr/(css|js|img)/(.*)?$ /$1/$2 [L,QSA,R=301]
| |
doc_23538318
|
I'd like my text blocks to follow each other without overlapping. Any hint on how I can solve that?
I've created a explanation schema:
A: When creating a fresh website always use the reset css template found here MeyerWeb Reset Css. This way all the html tags don't have existing padding or margin on their own and you can style it in your own way.
And when it comes to responsive mode always use % in your div elements and apply it inside your media queries
@media only screen (max-width:600px) { // Specify viewport value to change the look
.box-right-absolute {width:40%;}
}
.wrapper {position:relative;margin:0 auto;padding:0;width:100%;max-width:1200px}
.box-right-absolute {position:absolute;right:0;top:0;width:400px;}
.box-sub-right {position:relative;min-height:200px;background:red;color:#fff;padding:20px;margin-bottom:10px;}
@media only screen (max-width:600px) {
.box-right-absolute {width:40%;}
}
<div class="wrapper">
<div class="box-right-absolute">
<div class="box-sub-right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Diam volutpat commodo sed egestas. Eget est lorem ipsum dolor sit amet consectetur adipiscing. Gravida neque convallis a cras semper auctor neque vitae tempus. Cursus sit amet dictum sit. Lobortis feugiat vivamus at augue. Egestas sed tempus urna et pharetra pharetra massa massa. Amet commodo nulla facilisi nullam vehicula ipsum a arcu. In est ante in nibh mauris cursus mattis. Pellentesque elit eget gravida cum sociis natoque penatibus. Egestas integer eget aliquet nibh praesent tristique magna sit amet. Volutpat commodo sed egestas egestas. Gravida quis blandit turpis cursus in hac.
</div>
<div class="box-sub-right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Diam volutpat commodo sed egestas. Eget est lorem ipsum dolor sit amet consectetur adipiscing. Gravida neque convallis a cras semper auctor neque vitae tempus. Cursus sit amet dictum sit. Lobortis feugiat vivamus at augue. Egestas sed tempus urna et pharetra pharetra massa massa. Amet commodo nulla facilisi nullam vehicula ipsum a arcu. In est ante in nibh mauris cursus mattis. Pellentesque elit eget gravida cum sociis natoque penatibus. Egestas integer eget aliquet nibh praesent tristique magna sit amet. Volutpat commodo sed egestas egestas. Gravida quis blandit turpis cursus in hac.
</div>
</div>
</div>
| |
doc_23538319
|
i was able to connect to the instance via rdp until recently i am unable to connect all of a sudden
I have already set inbound rules to the VPC security group as well as the security group in the EC2 console, and the ACL but my rdp is still not connecting
A: Go to security groups ->Inbound -> Edit -> Add rule -> select RDP -> in drop down(select anyware ) -> save
A: First of all there can be multiple reasons why this RDP is not connecting.
You can try to do stop and restart the instance. Sometimes this solves the problem instantly, but sometimes there might be a firewall issue, check your rules.
As you said you have enabled all IPs on all protocols in security
group.
You may also try the troubleshooting steps suggested by AWS.
A: I have made a video on How to set your Remote Desktop using AWS Ec2 instance. You can refer to this link if it fits your need.
you need to add RDS inbound rule which by default runs on port 3291. Give access permission to Anywhere.
| |
doc_23538320
|
If we see the above image in 3rd row we can see white shaded rating bar, I want this same thing in one of my app, Any ideas/best ways to do it.
I am populating above rating list on RecyclerView list and I am populating the items using RecyclerView adapter.
A: try to reduce the opacity of your recycler item inside the adapter,
get the inflating positions of list/recyclerview if position is greater than 3 then apply rowView.setAlpha(0.6f);...for position 4 change alpha tvText.setAlpha(0.8f); similarly for topviews change the aplha tvText.setAlpha(1); change the alpha value for entire row item.
A: Just set the alpha channel of the views! Use the setAlpha() method of the View class to achieve this! Use setAlpha() with a value below 1, e.g.: 0.66.
| |
doc_23538321
|
There are plots with high or low density, and in each plot are subplots with treatment A in one subplot, treatment B in the other. The design is a latin square, with only one replicate of each treatment combination in each block effect (vertical blocking and horizontal blocking) so that blocking needs to be treated as a random effect.
The response variable is percent cover of plant species in the community.
The data is set up thus:
Treatment hblock vblock Inoc sp1 sp2 …
1 1 1 1 0.2 0.25
2 2 1 2 0.3 0.9
1 3 1 2 0.2 0.2
2 4 1 1 0.01 0.001
Where "Treatment" is the high and low density treatment, and "Inoc" is the treatment "A or B" in the subplots.
My question is, since I can't use random effects in permanova, so far as I can tell from reading about it, can I account for the blocking effects by nesting the interaction within the blocks - like this:
adonis(formula = temp[, -c(1:4)] ~ temp$Inoc * temp$Treatment , method = "bray", strata = temp$Vblock * temp$Hblock, permuatations = 1000)
Or is this approach invalid?
| |
doc_23538322
|
I want to sum some figures from a table. As by my idea, the two following codes must give the same output, but they don't :
I have a simple df :
df[["Opportunity Group", "enjeu", "Montant"]].sample(10)
which gives me :
Now for each customer I want the total amount of the df :
tab = df.pivot_table(index = "Opportunity Group",
columns = "enjeu" ,
values = "Montant" ,
margins = False ,
aggfunc = np.sum ).fillna(0)
tab
Which gives me :
but the figures are wrong, and if I do the following :
df[df["Opportunity Group"]=="NUTANIX"].groupby("enjeu")["Montant"].sum()
I don't get the same figures :
enjeu
(-1.0, 100.0] 0.00
(100.0, 200.0] 0.00
(200.0, 500.0] 0.00
(500.0, 1000.0] 0.00
(1000.0, 5000.0] 4208.64
(5000.0, 20000.0] 34393.65
(20000.0, 50000.0] 422983.67
Why is not :
tab = df.pivot_table(index = "Opportunity Group",
columns = "enjeu" ,
values = "Montant" ,
margins = False ,
aggfunc = np.sum ).fillna(0)
equivalent of the specific request by group, like for NUTANIX :
df[df["Opportunity Group"]=="NUTANIX"].groupby("enjeu")["Montant"].sum()
??
EDIT
the column "enjeu" get's mixed up by the pivot table
Before :
After :
| |
doc_23538323
|
but the tasks (android sdk, create new android project, create test project, create new xml file) not showing in the toolbar.
am I did something wrong?
A: In Eclipse, open "About Eclipse", all installed plugins should be displayed there.
Clicking on the icon should raise a new screen with the installed version of ADT.
| |
doc_23538324
|
sudo wget https://raw.githubusercontent.com/Yenthe666/InstallScript/11.0/odoo_install.sh
No fancy modules. After installing SSL cert(using Certbot) I realised that Discuss & Chat apps are not working. So I updated my config (workers=4, proxy mode is true) as well as Nginx config.
Odoo config:
[options]
addons_path = /odoo/odoo-server/addons,/odoo/custom/addons
admin_passwd = pwd
csv_internal_sep = ,
data_dir = /odoo/.local/share/Odoo
db_host = False
db_maxconn = 64
db_name = False
db_password = False
db_port = False
db_sslmode = prefer
db_template = template1
db_user = False
dbfilter =
demo = {}
email_from = False
geoip_database = /usr/share/GeoIP/GeoLite2-City.mmdb
http_enable = True
http_interface =
http_port = 8070
import_partial =
limit_memory_hard = 2684354560
limit_memory_soft = 2147483648
limit_request = 8192
limit_time_cpu = 600
limit_time_real = 1200
limit_time_real_cron = -1
list_db = True
log_db = False
log_db_level = warning
log_handler = :INFO
log_level = info
logfile = /var/log/cier/cier-server.log
logrotate = False
longpolling_port = 8072
max_cron_threads = 1
osv_memory_age_limit = 1.0
osv_memory_count_limit = False
pg_path = None
pidfile = None
proxy_mode = True
reportgz = False
server_wide_modules = web
smtp_password = False
smtp_port = 25
smtp_server = localhost
smtp_ssl = False
smtp_user = False
syslog = False
test_commit = False
test_enable = False
test_file = False
test_report_directory = False
translate_modules = ['all']
unaccent = False
without_demo = False
workers = 8
Nginx:
#odoo server
upstream odoo {
server 127.0.0.1:8070;
}
upstream odoochat {
server 127.0.0.1:8072;
}
# http -> https
server {
listen 80;
server_name www.onet.pl;
rewrite ^(.*) https://$host$1 permanent;
}
server {
listen 443;
server_name www.onet.pl;
proxy_read_timeout 720s;
proxy_connect_timeout 720s;
proxy_send_timeout 720s;
# Add Headers for odoo proxy mode
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
# SSL parameters
ssl on;
# listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/onet.pl/fullchain.pem; # managed$
ssl_certificate_key /etc/letsencrypt/live/onet.pl/privkey.pem; # manag$
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
# log
access_log /var/log/nginx/odoo.access.log;
error_log /var/log/nginx/odoo.error.log;
# Redirect longpoll requests to odoo longpolling port
location /longpolling {
proxy_pass http://odoochat;
}
# Redirect requests to odoo backend server
location / {
proxy_redirect off;
proxy_pass http://odoo;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
proxy_pass http://odoo;
expires 365d;
}
# common gzip
gzip_types text/css text/less text/plain text/xml application/xml application/json application/javascript;
gzip on;
}
The weird thing is that when I check the 8072 port(using lsof -i :8072) nothing is listening there...
Ok, I have spent some time on it and got a solution. Haven't really found the answer why long polling was not working with the proper settings - that is why I am going to leave the question open.
I have basically replaced the original nginx config with the simple proxy reverse config without HTTPS:
server {
listen 80;
server_name http://yoursite.com;
location / {
proxy_pass http://0.0.0.0:8069;
proxy_redirect off;
proxy_set_header Host $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_read_timeout 3000000;
client_max_body_size 2000M;
}
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
}
Then I simply used Certbot (https://certbot.eff.org/) and choose the option to redirect(that is the last point). Config generated by Certbot looks different but it works. Will test it on Monday on a different website and produce a tutorial.
| |
doc_23538325
|
Working example, JS:
var thisListShowsUp = ['Value1','Value2'];
var listToShow = view.$el.find('[data-id="listToShow"]');
var thisListDoNotShowUp = []
//fetchedItemFromDBList gets populated from get request from DB. See log
fetchedItemFromDBList.forEach(function(item)
{
thisListDoNotShowUp.push(item.stringValue);
});
console.log(thisListDoNotShowUp);
console.log(thisListShowsUp);
thisListShowsUp.forEach(function(item)
{
var option = document.createElement('option');
var stringValue = item.toString();
option.value = stringValue
listToShow.append(option);
});
Not working example, JS:
var thisListShowsUp = ['Value1','Value2'];
var listToShow = view.$el.find('[data-id="listToShow"]');
var thisListDoNotShowUp = []
//fetchedItemFromDBList gets populated from get request from DB. See log
fetchedItemFromDBList.forEach(function(item)
{
thisListDoNotShowUp.push(item.stringValue);
});
console.log(thisListDoNotShowUp);
console.log(thisListShowsUp);
thisListDoNotShowUp.forEach(function(item)
{
var option = document.createElement('option');
var stringValue = item.toString();
option.value = stringValue
listToShow.append(option);
});
HTML:
<input name="test" list="listToShow" />
<datalist id="listToShow" data-id="listToShow"></datalist>
log:
["foo1", "bar1"]
["Value1", "Value2"]
A: There is a constructor to create an option : new Option()
You also need to use a set to avoid duplicates
your code could be:
const
displayThis = new Set(['value1','value2']) // added values
, listToShow = document.querySelector('datalist[data-id="listToShow"]')
, fetchedItemFromDBList =
[ { stringValue: 'foo1' }
, { stringValue: 'bar1' }
]
fetchedItemFromDBList.forEach( item => displayThis.add( item.stringValue ))
displayThis.forEach( item => listToShow.appendChild(new Option('', item )))
<input name="test" list="listToShow" />
<datalist id="listToShow" data-id="listToShow"></datalist>
| |
doc_23538326
|
Parse error: syntax error, unexpected T_STRING in /newref-exec.php on line 6
I have read loads of different solutions to this problem but non seem to work
<?php
// connect to database
require($DOCUMENT_ROOT . "connect.php");
// check for blank entries
if ($_POST[doi2] == "NULL"){
echo "No Data to add";
}
else
{
$sql="INSERT INTO ref (uid, date, doi, title, year, journal)
VALUES
('1','CURDATE ()','$_POST[doi2]','$_POST[title2]','$_POST[year2]','$_POST[journal2]')";
if (!mysqli_query($link,$sql,$con))
{
die('The Reference could not be added, beacuse of SQL Error:' . mysql_error());
}
echo "New Reference Added";
}
?>
A: This line, the key needs to have quotes,
if ($_POST['doi2'] == "NULL"){
Also, if you want to check for empty entries, you need to probably do this,
if ($_POST['doi2'] == ""){ //checking "NULL", checks for a string 'NULL'
A: Rewrite the code in the below way.
<?php
// connect to database
require($DOCUMENT_ROOT . "connect.php");
// check for blank entries
if ($_POST['doi2'] == null){
echo "No Data to add";
} else {
$doi2 = $_POST['doi2'];
$title2 = $_POST['title2'];
$year2 = $_POST['year2'];
$journal2 = $_POST['journal2'];
$sql="INSERT INTO ref(uid, date, doi, title, year, journal) VALUES('1', 'CURDATE()', '$doi2', '$title2', '$year2', '$journal2')";
if (!mysqli_query($link, $sql, $con))
{
die('The Reference could not be added, beacuse of SQL Error:' . mysql_error());
}
echo "New Reference Added";
}
?>
| |
doc_23538327
|
Here is the code
import java.util.*;
class stringSort
{
public static void main(String args[])
{
String s1;
char[]s2;
System.out.println("Enter the string");
Scanner s=new Scanner(System.in);
s1=s.next();
//call the sort method to sort the string
s2=sort(s1);
System.out.println(String.valueOf(s2));
//remove duplicate entries in the sorted string
SortedSet<Character> set=new TreeSet<Character>();
set.addAll(Arrays.asList(s2));
System.out.println(String.valueOf(set.toArray()));
}
static char[] sort(String s)
{
char []temp=s.toCharArray();
Arrays.sort(temp);
return temp;
}
}
It gives the error
no suitable method found for addAll(List<char[]>)
set.addAll(Arrays.asList(s2));
A:
But the code is giving error
SortedSet<char> set=new TreeSet<char>();
This is illegal and won't compile. If you want to use a character set you have to use the Character class.
SortedSet<Character> set=new TreeSet<Character>();
UPDATE
It gives the error no suitable method found for addAll(List) set.addAll(Arrays.asList(s2));
That's because you need a Character array, not a char array, so you have two options:
*
*Change char[]s2; to Character[]s2;
*Convert the char array to a Character array before calling the sort method:
Character[] a = new Character[s2.length];
System.arraycopy(s2, 0, a, 0, s2.length);
a = sort(s1);
In both cases you'll have to change your sort method to this:
static Character[] sort(String s) {
Character[] temp = new Character[s.length()];
for (int i = 0; i < temp.length; i++) {
temp[i] = s.charAt(i);
}
Arrays.sort(temp);
return temp;
}
| |
doc_23538328
|
Example:
dateTime1 > 1/18/2017 2:30pm
The issue I'm running into is STR_TO_DATE() expects a string and returns null with DATETIME, DATE_FORMAT() expects a date and returns null with a string. I need a function or nested group of functions that will give me the same result regardless of the value of the datatype & would like to address directly in mysql rather than pre-processing or making the user input validation stricter. I used to use CAST(value, DATETIME), however CAST() doesn't read the date correctly in the more recent versions of MySQL (it ignores the am/pm specification). Any ideas?
A: GREATEST() did not work for me as it would always return null if any component was null, however it led me to COALESCE() which provides me with the solution I am looking for as it returns the first non NULL value. It makes the assumption the value will always be DATE, DATETIME, or a date time string which is the case for my issue:
SELECT COALESCE(STR_TO_DATE(value1, '%c/%e/%Y %r'), value1) > COALESCE(STR_TO_DATE(value2, '%c/%e/%Y %r'), value2)
Note: value1 and value2 are either DATE / DATETIME columns or date time string values
A: You can consider using the coalesce() function, with a list of different formats used with str_to_date(). coalesce() will ignore any null from the list (but at least one of them should be non-null, or you still get a null).
select
coalesce(
str_to_date('13/18/2017 2:30pm', '%m/%e/%Y %l:%i%p') -- will get a null
, str_to_date('18/13/2017 2:30pm', '%e/%m/%Y %l:%i%p') -- will get a null
, str_to_date('18/01/2017 14:30', '%e/%m/%Y %k:%i')
) as answer;
The code may be brittle, because there are so many different date/time formats that a human user may input.
You may also need to be very familiar with all the different format characters that str_to_date() take. See this manual page for more details:
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
Updated
An earlier version of this answer incorrectly suggested the use of the greatest() function.
| |
doc_23538329
|
(defn remove-smaller
[coll partial-order-fn]
___
)
where partial-order-fn takes two arguments and return -1 0 or 1 is they are comparable (resp. smaller, equal, bigger) or nil otherwise.
The result of remove-smaller should be coll, with all items that are smaller than any other item in coll are removed.
Example: If we defined a partial order such as numbers are compared normally, letters too, but a letter and a number are not comparable:
1 < 2 a < t 2 ? a
Then we would have:
(remove-smaller [1 9 a f 3 4 z])
==> [9 z]
A: (defn partial-compare [x y]
(when (= (type x) (type y))
(compare x y)))
(defn remove-smaller [coll partial-order-fn]
(filter
(fn [x] (every? #(let [p (partial-order-fn x %)]
(or (nil? p) (>= p 0)))
coll))
coll))
(defn -main []
(remove-smaller [1 9 \a \f 3 4 \z] partial-compare))
This outputs (9 \z), which is correct unless you want the return value to be of the same type as coll.
A: In practice I might just use tom's answer, since no algorithm can guarantee better than O(n^2) worst-case performance and it's easy to read. But if performance matters, choosing an algorithm that is always n^2 isn't good if you can avoid it; the below solution avoids re-iterating over any items which are known not to be maxes, and therefore can be as good as O(n) if the set turns out to actually be totally ordered. (of course, this relies on transitivity of the ordering relation, but since you call this a partial order that's implied)
(defn remove-smaller [cmp coll]
(reduce (fn [maxes x]
(let [[acc keep-x]
,,(reduce (fn [[acc keep-x] [max diff]]
(cond (neg? diff) [(conj acc max) false]
(pos? diff) [acc keep-x]
:else [(conj acc max) keep-x]))
[[] true], (map #(list % (or (cmp x %) 0))
maxes))]
(if keep-x
(conj acc x)
acc)))
(), coll))
A: (def data [1 9 \a \f 3 4 \z])
(defn my-fn [x y]
(when (= (type x) (type y))
(compare x y)))
(defn remove-smaller [coll partial-order-fn]
(mapv #(->> % (sort partial-order-fn) last) (vals (group-by type data))))
(remove-smaller data my-fn)
;=> [9 \z]
Potentially the order of the remaining items might differ to the input collection, but there is no order between the equality 'partitions'
| |
doc_23538330
|
<!-- Setup Rolling Log File to log all information -->
<appender name="DebugFileAppender" type="log4net.Appender.RollingFileAppender" >
<file value="${ProgramData}\\WPF Example\\log\\Debug" />
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<datePattern value="_yyyy-MM.\tx\t"/>
<staticLogFileName value="false"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
I use the same file in a number of projects and would like to have a stock log4net.config file that I do not need to modify per project. In the <file> tag, is there a way to replace the 'WPF Example' with a parameter (similar to '${ProgramData}' ) that would pull the AssemblyTitle from the AssemblyInfo.cs file?
| |
doc_23538331
|
public class DatabaseUserDetailsService implements UserDetailsService {
@Inject
private UserAccountService userAccountService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userAccountService.getUserByEmail(username);
return new MyUserDetails(user);
}
}
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
public User findByEmail(String email);
}
@Service
public class UserAccountService {
@Inject
protected UserRepository userRepository;
public User getUserByEmail(String email) {
return userRepository.findByEmail(email);
}
}
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.sample")
@EntityScan(basePackages = { "com.sample" })
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
...
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
protected static class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter {
@Inject
private UserAccountService userAccountService;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
@Bean
public UserDetailsService userDetailsService() {
return new DatabaseUserDetailsService();
}
}
}
@Entity
public class User extends AbstractPersistable<Long> {
@ManyToMany
private List<Role> roles = new ArrayList<Role>();
// getter, setter
}
@Entity
public class Role extends AbstractPersistable<Long> {
@Column(nullable = false)
private String authority;
// getter, setter
}
I cannot start app beacouse I get (full exception here http://pastebin.com/gM804mvQ)
Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.sample.model.User.roles[com.sample.model.Role]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1134)
When I configure my ApplicationSecurity with auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("...).authoritiesByUsernameQuery("...") everything is working including JPA and Spring Data repositories.
A: You can also follow this blog to implement custom user details service.
This example shows how you can send bean to userdetails service for injection.
*
*Autowire the Repository in the WebSecurityConfigurer
*Send this bean as a parameter to the user details service by a parameterized constructor.
*assign this a private member and use to load users from database.
A: Your app seems to work for me (once I added @Configuration to the AuthenticationSecurity). Here's another working sample of a simple app with JPA UserDetailsService in case it helps: https://github.com/scratches/jpa-method-security-sample
| |
doc_23538332
|
Here's a snapshot of some test data:
Here's my code:
Function TestDb() As ActionResult
Dim clientLocId As Integer = 23
Dim showDate As New Date
showDate = New Date(2015, 8, 14)
'showDate = New Date(2015, 9, 22)
'showDate = New Date(2015, 9, 27)
Dim orderRecs = db.Orders.Where(Function(x) x.ClientLocationId = clientLocId AndAlso x.OrderNumber IsNot Nothing _
AndAlso x.DateCompletedUtc IsNot Nothing _
AndAlso DbFunctions.TruncateTime(x.OrderDateLoc) = showDate.Date) _
.OrderByDescending(Function(x) x.OrderDateUtc)
Stop
End Function
And so here's my problem:
The rows for Order Dates 09/27/2015 and 09/22/2015 query properly with the logic above - yielding 1 row for each date requested. BUT - a query for the 08/14/2015 date yields NOTHING. I am in the -04:00 timezone now, if that matters. If I change the timezone [edit] in the row data [end edit] to -04:00 the 2 08/14/2015 rows query properly.
I have googled to try to find answers to this but have come up dry. Can someone weigh in on my problem?
[UPDATE]: Workaround
Here's a workaround (for now) based on a suggestion from this thread by @PiotrAuguscik suggesting to convert the query first to a list:
Dim orderRecs = (db.Orders.Where(Function(x) x.ClientLocationId = clientLocId AndAlso x.OrderNumber IsNot Nothing _
AndAlso x.DateCompletedUtc IsNot Nothing).ToList) _
.Where(Function(x) x.OrderDateLoc.Value.Date = showDate.Date) _
.OrderByDescending(Function(x) x.OrderDateUtc)
It's a little "crusty", but it works. I sure would like to know, however, why timezones would have anything to do with DbFunctions.TruncateTime().
[UPDATE #2] Proper solution code derived from answer from Matt Johnson
Dim orderRecs = db.Orders.Where(Function(x) x.ClientLocationId = clientLocId AndAlso x.OrderNumber IsNot Nothing _
AndAlso x.DateCompletedUtc IsNot Nothing AndAlso
(x.OrderDateLoc >= showDateDto AndAlso x.OrderDateLoc < showDateDto.AddDays(1))) _
.OrderByDescending(Function(x) x.OrderDateUtc)
A: A few things:
*
*Both your original query and your workaround are non-sargable. You should never manipulate the left side of an comparison in a WHERE clause. If you do, the database can't use any indexes and will get slower and slower the more data you have. Instead, do a range query.
*It would appear you have datetimeoffset types in your table. These represent specific moments in time, thus comparisons against two datetimeoffset values are done based on their UTC equivalents - not on their local display time. Values are indexed this way as well.
*Not everyone observes the same calendar date at the same time. You'll need to ask yourself, "who's date am I asking for?"
*
*If it's the date of the person making the query, then your input values should reflect that. Instead of passing into your query a VB Date (which is a System.DateTime) in terms of local time, either pass in a UTC-based DateTime, or a DateTimeOffset. Remember, you'll need to do a range query, so you would calculate a pair of them, as a half-open interval. In other words:
// this example uses the local time zone, but there are other ways also.
DateTimeOffset startDto = new DateTimeOffset(showDate.Date)
DateTimeOffset endDto = new DateTimeOffset(showDate.Date.AddDays(1))
// then in the query...
... x.OrderDateLoc >= startDto && x.OrderDateLoc < endDto
*If you're looking to match the local date as it is recorded, then you have additional work to do in your SQL Server database.
*
*First you'll need to strip away the offset by convert(datetime2, yourDateTimeOffset), or just compute the raw local date by convert(date, yourDateTimeOffset). You should do this in a computed column so you can also create an index on it.
*Then later, you can use that computed column to do the range query, or if you computed down to the date then you can just do an equality comparison against that.
*In general, I'd avoid using DbFunctions.TruncateTime in a where clause. It gets converted to some fairly inefficient SQL that looks like this when used against a datetimeoffset field:
convert(datetimeoffset, convert(varchar(255), yourField, 102) + ' 00:00:00 ' + Right(convert(varchar(255), yourField, 121), 6), 102)
Essentially, this uses strings to re-build the datetimeoffset while retaining the offset but setting the time to midnight, which is probably not what you really want to do. You can see this yourself in SQL Profiler.
A: This is a response to Matt Johnson's response. The queries above aren't necessarily non-sargable, it depends on the index. It becomes non-sargable when you use an index as a field function parameter. :)
| |
doc_23538333
|
This is my code currently, I am working with the default hello world code very slightly modified.
int main(int argc, char* argv[]) {
// Initialize V8.
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
// Create a new Isolate and make it the current one.
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
{
v8::Isolate::Scope isolate_scope(isolate);
// Create a stack-allocated handle scope.
v8::HandleScope handle_scope(isolate);
// Create a new context.
v8::Local<v8::Context> context = v8::Context::New(isolate);
// Enter the context for compiling and running the hello world script.
v8::Context::Scope context_scope(context);
{
// Create a string containing the JavaScript source code.
v8::Local<v8::String> source =
v8::String::NewFromUtf8(isolate, R"(
console.log("does not print?")
)",
v8::NewStringType::kNormal)
.ToLocalChecked();
// Compile the source code.
v8::Local<v8::Script> script =
v8::Script::Compile(context, source).ToLocalChecked();
// Run the script to get the result.
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
// Convert the result to an UTF8 string and print it.
v8::String::Utf8Value utf8(isolate, result);
printf("%s\n", *utf8);
}
}
// Dispose the isolate and tear down V8.
isolate->Dispose();
v8::V8::Dispose();
v8::V8::ShutdownPlatform();
delete create_params.array_buffer_allocator;
std::cin.get();
return 0;
}
and I am using the prebuilt v8 binaries here
A: Try the following:
*
*#include "src/debug/interface-types.h"
*define your own "console delegate" class, deriving from debug::ConsoleDelegate
*override any methods you're interested in, e.g. void Log(const debug::ConsoleCallArguments& args, const v8::debug::ConsoleContext&) override;
*instantiate it and call debug::SetConsoleDelegate(isolate, &your_console_delegate); after creating your Isolate
To see an example, start at https://cs.chromium.org/chromium/src/v8/src/d8/d8-console.h?l=14&gsn=D8Console and trace where it's used.
A: So for anyone in the future that is dealing with this, this is the process I used to fix it.
*
*download the source from here, only the src folder is needed.
*extract it and link it in to your project where ever you put vendor code in addition to the bundle.
*put it in the a src folder because otherwise its includes don't work
*you will need to make a bunch of include directories for it to compile, mine include v8/src, and v8
*make sure to link it with the nuget package, you may not have to do this, one machine needed it the other didn't.
*you do not need to generate builtins-generated/bytecodes-builtins-list.h
| |
doc_23538334
|
spark-submit
--deploy-mode cluster
--master yarn
--files ETLConfig.json
PySpark_ETL_Job_v0.2.py
ETLConfig.json has a parameter passed to the PySpark script. I am referring this config json file in the main block as below:
configFilePath = os.path.join(SparkFiles.getRootDirectory(), 'ETLConfig.json')
with open(configFilePath, 'r') as configFile:
configDict = json.load(configFile)
But, the command throws the following error.
No such file or directory: u'/tmp/spark-7dbe9acd-8b02-403a-987d-3accfc881a98/userFiles-4df4-5460-bd9c-4946-b289-6433-drgs/ETLConfig.json'
May I know what's wrong with my script? I also tried with SparkFiles.get() command but it also didn't work.
A: You use cluster deploy mode. In this case --files path refers not to local path on the machine you use to submit, but to the local path on the worker that is used to spawn the driver, which is an arbitrary node in your cluster.
If you want to distribute files with cluster mode you should store these in a storage that can accessed by each node. You can for example use:
*
*HTTP / HTPPS URL.
*HDFS URL.
A: You should be able to just load it from your PWD in the running driver. Yarn will start the master container process in the same folder as where --files will dump the file. For client mode that would be different, but for cluster mode it should work fine. For example, this works for me:
driver.py
from pyspark import SparkContext, SparkFiles
import os
with SparkContext() as sc:
print "PWD: " + os.getcwd()
print "SparkFiles: " + SparkFiles.getRootDirectory()
data = open('data.json')
print "Success!"
spark submit
spark-submit --deploy-mode cluster --master yarn --files data.json driver.py
Updated (comparing paths):
I updated my code to print both the PWD (which worked) and SparkFiles.getRootDirectory (which didn't work). For some reason the paths differ. I'm not sure why that is.. but loading files directly from the PWD is what I have always done for accessing files from the driver.
This is what paths printed:
PWD: /var/lib/hadoop-yarn/cache/yarn/nm-local-dir/usercache/rwidmaier/appcache/application_1539970334177_0004/container_1539970334177_0004_01_000001
SparkFiles: /var/lib/hadoop-yarn/cache/yarn/nm-local-dir/usercache/rwidmaier/appcache/application_1539970334177_0004/spark-e869ac40-66b4-427e-a928-deef73b34e40/userFiles-a1d8e17f-b8a5-4999-8
Update #2
Apparently, the way it works is --files and it's brethren only guarantee to provide the files in the SparkFiles.get(..) folder on the Executors, not on the Driver. HOWEVER, in order to ship them to the executors, Spark downloads them first to the PWD on the driver, which allows you to access it from there.
It actually only mentions the executors in the help text, not the driver.
--files FILES Comma-separated list of files to be placed in the working
directory of each executor. File paths of these files
in executors can be accessed via SparkFiles.get(fileName).
For reference, here is where the files are downloaded to the driver.
| |
doc_23538335
|
*
*I created a new branch, Branch A
*I made changes on Branch A and committed, branch A is a few commits ahead of the master branch
*I used 'git checkout master' to get back to the master branch
*I made some changes in one of the files
*I tried to use 'git status', but it cannot see the changes I made, therefore cannot add or commit the changes
What I want to do:
from:
1 - 2 (master)
\
6 - 7 (Branch A)
to:
1 - 2 - 3 (master)
\
6 - 7 (Branch A)
not merging or anything complicated
A: you can't see the changes of other branches. If you wanna check other branch commit you have to checkout the branch to see the commit.
if you wanna see the changes that you made on the branch you can run git diff . then you can see what actually differ from previous one. If you wanna make same commit to your all branch then you have to merge commit.
| |
doc_23538336
|
I use the website http://search.maven.org to find Java dependencies for my Maven-based projects.
Take this artefact as an example.
In the Dependency Information box (for Apache Maven), double click to highlight all text, then copy-paste into your favourite text editor. Look at the raw bytes. Something is weird. If I paste directly into my pom.xml file, Maven cries foul during the validate stage about badly formatted XML.
Example raw text with octal literals:
<dependency>
\302\240\302\240\302\240\302\240<groupId>cglib</groupId>
\302\240\302\240\302\240\302\240<artifactId>cglib-nodep</artifactId>
\302\240\302\240\302\240\302\240<version>2.1_3</version>
</dependency>
Am I crazy or does anyone else have this issue? Is this a problem with my web browser (Chrome), my text editor (Notepad++), my operating system (Windows 7) or the Central Repo website?
Update
*
*I tried copying from Google Chrome and pasting into various places. All have the same issue. I even tried pasting into a Cygwin session running vim. Same issue.
*I tried with Internet Explorer 9 and the text has regular whitespace (\040).
This looks like an encoding issue with either The Central Repo website, or my browser, Google Chrome.
A: If seems there is some conversion between unicode and and ASCII.
"\302\240" is a whitespace in unicode and I guess you paste it to an ANSI document and somewhere some conversion kicks in.
I can't reproduce it with Maxthon, so I guess it is an issue with Chrome or something else interferring with the pasting (like Notepad++ plugins maybe).
| |
doc_23538337
|
WSDeploy Ant task
<classpath>
<fileset dir="${dir.was.plugins}">
<include name="**/*.jar" />
</fileset>
</classpath>
<taskdef name="wsdeploy" classname="com.ibm.websphere.ant.tasks.WSDeploy" />
<target name="deploy">
<wsdeploy inputFile="myearfile.ear"
outputFile="myearfile_fordeployment.ear"
classpath="${classpath}"
debug="true"
ignoreErrors="false"
noValidate="false"
trace="true" />
</target>
My Problem
I don't know how to specify the remote server address and I'd be glad to get some links to tutorials or maybe a working Ant snippet to deploy an EAR to the websphere server.
We already have some SCP and SSHEXEC tasks running for the portlets, and they're calling the XMLAccess interface to place and start the portlets. Do I have to adapt that scripts for the EAR too or is that a completely wrong way to automatically deploy an EAR file?
UPDATE 2
I rewrote my ant script and now there is no ClassNotFoundException anymore. Still, there is an unexpected behavior: The script wants to use a profile I never specified...
Call to Ant:
%WAS_HOME%\bin\ws_ant.bat -Duser.install.root="%WAS_HOME%\profiles\EXPECTEDPROFILE" -f buildall.xml "%1"
I want to run all this with EXPECTEDPROFILE, but the error message that is following suggests that there is another profile UNEXPECTEDPROFILE involved.
Output:
wasListApps:
[wsadmin] WASX7023E: Fehler beim Erstellen der "SOAP"-Verbindung zu "MYHOST". Informationen zur Ausnahme: com.ibm.websphere.management.exception.ConnectorNotAvailableException: com.ibm.websphere.management.exception.ConnectorNotAvailableException: ADMC0016E: Das System kann keinen SOAP-Connector erstellen, um die Verbindung zum Host MYHOST an Port MYPORT herzustellen.
[wsadmin] WASX7213I: Dieser Script-Client ist mit keinem Serverprozess verbunden. Pr?fen Sie, ob in der Protokolldatei /PATH/TO/UNEXPECTEDT/PROFILE/logs\wsadmin.traceout n?here Einzelheiten enthalten sind.
[wsadmin] WASX8011W: Das AdminTask-Objekt ist nicht verfügbar.
[wsadmin] WASX7015E: Beim Ausf?hren des Befehls "$AdminApp list" ist eine Ausnahme eingetreten. Informationen zur Ausnahme:
[wsadmin] com.ibm.ws.scripting.ScriptingException: WASX7206W: Der Application Management Service ist nicht aktiv. Die Befehle f?r die Anwendungsverwaltung k?nnen nicht ausgef?hrt werden.
[wsadmin] Java Result: 103
UPDATE 1
Using wsinstallapp
After reading JoseKs answer I tried to use wsinstallapp to install my application with this Ant target:
<taskdef name="wsInstallApp" classname="com.ibm.websphere.ant.tasks.InstallApplication" classpath="${dir.was.plugins}/com.ibm.ws.runtime_6.1.0.jar" />
<target name="deploy" depends="EAR">
<wsInstallApp
wasHome="${WAS_HOME}"
ear="MYAPPLICATION.ear"
options=""
properties=""
profile=""
conntype="SOAP"
host="${TargetServer}"
port="${TargetPort}"
user="${TargetUser}"
password="${TargetPwd}"
failonerror="true" />
</target>
But this is what I get:
deploy:
[wsInstallApp] Anwendung wird installiert [/path/to/MYAPPLICATION.ear]...
[wsadmin] Exception in thread "main" java.lang.NoClassDefFoundError: org.eclipse.core.launcher.Main
[wsadmin] at com.ibm.wsspi.bootstrap.WSPreLauncher.launchEclipse(WSPreLauncher.java:335)
[wsadmin] at com.ibm.wsspi.bootstrap.WSPreLauncher.main(WSPreLauncher.java:91)
[wsadmin] Caused by: java.lang.ClassNotFoundException: org.eclipse.core.launcher.Main
[wsadmin] at java.net.URLClassLoader.findClass(URLClassLoader.java:496)
[wsadmin] at java.lang.ClassLoader.loadClass(ClassLoader.java:631)
[wsadmin] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
[wsadmin] at java.lang.ClassLoader.loadClass(ClassLoader.java:597)
[wsadmin] ... 2 more
I don't know why the task is searching for an Eclipse class...
A: I believe the ant task for actually deploying the EAR onto the remote Websphere is wsInstallApp as documented here
<taskdef name="wsInstallApp" classname="com.ibm.websphere.ant.tasks.InstallApplication"/>
<wsInstallApp
wasHome="location of websphere installation"
ear="the ear file you wish to install"
options="the options to pass to the installation process"
properties="java properties file containing attributes to set in the JVM System properties"
profile="a script file to be executed before the main command or file"
conntype="specifies the type of connection to be used."
host="the host to connect to"
port="the port on the host to connect to"
user="user ID to authenticate with"
password="password to authenticate with"
failonerror="true | false"/>
| |
doc_23538338
|
It seems to work correctly with some values (9*2, 8*2 or 10*10), but fails when I try and do others (11*11 gives me 110, same as 10*11). I believe it is whenever the multiplier is odd.
START:
MOVE.W #MULTIPLICAND,D0 ; Set D0 equal to the multiplicand
MOVE.W #MULTIPLIER,D1 ; Set D1 equal to the multiplier
MOVE.L #00000000,D2 ; Clear D2 as it will be used to store the product
LOOP BTST.L #1,D1 ; Check if D1 is odd
BEQ ADDSUM ; If so branch to ADDSUM
RETURN CMP #$01,D1 ; Check if the multiplier is equal to 1
BEQ END ; If so, terminate the loop
ASL #1,D0 ; Multiply the multiplicand by 2
ASR #1,D1 ; Divide the multiplier by two
BRA LOOP ; Branch back to the top of the loop
ADDSUM ADD.W D0,D2 ; Add D0 to D2
BRA RETURN ; After adding, we have to branch back to where we were in the loop
END SIMHALT
A: I figured it out. I figured I'd post it as an answer just in case anybody else ever stumbles upon this.
It turns out I didn't understand how the BTST.L #1,D1 instruction works. I thought the code in the original example was supposed to be checking if the last bit in D1 was equal to 1. In reality, BTST works by setting the Z condition code flag to 1 when the bit being tested is 0. The #1 in the instruction was specifying that it was testing the second bit from the right.
In order to determine even/odd, the rightmost bit is the one that has to be tested. I fixed my code by changing it to have the following:
LOOP BTST.L #0,D1 ; Check if D1 is even (Z-flag will be set to 1 if bit is zero)
BNE ADDSUM ; BNE will branch to ADDSUM if Z-flag is not set (meaning D1 is odd)
Hopefully this is able to help somebody else who is having the same problem.
| |
doc_23538339
|
SELECT ReportedDate
FROM table
WHERE ReportedDate IN (
SELECT ReportedDate
FROM table
GROUP BY ReportedDate
HAVING count(*) > 1
ORDER BY ugid, ReportedDate
)
However when I perform the same query on the actual table (1.5 million records), MySQL returns all rows as if it would with a SELECT * FROM table query.
Thank you for any kind of help
A: Your subquery isn't needed, and with a large data set will impact performance.
Instead of using the subquery and count(*), you might try this:
SELECT ReportedDate
FROM table
GROUP BY ReportedDate
HAVING count(DISTINCT ReportedDate) > 1
ORDER BY ugid, ReportedDate
Notice the distinct in the having clause.
A: Probably your table does not have unique ReportedDate values - they appear in table at least twice each.
| |
doc_23538340
|
In the WordPress > Woocommerce > Under Products Tab > Filter the required category of products and choose Bulk Edit.
I do not see an option to change the "Product Date Type" from Sample Products to Variable Products.
Is there a easy way to do it for multiple products?
| |
doc_23538341
|
<iframe src="http://www.solstas.com/find-a-location/" width="837" height="544">
</iframe>
And this code using jquery:
$("#siteloader").html('<object data="http://www.solstas.com/find-a-location/">');
But it's not showing anything, I tried other website then it works. Some says that it might probably because of X-Frame-Options being set to that site.
Please help.
A: You can try:
$("#siteloader").append($('<iframe width="837" height="544" src="http://www.solstas.com/find-a-location/"></iframe'));
A: You're not going to be able to frame this, because the site uses X-Frame-Options. I did this request:
GET /find-a-location HTTP/1.1
Host: www.solstas.com
And got this response:
HTTP/1.1 302 Found
Cache-Control: private
Content-Length: 176
Content-Type: text/html; charset=utf-8
Location: /error/internal-server-error?aspxerrorpath=/find-a-location
Server: Microsoft-IIS/7.5
X-Umbraco-Version: 4.7
Set-Cookie: UserLatitude=29.8301; path=/
Set-Cookie: UserLongitude=-95.4739; path=/
X-Powered-By: ASP.NET
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Date: Fri, 14 Mar 2014 06:15:15 GMT
<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="/error/internal-server-error?aspxerrorpath=/find-a-location">here</a>.</h2>
</body></html>
The X-Frame-Options: SAMEORIGIN means this page shouldn't be displayed in a frame, including an iframe. Practically speaking, it means you can't do it, because pretty much all modern browsers will obey this request.
A: This is the code to load iframe source to jquery
$(document).ready(function() {
$('#iframe').attr('src', 'http://www.solstas.com/find-a-location/');
});
Note : This will work if that domain(www.solstas.com) permits cross-origin framing
| |
doc_23538342
|
How can i create the database of this kind of flow? What i came up with is the following:
Question Types
*
*id
*type
Questions
*
*id
*question
*question_type_id
Question User
*
*question_id
*user_id
*value
Survey Question (the tricky part that i can't figure out)
*
*question_id
*survey_id
*value ?? (not sure if this should be a json field or do another thing)
Hope u guys can give me another idea about the database design.
A: It helps if you state the domain in a semi structured language. If I understand it correctly:
The system has two types of users, "administrators" and "answerers".
Answerers can belong to zero or more groups.
The system has many surveys.
A survey is applicable to exactly one group.
A survey has many questions.
An answerer can answer each question once.
If this is correct, it's much easier to derive the entities and relationships.
*User*
User_id (pk)
User_type (enum)
*Group*
Group_id (pk)
Description
*User_group*
User_id (pk, fk)
Group_id (pk, fk)
*Survey*
Survey_id (pk)
Group_id (fk)
....
*Question*
Question_id (pk)
Survey_id (fk)
Question_text
....
*Answer*
Question_id (pk, fk)
User_id (pk, fk)
Answer_text
....
| |
doc_23538343
|
So, neither I can't use block animations nor UIKit animations before 4.0. I try to use Core Animation.
Here's my code:
[CATransaction begin];
[CATransaction setAnimationDuration: 3.0];
[CATransaction setDisableActions: YES];
someView.frame = CGRectMake(endX, 0, endWidth, height);
// a lot of another property changes
[CATransaction commit];
Unfortunately, it doesn't work: views change size/opacity immediately, without any animation.
Here's my attempts:
*
*I set new frame not to view but to its layer (someView.layer.frame = ...) - it was even worse because subviews of view weren't resized.
*I set disable action option to YES and NO.
Solution requirements:
*
*iOS 3.2 must be supported (no blocks).
*Animations must be applied to different views (consequently, to different layers).
*Animation curve is difficult enough, so I can't use pre-defined animation curves (or, by CA language, MediaTimingFunction).
A: The code you posted explicitly disables animations. This line is the culprit:
[CATransaction setDisableActions: YES];
By making that call, all the changes made in your transaction will be committed immediately, without animating. Get rid of that line and the changes should animate.
If you need a custom curve you might want to use a CABasicAnimation, as someone else suggested. Indeed, CAAnimation objects only apply to a single layer, so you'd have to create multiple CAAnimation objects.
Alternately, you should be able to use the CATransaction method setAnimationTimingFunction, and pass it a custom timing function that you create. See the CAMediaTimingFunction class reference. Specifically take a look at the method functionWithControlPoints::::, which lets you create a timing function by specifying the control points for a bezier curve that describes your timing function. You are limited to a single cubic bezier that starts at 0,0 and ends at 1,1. There is no direct support for more complex timing functions, although I have seen hacks that achieve more complex effects.
A: Am not sure about if this is what you want or not, but you could use UIView animations
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:3.0];
someView.frame = CGRectMake(endX, 0, endWidth, height);
// a lot of another property changes
[UIView commitAnimations];
A: If you only want to have a custom timing function then you can do it with a CABasicAnimation. You can create a custom timing function (which is a bezier curve from (0,0) to (1,1) with two control points that you can specify.
If that is not enough for you (if you need more than 2 control points for your timing function) then you would have to use a CAKeyframeAnumation. Then you can specify as many values as you want (using the values property (an array).
In both cases you would create a animation object for the keypath "frame" and add the animation to the views layer. Note that animating a property explicitly doesn't change the value so after the animation te frame will go back to its original value unless you both animate and change the value
| |
doc_23538344
|
A: There're many source codes available if you can use google and bing... If you want to build this application with C# programming language, then you need to know some basics of Network Programming in C#.
*
*If you want build a program like voice chat. You will need grab the audio from the microphone using some technalogies like DirectSound, UDP packets and etc.
*If you want build a video streaming application you can use several ways to get video streaming/conferencing with .net easily.
Use of plain Windows Media Encoder components, RTC Clients, voice/SIP, Sockets and etc.
So you have wide choice of managed technologies here. Another thing is Live Meeting at which you had no chance to take good look yet.
A: For those still interested I found the NAudio library really interesting: https://github.com/naudio/NAudio
| |
doc_23538345
|
Currently, to open my private and public key pairs, I use the following expression:
fopen(dirname(__FILE__) . '/rsa_private_key.pem', 'r');
dirname(__FILE__) directs to /vagrant/opencart/upload/catalog/controller/payment, which is where this script that gets executed also resides. So, the private/public key pair resides in the same folder as the script that opens it.
I am doing some file restructuring, and have created a new folder under the path : /vagrant/opencart/upload/keys, where both my private and public keys now reside.
However, I am not quite sure how to point my fopen() to it. Since I am currently developing on my local machine, I could, say, for now use an absolute path, but soon this will be on different servers, so I cannot use absolute path forever.
My question is, how do I point fopen() to this path: /vagrant/opencart/upload/keys?
A: The first thing you should do is move your private key OUTSIDE of the web server's document root. The nature of the term "private key" tells you that you do NOT want someone to be able to access these keys! Putting them under the web server's docroot exposes them unnecessarily - even if you put rules in place to protect them (e.g., htaccess file), there's simply no reason to put them in a location that is - by definition - intended to be accessible by default.
Depending on what distribution you're going to eventually deploy on, there will likely be a standard location for deploying such; if not, I encourage you to define your own policy, such as putting them under /etc/opencart/keys.
Once you know/define your policy, you will have an absolute path that you can use, solving the original problem.
| |
doc_23538346
|
But the images are not displaying. And I am getting the following error in the console.
GET https://scontent-arn2-2.cdninstagram.com/v/t51.2885-15/sh0.08/e35/s640x640/174191033_293248945850264_4706822520582962514_n.jpg?tp=1&_nc_ht=scontent-arn2-2.cdninstagram.com&_nc_cat=1&_nc_ohc=lUMp5EnMMW8AX__E42K&edm=ABfd0MgBAAAA&ccb=7-4&oh=c755580e7a5f0c8e3d4170122390efbc&oe=60AE0543&_nc_sid=7bff83 net::ERR_BLOCKED_BY_RESPONSE
I checked the headers in the browser. Here are the request and response headers.
Even I created a simple HTML file with a single image tag and used the
https://scontent-arn2-2.cdninstagram.com/v/t51.2885-15/sh0.08/e35/s640x640/174191033_293248945850264_4706822520582962514_n.jpg?tp=1&_nc_ht=scontent-arn2-2.cdninstagram.com&_nc_cat=1&_nc_ohc=lUMp5EnMMW8AX__E42K&edm=ABfd0MgBAAAA&ccb=7-4&oh=c755580e7a5f0c8e3d4170122390efbc&oe=60AE0543&_nc_sid=7bff83
as image source but still getting the same error.
Is there any possibility to display the images? or Instagram is not allowing us to use their images on websites?
A: If you didn't find any solution yet, then you can use below PHP code to encode this image to base64.
URL : $url = "https://instagram.fsaw2-1.fna.fbcdn.net/v/t51.2885-15/301187532_174294221755151_1309939808330850870_n.jpg?stp=dst-jpg_e15&cb=2d435ae8-d7f9aae8&_nc_ht=instagram.fsaw2-1.fna.fbcdn.net&_nc_cat=1&_nc_ohc=-J-JDy4ZH1sAX_dLrAQ&edm=ALCvFkgBAAAA&ccb=7-5&ig_cache_key=MjkxMTI3NjYxNDM3MzgyNDM0MQ%3D%3D.2-ccb7-5&oh=00_AT-U540t2c9oCNV-Rlvszq5xd9Tyv5iEZ8U36xbg13cMqg&oe=63082161&_nc_sid=643ae9"
For image : 'data:image/jpg;base64,'.base64_encode(file_get_contents($url))
For video : 'data:video/mp4;base64,'.base64_encode(file_get_contents($url))
If you have bulk conversion then you can encode to base64 via jquery as well.
Hope this helps.
| |
doc_23538347
|
I have a ForEach Loop, and when I click on the card, it appends a new element to the array and then IT SHOULD SHOW 2 CARDS.
But there is still one card. (but I appended the new card element)
So what should I do?
struct TimelineFromUserView: View {
var card: [Card] = cardData
var body: some View {
VStack {
HStack {
Text("History").bold()
.font(.largeTitle)
.padding(.top, 20)
.padding(.leading, 20)
Spacer()
}
Divider()
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 30) {
ForEach(card) { item in
CardForTimeline(card: item)
.onTapGesture {
print("juhuu")
cardData.append(Card(number: 2, start: "01.10.2021", end: "20.10.2021", days: 19, success: false))
print(cardData)
}
.padding()
}
}
.padding(.top, 10)
}
}
}
}
struct Card: Identifiable{
var id = UUID()
var number: Int
var start: String
var end: String
var days: Int
var success: Bool
}
var cardData: [Card] = [
Card(number: 1 ,start: "05.06.2020", end: "15.06.2020", days: 10, success: true)
]
A: You only pass a copy card of the array cardData into the ForEach but if I understand your code snippets correctly it should be the original array cardData.
If that's not the problem it would be helpful to post more of your code.
A: I just replace CardForTimeline on Text (because I didn't have your CardForTimeline) and it return me 2 (also I replaced print(cardData) on print(cardData.count)). You can create fully new project and add this code. It will print 2, 3, 4, 5 after taps
struct ContentView: View {
var card: [Card] = cardData
var body: some View {
VStack {
HStack {
Text("History").bold()
.font(.largeTitle)
.padding(.top, 20)
.padding(.leading, 20)
Spacer()
}
Divider()
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 30) {
ForEach(card) { item in
Text(verbatim: "we")
.onTapGesture {
print("juhuu")
cardData.append(Card(number: 2, start: "01.10.2021", end: "20.10.2021", days: 19, success: false))
print(cardData.count)
}
.padding()
}
}
.padding(.top, 10)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Card: Identifiable{
var id = UUID()
var number: Int
var start: String
var end: String
var days: Int
var success: Bool
}
var cardData: [Card] = [
Card(number: 1 ,start: "05.06.2020", end: "15.06.2020", days: 10, success: true)
]
A: the problem is that SwiftUI does not know to update the view. Try writing
@State private var card: [Card] = [
Card(number: 1 ,start: "05.06.2020", end: "15.06.2020", days: 10, success: true)
]
instead of: var card: [Card] = cardData.
This should work because then you are telling SwiftUI that it should update the view whenever the value changes.
Additionally you would have to change the adding part of your code to this:
.onTapGesture {
self.card.append(Card(number: 2, start: "01.10.2021", end: "20.10.2021", days: 19, success: false))
}
The above is an approach using a local @State property to manage the state. You could also use a observable object with an array of cards instead. This could look like this:
struct ContentView: View {
@ObservedObject private var cardData = CardData()
var body: some View {
VStack {
HStack {
Text("History").bold()
.font(.largeTitle)
.padding(.top, 20)
.padding(.leading, 20)
Spacer()
}
Divider()
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 30) {
ForEach(cardData.cards) { card in
Text(card.id.uuidString)
.onTapGesture {
self.cardData.add(card: Card(number: 2, start: "01.10.2021", end: "20.10.2021", days: 19, success: false))
}
.padding()
}
}
.padding(.top, 10)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Card: Identifiable{
var id = UUID()
var number: Int
var start: String
var end: String
var days: Int
var success: Bool
}
class CardData: ObservableObject {
// store the cards and make sure its get-only from the outside
@Published private(set) var cards = [
Card(number: 1 ,start: "05.06.2020", end: "15.06.2020", days: 10, success: true)
]
// MARK: - Intents for modifing the cards, add additional if needed
func add(card: Card) {
self.cards.append(card)
}
}
I hope this will help you with your problems
| |
doc_23538348
|
This is the code I am usiong for the popup:
echo '<script>
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write(' . json_encode($row2["ARTICLE_DESC"]) . ');
child1.document.close();
}
</script>';
And the resulting html
<script>
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write("<!-- +++++++++++++++++++++++++ Bitte \u00e4ndern Sie im eigenen Interesse nichts an diesem Code! ++++++++++++++++++++++++ -->\n<!-- +++++++++++++++++++++++++ Das kann massive Fehldarstellungen ihrer Auktion zur Folge haben! +++++++++++++++++++ -->\n<!-- +++++++++++++++++++++++++ ++++++++++++++++++++++++++ Ihr Supreme Team +++++++++++++++++++++++++++++++++++++++++ -->\n");
child1.document.close();
}
</script><br />
<b>Notice</b>: Undefined index: CATEGORY in <b>C:\Programme\EasyPHP 2.0b1\www\get_auction.php</b> on line <b>39</b><br />
<div id='leftlayer'>
<strong>Article Number</strong> 220288560247
<p><strong>Article Name</strong></p> Ed Hardy Herren Shirt Rock & Roll Weiss XXL Neu & OVP
<p><strong>Subtitle</strong></p>
<p><strong>Username</strong></p> fashionticker1
<p><strong>Total Selling</strong></p> 1
<p><strong>Total Sold</strong></p> 0
<p><strong>Category</strong></p>
<p><strong>Highest Bidder</strong></p> 0
</div>
<div class='leftlayer2'>
<strong>Current Bid</strong> 0.00
<p><strong>Start Price</strong></p> 49.00
<p><strong>Buyitnow Price</strong></p> 59.00
<p><strong>Bid Count</strong></p> 0
<p><strong>Start Date</strong></p> 1.10.2008 16:22:09
<p><strong>End Date</strong></p> 6.10.2008 16:22:09
<p><strong>Original End</strong></p> 6.10.2008 16:22:09
<p><strong>Auction Type</strong></p> 1
</div>
<div class='leftlayer2'>
<strong>Private Auction</strong></p> 0
<p><strong>Paypal Accepted</strong></p> 0
<p><strong>Auction Watched</strong></p> 0
<p><strong>Finished</strong></p> 1
<p><strong>Country</strong></p>
<br>
<br>
<style ty
<p><strong>Location</strong></p> float: right;
<p><strong>Conditions</strong></p> margin: 0px;
</div>
<div class='leftlayer2'>
<strong>Auction Revised</strong></p> 0
<p><strong>Cancelled</strong></p> 0
<p><strong>Shipping to</strong></p> padding:5px;
<p><strong>Fee Insertion</strong></p> 0.00
<p><strong>Fee Final</strong></p> 0.00
<p><strong>Fee Listing</strong></p> 0.00
<p><a href='#' onclick='makewindows(); return false;'>Click for full description </a></p>
</div><div id='rightlayer'>Picture Picture
<img src=http://storage.supremeauction.com/flash/ebay2/10/49/76/10497654/13895964e.jpg>
</div>
The img src is a valid location and opens in a browser fine, but will not display in the page. I get a script error which does not state any details.
edit: When calling the file alone, not as part of the application, the resulting html file generates a link that creates a popup window, but the source shows that nothing is being assigned to the window:
child1.document.write("");
I made changes to the img src line:
<img src='".$lastImg."'>
Which results in the html returning:
<img src=''>
A: You really need to get Firefox/Firebug to help debug this. It's possible that your script error is causing the page to stop loading and thus your image is not displayed.
A: Your HTML looks invalid - you have:
<style ty
<p><strong>Location</strong></p> float: right;
<p><strong>Conditions</strong></p> margin: 0px;
Firstly the <style> tag is not closed (1. the opening tag is not even complete and 2. you don't have a closing tag) - when I look at the HTML using Firefox/Firebug, it is treating the rest of the HTML as being within that tag and therefore not displaying it.
Also you have style declarations like float: right; mixed within the HTML and not within a style tag.
A: If you carry this response through Ajax using innerHTML substitution it won't work. You need to parse the <script>...</script> in callback and eval() it.
And in general, you should be using some decent PHP framework on server side and Javascript library on client side. Otherwise you will soon start rewriting your program from scratch to clean it up, just to find out that it's hardly any better.
| |
doc_23538349
|
This Question was ask in One of my Interview.
Thanks
A: java.util.concurrent.Executors.newThreadPool(1).submit(Callable) will create a thread. The Callable implementation you submit will be run in that thread and a Future returned.
A: Ever since Java 1.5, you should not create threads manually, you should use high level concurrency tools (see for example Effective Java Item 68: Prefer executors and tasks to threads).
See the Executors page of the Oracle Concurrency trail or better yet, read Java Concurrency in Practice.
A: There is no way to create a Java thread without creating an instance of the Thread class or, an instance of some class that extends Thread...
...But that doesn't mean that your code has to create the new Thread instance. There are various library classes that create and use threads on your behalf (e.g., ThreadPoolExecutor, the java.util.stream package, etc.)
| |
doc_23538350
|
s = "aaabbbd"
def check_freq(s):
freq = {}
for c in s:
freq[c] = s.count(c)
for w in sorted(freq, key=freq.get, reverse=True):
if freq[w] == 1:
del freq[w]
print (w, freq[w])
check_freq(s)
Error is below
File "<ipython-input-60-a79c71ac1b31>", line 10, in check_freq
print (w, freq[w])
KeyError: 'd'
Expected output
{'a': 3, 'b': 3}
A: If you delete the key, how can you print it? Because the key is deleted, it raises a KeyError as the key is no longer present. Just add a continue when you delete it.
s = "aaabbbd"
def check_freq(s):
freq = {}
for c in s:
freq[c] = s.count(c)
for w in sorted(freq, key=freq.get, reverse=True):
if freq[w] == 1:
del freq[w]
continue
print (w, freq[w])
return freq
result = check_freq(s)
>a 3
b 3
result
> {'a': 3, 'b': 3}
A: The KeyError is happening because when you write
if freq[w] == 1:
del freq[w]
print (w, freq[w])
for w = 'd', freq[w] = 1. So, you are deleting freq[w] but in the next line, you are trying to print freq[w] which doesn't exist.
You could avoid this by using an if-else clause.
s = "aaabbbd"
def check_freq(s):
freq = {}
for c in s:
freq[c] = s.count(c)
for w in sorted(freq, key=freq.get, reverse=True):
if freq[w] == 1 or freq[w] == 2:
del freq[w]
else:
print (w, freq[w])
print(freq)
check_freq(s)
Output:
a 3
b 3
{'a': 3, 'b': 3}
A: By deleting the entry from the freq dictionary you cannot print it anymore; it doesn't exist. You could add an else clausule to prevent this:
for w in sorted(freq, key=freq.get, reverse=True):
if freq[w] == 1:
del freq[w]
else:
print (w, freq[w])
A: You could try this:
s = "aaabbbd"
def check_freq(s):
freq = {}
for c in s:
freq[c] = s.count(c)
for key, value in freq.items():
if value == 1:
del freq[key]
return freq
print check_freq(s)
Output:
{'a': 3, 'b': 3}
Actually you don't need to sort the dictionary. You just need to iterate through its elements and check whether the key is equal to one. Then delete this key-value pair from the dictionary.
A: Keep delete in try block and that worked for me.
try:
del freq[w]
except Exception as e:
print(e)
A: Instead of deleting keys, you could always rebuild a new dictionary with only keep keys with values greater than 2:
from collections import Counter
s = "aaabbbd"
counts = {k: v for k, v in Counter(s).items() if v > 2}
print(counts)
# {'a': 3, 'b': 3}
Which also uses collections.Counter() to construct the counts. Using s.count() is very inefficient since it scans the whole string each time to count a character. This ends up being quadratic O(N^2), since it has to visit every character for each character. Counter() simply counts all the characters in one traversal, which is O(N).
If you want to delete from the same dictionary, you can iterate over a copy and delete from the original with dict.pop:
from collections import Counter
s = "aaabbbd"
counts = Counter(s)
count_items = list(counts.items())
for k, v in count_items:
if v <= 2:
counts.pop(k) # Or del counts[k]
print(counts)
# Counter({'a': 3, 'b': 3})
Note: Counter() is a subclass of dict, so you can treat them the same. Having said this, one of the differences is that Counter() doesn't raise KeyError when a key doesn't exist, it returns 0 instead.
This can be demonstrated here:
>>> from collections import Counter
>>> x = Counter({'a': 1})
>>> y = {'a': 1}
>>> x['b']
0
>>> y['b']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'b'
| |
doc_23538351
|
I have the following query, which works really well:
items.find({"repo":{"$eq":"my-repository-virt"}}, {"$and":[{"@my.fileType":{"$match": "jar"}},{"@my.otherType":{"$match": "type2"}},{"@prodVersion":{"$match": "false"}}]})
But I have a problem in that there are duplicate files in some sub-folders with the same properties/filename that I would like to exclude.
I would like to add path to this query, but I can never get any results returned.
The repository is a virtual repository that links to 3 other real repositories.
One of my colleagues can call the following query with the command line tool and get the expected results:
jfrog rt search my-repo-snapshots/myproject/subfolder/jars/*.jar
I have tried adding the path parameter to my query, I've tried removing everything except the repo and the path, like this:
items.find({"repo":{"$eq":"my-repo-snapshots"}},{"path" : "my-repo-snapshots/myproject/subfolder/jars/*.jar"})
I've tried with just the path, with variations on the path, including/excluding the repo name, using the virtual repo, the actual repo, but I always get a successful search with 0 results returned.
How can I build this query to search the virtual repo, along a certain path, and including certain properties?
EDIT:
I've also tried:
items.find({"repo":{"$eq":"my-repo-snapshots"}},{"path" : {"$match":"my-repo-snapshots/myproject/subfolder/jars/*.jar"}})
Both with the repo in the path and without, I still get 0 results.
A: OK I figured it out.
The path part needs to be added in with the {"$and": ...} section where the properties are included. Like so:
items.find({"repo":{"$eq":"my-repository-virt"}},
{"$and":[
{"path":{"$match":"path/to/relevant/folders/*"}},
{"@my.fileType":{"$match": "jar"}},
{"@my.otherType":{"$match": "type2"}},
{"@prodVersion":{"$match": "false"}}
]})
A: The easier fix would have been:
items.find({"repo":{"$eq":"my-repo-snapshots"}},{"path" : {"$eq":"my-repo-snapshots/myproject/subfolder/jars"}, {"name" : {"$match":"*.jar"}})
So the problem with your initial attempt, is that the "path" should match the folder and the "name" should match the filename
| |
doc_23538352
|
My original code is something like this:
import Queue
from threading import Thread
num_fetch_threads = 4
enclosure_queue = Queue()
for i in range(num_fetch_threads):
worker = Thread(target=run_experiment, args=(i, enclosure_queue))
worker.setDaemon(True)
worker.start()
for experiment in experiment_collection:
enclosure_queue.put((experiment, otherVar))
enclosure_queue.join()
And the queue function like this:
def run_experiment(i, q):
while True:
... do stuff ...
q.task_done()
My new code is somethings like this:
from multiprocessing import Process, Queue
num_fetch_threads = 4
enclosure_queue = Queue()
for i in range(num_fetch_threads):
worker = Process(target=run_experiment, args=(i, enclosure_queue))
worker.daemon = True
worker.start()
for experiment in experiment_collection:
enclosure_queue.put((experiment, otherVar))
worker.join() ## I only put this here bc enclosure_queue.join() is not available
And the new queue function:
def run_experiment(i, q):
while True:
... do stuff ...
## not sure what should go here
I have been reading the docs and Google, but can't figure out what I am missing - I know that task_done / join are not part of the multiprocessing Queue class, but it's not clear what I am supposed to use.
"They differ in that Queue lacks the task_done() and join() methods
introduced into Python 2.5’s Queue.Queue class." Source
But without either of those, I'm not sure how the queue knows it is done, and how to continue on with the program.
A: Consider using a multiprocessing.Pool instead of managing workers manually. Pool handles dispatching tasks to workers, with convenient functions like map and apply, and supports .close and .join methods. Pool takes care of handling the queues between processes and processing the results. Here's how your code might look like using multiprocessing.Pool:
from multiprocessing import Pool
def do_experiment(exp):
# run the experiment `exp`, will be called by `p.map`
return result
p = Pool() # automatically scales to the number of CPUs available
results = p.map(do_experiment, experiment_collection)
p.close()
p.join()
| |
doc_23538353
|
A: There are various solutions suggested online (and there is still no flutter webview patch for transparent background start-up).
A reliable workaround is wrapping the webview in an indexed Stack widget and showing a black loading card until the web view fires its page loaded event, then switching to the webview.
| |
doc_23538354
|
Warning messages:
1: In scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, :
Reached total allocation of 7128Mb: see help(memory.size)
2: In scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, :
Reached total allocation of 7128Mb: see help(memory.size)
I tried doing this :
memory.size()
[1] 766.68
memory.limit()
[1] 7128
But still my file doesn't get loaded and I keep getting this warning. Is there a way I can get around reading this file in R?
Thank you !
A: R can be incredibly memory inefficient when loading large datasets. From the documentation:
Memory usage
These functions can use a surprising amount of memory when reading
large files. There is extensive discussion in the ‘R Data
Import/Export’ manual, supplementing the notes here.
Less memory will be used if colClasses is specified as one of the six
atomic vector classes. This can be particularly so when reading a
column that takes many distinct numeric values, as storing each
distinct value as a character string can take up to 14 times as much
memory as storing it as an integer.
Using nrows, even as a mild over-estimate, will help memory usage.
Using comment.char = "" will be appreciably faster than the read.table
default.
read.table is not the right tool for reading large matrices,
especially those with many columns: it is designed to read data frames
which may have columns of very different classes. Use scan instead for
matrices.
| |
doc_23538355
|
How to view pdf string in a new browser window?
js code:
/two inputs to get pdf file/
var selectedFileSlot={"END407":"report_28_03_13.pdf","END408":"[B@cef121c","END409":"*.pdf;*.doc;*.docx;*.odt;*.ods","END410":"5242880"}
var selectedNode= {"objectID":"22df1b2601a3552f24e5f011abc27f86","specID":"2001","entityConcreteID":"11000"}
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.response);
window.open(xmlhttp.response);//not able to open in new browser window
}
}
xmlhttp.open("GET","downloadDocument.action?selectedNode=" + JSON.stringify(selectedNode) + "&selectedFileSlot=" + JSON.stringify(selectedFileSlot),true);
xmlhttp.send();
struts.xml code:
<action name="downloadDocument" class="commonAction" method="downloadDocument">
<interceptor-ref name="sessionStack"></interceptor-ref>
<interceptor-ref name="cachingStack"></interceptor-ref>
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${fileFileName}"</param>
<param name="bufferSize">1024</param>
</result>
</action>
action class code:
commonDTO.setSelectedNode(this.selectedNode);
commonDTO.setSelectedFileSlot(this.selectedFileSlot);
byte[] bytes = commonDAO.getDownloadDocument(commonDTO); //getting pdf as byte array
inputStream = new ByteArrayInputStream(bytes);
A: That is the binary content of the PDF file, that you can't handle in Javascript, and that you need to return with application/pdf Content-type (not text/html or application/octet-stream), with a Stream result.
Why on earth are you using AJAX to load it in a new window ? Just use one of the following way.
| |
doc_23538356
|
subscripted value is neither array nor pointer nor vector.
The error is in
if((matriz[i][j]>maximo)&&(esta(vector[nvertices-1],i,j,nvertices)==0)){
and
siguiente=vector[i];
I am not quite clear what is the reason behind the error.
CODE:
#include<stdlib.h>
#include<stdio.h>
void camino(int* vector,int matriz,int nvertices);
int esta(int vector,int inicio,int fin,int nvertices);
int main(){
int nvertices; //numero de vertices
int nconexiones; //numero de conexiones disponibles
int i,j; //indices para recorrer la matriz
int conex = 0; //rectificador de conexiones
printf("Introduce el numero de vertices: ");
scanf("%d",&nvertices);
printf("Introduce el numero de conexiones disponibles: ");
scanf("%d",&nconexiones);
int matad[nvertices][nvertices]; //matriz de adyacencia
for(i=1;i<=nvertices;i++){ //Rellenar la matriz con ceros, por defecto no hay ninguna conexion
for(j=1;j<=nvertices;j++){
matad[i][j]=0;
}
}
printf("Introduce las capacidades.Si no existe introduce 0:\n");
for(i=1;i<=nvertices;i++){ //Introducimos las capacidades
for(j=1+i;j<=nvertices;j++){
if(conex<nconexiones){
printf("Ciudad %d - Ciudad %d: ",i,j);
scanf("%d",&matad[i][j]);
matad[j][i]=matad[i][j];
conex++;
}
}
}
int caminos[nvertices-1]; //Variable que almacena el camino (como una lista de vertices)
camino(&caminos[nvertices-1],matad[nvertices][nvertices],nvertices);//Llamada a la funcion camino
return 1;
}
void camino(int* vector,int matriz,int nvertices){
int i,j; //Indices para recorrer la matriz de adyacencia
for(i=1;i<=nvertices;i++){ //-- Explicacion --
int maximo = 0; //Vamos a empezar por el vertice 1, bucamos el camino de mayor
for(j=1;j<=nvertices;j++){ //capacidad, una vez lo tenemos comprobamos si esa union 1->X esta
if((matriz[i][j]>maximo)&&(esta(vector[nvertices-1],i,j,nvertices)==0)){ //o no esta en nuestra lista mediante la funcion esta(...), si esta
maximo=j; //lo añadimos y ahora partimos desde el vertice X -> Y, en caso
} //contrario hemos acabado.
} //------------------
} //La variable maximo es utilizada para ver que vertice tiene la mayor
} //capacidad
int esta(int vector,int inicio,int fin,int nvertices){
int anterior=0;
int siguiente=0;
int encontrado=0;
int i;
for(i=1;i<=nvertices-1;i++){
anterior=siguiente;
siguiente=vector[i];
if((inicio==anterior)&&(fin==siguiente)){
encontrado=1;
}
}
return encontrado;
}
A: *
*In your camino() function, matriz is an int.
*In your esta() function, vector is an int, too.
You can use the array indexing operator only on array type variables.
| |
doc_23538357
| ||
doc_23538358
|
In my use case however, I need to actively kill the timer.
The relevent part of code from the turtle module is:
def _ontimer(self, fun, t):
"""Install a timer, which calls fun after t milliseconds.
"""
if t == 0:
self.cv.after_idle(fun)
else:
self.cv.after(t, fun)
This answer explains how to destroy a timer using pure python tkinter. I found the after method in turtle._Root but I can't see how to get access to the id for it, or figure out exactly how I would use it if I had it.
Any help much appredciated.
Here's a sample program I would like to apply the solution to:
import turtle
turtle.shape("turtle")
def move():
turtle.fd(20)
turtle.ontimer(move, 500)
move()
turtle.done()
| |
doc_23538359
|
The data I have is taken from a PDF and looks like this upon reading into a DataFrame
Output
Summary
Prior Years
1
2
3
4
5
6
7
8
9
10
Total
Total Value 3,700
110
-
-
-
5
NaN
-
-
-
-
--
3,815
Total Value
115 100
-
-
-
10
NaN
-
-
-
-
--
225
The expected table output is
Expected Output
Summary
Prior Years
1
2
3
4
5
6
7
8
9
10
Total
Total Value
3,700
110
-
-
-
5
-
-
-
-
--
3,815
Total Value
115
100
-
-
-
10
-
-
-
-
--
225
To resolve the errors from the original output I did as follows
test.loc[:,"1":"5"]=test.loc[:,"Prior Years":"5"].shift(axis=1)
test[['Summary','Prior Years']]=test['Summary'].str.strip().str.extract(r'(\D*).*?([\d\,\.]*)' )
and
test.loc[:,"1":"5"]=test.loc[:,"Prior Years":"5"].shift(axis=1)
test[['Prior Years', '1']]=test['Prior Years'].str.split(' ',expand=True)
These solve the respective issues in both columns when isolated but I am looking to utilize both these conditions simultaneously
When I attempt to write 'for' loops using these conditions above, it affects the whole dataframe, rather than just the row where individual conditions are met
An example of this is
for i in test.loc[:,'Summary']:
if len(i)>12:
test.loc[:,"1":"5"]=test.loc[:,"Prior Years":"5"].shift(axis=1)
test[['Summary','Prior Years']]=test['Summary'].str.strip().str.extract(r'(\D*).*?([\d\,\.]*)' )
Which then outputs
Output
Summary
Prior Years
1
2
3
4
5
6
7
8
9
10
Total
Total Value
3,700
110
-
-
-
5
-
-
-
-
--
3,815
Total Value
115 100
-
-
-
10
-
-
-
-
--
225
I am using the string length criteria as the hit for the for loop as the 'Summary' Column and 'Prior Years' Column will have fairly uniform str lengths
A: Right now your operations are affecting the whole column. If you loop through the index instead, you can limit the operation to just the rows you want to change:
for idx in test.index:
if len(test.loc[idx, "Summary"]) > 12:
test.loc[idx,"1":"5"] = test.loc[idx,"Prior Years":"5"].shift(axis=1)
test.loc[idx, ['Summary','Prior Years']] = test.iloc[idx, 'Summary'].str.strip().str.extract(r'(\D*).*?([\d\,\.]*)' )
if len(test.loc[idx, "1"]) > 5:
test.loc[idx,"1":"5"] = test.loc[idx,"Prior Years":"5"].shift(axis=1)
test.loc[idx, ['Prior Years', '1']] = test.loc[idx, 'Prior Years'].str.split(' ',expand=True)
If this code is too slow, it's also possible to vectorize this:
mask = test.Summary > 12
test.loc[mask,"1":"5"] = test.loc[mask,"Prior Years":"5"].shift(axis=1)
test.loc[mask, ['Summary','Prior Years']] = test.iloc[mask, 'Summary'].str.strip().str.extract(r'(\D*).*?([\d\,\.]*)' )
mask = test["1"] > 5
test.loc[mask,"1":"5"] = test.loc[mask,"Prior Years":"5"].shift(axis=1)
test.loc[mask, ['Prior Years', '1']] = test.loc[mask, 'Prior Years'].str.split(' ',expand=True)
| |
doc_23538360
|
Furthermore, the alternative
representations shown in Table 4 for
certain operators and punctuators
(2.5) are reserved and shall not be
used otherwise:
and, and_eq, bitand, bitor, compl,
not, not_eq, or, or_eq, xor, xor_eq
I have tried using these with multiple compilers without problems.
From my understanding I'm only forbidden to use these as identifier names.
English isn't my first language, so it would be nice if someone could verify that I can indeed use these bit-wise mnemonics in expressions (i.e., "int i = not 0;").
EDIT: I should probably point out that I'm not going to obscure code by using these (if they are valid). It's just for general knowledge. =)
Thanks!
A: Yes, you can use them as alternative to name tokens. For example:
struct foo {
// defines a destructor
compl foo() { }
};
Your example would work too. It would however store an one into i. If you want to use bitwise not, you use compl (~):
int i = compl 0;
| |
doc_23538361
|
var sqltext,
listboxtext,
primaryindivtext,
title : string;
queryeof : boolean;
begin
sqltext := 'drop table ';
sqltext := sqltext+'form401ds;';
sqltext := sqltext+'create table form401ds (';
sqltext := sqltext+'sourcelistno integer,';
sqltext := sqltext+'sourceassociation integer,';
sqltext := sqltext+'sourceseqno integer,';
sqltext := sqltext+'sourceid varchar(20),';
sqltext := sqltext+'id varchar(20),';
sqltext := sqltext+'title varchar(40),';
sqltext := sqltext+'primaryindiv varchar(40) );';
DataMod.*IBSQL1.SQL.text* := sqltext;
DataMod.*IBSQL1.ExecSQL*;
A: For units already part of the project referencing them in code and then doing a build will prompt asking if you want the unit added to the uses clause. Trying to built code with the below with a Unit2 in the project:
procedure TForm1.Button1Click(Sender: TObject);
begin
Unit2.
end;
Gets a dialog:
Answering yes the implementation section is updated to include the unit:
implementation
{$R *.dfm}
uses Unit2;
Code completion will now work for things defined in the other unit.
A:
I have a database defined in a datamodule (DataMod)
I also obviously have a USES statement for DataMod defined in the main unit
It appears you are mixing unit name and data module name. Your description hints that the units name is
unit DataMod;
If this is the case, then the data module class can not be TDataMod (and instance can not be DataMod).
Perhaps the name of the data module class is TDataModule2. Then the interface part would look like this:
unit DataMod;
interface
uses
System.SysUtils, System.Classes, IBX.IBSQL;
type
TDataModule2 = class(TDataModule)
IBSQL1: TIBSQL;
private
public
end;
And then the instance would be declared as:
var
DataModule2: TDataModule2;
Finally, to address the TIBSQL from your forms unit you would need to
add the unit name to the uses clause in the implementation section of the form unit:
uses DataMod;
refer to the TIBSQL instance as follows
DataModule2.IBSQL1.SQL.text := '...';
| |
doc_23538362
|
m = re.search(r'(\b\w+\b)\s+\1', 'Cherry tree blooming will begin in in later March')
print m.group()
m = re.search(r'(\b\w+)\s+\1', 'Cherry tree blooming will begin in in later March')
print m.group()
A: \s is just whitespace. You can have word boundaries that aren't whitespace (punctuation, etc.) which is when you need to use \b. If you're only matching words that are delimited by whitespace then you can just use \s; and in that case you don't need the \b.
import re
sentence = 'Non-whitespace delimiters: Commas, semicolons; etc.'
print(re.findall(r'(\b\w+)\s+', sentence))
print(re.findall(r'(\b\w+\b)+', sentence))
Produces:
['whitespace']
['Non', 'whitespace', 'delimiters', 'Commas', 'semicolons', 'etc']
Notice how trying to catch word endings with just \s ends up missing most of them.
A: Consider wanting to match the word "march":
>>> regex = re.compile(r'\bmarch\b')
It can come at the end of the sentence...
>>> regex.search('I love march')
<_sre.SRE_Match object at 0x10568e4a8>
Or the beginning ...
>>> regex.search('march is a great month')
<_sre.SRE_Match object at 0x10568e440>
But if I don't want to match things like marching, word boundaries are the most convenient:
>>> regex.search('my favorite pass-time is marching')
>>>
You might be thinking "But I can get all of these things using r'\s+march\s+'" and you're kind of right... The difference is in what matches. With the \s+, you also might be including some whitespace in the match (since that's what \s+ means). This can make certain things like search for a word and replace it more difficult because you might have to manage keeping the whitespace consistent with what it was before.
A: It's not because it's at the end of the word, it's because you know what comes after the word. In your example:
m = re.search(r'(\b\w+\b)\s+\1', 'Cherry tree blooming will begin in in later March')
...the first \b is necessary to prevent a match starting with the in in begin. The second one is redundant because you're explicitly matching the non-word characters (\s+) that follow the word. Word boundaries are for situations where you don't know what the character on the other side will be, or even if there will be a character there.
Where you should be using another one is at the end of the regex. For example:
m = re.search(r'(\b\w+)\s+\1\b', "Let's go to the theater")
Without the second \b, you would get a false positive for the theater.
A: "I understand that \b can represent either the beginning or the end of a word. When would \b be required to represent the end?"
\b is never required to represent the end, or beginning, of a word. To answer your bigger question, it's only useful during development -- when working with natural language, you'll ultimately need to replace \b with something else. Why?
The \b operator matches a word boundary as you've discovered. But a key concept here is, "What is a word?" The answer is the very narrow set [A-Za-z0-9_] -- word is not a natural language word but a computer language identifier. The \b operator exists for a formal language's parser.
This means it doesn't handle common natural language situations like:
The word let's becomes two words, 'let' & 's' if `\b' represents the boundaries of a word. Also consider titles like Mr. & Mrs. lose their period.
Similarly, if `\b' represents the start of a word, then the appostrophe in these cases will be lost: 'twas 'bout 'cause
Hyphenated words suffer at the hand of `\b' as well, e.g mother-in-law (unless you want her to suffer.)
Unfortunately, you can't simply augment \b by including it in a character set as it doesn't represent a character. You may be able to combine it with other characters via alternation in a zero-width assertion.
When working with natural language, the \b operator is great for quickly prototyping an idea, but ultimately, probably not what you want. Ditto \w, but, since it represents a character, it's more easily augmented.
| |
doc_23538363
|
The problem is I am only let to upload to "3.5-inch Retina Display", "4-inch Retina Display" and "iPad" (see screenshot below). There is no way I can choose for which iOS certain screenshots should be shown.
Am I doing something wring or is Apple´s intention that only iOS7 screenshots should be displayed in App Store?
A: you can upload your screenshots regardless of the version ios. I have an application that has four screenshots ios7 and one of iOS6 and had no problems.
A: You can't specify screenshots to be shown depending on the iOS version, however, the screenshots that you do post can be taken from any iOS version. So feel free to mix and match if you wish, or consider photoshopping a banner on them that says "Looks beautiful in both iOS 6 and iOS 7"
A: As I know there is no way of choosing iOS Screenshots . I too uploaded one app but there is no choice to choose iOS Screenshots .
| |
doc_23538364
|
Python Code-
def FRC(str):
h = {}
for ch in str:
if ch in h:
return ch
else:
h[ch] = 0
return '\0'
print(FRC("abcdedcba"))
I have tried a few possible codes and was able to only enumerate the array of characters to count their occurrences. Thank you for any suggestions.
Update1 - The code I have worked on is as follows:
function get-duplicatechar {
[CmdletBinding()]
param (
[string]$teststring
)
$hash = @()
$teststring = $teststring.ToCharArray()
foreach ($letter in $teststring)
{
if($letter -contains $hash){
return $letter
}else {
$hash = $hash + $letter
}
return "\0"
}
}
get-duplicatechar("saahsahh")
A: You could use the (.Net) HashSet class for this, which Add method (besides adding the value,) returns true if the element is added to the HashSet<T> object and false if the element is already present.
function get-duplicatechar {
[CmdletBinding()]
param (
[string]$str
)
$h = [System.Collections.Generic.HashSet[char]]::new()
foreach ($ch in $str.ToCharArray()) {
if(!$h.add($ch)) { return $ch }
}
}
A: Here's a working version using your code as base:
function get-duplicatechar {
[CmdletBinding()]
param (
[string]$teststring
)
$hash = @{}
$CharArray = $teststring.ToCharArray()
foreach ($letter in $CharArray) {
if($letter -in $hash.Keys) {
$letter
break
}
else {
$hash[$letter] = $null
}
}
}
One problem is that you are strongly typing $teststring to be a string, so when you add a character array later PowerShell just converts it into a string and thus $teststring remains a string (try $teststring.GetType() after $teststring = $teststring.ToCharArray() to see this for yourself).
One way to solve this is to do what I did and use a different variable for the character array. You could also solve it by changing the variable to a character array directly by replacing [string]$teststring with [char[]]$teststring, that way any strings input to the function will be automatically cast as a character array.
The next mistake is using -contains where you need -in. The letter doesn't contain the array, you're looking for the letter in the array, just like you did in Python.
You can drop the return keyword entirely, PowerShell does not need it. Any output in your function will be output from the function automatically.
You also call your collection variable "hash", but you made an array. I changed it to be an actual hashtable, just like in your Python code. I also changed the way we add to it to more closely reflect what you did in Python. There are many ways to do this, this is just one. Notice we'll need to add ".Keys" in our if-statement as well so we check for keys matching our letter.
I think that's it, ask if anything is unclear.
| |
doc_23538365
|
A: This is a sketch of an answer.
You can read each row of your tables (you must know which fields are PK and
FKs) and change/replace them accordingly. A php script which migrates DB data to new servers does the same (to replace the base URLS so the DB data can work on the new server). The script reads each DB row, unserialises it if it is serialised, then treated as PHP data and saved back and then dumped.
| |
doc_23538366
|
https://www.youtube.com/watch?v=m9joBLOZVEo
I can't find good line characters that always produce a consistent, skewed line. / and \ don't work for me, neither do "\u2571" and "\u2572".
A: Try different fonts. On Windows, MS Gothic worked best (Python code):
| |
doc_23538367
|
In a video of building a laravel environment, a centos images is created and apache and mysql are installed in it.
On the other hand, using docker-compose.yml, create an apache container and a MySQL container.
What is the difference between these?
A: When you use centOS Image, it acts as a single docker component, which includes both the web server and database.
If, You use docker-compose, Apache and MySQL store as two separate containers.
And It's always recommended to use docker-compose
| |
doc_23538368
|
My understanding from the documentation is like it only works with cast receiver applications provided from a server and written
in HTML5/JavaScript not in Java.But some of the applications on the Android TV seems to support cast receiver when I connect my smartphone(e.g Netflix,Youtube)
Am I missing something on the documentation?
It would great if someone give a pointer on this topic (Google Cast Receiver applications using java code)
A: The receiver application is always written in html,css and js. When apps like Youtube or Netflix support casting, they have a receiver app (which has been suitably registered, published and deployed) which is loaded on to Chromecast when the user clicks on cast-icon.
The Youtube or Netflix App on android platform is acting as a sender application to Chromecast .
There is no Java SDK for receiver application. Even the concept on one does not make sense as the objective is to stream/display media on TV using the Chromecast. You are never casting from one Android/IOS device to another.
A: Yes it is, copied from my own answering the same question:
Yes! on September 2020 Google release the Android Receiver SDK for
Android TV. This is the official site:
https://developers.google.com/cast/docs/android_tv_receiver
This is the Google Codelab
https://codelabs.developers.google.com/codelabs/cast-connect-atv
Basically you will need the sender app and the receiver app. Usually
the sender app is the phone app and the receiver app will be the
Android TV app. It can also be the same apk. For example the same app
could handle phone layout and be the Sender App and the same app could
handle TV layouts and be the receiver app.
In any case you will need to create an Application in:
https://cast.google.com/publish
And Follow the instructions how to add an Android TV dongle via the
Chromecast Built-in Serial Number. Everything is well documented.
Take also in mind that you will need to re-think how the sender and
the receiver app works and synch the ExpandedControllerActivity in
your Sender App with your player (if your app is a streaming app).
NOTE: With this approach you DO NOT NEED any web receiver app BUT any
Android TV without your app installed won't work with this "receiver".
Ideally you will need the Web receiver and this new Android TV
receiver it is just a plus to allow your users has a better UX while
using your Android TV app.
| |
doc_23538369
|
_graph.setToolTipText("<html><div style=\"width: 300px; height: 100px;"
+ " overflow: auto; border: 0;<p style=\"padding:2 5 2 5;\"></div>Please Wait...");
Here _graph is object of component. Problem is, if data is exceeds I need to scroll but it is not happening.please anyone suggest me to make scrollbar.
A: Default tooltips are very basic: simply a lable-like component, even limited to text-only (except html). As I already mentioned, the way to more fancy tooltips is to extend JTooltip and let your graph component return that custom tooltip in createTooltip. An example and some pitfalls were recently discussed over at OTN
A: I do not know how to create a tooltip containing a scrollbar, but I can think of several reasons why you should reconsider whether you want this.
*
*I do not know any application which has a tooltip containing a scrollbar, so no user is going to expect that.
*A tooltip is by definition a small "hover box" with information about the item being hovered over. How do you combine small with the fact you need a scrollbar in it ?
*Have you encountered a tooltip where you could click on some text and which would show more information ? How many times did you had to try with your mouse to navigate to the link, without having the tooltip to disappear ? That is not user-friendly. A scrollbar will have the same problem.
So my advise: rethink your UI design. Judging from the text of your tooltip in the question, I would guess you need some sort of overlay displaying a "Please wait" message.
| |
doc_23538370
|
ex:
function(" ") // returns true
function(" 4 ") // returns false
One solution I've thought of is to use regex, then i'll know that it only contains whitespace if it's false... but i'm not sure if this would be more efficient than the isspace function.
regex: [\w\W] //checks for any word character(a,b,c..) and non-word character([,],..)
thanks in advance!
A: With a regular string, the best you can do will be of the form:
return string::find_first_not_of("\t\n ") == string::npos;
This will be O(n) in the worst case, but without knowing else about the string, this will be the best you can do.
A: Any method would, of necessity, need to look at each character of the string. A loop that calls isspace() on each character is pretty efficient. If isspace() is inlined by the compiler, then this would be darn near optimal.
The loop should, of course, abort as soon as a non-space character is seen.
A: You are making the assumption regex doesnt iterate over the string. Regex is probably much heavier than a linear search since it might build a FSM and traverse based on that.
The only way you could speed it up further and make it a near-constant time operation is to amortize the cost by iterating on every update to the string and caching a bool/bit that tracks if there is a space-like character, returning that value if no changes have been made since, and updating that bit whenever you do a write operation to that string. However, this sacrifices/slows that speed of modifying operations in order to increase the speed of your custom has_space().
A: For what it's worth, a locale has a function (scan_is) to do things like this:
#include <locale>
#include <iostream>
#include <iomanip>
int main() {
std::string inputs[] = {
"all lower",
"including a space"
};
std::locale loc(std::locale::classic());
std::ctype_base::mask m = std::ctype_base::space;
for (int i=0; i<2; i++) {
char const *pos;
char const *b = &*inputs[i].begin();
char const *e = &*inputs[i].end();
std::cout << "Input: " << std::setw(20) << inputs[i] << ":\t";
if ((pos=std::use_facet<std::ctype<char> >(loc).scan_is(m, b, e)) == e)
std::cout << "No space character\n";
else
std::cout << "First space character at position " << pos - b << "\n";
}
return 0;
}
It's probably open to (a lot of) question whether this gives much (if any) real advantage over using isspace in a loop (or using std::find_if).
A: You can also use find_first_not_of if you all the characters to be in a given list.
Then you can avoid loops.
Here is an example
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str1=" ";
string str2=" u ";
bool ContainsNotBlank1=(str1.find_first_not_of("\t\n ")==string::npos);
bool ContainsNotBlank2=(str2.find_first_not_of("\t\n ")==string::npos);
bool ContainsNotBlank3=(str2.find_first_not_of("\t\n u")==string::npos);
cout << ContainsNotBlank1 <<endl;
cout << ContainsNotBlank2 <<endl;
cout << ContainsNotBlank3 <<endl;
return 0;
}
Output:
1: because only blanks and a tab
0: because u is not into the list "\t\n "
1: because str2 contains blanks, tabs and a u.
Hope it helps
Tell me if you have any questions
| |
doc_23538371
|
System.InvalidOperationException: BufferedGraphicsContext cannot be disposed of because a buffer operation is currently in progress.
at System.Drawing.BufferedGraphicsContext.Dispose(Boolean disposing)
at System.Drawing.BufferedGraphicsContext.Dispose()
at System.Drawing.BufferedGraphicsContext.AllocBufferInTempManager(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle)
at System.Drawing.BufferedGraphicsContext.Allocate(IntPtr targetDC, Rectangle targetRectangle)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.MenuStrip.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
A: There is a very long MSDN forums discussion of this error here. In most cases the error is apparently associated with either:
*
*An underlying OutOfMemory problem, which manifests as the BufferedGraphicsContext exception, possibly due to a framework bug.
*A GDI object leak (creating GDI objects and not disposing them).
I recall seeing this error myself a year or so ago, and it was definitely associated with a memory problem that made our app fill up all available VM after a long run, so #1 agrees with what I have observed.
A: a shot in the dark - are you painting from multiple threads? If you are doing painting related work, do it on the GUI thread or synchronize your code carefully.
A: I know this question is old, but i had the same problem and found out, that it only showed up, when i used multiple controls which implemented manual double buffering.
For me, i found the problem at this point:
BufferedGraphicsContext _BackbufferContext = BufferedGraphicsManager.Current;
So all my controls used the Current context, which i assume is always the same.
After i replaced it by
BufferedGraphicsContext _BackbufferContext = new BufferedGraphicsContext();
everything works like wanted.
I hope this is a little bit helpfull.
| |
doc_23538372
|
Here is my code:
View (Chart)
Ext.define('APP.view.core.graphs.Countytotals', {
extend: 'Ext.Panel',
alias: 'widget.countytotalchart',
id: 'countyTotalsGraph',
width: 650,
initComponent: function() {
var me = this;
// Doesn't work?
var countyStore = Ext.create('APP.store.Countytotalsgraph');
// Works
var store = Ext.create('Ext.data.JsonStore', {
fields: ['COUNTY', 'AMOUNT'],
data: [{
'COUNTY': 'London',
'AMOUNT': 10.92
}, {
'COUNTY': 'Lancashire',
'AMOUNT': 6.61
}, {
'COUNTY': 'Kent',
'AMOUNT': 5.26
}, {
'COUNTY': 'West Yorkshire',
'AMOUNT': 4.52
}, {
'COUNTY': 'Nottinghamshire',
'AMOUNT': 4.01
}, {
'COUNTY': 'Other',
'AMOUNT': 68.68
}]
});
var chart = new Ext.chart.PolarChart({
width: '100%',
height: 500,
insetPadding: 50,
innerPadding: 20,
legend: {
docked: 'bottom'
},
listeners: {
afterrender: function (chart) {
if (chart.isVisible()) {
countyStore.load();
chart.redraw();
}
}
},
interactions: ['itemhighlight'],
store: countyStore,
series: [{
type: 'pie',
angleField: 'AMOUNT',
label: {
field: 'COUNTY',
display: 'outside',
calloutLine: {
length: 60,
width: 3
// specifying 'color' is also possible here
}
},
highlight: true,
tooltip: {
trackMouse: true,
renderer: function(storeItem, item) {
this.setHtml(storeItem.get('COUNTY') + ': ' + storeItem.get('AMOUNT') + '%');
}
}
}]
});
me.items = [chart];
this.callParent();
}
});
Store
Ext.define('APP.store.Countytotalsgraph', {
extend: 'Ext.data.Store',
model: 'APP.model.Countytotalsgraph',
autoLoad: false,
storeId: 'countyTotalsGraphStore',
proxy: {
type: 'ajax',
url : '/dashboard/countytotals',
method : 'POST',
reader: {
type: 'json',
rootProperty: 'data'
}
},
listeners: {
beforeload: function(store, eOpts) {
//if ( this.data.items.length ) {
//Ext.getCmp('optionsGrid').getView().refresh();
//}
store.proxy.extraParams = {
percentage: 'true'
}
}
}
});
Model
Ext.define('APP.model.Countytotalsgraph', {
extend: 'Ext.data.Model',
fields: ['COUNTY', 'AMOUNT']
});
This is how is renders with the static store:
This is how it renders with the remote store:
I am on the latest version of the GPL although the charts were built using Sencha CMD and the "sencha ant build" command in the sencha-charts directory.
Why does the static store display it (well still there is still an issue regarding the legend at the bottom) but the remote json not?
Iv'e tried to load the store after it the chart is rendered and is visible as I have seen a previous post regarding holding off on loading the store to give the chart time to render but this did not work:
listeners: {
afterrender: function (chart) {
if (chart.isVisible()) {
countyStore.load();
chart.redraw();
}
}
},
Thanks in advance :)
Nathan
A: Probably a bug in Ext.
The chart colors are set in Ext.chart.AbstractChart#updateColors. This is a "config" method, that is called automatically when setColors is called, and also from the constructor, when the config is initialized.
In your case, it is only called at construction time, before the remote store has been loaded; and it happens that polar series need to know the number of records in the store in order to know how many colors it must used (unlike other kind of charts that rely on number of axis or so).
Here's the code of that method:
updateColors: function (newColors) {
var me = this,
colors = newColors || (me.themeAttrs && me.themeAttrs.colors),
colorIndex = 0, colorCount = colors.length, i,
series = me.getSeries(),
seriesCount = series && series.length,
seriesItem, seriesColors, seriesColorCount;
if (colorCount) {
for (i = 0; i < seriesCount; i++) {
seriesItem = series[i];
// Ext.chart.series.Polar#themeColorCount uses store.getCount()
// so seriesColorCount will be 0
seriesColorCount = seriesItem.themeColorCount();
// ... hence seriesColor will be an empty array
seriesColors = me.circularCopyArray(colors, colorIndex, seriesColorCount);
colorIndex += seriesColorCount;
seriesItem.updateChartColors(seriesColors);
}
}
me.refreshLegendStore();
}
You could probably get it working by creating the chart after the load event of the store, but that's kind of kinky given your usage is as intended, and the bug will probably get smashed in a coming release.
For now, a possible fix is to override the onRefresh of the chart, that is called, well, when the store is refreshed, and force colors to be updated at this time:
Ext.define(null, {
override: 'Ext.chart.PolarChart'
,onRefresh: function() {
this.callParent(arguments);
var colors = this.getColors();
if (colors) {
this.updateColors(colors);
}
}
});
| |
doc_23538373
|
Particularly maintaining the classes that are applied to the body tag?
I have applied SmoothState to my Wordpress site but the major problem I have is with the classes on the body tag not updating. I rely on the classes Wordpress adds to the body tag to style different parts of the site. Smoothstate loads/changes page content but I cant get the body tag to update.
Has anyone encountered this same problem before? Could really do with some help.
Thanks in advance :-)
A: The page doesn't really refresh, only everything inside the Smoothstate container is reloaded.
You'll have to move the body class inside the Smoothstate container. You can do this by adding an extra div.
<body <?php body_class(); ?>>
<div id="smoothContainer">
To
<body>
<div id="smoothContainer">
<div <?php body_class(); ?>>
Don't forget to close it in footer.php!
| |
doc_23538374
|
I tried calling metrics like this :
shap.benchmark.metrics.local_accuracy(X, y, model)
But am always getting the error :
AttributeError: module 'shap' has no attribute 'benchmark'
A: Try instead:
from shap.benchmark import metrics
metrics.local_accuracy(X, y, model)
Why? Inspecting package's top level __init__.py you'll find out the following commented line:
#from . import benchmark
| |
doc_23538375
|
A: as you have a large amount of files its a good practice to work on threads, either you use the performSelectorInBackground or dispatch_async.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
// code to post on server
});
here is the good post about dispatch_async http://blog.slaunchaman.com/2011/02/28/cocoa-touch-tutorial-using-grand-central-dispatch-for-asynchronous-table-view-cells/
| |
doc_23538376
|
I have a v-for list of toppings, customers can choose up to 4 toppings from a list and he can select 2, 3 or 4 times the same topping.
I created a counter for each item in the list, which stores the selected topping name in an array with a limit of 4. This worked.
How can I select and increase the amount of topping selected in the interface?
Below I have my code, and some visual references
https://codepen.io/mordzin/pen/VwePBzq
var App = new Vue({
el: '#app',
data: {
flavorCounter: 0,
cardapio: [],
order: [],
selectedItem: null
},
mounted() {
// const axios = require('axios');
axios.get('https://v2-api.sheety.co/4a5e4bb41d15a6ea344152fafca024db/zunepizza/cardapio')
.then((response) => {
this.cardapio = response.data.cardapio
})
.catch((error) => {
})
.finally(() => {
})
},
methods:{
addFlavor(){
if (this.flavorCounter <= 3) {
flavor = event.target.getAttribute('flavor')
this.order.push(flavor);
this.flavorCounter ++
console.log(this.order)
console.log(this.flavorCounter)
} else {
console.log('Maximo de sabores')
}
},
removeFlavor(){
if (this.flavorCounter >= 1) {
flavor = event.target.getAttribute('flavor')
this.order.splice(index, 1);
this.flavorCounter --
console.log(this.order)
console.log(this.flavorCounter)
} else {
}
},
}
});
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,minimum-scale=1">
<title>Zune Pizza</title>
<link rel="stylesheet" href="zunepizza.css">
<link async href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link async href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.12/handlebars.min.js"></script> -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
<div id="app">
<template>
<div id="cardapio">
<ul v-for="cardapio in cardapio">
<li>
<div class="item-info">
<h3 class="item-title">{{cardapio.name}}</h3>
<div class="tag">
<h5>{{cardapio.type}}</h5>
</div>
<p class="item-title">{{cardapio.desc}}</p>
</div>
<div class="item-img">
<div class="flavorCounter" :id="cardapio.name">
<button
@click="addFlavor()"
:flavor="cardapio.name"
class="addFlavor controller-btn"> + </button>
<input :id='cardapio.name' type="number" value="0" class="flavorQuantity">
<button
@click='removecliFlavor()'
:flavor='cardapio.name'
class="addFlavor controller-btn"> - </button>
</div>
<img src="img/cardapio/baska.jpg" alt="">
</div>
</li>
</ul>
</div>
</template>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="zunepizza.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
zune pizza interface topping counter
i need something like the image below
ifood interface topping counter
A: You can achieve it by adding an amount property (for example) to your items:
this.cardapio = response.data.cardapio.map(data => ({ ...data, amount: 0 }))
Then you can bind the amount to the elements in your markup and modify it:
<!--It is always good to assign an :key-->
<ul v-for="(item, i) in cardapio" :key="i">
...
<button @click="item.amount < 4 ? item.amount++ : ''" ... > + </button>
<input v-model="item.amount"...>
<button @click="item.amount > 0 ? item.amount-- : ''" ... > + </button>
...
</ul>
To find selected items, you can just filter items with amount >0:
this.order = this.cardapio.filter(({ amount }) => amount > 0);
Hope that helps you
A: you can do smth like this: https://codepen.io/jasik/pen/NWxdLRg
<div id="cardapio">
<ul v-for="cardapio in cardapios">
<li>
<div class="item-info">
<h3 class="item-title">{{cardapio.name}}</h3>
<div class="tag">
<h5>{{cardapio.type}}</h5>
</div>
<p class="item-title">{{cardapio.desc}}</p>
</div>
<div class="item-img">
<div class="flavorCounter" :id="cardapio.name">
<button @click="cardapio.counter++" :disabled="cardapio.counter === 4" :flavor="cardapio.name" class="addFlavor controller-btn"> + </button>
<input :id='cardapio.name' type="number" v-model="cardapio.counter" class="flavorQuantity">
<button @click='cardapio.counter--' :disabled="cardapio.counter === 0" :flavor='cardapio.name' class="addFlavor controller-btn"> - </button>
</div>
<img src="img/cardapio/baska.jpg" alt="">
</div>
</li>
</ul>
</div>
data: {
cardapios: []
},
created() {
axios
.get(
"https://v2-api.sheety.co/4a5e4bb41d15a6ea344152fafca024db/zunepizza/cardapio"
)
.then((response) => {
let edited = response.data.cardapio;
edited.forEach((e) => {
e.counter = 0;
});
this.cardapios = edited;
})
.catch((error) => {})
.finally(() => {});
},
methods: {}
Hope you will find it helpful.
| |
doc_23538377
|
I am new in react native and i dont know redux.
someone can show me please how to do it with my example in a simple way?
this is the "OrderInformationScreen"
export default class OrderInformationScreen extends Component {
constructor(props) {
super(props);
const { state } = props.navigation;
this.state = {
title: state.params.data //navprops.params.data.SHORT_TEXT
}
//alert(JSON.stringify((state.params.data.SHORT_TEXT)))
}
render() {
return (
<>
<View
style={{
alignItems: 'flex-start',
justifyContent: 'center',
borderColor: 'blue',
flexDirection: "row",
justifyContent: 'space-evenly'
}}>
<TouchableOpacity onPress={() => console.log("cancel!")}>
<Avatar
size='large'
containerStyle={{ marginTop: 30 }}
activeOpacity={0.2}
rounded
source={require('../assets/down.png')} style={{ height: 80, width: 80 }}
onPress={() => console.log("cancel!")} />
<View >
<Text style={{ fontSize: 25, fontWeight: 'bold', color: 'red' }}>לדחות</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => console.log("works!")}>
<Avatar
size='large'
activeOpacity={0.1}
rounded
source={require('../assets/up.png')} style={{ height: 80, width: 80 }}
onPress={() => console.log("Works!")} />
<View>
<Text style={{ fontSize: 25, fontWeight: 'bold', color: 'green', marginHorizontal: 6 }}>לאשר</Text>
</View>
</TouchableOpacity>
</View>
<InfoTable headerInfo={this.state.title}></InfoTable>
</>
);
};
}
this is the StackNavigator :
const PlacesNavigator = createStackNavigator({
Main: MainScreen,
MyTasks: MyTasksScreen,
Settings: SettingsScreen,
Sync: SyncScreen,
Info: OrderInformationScreen
},
{
defaultNavigationOptions: {
headerStyle: {
animationEnabled: true,
backgroundColor: Platform.OS === 'android' ? Colors.primary : ''
},
headerTintColor: Platform.OS === 'android' ? 'white' : Colors.primary,
}
}
);
export default createAppContainer(PlacesNavigator);
this is the "SettingsScreen"
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import { CheckBox } from 'react-native-elements';
const SettingsScreen = props => {
const [checked1, setChecked1] = useState(null);
const [checked2, setChecked2] = useState(null);
const [checked3, setChecked3] = useState(null);
const [checked5, setChecked5] = useState(null);
const [checked6, setChecked6] = useState(null);
const [checked7, setChecked7] = useState(true);
const [checked8, setChecked8] = useState(null);
const handlePress = title => {
if (title === 'LION') { //6
setChecked6(true), setChecked7(false), setChecked8(false)
} else if (title === 'ZEBRA') {//7
setChecked7(true), setChecked6(false), setChecked8(false)
} else {
setChecked8(true), setChecked7(false), setChecked6(false)
}
}
useEffect(() => {
setChecked7(true)
}, [])
return (
<View>
<CheckBox
iconLeft
checkedColor='red'
title="LIZARD"
checked={checked1}
onPress={() => setChecked1(prev => !prev)}
/>
<CheckBox
iconLeft
checkedColor='red'
title="BIRD"
checked={checked2}
onPress={() => setChecked2(prev => !prev)}
/>
<CheckBox
iconLeft
checkedColor='red'
title="SNAKE"
checked={checked3}
onPress={() => setChecked3(prev => !prev)}
/>
<CheckBox
iconLeft
checkedColor='red'
title="SOUND"
checked={checked5}
onPress={() => setChecked5(prev => !prev)}
/>
<CheckBox
iconLeft
checkedColor='green'
title='LION'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={checked6}
onPress={() => handlePress('LION')}
/>
<CheckBox
iconLeft
checkedColor='green'
title='ZEBRA'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={checked7}
onPress={() => handlePress('ZEBRA')}
/>
<CheckBox
iconLeft
checkedColor='green'
title='BOB'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={checked8}
onPress={() => handlePress('BOB')}
/>
</View>
);
};
SettingsScreen.navigationOptions = {
headerTitle: 'SETTINGS'
};
export default SettingsScreen;
this is the "InfoTable" :
import React, { Component } from 'react';
import { StyleSheet, View, ScrollView } from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';
import Swiper from 'react-native-swiper'
export default class InfoTable extends Component {
constructor(props) {
super(props);
this.state = {
tableHead0: [`${this.props.headerInfo.SHORT_TEXT} (${(this.props.headerInfo.ORDERID).replace(/^0+/, '')})`],
tableHead3: ['BANANA'],//THIS I WANT HIDE AND SHOW
tableData3: [
['APPLE', `${this.props.headerInfo.COSTCENTER_TXT} (${(this.props.headerInfo.COSTCENTER)})`],
['MONKEY', `${this.props.headerInfo.LOC_WBS_ELEM_TXT} (${this.props.headerInfo.LOC_WBS_ELEM})`],
['FRIZ', `${this.props.headerInfo.SETTLORDER_TXT} (${this.props.headerInfo.SETTLORDER})`],
]
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.headerInfo != null) {
this.setState({ tableHead0: [nextProps.headerInfo] })
}
alert(JSON.stringify(nextProps))
}
render() {
const state = this.state;
return (
<Swiper style={styles.wrapper} showsButtons={true}>
<ScrollView>
<View style={styles.container}>
<Table borderStyle={{ borderWidth: 2, borderColor: '#d83dff' }}>
<Row data={state.tableHead0} style={styles.head0} textStyle={styles.headText} />
<Row data={state.tableHead3} style={styles.head} textStyle={styles.headText} />
<Rows data={state.tableData3} textStyle={styles.text} />
</Table>
</View>
</ScrollView>
</Swiper>
)
}
}
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#fff' },
head0: { height: 80, backgroundColor: '#54beff' },
head: { height: 40, backgroundColor: '#9febf5' },
headText: { fontWeight: 'bold', fontSize: 20 },
text: { margin: 10 },
});
A: Use AsyncStorage in your settings screen save the value of the checked radio and retrieve the value in InfoTable.
save value in storage.
import {
AsyncStorage,
...
} from 'react-native';
//save value in storage
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
// Error saving data
}
};
// retrieve value
retrieveData = async key => {
try {
const value = await AsyncStorage.getItem(key);
if (value !== null) {
// We have data!!
return value;
}
} catch (error) {
// Error retrieving data
}
};
Modify handlePress in SettingsScreen
const handlePress = title => {
if (title === 'LION') {
//6
setChecked6(true), setChecked7(false), setChecked8(false);
// remove key from storage
AsyncStorage.removeItem('checkbox').catch(e => console.log(e));
} else if (title === 'ZEBRA') {
//7
setChecked7(true), setChecked6(false), setChecked8(false);
// remove key from storage
AsyncStorage.removeItem('checkbox').catch(e => console.log(e));
} else {
setChecked8(true), setChecked7(false), setChecked6(false);
// add key to storage
storeData('checkbox', 'tableHead3').catch(e => console.log(e));
}
};
in InfoTable get the value from storage
state = {
checkBoxKey: '', // used to store value from storage
// I've added new object to store all the table data
tableData: {
tableHead0: [`${'SHORT_TEXT'} (${'ORDERID'})`],
tableHead3: ['BANANA'], //THIS I WANT HIDE AND SHOW
tableData3: [
['APPLE', `${'COSTCENTER_TXT'} (${'COSTCENTER'})`],
['MONKEY', `${'LOC_WBS_ELEM_TXT'} (${'LOC_WBS_ELEM'})`],
['FRIZ', `${'SETTLORDER_TXT'} (${'SETTLORDER'})`],
],
},
}
componentDidMount = async () => {
try {
const data = await this.retrieveData('checkbox');
if (data) {
this.setState(
{
checkBoxKey: data,
},
() => console.log(this.state.checkBoxKey)
);
}
} catch (e) {
console.log(e);
}
};
In your render, get checkBoxKey from state and use it to filter table data.
render = () => {
const state = this.state;
const tableData = state.tableData;
const displayKeys = Object.keys(tableData).filter(key => {
return key !== this.state.checkBoxKey;
});
return (
<Swiper style={styles.wrapper} showsButtons={true}>
<ScrollView>
<View style={styles.container}>
<Table borderStyle={{ borderWidth: 2, borderColor: '#d83dff' }}>
{displayKeys &&
displayKeys.map(key =>
this.is2dArray(tableData[key]) ? (
<Rows data={tableData[key]} textStyle={styles.text} />
) : (
<Row data={tableData[key]} textStyle={styles.text} />
)
)}
</Table>
</View>
</ScrollView>
</Swiper>
);
};
DEMO
A: I would suggest learning either MobX or Redux.
This is the most simple approach, and sooner or later you will want to control your state globally
| |
doc_23538378
|
This is a typical function of mine, Should I Bind a $temp in all the return cases and then return it at the end instead or is this fine?
define DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
function Resolvestuff($input) {
global $db;
if ($stmt = $db->prepare("Select Column from Table where `a` = ?")) {
$stmt->bind_param('s', $input);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($col1);
$row = $stmt->fetch();
if ($stmt->num_rows == 0) {
return "Nothing";
} else {
return $col1;
}
$stmt->free_result(); // i mean, is this even performed at some point ?
$stmt->close();
} else {
return "Nothing";
}
//Return here instead ?
}
A: A simple answer to your questions is that $stmt is a local variable so PHP will clean it all up and garbage collect soon after the execution of the function is over. You don't need to call free_result or close.
The longer answer is that you approaching this from the wrong angle. You should not create specific functions like this. You must have one generic function. For example.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
$mysqli->set_charset('utf8mb4'); // always set the charset
function fetchSingle(mysqli $db, string $sql, array $params = []) {
$stmt = $db->prepare($sql);
if ($params) {
$stmt->bind_param(str_repeat("s", count($params)), ...$params);
}
$stmt->execute();
$stmt->bind_result($col1);
$stmt->fetch();
return $col1;
}
$val = fetchSingle($mysqli, "Select Column from Table where `a` = ?", [$input]);
| |
doc_23538379
|
I just don't understand how I can't seem to get my adding of a task to work. If anybody can help me out with my code, I would be really grateful.
I made a GIF, where I demonstrate my problem when in this example I update a task
(https://www.dropbox.com/s/qndkfmxde6fos9r/hiI1hBNvSn.gif?dl=0)
Part of my app.js code:
zazzleApp.factory('TaskService', function ($http) {
var TaskService = {};
TaskService.taskList = [];
TaskService.addTask = function(pTask){
var newClickDate = clickDate;
console.log('LOGGGING NEW CLICK DATE = ', clickDate);
var newEditId = editId;
console.log('LOGGGING NEW edit id = ', newEditId);
var url;
console.log('edit id = ' , newEditId);
if (newEditId) {
url = 'api/task/update/' + newEditId;
} else {
url = 'api/task/create';
}
console.log("URL URL USA", url, newEditId);
defaultStart = new Date(newClickDate);
defaultStart = defaultStart.getFullYear() + "-" + (defaultStart.getMonth() + 1) + "-" + defaultStart.getDate();
defaultStart += " 00:00:00";
defaultEnd = new Date(newClickDate).addDays(1);
defaultEnd = defaultEnd.getFullYear() + "-" + (defaultEnd.getMonth() + 1) + "-" + defaultEnd.getDate();
defaultEnd += " 00:00:00";
console.log('LOGGING DEFAULT START AND DEFAULT END ' , defaultStart, defaultEnd);
pTask.color = $('#containerColorPicker').attr('ng-data-id');
return $http.post(url, {
'name': pTask.project_name,
'project_id': pTask.project_type,
'location_id': pTask.location,
'estimate_time': pTask.estimate_time || 2,
'project_client_name': pTask.project_client_name,
'url': pTask.url,
'resource_link': pTask.resource_link,
'notes': pTask.notes,
'start_time': pTask.start_time || defaultStart,
'end_time': pTask.end_time || defaultEnd,
/*'start_time': defaultStart,
'end_time': defaultEnd,*/
'color': pTask.color
}, {
headers: {
"Content-Type": "text/plain"
}
})
.success(function(data, status, headers, config) {
console.log(data);
TaskService.taskList.push(data);//pushing the new task
console.log("YYYYYYYYYYYYY -------->>>>>", defaultStart, newClickDate, newEditId);
})
.error(function(data, status, headers, config) {
console.log("Failed to add the task to DB");
});
};
return TaskService;
})
//START CONTROLLER
angular.module('zazzleToolPlannerApp')
.controller('CalendarCtrl', function ($scope, $mdDialog, $http, $rootScope, $timeout, User, Auth, UserService, TaskService) {
$scope.isAdmin = Auth.isAdmin;
$scope.getCurrentUser = Auth.getCurrentUser;
$scope.activeUser = $scope.getCurrentUser()._id;
//console.log('???????????? logging active/current user id', $scope.activeUser);
$scope.newTask = {};
$scope.newTask.project_name = "";
$scope.newTask.project_type = "";
$scope.newTask.location = "";
$scope.newTask.estimate_time = "";
$scope.newTask.project_client_name = "";
$scope.newTask.url = "";
$scope.newTask.resource_link = "";
$scope.newTask.notes = "";
$scope.newTask.color = "";
//console.log('00000000000 ', $scope.newTask); //empty
$scope.tasks = TaskService.taskList;
$scope.addTaskWithService = function () {
//note that you can process the promise right here (because of the return $http in the service)
TaskService.addTask($scope.newTask)
.success(function(data){
//here you can process the data or format it or do whatever you want with it
console.log("Controller: the task has been added");
$scope.tasks = [];// EMPTY THE ARRAY
TaskService.getTasks();
$scope.updateGridDataAwesome();
$scope.updateGridData();
//console.log('Taskservice Controller ', $scope.updateGridDataAwesome);
})
.error(function(data){
//something went wrong
console.log("Controller: error in adding task");
});
}
});
//END CONTROLLER
A: In the succes() callback of TaskService.addTask you're assigning an empty array instance to $scope.tasks, thus breaking the reference to TaskService.taskList. So calling TaskService.getTasks() won't have any effect on the scope variable anymore.
| |
doc_23538380
|
Here is what My link looks like
<%= link_to document.name,"#{document.file}"%>
A: @Stefan answered this in the comments.
in Gemfile:
gem 'mime-types'
in the uploader file generated by carrierwave:
require 'carrierwave/processing/mime_types'
class MyUploader < CarrierWave::Uploader::Base
include CarrierWave::MimeTypes
process :set_content_type
end
| |
doc_23538381
|
Very similar to the early RGB triangle tutorials that DirectX, OpenGL, etc. provide:
Mine works well enough with acute triangles:
But not so much with obtuse triangles:
I created the following SVG, with VueJS for data binding:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="800" height="600">
<defs>
<radialGradient id="red" gradientUnits="userSpaceOnUse" :cx="points[0].x" :cy="points[0].y"
:r="radius(points[0], points[1], points[2])">
<stop offset="0%" stop-color="#ff0000ff" />
<stop offset="100%" stop-color="#7fff0000" />
</radialGradient>
<radialGradient id="green" gradientUnits="userSpaceOnUse" :cx="points[1].x" :cy="points[1].y"
:r="radius(points[1], points[0], points[2])">
<stop offset="0%" stop-color="#00ff00ff" />
<stop offset="100%" stop-color="#ff7f0000" />
</radialGradient>
<radialGradient id="yellow" gradientUnits="userSpaceOnUse" :cx="points[2].x" :cy="points[2].y"
:r="radius(points[2], points[0], points[1])">
<stop offset="0%" stop-color="#ffff00ff" />
<stop offset="100%" stop-color="#7f7f0000" />
</radialGradient>
</defs>
<path :d="svgTriangle" fill="url(#red)" />
<path :d="svgTriangle" fill="url(#yellow)" />
<path :d="svgTriangle" fill="url(#green)" />
</svg>
Points are generated randomly within the SVG's 800x600 space:
for (let p = 0; p < 3; p++) {
this.points[p] = {
id: `p${p}`,
x: Math.floor(Math.random() * 800),
y: Math.floor(Math.random() * 600)
};
}
And the radius calculation is based on the length of the line to the midpoint of the other 2 vertices:
radius: function (me, other1, other2) {
const mid = {
x: (other1.x + other2.x) / 2,
y: (other1.y + other2.y) / 2
};
return Math.sqrt(Math.abs(me.x - mid.x) ** 2 + Math.abs(me.y - mid.y) ** 2);
}
I believe the problem is that the yellow and green (which are rendered after the red) have a much longer radius and are basically hiding the red. Linear gradients aren't any better. Since the gradient approach may be flawed, is there a better approach using SVG?
I know this is possible using Canvas/WebGL (example), but can this same thing even be done using SVG, perhaps with blend filters? Or if I want this type of interpolation, will I need to use Canvas/WebGL
Edit: I couldn't quite get the color blending as nice as I wanted in all the edge cases using SVG, so in the end I ended up moving to canvas and WebGL.
A: EDIT: There seems to be an actually correct solution besides the approximation I explain in this answer – look here.
There are two problems:
*
*The green gradient has too long radius, as you mentioned.
*The green gradient is rendered above the other two (and the yellow one above the red one), thus, the colors would be unbalanced even in an equilateral triangle.
I will try to help with the former. Good news, you can definitely use gradients! The gradientTransform attribute allows the gradient to be elliptical instead of circular, which gives you much more options. You can use
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="800" height="600">
<defs>
<radialGradient id="red" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"
:gradientTransform="transformation(points[0], points[1], points[2])">
<stop offset="0%" stop-color="#ff0000ff" />
<stop offset="100%" stop-color="#7fff0000" />
</radialGradient>
<radialGradient id="green" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"
:gradientTransform="transformation(points[1], points[2], points[0])">
<stop offset="0%" stop-color="#00ff00ff" />
<stop offset="100%" stop-color="#ff7f0000" />
</radialGradient>
<radialGradient id="yellow" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"
:gradientTransform="transformation(points[2], points[0], points[1])">
<stop offset="0%" stop-color="#ffff00ff" />
<stop offset="100%" stop-color="#7f7f0000" />
</radialGradient>
</defs>
<path :d="svgTriangle" fill="url(#red)" />
<path :d="svgTriangle" fill="url(#yellow)" />
<path :d="svgTriangle" fill="url(#green)" />
</svg>
with this function instead of radius:
transformation: function (me, other1, other2) {
const side1vector = {
x: other1.x - me.x,
y: other1.y - me.y
};
const side2vector = {
x: other2.x - me.x,
y: other2.y - me.y
};
const matrix = [
side1vector.x * Math.sqrt(3)/2,
side1vector.y * Math.sqrt(3)/2,
side2vector.x - 0.5*side1vector.x,
side2vector.y - 0.5*side1vector.y,
me.x,
me.y
];
return "matrix(" + matrix.join(" ") + ")";
}
This should do what you want.
Explanation: Each radial gradient is originally centered in point [0;0] and has radius 1. Then a affine transformation is applied that sends the center [0;0] to the respective vertex and sends points [2*√3/3;0] and [√3/3;1] to the other vertices (you can check it yourself). Since these points are outside the original gradient (further away from [0;0] than 1), the other vertices will also be outside the transformed gradient, so the gradient will never hide them.
Furthermore, this code produces the same result as your code in case of an equilateral triangle. And if you fill any other triangle using this code, it will be the same as if you filled an equilateral triangle, and then squished it with some affine transformation to the shape of the other one (this is because a combination of affine transformations is still a affine transformation and a affine transformation of one specific object is uniquely defined by positions of three transformed points, in this case the vertices). The important consequence is that each color covers the same "percentage" of the overall area in every triangle, so no need to fear that red can be missing altogether.
| |
doc_23538382
|
Exception in thread "main" java.lang.ClassCastException: javax.xml.ws.soap.AddressingFeature cannot be cast to [Ljavax.xml.ws.WebServiceFeature;
I know for a fact that javax.xml.ws.soap.AddressingFeature extends javax.xml.ws.WebServiceFeature, so I'm not sure what's happening. I know you cannot downcast in Clojure, but casting to a parent should work.
From my understanding, objects should be autocast, and if they are not, clojure.core/cast should work, however, both throw an exception.
My code looks something like this:
(-> (com.test.TestAPISOAP.)
(.getTestWSHttpBinding
(javax.xml.ws.soap.AddressingFeature. true true)))
A: It looks like .getTestWSHttpBinding accepts an array (the [L in [Ljavax.xml.ws.WebServiceFeature), not a single element.
Try creating an array with AddressingFeature as a single element using clojure.core/to-array:
(-> (com.test.TestAPISOAP.)
(.getTestWSHttpBinding
(to-array [(javax.xml.ws.soap.AddressingFeature. true true)])))
| |
doc_23538383
|
what we want to achieve is when they enter the phone number , we need to send an SMS automatically using our SMS gateway API link .
So when they enter their phone numbers and click on submit we want to the below onclick option to be done .
http://api.clickatell.com/http/sendmsg?api_id=XXXXx&to=+13456787654&user=XXXXXX&password=XXXXX&text= Gana dinero para su clase utilizando UBER para hacer un pago . XXXXXXX
I am not tech , so any other way please recommend .
Thanks
A: Simplest solution would be to use Zapier for the integration between Google docs and Clickatell
https://zapier.com/zapbook/clickatell/
| |
doc_23538384
|
What should I do in order that all my changes from my config file to be updated in my database as well?
Here is InitializeDbTestData(app) method
A: For others who are interested in this topic you should take a look here
Apparently there is no way to do this just to use other tools such as AdminUI(which you have to pay for it)
| |
doc_23538385
|
Each element is a signed int type, but only non-negative numbers are used, and -1 is used to represent an invalid value.
The instructions generated for the 2nd version is using SSE which uses SIMD shuffle and compare correctly. I expected this to run faster on Broadwell and Skylake, but when microbenchmarking it, SIMD version runs slower around 3.5ns on Skylake and 2.7ns on Broadwell.
Could you help me explaining why?
int example(int* values) {
int min_value = 0x7FFFFFFF;
for (int n = 0; n < 4; ++n) {
if (values[n] != -1 &&
values[n] < min_value) {
min_value = values[n];
}
}
return min_value;
}
https://gcc.godbolt.org/z/iWC26S
int example(int* values) {
uint min_0 = (uint)values[0] < (uint)values[1] ? (uint)values[0] : (uint)values[1];
uint min_1 = (uint)values[2] < (uint)values[3] ? (uint)values[2] : (uint)values[3];
return min_0 < min_1 ? min_0 : min_1;
}
https://gcc.godbolt.org/z/b7JhNZ
My whole program https://gcc.godbolt.org/z/bUXBqd
| |
doc_23538386
|
The request is made from the angular code. The angular is able to open the homepage when localhost is run without a trailing url, but when the url is given, the request doesn't reach angular controller, and the browser responds with the error Resource interpreted as Document but transferred with MIME type application/json. I've already checked out the existing solutions on S.O. but none worked. Please help.
binder.js(angular)
'use strict';
var app = angular.module('clip',['ngRoute','ngResource'])
app.config(function($routeProvider,$locationProvider){
$routeProvider.
when('/',{
templateUrl:"main.html",
}).
when('/:url',{
templateUrl:'url.html',
controller: "url"
})
$locationProvider.html5Mode({enabled:true})
});
app.controller("url",function($scope,$http,$routeParams){
$scope.load = function(){
var urls = $routeParams.url;
console.log("inside angular code");
$http.get('/:url').success(function(result){
if(result.exists) {
$scope.content = result.content;
$scope.exists=false;
}
else {
$scope.exists = true;
$scope.content="";
}
})
}
})
index.js
var express = require('express');
var db = require('./models.js');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(__dirname+"/public"))
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.set('port',(process.env.PORT||5000));
app.get('/',function(req,res){
res.sendFile('index.html')
})
app.route('/:url')
.get(function(req,res){
res.setHeader('Content-Type','application/json');
db.find({url:req.params.url},function(err,data){
if(data.length == 0){
res.json({
exists:false
})
}
else {
// TO-DO: delete from database
res.json({
exists:true,
data:data[0].content
})
}
})
})
app.listen(app.get('port'),function(){
console.log("Magic happens at port "+app.get('port'));
});
index.html(homepage)
<!DOCTYPE html>
<html ng-app='clip'>
<head>
<base href="/" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MyCLips</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-resource.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<script src="js/binder.js"></script>
</head>
<body>
<div ng-view>
</div>
</body>
</html>
url.html
<div class="container-fluid" data-ng-init="load()">
<form>
<div class="form-group">
<textarea class="form-control" required="required" rows="10" cols="10" placeholder="paste your data here" ng-model="content"></textarea>
<button type="submit" class="btn btn-success" ng-click="submit()" ng-show="exists">Create</button>
</div>
</form>
</div>
A: I found a solution to the problem. I was making request to the same url from both angular and node. So the response was getting delivered from the node directly, without passing the content to angular, and since, the content expected to be rendered was a document, and the response was in json, I was getting this error. I changed the url for searching database('/find/:url'), and simply made above url('/:url') render index.html, so that angular could request the new url for data while node renders the html page, and it worked.
A: ok.. so your route provider does'nt working.. in your url controller you use a $http dependency, so.. the Resource interpreted as Document but transferred with MIME type application/json means that the object are you receiving is not a json..
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-resource.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<script src="js/binder.js"></script>
i think you are not include the index.js..
| |
doc_23538387
|
When I click the button, I want to add a random data from the listview items and add it in the textview.
public class MainActivity extends AppCompatActivity {
ListView listgor;
EditText textgir;
Button katgir;
Button kuraceker;
TextView katilimcisecer;
ArrayList<String> data = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data.add("Hello World");
listgor = (ListView) findViewById(R.id.listeler);
textgir = (EditText) findViewById(R.id.sira1);
katgir = (Button) findViewById(R.id.katilimciekle);
kuraceker = (Button) findViewById(R.id.kuracek);
katilimcisecer = (TextView) findViewById(R.id.katilimci) ;
listgor.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data));
katgir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View currentView) {
data.add(textgir.getText().toString());
textgir.setText("");
}
});
}
}
A: To add data from listview items to TextView use code below.
int randomIndex = ThreadLocalRandom.current().nextInt(0, data.size())
yourTextView.setText(data.get(randomIndex))
| |
doc_23538388
|
The form looks like this:
Screenshot of how the form is supposed to look like
This is my code for now. The labels name is laAddress
#include "ui_izdavanje_recepta.h"
#include <QDate>
Izdavanje_recepta::Izdavanje_recepta(QWidget *parent) :
QDialog(parent),
ui(new Ui::Izdavanje_recepta)
{
ui->setupUi(this);
modelCBime = new QSqlQueryModel;
modelCBime->setQuery("SELECT idPacijent, ime FROM Pacijent");
ui->imePacCB->setModel(modelCBime);
ui->imePacCB->setModelColumn(1);
modelCBkod = new QSqlQueryModel;
modelCBkod->setQuery("SELECT idDoktor,ime FROM Doktor");
ui->SifraDoktoraCB->setModel(modelCBkod);
ui->SifraDoktoraCB->setModelColumn(0);
QDate cd = QDate::currentDate();
ui->laDatum->setText(cd.toString("d. M. yyyy"));
}
Izdavanje_recepta::~Izdavanje_recepta()
{
delete ui;
}
void Izdavanje_recepta::on_imePacCB_activated(const QString &arg1)
{
}
void Izdavanje_recepta::on_imePacCB_activated(int index)
{
QSqlRecord record=modelCBime->record();
spID = modelCBime->record(index).value("idPacijent").toInt(); //this grabs the id which will later on be put into the database
}`
| |
doc_23538389
|
My TabbedPage-Xaml looks like this
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
xmlns:views="clr-namespace:Futura.SA.CustomerModule.Views;assembly=Futura.SA.CustomerModule"
x:Class="Futura.SA.CustomerModule.Views.CustomerDetailPage">
<TabbedPage.Children>
<NavigationPage Title="Main">
<x:Arguments>
<views:CustomerDetailMainDataPage x:Name="TbpgMainData" Icon="barcode_white_24.png"/>
</x:Arguments>
</NavigationPage>
<NavigationPage Title="Address">
<x:Arguments>
<views:CustomerDetailAddressSelectionPage x:Name="TbpgAddressSelectionPage"/>
</x:Arguments>
</NavigationPage>
</TabbedPage.Children>
</TabbedPage>
When I select the Page "Adresses" and call _navigationService.NavigateAsync("NextPage") I assume that the Page of the Tab is replaced with the "NextPage". But instead it is navigating away from my TabbedPage and the NextPage is displayed as a regular page. When I go back I can see my TabbedPage again. Can I some how achieve my desired behavior?
I am using Prism 6.3 with Xamarin.Forms 2.4.
Thanks alot
A: Best take a look at what _navigationservice instance you are targeting, most likely it's the wrong one...
For PRISM to know what navigation page it should use to actually navigate, you'll need to target the one from the CustomerDetailAddressSelectionPage and not the one from the app root that kicked of the tabbed page.
Check if you are constructor injecting a nav service in the VM for CustomerDetailAddressSelectionPage.
| |
doc_23538390
|
A: If the button is called myButton try using
myButton.setEnabled(false);
Then you can add some type of listener to your radio button and in that listener add
myButton.setEnabled(true);
Also, you can check out the android:clickable attribute in xml.
| |
doc_23538391
|
I tried the following code to modifying my rc file --
dill.load_session('./param_new_EVI5_n1_design_2.pkl')
font = {'family' : 'sans-serif',
'sans-serif':'Helvetica',
'weight' : 'normal',
'size' : 18}
plt.rc('font', **font)
However, I'm getting the following error --
/home/shihab/.conda/envs/paper1_py37/lib/python3.7/site->packages/matplotlib/font_manager.py:1241: UserWarning: findfont: Font >family ['sans-serif'] not found. Falling back to DejaVu Sans.
(prop.get_family(), self.defaultFamily[fontext]))
| |
doc_23538392
|
<<
22:36:16,304 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-6) MSC000001: Failed to start service jboss.deployment.unit."ejb-application.ear".FIRST_MODULE_USE: org.jboss.msc.service.StartException in service jboss.deployment.unit."ejb-application.ear".FIRST_MODULE_USE: WFLYSRV0153: Failed to process phase FIRST_MODULE_USE of deployment "ejb-application.ear"
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:183)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1739)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1701)
at org.jboss.msc.service.ServiceControllerImpl$ControllerTask.run(ServiceControllerImpl.java:1559)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYJPA0019: Could not deploy application packaged persistence provider 'org.hibernate.jpa.HibernatePersistenceProvider'
at org.jboss.as.jpa.processor.PersistenceProviderHandler.deploy(PersistenceProviderHandler.java:80)
at org.jboss.as.jpa.processor.PersistenceBeginInstallProcessor.deploy(PersistenceBeginInstallProcessor.java:49)
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:176)
... 8 more
Caused by: java.lang.ClassCastException: class org.hibernate.jpa.HibernatePersistenceProvider
at java.lang.Class.asSubclass(Class.java:3404)
at org.jboss.as.jpa.processor.PersistenceProviderHandler.deploy(PersistenceProviderHandler.java:73)
... 10 more
>>
here is our Persistence.xml file
<<
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="jboss">
<!-- If you are running in a production environment, add a managed
data source, this example data source is just for development and testing! -->
<!-- The datasource is deployed as WEB-INF/hibernate-quickstart-ds.xml, you
can find it in the source at src/main/webapp/WEB-INF/hibernate-quickstart-ds.xml -->
<jta-data-source>java:jboss/jdbc/AppDatasource</jta-data-source>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
>>
We understand it is something to do with persistence.xml & jboss-deployment-structure.xml files.
We tried to include/exclude all the relevant modules in the files, but still we are getting the above issue.
Also, we are migrating from Hibernate 3 to Hibernate 5.
Kindly help to resolve this issue.
A: Looks like you might be packaging Hibernate along with your application in a different version or you excluded the Hibernate version in the jboss-deployment-structure.xml
| |
doc_23538393
|
A: GRANDstack is all about creating a GraphQL API application backed by Neo4j, not for directly querying the database with GraphQL. The neo4j-graphql integrations generate Cypher queries that are sent to Neo4j (via Bolt and the Neo4j client drivers) from the API application.
So it's more about generating database queries from GraphQL requests than sending GraphQL requests directly to the database. This image shows the GRANDstack architecture - the client is querying the GraphQL API app with GraphQL, that API app is then responsible for resolving the data from Neo4j (by sending Cypher queries over Bolt protocol), the interesting bit is the neo4j-graphql integration which is generating those database (Cypher) queries from GraphQL requests.
| |
doc_23538394
|
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
// First top-level window definition.
glutInitWindowSize(250, 500);
glutInitWindowPosition(100, 100);
// Create the first window and return id.
id1 = glutCreateWindow("windows.cpp - window 1");
// Initialization, display, and other routines of the first window.
setup1();
glutDisplayFunc(drawScene1);
glutReshapeFunc(resize1);
glutKeyboardFunc(keyInput); // Routine is shared by both windows.
// Second top-level window definition.
glutInitWindowSize(250, 500);
glutInitWindowPosition(400, 100);
// Create the second window and return id.
id2 = glutCreateWindow("windows.cpp - window 2");
// Initialization, display, and other routines of the second window.
setup2();
glutDisplayFunc(drawScene2);
glutReshapeFunc(resize2);
glutKeyboardFunc(keyInput); // Routine is shared by both windows.
glutMainLoop();
return 0;
}
I'm using Windows 7, and normally it should display two windows. But as you can see, only one Window displays properly and the other one doesn't seem to work quite as well. Are there additional steps that I have to take other than GLUT_DOUBLE and buffer swap?
A:
Are there additional steps that I have to take other than GLUT_DOUBLE and buffer swap?
Since you are creating multiple windows, you have to call glutSetWindow() in your callbacks.
freeglut has an extension (which doesn't work) to create a shared opengl context, but the original glut doesn't support it.
| |
doc_23538395
|
ERROR: Cannot install pyqt6-tools==6.0.1.3.2, pyqt6-tools==6.0.2.3.2, pyqt6-tools==6.0.3.3.2 and pyqt6-tools==6.1.0.3.2 because these package versions have conflicting dependencies.
The conflict is caused by:
pyqt6-tools 6.1.0.3.2 depends on pyqt6-plugins<6.1.0.3 and >=6.1.0.2.2
pyqt6-tools 6.0.3.3.2 depends on pyqt6-plugins<6.0.3.3 and >=6.0.3.2.2
pyqt6-tools 6.0.2.3.2 depends on pyqt6-plugins<6.0.2.3 and >=6.0.2.2.2
pyqt6-tools 6.0.1.3.2 depends on pyqt6-plugins<6.0.1.3 and >=6.0.1.2.2
To fix this you could try to:
1. loosen the range of package versions you've specified
2. remove package versions to allow pip attempt to solve the dependency conflict
I tried pip installing pyqt6-plugins but when I do that it says
ERROR: Could not find a version that satisfies the requirement pyqt6-plugins (from versions: none)
ERROR: No matching distribution found for pyqt6-plugins
| |
doc_23538396
|
The uploaded jar file is almost identical to the original:
*
*The file size compared to the original is similar (at the KB level)
*I can open the uploaded jar file using an unzipping program and view it's contents (resources and class files), and everything is the same compared to the original file
When I open up the uploaded jar file (using Notepad++), I did notice that the binary contents are different from the original. Also, when I used JarInputStream to read the JAR entries, there were no entries.
JarInputStream is = new JarInputStream(new FileInputStream(new File("uploaded.jar")));
JarEntry entry = null;
while(null != (entry = is.getNextJarEntry())) {
System.out.println(entry.getName());
}
Furthermore, when I double click on the jar (Windows), I get the following message.
Error: Invalid or corrupt jarfile
My questions are:
*
*Is there a way to programmatically check if a jar file is valid? I would have expected JarInputStream to detect this right away, but it shows no problems at all
*When I double click on the jar file, in windows, is it java.exe that is giving me the "invalid or corrupt JAR file" message?
*How come when an invalid jar file is passed in as part of the classpath, no error/exception is thrown? For example, by running the java -cp uploaded.jar;libs\* com.some.class.Test command?
This question is irrelevant from jar signing and/or checking the signature of a JAR file. It is simply checking if a file (uploaded or not) is a valid JAR file (not necessarily if the jar's class files are valid, as there is another SO post on this issue already).
My results for running jar -tvf uploaded.jar:
java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:127)
at java.util.zip.ZipFile.<init>(ZipFile.java:88)
at sun.tools.jar.Main.list(Main.java:977)
at sun.tools.jar.Main.run(Main.java:222)
at sun.tools.jar.Main.main(Main.java:1147)
A: A way to programmatically detect an invalid jar file is to use java.util.ZipFile.
public static void main(String[] args) {
if(args.length < 1) {
System.err.println("need jar file");
return;
}
String pathname = args[0];
try {
ZipFile file = new ZipFile(new File(pathname));
Enumeration<? extends ZipEntry> e = file.entries();
while(e.hasMoreElements()) {
ZipEntry entry = e.nextElement();
System.out.println(entry.getName());
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
If the jar file is invalid, a ZipException will be thrown when instantiating the ZipFile object.
| |
doc_23538397
|
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
How to display inversly with foreach ?
A: You could use Reverse():
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray.Reverse())
{
System.Console.WriteLine(i);
}
In general foreach must support any IEnumerable which only support forward enumeration of items in the collection, as an alternative to Reverse() you could write your own optimized implementation that works on an IList which provides an indexer.
A: using System.Linq;
foreach (int i in fibArray.Reverse())
But a normal for loop will be more efficient:
for( int index = fibArray.Length - 1; index >= 0; --index ) {
int i = fibArray[index];
...
}
A: foreach (int i in fibarray.Reverse<int>())
{
System.Console.WriteLine(i);
}
A: Nope. Use for instead, or modify your collection to be in the desired order before iterating.
A: Enumerable.Reverse()
foreach (int i in fibarray.Reverse)
System.Console.Writeline(i);
A: I don't think this is possible by default. You would need to create your own class with an iterator with that capability:
C# .NET Iterator Example : Reverse Iteration
A: In short, no. You cannot change the behavior of foreach. If you want to do this without returning a new array (like calling Reverse), then use a for loop.
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
for (int i = fibarray.Length - 1; i > -1; i--) {
Console.WriteLine(i);
}
| |
doc_23538398
|
I'm not sure if this is a bug or not, but those node appeared on my 2 clusters:
*
*first (my staging env), after update from 1.7.5 to 1.7.6
*second (my prod env), after update from 1.6.5 to 1.7.6
However, when I've created new cluster with version 1.7.5 and update it to 1.7.6 those pods have not appeared.
Mentiones pods are:
*
*calico-node
*calico-node-vertical-autoscaler
*calico-typha
*calico-typha-horizontal-autoscaler
*calico-typha-vertical-autoscaler
edit:
A: Calico is how Kubernetes network policies are implemented in GKE.
https://cloudplatform.googleblog.com/2017/09/network-policy-support-for-kubernetes-with-calico.html
I don't think it would be safe to delete them, if you did you very likely would end up with unreachable pods.
I thought it was necessary to specify --enable-network-policy when creating and even another extra step when updating a cluster. Though maybe the components are always deployed but allow all policies are created if the flags are not specified.
Edit: If you delete calico pods they will be recreated and the add-on manager ensures there is no way to remove calico.
Edit: There is a command to disable network policy in GKE and the directions can be found at https://cloud.google.com/container-engine/docs/network-policy#disabling_network_policy_enforcement.
A: It looks like Google provided a way to get rid of calico PODs via Google Cloud Console. Please see the screen below.
| |
doc_23538399
|
>>> os.system('echo -n abc')
-n abc
0
the output has -n which is not correct. If I run the command on terminal it doesn't print the newline at the end. It seems os.system method doesn't understand -n parameter. How can I solve this issue?
I have tried subprocess module but got the same result:
>>> subprocess.call('echo -n abc', shell=True)
-n abc
0
A: Is this correct behavior for echo to have?
This is legal, standards-compliant behavior for an echo implementation to have. Quoting from the POSIX echo standard (the APPLICATION USAGE section of which is also strongly recommended reading):
If the first operand is -n, or if any of the operands contain a backslash character, the results are implementation-defined.
Thus, echo is allowed to print -n literally -- or to do anything else when it's given as the first operand.
Why does my interactive shell do something different?
As the above-quoted specification says, behavior is undefined when -n is given as first argument. This means every behavior is equally legal; so not printing a trailing newline is also a legal behavior. Presumably your interactive shell does that (on the system at hand), whereas your /bin/sh does not.
How can I get reliable behavior when starting a shell to print text without a trailing newline?
If you want a command with well-specified behavior, use printf instead:
os.system('printf %s abc')
...will always print the exact string abc with no trailing newline, with any POSIX-compliant /bin/sh.
But of course, don't do any of this in Python; sys.stdout.write('abc') is far more sensible.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.