id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_1800
|
a) jruby?
b) Run a simple ruby xml rpc daemon that calls the actual ruby lib internally ? I believe xml rpc is easy in java.
c) Thrift ?
d) Implement a java lib that talks to their RESTful service(more dev time?)
What would be the quickest way to do this ?
A: Given that it's a simple REST API (for example, see http://support.recurly.com/faqs/api/accounts), I'd just replicate the ruby library in Java, it should be simple enough, could get you some karma on recurly guys if you can/will share it back and will avoid any integration or compatibility problems that might arise using an external daemon or jruby or thrift (the more components you add to your code, the more fragile it gets.)
Not necessarily the quickest but the safest route IMO. See here for what to use to implement the library if you deem it necessary.
| |
doc_1801
|
$pars = array('foo'=>array(1, 2, 3, 4));
function x($par){
// how do i get array key from $par, so it will print/return 'foo'
}
x($pars['foo']);
how do i get the array key, when i call function x($pars['foo'])
A: try like this,
function x($par){
foreach ($par as $key => $value)
{
//you can get key here
}
}
| |
doc_1802
|
What I would like is to have a square (2x2) presentation, with A over nothing, and B over C.
Can I either extract the individual panels of the plot, or create a facet with no axes or other graphic (like plotgrid with a NULL panel).
A: A second option would be the ggh4x package which via facet_manual adds some flexibility to place the panels:
library(ggplot2)
library(ggh4x)
design <- "
AB
#C"
ggplot(mtcars, aes(mpg, disp)) +
geom_point() +
facet_manual(~cyl, design = design)
A: One approach could be creating separate plots using nest() and map() from {tidyverse} and then using {patchwork} package to align them as we want.
(Since OP didn't provide any data and code, I am using builtin mtcars dataset to show how to do this). Suppose This is the case where we have a facetted plot with 3 panels in a 3 x 1 format.
library(tidyverse)
# 3 x 1 faceted plot
mtcars %>%
ggplot(aes(mpg, disp)) +
geom_point() +
facet_wrap(~cyl, nrow = 3)
Now to match the question, lets suppose panel for cyl 4 is plot A, panel for cyl 6 is plot B and for cyl 8 is plot C.
So to this, we first created a nested dataset with respect to facet variable using group_by(facet_var) %>% nest() and then map the ggplot over the nested data to get plots (gg object) for each nested data.
library(tidyverse)
library(patchwork)
# Say, plotA is cyl 4
# plotB is cyl 6
# plotC is cyl 8
# 2 x 2 facet plot
plot_data <- mtcars %>%
group_by(cyl) %>%
nest() %>%
mutate(
plots = map2(
.x = data,
.y = cyl,
.f = ~ ggplot(data = .x, mapping = aes(mpg, disp)) +
geom_point() +
ggtitle(paste0("cyl is ",.y))
)
)
plot_data
#> # A tibble: 3 × 3
#> # Groups: cyl [3]
#> cyl data plots
#> <dbl> <list> <list>
#> 1 6 <tibble [7 × 10]> <gg>
#> 2 4 <tibble [11 × 10]> <gg>
#> 3 8 <tibble [14 × 10]> <gg>
Then simply align the plots using {patchwork} syntax as we wanted. I have used plot_spacer() to create blank space.
plot_data
plots <- plot_data$plots
plots[[2]] + plots[[1]] + plot_spacer() + plots[[3]] +
plot_annotation(
title = "A 2 X 2 faceted plot"
)
| |
doc_1803
|
int _ = 10;
If underscore is a keyword, then why it is not present in the list of java keywords mentioned at Java Language Keywords
A: That tutorial is still on Java 8. If you want to follow more accurate and updated specification, you should take a look at the Java Language Specification, specifically this section from Specification for Java SE 11:
abstract continue for new switch
assert default if package synchronized
boolean do goto private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
_ (underscore)
A: Well, the note on top of the page you are referring to says it:
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
Apparently, they haven't (yet?) updated the tutorials to newer Java versions.
Even if it were allowed, I would suggest you not to be using the underscore character as a variable name anyway. Variable names should be descriptive.
| |
doc_1804
|
I'm trying to load model for mongoDB with this:
User.includes(:party).first
In debug mode for mongoid I see next requests:
D, [2015-12-19T13:53:19.354800 #3847] DEBUG -- : MONGODB | STARTED | {"find"=>"users", "filter"=>{}}
D, [2015-12-19T13:53:19.355403 #3847] DEBUG -- : MONGODB | SUCCEEDED | 0.000451s
D, [2015-12-19T13:53:19.366237 #3847] DEBUG -- : MONGODB | STARTED | {"find"=>"parties", "filter"=>{"user_id"=>{"$in"=>[nil]}}}
D, [2015-12-19T13:53:19.366626 #3847] DEBUG -- : MONGODB | SUCCEEDED | 0.000307s
As you can see second request performed with this params:
{"find"=>"parties", "filter"=>{"user_id"=>{"$in"=>[nil]}}}
I can't figure out why, here is my models:
class User
include Mongoid::Document
include Mongoid::Timestamps
field :nickname, type: String
field :email, type: String
has_one :party
has_many :added_songs, class_name: 'Playlist::Song'
has_many :chat_messages, class_name: 'Chat::Message'
end
class Party
include Mongoid::Document
include Mongoid::Timestamps
field :active, type: Boolean, default: true
field :title, type: String
belongs_to :user
has_one :chat, class_name: 'Party::Chat'
has_one :playlist, class_name: 'Party::Playlist'
end
And the interesting part is that if I do:
Party.includes(:user).first
It works fine. Thanks for any help!
A: You have not necessarily specified what "it works" means but I assume you just mean that it actually returns a document from the database. As far as I can tell your eager load is working as intended.
You are specifying that User has one Party. That means the user_id is stores in the Party, and that party_id is not stored in User.
So when you run this query:
User.includes(:party).first
It will specifically look for the Party objects that do not have a specific User:
"find"=>"parties", "filter"=>{"user_id"=>{"$in"=>[nil]}}
So if you do the reverse:
Party.includes(:user).first
It is not capable of doing this:
"find"=>"users", "filter"=>{"party_id"=>{"$in"=>[nil]}}
Because there is no party_id stored in the User collection.
So if you want to run User.includes(:party).first you should try finding a specific User first, something like:
User.where(:_id => "one of your users").includes(:party).first
| |
doc_1805
|
I am currently working on a Spark Structured Streaming window job and running on YARN. it seems that on every batch interval I get the warning then the job is down:
WARN state.HDFSBackedStateStoreProvider: The state for version 1780 doesn't exist in loadedMaps. Reading snapshot file and delta files if needed...Note that this is normal for the first batch of starting query.
the warn log picture
the stdout log picture2
Here is my code:
df.writeStream\
.foreachBatch(handle_kafka.__execute)\
.option("checkpointLocation", "/user/hive/warehouse/tempdb.db/kafka_silver_gamelog_streaming") \
.outputMode("update")
.start()
Please help me out for the same. There may be workarounds for this issue, please suggest me if any.
| |
doc_1806
|
Fatal error: Class 'ManageRatings' not found in C:\wamp\www\laravel\fresh\app\classes\rating.php
Below is my 3 custom files and a View File..
(ManageRatings.php)
<?php namespace App\classes;
use App\shaadi_hall_info;
use DB;
class ManageRatings{
public static function getItems($id = null){
if(isset($id)){
$query = DB::table('shaadi_hall_info')->select('rating', 'total_rating','total_rates','ip_address')->where('hall_id','=','$id')->get();
}
else
{
$query = DB::table('shaadi_hall_info')->get();
}
return $query;
}
public function insertRatings($id,$rating,$total_rating,$total_rates,$ip_address){
$query = DB::table('shaadi_hall_info')
->where('hall_id','=','id')
->update(array('rating' => 'rating', 'total_rating' => 'total_rating', 'total_rates' => 'total_rates', 'ip_address' => 'CONCAT(ip_address,",$ip_address")'));
return $query;
}
}
(Ratings.php)
<?php namespace App\classes;
use App\classes\ManageRatings;
use App\shaadi_hall_info;
use DB;
$response['success'] = false;
$response['error'] = false;
$init = new ManageRatings;
if($_POST)
{
$id = $_POST['idBox'];
$rate = $_POST['rate'];
}
$ip_address = $_SERVER["REMOTE_ADDR"];
$existingData = $init->getItems($id);
foreach($existingData as $data)
{
$old_total_rating = $data['total_rating'];
$total_rates = $data['total_rates'];
}
$current_rating = $old_total_rating + $rate;
$new_total_rates = $total_rates + 1;
$new_rating = $current_rating / $new_total_rates;
$insert = $init->insertRatings($id,$new_rating,$current_rating,$new_total_rates,$ip_address);
if($insert == 1)
{
$response['success'] = 'Success';
}
else
{
$response['error'] = 'Error';
}
echo json_encode($response);
(getItems.php)
<?php namespace App\classes;
use App\classes\ManageRatings;
use App\shaadi_hall_info;
use DB;
$init = new ManageRatings;
$allItems = $init->getItems();
Here is my View Part where I am sending the request to Rating.php file..
<script type="text/javascript">
jQuery(document).ready(function(){
$(".rating").jRating({
decimalLength : 1,
rateMax : 5, // maximal rate - integer from 0 to 9999 (or more)
phpPath: '../App/classes/rating.php',
onSuccess: function(){
alert('Your rating has been submitted');
},
onError: function(){
alert('There was a problem submitting your feedback');
}
});
});
</script>
I am using the correct namespace in each file but don't know why I am getting this weird Error. Rating System code is working fine in simple Php but when I convert it into Laravel 5 I am getting this strange error. Please help me in this I got stuck in this for last 6 hours... Thanks in advance..
| |
doc_1807
|
<span id="input-prompt-0" class="input-prompt">Company Name</span>
For every text input field. Instead it keeps giving me this:
<span id="input-prompt-0" class="input-prompt" style="display: block;">Company Name</span>
Any ideas why?
Here's the code:
$(document).ready(function(){
$('input[type=text][title],input[type=password][title],textarea[title]').each(function(i){
$(this).addClass('input-prompt-' + i);
var promptSpan = $('<span class="input-prompt"/>');
$(promptSpan).attr('id', 'input-prompt-' + i);
$(promptSpan).append($(this).attr('title'));
$(promptSpan).click(function(){
$(this).hide();
$('.' + $(this).attr('id')).focus();
});
if($(this).val() != ''){
$(promptSpan).hide();
}
$(this).before(promptSpan);
$(this).focus(function(){
$('#input-prompt-' + i).hide();
});
$(this).blur(function(){
if($(this).val() == ''){
$('#input-prompt-' + i).show();
}
});
});
});
A: The line $('#input-prompt-' + i).show(); is modifying the style. From the docs on jQuery.show:
The matched elements will be revealed immediately, with no animation.
This is roughly equivalent to calling .css('display', 'block'), except
that the display property is restored to whatever it was initially.
I guess the more prominent question is why this is "throwing off [your] css"?
A: This line of code adds the style attribute:
$('#input-prompt-' + i).show();
You can instead use:
$('#input-prompt-' + i).css("display", "");
That will show the span and eliminate the style attribute.
A: The problem is most likely related to you using .show() and .hide().
These functions alter the style of the element to do their magic.
A: JQuery show() and hide() functions modified the styles
| |
doc_1808
|
My ROS version is ROS Indigo and OS version is Ubuntu 14.04
A: Here is a step-by-step guide of doing it using ROS bloom:
*
*Navigate to your package path
cd /path/to/package
*Use ROS bloom to create the .deb file
bloom-generate rosdebian --os-name ubuntu --ros-distro kinetic fakeroot debian/rules binary
* If your ROS distribution is different from Kinetic, replace kinetic with your distribution
*Copy the .deb file to the other machine, and in its folder type
sudo dpkg -i packagename.deb
this will install the package on that machine, and you are now able to use it like any other ROS package
A: 1 - I think the ROS build farm would be a good starting point and solution for that. You cannot create a .deb as you said but, you can create a source closed ROS packages
The ROS build farm is also designed to enable deploying a custom build farm. This can be useful to release closed-source packages, build for platforms and architectures not provided by the official ROS build farm, and/or customize any part of the process to specific needs.
Take a look here for a better overview.
2 - Another approach would be using a CMake install. Although this will require the same architecture and ROS Distro between both your platforms and a location that can be the same for both machines.
Define a CMAKE_INSTALL_PREFIX for some location like: /opt/your_ros_install.
Run sudo make install to allow installing there.
Copy the install directory from machine A to machine B, using scp or tar or some other technique.
To run your installed ROS packages on either machine: source /opt/your_ros_install/setup.bash.
A: Take a look at this post: Generate .deb from ROS package
Use the following commands:
path-of-your-package$ bloom-generate rosdebian --os-name ubuntu --ros-distro kinetic
$fakeroot debian/rules binary
| |
doc_1809
|
#include <stdio.h>
int main() {
int m = 300;
double fx = 300.6006;
char z = "c";
printf("%d\n %lf\n %c\n", m, fx, z);
printf("%p\n %p\n %p\n", &m, &fx, &z);
int* ptr_m = &m;
double* ptr_fx = &fx;
char* ptr_z = &z;
printf("%d\n %lf\n %c\n", *ptr_m, *ptr_fx, *ptr_z);
printf("%p\n %p\n %p\n", &ptr_m, &ptr_fx, &ptr_z);
return 0;
}
Can you help me fix this ?
A: Replace:
char z = "c";
with
char z = 'c';
A: "c" is a character literal having the array type char[2]. It is represented in memory like array { 'c', '\0' }. Used as an initializer expression it is implicitly converted to a pointer to its first element of the type char *. So in this declaration
char z = "c";
that is equivalent to the declaration
char z = &"c"[0];
you are trying to initialize the object z having the type char with a pointer of the type char *. Instead of the string literal you need to use an integer character constant like
char z = 'c';
In calls of printf like this
printf("%d\n %lf\n %c\n", m, fx, z);
the length modifier l in this format %lf is redundant and has no effect. You may write
printf("%d\n %f\n %c\n", m, fx, z);
Also you should cast pointers to the type void * in calls of printf like this
printf("%p\n %p\n %p\n", ( void * )&m, ( void * )&fx, ( void * )&z);
And it seems instead of this call of printf
printf("%p\n %p\n %p\n", &ptr_m, &ptr_fx, &ptr_z);
you mean this call
printf("%p\n %p\n %p\n", ( void * )ptr_m, ( void * )ptr_fx, ( void *)ptr_z);
| |
doc_1810
|
*
*IIS 7.5 / Windows Server 2008 R2
*Multiple IIS sites bound to the same IP address, using host names.
*Inbound traffic to sites working fine.
*Outbound web requests made by the back-end site code fail. Remote site returns 404 (NotFound).
*Verified via a network trace that the traffic is making it to the remove server.
*Same requests work fine if done from a site using a dedicated IP address (i.e. not shared w/ any other sites).
Anyone have any ideas on how to make this work or what could be going wrong?
Network trace on hosting server:
Successful request from site w/ non-shared IP address:
No. Time Source Destination Protocol Info
6366 15:54:35.590463 192.168.1.76 173.194.77.121 HTTP GET /key/value/one/two HTTP/1.1
6369 15:54:35.599879 173.194.77.121 192.168.1.76 TCP http > 55407 [ACK] Seq=1 Ack=110 Win=344 Len=0
6370 15:54:35.621587 173.194.77.121 192.168.1.76 HTTP HTTP/1.1 200 OK (application/json)
6608 15:54:35.815774 192.168.1.76 173.194.77.121 TCP 55407 > http [ACK] Seq=110 Ack=357 Win=509 Len=0
Failed request from site using a shared IP address:
No. Time Source Destination Protocol Info
9720 15:54:39.244192 192.168.1.80 173.194.77.121 HTTP GET /key/value/one/two HTTP/1.1
9760 15:54:39.256958 173.194.77.121 192.168.1.80 TCP [TCP segment of a reassembled PDU]
9761 15:54:39.256962 173.194.77.121 192.168.1.80 HTTP HTTP/1.1 404 Not Found (text/html)
9762 15:54:39.257027 192.168.1.80 173.194.77.121 TCP 55438 > http [ACK] Seq=212 Ack=1676 Win=512 Len=0
Code:
public static HttpWebRequest CreateWebRequest(string url, string method = "GET", string referer = null, string contentType = null, int timeout = 100000, string authentication = null, string bindToIpAddress = null, string host = null)
{
var request = (HttpWebRequest)WebRequest.Create(url);
if (!string.IsNullOrWhiteSpace(bindToIpAddress))
{
IPAddress bindIp;
if (!IPAddress.TryParse(bindToIpAddress, out bindIp))
{
throw new ArgumentException("bindToIpAddress");
}
request.ServicePoint.BindIPEndPointDelegate = ((sp, rep, rc) =>
{
return new IPEndPoint(bindIp, 0);
});
}
request.Accept = "*/*";
request.ContentType = contentType;
request.Referer = referer;
request.Method = method;
request.Timeout = timeout;
if (!string.IsNullOrWhiteSpace(host))
{
request.Host = host;
}
return request;
}
string GetData()
{
try
{
string result;
var request = CreateWebRequest("http://jsonplaceholder.typicode.com/posts/1",
"GET",
"somedomain.com",
timeout: (10 * 1000),
bindToIpAddress: "192.168.27.133" /*site IP*/);
request.Accept = "application/json";
using (var response = request.GetResponse())
{
using (var sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
}
}
return result;
}
catch (Exception ex)
{
return null;
}
}
A: The 404 response comes back from the remote site, so the remote site is failing to process your request, and it has nothing to do with what's going on on your local server.
The only difference from the remote site's point of view is the sender's IP address, so it must be configured to accept requests only from certain IP addresses. This restriction could be in the remote server, or any firewall, router or proxy in between.
A: This turned out to be a bug in our application. In some cases, the host header (Host property on the request) was being set improperly (to the hosting/source site's host name). The stripped down code sample in the question doesn't show it. It was fine for web services that ignored the header and was an issue (404 response) for others that did not ignore the header. The issue had nothing to do w/ IIS or shared IP address. Thanks for all of the responses.
| |
doc_1811
|
Here is the image of the issue which I am talking about
Code is here:
import {
Button,
Input,
InputGroup,
Modal,
ModalBody,
ModalFooter,
ModalHeader} from "reactstrap";
return (
<Modal
isOpen={this.state.textEditorToggle}
className="text_edit_model edit-model"
>
<ModalHeader toggle={this.toggleModal}>{fieldName}</ModalHeader>
<ModalBody>
<CKEditor
config={{
extraPlugins: [uploadPlugin],
}}
editor={ClassicEditor}
data={value ? value : ""}
onReady={(editor) => {}}
// onInit={(editor) => {}}
onChange={this.handleCk5change}
/>
</ModalBody>
<ModalFooter>
<div className="record_btn" onClick={toggle}>
<button>CANCEL</button>
</div>
<div
className="record_btn"
onClick={saveFun}
>
<button disabled={load}>SAVE</button>
</div>
</ModalFooter>
</Modal>
)
I have also checked with changing Modal with normal and changing accordingly, It is working fine but this problem is occuring only with reactstrap Modal. I believe it is related to focus of Modal but not sure how to solve it. Can someone help here?
| |
doc_1812
|
I have a check_method field in the Host class. Here it is set using self and when I use json.dumps for serialization, it gets into the output file.
If I remove self, then the field becomes inaccessible from the main code.
The described class is part of a class AppConfig. AppConfig is a class containing the usual fields. The get_hosts() method returns an array of hosts.
AppConfig class that is serialized using json.dumps()
import json
class Host(object) :
otval_date = ''
otval_cnt = 0
def __init__(self, name : str, host : str, check_method : str, http_code : str, stop_after : bool, notify : bool):
self.name = name
self.host = host
self.check_method = check_method
self.http_code = http_code
self.stop_after = stop_after
self.notify = notify
class AppConfig(object) :
def __init__(self, config : any):
self.log_important = config['log_important']
self.await_time = config['await_time']
self.ips = get_hosts(config['ips'], 'ping')
self.domains = get_hosts(config['domains'], 'curl')
def get_hosts(conf_host_objs, check_method) -> list :
hosts_list = []
for host in conf_host_objs:
hosts_list.append(Host(
name = host['name'],
host = host['host'],
check_method = check_method,
http_code = host['http_normal_code'] if 'http_normal_code' in host else '',
stop_after = host['stop_after'] == 1,
notify = host['notify']
))
return hosts_list
# test example
config = {'log_important': False, 'await_time': 2, 'ips': [{'host': '192.168.0.1', 'name': 'local network', 'stop_after': 1, 'notify': False}, {'host': '8.8.8.8', 'name': 'google dns', 'stop_after': 1, 'notify': False}], 'domains': [{'host': 'stackoverflow.com', 'name': 'stackoverflow.com', 'http_normal_code': 200, 'stop_after': 0, 'notify': True}]}
APP_CONFIG = AppConfig(config)
# Here the main work happens with the APP_CONFIG class.
# It can change, expand, contract, and so on
json_config_dumps = json.dumps(APP_CONFIG, default=lambda x: x.__dict__)
print(json_config_dumps)
What do I need to do to continue seeing the field in the main code? But at the same time, so that it is initialized when creating a class in the constructor. The field can be static. I don't change it from the main code.
Thanks!
A:
How to serialize only some fields in json in python?
You simple pass to the json serializer only the fields you're interested in serialising and nothing more.
How to do that? simple make either a function or a class method that return a new dictionary, list or whatever json compatible thing you're interested in it with the thing you want.
for example, said you only want to serialize only certain parts of the following class A and B, then you can do as follow
class A:
def __init__(self, a: str, b:str):
self.a = a
self.b = b
def to_json(self) -> dict: # add a method to make it json compatible
return {"A":self.a}
class B:
def __init__(self, a: str, b:str):
self.a = a
self.b = b
def b_to_json(inst_b: B) -> list: # add a function to make it json compatible
return [inst_b.b]
and use them accordingly
>>> import json
>>> a= A("hello", "world")
>>> b= B("buu","this is b")
>>> json.dumps(a.to_json())
'{"A": "hello"}'
>>> json.dumps(b_to_json(b))
'["this is b"]'
>>> a
<__main__.A object at 0x000002C56D6366D0>
>>> b
<__main__.B object at 0x000002C5700584D0>
>>>
to get the thing back from the json, then you need the make the inverse function (in the example above that isn't really possible because one of the attributes is missing in the json result, so a default value is needed to fill the gab so you aren't guaranty to get a exact copy of the original)
What do I need to do to continue seeing the field in the main code? But at the same time, so that it is initialized when creating a class in the constructor. The field can be static. I don't change it from the main code.
I'm not sure what you mean by that, serializing an object doesn't destroy or remove the original object, it just make a new one in a new form
| |
doc_1813
|
I execute the command: npm run build
but When I charged the page I don't se the chunk file, why? I forgot to do somethings?
auth.module.ts :
@NgModule({
declarations: [
AuthComponent,
LoginComponent,
RegisterComponent,
ForgotPasswordComponent,
ResetPasswordComponent
],
exports: [],
imports: [
FormsModule,
CommonModule,
AuthRoutingModule
]
})
export class AuthModule { }
auth-routes.modules.ts
const authRoutes: Routes = [
{
path: "login", component: LoginComponent, data: { title: "Login" }
},
{
path: "register", component: RegisterComponent, data: { title: "Register" }
},
{
path: "forgot/password", component: ForgotPasswordComponent, data: { title: "Forgot Password" }
},
{
path: "reset/password", component: ResetPasswordComponent, data: { title: "Reset Password" }
}
];
@NgModule({
imports: [RouterModule.forChild(authRoutes)],
exports: [RouterModule]
})
export class AuthRoutingModule { }
pages.module.ts
@NgModule({
declarations: [
PagesComponent,
AllUsersComponent,
AllUsersComponent,
TestrouteComponent
],
exports: [],
imports: [
PagesRoutingModule,
AuthModule,
CommonModule,
RouterModule
]
})
pages.routes.ts
const pagesRoutes: Routes = [
{
path: "users", component: AllUsersComponent, data: { title: "Users" }
},
{
path: "orders", component: AllOrdersComponent, data: { title: "Orders" }
},
{
path: "protect", component: TestrouteComponent, data: { title: "Protect" }, canActivate: [AuthGuard]
}
];
@NgModule({
imports: [RouterModule.forChild(pagesRoutes)],
exports: [RouterModule]
})
export class PagesRoutingModule { }
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
CommonModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
AuthModule,
PagesModule,
ServiceModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
const routes: Routes = [
{
path: '',
loadChildren: './pages/auth/auth.module#AuthModule'
},
{
path: '', component: PagesComponent, loadChildren: '../app/pages/pages.module.ts#PagesModule'
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
A: i think i saw what you doing wrong.
try this on your app routing module
app-routing.module.ts
const routes: Routes = [
{
path: '/c',
loadChildren: './pages/auth/auth.module#AuthModule'
},
{
path: '/p',loadChildren:'../app/pages/pages.module#PagesModule'
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
now your URL's is gonna be https://yoursite.com/c/componentsFromAuthModule
and https://yoursite.com/p/componentsFromPageModule
if don't work please make a stackblitz and i can help you
| |
doc_1814
|
I want to access navigation drawer in all activities.I don't want to use fragments.Instead i want to use activities.I know that use of fragments are better than activities.
please help me guys.
A: You really should think again about this. Don't be afraid of using fragments, they are good and you will use it a lot in the future. I see that there is no need at all for such design and it's less flexible and will cause bad design and code redundancy. You may mention the full scenario and we can help you designing your app better.
A: I think that you can't use 'NavigationDrawer' to do this, you must use 'Fragments' with 'NavigationDrawer' and I recommend you to do it in this way to improve app flexibility and user interface.
First: Google recommend use 'Fragment'. To create a dynamic and multi-pane user interface on Android, you need to encapsulate UI components and activity behaviors into modules that you can swap into and out of your activities. You can create these modules with the Fragment class, which behaves somewhat like a nested activity that can define its own layout and manage its own lifecycle.
Visit http://developer.android.com/training/basics/fragments/index.html
Second: The main content view (the FrameLayout above) must be the first child in the DrawerLayout because the XML order implies z-ordering and the drawer must be on top of the content.
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
Visit http://developer.android.com/training/implementing-navigation/nav-drawer.html
Third: You want something like this. 'Navigation Hubs' The navigation drawer is a reflection of your app’s structure and displays its major navigation hubs. Think of navigation hubs as those places in your app that a user will want to visit frequently or use as a jumping-off point to other parts of the app. At a minimum, the navigation hubs are the top-level views, since they correspond to your app’s major functional areas. If your app’s structure is deep, you can add screens from lower levels that your users will likely visit often and make those navigation hubs as well.
Visit http://developer.android.com/design/patterns/navigation-drawer.html
| |
doc_1815
|
class ResultSet
implements ArrayAccess, Countable, Iterator {
/// Rest of implementation ...
}
I'm running into a problem using usort() and passing my object as the first parameter. usort() expects an array instead of an object, but given my implementation of the ArrayAccess interface I don't know what else it could be needing.
The exact error returned by php is:
Warning: usort() expects parameter 1 to be array, object given.
A: If memory serves, there's a big warning sign on the ArrayAccess page, or in one of the comments on it (probably the latter, in fact). It basically says something in the order of: the interface is somewhat useless, because PHP's array functions don't recognize any of its members as arrays.
A: How would usort know how you've implemented ArrayAccess? There is no defined place where the values are kept -- that flexibility is the whole point of the interface.
If you are storing the elements in an array that is a private member of the object, you could proxy the usort operation. For example:
public function usort($callback) {
usort($this->container, $callback);
}
| |
doc_1816
|
I received this response:
-bash: adb: command not found
What should I do? Please keep it simple as I don't know much about this.
A: Type "which adb" in the terminal and see the location of the adb. If no location/ path to adb is displayed, then you should add the location of the platform-tools folder from the android sdk in the system PATH variable.
export PATH=$PATH:/home/path_to_android_sdk/platform-tools
Also, to make the change permanent, you could edit the .bashrc file and add the above line at the end. Save and execute .bashrc.
A: your PATH certainly does not include ADB. it will usually be found inside android sdk paltform-tools (a search for "platform-tools" will usually do the trick).
NOTE: under UBUNUTU 12.04, adt saved android sdk in: /usr/lib/eclipse/adt-bundle-linux-x86_64/sdk/platform-tools
| |
doc_1817
|
Here we can check the service is running in localhost at 9000
But when I try socket.getservbyport(9000) It didn't returned the service Name
May I know why this happens, and is there any way where I can check whether the service is running or not with the help of socket? please explain me why Socket is not returning the correct results here Thanks In advance!
| |
doc_1818
|
In continuation with the comment, that talks about a pipeline in QA environment to execute(smoke/regression/...) on every new artifact generated by Dev pipeline in Nexus(say).
1)
For every new artifact(say product-x.y-snapshot.jar in Nexus) generated in Dev pipeline, What is the option in Jenkins that is used to trigger a QA pipeline execution? Mechanics of using Jenkins...
2)
Using Jenkins pipeline(QA env), What technology is used to deploy product-x.y-snapshot.jar in a VM and invoke QA tests(written in python)? and provide the test results.
A: 1) If you want to automate this procedure and run QA pipeline only if new tag is created then you can use GitHub/GitLab/BitBucket webhooks.
2) You can use Jenkins pipeline (declarative or more advanced scripted pipeline syntax) to run tests on your agent directly. To downloading artifacts for testing, you can use something like Repository Connector Plugin or this scripted solution.
| |
doc_1819
|
Here is the logcat
2020-02-22 13:46:43.766 9544-9544/com.myapp.test E/MainActivity: Image file creation failed
java.io.IOException: Permission denied
at java.io.UnixFileSystem.createFileExclusively0(Native Method)
at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
at java.io.File.createTempFile(File.java:2018)
at com.myapp.test.MainActivity.create_image(MainActivity.java:915)
at com.myapp.test.MainActivity.access$200(MainActivity.java:85)
at com.myapp.test.MainActivity$6.onShowFileChooser(MainActivity.java:513)
at vo.runFileChooser(PG:10)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:336)
at android.os.Looper.loop(Looper.java:197)
at android.app.ActivityThread.main(ActivityThread.java:7762)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
My AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:remove="android:maxSdkVersion" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
And code in the MainActivity.Java
private File create_image() throws IOException {
@SuppressLint("SimpleDateFormat")
String file_name = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
String new_name = "file_"+file_name+"_";
File sd_directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(new_name, ".jpg", sd_directory); // fails due to permission denied
}
A: I was using official documentation to implement taking a photo from camera:
https://developer.android.com/training/camera/photobasics
yet it doesn't work and throws an exception on createTempFile method. Strangely google hasn't updated the code.
Here's a solution I've found:
Add:
android:requestLegacyExternalStorage="true"
to AndroidManifest.xml. No need to change anything in code. Works for now, but may not in upcoming Android versions.
A: You need to change
File sd_directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
to
File sd_directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
A: You need to add a file provider
https://developer.android.com/reference/android/support/v4/content/FileProvider
And request the read/write storage permissions at runtime.
https://developer.android.com/training/permissions/requesting
A: In android 10 permission isn't directly accepted. So, you have ask from user to accept permission. There's a library which you can use for asking permission. Let me add that link
It is known as Dexter Library
You have to add a line to gradle.build
implementation 'com.karumi:dexter:6.2.2'
Following source code used for single permission at a time.
Dexter.withContext(this)
.withPermission(Manifest.permission.CAMERA)
.withListener(new PermissionListener() {
@Override public void onPermissionGranted(PermissionGrantedResponse response) {/* ... */}
@Override public void onPermissionDenied(PermissionDeniedResponse response) {/* ... */}
@Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
}).check();
There's way to asking for multiple permission in Dexter library. You can get that on that link
A: As you are using getExternalStoragePublicDirectory In android 10+, you can't write on public folder directly. One way is to use getExternalFilesDir to capture image and then use MediaStore APIs to copy file into public directory.
| |
doc_1820
|
One example is this:
> rails g mailer UserMailer
[16:34:48] (0.1ms) BEGIN
User Exists (0.6ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('') LIMIT 1
(0.1ms) ROLLBACK
(0.1ms) BEGIN
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('') LIMIT 1
(0.1ms) ROLLBACK
create app/mailers/user_mailer.rb
invoke haml
create app/views/user_mailer
invoke rspec
create spec/mailers/user_mailer_spec.rb
The unexpected output is ALWAYS some sort of SQL logging. Anyone know what would cause this?
A: The problem seems to be uniqueness validation. You have validate_uniqueness_of :email in your model and you are trying to create a new user with the same email, at least the error shows so.
| |
doc_1821
|
factory(require("jquery"), document, window, navigator);
^ReferenceError: document is not defined
Facing issue angular universal rendering server side, I have googled this and go through many posts but didn't get any helpful resource.
A: Jquery works on the browser side and browser functions is not supported on server side.
for example if you want to use jquery in angular universal you will have to make sure you are using it on browser side only.
For example you can do the following.
In your component.ts file import the following.
import { isPlatformServer } from '@angular/common';
import * as $ from 'jquery';
and then in your ngOnInit function do the following
constructor(@Inject(PLATFORM_ID) private platformId: any) {}
ngOnInit() {
if (isPlatformBrowser(this.platformId)) {
/* jQuery here */
$("#test-button").click(function () {
alert('WOOOW');
$(this).css("background","#000");
});
}
}
A: I was having same issue, searched. Found this answer on https://github.com/angular/universal-starter/issues/623
Put this code in your server.ts file
const domino = require("domino");
const fs = require("fs");
const path = require("path");
const templateA = fs
.readFileSync(path.join("dist/browser", "index.html"))
.toString();
const win = domino.createWindow(templateA);
win.Object = Object;
win.Math = Math;
global["window"] = win;
global["document"] = win.document;
global["branch"] = null;
global["object"] = win.object;
A: To avoid your errors you can create mock for document and window objects in NodeJS server implementation server.ts:
// ssr DOM
const domino = require('domino');
const fs = require('fs');
const path = require('path');
// index from browser build!
const template = fs.readFileSync(path.join(DIST_FOLDER, 'index.html')).toString();
// for mock global window by domino
const win = domino.createWindow(template);
// mock
global['window'] = win;
// not implemented property and functions
Object.defineProperty(win.document.body.style, 'transform', {
value: () => {
return {
enumerable: true,
configurable: true,
};
},
});
// mock documnet
global['document'] = win.document;
// othres mock
global['CSS'] = null;
// global['XMLHttpRequest'] = require('xmlhttprequest').XMLHttpRequest;
global['Prism'] = null;
Here you can find working example
After modifications rebuild your server sources again.
A: If you are using server-side than you must have to add check whether the platform is browser or server because keywords like Document, Window are not available in Server side support
you can use isPlatformBrowser from angular.
| |
doc_1822
|
code:
chrome.tabs.executeScript(tab.id, {code:var string1= ??? ;
chrome.runtime.sendMessage(string1);"});
How do I do this . My function contains Javascript code that returns a string or an array of strings.
Some help would be appreciated.
Update:
function(array_of_Tabs) {
var tab = array_of_Tabs[0];
//tab.url; - url of the active tab
chrome.tabs.executeScript(tab.id, {code: 'var test = document.body,text= test.textContent,bodyStart="<BODY",bodyEnd="</BODY>",regex=bodyStart+"(.*?)"+ bodyEnd,regexg = new RegExp(regex, "g"),match = regexg.exec(text);' + 'chrome.runtime.sendMessage(match);'});
});
chrome.runtime.onMessage.addListener(function(request) {
document.getElementsByTagName('html')[0].innerHTML = request;
});
This should've worked according to what you told me, But doesn't . Why.?
And yes BTW I am not parsing pure html on the page it may be anything say to for that matter.
A: chrome.tabs.executeScript has a third, optional argument that has access to the result of your injected code. E.g.
// In `background.js`:
...
const tab = ...
chrome.tabs.executeScript(
tab.id,
{code: 'const string1 = "Hello, world!"; return string1;'},
resultArr => processString1(resultArr[0]));
function processString1(str1) {
alert(`String1 = "${str1}"`);
}
If this does not cover your needs and you still want to use Message Passing:
// In `background.js`:
...
const tab = ...
chrome.tabs.executeScript(
tab.id,
{
code: 'const string1 = "Hello, world!"; ' +
'chrome.runtime.sendMessage({text: string1});',
});
chrome.runtime.onMessage.addListener(msg => {
if (msg.text !== undefined) {
alert(`String1 = "${msg.text}"`);
}
});
| |
doc_1823
|
I have a small submenu thats fixed to top, so when I click on an anchor-link I want the anchor after the submenu.
First my code, this works in most cases:
function offsetSubmenu() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - submenuHeight);
}
}
$(window).on("hashchange", function () {
offsetSubmenu();
});
window.setTimeout(function() {
offsetSubmenu();
}, 1);
You see the code is executed once when the page is loaded and everytime the hash in url change. And it works so far. The problem is when the hash don't change. For example when u click on first Hashlink, scroll around and then again klick on that link the hash does not change and so windowscroll jumps to the anchor without the offset of the submenu.
A clicklistener does not work, cause $("a").click(..) is executed before the browser jumps to the anchor.
Any idea how I can handle the offset for anchors when the hashtag does not change?
A: If the $("a").click(...) is executed before the browser jumps to the anchor, add a small delay to the offsetMenu call so it is executed after the jump. Something like:
setTimeout(offsetSubmenu, 1)
(the same way as you execute offsetSubmenu the first time)
| |
doc_1824
|
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, marker2); // I need instead of 2 to print the value of variable id
});
How can I dynamically change the number 2 to variable ID ?
Thanks for any help
A: Instead of using eval, - better change you data structures:
var markers = {
'1': function () { doStuff(); },
'2': function () { doOtherStuff(); },
}
$('a').live('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, markers[id]);
});
A: Don't use eval, use a hash:
var markers = {
"key1": function(){},
"key2": function(){},
"key3": function(){}
};
$('a').live('click',function(e){
e.preventDefault();
var id = this.id; //Use this.id instead of attr
infowindow2.open(map, markers[id]);
});
A: EVAL should always be the last option
In order use dynamic name in a function names you can windows object.
Here is an Example:
var id = '2';
function map2() {
alert('me called');
}
window["map"+id]();
Demo
Your Usage would be something like this
$('a').on('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, window['map'+id]());
});
A: I think it would be easier to write a new function with a switch. I can't recommend using eval.
A: $('a').live('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, eval('marker' + id));
});
LIVE DEMO
Notes:
*
*eval is deprecated, You should look for a better design.
*so as live... You should use on instead.
| |
doc_1825
|
private List<Employee> postData; // corresponding getter and setter
public String getJson()
{
System.out.print("Sahi hai");
System.out.print("postData =="+postData);
return ActionSupport.SUCCESS;
}
I have done struts mapping also.
A: As you are using stringify before sending, you have to declare "postData" as string in the action.
String postData; //with getters n setters
public String getJson()
{
System.out.print("postData =="+getPostData());
return ActionSupport.SUCCESS;
}
and in ajax give data as
data :{"postData":data}
| |
doc_1826
|
CNContact->phoneNumbers->(String, CNPhoneNumber->stringValue)
Presume in the code below that I fetched the contacts via:
let keys = [CNContactEmailAddressesKey,CNContactPhoneNumbersKey, CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]
let fetchRequest = CNContactFetchRequest(keysToFetch: keys)
var contacts:[CNContact] = []
try! CNContactStore().enumerateContactsWithFetchRequest(fetchRequest) { ...
I want to compare the stringValue to a known value. Here's what I have so far from a playground:
import UIKit
import Contacts
let JennysPhone = "111-867-5309"
let SomeOtherPhone = "111-111-2222"
let AndAThirdPhone = "111-222-5309"
let contact1 = CNMutableContact()
contact1.givenName = "Jenny"
let phone1 = CNPhoneNumber(stringValue: JennysPhone)
let phoneLabeled1 = CNLabeledValue(label: CNLabelPhoneNumberMobile, value: phone1)
contact1.phoneNumbers.append(phoneLabeled1)
let contact2 = CNMutableContact()
contact2.givenName = "Billy"
let phone2 = CNPhoneNumber(stringValue: SomeOtherPhone)
let phoneLabeled2 = CNLabeledValue(label: CNLabelPhoneNumberMobile, value: phone2)
contact2.phoneNumbers.append(phoneLabeled2)
let contact3 = CNMutableContact()
contact3.givenName = "Jimmy"
let phone3 = CNPhoneNumber(stringValue: SomeOtherPhone)
let phoneLabeled3 = CNLabeledValue(label: CNLabelPhoneNumberMobile, value: phone3)
contact3.phoneNumbers.append(phoneLabeled3)
let contacts = [contact1, contact2, contact3]
let matches = contacts.filter { (contact) -> Bool in
let phoneMatches = contact.phoneNumbers.filter({ (labeledValue) -> Bool in
if let v = labeledValue.value as? CNPhoneNumber
{
return v.stringValue == JennysPhone
}
return false
})
return phoneMatches.count > 0
}
if let jennysNum = matches.first?.givenName
{
print("I think I found Jenny: \(jennysNum)")
}
else
{
print("I could not find Jenny")
}
This does work, but it's not efficient. On a device I would need to run this in a background thread, and it could take a while if the person has a lot of contacts. Is there a better way to find a contact by phone number (or email address, same idea) using the new iOS Contacts framework?
A: If you are looking for a more Swift-y way to do it:
let matches = contacts.filter {
return $0.phoneNumbers
.flatMap { $0.value as? CNPhoneNumber }
.contains { $0.stringValue == JennysPhone }
}
.flatMap casts each member of phoneNumbers from type CNLabeledValue to type CNPhoneNumber, ignoring those that cannot be casted.
.contains checks if any of these phone numbers matches Jenny's number.
A: I'm guessing you're wanting a more swift-y way, but obviously anything you can do in Obj-C can also be done in swift. So, you can still use NSPredicate:
let predicate = NSPredicate(format: "ANY phoneNumbers.value.digits CONTAINS %@", "1118675309")
let contactNSArray = contacts as NSArray
let contactsWithJennysPhoneNumber = contactNSArray.filteredArrayUsingPredicate(predicate)
| |
doc_1827
|
i want to convert it to windows phone app. The only problem i am facing is that the alphabets and words to be guessed are not coming to right places... I have tried alot... but I just cant move the positions of the grid and the stackpanel from the top of the app... Please help!
here is the code.
namespace Canhangman
{
public partial class MainPage : PhoneApplicationPage
{
public int x = 0;
StackPanel sp = new StackPanel();
StackPanel sp_special = new StackPanel();
List<TextBox> text = new List<TextBox>(); // keeping all textboxes
StackPanel sp1;
Grid g, g1;
Rectangle r1;
int nooftxtbox = -1;
string[] words = new string[100] {"KARAKARTAL","BİLGİSAYAR","KİTAPLIK","FAALİYET","PANTOLON",
"KİLİSE","TELEFON","CEYLAN","KANGURU","JANDARMA","PİYADE","MAKARNA",
"KEVGİR","MALUMAT","GALERİ","ARABA","DİKELMEK","KALKMAK","OTURMAK",
"GÖZLÜKÇÜ","DOĞUŞTAN","YAZICI","TARAYICI","ŞİFONYER","FASULYE","PAZARLIK",
"KALDIRIM","İNDİRİM","SAĞANAK","ABAJUR","KARNIBAHAR","ÜNİFORMA","ÜNİVERSİTE",
"AYAKLANMA","TEBESSÜM","MÜTEAHHİT","MÜBAŞİR","MÜSTEŞAR","MÜFETTİŞ","BAKANLIK",
"CUMHURİYET","OSMANLI","PAŞAZADE","KUMBURGAZ","PANSİYON","TANSİYON","İLKOKUL",
"KONSERVATUAR","KONGRE","KUMANDA","KEMER","ÇAKMAK","ÇAYDANLIK","CETVEL","BİSTÜYER",
"KELEBEK","KAPLUMBAĞA","KORTEJ","TUHAF","BORNOZ","KAPŞON","OROTORYO","ORDİNARYÜS",
"KERPİÇ","KALPAZAN","TASARRUF","MÜNECCİM","İLMİHAL","MUHBİR","LİZOZOM","RİBOZOM",
"KLASÖR","KILAVUZ","MODÜLER","TEHLİKE","STATİK","MEKANİK","POTANSİYEL","KULAKLIK",
"ARDIŞIK","ÇERÇEVE","MONİTÖR","SANDALYE","MERDİVEN","OTOBÜS","MİNİBÜS","KAREOKE",
"KARTONPİYER","ÇEKMECE","ALIŞVERİŞ","KALDIRAÇ","KARINCA","KARBONAT","GERGEDAN",
"İSTİRİDYE","TENEFFÜS","ORİGAMİ","BEZİK","EKONOMİ","GRAFİK"};
public string s;
public MainPage()
{
string[] alph = new string[29] {"A","B","C","Ç","D","E","F","G","Ğ","H","I","İ","J","K","L",
"M","N","O","Ö","P","R","S","Ş","T","U","Ü","V","Y","Z"};
// Required to initialize variables
InitializeComponent();
SolidColorBrush sb = new SolidColorBrush();
sb.Color = Colors.Blue;
sp.Height = 100;
sp_special.Height = 100;
sp.Background = sb;
sp_special.Background = sb;
sp.Orientation = System.Windows.Controls.Orientation.Horizontal;
sp_special.Orientation = System.Windows.Controls.Orientation.Horizontal;
Canvas.SetLeft(sp, 0);
Canvas.SetLeft(sp_special,0);
Canvas.SetTop(sp,0);
Canvas.SetTop(sp_special,200);
sp1 = new StackPanel();
sp1.Background = sb;
sp1.Orientation = System.Windows.Controls.Orientation.Horizontal;
Canvas.SetLeft(sp1, 20);
Canvas.SetTop(sp1, 100);
g = new Grid();
Canvas.SetLeft(g, 200);
Canvas.SetTop(g, 320);
g1 = new Grid();
g.Height = 20;
g1.Height= 20;
g.Width = 300;
g1.Width =300;
Canvas.SetLeft(g1, 200);
Canvas.SetTop(g1, 300);
ContentPanel.Children.Add(sp);
ContentPanel.Children.Add(sp_special);
ContentPanel.Children.Add(g);
ContentPanel.Children.Add(g1);
for (int i = 0; i < 29; i++)
{
Button b = new Button();
b.Name = "b" + i;
b.Content = alph[i];
b.Width = 25;
b.Height = 5;
b.FontWeight = FontWeights.Bold;
if(i<20)
{
sp.Children.Add(b);
b.Click += new System.Windows.RoutedEventHandler(b_Click);
}
else
{
sp_special.Children.Add(b);
b.Click += new System.Windows.RoutedEventHandler(b_Click);
}
}
Random r = new Random();
s = words[r.Next(0, words.Length)];
for (int j = 0; j < s.Length; j++)
{
r1 = new Rectangle();
r1.Width = 15;
r1.Height = 5;
SolidColorBrush sb1 = new SolidColorBrush();
sb1.Color = Colors.Black;
r1.Fill = sb1;
TextBox t = new TextBox();
t.Name = "t" + j;
t.Text = s[j].ToString().ToUpper();
t.Visibility = Visibility.Collapsed;
t.Width = 25;
t.Height = 5;
t.IsEnabled = false;
text.Add(t); // adding textBox to list
g.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength((double)30) });
g1.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength((double)30) });
g1.ShowGridLines = true;
Grid.SetColumn(t, j);
Grid.SetColumn(r1, j);
if (t.Text != " ")
{
g.Children.Add(r1);
g1.Children.Add(t);
}
nooftxtbox++;
}
}
private void b_Click(object sender, System.Windows.RoutedEventArgs e)
{
bool iscomplete = true;
bool flag = false;
string bstr;
TextBox txtName;
bstr = ((Button)sender).Content.ToString();
if (x != 6)
{
for (int j = 0; j <= nooftxtbox; j++)
{
txtName = g1.Children[j] as TextBox;
if (txtName.Text == bstr)
{
txtName.SetValue(Grid.ColumnProperty, j);
txtName.Visibility = Visibility.Visible;
txtName.IsEnabled = false;
((Button)sender).Visibility = Visibility.Collapsed;
flag = true;
}
else
{
((Button)sender).Visibility = Visibility.Collapsed;
}
}
if (!flag)
{
x = x + 1;
}
if (x == 1)
{
loop1.Visibility = Visibility.Collapsed;
head.Visibility = Visibility.Visible;
}
if (x == 2)
{
loop1.Visibility = Visibility.Collapsed;
head.Visibility = Visibility.Visible;
body1.Visibility = Visibility.Visible;
}
if (x == 3)
{
loop1.Visibility = Visibility.Collapsed;
head.Visibility = Visibility.Visible;
body1.Visibility = Visibility.Visible;
lefthand.Visibility = Visibility.Visible;
}
if (x == 4)
{
loop1.Visibility = Visibility.Collapsed;
head.Visibility = Visibility.Visible;
body1.Visibility = Visibility.Visible;
lefthand.Visibility = Visibility.Visible;
righthand.Visibility = Visibility.Visible;
}
if (x == 5)
{
loop1.Visibility = Visibility.Collapsed;
head.Visibility = Visibility.Visible;
body1.Visibility = Visibility.Visible;
lefthand.Visibility = Visibility.Visible;
righthand.Visibility = Visibility.Visible;
leftleg.Visibility = Visibility.Visible;
}
if (x == 6)
{
loop1.Visibility = Visibility.Collapsed;
head.Visibility = Visibility.Visible;
body1.Visibility = Visibility.Visible;
lefthand.Visibility = Visibility.Visible;
righthand.Visibility = Visibility.Visible;
leftleg.Visibility = Visibility.Visible;
rightleg.Visibility = Visibility.Visible;
deadtxt.Visibility = Visibility.Visible;
trybutton.Visibility = Visibility.Visible;
for (int i = 0; i < text.Count; i++)// checking whether user has completed the guess or not
{
text[i].Visibility = Visibility.Visible;
}
iscomplete = false;
sp.Visibility = Visibility.Collapsed;
sp_special.Visibility = Visibility.Collapsed;
}
if(iscomplete)
{
bool complete = true;
for (int i = 0; i < text.Count; i++)// checking whether user has completed the guess or not
{
if (text[i].Visibility == Visibility.Collapsed)
{
complete = false;
}
}
if (complete)
{
// safetxt and hiding the letter boxes
safetxt.Visibility = Visibility.Visible;
trybutton.Visibility = Visibility.Visible;
sp.Visibility = Visibility.Collapsed;
sp_special.Visibility = Visibility.Collapsed;
loop1.Visibility = Visibility.Visible;
//hiding the hanged man
head.Visibility = Visibility.Collapsed;
body1.Visibility = Visibility.Collapsed;
leftleg.Visibility = Visibility.Collapsed;
rightleg.Visibility = Visibility.Collapsed;
lefthand.Visibility = Visibility.Collapsed;
righthand.Visibility = Visibility.Collapsed;
//showing man walking away
head_Copy.Visibility = Visibility.Visible;
body1_Copy.Visibility = Visibility.Visible;
leftleg_Copy.Visibility = Visibility.Visible;
rightleg_Copy.Visibility = Visibility.Visible;
lefthand_Copy.Visibility = Visibility.Visible;
righthand_Copy.Visibility = Visibility.Visible;
}
}
}
else
{
deadtxt.Visibility = Visibility.Visible;
loop1.Visibility = Visibility.Visible;
head.Visibility = Visibility.Visible;
body1.Visibility = Visibility.Visible;
leftleg.Visibility = Visibility.Visible;
rightleg.Visibility = Visibility.Visible;
lefthand.Visibility = Visibility.Visible;
righthand.Visibility = Visibility.Visible;
trybutton.Visibility = Visibility.Visible;
}
}
private void trybutton_Click(object sender, RoutedEventArgs e)
{
this.ContentPanel.Children.Add(new MainPage());
}
}
}
this is the link of originial app that i want to change
the problem is at the dashes and the letters
http://www.sarayyayin.com/silverlighthangman/TestPage.html
I cant post images otherwise i would have uploaded the screenshot of my app :-(
A: You can't just convert a Silverlight 4 application into a Windows Phone 7 application.
They both use different version of Silverlight and are on completely different platforms using different set of controls.
Try building it step by step and reuse any code that you can out of existing application.
| |
doc_1828
|
The URL contains a referral ID e.g twitter, facebook or an email e.g [email protected]. This is stored as $ref
I have the following switch statement:
switch ($ref) {
case "twitter":
echo "twitter";
break;
case "facebook":
echo "facbeook";
break;
case "blog":
echo "blog";
break;
case strstr($ref,'@'):
echo "email = ".$ref;
default:
echo "no referral found";
break;
}
However if URL is passed with nothing (e.g just www.mything.co.uk) then I wish to go to the default case.
Instead, I get the following output:
email = no referral found
Why does the default also include the text I set for case strstr($ref,'@') ?
A: OP question: "Why does the default also include the text I set for case strstr($ref,'@') ?"
Answer: there's no break; following the output, and thus falls through to the default case.
UPDATE: Addressing the issue of putting a statement within a case, I'm also including an easy work-around:
switch ($ref) {
case "twitter":
echo "twitter";
break;
case "facebook":
echo "facbeook";
break;
case "blog":
echo "blog";
break;
default:
if (strstr($ref,'@')) {
echo "email = ".$ref;
} else {
echo "no referral found";
}
break;
}
A: When $ref is an empty String, then strstr($ref,'@'); returns an empty string too, this is why the case strstr($ref,'@'): matches the switch input $ref.
The problem is, you can't even use a email validation function like
filter_var($ref, FILTER_VALIDATE_EMAIL)
That would return false in case of an empty input instead of an empty string, but switch does loose comparison, meaning that an "" == false would return true:
http://php.net/manual/en/types.comparisons.php#types.comparisions-loose
Thus the only solution I see is to use an if statement using the === operator:
if($ref == 'twitter') {
echo "twitter";
} else if($ref == 'facebook') {
echo "facbeook";
} else if($ref == 'blog') {
echo "blog";
} else if($ref === filter_var($ref, FILTER_VALIDATE_EMAIL)) {
echo "email = ".$ref;
} else {
echo "no referral found";
}
A: That's because your test is performed like if ($ref == strstr($ref, '@')), where strstr returns false which equals an empty string. You cannot really use dynamic comparisons in switch statements. Use if..else if you need that. Alternatively, abuse switch a bit:
switch (true) {
case $ref == 'twitter':
..
case strstr($ref, '@'):
..
}
A: That will work:
case (strstr($ref, '@') ? true : false):
But it's not really good of practice.
| |
doc_1829
|
What is the standard interface in the .NET Core to manipulate files? I want to delete or write a file etc.
A: It's worth differentiating between ASP.NET Core and .NET Core. You linked to ASP.NET Core documentation for file providers, which are used to read files which might be virtual files within an assembly etc.
For plain file system access, use System.IO.File as you do in desktop .NET. That's been part of .NET Core since version 1. It allows files to be created, appended, read, deleted etc.
| |
doc_1830
|
Currently I have to set up generated commands like this:
public static MySqlCommand User(MySqlConnection MySQL, User u)
{
var cmdVars = new List<string>();
const string cmd = "SELECT * FROM `schema`.`table` WHERE 1=1 AND ";
if (u.ID != null) cmdVars.Add("`ID` LIKE @0");
if (u.Username != null) cmdVars.Add("`Username` LIKE @1");
if (u.First != null) cmdVars.Add("`FirstName` LIKE @2");
if (u.Last != null) cmdVars.Add("`LastName` LIKE @3");
if (u.Phone != null) cmdVars.Add("`Phone` LIKE @4");
if (u.Extension != null) cmdVars.Add("`Extension` LIKE @5");
if (u.Email != null) cmdVars.Add("`Email` LIKE @6");
var MySqlCmd = new MySqlCommand(cmd + string.Join(" AND ", cmdVars), MySQL);
if (u.ID != null) MySqlCmd.Parameters.AddWithValue("@0", u.ID);
if (u.Username != null) MySqlCmd.Parameters.AddWithValue("@1", u.Username);
if (u.First != null) MySqlCmd.Parameters.AddWithValue("@2", u.First);
if (u.Last != null) MySqlCmd.Parameters.AddWithValue("@3", u.Last);
if (u.Phone != null) MySqlCmd.Parameters.AddWithValue("@4", u.Phone);
if (u.Extension != null) MySqlCmd.Parameters.AddWithValue("@5", u.Extension);
if (u.Email != null) MySqlCmd.Parameters.AddWithValue("@6", u.Email);
return MySqlCmd;
}
Which, although works fine, is gross to look at as more parameters are added and requires a user to create a new User object just to search by one value.
I considered switching to the method shown in this question, but in use with MySQLConnector it becomes overly complicated to manage the values and doesn't really do anything for improved readability.
A: How about using a query like this
... WHERE (@0 is null or `ID` LIKE @0)
AND (@1 is null or `Username` LIKE @1)
AND (@2 is null or `FirstName` LIKE @2) ...
Then you can add all your parameters no matter if NULL or not.
Before executing you can run this
private void FillNullValuesWithDbNull(SqlParameterCollection parameters)
{
foreach (IDataParameter param in parameters)
{
if (param.Value == null) param.Value = DBNull.Value;
}
}
A: My suggestion would be instead of having a User instance passed to the function, create a new class called something like UserSearchCriteria; that class could have a much simpler design (0 parameter constructor, all properties with simple setters, etc...).
It wouldn't do much to shorten or "clean up" the function code, but would make using the function much simpler.
Actually, as far as the function goes, you can probably do something like this...
public static MySqlCommand User(MySqlConnection MySQL, UserSearchCriteria u)
{
var cmdVars = new List<string>();
const string cmd = "SELECT * FROM `schema`.`table` WHERE 1=1 AND ";
var MySqlCmd = new MySqlCommand("", MySQL);
if (u.ID != null)
{
cmdVars.Add("`ID` LIKE @0");
MySqlCmd.Parameters.AddWithValue("@0", u.ID);
}
if (u.Username != null)
{
cmdVars.Add("`Username` LIKE @1");
MySqlCmd.Parameters.AddWithValue("@1", u.Username);
}
// and the rest of the relevant properties
MySqlCmd.CommandText = cmd + string.Join(" AND ", cmdVars);
return MySqlCmd;
}
public void somefunction()
{
var myCmd = User(someconnections, new UserSearchCriteria() {FirstName = "Joe"});
}
| |
doc_1831
|
I am sending request through Ajax call in JavaScript that goes to server generates excel which needs to be downloaded.
The view should generate http response that sends excel file to html that could be downloaded to a file at client
A: It's not as complicated as you may think. In fact, as I understand, you have a Django model and you need to export some instances' data in an .xlsx file for example.
I'd suggest the following simple solution:
import openpyxl
from openpyxl.utils import get_column_letter
from django.http.response import HttpResponse
def method(request, **kwargs):
queryset = ModelName.objects.filter() # adjust accordingly
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=this-is-your-filename.xlsx'
wb = openpyxl.Workbook()
ws = wb.get_active_sheet()
ws.title = "Your Title"
row_num = 0
columns = [
("ID", 5),
(u'Name', 20),
]
for col_num in range(len(columns)):
c = ws.cell(row=row_num + 1, column=col_num + 1)
c.value = columns[col_num][0]
ws.column_dimensions[get_column_letter(col_num + 1)].width = columns[col_num][1]
for obj in queryset:
row_num += 1
row = [
obj.pk,
obj.name,
]
for col_num in range(len(row)):
c = ws.cell(row=row_num + 1, column=col_num + 1)
c.value = row[col_num]
wb.save(response)
return response
Please keep in mind that you need to install with pip install openpyxl the openpyxl lib first.
A: I had to complete this exact task and ended up using the following method. Instead of using an AJAX call, I just do
window.location.pathname = "/relative/path/to/url/"
within Javascript click handler for the button.
Within Django, I am using the following code (I am using XlsxWriter but you could use whatever you wish for creating XLSX file):
excel_file = BytesIO()
workbook = xlsxwriter.Workbook(excel_file)
# Code to populate the workbook
# Here comes the magic
workbook.close()
excel_file.seek(0)
response = HttpResponse(excel_file.read(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=somename.xlsx'
return response
When called this way, the created Excel file is downloaded and the user remains on the calling page, which is the exact behavior I wanted.
| |
doc_1832
|
A: Well, it would be correct if you added guards to each of the outgoing control flows. This way the token emitted by Main menu would take an arbitrary route.
A decision is not limited to two outputs. However, if your tool only permits two you can make a cascade:
| |
doc_1833
|
A: close the current terminal window and reopen and try again.
A: I think you have not defined the path of how-to-open in Environment Variables on the System Properties.
Add ;%USERPROFILE%\AppData\Roaming\npm (path of your how-to-open installed directory)
To the end of your Path variable on the "User variable" section of the Environment Variables on the System Properties.
Then reopen cmd prompt and type how-to-openagain.It should work now.Hope it helps.
| |
doc_1834
|
A: Take a look at the Android documentation on Building Custom Components. Basically you should be able to do this by overriding the onDraw method and adding your own functions to set/get the state of the progress bar. Read through that article and you should have a good idea on how to get started making your own progress bar component.
Or just override the onDraw in your own ProgressBar derived class
A: Check out this link and you will find your accurate destination. :)
| |
doc_1835
|
My questions are :
*
*As far as I understand, the classpath is shared across the jvm -I heard about classpath levels but I don't understand much and I didn't find a reference to it-, so does this mean that jar files included in one project is visible from other projects?
*also does this mean that it is possible that we can have conflicts between 2 versions of the same jar deployed in 2 different applications if a third application is accessing this library while I forgot to include this jar in its lib folder?
I have been deploying web apps for years but I haven't come across any of these issues .... so I doubt I misunderstood something
A: As Gimby commented, the libraries are put on the webapp's classpath, which is handled by the webapp's ClassLoader. Each webapp having their own ClassLoader, they can't see or mix up each other's libraries.
Case two. The container does have its own classpath (and ClassLoader(s)), which means that if you have the same library loaded by the container and the webapp, you can get extremely confusing error messages telling you that "foo.bar.SomeClass cannot be cast into foo.bar.SomeClass".
| |
doc_1836
|
Here's what I have:
(BroadcastReceiver Class)
public class MusicBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive( Context context , Intent arg1 )
{
AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
manager.setMode(AudioManager.MODE_NORMAL);
System.out.println("Playing: " + manager.isMusicActive());
if (manager.isMusicActive())
{
//context.startService(new Intent(context, TimerService.class));
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, TimerService.class);
PendingIntent pendIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long timeToWake = System.currentTimeMillis() + ( 30 * 1000);
mgr.set(AlarmManager.RTC_WAKEUP, timeToWake, pendIntent);
System.out.println("Started service");
}
}
}
When music starts playing, the receiver gets called, perfect behavior. But when I call "manager.isMusicActive()", this doesn't return the correct value. In my main activity I created a button which when pressed would check if music is active, using the same code. And there "isMusicActive()" works perfectly (Here's the code for that)
btn_CheckMusic.setOnClickListener(new OnClickListener()
{
public void onClick( View v )
{
AudioManager mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
if (mAudioManager.isMusicActive())
{
Intent i = new Intent(SERVICECMD);
i.putExtra(CMDNAME, CMDSTOP);
getActivity().sendBroadcast(i);
Toast.makeText(getActivity(), "Music Stopped", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(), "Music isn't playing", Toast.LENGTH_SHORT).show();
}
}
});
so I have no idea what is causing it to mess up in the Receiver class
| |
doc_1837
|
Can you give me a way how can i export the products having no images ?
I have tried to export the product having image value as 'no_selection' but, it gives me only 2-3 items. Then i tried to cross verify those entity_id which have no images into 'catalog_product_entity_varchar' table. And i surprised by not finding when some entity_id presents in 'catalog_product_entity' table but not in 'catalog_product_entity_varchar' table.
Can anyone give me a way to solve this problem.
Any help will really be appreciated.
Regards
A: Does this query help?
SELECT t0.sku
FROM catalog_product_entity AS t0
WHERE NOT EXISTS(
SELECT NULL
FROM catalog_product_entity_media_gallery AS t1
WHERE (t1.entity_id = t0.entity_id)
)
A: If you only need SKUs, one method I have used in the past is via a Magento shell script. This example will output only SKU's (one per line) for only those products which have no value for the image attribute.
<?php
error_reporting(E_ALL);
error_reporting(-1);
require_once 'app/Mage.php';
Mage::app();
$collection = Mage::getModel('catalog/product')->getCollection();
foreach($collection as $product){
$productId = $product->getId();
$prod = Mage::getModel('catalog/product')->load($productId);
$hasImage = Mage::helper('catalog/image')->init($prod, 'image');
if (!$hasImage){
echo $prod->getSku() . "\n";
}
}
?>
I put this into "list-noimages.php, and into my Magento root folder. Only use this in development environment, or very limited on production. Run it via shell as so:
php list-noimages.php
For that many products you can output to a file:
php list-noimages.php >> skus.txt
Otherwise visit the file via your web browser and save the output.
| |
doc_1838
|
import pandas as pd
import altair as alt
budget = pd.read_csv("https://github.com/chris1610/pbpython/raw/master/data/mn-budget-detail-2014.csv")
budget_top_10 = budget.sort_values(by='amount',ascending=False)[:10]
alt.Chart(budget_top_10).mark_bar().encode(
x='detail',
y='amount').configure_axis(
grid=False
)
The documentation points to a .configure_axisTop() command but adding it to my code and changing its arguments seems to make no difference.
Source of the data.
A: It's hard to tell, but that is not part of the grid or axis, but part of the view. You can hide it using configure_view(strokeOpacity=0):
import pandas as pd
import altair as alt
budget = pd.read_csv("https://github.com/chris1610/pbpython/raw/master/data/mn-budget-detail-2014.csv")
budget_top_10 = budget.sort_values(by='amount',ascending=False)[:10]
alt.Chart(budget_top_10).mark_bar().encode(
x='detail',
y='amount'
).configure_view(
strokeOpacity=0
)
| |
doc_1839
|
I have done as Agarwal suggested, and now have this error:
04-21 11:42:01.807: E/AndroidRuntime(1456): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
I am using this code to dynamically set the width of 15 Buttons. And, you guessed it, it doesn't work. The error happens in the for loop, but I'm not sure why.
Button[] buttons = new Button[16];
buttons[0] = (Button)findViewById(R.id.root2);
buttons[1] = (Button)findViewById(R.id.root3);
/* blah blah blah */
buttons[13] = (Button)findViewById(R.id.root15);
buttons[14] = (Button)findViewById(R.id.root16);
LayoutParams lp = new LayoutParams(widthOfButtons,LayoutParams.WRAP_CONTENT);
for(int x = 0; x < 16; x ++){
buttons[x].setLayoutParams(lp);
}
Thanks for any help. (And if anyone can think of a better way to fill the buttons[] variable, that would be very much appreciated.)
A: for(int x = 0; x < 16; x ++){
buttons[x].setLayoutParams(lp);
}
the above loop repaeat for 16 times and you had instilized only 15 buttons either add a button or change x < 15.
if you change x< 15 then also change the below
Button[] buttons = new Button[15];
A: I have fixed it using this:
LayoutParams lp = new LinearLayout.LayoutParams(widthOfButtons,LayoutParams.WRAP_CONTENT);
for(int x = 0; x < 15; x ++){
buttons[x].setLayoutParams(lp);
}
Getting LayoutParams from LinearLayout.
| |
doc_1840
|
Is there any way to show the page extensions like .html or .php?
Please help I am new in YII.
A: Use urlSuffix parameter
array(
......
'components'=>array(
......
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'pattern1'=>'route1',
'pattern2'=>'route2',
'pattern3'=>'route3',
),
'urlSuffix' => '.html'
),
),
);
| |
doc_1841
|
I want to know if it is possible to store the key locally on the ipad and refer to it locally somehow in the index file. Is it possible to have a local server running on the ipad and provide a localhost url in index files? If so, would the server be bundled with the app build?
Thanks,
Hetal
A: cocoahttpserver is a HTTP Server on top of ASIHTTPRequest
I haven't done streaming with it, but the homepage says
Asynchronous networking using standard Cocoa sockets/streams
| |
doc_1842
|
(arrows represent direction of stream flow)
Within this stream network are braids which are important features I need to retain. I am categorizing braid features into "simple" (two edges that share two nodes) and "complex" (more than two edges, with more than two nodes).
Simple braid example
Complex braid example
Normally, I would just use the NetworkX built-in function read_shp to import the shapefile as a DiGraph. As is evident in the examples, the "simple" braid will be considered a parallel edge in a NetworkX DiGraph, because those two edges (which share the same to and from nodes) would be collapsed into a single edge. In order to preserve these multiple edges, we wrote a function that imports a shapefile as a MultiDiGraph. Simple braids (i.e. parallel edges) are preserved by using unique keys in the edge objects (this is embedded in a class):
def _shp_to_nx(self, in_network_lyr, simplify=True, geom_attrs=True):
"""
This is a re-purposed version of read_shp from the NetworkX library.
:param shapelayer:
:param simplify:
:param geom_attrs:
:return:
"""
self.G = nx.MultiDiGraph()
for f in in_network_lyr.getFeatures():
flddata = f.attributes()
fields = [str(fi.name()) for fi in f.fields()]
geo = f.geometry()
# We don't care about M or Z
geo.geometry().dropMValue()
geo.geometry().dropZValue()
attributes = dict(zip(fields, flddata))
# Add a new _FID_ field
fid = int(f.id())
attributes[self.id_field] = fid
attributes['_calc_len_'] = geo.length()
# Note: Using layer level geometry type
if geo.wkbType() in (QgsWKBTypes.LineString, QgsWKBTypes.MultiLineString):
for edge in self.edges_from_line(geo, attributes, simplify, geom_attrs):
e1, e2, attr = edge
self.features[fid] = attr
self.G.add_edge(tuple(e1), tuple(e2), key=attr[self.id_field], attr_dict=attr)
self.cols = self.features[self.features.keys()[0]].keys()
else:
raise ImportError("GeometryType {} not supported. For now we only support LineString types.".
format(QgsWKBTypes.displayString(int(geo.wkbType()))))
I have already written a function to find the "simple" braid features (I just iterate through the MultiDiGraphs nodes, and find edges with more than one key). But I also need to find the "complex" braids. Normally, in a Graph, I could use the cycle_basis to find all of the "complex" braids (i.e. cycles), however, the cycle_basis method only works on un-directed Graphs, not directional graphs. But I'd rather not convert my MultiDiGraph into an un-directed Graph, as there can be unexpected results associated with that conversion (not to mention losing my edge key values).
How could I go about finding cycles which are made up of more than one edge, in a relatively time-efficient way? The stream networks I'm really working with can be quite large and complex, representing large watersheds.
Thanks!
A: So I came up with a solution, for finding both "simple" and "complex" braids.
def get_complex_braids(self, G, attrb_field, attrb_name):
"""
Create graph with the braid edges attributed
:param attrb_field: name of the attribute field
:return braid_G: graph with new attribute
"""
if nx.is_directed(G):
UG = nx.Graph(G)
braid_G = nx.MultiDiGraph()
for edge in G.edges(data=True, keys=True):
is_edge = self.get_edge_in_cycle(edge, UG)
if is_edge == True:
braid_G.add_edge(*edge)
self.update_attribute(braid_G, attrb_field, attrb_name)
return braid_G
else:
print "ERROR: Graph is not directed."
braid_complex_G = nx.null_graph()
return braid_complex_G
def get_simple_braids(self, G, attrb_field, attrb_name):
"""
Create graph with the simple braid edges attributed
:param attrb_field: name of the attribute field
:return braid_G: graph with new attribute
"""
braid_simple_G = nx.MultiDiGraph()
parallel_edges = []
for e in G.edges_iter():
keys = G.get_edge_data(*e).keys()
if keys not in parallel_edges:
if len(keys) == 2:
for k in keys:
data = G.get_edge_data(*e, key=k)
braid_simple_G.add_edge(e[0], e[1], key=k, attr_dict=data)
parallel_edges.append(keys)
self.update_attribute(braid_simple_G, attrb_field, attrb_name)
return braid_simple_G
A: This is not a definite answer, but longer than maximum allowed characters for a comment, so I post it here anyway.
To find simple braids, you can use built-in methods G.selfloop_edges and G.nodes_with_selfloops.
I haven't heard about cycle_basis for directed graphs, can you provide a reference (e.g. scientific work)? NetworkX has simple_cycles(G) which works on directed Graphs, but it is also not useful in this case, because water does not visit any node twice (or?).
I am afraid that the only way is to precisely describe the topology and then search the graph to find matching occurrences. let me clarify my point with an example. the following function should be able to identify instances of complex braids similar to your example:
def Complex_braid(G):
res = []
# find all nodes with out_degree greater than one:
candidates = [n for n in G.nodes() if len(G.successors(n)) > 1]
# find successors:
for n in candidates:
succ = G.successors(n)
for s in succ:
if len(list(nx.all_simple_paths(G,n,s))) > 1:
all_nodes = sorted(list(nx.all_simple_paths(G,n,s)), key=len)[-1]
res.append(all_nodes)
return res
G = nx.MultiDiGraph()
G.add_edges_from([(0,1), (1,2), (2,3), (4,5), (1,5), (5,2)])
Complex_braid(G)
# out: [[1, 5, 2]]
but the problem actually is that complex braids can be in different topological configurations and therefore it doesn't really make sense to define all possible topological configurations, unless you can describe them with one (or few) patterns or you can find a condition that signify the presence of complex braid.
| |
doc_1843
|
CODE FOR PARENT:
function setText1(txt) {
document.getElementById('TextBox4').value = txt;
}
CODE FOR POPUP:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
//TextBox2.Text = row.Cells[1].Text;
ScriptManager.RegisterStartupScript(this,GetType(), "settxt", "setText1('"+ row.Cells[1].Text + "');", true);
}
The values are not getting transferred .
Help please
A: Copy the modified line to your code
ScriptManager.RegisterStartupScript(this,GetType(), "settxt", "window.opener.setText1('"+ row.Cells[1].Text + "');", true);
A: you can call parent page by using javascript by using
window.opener.document.getElementById("TextBox4").value = txt;
or you can call parent page function by uisng same way
window.opener.setText();
setText() function written on parent page not in popup page.
A: Otherwise after the selected index changed set some property in the server side
in the cs
protected string SelectedValue{
get {
return "whatever";
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
//TextBox2.Text = row.Cells[1].Text;
SelectedValue = row.Cells[1].Text
}
in the js
$(document).ready(function(){
var selectedValue= '<%=SelectedValue%>';
window.opener.document.getElementById("TextBox4").value = selectedValue;
});
there could be syntactical mistakes. Hope this helps.
| |
doc_1844
|
<div class="panel panel-default" style="margin: 8px;margin-top: -10px;">
<div class="panel-heading">
<h5>Legislators By State</h5>
<div class="search" style="float: right;margin-top: -29px;">
<form class="form-inline">
<div class="form-group">
<select ng-model="state_select" ng-options="f.name for f in state_select | orderBy:'name'">
<option value="">ALL STATES</option>
</select>
</div>
</form>
</div>
</div>
1)I want the h5 tag to be displayed on the left and the select box on the right on both mobile and laptop displays. Currently it's working for laptop but not for mobiles.
2)In laptop displays the select should behave normally i.e. like a drop down to select items from. While in mobile I want that when a user clicks the options to be displayed like now a days we get the options scroll-able at the bottom of the screen. So that user can scroll through all the options and select one value.
I am new at responsive design thing so just trying to learn.
A: Use, Bootstrap's Column classes.. here col-xs-6 .... "xs" used for mobile devices and "6" is how many columns we want for that div from total 12 column grid.
<div class="panel panel-default" style="margin: 8px;margin-top: -10px;">
<div class="panel-heading">
<div class="row">
<div class="col-xs-6">
<h5>Legislators By State</h5>
</div>
<div class="col-xs-6">
<div class="search">
<form class="form-inline">
<div class="form-group">
<select class="form-control" ng-model="state_select" ng-options="f.name for f in state_select | orderBy:'name'">
<option value="">ALL STATES</option>
</select>
</div>
</form>
</div>
</div>
</div>
</div>
| |
doc_1845
|
array([[1, 0, 1, 1, 1, 0, 1, 1],
[1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 0, 0, 1, 1, 1],
[1, 0, 1, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 1, 0, 1, 1],
[0, 1, 0, 1, 1, 1, 0, 0]])
First column is the sign of a number.
Example:
1, 0, 1, 1, 1, 0, 1, 1 -> 1 0111011 -> -59
When I used int(str, base=2) as a result I received value 187, and the value should be -59.
>>> int(''.join(map(str, array[0])), 2)
>>> 187
How can I convert the string into the signed integer?
A: Pyhton doesn't know that the first bit is supposed to represent the sign (compare with bin(-59)), so you have to handle that yourself, for example, if A contains the array:
num = int(''.join(map(str, A[0,1:])), 2)
if A[0,0]:
num *= -1
Here's a more Numpy-ish way to do it, for the whole array at once:
num = np.packbits(A).astype(np.int8)
num[num<0] = -128 - num[num<0]
Finally, a code-golf version:
(A[:,:0:-1]<<range(7)).sum(1)*(1-2*A[:,0])
A: You could split each row a sign and value variable. Then if sign is negative multiply the value by -1.
row = array[0]
sign, value = row[0], row[1:]
int(''.join(map(str, value)), 2) if sign == 0 else int(''.join(map(str, value)), 2) * -1
A: First of all, it looks like NumPy array rather than NumPy matrix.
There are a couple options I can think of. Pretty straight forward way will look like that:
def rowToSignedDec(arr, row):
res = int(''.join(str(x) for x in arr[row][1:].tolist()),2)
if arr[row][0] == 1:
return -res
else:
return res
print rowToSignedDec(arr, 0)
-59
That one is clearly not the most efficient one and neither the shortest one-liner:
int(''.join(str(x) for x in arr[0][1:].tolist()),2) - 2*int(arr[0][0])*int(''.join(str(x) for x in arr[0][1:].tolist()),2)
Where arr is the above-mentioned array.
| |
doc_1846
|
Let's say I have a (very simplified) data model of two entities:
class User {
@Index Long userId;
String name;
}
class Message {
@Index Long messageId;
String message;
private Ref<User> recipient;
}
At first glance, it makes no sense to put these into the same "table" as they are completely different.
But let's look at what happens when I want to search across all entities. Let's say I want to find and return users and messages, which satisfy some search criteria. In traditional database design I would either do two separate search requests, or else create a separate index "table" during writes where I repeat fields redundantly so that I can later retrieve items in a single search request.
Now let's look at the following design. Assume I would use a single entity, which stores everything. The datastore would then look like this:
Type | userId | messageId | Name | Message
USER | 123456 | empty | Jeff | empty
MESSAGE | empty | 789012 | Mark | This is text.
See where I want to go? I could now search for a Name and would find all Users AND Messages in a single request. I would even be able to add an index field, something like
@Index List index;
to the "common" entity and would not need to write data twice.
Given the behavior of the datastore that it never returns a record when searching for an indexed field which is empty, and combining this with partial indexes, I could also get the User OR Message by querying fields unique to a given Type.
The cost for storing long (non-normalized) records is not higher than storing individual records, as long as many fields are empty.
I see further advantages:
*
*I could use the same "table" for auditing as well, as every record
stored would form a "history" entry (as long as I don't allow
updates, in which case I would need to handle this manually).
*I can easily add new Types without extending the db schema.
*When search results are returned over REST, I can return them in a single List, and the client looks at the Type.
There might be disadvantages as well, for example with caching, but maybe not. I can't see this at this point.
Anybody there, who has tried going down this route or who can see serious drawbacks to this approach?
A: This is actually how the google datastore works under the covers. All of your entities (and everyone else's entities) are stored in a single BigTable that looks roughly like this:
{yourappid}/{key}/{serialized blob of your entity data}
Indexes are stored in three BigTables shared across all applications. I try to explain this in a fair amount of detail in my answer to this question: efficient searching using appengine datastore ancestor paths
So to rephrase your question, is it better to have Google maintain the Kind or to maintain it yourself in your own property?
The short answer is that having Google maintain the Kind makes it harder to query across all Kinds but makes it easier to query within one Kind. Maintaining the pseudo-kind yourself makes it easier to query across all Kinds but makes it harder to query within one Kind.
When Google maintains the Kind as per normal use, you already understand the limitation - there is no way to filter on a property across all different kinds. On the other hand, using a single Kind with your own descriminator means you must add an extra filter() clause every time you query:
ofy().load().type(Anything.class).filter("discriminator", "User").filter("name >", "j")
Sometimes these multiple-filter queries can be satisfied with zigzag merges, but some can't. And even the ones that can be satisfied with zigzag aren't as efficient. In fact, this tickles the specific degenerative case of zigzags - low-cardinality properties like the discriminator.
Your best bet is to pick and choose your shared Kinds carefully. Objectify makes this easy for you with polymorphism: https://code.google.com/p/objectify-appengine/wiki/Entities#Polymorphism
A polymorphic type hierarchy shares a single Kind (the kind of the base @Entity); Objectify manages the discriminator property for you and ensures queries like ofy().load().type(Subclass.class) are converted to the correct filter operation under the covers.
I recommend using this feature sparingly.
A: One SERIOUS drawback to that will be indexes:
every query you do will write a separate index to be servable, then ALL writes you do will need to write to ALL these tables (for NO reason, in a good amount of cases).
I can't think of other drawbacks at the moment, except the limit of a meg per entity (if you have a LOT of types, with a LOT of values, you might run into this as you end up having a gazillion columns)
Not mentioning how big your ONE entity model would be, and how possibly convoluted your code to "triage" your entity types could end up being
| |
doc_1847
|
The user is given the possibility that before loading the data, the previous data will be deleted or added to the existing ones.
To delete data from the table I use the TRUNCATE command but I need to know if it has been executed correctly to get a "previous data deleted" message.
But the rowCount() function is not valid.
How can I know using PDO that the TRUNCATE has been executed correctly?
This is my current code that does remove the data but does not display the message.
$stmt = $db->prepare('TRUNCATE TABLE ' . TABLA_CLIENTES);
$stmt->execute();
$recDeleted = $stmt->rowCount();
if ($recDeleted) { ?>
<div class="alert alert-success col-xs-offset-1 col-xs-10" role="alert">
<p><i class="glyphicon glyphicon-ok"></i> Previous data successfully deleted.</p>
</div>
<?php
}
Thank you for any help you can give me.
| |
doc_1848
|
TypeError: this.toPaddedString is not a function
[Break On This Error]
return this.toPaddedString(2, 16);
Here is the JS iam using but didn't make any changes to the prototype, still the error emerges from the prototype.
( function($) {
// we can now rely on $ within the safety of our "bodyguard" function
$(document).ready( function() {
$('.s_code').change(function() {
// remove all previous selections
$('.option_all_box').attr('checked', false);
$('.option_all').val('0');
// hide all divs
$('.option_top').hide();
// show appropriate div & select first option
if($(this).val() == 'A')
{
$('.option_s').fadeIn();
$('.s_first').attr('checked', true);
}
else if ($(this).val() == 'B')
{
$('.option_p').fadeIn();
$('.p_first').attr('checked', true);
}
});
$('#frm_calculate').change(function() {
// ajaxify the calculate
// submit the form
$('#totalship').html('Please wait, Recalculating...');
formdata2 = $("form #frm_calculate").serialize();
var posting = $.post('calculate.php', formdata2, 'json');
posting.done(function( data ) {
//alert(data);
if(data.error)
{
//$('#totalship').html("Error!");
if(data.error.errorMessage == 'Please enter a valid amount.')
{
$('#totalship').html('Please enter a valid amount for extra cover (greater than zero)');
}
else
{
$('#totalship').html(data.error.errorMessage);
}
}
else
{
var result = data.postage_result;
thisqty = <?php echo $qtyArray[$i];?> ;
str = result.service + '<br>' + result.delivery_time + '<br>' + result.total_cost*thisqty;
// loop over the cost breakdown
//alert($(result.costs.cost).size());
listsize = $(result.costs.cost).size();
str = str + "<table width='100%'>";
if (listsize > 1)
{
$.each(result.costs.cost, function(key,value) {
str = str +'<tr><td width="50%">'+ value.item + '</td><td width="50%" style="text-align: right;">$' + value.cost*thisqty + '</td></tr>';
});
}
else if (listsize == 1)
{
value = result.costs.cost;
str = str + '<tr><td width="50%">'+value.item + '</td><td width="50%" style="text-align: right;">$' + value.cost*thisqty + '</td></tr>';
}
//Get variable from javascript back into this file's PHP code
var sendtoget1 = result.total_cost;
var sendtoget = sendtoget1; //*thisqty
var posting2 = $.post('sendtoget.php', sendtoget , 'text');
posting2.done(function( data ) {
//alert(data);
});
str = str + "</table>";
$('#totalship').html(str);
$('#totalship').fadeIn();
}
});
});
} );
} ) ( jQuery );
Thanks
A: Sorry for the late reply, but I got the same error but under a slightly different circumstances. My data was not formatted correctly when I was doing my ajax call. I ended up doing $.ajax(..., data: {key:value},...) and it ended up working.
This was the top post that came up when I googled the error, so I figured I should share incase someone else is in the same situation.
| |
doc_1849
|
onsubmit='$('#datatodisplay').val( $('<div>').append( $('#dataTable').eq(0).clone() ).html() )'>
<pre><input id='excel' type='image' src='img/file.png'></pre>
<p id='save'>Save table data to Excel</p>
<pre><input type='hidden' id='datatodisplay' name='datatodisplay' />
</form>
<input class='noPrint' type='button' id='print' value='Print' />";
When i run the page, i dont get a parse error, however ').append( $('#dataTable').eq(0).clone() ).html() )'> actually shows on the page, therefore the jQuery doesn't work!
How can i include it in the echo correctly?
Thanks
A: Why not skip the echo altogether like this:
//your PHP code before this echo statement
//let us say this is part of a IF statement
if(true)
{
?>
<form class='noPrint' action='demo/saveToExcel.php' method='post' target='_blank'
onsubmit="$('#datatodisplay').val( $('<div>').append( $('#dataTable').eq(0).clone() ).html() )">
<pre><input id='excel' type='image' src='img/file.png'></pre>
<p id='save'>Save table data to Excel</p>
<pre><input type='hidden' id='datatodisplay' name='datatodisplay' />
</form>
<input class='noPrint' type='button' id='print' value='Print' />
<?php
} //if ends here
// continue with your PHP code
EDIT: You also have a improperly nested quote characters in onsubmit. The code given above ALSO fixes that by converting those quotes to double quotes.
You can also use echo and escape those quotes like this:
echo "<form class='noPrint' action='demo/saveToExcel.php' method='post' target='_blank'
onsubmit=\"$('#datatodisplay').val( $('<div>').append( $('#dataTable').eq(0).clone() ).html() )\">
<pre><input id='excel' type='image' src='img/file.png'></pre>
<p id='save'>Save table data to Excel</p>
<pre><input type='hidden' id='datatodisplay' name='datatodisplay' />
</form>
<input class='noPrint' type='button' id='print' value='Print' />";
A: You have
onsubmit='$('
Single quotes inside attribute values delimited with single quotes must be represented as ' so they get treated as data and not the other end of the attribute value.
Also, and credit to knittl, double quote delimited strings in PHP interpolate variables. So you need to escape the $ signs for PHP.
This would also be better written using:
*
*Unobtrusive JavaScript
*
*Thus keeping the JS in a separate file and not having to worry about nested quotes
*A block of HTML instead of an echo statement (conditionals wrapped around it still apply)
*
*Letting you avoid having three levels of quotes (PHP, HTML, JavaScript)
*Avoiding having to worry about variable interpolation in PHP
A: With that kind of variable, the heredoc concept would be pretty useful
$variable = <<<XYZ
........
........
XYZ;
A: Add @ sign in front of string like this
echo @" and now you can have multiple lines
I hope this helps
A: You shouldnt use echo for this, you can just safely stop PHP for a sec.
The error seems to be in the HTML, as such:
onsubmit='$('#datatodisplay').
HTML thinks the onsubmit is only $(, you should use " instead.
A: there are several issues …
php substitutes variables in double quoted strings ("$var"), with their value.
you'd either have to use single quotes and escape the other single quotes, or use heredoc:
echo <<<EOT
<form class="noPrint" action="demo/saveToExcel.php" method="post" target="_blank"
onsubmit="$('#datatodisplay').val( $('<div>').append( $('#dataTable').eq(0).clone() ).html() )">
<pre><input id="excel" type="image" src="img/file.png"></pre>
<p id="save">Save table data to Excel</p>
<pre><input type="hidden" id="datatodisplay" name="datatodisplay" />
</form>
<input class="noPrint" type="button" id="print" value="Print" />
EOT;
you can also output your html directly, without php
// suspend php script
?>
<form class="noPrint" action="demo/saveToExcel.php" method="post" target="_blank"
onsubmit="$('#datatodisplay').val( $('<div>').append( $('#dataTable').eq(0).clone() ).html() )">
<pre><input id="excel" type="image" src="img/file.png"></pre>
<p id="save">Save table data to Excel</p>
<pre><input type="hidden" id="datatodisplay" name="datatodisplay" />
</form>
<input class="noPrint" type="button" id="print" value="Print" />
<?php // resume php script
furthermore, javascript event handlers should not be declared inline. use javascript to create and apply them to DOM elements
A: try this
echo "<form class='noPrint' action='demo/saveToExcel.php' method='post' target='_blank'
onsubmit='$(\"#datatodisplay\").val( $(\"<div>\").append( $(\"#dataTable\").eq(0).clone() ).html() )'>
<pre><input id='excel' type='image' src='img/file.png'></pre>
<p id='save'>Save table data to Excel</p>
<pre><input type='hidden' id='datatodisplay' name='datatodisplay' />
</form>
<input class='noPrint' type='button' id='print' value='Print' />";
you have '$('#datatodisplay'). html parses this as '$(' then takes the first > which is in <div> and print all whats after .
A: echo "<form class='noPrint' action='demo/saveToExcel.php' method='post' target='_blank'";
echo "onsubmit='\$(\'#datatodisplay\').val(\$(\'<div>\').append(\$(\'#dataTable\').eq(0).clone() ).html() )'>";
echo "<pre><input id='excel' type='image' src='img/file.png'></pre>";
echo "<p id='save'>Save table data to Excel</p>";
echo "<pre><input type='hidden' id='datatodisplay' name='datatodisplay' />";
echo "</form>";
echo "<input class='noPrint' type='button' id='print' value='Print' />";
try this! ;) you have to escape $ with \ and there shouldnt be \n (new line in response) so thats why multiple echos or you can all put to variable and then echo it at end!
A: Sorry, this is right answer lol
echo "<form class='noPrint' action='demo/saveToExcel.php' method='post' target='_blank'
onsubmit=\"$('#datatodisplay').val( $('<div>').append( $('#dataTable').eq(0).clone() ).html() )\">
<pre><input id='excel' type='image' src='img/file.png'></pre>
<p id='save'>Save table data to Excel</p>
<pre><input type='hidden' id='datatodisplay' name='datatodisplay' />
</form>
<input class='noPrint' type='button' id='print' value='Print' />";
Why are you so angry. hehe :)
| |
doc_1850
|
+---------------------------------------+
| FunkyUsers |
+-------+---------+----------+----------+
|acc_num| user_id | date | is_valid |
+-------+---------+----------+----------+
| a1 | u1 | 20200201 | true |
| a1 | u1 | 20200201 | true |
| a1 | u1 | 20200311 | true |
| a1 | u2 | 20200201 | false |
| a1 | u2 | 20200201 | false |
| a1 | u2 | 20200201 | false |
| a1 | u3 | 20111201 | true |
| a1 | u3 | 20111201 | true |
| a1 | u3 | 20111201 | true |
+-------+---------+----------+----------+
I like to have the following output:
+--------------------------------------------------+
| FunkyUsers |
+-------+---------+----------+----------+----------+
|acc_num| user_id | date | is_valid | count |
+-------+---------+----------+----------+----------+
| a1 | u1 | 20200201 | true | 2 |
| a1 | u1 | 20200201 | true | 2 |
+-------+---------+----------+----------+----------+
| a1 | u1 | 20200311 | true | 2 |
+-------+---------+----------+----------+----------+
| a1 | u2 | 20200201 | false | 0 |
| a1 | u2 | 20200201 | false | 0 |
| a1 | u2 | 20200201 | false | 0 |
+-------+---------+----------+----------+----------+
| a1 | u2 | 20111201 | true | 1 |
| a1 | u2 | 20111201 | true | 1 |
| a1 | u2 | 20111201 | true | 1 |
+-------+---------+----------+----------+----------+
Description:
*
*Please note the partition acc_num, user_id
*Please note the subpartition within the above partition which is the date
*When is_valid is true for a (partition, subpartition) increment the count for that (partition)
*Finally the is_valid will have the same value for each row within the same (partition, subpartition)
A: As far as I understand, you want to count distinct dates for is_valid = 1 for a user.
You can use window function count with distinct parameter for date.
select
acc_num, user_id, date, is_valid,
count(distinct case when is_valid then date end) over (partition by acc_num, user_id, is_valid)
from FunkyUsers
I'm told it's not possible to use distinct in window functions in Redshift.
So, you can use this query:
with
counts as
(
SELECT acc_num, user_id, is_valid, COUNT(DISTINCT CASE WHEN is_valid THEN date END) as count
FROM FunkyUsers
GROUP BY acc_num, user_id, is_valid
)
SELECT f.*, c.count
FROM FunkyUsers f
LEFT JOIN counts c
ON f.acc_num = c.acc_num
AND f.user_id = c.user_id
AND f.is_valid = c.is_valid
A: You can use window function sum with partitioning:
select acc_num, user_id, date, is_valid,
sum(case when is_valid then 1 end) over(partition by acc_num, user_id, date)
from FunkyUsers
A: count(distinct) is not supported. But a simple work-around is to use row_number():
select fu.*,
sum(case when is_valid and seqnum = 1 then 1 else 0 end) over (partition by acc_num, user_id order by date) as count
from (select fu.*,
row_number() over (partition by acc_num, user_id, date order by date) as seqnum
from funkyusers fu
) fu;
This is much simpler than a solution that uses aggregation and join and it should have better performance as well.
| |
doc_1851
|
Also i dont see any sleep calls, so how buffer overflow is controlled in /dev/snd devices.
| |
doc_1852
|
I need to fetch n documents from t1 with certain criteria, such that some field of t1 also exists in t2.
This works, but if t1 has millions of documents and I only need to get the first 5 matching documents, then it would be stupid to fetch all.
responses = [];
const data = await t1.find({});
for (var i = 0; i < data.length; i++) {
await t2.findOne({
t2.field : t1.field,
t2.field2 : someOtherInfo
}).then((obj) => responses.push(data[i]));
if (responses.length > n) break;
}
return responses;
I have tried to use limit, but I cannot figure out the filtering part. Hence, this crude solution.
What is the better way to do this?
| |
doc_1853
|
Everything works perfectly in Edge browser, but when I do test in Chrome, the button becomes disabled, but post request is not sent to server.
jquery script which shows loading gif and blocks submit input button:
function loading() {
if ($('#calendar1').val() && $('#calendar2').val()) {
$("#loading").show();
$("#content").hide();
$(':input[type="submit"]').prop('disabled', true);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" class="ordinary_form" id="wifi_form">
<label for="calendar1"> Choose time period start: </label>
<input type="date" name="calendar1" id="calendar1" required> <br> <br>
<label for="calendar2"> Choose time period end: </label>
<input type="date" name="calendar2" id="calendar2" required></p>
<label for="period"> Choose step: </label>
<select required name="period" id="period">
<option selected value="0">Day</option>
<option value="1">Week</option>
<option value="2">Month</option>
</select>
<br><br>
<input target="_self" type="submit" value="Send" formtarget="{{url_for('wifi')}}" formmethod="post" onclick="loading();">
</form>
Python code (I guess you do not need it, but let it be here):
@app.route("/wifi", methods=["GET", "POST"])
@flask_login.login_required
def wifi():
# something here
if request.method == 'POST':
start_date = request.form["calendar1"]
end_date = request.form["calendar2"]
period = request.form["period"]
# do some work
return render_template("wifi.html", result_dict=result_dict, wifipic="wifi" + pic_end)
A: Because you can only do that in the submit event
Disabling the button itself on click of the button will stop the form from being submitted
It also seems that your formtarget="{{url_for('wifi')}}" formmethod="post" should be removed. No need to set that when you have a form already
In any case formtarget is not a URL - you may have meant formaction
$("#wifi_form").on("submit",function() {
if ($('#calendar1').val() && $('#calendar2').val()) {
$("#loading").show();
$("#content").hide();
$(':input[type="submit"]').prop('disabled', true);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="{{url_for('wifi')}}" class="ordinary_form" id="wifi_form">
<label for="calendar1"> Choose time period start: </label>
<input type="date" name="calendar1" id="calendar1" required> <br> <br>
<label for="calendar2"> Choose time period end: </label>
<input type="date" name="calendar2" id="calendar2" required></p>
<label for="period"> Choose step: </label>
<select required name="period" id="period">
<option selected value="0">Day</option>
<option value="1">Week</option>
<option value="2">Month</option>
</select>
<br><br>
<input type="submit" value="Send" >
</form>
| |
doc_1854
|
com.ibm.as400.access.AS400SecurityException: Password is expired.
Does JTOpen provide any method to expire a user's password?
Thanks in advance
| |
doc_1855
|
I have googled "javascript yield" and read the first 4 pages of hits. Some discuss a new "yield" keyword, but there is only one description and example, which I find incomprehensible, e.g. "The function containing the yield keyword is a generator. When you call it, it's formal parameters are bound to actual arguments, but it's body isn't actually evaluated". Does yield yield to the UI?
One of the few solutions I did find is this old post which uses the deprecated callee argument and a timer to call itself:
http://www.julienlecomte.net/blog/2007/10/28/
However, the above example doesn't contain any loop variables or state, and when I add these it falls apart, and my net result is always zero.
It also doesn't do chunking, but I have found some other examples which chunk using "index % 100 == 0" on every iteration. However, this seems to be a slow way of doing it. E.g. this:
How to stop intense Javascript loop from freezing the browser
But it doesn't have any way to update progress, and doesn't yield to the UI (so still hangs the browser). Here is a test version which hangs the browser during execution:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
var spins = 1000000
var chunkSize = 1000;
var chunk;
function Stats() {this.a=0};
var stats = new Stats();
var big;
var index = 0;
var process = function() {
for (; index < spins; index++) {
stats.a++;
big = (big/3.6)+ big * 1.3 * big / 2.1;
console.write(big);
// Perform xml processing
if (index + 1 < spins && index % 100 == 0) {
document.getElementById("result").innerHTML = stats.a;
setTimeout(process, 5);
}
}
document.getElementById("result").innerHTML = stats.a;
};
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body onload="process()">
<div id=result>result goes here.</div>
</body>
</html>
and here is another attempt which the stats.a is always zero (So I presume there is some scoping issue):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
var spins = 1000000
var chunkSize = 1000;
var chunk;
function Stats() {this.a=0};
var stats = new Stats();
function doIt() {
function spin() {
for (spinIx=0; (spinIx<chunkSize) && (spinIx+chunk < spins); spinIx++) {
stats.a++;
}
}
for (chunk =0; chunk < spins; chunk+=chunkSize){
setTimeout(spin, 5);
document.getElementById("result").innerHTML = stats.a;
}
document.getElementById("result").innerHTML = stats.a;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body onload="doIt()">
<div id=result>result goes here.</div>
</body>
</html>
I've spent 48 hours trying to get this working - either I am very dumb or this is very hard. Any ideas?
Several people have suggested web workers. I tried several days to get his working, but I could not find a similar example which passes a number etc. The code below was my last attempt to get it working, but the result is always 0 when it should be 100000. I.e. it fails in the same way that my second example above fails.
spinMaster.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<script>
if(typeof(Worker)==="undefined") {
document.write("<h1>sorry, your browser doesnt support web workers, please use firefox, opera, chorme or safari</h1>");
}
var worker =new Worker("spinWorker.js");
worker.postMessage({times:1000000});
worker.onmessage=function(event){
document.getElementById("result").innerHTML=event.data;
};
</script>
<div id="result">result goes here</div>
</body>
</html>
spinWorker.js
function State() {
this.a=0;
}
var state = new State();
self.addEventListener('message', spin, false);
function spin(e) {
var times, i;
times = e.data.times;
//times = 1000000; // this doesnt work either.
for(i;i<times;i++) {
state.a++;
}
self.postMessage(state.a);
}
resultant output: 0
A: Web workers sound like the better solution.
I wrote this up quickly so i dunno if itll work. Performance will be very bad...
Edit: Changed to same format as poster. Tested
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
var spins = 1000000
var chunkSize = 1000;
var chunk;
function Stats() {this.a=0};
var stats = new Stats();
var big = 0.0;
var index = 0;
function workLoop() {
index += 1;
stats.a++;
big = (big/3.6)+ big * 1.3 * big / 2.1;
console.log(big);
// Perform xml processing
document.getElementById('result').innerHTML = stats.a;
if (index < spins) {
setTimeout(workLoop, 5);
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body onload="workLoop()">
<div id="result">result goes here.</div>
</body>
</html>
A: since JS is single threaded usually, I don't think there is any way around it. If you are supporting only newer browsers however, you might want to look into web workers, which can spawn a new thread to do work: http://developer.mozilla.org/en-US/docs/DOM/Using_web_workers
the only downside I can think of is that I've read it is hard to debug Web Workers because dev tools (Chrome Dev tools unless running dev channel, firebug), doesn't support profiling for it.
here's a nice tutorial to get you started: http://net.tutsplus.com/tutorials/javascript-ajax/getting-started-with-web-workers/
A: You have close to a working example in your 1st test, but I do see a logic error. In your if(), you need to return from the function otherwise it'll always be running multiple functions competing for that thread.
var process = function() {
for (; index < spins; index++) {
stats.a++;
big = (big/3.6)+ big * 1.3 * big / 2.1;
console.write(big);
// Perform xml processing
if (index + 1 < spins && index % 100 == 0) {
document.getElementById("result").innerHTML = stats.a;
setTimeout(process, 5);
//!!!!!
return;//without this it'll keep iterating through the for loop without waiting for the next 5ms
//!!!!!
}
}
document.getElementById("result").innerHTML = stats.a;
};
Neither of the samples as-is wait for the next setTimeout (in your 2nd Example you continue iterating through your for loop until the for loop is completed, but at each block size you set a timeout for a subsequent iteration. All this does is delay the entire sequence for 5 ms, they still all pileup and execute 5 ms from when your for loop begins iterating)
All in all you seem to be on the right track, there are just small logic errors in both examples.
A: There is a library on github available for this type of big looping without locking the browser/thread and without using web-workers.
Somewhat experimental, and supports big recursive loops, but it may work for you. Depends on q.js for resolving promises.
https://github.com/sterpe/stackless.js
A: This should do what you want:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
var spins = 1000000
var chunkSize = 1000;
var stats = {a:0,spins:0};
function doIt() {
for (var chunk = 0; chunk < chunkSize; chunk++) {
stats.a++;
}
document.getElementById("result").innerHTML = stats.a;
if(++stats.spins < spins) setTimeout(doIt,5);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body onload="doIt()">
<div id=result>result goes here.</div>
</body>
</html>
| |
doc_1856
|
I tried using the following .perldb:
&parse_options("HistFile=.perlDebugHist");
sub afterinit { push @DB::typeahead, ("o inhibit_exit", chr(27).chr(10)) }
but when the session starts, it says
auto(-2) DB<62> o inhibit_exit
inhibit_exit = '1'
auto(-1) DB<63>
Unrecognized character \x1B; marked by <-- HERE after :db_stop;
<-- HERE near column 96 at (eval 9)[/usr/share/perl/5.22/perl5db.pl:737] line 2.
at (eval 9)[/usr/share/perl/5.22/perl5db.pl:737] line 2.
eval 'no strict; ($@, $!, $^E, $,, $/, $\\, $^W) = @DB::saved;package main; $^D = $^D | $DB::db_stop;
;
' called at /usr/share/perl/5.22/perl5db.pl line 737
DB::eval called at /usr/share/perl/5.22/perl5db.pl line 3110
DB::DB called at ~/bin/debug.pl line 61
A: Here is a possible workaround that assumes you use the gnu readline library:
Create a file called perldb_inputrc in the current directory with content:
set editing-mode vi
Then change the afterinit() sub to:
sub afterinit {
if (!$DB::term) {
DB::setterm();
}
$DB::term->read_init_file('perldb_inputrc');
push @DB::typeahead, "o inhibit_exit";
}
See perldoc perl5db for more information.
Update:
A simpler approach is to the readline init file. You can use a global file ~/.inputrc or a use a local one for the current debugging session only by setting the environment variable INPUTRC. For example, using the above perldb_inputrc file as an example, you could use (in your .perldb init file):
sub afterinit { push @DB::typeahead, "o inhibit_exit" }
and then run the Perl script like this:
INPUTRC=./perldb_inputrc perl -d myscript.pl
| |
doc_1857
|
{\"error\":{\"message\":\"Invalid
parameter\",\"type\":\"OAuthException\",\"code\":100,\"error_subcode\":1487930,\"is_transient\":false,\"error_user_title\":\"Promoted
Object Is Missing\",\"error_user_msg\":\"You must select an object to
promote that is related to your objective, for example a Page post,
website URL, or app. Please add a promoted object and try
again.\",\"fbtrace_id\":\"GrLuBDDVrhZ\"}}
import requests
import urllib
ad_group_obj = 'name=fb_1200_628_04.png,object_story_spec={"page_id":"your
page id","link_data":{"link":"https://www.link.com/"}}'
ad_group_obj = (urllib.parse.quote(ad_group_obj))
#print (ad_group_obj)
files = {
'access_token': (None, 'your access token'),
'asyncbatch': (None,'
[{"method":"POST","relative_url":"act_126671081468820/adcreatives","name
":"My Async Ad Creative","body":"'+(ad_group_obj)+'",}]'),
}
print (files)
response = requests.post('https://graph.facebook.com/v3.0/', files=files)
print (response.text)
| |
doc_1858
|
the scale is linear and I set the range of it based on the dataframe index
I need to keep the scale as linear but want to set the vertical scale or the y-axis scale for example to be 1:100 how to achieve that
layout = go.Layout(
title='VSH',
autosize=False,
width=500,
height=1500,
yaxis=dict(
title='DEPT',
showgrid=True,
showticklabels=True,
gridcolor='#bdbdbd',
gridwidth=2
),
xaxis=dict(
title='Vsh',
showgrid=True,
showticklabels=True,
gridcolor='#bdbdbd',
gridwidth=2
)
)
df = df.loc[(df.index >= int(top)) & (df.index <= int(base))]
trace1 = go.Scatter(x = df['Vsh']/10 , y = df.index , mode='lines')
fig = go.Figure(data=[trace1] , layout = layout)
iplot(fig)
A: Just create a list (for example, from 1 to 100):
list1 = [i for i in range(0, 101)]
and added two parameters to yaxis in layout:
yaxis=dict(tickvals=[i for i in range(len(list1))],
ticktext=list1)
You can read more about ticktext and tickvals in plotly docs: 1 and 2.
| |
doc_1859
|
Here is the code:
for(DriverInfo aDriver : registeredDrivers) {
// If the caller does not have permission to load the driver then
// skip it.
if(isDriverAllowed(aDriver.driver, callerCL)) {
try {
println(" trying " + aDriver.driver.getClass().getName());
Connection con = aDriver.driver.connect(url, info);
if (con != null) {
// Success!
println("getConnection returning " + aDriver.driver.getClass().getName());
return (con);
}
} catch (SQLException ex) {
if (reason == null) {
reason = ex;
}
}
} else {
println(" skipping: " + aDriver.getClass().getName());
}
}
But there is a method "acceptsURL" from interface Driver:
boolean acceptsURL(String url) throws SQLException;
So my question is, why DriverManager does not call this method before it do the real connection to filter unrelated drivers?
Or with code, may be this is better?
for(DriverInfo aDriver : registeredDrivers) {
// If the caller does not have permission to load the driver then
// skip it.
if(isDriverAllowed(aDriver.driver, callerCL) && aDriver.driver.acceptsURL(url)) {
try {
println(" trying " + aDriver.driver.getClass().getName());
Connection con = aDriver.driver.connect(url, info);
if (con != null) {
// Success!
println("getConnection returning " + aDriver.driver.getClass().getName());
return (con);
}
} catch (SQLException ex) {
if (reason == null) {
reason = ex;
}
}
} else {
println(" skipping: " + aDriver.getClass().getName());
}
}
A: The DriverManager reference implementation (OpenJDK) doesn't use acceptsUrl. That doesn't necessarily mean there are no DriverManager implementations using it. In fact, as far as I recall, earlier Sun Java implementations did call acceptsURL. The main reason it isn't called, is that the JDBC specification requires DriverManager to call connect on each registered driver anyway. See below.
Nothing in the specification or API documentation says that DriverManager must use acceptsURL. The JDBC 4.3 specification on this only says (section 9.2 The Driver interface):
The DriverManager class invokes Driver methods when it wishes to
interact with a registered driver. The Driver interface also
includes the method acceptsURL. The DriverManager can use this
method to determine which of its registered drivers it should use for
a given URL.
(emphasis mine)
Note the use of the word can instead of must or will.
The subsequent paragraph says:
When the DriverManager is trying to establish a connection, it calls
that driver’s connect method and passes the driver the URL. If the
Driver implementation understands the URL, it will return a
Connection object or throw a SQLException if a connection cannot
be maded [sic] to the database. If the Driver implementation does
not understand the URL, it will return null.
In addition, section 9.4 The DriverManager class says:
*
*getConnection — the method the JDBC client invokes to establish a connection. The invocation includes a JDBC URL, which the
DriverManager passes to each driver in its list until it finds
one whose Driver.connect method recognizes the URL. That driver returns a Connection object to the DriverManager, which in turn
passes it to the application.
(emphasis mine)
How I read this, calling Driver.connect on each driver is required anyway, so there is no point for the implementation to call acceptsURL.
Now, as to why the JDBC specification is written this way, I don't know, and I'm a member of the JSR-221 (JDBC 4) Expert Group myself. When I joined the Expert Group the implementation (and specification) was already this way, so I'm not aware of its history. However, I'm not sure you'll get a better answer here than above unsatisfactory answer (it is so because the specification says so).
However, if I had to guess, it is probably to do with the fact that for some drivers determining if they can accept an URL could be relatively complex or expensive. In that case it is better to just try and connect, because for a driver rejecting the URL the cost is (or should be) the same as just calling acceptsURL, while for a driver that will actually accept the URL, the cost would be hit twice if DriverManager would first call acceptsURL followed by a connect.
This doesn't mean that the acceptsURL method is entirely without value. Some applications (eg some query tools or reporting tools) use it to discover which driver(s) would handle a specific URL, so they can interrogate the Driver implementation(s) for their supported connection properties (Driver.getPropertyInfo) so they can populate there connection wizard with the available properties. Other programs could use it to get information like its version (Driver.getMajorVersion, Driver.getMinorVersion), parent logger (Driver.getParentLogger) or JDBC compliancy (Driver.jdbcCompliant).
| |
doc_1860
|
Node Path = "Tool/Manager/Name"
Node data Type = "string" and data is "Jone"
When I use nodesToRead.Add(new NodeId(path, 6)); Is work!
But, if I change the node data to string[]{"Jone","Peter","Himari"}
When I use nodesToRead.Add(new NodeId(path, 6)), It return a System.string[]. and I need to use some methods to get string[0] data.
How can I read the "Jone" by only node path without do some methods to get "Jone"?
This is used Softing(Software) to read my server. It read an array type. {AA,NN,CC}
I want to know how to read each elements by set Browse Name?
Example: only read "AA" by set Browse Name?.
enter image description here
Because the Siemens OPC Server can read read each elements by set Browse Name.
It's Browse Name can set like AxisNameList[u1,1] to read the array{1},and It Configuration Browse only one node like "AxisNameList" Node.
if i publish this path "AxisNameList", it will by request array[0] data.
if i publish this path "AxisNameList[u1,1]", it will by request array[1] data.
If i want to achieve this function, How do i modify my OPC UA Server?
A: OPC UA Specification Part4
5.10.2 Read Service
Parameters of Read Service is defined as following
Read Service Parameters
The type of nodesToRead[] is ReadValueId,
which is defined as following
ReadValueId DataType
indexRange is the parameter you need.
So, OPC UA supports reading a single element of an array.
But i don't known if your SDK support it.
here is the datatype of readparameters in the sdk i used.
struct ReadParameters
{
double MaxAge;
OpcUa::TimestampsToReturn TimestampsToReturn;
std::vector<OpcUa::ReadValueId> AttributesToRead;
ReadParameters();
};
struct ReadValueId
{
OpcUa::NodeId NodeId;
OpcUa::AttributeId AttributeId;
std::string IndexRange;
OpcUa::QualifiedName DataEncoding;
};
| |
doc_1861
|
I am using Oracle Cloud Explorer.
I tried this query but it did not work:
select table_name
from all_tab_columns
where column_name = 'PICK_COLUMN';
A: What does it mean - "it did not work"? What does you have in result?
Among other things, you can try to refer to other system tables, such as DBA_TAB_COLUMNS or USER_TAB_COLUMNS.
A: You are going in right way.
Just use upper or lower on both side of comparision, as Oracle object names are case sensitive if they are created with double quotes else they are case insensitive (stored in upper case name). Whenever you query oracle dictionary views, always follow this practise.
So you need following query:
select table_name from all_tab_columns where upper(column_name) = 'PICK_COLUMN';
Cheers!!
| |
doc_1862
|
To clarify:
When you highlight a selection of words in an article, a little tooltip pops up with the option to tweet or comment on the selection of words you highlighted.
Here's a screenshot:
I have absolutely no idea how to achieve this - so I don't have any code to provide (and I can't work it out from the medium.com source)
If you have any idea on how to do this - please share
Thanks, Tom
A: Try looking at Highlighter.js on github. It's similar to what's happening on Medium.com blog but requires a bit of work in order to achieve what you want.
A: First step is to get the selection of the user. This can be done with window.getSelection().
var getSelectedText = function () {
var selectedText = '';
if (window.getSelection()) {
selectedText = window.getSelection();
} else if (document.getSelection()) {
selectedText = document.getSelection();
} else if (document.selection) {
selectedText = document.selection.createRange().text;
}
return selectedText;
};
window.addEventListener('mouseup', function () {
var result = getSelectedText();
// Now you can do whatever you want with your selected text
});
Then you need to create a sticky tooltip on the position of this selection (you can find this by getting the element.offsetLeft, element.offsetTop of your element).
Then you need to hook in a commenting system that stores the relationship to the selection (by wrapping the selection with a span and an ID for example and open up the editor.
This is only the basic introduction for what you asked, it’s slightly more complex but also depends on what you exactly want to do with it.
Hope it helps!
A: Take a look in this fiddle:
http://jsfiddle.net/9RxLM/
and use below code:
$(".tiptext").mouseover(function() {
$(this).children(".description").show();
}).mouseout(function() {
$(this).children(".description").hide();
});
Or you can use jquery tool tip:
http://www.1stwebdesigner.com/css/stylish-jquery-tooltip-plugins-webdesign/
| |
doc_1863
|
Is there a better tutorial/article/example that I should read or follow before implementing?
A: I didn't like the specificity of the provided tutorial either. I don't have a link to a tutorial, but perhaps I can give you a few road signs to guide you in the direction of a solution.
What I did was to create my own ACL and Permissions. I created a new class SecuredEntity which is the parent class of all of my domain entities which need ACL support. This was possible in my situation as I was starting from the ground up. Obviously you could use composition rather than inheritance if you cannot extend a common ancestor.
This SecuredEntity contains my own implementation of an ACL, which basically is a map of principals to permissions. A principal is either an account id, or a role, or a group. Each user has a set of principals which they can act as which is the set {the user's own account, all the roles of the user, and any groups the account is a part of}.
I then implemented a custom PermissionEvaluator which retrieves the principals set for the user indicated by the provided Authentication, and then examines the indicated object to determine if the user has indicated permission.
After registering the custom permission evaluator with both the Default expression handler and the web expression handler, I could then use expressions such as
@PreAuthorize("hasPermission(#entityId, 'EntityClass', 'read')")
@RequestMapping("/entities/{entityId}")
public String fetchEntity(@PathVariable("entityId") String entityId) {...}
| |
doc_1864
|
What would be required to add zoomIn and zoomOut buttons(+ and -), and then add scroll buttons (left, right, up, down) or scroll bar so the user can access content that goes outside the borders after zooming.
The code below works for zooming in, however, there is no way to view content outside the edges after zooming
pdfDoc.getPage(pageNum).then(function(page){
var viewport = page.getViewport({scale: 2});
canvas.width = viewport.width;
canvas.height = viewport.height;
page.render({ canvasContext:ctx,
viewport: viewport })
})
Any help is greatly appreciated.
| |
doc_1865
|
This is causing exceptions, because it tries using the FB OAuth token - luckily it already has been used by the user.
It's hitting an url like:
/auth/fb/login-with-redirect?redirectUrl=https%3A%2F%example.com%2Fnl&code=AQCwC2...YPe
*
*Anyone else experiencing this?
*Is there any legit reason for FB to do this? Like checking for spam or whatever?
*I'm now sniffing out the facebookexternal hit useragent and just early return an empty page. Can this cause problems?
| |
doc_1866
|
Here is some code :
void GameEngine::createMap(std::vector<std::string> &parse)
{
int x;
int y;
std::string strx;
std::string stry;
strx = parse.at(0);
stry = parse.at(1);
x = atoi(strx.c_str());
y = atoi(stry.c_str());
std::cout << "okokok" << std::endl;
//_gMap is a Graphmap*;
this->_gMap = new GraphMap(x, y);
std::cout << "okokokabc" << std::endl;
}
createMap() is a function called when the server i'm connected to sends me "msz X Y\n", it's being called for sure. with valid X Y.
So here is a function that calls my class' (GraphMap) constructor. X and Y are to valid numbers
And here is the GraphMap Class.
The .hh
#ifndef GRAPHMAP_HH_
#define GRAPHMAP_HH_
class GameEngine;
class GraphMap
{
private:
int _height;
int _width;
int _squareSize;
public:
GraphMap(int, int);
~GraphMap();
void draw(SDL_Renderer *);
};
#endif
And the .cpp:
#include "GameEngine.hh"
#include "GraphMap.hh"
GraphMap::GraphMap(int width, int height)
{
std::cout << "testouilleee1" << std::endl;
_width = width;
std::cout << "testouilleee2" << std::endl;
_height = height;
std::cout << "testouilleee3" << std::endl;
_squareSize = 1000 / width;
std::cout << "testouilleee4" << std::endl;
}
GraphMap::~GraphMap() {}
void GraphMap::draw(SDL_Renderer *renderer)
{
int i;
int j;
for(i = 1 ; i <= _width ; i++)
{
for (j = 1 ; j <= _height ; j++)
{
SDL_Rect rect;
rect.x = ((i - 1) * _squareSize);
rect.y = ((j - 1) * _squareSize);
rect.w = _squareSize - 1;
rect.h = _squareSize - 1;
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_RenderFillRect(renderer, &rect);
}
j = 1;
}
}
The thing that i can't understand is that the output is :
$ ./run.sh
okokok
testouilleee1
testouilleee2
testouilleee3
testouilleee4
./run.sh: line 12: 10414 Segmentation fault (core dumped) ./zappy_graph 127.0.0.1 4242
That means it goes to the last line of the constructor but then segFaults and do not prints the "okokokabc" which I can not understand
Here are some debug info from GDB :
0x0000000000404556 in GameEngine::createMap (this=0x0, parse=...) at GameEngine.cpp:90
90 this->_gMap = new GraphMap(x, y);
(gdb) bt
#0 0x0000000000404556 in GameEngine::createMap (this=0x0, parse=...) at GameEngine.cpp:90
#1 0x000000000040561b in Command::msz (this=0x712360, cmd=..., game=0x0) at Command.cpp:32
#2 0x000000000040647c in Command::Parse (this=0x712360, command=..., game=0x0) at Command.cpp:138
#3 0x000000000040949b in Socket::selectSocket (this=0x7120a0) at Socket.cpp:67
#4 0x000000000040441e in GameEngine::update (this=0x712010) at GameEngine.cpp:58
#5 0x00000000004046f0 in GameEngine::run (this=0x712010) at GameEngine.cpp:110
#6 0x000000000040968e in main (ac=1, av=0x7fffffffdd78) at main.cpp:22
(gdb) print x
$1 = 20
(gdb) print y
$2 = 20
If you need more info/code just tell me i'll post it as soon as I can.
A: GDB shown that the GameEngine address is 0x0:
GameEngine::createMap (this=0x0...
So the problem is that for some reason the GameEngine pointer is wrong (was not initialized or corrupted).
Note that this pointer seems to come from at least
Command::Parse (this=0x712360, command=..., game=0x0)
(I suppose the last parameter is the GameEngine itself?)
Note also that some lines below there is a correct GameEngine object:
GameEngine::update (this=0x712010) at GameEngine.cpp:58
If you have only one GameEngine in your program (which I assume is the case), then this means that GameEngine address is somehow lost between GameEngine::update() and Command::Parse().
| |
doc_1867
|
Here’s the whole story: I had two websites, w1 and w2. After a while, I decided to move the content of w2 to a subdirectory in w1. So, now I have a CMS in the root of W1, and another CMS in the subdirectory (the first CMS is TextPattern and the second one is OpenCart). I’ve redirected the old w2 website to that particular sub directory in w1.
The htaccess in old w2 contains:
Redirect 301 / w2/subdirectory?oldlink=
(the ?oldlink= might seem stupid, but I didn’t know how better to do that!)
The htaccess in the root of w1:
DirectoryIndex index.php index.html
Options +FollowSymLinks
Options -Indexes
ErrorDocument 403 default
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+) - [PT,L]
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*) index.php
RewriteCond %{HTTP:Authorization} !^$
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
</IfModule>
#php_value register_globals 0
# SVG
AddType image/svg+xml svg svgz
AddEncoding gzip svgz
And lastly, the htaccess in the subfolder (inside w1, for the content of the old w2):
Options +FollowSymlinks
# Prevent Directoy listing
Options -Indexes
# Prevent Direct Access to files
<FilesMatch "\.(tpl|ini|log)">
Order deny,allow
Deny from all
</FilesMatch>
# SEO URL Settings
RewriteEngine On
RewriteBase /subdirectory/
RewriteRule sitemap.xml /index.php?route=feed/google_sitemap
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]
I don’t have any redirecting tags in my web pages.
Everything works fine in the subdirectory; I can open pages, navigate through them, etc.
When I check w1 in online link checkers, I get 404 for the pages in the subdirectory. When I check it with Fetch as Google, it gives me “The page seems to redirect to itself. This may result in an infinite redirect loop. Please check the Help Center article about redirects.” Warning, and the following details are:
HTTP/1.1 301 Moved Permanently
Date: Sun, 27 Oct 2013 16:42:24 GMT
Server: LiteSpeed
Connection: Keep-Alive
Keep-Alive: timeout=5, max=100
Location: the sub directory
X-Powered-By: PleskLin
Content-Type: text/html
Content-Length: 413
<html>
<head><title> 301 Moved Permanently
</title></head>
<body><h1> 301 Moved Permanently
</h1>
The document has been permanently moved to <A HREF="%s">here</A>.<hr />
Powered By <a href='http://www.litespeedtech.com'>LiteSpeed Web Server</a><br />
<font face="Verdana, Arial, Helvetica" size=-1>LiteSpeed Technologies is not responsible for administration and contents of this web site!</font></body></html>
So, I’m really confused. I can’t find the source of the infinite redirect. Can anyone help me with this?
Thanks.
| |
doc_1868
|
Project's build.gradle:
firebase_version = '15.0.0'
And the following library dependencies:
App's build.gradle:
implementation "com.google.firebase:firebase-firestore:$firebase_version"
It looks like these versions were released on the 10th of April, however when compiling my app with the updated libraries, it fails to run with the following error:
error: cannot access zzbgl
class file for com.google.android.gms.internal.zzbgl not found
When checking all my library versions, my build.gradle has the following error:
not sure if anyone has experienced this by any chance since the latest updates? Before updating from 12.0.1, everything was working.
Thanks
A: Simply override (add to your gradle file) the conflicting library, updating the version to match the ones you already have in your gradle file. Somewhere in your dependencies someone is using an older version of this library and it's crashing with your version:
implementation "com.google.android.gms:play-services-auth:$firebase_version"
| |
doc_1869
|
I've tried synchronizing the packages and project, no luck.
In the image below, there is a LinuxSandboxStrategy file that should be "between" BUILD and LinuxSandboxWrapper. Another missing file can be seen under the skyframe package.
I'm using intellij community edition 2016.1 on Linux.
A: It's an old known bug (Feb 2014)... not fixed yet (July 2016)
Here is the related bug report : https://youtrack.jetbrains.com/issue/IDEA-121164
| |
doc_1870
|
As you can see there is a black bar at the top. There is also a white navigation bar at the bottom. The black bar at the top comes a few seconds after opening the application and causes the background image to decrease in size.
My splash_screen.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<color android:color="@color/splash_background"/>
</item>
<item android:gravity="fill">
<bitmap
android:tileMode="disabled"
android:gravity="fill"
android:mipMap="true"
android:src="@drawable/splash_logo"/>
</item>
</layer-list>
My styles.xml:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="MyTheme.Splash" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">@drawable/splash_screen</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowActionBar">false</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.MaterialComponents.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.MaterialComponents.Light" />
</resources>
My SplashActivity.cs:
namespace OkuKazan
{
[Activity(Label = "OkuKazan", Icon = "@mipmap/icon", Theme ="@style/MyTheme.Splash", MainLauncher = true, NoHistory = true)]
public class SplashActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
}
protected override async void OnResume()
{
base.OnResume();
await SimulateStartUp();
}
async Task SimulateStartUp()
{
await Task.Delay(TimeSpan.FromSeconds(3));
StartActivity(new Intent(Application.Context, typeof(MainActivity)));
}
}
}
According to my research they are using something like NavigationPage but as I am a new xamarin user I don't get it. I would really appreciate if you can help.
EDIT 1:
I edited my styles.xml but it is still not working. The black bar at the top and the white bar didn't disappear :(
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>m>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="windowActionModeOverlay">false</item>
<item name="android:windowBackground">@android:color/white</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:textCursorDrawable">@null</item>
<item name="android:forceDarkAllowed">false</item>
</style>
<style name="MyTheme.Splash" parent="AppTheme">
<item name="android:windowFullscreen">true</item>
<item name="android:windowBackground">@drawable/splash_screen</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.MaterialComponents.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.MaterialComponents.Light" />
</resources>
A: A theme looking something like:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>m>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="windowActionModeOverlay">false</item>
<item name="android:windowBackground">@color/white</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:textCursorDrawable">@null</item>
<item name="android:forceDarkAllowed">false</item>
</style>
<style name="AppTheme.Splash" parent="AppTheme">
<item name="android:windowFullscreen">true</item>
<item name="android:windowBackground">@drawable/bg_splashscreen</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
</style>
Then use the AppTheme.Splash on your Activity. This works on one of the Apps I work on. You can play around with the attributes. However, the windowFullScreen and windowNoTitle are probably the most important ones.
| |
doc_1871
|
@Html.Label(ViewData.ModelMetadata.DisplayName)
@Html.TextBox("",
ViewData.TemplateInfo.FormattedModelValue,
new { placeholder = ViewData.ModelMetadata.Watermark })
@if (ViewData.ModelMetadata.IsRequired)
{
@:<span class="required"></span>
}
@Html.ValidationMessage("")
It's pretty much the same for my textarea. What I am hoping to do is to create a similar EditorTemplate for my dropdownlists. Something like:
...
@Html.DropDown("", ......)
....
I have tried variations using the code in parentheses for textbox above and I have tried figuring out, based on my actual dropdownlist, what code goes in there. I have had no luck.
This way I could use either [UIHint("TemplateName")] or do something like @Html.EditorFor(m => m.MyProperty, "TemplateName") to call it up.
Here is what my dropdownlist looks like in a normal view:
...
@Html.DropDownListFor
(m => m.MyProperty,
new SelectList(Model.MyPropertyList,
"Value", "Text"))
...
The above code works fine in my views, and if there is no solution I'll just keep re-using it. However, I have other dropdownlists I want to create and I want to put all dropdownlists in templates for reuse. I thought it would be better to have one dropdownlist EditorTemplate to rule them all. ;)
A: The trouble is that in order to generate a dropdown list you need 2 properties: a scalar property (MyProperty in your example) to bind the selected value to and a collection property (MyPropertyList in your example). Editor templates are suitable for single properties. So unless you define some generic class that will contain those 2 properties to represent a dropdown list and then define an editor template for this generic class your current code should work also fine.
A: Not the best solution, but
@Html.DropDownList(ViewData.TemplateInfo.FormattedModelValue.ToString(),
new SelectList(ViewData["GenericSelectionList"] as IList),
ViewData["Id"].ToString(), ViewData["Name"].ToString())
and then on your parent view (or where ever it should be called)
@html.EditorFor(x=> Model.ScalarProperty, new {GenericSelectionList =YourList, Id ="IdProperty", Name ="NameProperty"})
| |
doc_1872
|
http://paste.ubuntu.com/6824071/
but when I run 'gulp' in cli it just runs the tasks and quits. It dosen't stay to watch the files and recompile.
Ezras-MacBook-Air:no1fitness-sandbox Ezra$ gulp
[gulp] Using file /www/no1fitness-sandbox/gulpfile.js
[gulp] Working directory changed to /www/no1fitness-sandbox
[gulp] Running 'default'...
gulp.run() has been deprecated. Use task dependencies or gulp.watch task triggering instead.
[gulp] Running 'styles'...
[gulp] Finished 'default' in 8.2 ms
[gulp] Finished 'styles' in 1.85 s
Ezras-MacBook-Air:no1fitness-sandbox Ezra$
The only way I can make it do it is by removing the task around the gulp.watch function.
is this right? Are there better ways (that work)?
Then theres the warning about gulp.run, which I'm confused about as their own docs still seem to use it.
A: You aren't calling the watch task — you are running the default task:
[gulp] Running 'default'...
Run gulp watch to run your watch task.
A: I know that the question was answered right, but this post comes from Google while I was searching for my problem and the solution in my case is:
npm install gulp-watch
Hope this saves someone else time ^^
A: Another cause could be that the directory to watch does not contains any file. In that case 'gulp watch' stops immediately.
| |
doc_1873
|
Is it possible to replace the shared with an updated version?
I don't see any option to do that in the File menu, just renaming and editing the file description.
Google Docs works well to share and correct papers, but I'm finding it difficult to share and correct anything else. Thanks for any help!
A: I believe gmail now let's you attach/share updated files to email via Google Drive, and it always keeps the most up-to-date version available. So you can simply update your .do file on your desktop, keep the updated version on your Google Drive, and your students should get them.
http://gmailblog.blogspot.com/2012/11/gmail-and-drive-new-way-to-send-files.html
A: You can upload multiple versions of the same file. All the versions will be available for review later. To upload a new version, Just click on manage revisions (from where you are in your image) and a dialog will appear. Click on "upload new revision" and navigate to your updated file.
A: You can also consider Google Code (http://code.google.com; if you have a gmail account, you also have the Code account, or at least you can transparently create one from the main Google account), and work with your code using the standard code sharing, development and maintenance tools like Mercurial and its various interfaces. I have developed Stata code pretty much professionally, trust me that this is a much better tool than Google Docs (and any other real programmer here on SO would confirm that).
| |
doc_1874
|
*
*UI
*API
*Model
*Repository
*Common
*Database
In the above API has project dependency with Model,Repository and Common.
My Problem is Claim User (Using JWT Middle ware) need to inject to repository layer so that created_by and modified_by cannot be parameter from API layer code
A: You can get the loggedInUserId in your Repository Layer using IHttpContextAccessor as follows:
public class Repository
{
private readonly IHttpContextAccessor _httpContextAccessor;
public Repository(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void YourRepositoryMethod()
{
var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
// or
var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
}
}
Then you should register IHttpContextAccessor in the Startup class as follows:
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Or you can also register as follows
services.AddHttpContextAccessor();
}
| |
doc_1875
|
Schema of User and all related to it.
const answersSchema = new mongoose.Schema({
description: String,
code: String,
postDate: String
});
const questionsSchema=new mongoose.Schema({
title: String,
description: String,
code: String,
postDate: String,
answers: [answersSchema]
});
const blogpostsSchema=new mongoose.Schema({
title:String,
content:String,
postDate: String
});
const clientSchema= new mongoose.Schema({
email: String,
password: String,
googleId: String,
thumbnail: String,
blogPosts: [blogpostsSchema],
questions: [questionsSchema]
});
const Client = mongoose.model("Client",clientSchema);
const BlogPost= mongoose.model("BlogPost",blogpostsSchema);
const Answer = mongoose.model("Answer", answersSchema);
const Question =mongoose.model("Question",questionsSchema);
This is my query
Client.find({"blogPosts": {$exists: true}},function(err,foundUser){
if (foundUser){
console.log(foundUser)
res.render("blog",{userWithPosts: foundUser, clientStatus: clientStatus, logButton: logButton})
} else {
if(err){
console.log(err);
}
}
})
With this Query, there was a problem.
I want CLIENT Who has blogPosts,
how can I check whether the CLIENT has posts in blogPosts
| |
doc_1876
|
int main(){
int *x=(int*)malloc(sizeof(int)); // break here
*x=10;
free(x);
return 0;
}
I want to break at malloc. Here is what I try:
# gcc -g foo.c -o bar
# gdb bar
(gdb) b main
Breakpoint 1 at 0x80484cf: file src.c, line 7.
(gdb) r
Breakpoint 1, main () at src.c:7
(gdb) b malloc
Breakpoint 2 at 0x550944
(gdb) c
Program exited normally.
My system spec is:
*
*OS: CentOS 5.5
*gcc: gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52)
*gdb: GNU gdb (GDB) Red Hat Enterprise Linux (7.0.1-42.el5)
Please tell me where am I going wrong!!
A: I cannot reliably reproduce the error, but on Linux you could try breaking at __libc_malloc instead of malloc.
A: Resolved
Figured it out,
Actually breakpoint was being set in ld-linux.so instead of libc.so, could resolve it using:
*
*b __malloc
*b __libc_malloc
Thanks for looking into it!!
Though a new question would be:
how to ask gdb to set breakpoints only in a specific library (I know it can be done for a file)!!
| |
doc_1877
|
I have several classes, which are LitteralPart, Monome, Polynome and PolynomialFraction. They all have to be able to use each other, (i.e. Monome have to be able to owns methods which could return PolynomialFraction), but when I try to compile the program, I get around 400 like
"Polynome" does not name a type
"Monome" is not declared
"LitteralPart" is not declared in this scope
and so on.
Each of headers file are as the following :
#ifndef // Variable for the file
#define // Variable for the file
#include "includes.h" // Contains several includes like <QString> or <QVector>
#include // All others class headers
class Class
{
// Class definition
};
// Operators overloading
For example, here is the Polynome header with all errors in comment :
#ifndef POLYNOME_H
#define POLYNOME_H
#include "includes.h"
#include "monome.h"
#include "polynomialfraction.h"
#include "math.h"
class Polynome
{
public:
Polynome();
Polynome(QString polynome);
void setMonomeVector(QVector<Monome> monomeVector);
/*
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
*/
QVector<Monome> getMonomeVector()const;
/*
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
*/
int getConstantValue();
QStringList getLitteralParts() const;
void simplify();
void invert();
int getDegree() const;
QString toString()const;
void operator+=(Monome const& other);
/*
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
*/
void operator+=(Polynome const& other);
void operator-=(Monome const& other);
/*
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
*/
void operator-=(Polynome const& other);
void operator*=(int const& other);
/*
with "void operator*=(int const& other)";
with "void operator*=(int const& other)";
with "void operator*=(int const& other)";
with "void operator*=(int const& other)";
with "void operator*=(int const& other)";
*/
void operator*=(Monome const& other);
/*
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
*/
void operator*=(Polynome const& other);
void operator/=(int const& other);
/*
with "void operator/=(int const& other)";
with "void operator/=(int const& other)";
with "void operator/=(int const& other)";
with "void operator/=(int const& other)";
with "void operator/=(int const& other)";
*/
void operator/=(Monome const& other);
/*
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
*/
void operator/=(Polynome const& other);
void operator=(QString const& value);
void operator=(const char* value);
private:
QVector<Monome> monomeVector;
/*
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
"Monome" was not declared in this scope
template argument 1 is invalid
*/
};
Polynome operator+(Polynome const& a, Monome const& b);
/*
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
*/
Polynome operator+(Polynome const& a, Polynome const& b);
Polynome operator-(Polynome const& a, Monome const& b);
/*
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
*/
Polynome operator-(Polynome const& a, Polynome const& b);
Polynome operator*(Polynome const& a, int const& b);
Polynome operator*(int const& b, Polynome const& a);
Polynome operator*(Polynome const& a, int const& b);
Polynome operator*(Polynome const& a, Monome const& b);
/*
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
*/
Polynome operator*(Polynome const& a, Polynome const& b);
Polynome operator/(Polynome const& a, int const& b);
Polynome operator/(int const& b, Polynome const& a);
Polynome operator/(Polynome const& a, Monome const& b);
/*
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
*/
Polynome operator/(Monome const& b, Polynome const& a);
/*
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
"Monome" has not been declared
*/
Polynome operator/(Polynome const& a, Polynome const& b);
#endif // POLYNOME_H
There are the same problems in all others files.
All those files, except includes.h have been placed in a subdirectory of the project, but if I use #include "polynome.h", #include "variables/polynome.h" or even their absolute path, that changes nothing.
A: I have put (and renamed) all my classes declarations together, so I have :
#ifndef VARIABLESINCLUDE_H
#define VARIABLESINCLUDE_H
#include "includes.h"
#include "math.h"
class Litteral;
class Monomial;
class Polynomial;
class PolynomialFraction;
class Litteral
{
public:
Litteral();
Litteral(QString value);
QString toString() const;
void invert();
void setLitteral(QString litteral);
void setExposant(int exposant);
QString getLitteral() const;
int getExposant() const;
QString operator+(Litteral a);
private:
QString litteral;
int exposant;
};
bool operator==(Litteral const& a, Litteral const& b);
bool operator!=(Litteral const& a, Litteral const& b);
class Monomial
{
public:
Monomial();
Monomial(QString monome);
QStringList getLitterals() const;
QString toAbsoluteValueString() const;
QString toString() const;
void invert();
void operator*=(int other);
void operator*=(Litteral other);
void operator*=(Monomial other);
void operator/=(int const& other);
void operator/=(Litteral const& other);
void operator/=(Monomial const& other);
void setCoefficient(int coefficient);
void setLitteralVector(QVector<Litteral> litteralPartVector);
void addLitteral(Litteral litteralPart);
bool isNull() const;
int getMaxPower() const;
int getDegree() const;
int getCoefficient() const;
QVector<Litteral> getLitteralVector() const;
void simplify();
private:
QVector<Litteral> litteralPartVector;
int coefficient;
};
Monomial operator*(Monomial const& a, int const& b);
Monomial operator*(Monomial const& a, Litteral const& b);
Monomial operator*(Monomial const& a, Monomial const& b);
Monomial operator/(Monomial const& a, int const& b);
Monomial operator/(Monomial const& a, Litteral const& b);
Monomial operator/(Monomial const& a, Monomial const& b);
class Polynomial
{
public:
Polynomial();
Polynomial(QString polynome);
void setMonomialVector(QVector<Monomial> monomeVector);
QVector<Monomial> getMonomialVector()const;
int getConstantValue();
QStringList getLitterals() const;
void simplify();
void invert();
int getDegree() const;
QString toString()const;
void operator+=(Monomial const& other);
void operator+=(Polynomial const& other);
void operator-=(Monomial const& other);
void operator-=(Polynomial const& other);
void operator*=(int const& other);
void operator*=(Monomial const& other);
void operator*=(Polynomial const& other);
void operator/=(int const& other);
void operator/=(Monomial const& other);
void operator/=(Polynomial const& other);
void operator=(QString const& value);
void operator=(const char* value);
private:
QVector<Monomial> monomeVector;
};
Polynomial operator+(Polynomial const& a, Monomial const& b);
Polynomial operator+(Polynomial const& a, Polynomial const& b);
Polynomial operator-(Polynomial const& a, Monomial const& b);
Polynomial operator-(Polynomial const& a, Polynomial const& b);
Polynomial operator*(Polynomial const& a, int const& b);
Polynomial operator*(int const& b, Polynomial const& a);
Polynomial operator*(Polynomial const& a, int const& b);
Polynomial operator*(Polynomial const& a, Monomial const& b);
Polynomial operator*(Polynomial const& a, Polynomial const& b);
Polynomial operator/(Polynomial const& a, int const& b);
Polynomial operator/(int const& b, Polynomial const& a);
Polynomial operator/(Polynomial const& a, Monomial const& b);
Polynomial operator/(Monomial const& b, Polynomial const& a);
Polynomial operator/(Polynomial const& a, Polynomial const& b);
class PolynomialFraction
{
public:
PolynomialFraction();
PolynomialFraction(Polynomial numerator);
PolynomialFraction(Polynomial numerator, Polynomial denominator);
PolynomialFraction(QString numerator);
PolynomialFraction(QString numerator, QString denominator);
PolynomialFraction(const char* numerator);
PolynomialFraction(const char* numerator, const char* denominator);
QString toString() const;
void invert();
Polynomial getNumerator() const;
Polynomial getDenominator() const;
void setNumerator(Polynomial numerator);
void setDenominator(Polynomial denominator);
void operator+=(int const& other);
void operator+=(Monomial const& other);
void operator+=(Polynomial const& other);
void operator+=(PolynomialFraction const& other);
void operator-=(int const& other);
void operator-=(Monomial const& other);
void operator-=(Polynomial const& other);
void operator-=(PolynomialFraction const& other);
void operator*=(int const& other);
void operator*=(Monomial const& other);
void operator*=(Polynomial const& other);
void operator*=(PolynomialFraction const& other);
void operator/=(int const& other);
void operator/=(Monomial const& other);
void operator/=(Polynomial const& other);
void operator/=(PolynomialFraction const& other);
void operator=(QString const& value);
void operator=(char* const value);
private:
Polynomial numerator, denominator;
};
PolynomialFraction operator+(PolynomialFraction const& a, int const& b);
PolynomialFraction operator+(PolynomialFraction const& a, Monomial const& b);
PolynomialFraction operator+(PolynomialFraction const& a, Polynomial const& b);
PolynomialFraction operator+(int const& b, PolynomialFraction const& a);
PolynomialFraction operator+(Monomial const& b, PolynomialFraction const& a);
PolynomialFraction operator+(Polynomial const& b, PolynomialFraction const& a);
PolynomialFraction operator+(PolynomialFraction const& a, PolynomialFraction const& b);
PolynomialFraction operator-(PolynomialFraction const& a, int const& b);
PolynomialFraction operator-(PolynomialFraction const& a, Monomial const& b);
PolynomialFraction operator-(PolynomialFraction const& a, Polynomial const& b);
PolynomialFraction operator-(int const& b, PolynomialFraction const& a);
PolynomialFraction operator-(Monomial const& b, PolynomialFraction const& a);
PolynomialFraction operator-(Polynomial const& b, PolynomialFraction const& a);
PolynomialFraction operator-(PolynomialFraction const& a, PolynomialFraction const& b);
PolynomialFraction operator*(PolynomialFraction const& a, int const& b);
PolynomialFraction operator*(PolynomialFraction const& a, Monomial const& b);
PolynomialFraction operator*(PolynomialFraction const& a, Polynomial const& b);
PolynomialFraction operator*(int const& b, PolynomialFraction const& a);
PolynomialFraction operator*(Monomial const& b, PolynomialFraction const& a);
PolynomialFraction operator*(Polynomial const& b, PolynomialFraction const& a);
PolynomialFraction operator*(PolynomialFraction const& a, PolynomialFraction const& b);
PolynomialFraction operator/(PolynomialFraction const& a, int const& b);
PolynomialFraction operator/(PolynomialFraction const& a, Monomial const& b);
PolynomialFraction operator/(PolynomialFraction const& a, Polynomial const& b);
PolynomialFraction operator/(int const& b, PolynomialFraction const& a);
PolynomialFraction operator/(Monomial const& b, PolynomialFraction const& a);
PolynomialFraction operator/(Polynomial const& b, PolynomialFraction const& a);
PolynomialFraction operator/(PolynomialFraction const& a, PolynomialFraction const& b);
#endif // VARIABLESINCLUDE_H
Then, in all .cpp files, I replaced #include "polynome.h" by #include "variablesinclude.h". That solved the problem.
| |
doc_1878
|
require(zoo)
# random hourly data over 30 days for five series
x <- matrix(rnorm(24 * 30 * 5),ncol=5)
# Assign hourly data with a real time and date
x.DateTime <- as.POSIXct("2014-01-01 0100",format = "%Y-%m-%d %H") +
seq(0,24 * 30 * 60 * 60, by=3600)
# make a zoo object
x.zoo <- zoo(x, x.DateTime)
#plot(x.zoo)
# what I want:
# the average value for each series at 1am, 2am, 3am, etc. so that
# the dimensions of the output are 24 (hours) by 5 (series)
# If I were just working on x I might do something like:
res <- matrix(NA,ncol=5,nrow=24)
for(i in 1:nrow(res)){
res[i,] <- apply(x[seq(i,nrow(x),by=24),],2,mean)
}
res
# how can I avoid the loop and write an aggregate statement in zoo that
# will get me what I want?
A: Calculate the hour for each time point and then aggregate by that:
hr <- as.numeric(format(time(x.zoo), "%H"))
ag <- aggregate(x.zoo, hr, mean)
dim(ag)
## [1] 24 5
ADDED
Alternately use hours from chron or hour from data.table:
library(chron)
ag <- aggregate(x.zoo, hours, mean)
A: This is quite similar to the other answer but takes advantage of the fact the the by=... argument to aggregate.zoo(...) can be a function which will be applied to time(x.zoo):
as.hour <- function(t) as.numeric(format(t,"%H"))
result <- aggregate(x.zoo,as.hour,mean)
identical(result,ag) # ag from G. Grothendieck answer
# [1] TRUE
Note that this produces a result identical to the other answer, not not the same as yours. This is because your dataset starts at 1:00am, not midnight, so your loop produces a matrix wherein the 1st row corresponds to 1:00am and the last row corresponds to midnight. These solutions produce zoo objects wherein the first row corresponds to midnight.
| |
doc_1879
|
<form action="" method="post" enctype="multipart/form-data" name="form1" id="genericForm">
<fieldset>
<p>Filter Rating</p>
<select name="value">
<option value="1">One Star</option>
<option value="2">Two Stars</option>
<option value="3">Three Stars</option>
<option value="4">Four Stars</option>
<option value="5">Five Stars</option>
</select>
</div>
<input type="submit" name="Submit" value="Submit"><br />
</form>
The php :
<?php
$Link = mysql_connect($Host, $User, $Password);
if($_POST['value'] == '1') {
// query to get all 1 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='1'";
}
elseif($_POST['value'] == '2') {
// query to get all 2 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='2'";
}
elseif($_POST['value'] == '3') {
// query to get all 3 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='3'";
}
elseif($_POST['value'] == '4') {
// query to get all 4 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='4'";
}
elseif($_POST['value'] == '5') {
// query to get all 5 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='5'";
}
WHILE($board = mysql_fetch_array($result)):
$title = $board['title'];
$studio = $board['studio'];
$language = $board['language'];
$certification = $board['certification'];
echo '
Title : '.$title.'<br />
Studio : '.$studio.'<br />
Language : '.$language.'<br />
Certification : '.$certification.'<br />
;
endwhile;
?>
A: Try it this way, assuming you're already connected and have selected DB and that you're using your entire code inside the same file, since you are using action=""; this denotes executing as "self".
You also are not executing mysql_query() which I have added below.
Be sure to change xxx below with your DB credentials and your_db to your database's name.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$Host = "xxx";
$User = "xxx";
$Password = "xxx";
$Link = mysql_connect($Host, $User, $Password);
$db_selected = mysql_select_db('your_db', $Link);
if (!$db_selected) {
die ('Can\'t use that DB : ' . mysql_error());
}
if(isset($_POST['Submit'])){
if($_POST['value'] == '1') {
// query to get all 1 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='1'");
}
elseif($_POST['value'] == '2') {
// query to get all 2 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='2'");
}
elseif($_POST['value'] == '3') {
// query to get all 3 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='3'");
}
elseif($_POST['value'] == '4') {
// query to get all 4 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='4'");
}
elseif($_POST['value'] == '5') {
// query to get all 5 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='5'");
}
WHILE($board = mysql_fetch_array($query)){
$title = $board['title'];
$studio = $board['studio'];
$language = $board['language'];
$certification = $board['certification'];
echo '
Title : '.$title.'<br />
Studio : '.$studio.'<br />
Language : '.$language.'<br />
Certification : '.$certification.'<br />';
}
} // brace for if(isset($_POST['Submit']))
?>
</div>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="genericForm">
<fieldset>
<p>Filter Rating</p>
<select name="value">
<option value="1">One Star</option>
<option value="2">Two Stars</option>
<option value="3">Three Stars</option>
<option value="4">Four Stars</option>
<option value="5">Five Stars</option>
</select>
</div>
<input type="submit" name="Submit" value="Submit"><br />
</form>
Note:
This enctype="multipart/form-data" isn't required if it's not going to be used to upload files.
A: If im not mistaken this is what you want? you just need to loop through the row in the tables and fetch it.
<div class="form">
<?php
$Link = mysql_connect($Host, $User, $Password);
$Query = "select * from books where product = 'hannibal' AND book = '1'";
$result = mysql_query($Query);
while ($row = mysql_fetch_array($result)) {
$subject = $row['subject'];
$username = $row['username'];
$date = $row['date'];
$comments = $row['comments'];
?>
<h1>Subject : <?php echo $subject;?>
Posted by <?php echo $username;?> on <?php echo $date;?></h1><br />
<?php echo $comments;?>'; <br />
<?php
}
?>
</div>
| |
doc_1880
|
*
*External application communicates with native host
*Native host communicates with extension
So far I have the extension and the native host working, however I noticed that connecting to the native host via the extension opens a new instance of the host, regardless of whether or not the host was already running. This is a problem as I'd like the host to run persistently in order to receive messages from an external application.
I tried different methods of connecting to the host including runtime.connectNative() and runtime.sendNativeMessage(), but they both produce the same behavior (starting new host instance). At this point I'm thinking of abandoning direct communication and using something more indirect like creating a local file and having the extension constantly read it, although I doubt that would work as the service worker gets killed after a certain time, and using the content script would make the extension laggy. Any help would be greatly appreciated.
A: You need to re-use the port returned by runtime.connectNative() if you want to talk to the same native host instance. Every call to runtime.connectNative() or runtime.sendNativeMessage() will open a new instance of the native host.
// background script (in chrome extension)
// save port as a global variable (so we can target the same instance of native host)
let port;
function sendMessage(yourMessage) {
if (!port) {
// this will run the first time to launch the native host, and save the connection to that instance in the port
port = chrome.runtime.connectNative('yourNativeHostId');
}
port.postMessage(yourMessage);
}
sendMessage('message 1');
sendMessage('message 2');
sendMessage('message 3');
// ^ they should all be delivered to the same instance of native host
| |
doc_1881
|
I am doing 6 requests OnInit() however, some of the requests finish before another, the order matters. Is it possible to await an observable in typescrypt? All functions look the same, they just make a different request to the server.
Thanks for the help :)
Here's my code:
I managed to achieve it by chaining the request( calling next request after I get the response from the previous one, however, that solution was not efficient and looked ugly)
ngOnInit() {
this.userId = this.auth.getUserId();
this.getTrendingRentals();
this.getFollowingRentals();
...
this.getLuxuryRentals();
//console.log(this.totalRentals);
}
private getTrendingRentals() {
const rentalObservable = this.rentalService.getRentals();
//Subscribe to service observer
rentalObservable.subscribe((rentals: Rental[]) => {
this.trendingRentals = rentals;
this.totalRentals.push(this.trendingRentals);
}, (err) => {
}, () => {
});
}
public getLuxuryRentals(): Observable<any>{
return this.http.get('/api/v1/rentals/luxury');
}
A: you can use switchMap in the pipe to use the result of the first observable in the subsequent observable.
of("Hello").pipe(
switchMap(result => of(result + ", World")),
switchMap(result => of(result + "!")),
)
.subscribe(console.log);
// output: Hello, World!
but if you don't need the result of the previous observable and just want to trigger observables in a specific order, you can use concat which waits for every observable to complete before triggering the next observable:
concat(
of(1).pipe(delay(2000)),
of(2).pipe(delay(500)),
of(3).pipe(delay(1000))
)
.subscribe(console.log);
// output: 1 2 3
A: Methods that are fetching data shouldn't return subscriptions but return observables,
private getTrendingRentals() {
return this.rentalService.getRentals();
}
rxjs provides few functions to address this kind of problem. Take a look at functions: merge, mergeMap, switchMap, concatMap.
For example:
this.auth.getUserId().pipe(
mergeMap(userId => this.getTrendingRentals()),
mergeMap(trendingRentals => this.getFollowingRentals()),
mergeMap(followingRentals => this.getFollowingRentals()),
mergeMap(luxuryRentals => this.getLuxuryRentals())
).subscribe(...)
or
this.auth.getUserId().pipe(
mergeMap(userId => this.getTrendingRentals()),
mergeMap(trendingRentals => merge(this.getFollowingRentals(), this.getFollowingRentals(), this.getLuxuryRentals()))
).subscribe(...)
Dependence on your particular needs.
Update:
@jcal solution with concat looks better :)
| |
doc_1882
|
On the page I am trying to test I have a dropdown with states that are available to select. I am simply trying to verify that all of the states that are expected are in fact displayed.
I've recorded my steps and then added a verify text command, set the target and added my text (The text is the values in the drop down).
I run that validation and the test fails saying actual value (Let's say X) does not match (let's say X).
As far as I can see, the text matches exactly so I am not sure what else to do.
Any help would be greatly appreciated.
A: Please check first if the text added by you is same as the actual text (in terms of case-sensitivity and spacing).
Also it would be helpful if you can share the screenshot of your script or/else the script itself by exporting it.
| |
doc_1883
|
document.querySelector('.js-delete').addEventListener('click', function(e) {
event(e, trigger);
});
function event(e, callback) {
e.target.addEventListener('transitionend', function(e) {
e.target.removeEventListener(e.type, arguments.callee);
callback(e);
});
}
function trigger(e) {
alert("DONE");
}
.js-delete {
-webkit-transition: width .3s;
transition: width .3s;
width: 100px;
}
.js-delete:hover {
width: 100%;
}
<button class="js-delete">Delete</button>
Where, I have event listener on click, and after this click one more event inside, which triggers after transition is ends, and alert message should be visible.
Everything, is ok. But the question is, when i click more than 1 time, before transition ended, I will have same number of alert messages.
So, I want to get, just one alert independently, how many time I click to my button.
Thanks!
A: I wouldn't use arguments.callee, it's deprecated (will not work with 'strict mode').
Just use named functions for event handlers instead of anonymous and it will be easier to remove them.
Also some wrapper function to add the event handlers again.
// Start application lifecycle by registering click event
registerClickHandler();
function registerClickHandler() {
document.querySelector('.js-delete').addEventListener('click', clickHandler);
}
function clickHandler(e) {
// Immediatley remove click event handler after event fired
e.target.removeEventListener(e.type, clickHandler);
// Register transition event handler
registerTransitionHandler(e);
}
function registerTransitionHandler(e) {
e.target.addEventListener('transitionend', transitionHandler);
}
function transitionHandler(e) {
// Immediately remove transitionend event handler after event fired
e.target.removeEventListener(e.type, transitionHandler);
// Register click event again
registerClickHandler();
// Run callback at transitionend event
transitionEndCallback(e);
}
function transitionEndCallback(e) {
alert("DONE");
}
.js-delete {
-webkit-transition: width .3s;
transition: width .3s;
width: 100px;
}
.js-delete:hover {
width: 100%;
}
<button class="js-delete">Delete</button>
A: This seems like a hack to me but I added a variable busy that I toggle so it won't be called if it's been called already
var busy=false;
document.querySelector('.js-delete').addEventListener('click', function(e) {
if(!busy){
busy=true;
event(e, trigger);
}
});
function event(e, callback) {
e.target.addEventListener('transitionend', function(e) {
e.target.removeEventListener(e.type, arguments.callee);
callback(e);
});
}
function trigger(e) {
alert("DONE");
busy=false;
}
.js-delete {
-webkit-transition: width .3s;
transition: width .3s;
width: 100px;
}
.js-delete:hover {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="js-delete">Delete</button>
A: You're adding multiple event listeners to transitionend every time you click the delete button. I've tweaked your code so see if this works:
var clickHandler = function(e) {
event(e, trigger);
}
document.querySelector('.js-delete').addEventListener('click',clickHandler);
function event(e, callback) {
e.target.addEventListener('transitionend', function(e) {
e.target.removeEventListener(e.type, arguments.callee);
callback(e);
});
}
function trigger(e) {
alert("DONE");
e.target.removeEventListener(e.type, clickHandler);
}
A: this is happening because each time you click the button, you are registering a new eventListener with 'transitionend' ... tbh, I''m not sure why you have this anyway. Modify your code to this:
function event(e, callback) {
e.target.removeEventListener(e.type, arguments.callee);
callback(e);
}
| |
doc_1884
|
XYZ LLC INC1 INC2 INC1
ABC Inc INC4 INC1 INC2 INC1
ZZZ InC INC
Result
Name Combine
XYZ LLC INC1,INC2
ABC Inc INC4,INC1,INC2
ZZZ Inc INC
A: Use a simple TEXTJOIN:
=TEXTJOIN(",",TRUE,B2:E2)
| |
doc_1885
|
something like this
Strangely, it is only displaying one particle on canvas. I am debugging with console.log(vertices), but it clearly shows all the vertices in the array.
My code in CodeSandBox
A: The problem is with your loop. You're assigning a value to theta and phi only once outside your loop, then you give the same value to all 1600 vertices:
const theta = Math.acos(THREE.Math.randFloatSpread(2));
const phi = THREE.Math.randFloatSpread(360);
for (let i = 0; i < 1600; i++) {
const vertex = new THREE.Vector3();
vertex.x = distance * Math.sin(theta) * Math.cos(phi);
vertex.y = distance * Math.sin(theta) * Math.sin(phi);
vertex.z = distance * Math.cos(theta);
vertices.push(vertex.x, vertex.y, vertex.z);
}
When you use console.log(vertices), look at the x, y, z values and you'll see they all repeat.
What you should do is re-assign a new theta and a new phi inside the loop, so each vertex gets a unique position:
let theta, phi;
let x, y, z;
for (let i = 0; i < 1600; i++) {
theta = Math.acos(THREE.Math.randFloatSpread(2));
phi = THREE.Math.randFloatSpread(360);
x = distance * Math.sin(theta) * Math.cos(phi);
y = distance * Math.sin(theta) * Math.sin(phi);
z = distance * Math.cos(theta);
vertices.push(x, y, z);
}
You also don't need to create a THREE.Vector3() on each iteration, it's pretty inefficient to create 1600 Vector3s just to be discarded immediately. Instead you can re-use the same x, y, z variables to avoid all those object construction costs.
See here for a working demo of your example. I also scaled down the point size to 1.
A: Just a small remark, not the answer (all kudos to @Marquizzo)
Since r133, there is a method .randomDirection() of THREE.Vector3(), which helps us to set points on a sphere in a more convenient way.
Thus, all the code for instantiating of particles is:
const distance = Math.min(200, window.innerWidth / 16);
let vertices = new Array(1600).fill().map((v) => {
return new THREE.Vector3().randomDirection().setLength(distance);
});
const geometry = new THREE.BufferGeometry().setFromPoints(vertices);
const material = new THREE.PointsMaterial({ color: 0xffffff, size: 1 });
const particles = new THREE.Points(geometry, material);
Demo
| |
doc_1886
|
Can someone show me the necessary steps to achieve this in a basic Laravel project?
A: Laravel comes with 2 frontend package managers: npm and yarn
npm
npm i mdbootstrap
yarn
yarn add mdbootstrap
After this your package is located in the node_modules directory.
You can import sass files and let the js be combined from packages to vendor.js.
You can configure what gets transpiled to where using webpack.mix.js
Running npm run dev will start the transpiling.
If you want to install mdbootstrap pro, you should follow these steps
*
*get a license and mail [email protected] requesting access to their git repo (as they have not automated this)
*generate an access token on gitlab
*run
npm install git+https://oauth2:[TOKEN]@git.mdbootstrap.com/mdb/[REPO].git --save
Where [TOKEN] is your token from step 2 and [REPO] is the one you need from the choices jquery, angular, vue or react. You can find the exact urls by visiting git.mdbootstrap.com and choosing the right project. In the top right corner find the clone button and copy the https link.
A: If you don't want to use CLI /NPM there is an easy way to import MDBootstrap in to Laravel.
Simply copy the mdb.min.js and mdb.min.js.map to your public/js folder.
Next copy the mdb css files (there should be around 8 of them) to your public/css folder.
Now in the HTML blade files (I use a head blade include file for this) add the following:
<!-- import MDB Pro -->
<link rel="stylesheet" href="/css/mdb.min.css" />
...then just before your closing BODY tag (I use a "foot" blade include), add the following:
<!-- import Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet">
<!-- import Material Icons from Google Fonts -->
<link rel="stylesheet" href="//fonts.googleapis.com/icon?family=Material+Icons">
<!-- import the MDB javascript file https://mdbootstrap.com/ -->
<script type="text/javascript" src="{{ asset('js/mdb.min.js') }}"></script>
...just remember to update the files when new releases occur. Because it won't happen automatically without NPM.
| |
doc_1887
|
What are the means for that? Refection? Compiler API?
I can do
package tests;
public class TryReflection02 {
interface A {
}
public static void main(String[] args) {
Object o = new A() {};
System.out.println( o.toString() );
o = A.class.newInstance() // exception
}
}
Can I do the same having A.class value?
A: No, you can't. A is an interface, and only classes can be instantiated.
What you can do is to use a library/helper that uses some trickery to create a class that implements the interface and instantiates that. The JDK's Proxy class contains static methods to do just that. There are also tools that can do it which are custom-geared for test-related use cases: mockito, for instance.
These tools do exactly what you hint at in this question's title: rather than instantiating the interface, they generate a new class that implements the interface, and then instantiate that class.
| |
doc_1888
|
i tryed to do but no example in internet..
So if you got one can you share or can you give me opinion ??
my code is this but not support multitouch
package multi.touch;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.Button;
import android.widget.TextView;
public class baslat extends Activity implements OnTouchListener {
TextView yazi;
TextView bir,iki;
Button buton1,buton2;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
yazi=(TextView)findViewById(R.id.textView1);
bir=(TextView)findViewById(R.id.textView2);
iki=(TextView)findViewById(R.id.textView3);
buton1=(Button)findViewById(R.id.button1);
buton2=(Button)findViewById(R.id.button2);
buton2.setOnTouchListener(this);
buton1.setOnTouchListener(this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
yazi.setText(String.valueOf(event.getPointerCount()+"\n\n"));
bir.setText(String.valueOf("Birinci "
+ (int)event.getX(0)+"\n\n"+(int)event.getY(0)));
iki.setText(String.valueOf("Ikinci"+
(int)event.getX(1)+"\n\n"+(int)event.getY(1)));
//buton2.setLayoutParams(new
LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,
(int)event.getX(0),
(int)event.getY(0))); return
super.onTouchEvent(event);
} @Override public boolean onTouch(View v, MotionEvent event) {
Button fds=(Button)v;
return false; }
}
A: Old question but I was running my head in the wall with this problem until I finally came across just setting
android:splitMotionEvents="true"
on the layout view that contains the button views, which allows for multiple buttons to be pressed, which I found digging in the ApiDemos that are available in the sdk demos download
A: In the Android UI framework, all touch events belong to the View where the touch originated. So if you touch your Button, all touch events are processed through that Button until you lift your finger up; this includes other touch pointers for multi-touch. In my experience the only way to achieve multi-touch across separate View objects (your 2 Buttons), is to capture all touch events in one View that covers the whole screen, and delegate the touch events yourself. It's a bit of work, but it can be done.
An example might be to include an ImageView that fills the screen but has no Drawable source (or it's completely transparent). Put this on top of your other elements (perhaps with a FrameLayout), and in the onTouchEvent() method of the ImageView, analyze the touch coordinates, and pass the touch event down to the correct button. This gets rather complicated with multiple touch pointers, but as far as I know, it's the only way to pass touch events to separate View objects.
A: I was a little bored with this subject and i made an handler class for leading with multitouch buttons. Feel free to use and/or update that.
//CLASS TO HANDLE THE EVENT
public class MultitouchButtonHandler {
ArrayList<View> views_info = new ArrayList<View>();
public MultitouchButtonHandlerResult onTouchEvent(View v, MotionEvent ev) {
//GET EVENT INFO
final int action = ev.getAction();
int action_masked = action & MotionEvent.ACTION_MASK;
if(action_masked==MotionEvent.ACTION_MOVE){
return null;
}
//GET ABSOLUTE SIZE AND CHECK IF THIS ANY VIEW ATTACHED TO THIS POSITION
final int original_location[] = { 0, 0 };
v.getLocationOnScreen(original_location);
final int actionPointerIndex = ev.getActionIndex();
float rawX = (int) ev.getX(actionPointerIndex) + original_location[0];
float rawY = (int) ev.getY(actionPointerIndex) + original_location[1];
View eventView = getViewByLocation((int)rawX, (int)rawY);
if(eventView==null) return null;
MultitouchButtonHandlerResult result = new MultitouchButtonHandlerResult();
result.view = eventView;
//CHECK WHAT KIND OF EVENT HAPPENED
switch (action_masked) {
case MotionEvent.ACTION_DOWN: {
result.event_type = MotionEvent.ACTION_DOWN;
return result;
}
case MotionEvent.ACTION_UP: {
result.event_type = MotionEvent.ACTION_UP;
return result;
}
case MotionEvent.ACTION_CANCEL: {
result.event_type = MotionEvent.ACTION_CANCEL;
return result;
}
case MotionEvent.ACTION_POINTER_UP: {
result.event_type = MotionEvent.ACTION_UP;
return result;
}
case MotionEvent.ACTION_POINTER_DOWN: {
result.event_type = MotionEvent.ACTION_DOWN;
return result;
}
default:
break;
}
return null;
}
public void addMultiTouchView(View v){
views_info.add(v);;
}
public void removeMultiTouchView(View v){
views_info.remove(v);;
}
public View getViewByLocation(int x, int y){
for(int key=0; key!= views_info.size(); key++){
View v = views_info.get(key);
//GET BUTTON ABSOLUTE POSITION ON SCREEN
int[] v_location = { 0, 0 };
v.getLocationOnScreen(v_location);
//FIND THE BOUNDS
Point min = new Point(v_location[0], v_location[1]);
Point max = new Point(min.x + v.getWidth(), min.y + v.getHeight());
if(x>=min.x && x<=max.x && y>=min.y && y<=max.y){
//Log.d("mylog", "***Found a view: " + v.getId());
return v;
}
}
//Log.d("mylog", "Searching: " + x +", " + y + " but not found!");
return null;
}
}
//CLASS TO FULLFILL WITH RESULT
public class MultitouchButtonHandlerResult {
public View view;
public int event_type;
}
//In your view
private OnTouchListener listener_touch_button = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
MultitouchButtonHandlerResult result=multitouch_handler.onTouchEvent(v, event);
if(result==null) return true;
switch(result.event_type){
case MotionEvent.ACTION_DOWN:
Log.d("mylog", "DOWN");
break;
case MotionEvent.ACTION_UP:
Log.d("mylog", "UP");
break;
case MotionEvent.ACTION_CANCEL:
Log.d("mylog", "CANCEL");
break;
}
Log.d("mylog", "View ID: " + result.view.getId());
return false;
}
};
A: Did you check this link -
How to use Multi-touch in Android 2
http://www.zdnet.com/blog/burnette/how-to-use-multi-touch-in-android-2/1747
How to code for multitouch
| |
doc_1889
|
Why would this code (with ===) return error "TypeError: Cannot read property 'ID' of undefined":
dndetail.controller('dndetailCtrl', ['$rootScope', '$scope', '$routeParams', '$localStorage', function ($rootScope, $scope, $routeParams, $localStorage) {
var mjav = [];
$scope.$storage = $localStorage;
var lslist = $scope.$storage.dnlist;
var id = $routeParams.dnid;
$scope.$storage.test1 = $scope.$storage.dnlist[1].ID;
for (var i = 0; i <= $scope.$storage.dnlist.length; i++) {
if ($scope.$storage.dnlist[i].ID === id) {
$scope.data = $scope.$storage.dnlist[i];
break;
}
}
//$scope.data = $rootScope.dnlist[$rootScope.getIndex($routeParams.dnid)];
}]);
And the code with == works as expected. I'm a relatively new Javascript user (3months), before I had some experience with VB/C#.net.
EDIT: forgot to mention I have tested both variables with typeof and they both return integer.
A: Let's break this down a bit to make sense of it.
*
*The error - TypeError: Cannot read property 'ID' of undefined is applicable when using both the == (type conversion comparison) and the === (strict comparison) because there seems to be an issue with $scope.$storage.dnlist[i].ID. But due to the difference between the two comparisons the problem is being masked when using the == (type conversion comparison).
*== is a loosely equal to or non strict check, it will use type conversion to convert both values to the same type before checking if they are equal. In your scenario because $scope.$storage.dnList[i].ID is returning undefined. undefined is considered a falsy value in JavaScript (converts to false when coerced) so when the == comparison uses type conversion, in this instance, undefined is being coerced (forced) to a 0 as this is another falsy value. Now that both values are integers it can perform it's equality check
*=== on the other hand is a strict equality check meaning that no type conversions are made. It will simply check if both values are exactly equal in both type and value. Which in this case is no, one is an integer and one is undefined and therefore your error is thrown.
More info on equality checks here and truthy and falsy values here.
A: In your for loop you seem to be starting the index from 0 and using <= instead use:
for (var i = 0; i < $scope.$storage.dnlist.length; i++) { ... }
A: Do you understand that $scope.$storage.dnlist[i] is not defined (does not exist) so you can not reference the id property of it?
To me, the issue is that you are going through your loop one too many times and on the last time through $scope.$storage.dnlist[i] does not exist and js throws the exception when you try to reference the id property of a non-existent object.
The comparison in your for statement should be "i<" rather than "i<=" so you do not go past the end of the array.
| |
doc_1890
|
I'm writing against API 7 and cannot switch to API 11 or above to use getType method (this is not my project and this are the requirements).
The problem is that I cannot create an instance of this class like a normal cursor. How is it done? I've tried casting it:
SQLiteCursor cursor = (SQLiteCursor)mDbHelper.getWritableDatabase().rawQuery(query,null);
but all I get is a ClassCastException. Documentation states that SQLiteCursor is "A Cursor implementation that exposes results from a query on a SQLiteDatabase". So how can I get it if SQLiteDatabases rawQuery and query methods all return Cursor which cannot be cast?
I really need to somehow get the type of data in columns, so I know how to cast them (I never a priori know them, because all the tables are very generic). Is there a simple way to get to this methods or should I make some workaround?
Thanks for any suggestions,
kajman
A: Try to use like below
SQLiteDatabase myDB = this.openOrCreateDatabase("dbname", SQLiteDatabase.OPEN_READWRITE, null);
Cursor c = myDB.rawQuery("select Name from contacts ", null);
| |
doc_1891
|
<ul className="navbar-nav my-2 my-lg-0">
{
settings !== null &&
<li className="nav-item">
<a className="nav-link" href={settings.facebook.url}>Facebook</a>
</li>
}
{
settings !== null &&
<li className="nav-item">
<a className="nav-link" href={settings.twitter.url}>Articles</a>
</li>
}
</ul>
However, since the settings object is retrieved by an Ajax call to the database, this is asynchronous and I have to make sure that `settings exists before making it showing up some datas.
My question is, since the following doesn't work:
<ul className="navbar-nav my-2 my-lg-0">
{
settings !== null &&
<li className="nav-item">
<a className="nav-link" href={settings.facebook.url}>Facebook</a>
</li>
<li className="nav-item">
<a className="nav-link" href={settings.twitter.url}>Articles</a>
</li>
}
</ul>
Is there any way to make one verification for multiple React elements?
Thank you in advance
A: The elements returned if the condition passes need to be wrapped inside a single element, such as <div> or, as @kunukn suggests <React.Fragment>
<ul>
{
setting !== null && (
<React.Fragment>
<li className="nav-item">
<a className="nav-link" href={settings.facebook.url}>Facebook</a>
</li>
<li className="nav-item">
<a className="nav-link" href={settings.twitter.url}>Articles</a>
</li>
</React.Fragment>
)
}
</ul>
A: you can use an array to return multiple elements
<ul className="navbar-nav my-2 my-lg-0">
{
settings !== null ?
[
<li key={'anything_1'} className="nav-item">
<a className="nav-link" href={settings.facebook.url}>Facebook</a>
</li>,
<li key={'anything_2'} className="nav-item">
<a className="nav-link" href={settings.twitter.url}>Articles</a>
</li>
]
:
null
}
</ul>
| |
doc_1892
|
here are some references to the effect I am trying to achieve:
https://randellcommercial.uk/ - plugins.
https://1til1landskab.dk/ - really nice, also it changes background colour too which is cool.
http://adasokol.com/works/ - bit mental, but you get the idea.
this is what I have been basing my efforts off. however, it seems there is so much unnecessary code. I've been trimming it down and ended up with this. However, it's no good. it's glitchy and feels over-engineered.
document.documentElement.className = "js";
var supportsCssVars = function() {
var e,
t = document.createElement("style");
return (
(t.innerHTML = "root: { --tmp-var: bold; }"),
document.head.appendChild(t),
(e = !!(
window.CSS &&
window.CSS.supports &&
window.CSS.supports("font-weight", "var(--tmp-var)")
)),
t.parentNode.removeChild(t),
e
);
};
{
const mapNumber = (X, A, B, C, D) => ((X - A) * (D - C)) / (B - A) + C;
const getMousePos = (e) => {
let posx = 0;
let posy = 0;
if (!e) e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
} else if (e.clientX || e.clientY) {
posx =
e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy =
e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
return {
x: posx,
y: posy
};
};
// Generate a random float.
const getRandomFloat = (min, max) =>
(Math.random() * (max - min) + min).toFixed(2);
class HoverImgFx2 {
constructor(el) {
this.DOM = {
el: el
};
this.DOM.reveal = document.createElement("div");
this.DOM.reveal.className = "hover-reveal";
this.DOM.reveal.innerHTML = `<div class="hover-reveal__inner"><div class="hover-reveal__img" style="background-image:url(${this.DOM.el.dataset.img})"></div></div>`;
this.DOM.el.appendChild(this.DOM.reveal);
this.DOM.revealInner = this.DOM.reveal.querySelector(".hover-reveal__inner");
this.DOM.revealInner.style.overflow = "hidden";
this.DOM.revealImg = this.DOM.revealInner.querySelector(
".hover-reveal__img"
);
this.initEvents();
}
initEvents() {
this.positionElement = (ev) => {
const mousePos = getMousePos(ev);
const docScrolls = {
left: document.body.scrollLeft + document.documentElement.scrollLeft,
top: document.body.scrollTop + document.documentElement.scrollTop
};
this.DOM.reveal.style.top = `${mousePos.y + 20 - docScrolls.top}px`;
this.DOM.reveal.style.left = `${mousePos.x + 20 - docScrolls.left}px`;
};
this.mouseenterFn = (ev) => {
this.positionElement(ev);
this.showImage();
};
this.mousemoveFn = (ev) =>
requestAnimationFrame(() => {
this.positionElement(ev);
});
this.mouseleaveFn = () => {
this.hideImage();
};
this.DOM.el.addEventListener("mouseenter", this.mouseenterFn);
this.DOM.el.addEventListener("mousemove", this.mousemoveFn);
this.DOM.el.addEventListener("mouseleave", this.mouseleaveFn);
}
showImage() {
TweenMax.killTweensOf(this.DOM.revealInner);
TweenMax.killTweensOf(this.DOM.revealImg);
this.tl = new TimelineMax({
onStart: () => {
this.DOM.reveal.style.opacity = 1;
TweenMax.set(this.DOM.el, {
zIndex: 1000
});
}
})
.add("begin")
.add(
new TweenMax(this.DOM.revealInner, 0.4, {
ease: Quint.easeOut,
startAt: {
x: "-100%",
y: "-100%"
},
x: "0%",
y: "0%"
}),
"begin"
)
.add(
new TweenMax(this.DOM.revealImg, 0.4, {
ease: Quint.easeOut,
startAt: {
x: "100%",
y: "100%"
},
x: "0%",
y: "0%"
}),
"begin"
);
}
hideImage() {
TweenMax.killTweensOf(this.DOM.revealInner);
TweenMax.killTweensOf(this.DOM.revealImg);
this.tl = new TimelineMax({
onStart: () => {
TweenMax.set(this.DOM.el, {
zIndex: 999
});
},
onComplete: () => {
TweenMax.set(this.DOM.el, {
zIndex: ""
});
TweenMax.set(this.DOM.reveal, {
opacity: 0
});
}
})
.add("begin")
.add(
new TweenMax(this.DOM.revealInner, 0.3, {
ease: Quint.easeOut,
x: "100%",
y: "100%"
}),
"begin"
)
.add(
new TweenMax(this.DOM.revealImg, 0.3, {
ease: Quint.easeOut,
x: "-100%",
y: "-100%"
}),
"begin"
);
}
}
[...document.querySelectorAll('[data-fx="2"] > a, a[data-fx="2"]')].forEach(
(link) => new HoverImgFx2(link)
);
[
...document.querySelectorAll(
".block__title, .block__link, .content__text-link"
)
].forEach((el) => {
const imgsArr = el.dataset.img.split(",");
for (let i = 0, len = imgsArr.length; i <= len - 1; ++i) {
const imgel = document.createElement("img");
imgel.style.visibility = "hidden";
imgel.style.width = 0;
imgel.src = imgsArr[i];
imgel.className = "preload";
contentel.appendChild(imgel);
}
});
imagesLoaded(document.querySelectorAll(".preload"), () =>
document.body.classList.remove("loading")
);
}
.hover-reveal {
position: fixed;
width: 200px;
height: 150px;
}
.hover-reveal__inner,
.hover-reveal__img {
width: 100%;
height: 100%;
position: relative;
}
.hover-reveal__img {
background-size: cover;
background-position: 50% 50%;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<main>
<div class="content">
<div class="block" data-fx="2">
<a class="block__link" data-img="https://www.kaspersky.co.uk/content/en-gb/images/product-icon-KSOS.png">Asli</a>
<a class="block__link" data-img="https://www.kaspersky.co.uk/content/en-gb/images/product-icon-KSOS.png">D24</a>
<a class="block__link" data-img="https://www.kaspersky.co.uk/content/en-gb/images/product-icon-KSOS.png">Jantung</a>
<a class="block__link" data-img="https://www.kaspersky.co.uk/content/en-gb/images/product-icon-KSOS.png">Tracka</a>
</div>
</div>
</main>
<script src="js/TweenMax.min.js"></script>
<script src="js/demo.js"></script>
</body>
How can I create a simple image reveal on rollover that is clean and simple?
| |
doc_1893
|
For example point (xi,yi) on input image should be mapped into point (xo,yo). To find the place of point on output image, I have a look up table.
It is easy to do it in C/C++, but it is very slow. Is there any way that I can do it using OpenGL shader so it gate the speed increase of GPU on target system?
How can I speed up this process if I can not use opengl?
Edit 1
Mock sample c/c++ code:
class Point
{
int x;
int y;
}
Point LUT[w,h]; // would hold LUT
void Transform(image in,image out)
{
for(int x=0;x<w;x++)
{
for(int y=0;y<h;y++)
{
color pixelColor=in.GetPixelColor(x,y);
out.PutPixelColor(LUT[x,y].x,LUT[x,y].y),pixelColor);
}
}
}
void main()
{
image in,out;
ReadLUT(LUT); // read LUT from file and fill LUT table
ReadImage(in); // read input image.
Transform(in,out); // transform image based on LUT
SaveImage(out); // write output image
}
| |
doc_1894
|
test1 -p333 -u512 -t3 -c10000 -m100000000
test1 -p444 -u256 -t1 -c50000 -m20000000
test2 -c555 -v -d2 -t2
test2 -c111 -v -d8 -t4
test3 ...
I.e. we run executable files with different parameters again and again, collect logs and analyze it. At the moment we don't use any testing framework. Sometimes we change the parameters, but rarely.
However we are going to move our tests to Googletest (or CppUnit, we have not decided yet), and I have no idea how can the tests be modified to be used with gtest. For example, I can move test1 and test2 to test fixtures, but I have no idea how to run it with different parameters (without changing the code and recompiling).
Is there any approach to move our parametrized tests under Googletest or Cppunit?
A: Google Test has support for value parameterized tests. It is described in its wiki. The wiki example explains support only for a simple parameter type, but you can pack multi-value parameters into a struct or a tuple.
A: With Google Test, you can create your own main, like describe here, and then you can manage your args.
| |
doc_1895
|
even with a empty cache i get errors;
they worked until i switched video source to binary data. works fine in mozilla both in windows and in linux, without any errors, but not in others. I load this page within an iframe on my homepage.
video source comes from $_[GET] method and then attached to a data-src attribute.
/*plus other functions*/
video=player.querySelectorAll(".play-window")[0].getElementsByTagName("video")[0];
function is_playing(curTime){
return feedback;
};
function can_play(what){
if((!what.canplay||!what.canplaythrough)&&what.loaded==false&&what.src==''){
what.setAttribute('poster',src_err);total.innerHTML='src Error';
}else{is_playing(what.currentTime);
};`` };
window.addEventListener('DOMContentLoaded',function(){
video.src=src_arg_all[0].getAttribute('data-src');video.load();can_play(video);
});
/*plus other functions & event listeners*/
so far i've tested this problem on windows and linux based browsers.
nothing special.
if more details needed i will post them here. thanks for any help in advance.
A: `if(navigator.userAgent.toLowerCase().includes('chrome')){video.src=src_arg_all[0].getAttribute('data-src');};`
it was so easy it must have slipped my mind. ;-)
| |
doc_1896
|
__INT_HANDLERS_SECTION__ static void saveTaskContext(_str_TSS * str_TSS_task)
{
register uint32 * eax asm ("eax");
register uint32 * ebx asm ("ebx");
register uint32 * ecx asm ("ecx");
register uint32 * edx asm ("edx");
register uint32 * esi asm ("esi");
register uint32 * edi asm ("edi");
register uint32 * ebp asm ("ebp");
register uint32 * esp asm ("esp");
asm volatile("mov eax,gs");
str_TSS_task->GS = *eax;
asm volatile("mov eax,fs");
str_TSS_task->FS = *eax;
asm volatile("mov eax,ds");
str_TSS_task->DS = *eax;
asm volatile("mov eax,ss");
str_TSS_task->SS = *eax;
asm volatile("mov eax,es");
str_TSS_task->ES = *eax;
asm volatile("mov eax,cr3");
str_TSS_task->ES = *eax;
str_TSS_task->EDI = * edi;
str_TSS_task->ESI = * esi;
str_TSS_task->ESP = * esp;
asm volatile("pop edx");
str_TSS_task->EDX = *edx;
asm volatile("pop ecx");
str_TSS_task->ECX = *ecx;
asm volatile("pop ebx");
str_TSS_task->EBX = *ebx;
asm volatile("pop eax");
str_TSS_task->EAX = *eax;
asm volatile("pop eax");
str_TSS_task->EFLAGS = *eax;
asm volatile("pop eax");
str_TSS_task->CS = *eax;
asm volatile("pop eax");
str_TSS_task->EIP = *eax;
str_TSS_task->EBP = *ebp;
return;
} // <------------------------- LINE 515 !!!
I am looking forward to save the values of the registers (as the name of the function says) but when i try to compile i get the next gcc error:
src/handlers.c: In function ‘saveTaskContext’:
src/handlers.c:515:1: error: unable to find a register to spill
}
^
src/handlers.c:515:1: error: this is the insn:
(insn 7 92 93 2 (set (reg:SI 146 [orig:88 D.1975 ] [88])
(mem:SI (reg/f:SI 145 [orig:87 D.1974 ] [87]) [0 *_2+0 S4 A32])) src/handlers.c:470 90 {*movsi_internal}
(expr_list:REG_DEAD (reg/f:SI 145 [orig:87 D.1974 ] [87])
(nil)))
src/handlers.c:515: confused by earlier errors, bailing out
Any ideas how to solve it? I would really appreciate :)
edit: I forgot to say that before doing the pop's i already have in the stack (in top-down order) EIP, CS, EFLAGS, EAX, EBX, ECX and EDX
A: The i386 only has eight general-purpose registers. You assign specific roles to all of them. As a result, GCC is not able to find a workable register allocation. (It needs some registers to implement indirect loads and stores.) Furthermore, ESP and EBP are used in the function prologue and likely have been clobbered before your code runs. It is also odd that a register variable called eax would contain a pointer to a value that is then read.
You will have to write this code in a separate assembler routine, not as C inline assembly. It is also unclear whether you can achieve what you want with the ABI calling convention.
| |
doc_1897
|
Each instance of Microservice runs as a container in a Pod. Is it possible to deploy MongoDB as another container in the same Pod? Or what is the best practice for this use case?
If two or more instances of the same Microservice are running in different Pods, do I need to deploy 2 or more instances of MongoDB or single MongoDb is referenced by the multiple instances of the same Microservice? What is the best practice for this use case?
Each Microservice is Spring Boot application. Do I need to do anything special in the Spring Boot application source code just because it will be run as Microservice as opposed to traditional Spring Boot application?
A:
Each instance of Microservice runs as a container in a Pod. Is it possible to deploy MongoDB as another container in the same Pod?
Nope, then your data would be gone when you upgrade your application.
Or what is the best practice for this use case?
Databases in a modern production environment are run as clusters - for availability reasons. It is best practice to either use a managed service for the database or run it as a cluster with e.g. 3 instances on different nodes.
If two or more instances of the same Microservice are running in different Pods, do I need to deploy 2 or more instances of MongoDB or single MongoDb is referenced by the multiple instances of the same Microservice?
All your instances of the microservice should access the same database cluster, otherwise they would see different data.
Each Microservice is Spring Boot application. Do I need to do anything special in the Spring Boot application source code just because it will be run as Microservice as opposed to traditional Spring Boot application?
Spring Boot is designed according to The Twelve Factor App and hence is designed to be run in a cloud environment like e.g. Kubernetes.
A: Deploy mongodb pod as a statefulset. refer below helm chart to deploy mongodb.
https://github.com/bitnami/charts/tree/master/bitnami/mongodb
Using init container you can check inside springboot pod to check if the mongodb is up and running then start the springboot container. Follow the below link for help
How can we create service dependencies using kubernetes
| |
doc_1898
|
There is a way to obtain the link to the static map maybe using gmap3?
Thank you
| |
doc_1899
|
class student:
def __init__(self, name, age, iden, lMark):
self.name=name
self.age=age
self.iden=iden
self.lMark=lMark
def printAve(self, obj):
for i in obj.lMark:
res+=i
av=res/len(lMark)
return av
def disInfo(self, obj):
print("the name is: ",obj.name)
print("the age is: ",obj.age)
print("the identity is: ",obj.iden)
print("the marks are: ", for i in lMark:
print(i))
def addStudent(self, n, a, i, l):
ob=student(n,a,i,l)
ls.append(ob)
return true
def searchStudent(self, _val):
for i in len(ls):
if ls[i]==_val:
return i
ls=[]
s=student("Paul", 23,14, list(15,16,17,20,12))
bool added = s.add("Van", 20, 12, list(12,18,14,16))
if added==True:
print("Student added successfully")
for i in range(ls.__len__())
s.disInfo(ls[i])
Can someone help me to solve this problem and explain me how to do?
A: You can't put a bare for loop in the argument list to print, and of course the embedded print doesn't return what it prints. What you can do is
print("the marks are:", ", ".join(lMark))
or perhaps
print("the marks are:", *lMark)
(Also, I believe you mean obj.lMark.)
To reiterate, if you call some code in the argument to print, that code should evaluate to the text you want print to produce; not do printing on its own. For example,
def pi()
return 3.141592653589793 # not print(3.141592653589793)
def adjective(arg):
if arg > 100:
return "big" # not print("big")
else:
return "small" # not print("small")
print(str(pi()), "is", adjective(pi()))
Notice how each function call returns something, and the caller does something with the returned value.
A: from statistics import mean
# classes are named LikeThis
# constants named LIKE_THIS
# other variables should be named like_this
# hungarian notation is not used in Python
class Student:
# instead of a global variable named ls,
# I'm using a class variable with a clear name instead
all_students = []
def __init__(self, name, age, iden, marks):
self.name = name
self.age = age
self.iden = iden
self.marks = marks
def printAve(self):
# you don't need to pass two arguments when you're only operating on a single object
# you don't need to reinvent the wheel, see the import statement above
return mean(self.marks)
def disInfo(self):
print("the name is:", self.name)
print("the age is:", self.age)
print("the identity is:", self.iden)
# you can't put a statement inside of an expression
# I'm guessing you want the marks all on the same line?
# the *args notation can pass any iterable as multiple arguments
print("the marks are:", *self.marks)
# this makes more sense as a classmethod
# clear variable names are important!
@classmethod
def addStudent(cls, name, age, iden, marks):
# I'm using cls instead of Student here, so you can subclass Student if you so desire
# (for example HonorStudent), and then HonorStudent.addStudent would create an HonerStudent
# instead of a plain Student object
cls.all_students.append(cls(name, age, iden, marks))
# note the capital letter!
return True
# again, this should be a classmethod
@classmethod
def searchStudent(cls, student):
# use standard methods!
try:
return cls.all_students.index(student)
except ValueError:
return None
# the literal syntax for lists in Python is `[1, 2, 3]`, _not_ `list(1, 2, 3)`.
# it also makes more sense to use Student.addStudent here, because just calling Student() doesn't add it
# to the list (although you could do that in __init__ if you always want to add them to the list)
Student.addStudent("Paul", 23, 14, [15, 16, 17, 20, 12])
# in Python, type annotations are optional, and don't look like they do in C or Java
# you also used `add` instead of `addStudent` here!
added: bool = Student.addStudent("Van", 20, 12, [12,18,14,16])
# don't need == True, that's redundant for a boolean value
if added:
print("Student added successfully")
# never call `x.__len__()` instead of `len(x)`
# (almost) never use `for i in range(len(x))` instead of `for item in x`
for student in Student.all_students:
student.disInfo()
A: First I answer your initial question, you can print a list in different ways, here are some of them.
You can iterate through it with a for loop and print every element on a different line:
for elem in self.lMark:
print(elem)
You can also append all values to a string and separate them by a character or something.
(Note: There will be a trailing space at the end.)
myString = ""
for elem in self.lMark:
myString = myString + str(elem) + " "
print(myString)
Better is this by doing it with strings-join method and a short version of the container iteration:
", ".join([str(i) for i in self.lMark])
There were some more issues in the code example.
Here is a running version of the script:
class Student:
def __init__(self, name, age, iden, lMark):
self.name=name
self.age=age
self.iden=iden
self.lMark=lMark
def printAve(self, obj):
for i in obj.lMark:
res+=i
av=res/len(self.lMark)
return av
def disInfo(self):
print("the name is: ",self.name)
print("the age is: ",self.age)
print("the identity is: ",self.iden)
print("the marks are: ", ", ".join([str(i) for i in self.lMark]))
class StudentList:
def __init__(self):
self.__list_of_students = []
def add(self, s):
self.__list_of_students.append(s)
return True
def get(self):
return self.__list_of_students
def search(self, name):
for s in self.__list_of_students:
if s.name == name:
return s
return None
ls = StudentList()
s=Student("Paul", 23,14, [15,16,17,20,12])
ls.add(s)
added = ls.add(Student("Van", 20, 12, [12,18,14,16]))
if added:
print("Student added successfully")
search_name1 = "Paula"
search_name2 = "Van"
if ls.search(search_name1):
print(search_name1, "is part of the list!")
else:
print("There is no", search_name1)
if ls.search(search_name2):
print(search_name2, "is part of the list!")
else:
print("There is no", search_name2)
for student in ls.get():
student.disInfo()
print("-"*10)
I would suggest to separate the list of students and the students to two different classes as shown in the code above.
A: You can unpack your list with the * operator:
print("the marks are: ", *lMark)
A: Try setting this as a function. i.e
def quantity():
for i in lMark:
print(i)
Then,
def disInfo(self, obj):
print("the name is: ",obj.name)
print("the age is: ",obj.age)
print("the identity is: ",obj.iden)
print("the marks are: ", + quantity)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.