id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23527500
|
The line issue is this:
& "SELECT @cols = @cols + stuff((select '," ' + offer + '"' " _
after the the second ' is when it disables the rest of the code.
Here is an example of the Code with more detail.
StrSQL = "SET NoCount ON " _
& "DECLARE @cols AS NVARCHAR(MAX)=''; " _
& "DECLARE @query AS NVARCHAR(MAX)=''; " _
& "SELECT @cols = @cols + stuff((select '," ' + offer + '"' " _
& "FROM catcov y join CatalogInfo z on (y.MailYear = z.mailyear) and (y.offer = z.catalog) " _
Any help would be appreciated.
EDIT:
Solution to this issue was to add an extra " to my line so it looks like this.
& "SELECT @cols = @cols + stuff((select ',"" ' + offer + '""' " _
Thanks for the help all!
A: As I mentioned in the comments, don't use a self referencing variable here. If you're on a modern version of SQL Server, then you can use STRING_AGG to easily achieve what you're after:
StrSQL = "SET NoCount ON " _
& "DECLARE @cols AS NVARCHAR(MAX); " _
& "DECLARE @query AS NVARCHAR(MAX); " _
& "SET @cols = (SELECT STRING_AGG(offer,',') WITHIN GROUP (ORDER BY offer)" _
& " FROM catcov cc JOIN CatalogInfo CI ON (cc.MailYear = CI.mailyear) AND (cc.offer = ci.catalog));" _ ' does this actually continue afterwards?
If, however, you're on an older version, and don't have access to STING_AGG you can use the FOR XML PATH method:
StrSQL = "SET NoCount ON " _
& "DECLARE @cols AS NVARCHAR(MAX); " _
& "DECLARE @query AS NVARCHAR(MAX); " _
& "SET @cols = (SELECT CONCAT(',',offer)" _
& " FROM catcov cc JOIN CatalogInfo CI ON (cc.MailYear = CI.mailyear) AND (cc.offer = ci.catalog)" _
& " FOR XML PATH""),TYPE).value('.','nvarchar(MAX)');" _ ' does this actually continue afterwards?
Unfortunately, I can't test either of these, but if there are any typoes, hopefully you can fix them.
| |
doc_23527501
|
I was thinking of creating a Redis store that would store the number of current requests per SOLR server, and querying on this store to get the SOLR server with the least # of current requests. Of course, I would update this store everytime a request is done.
Is this the best approach? What would you do in this situation?
A: I'm guessing you already set up Solr replication. Now, since Solr is a standard HTTP application, you can use any generic HTTP load balancer, such as HAProxy or Varnish. See this article on setting up HAProxy with Solr.
A: There is an existing load balancing solution for Solr, discussed here: have you looked at that?
| |
doc_23527502
|
source = one-of [sources] with available? but my current logic results in feeding all 3 parts. I tried using the hold but it still feeds from all 3 sources.
A pallet enters from orders and when it reaches assembler, holdForPallet is unblocked(). My intention is to use a single component from one of the suSources. A suSource may not have a part available and therefore we have more than one suSource.
A: Many different ways are possible. One would be to set the 3 sources to "Arrivals defined by" = "calls of inject() function".
Then, your orders source can call sourceNeeded.inject() to create one.
Another option: keep the 3 sources as is but add "Wait" objects after each. Now, your orders source can pull in from a specific "Wait" object using myWaitObject.free(x)
| |
doc_23527503
|
sqlalchemy.orm.exc.FlushError: Attempting to flush an item of type
as a member of collection "Tag.item". Expected
an object of type or a polymorphic subclass of
this type. If is a subclass of , configure mapper "Mapper|Item|items" to load this
subtype polymorphically, or set enable_typechecks=False to allow any
subtype to be accepted for flush.
The insert query
project = Proyecto.query.filter_by(id_project=id_project).first()
creado_en = datetime.datetime.utcnow()
nuevo_hub = Hub(name,location,comments,creado_en)
#FAIL HERE, even if Hub extends of Item
nuevo_tag = Tag(project,nuevo_hub,TYPE_HUB,creado_en)
db.session.add(nuevo_tag)
db.session.add(nuevo_hub)
db.session.commit()
The rest of code
class Item(db.Model):
__tablename__ = "items"
id_item = db.Column(db.Integer, autoincrement=True, primary_key=True)
type = db.Column(db.Integer)
created_at = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime)
__mapper_args__ = {
'polymorphic_identity': 'items',
'polymorphic_on':type,
'with_polymorphic':'*'
}
def __init__(self,creado_en=None):
self.created_at = creado_en
self.updated_at = creado_en
class Hub(Item):
__tablename__ = "hubs"
__mapper_args__ = {
'polymorphic_identity': 0,
'with_polymorphic':'*'
}
id_hub = db.Column(db.Integer, db.ForeignKey('items.id_item'), primary_key=True)
# id_hub = db.Column(db.Integer, autoincrement=True, primary_key=True)
name = db.Column(db.String(50), nullable=False, index= True)
location = db.Column(db.String(50))
comments = db.Column(db.String(128))
created_at = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime)
# conexiones = db.Column(db.Integer)
def __init__(self, nombre=None, location=None,comments=None, creado_en=None):
self.name = nombre
self.location = location
self.comments = comments
self.created_at = creado_en
self.updated_at = creado_en
class Tag(db.Model):
__tablename__ = "tags"
id_tag = db.Column(db.Integer, autoincrement=True, primary_key=True)
id_project = db.Column(db.Integer,db.ForeignKey("projects.id_project"))
id_item = db.Column(db.Integer,db.ForeignKey("items.id_item"))
project = db.relationship(Proyecto, backref=db.backref('list_tags', lazy='dynamic'))
item = db.relationship(Item, backref=db.backref('list_tags', lazy='dynamic'))
type = db.Column(db.Integer) #(0,hub);(1,cable);(2,pipe);(3,electrical_pipes)
created_at = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime)
def __init__(self,project,item,type,created_at):
self.project = project
self.item = item
self.type = type
self.created_at = created_at
self.updated_at = created_at
A: I had the same problem, in my case I fix that based on this answer:
Flask-SQLAlchemy polymorphic association
Also, the official SQLAlchemy docs can help:
Joined Table Inheritance In joined table inheritance, each class along
a particular classes’ list of parents is represented by a unique
table. The total set of attributes for a particular instance is
represented as a join along all tables in its inheritance path. Here,
we first define the Employee class. This table will contain a primary
key column (or columns), and a column for each attribute that’s
represented by Employee. In this case it’s just name:
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
name = Column(String(50))
type = Column(String(50))
__mapper_args__ = {
'polymorphic_identity':'employee',
'polymorphic_on':type
}
I think your code should look like:
class Hub(Item):
__tablename__ = "hubs"
id_hub = db.Column(db.Integer, autoincrement=True, primary_key=True)
name = db.Column(db.String(50), nullable=False, index= True)
location = db.Column(db.String(50))
comments = db.Column(db.String(128))
created_at = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime)
# conexiones = db.Column(db.Integer)
__mapper_args__ = {
'polymorphic_identity': 0,
'polymorphic_on': id_hub
}
def __init__(self, nombre=None, location=None,comments=None, creado_en=None):
self.name = nombre
self.location = location
self.comments = comments
self.created_at = creado_en
self.updated_at = creado_en
You may also need to set is to concrete = True to be able to query it from child class.
Concrete inheritance is inheritance of method implementations and member variables from a super-class.
Details at:
Abstract Concrete Classes
__mapper_args__ = {
'polymorphic_identity': 0,
'polymorphic_on': id_hub,
'concrete': True
}
| |
doc_23527504
|
location /addressJson/0{
proxy_pass http://wangzc.wang:1337/0;
}
location /addressJson/1{
proxy_pass http://wangzc.wang:1337/1;
}
location /addressJson/2{
proxy_pass http://wangzc.wang:1337/2;
}
location /addressJson/3{
proxy_pass http://wangzc.wang:1337/3;
}
location /addressJson/4{
proxy_pass http://wangzc.wang:1337/4;
}
location /addressJson/5{
proxy_pass http://wangzc.wang:1337/5;
}
location /addressJson/6{
proxy_pass http://wangzc.wang:1337/6;
}
location /addressJson/7{
proxy_pass http://wangzc.wang:1337/7;
}
How can I abbreviate?
A: You do not need to use a regular expression location to match any URI that begins with the same text. Use a prefix location. The location that matches all of the locations in your question is:
location /addressJson/ { ... }
The optional uri part of the proxy_pass value performs an aliasing function, which will substitute the prefix (specified in the prefix location) with the uri part in the proxy_pass value. See this document for details.
For example:
location /addressJson/ {
proxy_pass http://example.com:1337/;
}
If the original requested URI is /addressJson/foo then the /addressJson/ part is removed and the / prepended before sending the revised URL as http://example.com:1337/foo.
Note that the location value should end with / in order that the text substitution works correctly.
| |
doc_23527505
|
However, when I execute the command:
:nnoremap <C-[> <C-t>
then my arrow key navigation get messed up. I'm not sure what happens, but clearly that's not the ideal way to do it.
I've tried to unbind Ctrl+[ but vim reports that it wasn't bound, and I've tried some tricks like first binding Ctrl+[ to itself and then unbinding. Always the same result.
Side note: Interestingly, when I add it to my .vimrc (as the last command) it's even worse. Something nondeterministic happens and vim opens randomly in one of these 3 states:
*
*The bottom status line says "E73: tag stack empty", implying it received a Ctrl+t-esque command, however the if I hit a nav key like j, it deletes the current and bottom line and then puts me into insert mode. (Happens ~70% of the time.)
*Sometimes it's in replace mode. (Happens ~15% of the time.)
*Sometimes it's in normal mode. (Happens ~15% of the time.)
How can I properly remap Ctrl+[ to a different function in .vimrc?
A: You can't rebind Ctrl[. Pressing the Escape key in a terminal sends Ctrl[, just like pressing the Tab key sends CtrlI. There's no separate Esc code.
Vim is probably acting crazily when you try this because basically every ANSI key sequence starts with Ctrl[, so your rebinding is firing on all terminal input, and whatever else is in the key sequence looks like more commands to vim.
A: Due to the way that the keyboard input is handled internally, this unfortunately isn't generally possible today, even in GVIM. Some key combinations, like Ctrl + non-alphabetic cannot be mapped, and Ctrl + letter vs. Ctrl + Shift + letter cannot be distinguished. (Unless your terminal sends a distinct termcap code for it, which most don't.) In insert or command-line mode, try typing the key combination. If nothing happens / is inserted, you cannot use that key combination. This also applies to <Tab> / <C-I>, <CR> / <C-M> / <Esc> / <C-[> etc. (Only exception is <BS> / <C-H>.) This is a known pain point, and the subject of various discussions on vim_dev and the #vim IRC channel.
Some people (foremost Paul LeoNerd Evans) want to fix that (even for console Vim in terminals that support this), and have floated various proposals, cp. http://groups.google.com/group/vim_dev/browse_thread/thread/626e83fa4588b32a/bfbcb22f37a8a1f8
But as of today, no patches or volunteers have yet come forward, though many have expressed a desire to have this in a future Vim 8 major release.
| |
doc_23527506
|
https://en.wikipedia.org/wiki/Xorshift
http://xoroshiro.di.unimi.it/
I´m just now checking the generators with 64 bit states, like the xorshift64star from the wikipedia (here with my changes to trace the error)
double xorshift64star() {
uint64_t x = global_state[0]; /* The state must be seeded with a nonzero value. */
x ^= x >> 12; // a
x ^= x << 25; // b
x ^= x >> 27; // c
global_state[0] = x;
auto u64val = x * 0x2545F4914F6CDD1D;
double dval = (double)u64val;
return dval;
}
However, running on an online compiler https://www.onlinegdb.com/ the double value returned is always 0 or 3.1148823182455562e-317
I haven´t been able to find a solution on how to make the output from this function to be normalize into a [0,1] uniform distribution, without losing much precision and entropy.
What is the "corect" transformation I would have to do the output?
SOLVED!
Thank you @RetiredNinja.
The generator was already normalizing the uint64 value. However only casting it to double don´t seem to work for that particular compiler.
The solution was to use the custom cast from http://xoroshiro.di.unimi.it/
static inline double to_double(uint64_t x) {
const union { uint64_t i; double d; } u = {.i = UINT64_C(0x3FF) << 52 | x >> 12 };
return u.d - 1.0;
}
A: Assuming that your u64val is uniform between 0 and numeric_limits<uint64_t>::max, the obvious transform is u64val/numeric_limits<uint64_t>::max.
This is not the most accurate transform, though. The problem here is that you end up generating multiples of 1.0/numeric_limits<uint64_t>::max. This obviously gives many small values a probability of zero. But consider this: the probabilities of all numbers between 0 and 1e-100 combined has to be 1e-100. That means you'd need to generate about 1e100 numbers to get any one of these numbers.
This basically means we've got an underspecified engineering problem here. Exactly how close should the approximation to uniform be?
| |
doc_23527507
|
function makeObject($s) {
$secobj = new mySimpleClass($s);
return $secobj;
}
class mySimpleClass {
$secret = "";
public function __construct($s) {
$this -> secret = $s;
}
public function getSecret() {
return base64_encode(string $secret);
}
}
Anyone see whats wrong? Thanks!
A: You need to set the visibility of $secret
private $secret = "";
Then just remove that casting on the base64 and use $this->secret to access the property:
return base64_encode($this->secret);
So finally:
class mySimpleClass
{
// public $secret = "";
private $secret = '';
public function __construct($s)
{
$this->secret = $s;
}
public function getSecret()
{
return base64_encode($this->secret);
}
}
A: I suggest you to declare $secret as public or private & access it using $this->. Example:
class mySimpleClass {
public $secret = "";
public function __construct($s) {
$this -> secret = $s;
}
public function getSecret() {
return base64_encode($this->$secret);
}
}
| |
doc_23527508
|
@Scripts.Render("~/bundles/scripts") ~ 4 seconds
vs
<script src='@Scripts.Url("~/bundles/scripts")'></script> < 1 second
My BundleConfig.cs has no special configuration, this is exactly as it appears:
bundles.Add(new ScriptBundle("~/bundles/scripts").Include(
"~/Scripts/jquery-1.7.2.min.js",
"~/Scripts/jquery.validate.min.js",
"~/Scripts/jquery.validate.unobtrusive.js",
"~/Scripts/jquery-ui-1.9.0.custom.min.js",
"~/Scripts/bootstrap.min.js",
"~/Scripts/bootstrap-modal.js",
"~/Scripts/bootstrap-dropdown.js",
"~/Scripts/bootstrap-tooltip.js",
"~/Scripts/bootstrap-typeahead.js",
"~/Scripts/bootstrap-transition.js",
"~/Scripts/bootstrap-popover.js"));
My web.config is even configured to optimize in Debug but I have tried running in Release mode and still get the same result:
<compilation optimizeCompilations="true" debug="false" targetFramework="4.0" />
Any ideas why Scripts.Render is so slow?
A: The problem was with the outdated package I had installed. A simple Update-Package in package manager console and I went from
<package id="Microsoft.AspNet.Web.Optimization"
version="1.0.0-beta2" targetFramework="net40" />
to
<package id="Microsoft.AspNet.Web.Optimization"
version="1.0.0" targetFramework="net40" />
Now Scripts.Render() is peforming much better :-)
| |
doc_23527509
|
id col1 col2 col3 col4
N 1 8 5 10
N 3 7 4 20
N 5 6 3 40
N 1 8 5 10
N 3 7 4 20
N 5 6 3 40
F 10 1 2 5
F 10 1 2 5
F 10 1 2 5
")
Output
col1 col2 col3 col4
Mean_N
Mean_F
Ratio_N_F
Pvalue_NvsF
I can calculate p-value by:
lapply(m[-1], function(x) t.test(x ~ m$id))
I could use melt() to calculate the mean
How can I put all together in a final data frame?
A: Consider an rbind across separate aggregations calls. Below assumes ratio, Ratio_N_F, is the ratio of column means.
outdf <- rbind(
Mean_N = aggregate(.~id, mydf[mydf$id=='N',], FUN=mean)[-1],
Mean_F = aggregate(.~id, mydf[mydf$id=='F',], FUN=mean)[-1],
Ratio_N_F = aggregate(.~id, mydf[mydf$id=='N',], FUN=mean)[-1] /
aggregate(.~id, mydf[mydf$id=='F',], FUN=mean)[-1],
Pvalue_NvsF = sapply(mydf[-1], function(x) t.test(x ~ mydf$id)$p.value)
)
outdf
# col1 col2 col3 col4
# Mean_N 3.000000e+00 7.000000e+00 4.00000000 23.33333333
# Mean_F 1.000000e+01 1.000000e+00 2.00000000 5.00000000
# Ratio_N_F 3.000000e-01 7.000000e+00 2.00000000 4.66666667
# Pvalue_NvsF 2.093883e-04 1.523397e-05 0.00276496 0.02178842
| |
doc_23527510
|
public interface IProduct : IAuditable
{
string Code { get; set; }
string Name { get; set; }
string Description { get; set; }
ProductItemsList Items { get; }
ProductType Type { get; }
}
Where IAuditable is defined as:
public interface IAuditable
{
DateTimeOffset CreatedOn { get; }
int CreatedBy { get; }
DateTimeOffset ModifiedOn { get; }
int ModifiedBy { get; }
}
In a view that is bound to an enumerable of IProduct,
This works:
(btw ReSharper tells me to remove the cast)
@Html.DisplayFor(model => ((IAuditable)model.ModelObject).CreatedOn)
But this fails:
@Html.DisplayFor(model => model.ModelObject.CreatedOn)
(with error "MyProj.Products.IProduct.CreatedOn could not be found")
Can someone explain this to me. It's Friday afternoon so I'm probably being stupid.
| |
doc_23527511
|
The css originally had the following:
.threeFrames .leftStyle {float: left; position: relative; width: 20%;}
.threeFrames .centerStyle {float: left; position: relative; max-width: 60%;}
.threeFrames .rightStyle {float: left; position: relative; width: 20%;}
But this didn't have the effect I wanted. I want to set the two end columns to fixed width 240px however, when I do this, when the browser is resized, it bumps the right hand column below the others, whereas I want just the middle column to shrink.
A: If you make .rightStyle {float:right;} and don't style the middle column at all, it will automatically wrap around when possible.
| |
doc_23527512
|
char* input = (char*)malloc(sizeof(char) * BUFFER) // buffer is defined to 100
int digit = atoi(input); // convert char into a digit
int digit_check = 0;
digit_check += digit % 10; // get last value of digit
When I run the input 1234567896 and similarly digit = 1234567896 and digit_check = 6.
However when I run the input 9999999998, digit = 1410065406 and therefore digit_check = 6 when it should be 8.
For the second example, why is there a difference between input and digit when it should be the same value?
A: Probably because 9999999998 is bigger then the maximum (signed) integer representation, so you get an overflow.
In fact this is the binary representation of 9999999998 and 1410065406:
10 01010100 00001011 11100011 11111110
01010100 00001011 11100011 11111110
As you can see if you see 1410065406 is the 32ed bit value of 9999999998
A: atoi is limited to an int size (32 bits on most recent plateform).
If you want to handle large numbers, you can use atol or scanf("%ld").
Don't forget to type your variable to long int (or long).
You could also just getting the very last character of your input (gathered as a string rather than as an int) and use atoi on it, so it would never overflow.
A: On many platforms size of int is limited by 4 bytes, that limits digit in [-2 ** 31, 2**31 - 1].
Use long (or long long) with strtol (or strtoll) depending on platform you build for. For example, GCC on x86 will have 64-bit long long, and for amd64 it will have 64-bit long and long long types.
So:
long long digit = strtoll(input, NULL, 10);
NOTE: strtoll() is popular in Unix-like systems and became standard in C++11, but not all VC++ implementations have it. Use _strtoi64() instead:
__int64 digit = _strtoi64(input, NULL, 10);
A: You probably want to use the atoll function, which returns a long long int, that is twice as big as int (most likely 64 bits in your case).
It is declared in stdlib.h
http://linux.die.net/man/3/atoll
A: You should avoid to call atoi on uninitialized string, if there is no \0 on the string, you will invalid read and have a segmentation fault.
You should use strtoimax instead, it's more safe.
A: 9999999998 is bigger then the maximum value that an integer can represent. Either use atol() OR atoll()
A: You should stop using atoi function or any other functions from ato... group. These functions are not officially deprecated, but they are effectively abandoned since 1995 and exist only for legacy code compatibility purposes. Forget about these functions as if they do not exist. These function provide no usable feedback in case of error or overflow. And overflow is what apparently happens in your example.
In order to convert strings to numbers, C standard library provides strtol function and other functions from strto... group. These are the functions you should use to perform the conversion. And don't forget to check the result for overflow: strto... functions provide this feedback through the return value and errno variable.
| |
doc_23527513
|
It would be better to write a choice function in the code.
It will be def choice in the class.
Now the choice variable is outside the class.
Rewrite the code into the class.
the output is
Enter choice: 1 for full_name, 2 for age, 3 for bmi, 4 for analysis
user enter 1
output: Alex L.
user enter 2
output:28
user enter 3
ouput:0.0024691358024691358
user enter 4
output:You need to eat more.
do not use global variable and use the "def choice:" to rewrite it.
import datetime
choice=input('Enter choice: 1 for full_name, 2 for age, 3 for bmi, 4 for analysis')
choice=int(choice)
class Person:
def __init__(self, name, birthday_year, address, telephone, email):
self.name = name
self.birthday_year = birthday_year
self.address= address
self.telephone = telephone
self.email = email
def full_name(self,surname,firstname):
self.surname = surname
self.firstname = firstname
return self.firstname+" "+self.surname
def age(self,birthday_year):
self.birthday_year=birthday_year
currentyear= datetime.datetime.now().year
age = currentyear - self.birthday_year
return age
def bmi(self,weight,height):
self.weight= weight
self.height = height
result= self.weight / (self.height**2)
return result
def analysis(self,result):
self.result=result
if result < 18.5:
print ("You need to eat more.")
elif result > 25:
print ("Try to care yourself.")
else:
print ("You are a healthy person.")
def main():
s= Person ("Alex",1990,"Wonderland",2345678,"aa@smail.com")
if choice== 1:
a = s.full_name("L.", "Alex")
print(a)
elif choice==2:
b = s.age(1990)
print(b)
elif choice==3:
c = s.bmi(80, 180)
print(c)
elif choice ==4:
c = s.bmi(80, 180)
d = s.analysis(c)
print(d)
else:
print("invaild entry")
if __name__ == "__main__":
main()
A: You can use a dictionary and functions, which are needed to be run in each select. Here is a sample code. You will need to modify this code to serve your needs.
def one():
return "Alex L"
def two():
return "28"
def three():
return "0.0024691358024691358"
def four():
return "You need to eat more"
def choice(argument):
switcher = {
1: one,
2: two,
3: three,
4: four,
}
# Get the function from switcher dictionary
func = switcher.get(argument, lambda: "Invalid choice")
# Execute the function
print(func())
choice(1)
choice(2)
choice(3)
choice(4)
| |
doc_23527514
|
This bug causes the columns to appear "on top of" each other...
In ng-grid-2.0.14.debug.js there is a directive created called ngGrid (of course!). The directive uses the suggested "directive definition object" form. They define an inherited scope by defining scope:true and they declare a compile function which returns an object structure containing ONLY the function pre and DOES NOT declare the function post.
What is weird is that there is a return statement within this pre function, and I cannot find documentation about return statements within a pre function. The function ends up in Angular's "processQueue", which I believe could be Deffered.$$state.pending (I am tracing the call stack to find this, so I am not sure). During a $digest loop, angular tests these array indexes as functions and invokes them.
The ngGrid function that is being called, which can be found at ng-grid-2.0.14.debug.js line 3318, does a lot, and most of these things are working, such as $destroy cleanup logic, $complie($scope) of the gridTemplate, event listener establishing, and, most importantly, the addition of two very specific classes to our directive's iElement which appears to still be "in scope." This is the part that is failing.
They are adding a class to the iElement by:
iElement.addClass("ngGrid").addClass(grid.gridId.toString());
Sometimes this works, sometimes this doesn't...
Sometimes the element picks up the classes "ng-scope ngGrid ng[0-9]{13}" (e.g: ng-scope ngGrid ng1453913625179), and sometimes it does not, even when I have stepped through the function and watched the line of code that adds the classes get executed.
Further Investigation!: If I place an ng-if="true" on the parent node of my "ngGrid element" (the element that instanciates the ngGrid directive by attribute), then eveything works!
My Question: Does appending classes to an element within a $digest loop have issues or any reason why this would work sometimes and not all the time? Also, can you find documentation on setting return values for pre? I couldn't find anything about the return values here. Finally, why does setting ng-if="true" on the parent of iElement fix the issue of the class names not being appended to iElement's class list? Thanks!
| |
doc_23527515
|
for row in range(dim):
# Add an empty array that will hold each cell
# in this row
grid.append([])
for column in range(dim):
grid[row].append(np.random.binomial(1, 0.2, 1)) # Append a cell
if (row == column == dim - 1):
grid[row][column] = 0
grid[0][0] = 0
I would like to avoid using a node class as I have had limited success with it. I want to know how I can represent/store parent-child relationships in a BFS search from the (0,0) position on this maze to the (dimension - 1, dimension - 1) position. Also, given the nature of the graph/maze/grid, I NEED to avoid having children with the same location but different parents. I want to return the shortest list of nodes between the start and end positions.
Thank you for your help.
| |
doc_23527516
|
/**
* @var ArrayCollection
* @ORM\ManyToMany(targetEntity="Industry",inversedBy="companies")
*/
protected $industries;
In admin class i wrote like
/**
* @param DatagridMapper $datagridMapper
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('industries', null, [], null, [ 'multiple' => true,'expanded' => true,
])
;
}
But the only result i got is error
Variable "widget_type" does not exist in SonataAdminBundle:Form:filter_admin_fields.html.twig >at line 33
500 Internal Server Error - Twig_Error_Runtime
A: Comment this line
{% set label_attr = label_attr|merge({'class': (label_attr.class ~ ' ' ~ (widget_type != '' ? (multiple ? 'checkbox' : 'radio') ~ '-' ~ widget_type : ''))}) %}
In Sonata-project/admin-bundle/resources/view/Form/filter_admin_fields.html line 36
| |
doc_23527517
|
SyntaxError: unexpected EOF while parsing
I tried putting a print("Done!") at the end but that said
IndentationError: unexpected unindent.
max = int("FFFC",16)
min = 0
for x in range(max + 1):
try:
hex_value = hex(x)
proper = str(hex_value)[2:].upper()
while len(proper) != 4:
proper = "0" + proper
proper = "U+" + str(proper)
print(f"{proper} : {chr(x)}")
Error:
File "unicode.py", line 11
^
SyntaxError: unexpected EOF while parsing
This is in the last line of code (where it is blank).
A: You need to include an except statement for every try.
| |
doc_23527518
|
Reasons:
*
*To obfuscate the code for delivery to a customer so as not to reveal our Intellectual Property - for delivery onto a customer's own machine/systems for which I have no control over what permissions I can set regarding access, so the program file has to be binary whereby the workings cannot be easily seen by viewing in a text editor or hexdump viewer.
*To make a single, simply deployed program for the customer without/or a minimal amount of any external dependencies.
I would prefer something simple without the need for package manager since:
*
*I can't rely on the customer's knowledge to carry out (un) packaging instructions and
*I can't rely on the policies governing their machines regarding installing packages (and indeed from third parties).
The simplest preferred approach is to be able to compile to proper machine code a single executable that will run out of the box without any dependencies.
A: You could use this: http://megastep.org/makeself/
This generates a shell script that auto-extracts a bundled tar.gz archive into the temporary directory, and then can run an arbitrary command upon extraction.
Using this tool, you can provide only one shell script to the client.
This script will then extract your ofbsh obfuscated scripts and binaries into /tmp, and run them transparently.
A: You can obfuscate shell scripts with something like ofbsh. You won't easily bundle other programs into a single executable for unix, though. Normally the approach for installation would be to buld a package for your platform's package manager (e.g. rpm, deb, pkg) or to provide a tarball to unravel in the appropriate directory.
If you need an executable file that unpacks the contents you might be able to use a shell archive. Take a look at the docs for shar(1) and see if that will get what you want
If you really need a scripting capability to glue multiple C programs together, take a look at the Tcl language. It has an API that is designed to trivially wrap C programs that expect to see argv[] style parameters. You can even embed the chunks of C code into a custom Tcl interpreter and glue it together with various Tcl scripts.
If you really need to make it opaque, you could encrypt the tcl scripts and wrap the whole thing in something that unencrypts the tcl scripts to a buffer and then runs the Tcl interpreter on them. Tcl can accept scripts from a file or a char* buffer, so the unencrypted scripts never have to hit the file system.
A: The solution that fully meets my needs would be SHC - a free tool, or CCsh a commercial tool. Both compile shell scripts to C, which then can be compiled using a C compiler.
Links about SHC:
*
*https://github.com/neurobin/shc
*http://www.datsi.fi.upm.es/~frosal/
*http://www.downloadplex.com/Linux/System-Utilities/Shell-Tools/Download-shc_70414.html
Links about CCsh:
*
*http://www.comeaucomputing.com/faqs/ccshlit.html
A: shc
I have modified the original source and upgraded to a new version with some feature addition and bug fixes.
It's here.
Example Usage:
shc -f script.sh -o binary_name
script.sh will be compiled to a binary named binary_name
Note that, you still need the required shell to be installed in your system to run this executable.
A: arx is a great bundler, and you may be able to integrate a obfuscator in its workflow.
A: Options that are available to you:
*
*Write a logic in your code that, when the code is run for the first time on a box, it'll check to see if all the required packages exist. And if they do not, the code will automatically go get the packages itself and will install them...without asking to the user to do anything. The only question the user needs to be asked is "Is it ok to proceed with the install of the aforementioned packages? (Y/N)". Anything outside of that is too much.
*Once the above code is complete (yes, i'm aware it may not be all that simple for you to code this, or may be it is, i don't know your coding capabilities), copy and paste your completed code to a site like kinglazy.com and an actual executable file will be generated for you.
There are quite a few benefits of this particular option:
*
*Yes, you will be able to run the encrypted version of your script without exposing any proprietary information.
*No one can try to "view" your script, because if they do, they'll see nothing but indecipherable, encrypted jargon which wont make sense to them.
*No one can attempt to modify your script because if they do, the script will immediately become inoperable.
*No one can run a debugger on your script to see how it works. If they do, the script will abort.
*Also, no one can create copies of your script on the same server. If they do, it will abort and won't work. It'll only allow users to create symlinks to the original location of wherever you want the script to be.
I may be missing some things in what you asked for, but i believe the above satisfies a good portion of what you wanted.
Not sure if this works on other scripts but it certainly does for shell scripts.
A: You can also use the free online version of CCsh to compile a shell script into a binary:
http://www.comeaucomputing.com/tryccsh/
| |
doc_23527519
|
Also i want to get the carrier provider in which the data is active.
Eq :
sim 1 : carrier 1
Sim 2 : carrier 2
If data is active on sim 2
It should return the carrier 2 name.
A: my way (Android >= 22)
int getDefaultDataSubscriptionId(final SubscriptionManager subscriptionManager) {
if (android.os.Build.VERSION.SDK_INT >= 24) {
int nDataSubscriptionId = SubscriptionManager.getDefaultDataSubscriptionId();
if (nDataSubscriptionId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
return (nDataSubscriptionId);
}
}
try {
Class<?> subscriptionClass = Class.forName(subscriptionManager.getClass().getName());
try {
Method getDefaultDataSubscriptionId = subscriptionClass.getMethod("getDefaultDataSubId");
try {
return ((int) getDefaultDataSubscriptionId.invoke(subscriptionManager));
}
catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
}
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
return (SubscriptionManager.INVALID_SUBSCRIPTION_ID);
}
@TargetApi(22)
public String getUIText22(final TelephonyManager telephonyManager) {
SubscriptionManager subscriptionManager = (SubscriptionManager) getContext().getApplicationContext().getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
int nDataSubscriptionId = getDefaultDataSubscriptionId(subscriptionManager);
if (nDataSubscriptionId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
SubscriptionInfo si = subscriptionManager.getActiveSubscriptionInfo(nDataSubscriptionId);
if (si != null) {
return (si.getCarrierName().toString());
}
}
}
A: Here is a simple solution to get current active data sim operator for dual sim environment. It works after api level 22.
public static String getDataSimOperator(Context context) {
if (context == null) {
return null;
}
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (tm != null) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
int dataSubId = SubscriptionManager.getDefaultDataSubscriptionId();
TelephonyManager dataSimManager = tm.createForSubscriptionId(dataSubId);
return dataSimManager.getSimOperator();
} else {
String operator = getDataSimOperatorBeforeN(context);
if (operator != null) {
return operator;
} else {
return tm.getSimOperator();
}
}
} else {
return tm.getSimOperator();
}
}
return null;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
private static String getDataSimOperatorBeforeN(Context context) {
if (context == null) {
return null;
}
int dataSubId = -1;
try {
Method getDefaultDataSubId = SubscriptionManager.class.getDeclaredMethod("getDefaultDataSubId");
if (getDefaultDataSubId != null) {
getDefaultDataSubId.setAccessible(true);
dataSubId = (int) getDefaultDataSubId.invoke(null);
}
} catch (Exception e) {
e.printStackTrace();
}
if (dataSubId != -1) {
SubscriptionManager sm = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
if (sm != null && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)
== PackageManager.PERMISSION_GRANTED) {
SubscriptionInfo si = sm.getActiveSubscriptionInfo(dataSubId);
if (si != null) {
// format keep the same with android.telephony.TelephonyManager#getSimOperator
// MCC + MNC format
return String.valueOf(si.getMcc()) + si.getMnc();
}
}
}
return null;
}
| |
doc_23527520
|
http://rosettacode.org/wiki/LZW_compression#C
It creates encoded file length as too long than original file size, what is the reason for that?
please anybody help me to understand the what is happening in real time.
A: It is impossible for a lossless compression to compress every file to a shorter file.
This is because there are 256N files that are N bytes long, but there are (256N-1)/255 files that are shorter than N bytes. So not every file can be mapped to shorter files.
More than that, if any file becomes shorter, then some shorter file had to give up its spot to make that possible. So some files must become larger.
Lossless compression works by recognizing common patterns in typical files created by humans and converting long high-probability sequences of bytes to shorter sequences. The price for this is that some sequences become longer. The goal of the design is to make typical files compress, but atypical files must get longer.
If a compression does its job, redundant information is removed from a file, and the output is similar to random data. Then the output cannot be compressed further.
| |
doc_23527521
|
Sometimes when I edit/add new code to my project, it doesn't refresh. AS simply runs the old code. Sometimes I have to add empty new lines and run it again to make my modifications effect.
I would like to turn off every caching and smart speed run bs in order to make this laughable death star IDE work for once in the life, doing one thing properly, instead of doing 1000 things badly.
How is it possible that when they make an update, fixing/adding 2 new things but make worse/broke 3 old ones?
I tried to turn off instant run but it is not even among options.
Thanks in advance.
A: Try this settings:
Run -> Edit Configuration...
A: Try #1: Update to the latest distributions Gradle in gradle-wrapper.properties file and clean project.
# 6.8.2
distributionUrl=https\://services.gradle.org/distributions/gradle-<latest-version>-bin.zip
Try #2 (A temporary alternative): Use the Android Studio beta version in the meantime there is a new AS version.
A: Try to close Android Studio and then delete .gradle folder and then start AS again , this what I did when it happen to me, and it did the trick for me!
This is folder exist in :
C:\Users\userName\.gradle
A: Uninstall android studio and sdk files also (try to delete all files regarding android studio from c drive)...Then install android studio in another drive and download the sdk files. It works for me hopefully also work for you.
A: if you had to install gradle. you can empty your caches with this command in your android folder
mac ./gradlew clean
windows gradlew clean
A: It's a known issue in Android Studio.
Follow these steps:
*
*Make a copy of the project to a new folder.
*Inside this folder
delete the following files:
.iml file
.idea folder
.build folder
.gradle folder
*Open Android Studio
*Select 'File > Import
Project...'
*Select the new projects settings.gradle file and click 'open'
*Rebuild again (it might need to install the dependencies)
From now on it won't happen again to your project.
A: Might not be the best solution but it works for now.
Just go to "File -> Settings -> Build, Execution, Deployment -> Instant Run" and just disable it. With this Android Studio builds from scratch each time but it's better than not building it right.
A: I have this problem sometimes too. I found out that the problem is with gradle build cache. I just disable it and everything works fine again. You can check your gradle.properties to see if org.gradle.caching is set to true or not. If you have this setting then try to disable it and see if it fixes your problem or not.
Note that disabling it might increase your build time.
A: Oh yeah, this used to happen with me initially. Resetting the gradle file or forcing a clean up of the project will yield correct results, but is also irritating to do manually after each minor code change (specially if you're working in sub modules.
The reason why the app refuses to update to the new code is due to something called as Instant Run swaps. Basically there exists hot, warm and cold swaps that is used to speed up build time, however this also causes the situation that you're facing. Read up more about Instant Run here -> https://android.googlesource.com/platform/tools/base/+/studio-3.0/instant-run/README.md
As for disabling Instant Run, go to Android Studio Settings/Preferences -> Build,Execution,Deployment -> Instant Run -> Untick Enable Instant Run checkbox
Now each time you build your app you'll notice higher build time, but your code will be updated in the app build.
A: Have you tried disabling the build cache in gradle.properties?
android.enableBuildCache=false
After setting this it could help to use File -> Invalidate Caches and Restart a last time.
From then on, it should do what you want at the cost of a bit build speed (but honestly I don't see much difference in speed since I turned that off).
In addition, as @Himesh Perera said, turn off that instant run. It causes lots of trouble.
| |
doc_23527522
|
A: You can try overriding the logger in an initializer, like here.
# Create logger that ignores messages containing “CACHE”
class CacheFreeLogger < ::Logger
def debug(message, *args, &block)
super unless message.include? 'Expire fragment'
end
end
# Overwrite ActiveRecord’s logger
ActiveRecord::Base.logger = ActiveSupport::TaggedLogging.new(
CacheFreeLogger.new(STDOUT)) unless Rails.env.test?
| |
doc_23527523
|
Inputs:
*
* points - a set of (x,y) coordinates for the data points; x and y are non-negative
* avgX, avgY - the average of the x and y coordinates of all data points
Outputs:
*
* aDist, bDist - the lengths of the major and minor axes
// Find a and b -- use principal component analysis
// http://ask.metafilter.com/36213/Best-Fit-Ellipse (2nd reply)
// http://number-none.com/product/My%20Friend,%20the%20Covariance%20Body/index.html
double mat[2][2]; // Will be the covariance matrix.
// Eigenvectors will be major & minor axes. Eigenvalues will be lengths of axes, squared.
mat[0][0] = mat[0][1] = mat[1][0] = mat[1][1] = 0;
for (CPixelList::iterator i = points->begin(); i != points->end(); i++)
{
// Add [ x - avgX, y - avgY ] * [ x - avgX ] to mat
// [ y - avgY ]
double diffX = i->x - avgX;
double diffY = i->y - avgY;
mat[0][0] += diffX * diffX;
mat[0][1] += diffX * diffY;
mat[1][1] += diffY * diffY;
}
mat[1][0] = mat[0][1];
// http://www.math.harvard.edu/archive/21b_fall_04/exhibits/2dmatrices/index.html
double T = mat[0][0] + mat[1][1]; // Trace
double D = mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0]; // Determinant
double L1 = T/2 + sqrt(T*T/4 - D); // Eigenvalues
double L2 = T/2 - sqrt(T*T/4 - D); //
aDist = sqrt(L1);
bDist = sqrt(L2);
I have checked the inputs in the debugger, and they look OK. I have tried this code for some simple shapes (circles, ellipses, rectangles) with no rotation, and aDist and bDist are proportional to the shape but always too large. For example, if 'points' is a 100x100 circle, then aDist and bDist are 582.
Update: After summing up mat, I now divide each element by points->size(), as Mike suggested. If points is the square <(0,0),(10,0),(10,10),(0,10)>, then aDist and bDist are now 5, as expected which is too small. As more pixels are added to that square, aDist and bDist get smaller. For example, <(0,0),(5,0),(10,0),(10,5),(10,10),(5,10),(0,10),(0,5)> gives a radius of sqrt(18.75)=4.33.
A: You need to divide mat by the total number of points to get the correct covariance matrix.
| |
doc_23527524
|
Here is the code I have tried using from the following link :
upload file to ftp site using vb.net
I am using Visual studio 2015 community and it doesn`t recognise the FTPWebRequest method.
I have also looked at the BackgroundTransfer sample from the following link :
https://github.com/Microsoft/Windows-universal-samples
But when I run it and enter my FTP server address in the form
ftp://IPAddress/TestFolder/
and attach a simple text file it gives me an error at the line :
Dim upload As UploadOperation = uploader.CreateUpload(uri, file)
as The parameter is incorrect.
I can`t seem to find anything else to help with a UWP app as all the sites and forums I have looked at all seem to have similar code to the first link.
I can access the Ftp site through windows explorer on my laptop and drag and drop files that way so I know the site is accessible.
Not sure if there is a reference I am missing, I have the Internet(client) and Internet(client and Server) enabled in the appxmanifest.
A: From MSDN:
Download operations via FTP are supported. However, for FTP operations, authentication credentials must be provided within the specified URI. For example, ftp://user:password@server/file.txt
BackgroundDownloader class
A: Thanks for the replies.
I decided to use a package from https://www.chilkatsoft.com/ftp-2-dotnet.asp. which is available as a nuget package.
With a few lines of code I was able to upload a file using ftp with no problems.
| |
doc_23527525
|
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.esty.beyond.jossto"
android:installLocation="internalOnly"
android:versionCode="4"
android:versionName="1.4">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true" >
</supports-screens>
<compatible-screens>
<!-- small size screens -->
<screen android:screenSize="small" android:screenDensity="ldpi" />
<screen android:screenSize="small" android:screenDensity="mdpi" />
<screen android:screenSize="small" android:screenDensity="hdpi" />
<screen android:screenSize="small" android:screenDensity="xhdpi" />
<!--Only hdpi and xhdpi for normal size screens -->
<screen android:screenSize="normal" android:screenDensity="ldpi" />
<screen android:screenSize="normal" android:screenDensity="mdpi" />
<screen android:screenSize="normal" android:screenDensity="hdpi" />
<screen android:screenSize="normal" android:screenDensity="xhdpi" />
<!-- all large size screens -->
<screen android:screenSize="large" android:screenDensity="ldpi" />
<screen android:screenSize="large" android:screenDensity="mdpi" />
<screen android:screenSize="large" android:screenDensity="hdpi" />
<screen android:screenSize="large" android:screenDensity="xhdpi" />
<!-- all xlarge size screens -->
<screen android:screenSize="xlarge" android:screenDensity="ldpi" />
<screen android:screenSize="xlarge" android:screenDensity="mdpi" />
<screen android:screenSize="xlarge" android:screenDensity="hdpi" />
<screen android:screenSize="xlarge" android:screenDensity="xhdpi" />
<!-- Special case for Nexus 7 -->
<screen android:screenSize="large" android:screenDensity="213" />
</compatible-screens>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name="com.esty.beyond.jossto.AppController"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:theme="@style/AppTheme" >
<receiver
android:name="com.esty.beyond.jossto.ConnectionChangeReceiver"
android:label="NetworkConnection" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<activity
android:name="com.esty.beyond.jossto.ChatsActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.esty.beyond.jossto.BootCompletedIntentReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name="com.esty.beyond.jossto.PushService"
android:process=":remote" />
<activity
android:name="com.esty.beyond.jossto.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:label="@string/title_activity_chats"
>
</activity>
<activity
android:name="com.esty.beyond.jossto.PhoneVerificationActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="SMS Verification"
android:screenOrientation="portrait" />
<activity
android:name="com.esty.beyond.jossto.UserChatActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_chat"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" >
</activity>
<activity
android:name="com.esty.beyond.jossto.ChatSettingsActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_chat_settings"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.SelectContactActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_select_contact"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.ContactInfoActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_contact_info"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.NetworkUsageActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_network_usage"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.NotificationsActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_notifications"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.PrivacyActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_privacy"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.UserProfileActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_profile"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.DeleteMyAccountActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_delete_my_account"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.MyProfileSettingsActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_profile_settings"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.SettingsActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_settings"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.BlockContactsActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_block_contacts"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.ProfileInfoActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_profile_info"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.BusyActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_busy"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.ConfirmSms"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_confirm_sms"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.esty.beyond.jossto.Profile_Advance_Settings"
android:label="@string/title_activity_profile__advance__settings" >
</activity>
<activity
android:name="com.esty.beyond.jossto.WebBrowser"
android:label="@string/title_activity_web_browser" >
</activity>
<receiver
android:name="com.esty.beyond.jossto.AlarmReceiver"
android:process=":remote" >
</receiver>
<activity
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:name="com.esty.beyond.jossto.ContactTabActivity"
android:label="@string/title_activity_contact_tab"
android:theme="@style/MyActionBarTheme" >
</activity>
<activity
android:name="com.esty.beyond.jossto.PhoneContactsActivity"
android:label="@string/title_activity_phone_contacts" >
</activity>
<activity
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:name="com.esty.beyond.jossto.NearByFriendsActivity"
android:label="Near By" >
</activity>
<activity
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:name="com.esty.beyond.jossto.NearByFriendProfile"
android:label="Friend Profile" >
</activity>
<activity
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:name="com.esty.beyond.jossto.NearByTabActivity"
android:label="Near By"
android:theme="@style/MyActionBarTheme" >
</activity>
<activity
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:name="com.esty.beyond.jossto.NearBySentRequestActivity"
android:label="Sent Request" >
</activity>
<activity
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:name="com.esty.beyond.jossto.NearByPendingRequestActivity"
android:label="@string/title_activity_near_by_pending_request" >
</activity>
</application>
</manifest>
A: This issue is already revolving around the community, try these below links.
Link 1
Link 2
Link 3
which may help you in some case.
| |
doc_23527526
|
var client = ((Socket) asyncResult.AsyncState).EndAccept(asyncResult);
System.ObjectDisposedException: 'Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.'
I was just wondering, what is the right way (in terms of best practice) to avoid an error like this? I'm unsure on how to handle it, how do I check if its disposed before hand, but is that what I should be doing? Or checking something else.
I'm self taught C# so I never learnt things like this, could someone give some insight?
Here is the full class:
internal sealed class SocketHandler : IDisposable
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private readonly Socket _serverSocket;
public SocketHandler()
{
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Load();
}
public void Dispose()
{
_serverSocket?.Close(); // close also calls dispose...
}
private void Load()
{
var config = Program.Server.ConfigHandler;
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, config.GetConfigValueByKey("network.sockets.port").ToInt()));
_serverSocket.Listen(int.Parse(config.GetConfigValueByKey("network.sockets.backlog")));
_serverSocket.BeginAccept(OnAcceptConnection, _serverSocket);
}
private void OnAcceptConnection(IAsyncResult asyncResult)
{
try
{
if (_serverSocket == null)
{
return;
}
var client = ((Socket) asyncResult.AsyncState).EndAccept(asyncResult);
var playerHandler = Program.Server.BaseHandler.PlayerHandler;
var players = playerHandler.Players;
var config = Program.Server.ConfigHandler;
var maxConnections = int.Parse(config.GetConfigValueByKey("game.players.limit"));
var maxConnectionsPerIp = int.Parse(config.GetConfigValueByKey("game.players.ip_limit"));
if (players.Count >= maxConnections)
{
Logger.Warn("Incoming connection was refused because the player limit was exceeded.");
client.Shutdown(SocketShutdown.Both);
client.Close();
return;
}
if (players.Values.Count(x => x != null && !x._disconnected && x.getIp() == client.RemoteEndPoint.ToString().Split(':')[0]) > maxConnectionsPerIp)
{
Logger.Warn("Incoming connection was refused because the IP limit was exceeded.");
client.Shutdown(SocketShutdown.Both);
client.Close();
return;
}
var clientId = Randomizer.Next(1, 10000);
Program.Server.BaseHandler.PlayerHandler.TryAddPlayer(clientId, new Player(clientId, client, new InitialPacketParser()));
}
catch (SocketException socketException)
{
Logger.Fatal(socketException, "Failed to accept socket connection.");
}
finally
{
_serverSocket?.BeginAccept(OnAcceptConnection, _serverSocket);
}
}
}
A: As far as I understand the reference source a Socket does not Dispose itself. So, since your _serverSocket is private, you are the only one to control when it is disposed.
Your OnAcceptConnection() method already started to try to check that, but not completely.
In your Dispose() method (or any other place where you Close() or Dispose() your _serverSocket) you need to also set _serverSocket to null. You can do it like this in a thread-safe way:
public class SocketHandler
{
private Socket _serverSocket; // not read-only
/* ... */
public void Dispose()
{
Socket tmp = _serverSocket; // save instance
_serverSocket = null; // set field to null
tmp?.Close();
}
Now your OnAcceptConnection() returns when it checks if (_serverSocket == null) and you avoid the exception.
A: The problem might also come from how you are using SocketHandler in the first place. I can see nothing wrong with how the IDisposable pattern is implemented in your class. The normal way to avoid accessing a Disposable class after it has been disposed is wrapping it in a using statement which will auto-dispose the class after leaving the block:
using( SocketHandler handler = new SocketHandler())
{
(...)
} //handler will be disposed and not accessible after here
For more information on this Microsoft Docs has a good article explaining IDispose
EDIT:
Thanks for pointing out that I was on a completely wrong way to understand the question.
I at least recreated the scenario to best of my knowledge:
class Program
{
static void Main(string[] args)
{
using (C1 instance = new C1())
{
Task.Factory.StartNew(() =>
{
Task.Delay(1000);
bool disposed = (bool)typeof(C1).GetField("disposed", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(instance);
if (disposed)
{
Console.WriteLine("Already disposed will not call DoSomething()");
}
else
{
instance.DoSomething();
}
});
}
Console.ReadKey(true);
}
}
class C1 : IDisposable
{
bool disposed = false;
public C1()
{
}
public void DoSomething()
{
if (disposed)
throw new ObjectDisposedException("C1");
Console.WriteLine("Still existing!");
}
public void Dispose()
{
Dispose(true);
Console.WriteLine("Disposed!");
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
disposed = true;
}
}
And managed to workaround the exception with a reflection. Assuming that microsoft will have used the same pattern + namings as they are according to their Framework Design Guidelines this solution could at least be used as a workaround.
But I highly doubt that this the best way.
| |
doc_23527527
|
Another approach I'm thinking is downloading the master folder from the remote repository then do the mock upgrading there. Please advise me if there is a better and more efficient way of doing this.
A: You can create a new branch and it will not affect other branches. So to answer your question, go ahead and upgrade Rails!
| |
doc_23527528
|
But how can I override this flag? Are there global Wicket-settings for this?
A: If you found this flag you might have noticed this method
public final FormComponent<T> setConvertEmptyInputStringToNull(boolean flag)
that's used to set the flag to whatever boolean value desired...
It's part of the AbstractTextComponent parent-class to TextField. For further information, check the JavaDocs
| |
doc_23527529
|
What is the difference between a function expression vs declaration in JavaScript?
var functionName = function() {} vs function functionName() {}
I came to know about the difference that one is defined at parse time and the other one at run time. But my curiosity is regarding which to use and which not to use and why one will be preffered over other.
A: This is a detailed writeup on the topic.
FYI, you can have a functionName before the parentheses even in a function expression:
var functionName = function functionName() { ... }
One reason to use a form that has function name in it (between function and ()) is so that a debugger can helpfully tell you what function something occurred in, when displaying a stack trace.
One reason to use a function expression is so that you have more flexibility about putting the function into a namespace. So if you are using namespace to organize your javascript into modules, you may well need to use function expressions.
For those reasons, the above form (function expression with function name) could be considered the best of both worlds. But it has the disadvantage of being repetitive (DRY!).
A: Really very little. function foo(x) is just shorthand for foo = function(x). Adding the var limits the scope as with any name in Javascript.
| |
doc_23527530
|
Now I have to pack the program into RPM package, and it should be able to auto install the dependencies so that the RPM package can be installed on a clean RHEL machine, and the program can run instantly after the installation.
Problem is if I write the below script in SPEC file %pre section, it gets stuck during "transaction".
sudo yum groupinstall "Development Tools" -y
sudo yum install mysql-server mysql-client -y
It seems you can't use another rpm installation tool in SPEC file.
How do I do this?
A: You can't do it directly, you cannot install another RPM from within your RPM spec file.
The normal way, which you should follow, is to make your RPM depends on the other RPMs it needs, e.g. by adding this to your .spec file:
Requires: gcc, mysql-server, mysql-devel
When you then try to install your rpm with the rpm command:
rpm -ivh yourrpm-1.0.0.rpm
it will fail and tell you which packages to install, and you have to install those packages manually first.
Or you can use yum to install your rpm file:
yum install ./yourrpm.1.0.0.rpm
and yum will download and install the required dependencies before it installs your RPM package.
A: Yes: there is an exclusive rpmdb lock held while installing preventing all attempts to use rpm from within a package script.
Usually what is done is create a custom yum repository and invoke yum.
Otherwise create a short shell script that invokes rpm/yum to automate your install.
| |
doc_23527531
|
interface A
{
void x();
void y();
}
However, I want vendors to be able to throw exceptions to signal something has failed and potentially the method could thrown a RuntimeException. In each case, the code that calls these methods should handle the failure and continue. Just because 1 vendor throws an NPE, I don't want the system to come crashing down. Instead of leaving it up to the person calling the method (or really down the line maintainence), I would like to make sure each call will catch all exceptions by declaring each method as:
void x() throws Exception;
but this is generally bad practice (PMD doesn't like it and generally I agree with the rule for concrete methods) so I wonder is this an exception to the rule or is there a better way?
Let me be clear, I'm looking for a solution where the caller of the interface is forced to handle all exceptions (including RuntimeExceptions).
To further detail my environment, all of this is running within an OSGi framework. So each vendor packages their code in a bundle and OSGi will handle all exceptions to prevent the entire system from crashing. What I'm really looking at are OSGi service interfaces that will be called by some core bundle. What I want to make sure is that when I iterate through all of the services, one service doesn't throw an NPE and stop the process that is executing. I want to handle it more gracefully by catching all exceptions thrown from the service so the other provided services are still managed.
A: Create your own Exception class ie. MySeviceException and throw it from the interface. The idea here is to throw meaningful exceptions so don't be afraid of creating many custom exception classes if that provides most readability and maintainability for your purposes. You can catch the vendor detailed exceptions in the downstream and wrap them as your custom exception so that the upstream flow does not have to deal with vendor specific exceptions.
class MySeviceException extends Exception{
public MySeviceException() {}
public MySeviceException(String msg) { super(msg); }
public MySeviceException(Throwable cause) { super(cause); }
public MySeviceException(String msg, Throwable cause) { super(msg, cause); }
}
interface A
{
void x() throws MySeviceExceptionException;
void y() throws MySeviceExceptionException;
}
As a rule of thumb never catch Errors, always catch Exceptions and deal with it!
A: Vendors can certainly throw RuntimeException to their heart's content, because they're unchecked. That means you don't have to add the throws clause to the interface.
It also means that clients won't have any warning from the interface definition, and the compiler won't enforce a required try/catch. The only way they'll know is to read your Javadocss.
You can create a custom exception that extends java.lang.Exception; that's a checked exception. You'll have to add it to the throws clause; the compiler will enforce a try/catch around those methods; your clients will have to handle the problem.
A: I would avoid placing the exception throw in the interface because of limitations that you force on implementers. If I must throw an exception by implementing your interface, it will make mockups for testing more difficult.
If something goes wrong in the code that implements your interface, that should be the concern of the programmer of the implementing class.
A: Creating a throws clause, even with a custom exception type, is not really an answer here. You are always going to have things like NPEs. Even if you specify to the vendors that all exceptions must be wrapped in your custom exception type there are going to be cases where somebody makes a mistake and an NPE gets through. If it wasn't for mistakes you wouldn't have NPEs.
Adding "throws Exception" is a bad idea in a lot of cases, but in some cases it works out. In frameworks like Struts and JUnit you can add "throws Exception" without a problem because the framework allows for it. (JUnit wouldn't be very useful if the first exception thrown made the test suite halt.)
You could design the system so that calls to vendor code happen in specific modules that get plugged into the system and which have exception-handling taken care of by the system, similar to how Actions work in Struts. Each Action can throw anything, there's an exception handler that logs what went wrong. That way the business logic that calls into vendor APIs wouldn't have to be bothered with useless exception-catching boilerplate, but if something goes wrong the program doesn't exit.
A: I agree with PMD - declaring that you throw generic Exceptions is ugly. I think it is better to
*
*Define new, domain-specific, non-runtime exception classes (if the built-in-ones will not do; always stick to predefined classes if you match their semantics), and declare them in the methods that can throw them
*Keep runtime exceptions to a bare minimum. They only make sense when you have no control over how you are called, and nothing else will do. If you have any reason to expect them to be thrown in a piece of code you are calling, then catch them as early as makes sense and re-throw them as standard exceptions (see above point).
Recent versions of Java allow you to chain exceptions. For example, if you get a NullPointerException ex while parsing a File f with an external library, you would want to catch it and rethrow it as, say, a new FileParsingException("error parsing " + f + ": " + ex.getMessage(), ex);
A: Depending on your JVM settings, any method has the ability to throw a RuntimeException whether you declare it as throwing Exception or not. Catching/handling RuntimeExceptions is generally a bad practice. While there are some limited cases where this behavior could be required, RuntimeExceptions are primarily an indicator that there is something wrong with the code, rather than the usage of the product. Of course, a major downside to catching RuntimeExceptions (especially if you're ignoring them) is that things could be blowing up in your system and you have no idea that it's happening...then all of a sudden, your system spits out completely invalid data, or crashes anyway from some other reason, making it more difficult to track down the root cause.
See Sun/Oracle's tutorial about exceptions
http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
To answer the question, unless you know exactly what Exception derivative you can expect to be throwing, you're pretty much stuck throwing Exception, though I have major doubts as to the usefulness of throwing the generic Exception class, unless you only care about logging out the stack trace and such so that you know it happened? If you're trying to robustly handle the Exception without knowing what kind of Exception it is, then you probably won't be very successful in handling it properly or even well-enough.
A: You could implement your interface in an abstract class that uses the template method pattern to catch and wrap RuntimeExceptions with a custom exception. However, there is no way to enforce that the vendors use the abstract class (other than documentation).
class MySeviceException extends Exception{
public MySeviceException() {}
public MySeviceException(String msg) { super(msg); }
public MySeviceException(Throwable cause) { super(cause); }
public MySeviceException(String msg, Throwable cause) { super(msg, cause); }
}
interface A
{
void x() throws MySeviceExceptionException;
void y() throws MySeviceExceptionException;
}
class ABase implements A
{
public final void x() throws MySeviceExceptionException {
try {
doX();
} catch(RuntimeException ex) {
throw new MySeviceExceptionException(ex);
}
}
public final void y() throws MySeviceExceptionException {
try {
doY();
} catch(RuntimeException ex) {
throw new MySeviceExceptionException(ex);
}
}
public abstract void doX() throws MySeviceExceptionException;
public abstract void doY() throws MySeviceExceptionException;
}
| |
doc_23527532
|
*
*Pattern wise publisher should just publish an event and should not care about listeners / subscribers for that topic / event.
*In case of JavaScript, lot of frameworks for Pub / Sub publishes event in Sync manner
*for example : framework just maintains map of event to function.
*on particular event occurrence, it iterates over subscribers and calls function one by one - > function_1.apply(context, args) and then function_2.apply(context, args)
*This makes it Synchronous as, unless and until function_1 finishes, function_2 is unaware that particular event happened.
What is an ideal way of implementing Pub / Sub in JavaScript ?
A: I add an "enqueue" parameter to my publish method that when truthy, wraps the actual publish in a setTimeout(..., 0) so that the publisher can choose to have the handling fire immediately, or have it enqueued in the JavaScript execution queue, allowing the current path of execution to complete first.
If you are maintaining your own list of subscribers, you can have the subscribe method implement the enqueue flag as an attribute of the subscription. Thus the publisher could enqueue individual subscribers based on their preference as indicated in their subscription.
| |
doc_23527533
|
Using the drop-down and choosing any other platform works fine. Why is this happening for Android 2.2 previews?
I have also updated the ADT plugin for ecplise as well. Any suggestions?
A: This is a bug: http://code.google.com/p/android/issues/detail?id=17369
A: Updating from 10.0.1 to 12.0.0 resolved this issue for me.
In Eclipse, Help --> Check for updates
You'll likely see three items to be updated to 12.0.0+. Install, restart Eclipse, and the layout view should display without error.
A: More of a fix than an answer, or a fix with no explanation: r-click on the res\layout*.xml file you want to open, select Open with, then select Android Layout Editor. That should open the .xml in the graphical layout/design view you're used to.
For whatever reason, after updating from 10.0.1 to 12.0.0, my layout viewer default changed to XML Editor (one of the options under the context menu referenced above), and I have to manually open with different editor. Opening manually selecting Android Layout Editor seems to set ALE as the default for that .xml file going forward.
A: I had the same issue. Went in Eclipse->Help->CheckforUpdates. Selected everything there and hit next. Keep hitting next until finish. The update will start at the bottom right hand corner. Will also ask for permission. Press "OK". Will restart eclipse and problem is solved. I guess there was a bug with ADT but whatever this update fixed it.
| |
doc_23527534
|
However in case someone wants to print off just price list with certain products I don't want all the pages to print off but only current one.
Is there any print breaking character or tag?
Just in case someone has better idea all I want to achieve is having price list in html to change it in one place but still be able to convert separate product price lists into PDF files for emailing purposes of particular product.
A: Use this CSS:
@media print
{
.page-break { display:block; page-break-before:always; }
}
and then cite this in your HTML where you want the page to break:
<div class="page-break"></div>
And there you go :)
A: As per w3schools, you can also do the following:
@media print {
.page {page-break-after: always;}
}
and then, in your HTML:
<div class="page">
<!-- Page Contents -->
</div>
Or, if you have a footer under every page (for example for page numbering):
@media print {
footer {page-break-after: always;}
}
| |
doc_23527535
|
I would like to offer the user a chance to define a simple report which I would then send to an Excel file (am familiar with the VFP interface to Excel). To that end I need to display the table name and table comment (and a list of fields from the .dbf file itself).
Is there an easy way to extract the ‘Table comment’ part of the ‘Property’ field? I believe that I need to parse that field, since the ‘Table comment’ is embedded within it.
A: Actually in VFP there are more than one place to get that information. You can use DbGetProp(), ie:
open database (_samples+'data\testdata.dbc')
? DbGetProp('Customer', 'TABLE', 'Comment')
Also AFields() have that information:
use (_Samples+'data\Customer')
afields(laFields)
? laFields(1,16)
| |
doc_23527536
|
const mongoose = require("mongoose")
I get back the following error:
/Users/user/shares3/node_modules/mongodb/lib/utils.js:1069
catch {
^
SyntaxError: Unexpected token {
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/Users/user/shares3/node_modules/mongodb/lib/operations/add_user.js:6:17)
This code is as simple as could be. I have tried reinstalling the mongoose package.
Do you have any ideas on how I can troubleshoot this?
A: The issue is caused by using a (very) old version of Node.js that doesn't support try/catch.
| |
doc_23527537
|
for example: given the string 'abaadddefggg'
for length = 3 I should get the output of 'ddd'
for length = 2 I should get 'aa' and so on
any ideas?
A: You could iterate over the strings indexes, and produce all the substrings. If any of these substrings is made up of a single character, that's the substring you're looking for:
def sequence(s, length):
for i in range(len(s) - length):
candidate = s[i:i+length]
if len(set(candidate)) == 1:
return candidate
A: One approach in Python 3.8+ using itertools.groupby combined with the walrus operator:
from itertools import groupby
string = 'abaadddefggg'
k = 3
res = next(s for _, group in groupby(string) if len(s := "".join(group)) == k)
print(res)
Output
ddd
An alternative general approach:
from itertools import groupby
def find_substring(string, k):
for _, group in groupby(string):
s = "".join(group)
if len(s) == k:
return s
res = find_substring('abaadddefggg', 3)
print(res)
| |
doc_23527538
|
# int array
int_array = np.array([i for i in range(10)])
squared_int = int_array ** 2
squares = np.array([i**2 for i in range(10)])
squared_int == squares
This gives the output I expect. An array containing the squares of the numbers 0-9
# complex array
complex_array = np.array([complex(i,i) for i in range(10)])
squared_complex = complex_array ** 2
complex_squares = np.array([complex(i,i)*complex(i,i) for i in range(10)])
squared_complex == complex_squares # array of True
I would expect the following statements to yield True, but they do not.
1+1j * 1+1j == complex_squares[1]
2+2j * 2+2j == squared_complex[2]
The content of complex_squares and squared_complex looks like this:
array([0. +0.j, 0. +2.j, 0. +8.j, 0. +18.j, 0. +32.j, 0. +50.j,
0. +72.j, 0. +98.j, 0.+128.j, 0.+162.j])
I also tried to check if complex(i,i) is equivalent with i+ij, which gave a weird result:
complex(1,1) == 1+1j # True
complex(1,1) ** 2 == 1+1j**2 # False
complex(1,1) ** 2 # 2j
1+1j ** 2 # 0j
1+1j * 1+1j # 1+2j
complex(1,1) * complex(1,1) # 2j
Why is this happening?
Why is complex(i,i) and i+ij inconsistent?
I thought they were the same thing.
A: As stated by @Onyambu:
You need parentheses, i.e. (1+1j)**2. Otherwise you are doing 1+1j*1j, which is not the square of a complex number.
A: Like @André Sbrocco Figueiredo mentioned, the reason is in the fact you didn't use pharantases. Here is the fix:
print(complex(1,1) == 1+1j) # True
print(complex(1,1) ** 2 == (1+1j)**2) # True
print(complex(1,1) ** 2) # 2j
print((1+1j) ** 2) # 2j
print((1+1j) * (1+1j)) # 2j
print(complex(1,1) * complex(1,1)) # 2j
Cheers.
| |
doc_23527539
|
<teiHeader>
<fileDesc>
<titleStmt>
<title> Oxford City Council Health and Environmental Protection Committee meeting. Sample containing about 11223 words speech recorded in public context </title>
<respStmt>
<resp> Data capture and transcription </resp>
<name> Oxford University Press </name>
</respStmt>
</titleStmt>
<editionStmt>
<edition>BNC XML Edition, December 2006</edition>
</editionStmt>
<extent> 11223 tokens; 11688 w-units; 482 s-units </extent>
<publicationStmt>
<distributor>Distributed under licence by Oxford University Computing Services on behalf of the BNC Consortium.</distributor>
<availability> This material is protected by international copyright laws and may not be copied or redistributed in any way. Consult the BNC Web Site at http://www.natcorp.ox.ac.uk for full licencing and distribution conditions.</availability>
<idno type="bnc">KS0</idno>
<idno type="old"> OCCEnv </idno>
</publicationStmt>
<sourceDesc>
<recordingStmt>
<recording n="139401" type="DAT"/>
</recordingStmt>
</sourceDesc>
</fileDesc>
<encodingDesc>
<tagsDecl>
<namespace name="">
<tagUsage gi="align" occurs="69"/>
<tagUsage gi="c" occurs="1408"/>
<tagUsage gi="div" occurs="1"/>
<tagUsage gi="event" occurs="3"/>
<tagUsage gi="mw" occurs="110"/>
<tagUsage gi="pause" occurs="2"/>
<tagUsage gi="s" occurs="482"/>
<tagUsage gi="u" occurs="192"/>
<tagUsage gi="unclear" occurs="65"/>
<tagUsage gi="vocal" occurs="7"/>
<tagUsage gi="w" occurs="11688"/>
</namespace>
</tagsDecl>
</encodingDesc>
<profileDesc>
<creation date="0000">0000-00-00 Origination/creation date not known </creation>
<particDesc n="C872">
<person ageGroup="X" xml:id="PS6H7" role="unspecified" sex="f" soc="AB" dialect="NONE" educ="X">
<persName>Chair</persName>
</person>
<person ageGroup="X" xml:id="PS6H8" role="unspecified" sex="m" soc="UU" dialect="NONE" educ="X">
<persName>g</persName>
</person>
<person ageGroup="X" xml:id="PS6H9" role="unspecified" sex="f" soc="UU" dialect="NONE" educ="X">
<persName>chair2</persName>
</person>
<person ageGroup="X" xml:id="PS6HA" role="unspecified" sex="m" soc="UU" dialect="NONE" educ="X">
<persName>i</persName>
</person>
<person ageGroup="X" xml:id="PS6HB" role="unspecified" sex="m" soc="UU" dialect="NONE" educ="X">
<persName>h</persName>
</person>
<person ageGroup="X" xml:id="PS6HC" role="unspecified" sex="m" soc="UU" dialect="NONE" educ="X">
<persName>foe</persName>
</person>
<person ageGroup="X" xml:id="PS6HD" role="unspecified" sex="f" soc="UU" dialect="NONE" educ="X">
<persName>b</persName>
</person>
<person ageGroup="X" xml:id="PS6HE" role="unspecified" sex="m" soc="UU" dialect="NONE" educ="X">
<persName>a</persName>
</person>
<person ageGroup="X" xml:id="PS6HF" role="unspecified" sex="f" soc="UU" dialect="NONE" educ="X">
<persName>ei</persName>
</person>
<person ageGroup="X" xml:id="PS6HG" role="unspecified" sex="m" soc="UU" dialect="NONE" educ="X">
<persName>bp</persName>
</person>
<person ageGroup="X" xml:id="PS6HH" role="unspecified" sex="m" soc="UU" dialect="NONE" educ="X">
<persName>c</persName>
</person>
<person ageGroup="X" xml:id="PS6HJ" role="unspecified" sex="m" soc="UU" dialect="NONE" educ="X">
<persName>d</persName>
</person>
<person ageGroup="X" xml:id="PS6HK" role="unspecified" sex="f" soc="UU" dialect="NONE" educ="X">
<persName>e</persName>
</person>
<person ageGroup="X" xml:id="PS6HL" role="unspecified" sex="u" soc="UU" dialect="NONE" educ="X">
<persName>d</persName>
</person>
</particDesc>
<settingDesc>
<setting n="OCCEnv" who="PS6H7 PS6H8 PS6H9 PS6HA PS6HB PS6HC PS6HD PS6HE PS6HF PS6HG PS6HH PS6HJ PS6HK PS6HL">
<placeName>Oxfordshire: Oxford </placeName>
<activity> Council Committee Meeting </activity>
</setting>
</settingDesc>
<textClass>
<catRef targets="SPO ALLTIM3 ALLAVA0 ALLTYP2 SCGDOM3 SPOLOG2 SPOREG1"/>
<classCode scheme="DLEE">S meeting</classCode>
<keywords>
<term> (none) </term>
</keywords>
</textClass>
</profileDesc>
<revisionDesc>
<change date="2006-10-21" who="#OUCS">Tag usage updated for BNC-XML</change>
<change date="2000-12-13" who="#OUCS">Last check for BNC World first release</change>
<change date="2000-09-06" who="#OUCS">Redo tagusage tables</change>
<change date="2000-09-01" who="#OUCS">Check all tagcounts</change>
<change date="2000-06-23" who="#OUCS">Resequenced s-units and added headers</change>
<change date="2000-01-29" who="#OUCS">Revised participant details</change>
<change date="2000-01-21" who="#OUCS">Added date info</change>
<change date="2000-01-09" who="#OUCS">Updated all catrefs</change>
<change date="2000-01-09" who="#OUCS">Updated REC elements to include tape number</change>
<change date="2000-01-08" who="#OUCS">Updated titles</change>
<change date="1999-12-25" who="#OUCS">corrected tagUsage</change>
<change date="1999-09-21" who="#UCREL">POS codes revised for BNC-2; header updated</change>
<change date="1994-11-27" who="#dominic">Initial accession to corpus</change>
</revisionDesc>
</teiHeader>
<stext type="OTHERSP">
<div>
<!--
Oxford City Council: Health and Environmental Protection Committee (Nuclear Issues and Pollution Control) Sub-Committee.
Wednesday, 18th April 1990, 2.30pm, Town Hall.-->
<u who="PS6H7">
<s n="3">
<w c5="AV0" hw="well" pos="ADV">Well</w>
<c c5="PUN">, </c>
<w c5="AJ0" hw="good" pos="ADJ">good </w>
<w c5="NN1" hw="afternoon" pos="SUBST">afternoon</w>
<c c5="PUN">, </c>
<w c5="PNI" hw="everybody" pos="PRON">everybody</w>
<c c5="PUN">, </c>
<w c5="PNP" hw="i" pos="PRON">I </w>
<w c5="VVB" hw="think" pos="VERB">think </w>
<w c5="PNP" hw="we" pos="PRON">we</w>
<w c5="VHD" hw="have" pos="VERB">'d </w>
<w c5="AV0" hw="well" pos="ADV">better </w>
<w c5="VVI" hw="get" pos="VERB">get </w>
<w c5="VVN" hw="start" pos="VERB">started</w>
<c c5="PUN">.</c>
</s>
<s n="4">
<w c5="PNP" hw="we" pos="PRON">We </w>
<w c5="VVD" hw="look" pos="VERB">looked </w>
<w c5="AV0" hw="so" pos="ADV">so </w>
<w c5="AJ0" hw="thin" pos="ADJ">thin </w>
<w c5="PRP" hw="on" pos="PREP">on </w>
<w c5="AT0" hw="the" pos="ART">the </w>
<w c5="NN1" hw="ground" pos="SUBST">ground</w>
<c c5="PUN">, </c>
<w c5="PNP" hw="i" pos="PRON">I </w>
<w c5="VVD" hw="think" pos="VERB">thought </w>
<w c5="PNP" hw="we" pos="PRON">we</w>
<w c5="VM0" hw="would" pos="VERB">'d </w>
<w c5="VVI" hw="sit" pos="VERB">sit </w>
<w c5="CJC" hw="and" pos="CONJ">and </w>
<w c5="VVI" hw="wait" pos="VERB">wait </w>
<w c5="CJC" hw="and" pos="CONJ">and </w>
<w c5="VVI" hw="see" pos="VERB">see </w>
<w c5="CJS" hw="if" pos="CONJ">if </w>
<w c5="PNI" hw="everyone" pos="PRON">everyone</w>
<w c5="VBZ" hw="be" pos="VERB">'s </w>
<w c5="VVG-AJ0" hw="come" pos="VERB">coming</w>
<c c5="PUN">, </c>
<w c5="CJC" hw="but" pos="CONJ">but </w>
<w c5="UNC" hw="erm" pos="UNC">erm </w>
<w c5="PNP" hw="we" pos="PRON">we</w>
<w c5="VM0" hw="will" pos="VERB">'ll </w>
<w c5="VHI" hw="have" pos="VERB">have </w>
<w c5="TO0" hw="to" pos="PREP">to </w>
<w c5="VVI" hw="get" pos="VERB">get </w>
<w c5="VVN" hw="start" pos="VERB">started </w>
<w c5="AV0" hw="anyway" pos="ADV">anyway</w>
<c c5="PUN">.</c>
</s>
<s n="5">
<w c5="PNP" hw="we" pos="PRON">We</w>
<w c5="VM0" hw="will" pos="VERB">'ll </w>
<w c5="VVI" hw="welcome" pos="VERB">welcome</w>
<c c5="PUN">, </c>
<w c5="PNP" hw="we" pos="PRON">we </w>
<w c5="VHB" hw="have" pos="VERB">have </w>
<w c5="CRD" hw="two" pos="ADJ">two </w>
<w c5="NN2" hw="speaker" pos="SUBST">speakers</w>
<c c5="PUN">, </c>
<w c5="NP0" hw="mr" pos="SUBST">Mr </w>
<w c5="NP0" hw="bob" pos="SUBST">Bob </w>
<w c5="NP0" hw="plumtree" pos="SUBST">Plumtree</w>
<c c5="PUN">, </c>
<w c5="CJC" hw="and" pos="CONJ">and </w>
<w c5="NP0" hw="ms" pos="SUBST">Ms </w>
<w c5="NP0" hw="erica" pos="SUBST">Erica </w>
<w c5="NP0" hw="ison" pos="SUBST">Ison</w>
<c c5="PUN">.</c>
</s>
<s n="6">
<w c5="PNP" hw="we" pos="PRON">We </w>
<w c5="VVD" hw="ask" pos="VERB">asked </w>
<w c5="PNP" hw="they" pos="PRON">them </w>
<w c5="PRP" hw="to" pos="PREP">to </w>
<w c5="AT0" hw="the" pos="ART">the </w>
<w c5="NN1" hw="meeting" pos="SUBST">meeting </w>
<w c5="CJC" hw="and" pos="CONJ">and </w>
<w c5="PNP" hw="we" pos="PRON">we </w>
<w c5="VVB" hw="look" pos="VERB">look </w>
<w c5="AV0" hw="forward" pos="ADV">forward </w>
<w c5="PRP" hw="to" pos="PREP">to </w>
<w c5="VVG-NN1" hw="listen" pos="VERB">listening </w>
<w c5="PRP" hw="to" pos="PREP">to </w>
<w c5="PNP" hw="you" pos="PRON">you </w>
<w c5="AV0" hw="later" pos="ADV">later </w>
<w c5="AVP" hw="on" pos="ADV">on </w>
<w c5="PRP" hw="in" pos="PREP">in </w>
<w c5="AT0" hw="the" pos="ART">the </w>
<w c5="NN1" hw="agenda" pos="SUBST">agenda</w>
<c c5="PUN">.</c>
</s>
<s n="7">
<w c5="AT0" hw="the" pos="ART">The </w>
<w c5="NN2" hw="minute" pos="SUBST">minutes </w>
<w c5="PRF" hw="of" pos="PREP">of </w>
<w c5="AT0" hw="the" pos="ART">the </w>
<w c5="NN1" hw="meeting" pos="SUBST">meeting </w>
<w c5="VVD-VVN" hw="hold" pos="VERB">held </w>
<w c5="PRP" hw="in" pos="PREP">in </w>
<w c5="NP0" hw="january" pos="SUBST">January</w>
<c c5="PUN">.</c>
</s>
<s n="8">
<w c5="DT0" hw="any" pos="ADJ">Any </w>
<w c5="NN2" hw="correction" pos="SUBST">corrections </w>
<w c5="PRP" hw="to" pos="PREP">to </w>
<w c5="AT0" hw="the" pos="ART">the </w>
<w c5="NN2" hw="minute" pos="SUBST">minutes </w>
<w c5="ORD" hw="first" pos="ADJ">first</w>
<c c5="PUN">?</c>
</s>
<s n="9">
<w c5="NN1-VVB" hw="page" pos="SUBST">Page </w>
<w c5="CRD" hw="1" pos="ADJ">1</w>
<c c5="PUN">?</c>
</s>
<s n="10">
<w c5="NN1" hw="page" pos="SUBST">Page </w>
<w c5="CRD" hw="2" pos="ADJ">2</w>
<c c5="PUN">?</c>
</s>
<s n="11">
<w c5="NN1" hw="page" pos="SUBST">Page </w>
<w c5="CRD" hw="3" pos="ADJ">3</w>
<c c5="PUN">?</c>
</s>
</u>
<u who="PS6H8">
<s n="12">
<w c5="ITJ" hw="yes" pos="INTERJ">Yes</w>
<c c5="PUN">, </c>
<w c5="NP0" hw="judith" pos="SUBST">Judith </w>
<w c5="NP0-NN1" hw="gaffan" pos="SUBST">Gaffan </w>
<w c5="PNP" hw="i" pos="PRON">I </w>
<w c5="VVB" hw="believe" pos="VERB">believe</w>
<c c5="PUN">, </c>
<w c5="UNC" hw="erm" pos="UNC">erm </w>
<w c5="XX0" hw="not" pos="ADV">not </w>
<w c5="NP0" hw="judith" pos="SUBST">Judith </w>
<w c5="NP0-NN1" hw="gaffon" pos="SUBST">Gaffon</w>
<c c5="PUN">, </c>
<w c5="DTQ" hw="whatever" pos="PRON">whatever </w>
<w c5="DT0" hw="that" pos="ADJ">that </w>
<w c5="VVD" hw="mean" pos="VERB">meant</w>
<c c5="PUN">, </c>
<w c5="PNP" hw="it" pos="PRON">it</w>
<w c5="VBZ" hw="be" pos="VERB">'s </w>
<align with="KS0LC002"/>
</s>
</u>
<u who="PS6H8">
<s n="483">
<w c5="EX0" hw="there" pos="PRON">There </w>
<w c5="VBZ" hw="be" pos="VERB">is </w>
<w c5="AT0" hw="a" pos="ART">a </w>
<w c5="NN1" hw="school" pos="SUBST">school </w>
<w c5="PRP" hw="in" pos="PREP">in </w>
<w c5="NP0" hw="ferry" pos="SUBST">Ferry </w>
<w c5="NP0" hw="hinksey" pos="SUBST">Hinksey </w>
<w c5="NP0" hw="road" pos="SUBST">Road </w>
<w c5="VBZ" hw="be" pos="VERB">is</w>
<w c5="XX0" hw="not" pos="ADV">n't </w>
<w c5="EX0" hw="there" pos="PRON">there</w>
<c c5="PUN">, </c>
<w c5="AT0" hw="a" pos="ART">a </w>
<w c5="AJ0" hw="middle" pos="ADJ">middle </w>
<w c5="NN1" hw="school" pos="SUBST">school </w>
<w c5="PNP" hw="i" pos="PRON">I </w>
<w c5="VVB" hw="think" pos="VERB">think</w>
<c c5="PUN">, </c>
<w c5="AV0" hw="so" pos="ADV">so </w>
<w c5="DT0" hw="that" pos="ADJ">that</w>
<w c5="VBZ" hw="be" pos="VERB">'s </w>
<w c5="AT0" hw="the" pos="ART">the </w>
<w c5="AJ0" hw="only" pos="ADJ">only </w>
<w c5="PNI" hw="one" pos="PRON">one </w>
<w c5="PNP" hw="i" pos="PRON">I </w>
<w c5="VVB" hw="know" pos="VERB">know</w>
<c c5="PUN">.</c>
</s>
<s n="484">
<w c5="AT0" hw="the" pos="ART">The </w>
<w c5="NN1" hw="thing" pos="SUBST">thing </w>
<w c5="PNP" hw="i" pos="PRON">I</w>
<w c5="VM0" hw="would" pos="VERB">'d </w>
<w c5="AV0" hw="really" pos="ADV">really </w>
<w c5="VVI" hw="like" pos="VERB">like </w>
<w c5="VBZ" hw="be" pos="VERB">is </w>
<w c5="AT0" hw="a" pos="ART">a </w>
<w c5="NN1" hw="glossary" pos="SUBST">glossary </w>
<w c5="PRF" hw="of" pos="PREP">of </w>
<w c5="NN2" hw="term" pos="SUBST">terms</w>
<c c5="PUN">.</c>
</s>
</u>
</div>
</stext>
</bncDoc>
the xquery file
let $file := doc("C:/Users/money/Desktop/xml/files/KS0.xml")/bncDoc/stext/div/u/s/w
return
for $value in distinct-values(for $node in $file where $node[text()] = "has" return normalize-space(lower-case($node/following-sibling::node()[1])))
let $count := count(for $node in $file where $node[text()] = "has" return normalize-space(lower-case($node/following-sibling::node()[1])) eq $value)
return concat($value, " ", $count)
the above code produces output
*
*large 26
*been 26
*gone 26
*done 26
*a 26
*26
*intentions 26
*just 26
*got 26
*to 26
*now 26
*in 26
*tropical 26
*since 26
*dare 26
in the output above 26 is wrong value
26 are the number of time we had match on condition where node text is "has"
after distinct we get 17 results which are ok but 26 (frequency is wrong)
output should be
*
*large 1
*been 2
*gone 1
*done 1
*a 6
etc
A: Perhaps the following is what you want (you haven't really explained what you are trying to achieve):
declare variable $search-term as xs:string external := 'has';
let $words := doc("C:/Users/money/Desktop/xml/files/KS0.xml")/bncDoc/stext/div/u/s/w
return
for $word in $words[normalize-space() = $search-term]
group by $sibling := normalize-space($word/following-sibling::w[1])
return $sibling || ' ' || count($word)
| |
doc_23527540
|
Should I use components instead of controllers? Or should I keep using controllers and use the components just for frontend stuff?
Which is the best practice?
A: It totally depends on how you feel comfortable when structuring your application. Neither way is a best practice as such, but you may appreciate the consistency of using components everywhere.
I've seen some Livewire apps that take a minimal approach and just nest Livewire components within their standard controller-driven app. If you're easing an existing app into Livewire, this is perfect as it allows you to transition parts of it at a time. However, it's not the approach I would take if I were building an app from scratch.
I prefer to ditch controllers altogether. I enjoy having a complete Livewire component hierarchy that represents my app, with my page components at primary level, and then any nested components in a directory of the same name. Let's take this example -
app/Http/Livewire
- Account.php < Account page component
- Account < Account page nested components directory
- UpdateNameForm.php < Nested update name component
- UpdatePasswordForm.php < Nested update password component
- DeleteForm.php < Nested account deletion component
- Dashboard.php < Dashboard page component
To me, it really doesn't matter if some of my page components are static. There's not really any significant performance overhead of using Livewire to render a view as opposed to a controller. You know exactly where to look for lots of your application logic, without digging to see if a page is dynamic or not. You're also able to benefit from some sweet features that Livewire provides, such as route model binding using a typed component property. You can even remove your component's render() method if you are following the default file naming conventions.
| |
doc_23527541
|
After adding five lines to the TextView I want to start to add to the beginning of the text view.
For example: (numbers as text), 1,2,3,4,5 -> 6,2,3,4,5 -> 6,7,3,4,5 and so on.
I thought about using StringBuilder but I don't see an efficient way to implement this.
The delimiter of each row is "\n\n" maybe it will help to solve the problem.
Or maybe should I just do 5 textView's and have some switch case between them?
Button xml:
<TextView
android:id="@+id/searchesInputTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollHorizontally="false"
android:width="300dp"
android:height="200dp"
android:background="@drawable/border_style"
android:maxLines="5"
android:layout_marginTop="24dp"
/>
in MainActivity.java:
public class MainActivity extends AppCompatActivity {
private TextView searchesTextView;
private ImageButton refreshCurrentLocationButton;
private String myText = "";
refreshCurrentLocationButton = (ImageButton) findViewById(R.id.currentLocationRefreshImageButton);
searchesTextView = (TextView) findViewById(R.id.searchesInputTextView);
refreshCurrentLocationButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Actual code
myText += location.ToString() + "\n\n";
searchesTextView.setText(myText);
});
}
| |
doc_23527542
|
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(userItems: UserItemModel[], searchTerm: string): UserItemModel[] {
if (!userItems) { return []; }
if (!searchTerm) { return userItems; }
searchTerm = searchTerm.toLocaleLowerCase();
return userItems.filter(ui => {
return ui.item?.name?.toLocaleLowerCase().includes(searchTerm);
});
}
}
Here I can use only a simple string as searchTerm. How can I write a new pipe to support an array of strings as a searchTerms?
e.g. searchTerms: string[]
transform(userItems: UserItemModel[], searchTerms: string[]): UserItemModel[] {
The use case here is I need to filter the content of an array using a Category filter (i.e. multiple categories).
A: you could use Array.prototype.some for the checking. (or Array.prototype.every depending on your requirement - if wish to filter these which include all the search terms only)
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(userItems: UserItemModel[], searchTerms: string[]): UserItemModel[] {
if (!userItems) { return []; }
if (!searchTerms) { return userItems; }
return userItems.filter(ui => {
return searchTerms.some(term => ui.item?.name?.toLocaleLowerCase().includes(term.toLocaleLowerCase()));
});
}
}
| |
doc_23527543
|
def "test1"() {
when:
sharedVar1 = doSomething(10, 20)
then:
sharedVar1 > 0
}
def "test2"() {
when:
sharedVar2 = doSomething(3, 7)
then:
sharedVar2 > 0
}
...
There can be upwards of eight of these in a row, all doing exactly the same thing, just with different variables.
I attempted to make this simpler using @Unroll and data tables, like so:
@Unroll
def "test #n"() {
when:
localVar = doSomething(a, b)
then:
localVar > 0
where:
localVar | a | b | n
sharedVar1 | 10 | 20 | 1
sharedVar2 | 3 | 7 | 2
...
}
But I've come across the (in hindsight) obvious problem where the assignment in the when: block is assigning the value to the local variable localVar and not the shared variable that I want to assign the value to.
Is there any simple way to use the data-table/data-pipe style of writing these tests that allows me to assign to the shared variables, or am I essentially limited to only using this style of testing when I don't need to assign values to shared variables?
| |
doc_23527544
|
When you select a service, a div removes class ".disabled" and the checkboxes remove attribute "disabled" (unclickable)
What I want to do is the following, after selecting the option "Mobile Application", this will happen:
*
*Class disabled is removed from
<div id="appoptions" class="disabled"></div>
*Attribute disabled is also removed, from checkboxes:
<input type="checkbox "class="servico" disabled>
*In the end, both must be like:
<div id="appoptions"></div>
<input type="checkbox "class="servico">
FIDDLE: https://jsfiddle.net/ujgx4st3/3/
Any help appreciated.
HTML
<select>
<option selected="selected" id="service">Choose one of the options</option>
<optgroup label=""></optgroup>
<optgroup label="Full webpage">
<option value="webpage">Create a new, custom website</option>
<option value="reweb">Modernize our current website</option>
<option value="trasnf">I don't know what I'm looking for</option>
</optgroup>
<optgroup label=""></optgroup>
<optgroup label="Design Services">
<option value="logo">Logo Design</option>
<option value="branding">Branding</option>
<option value="webdesign">Webpages design</option>
<option value="mobile">Social Design <label class="hidden-xs">(Youtube, Facebook, Twitter, etc)</label></option>
<option value="uxui">Mobile UX/UI</option>
</optgroup>
<optgroup label=""></optgroup>
<optgroup label="Web Development">
<option value="manage">Website Management</option>
<option value="manage">Update to Responsive</option>
<option value="coding">Page Coding</option>
<option value="software">Software Programming</option>
<option value="mobile">Mobile Application</option>
</optgroup>
<optgroup label=""></optgroup>
<optgroup label="SEO & Social Media">
<option value="smarket">Social Marketing <label class="hidden-xs">(Facebook, Twitter, Youtube, etc)</label></option>
<option value="seo">Search Engine Optimization</option>
</optgroup>
<optgroup label=""></optgroup>
<optgroup label="Website with CMS">
<option value="wordpress">Wordpress</option>
<option value="joomla">Joomla</option>
<option value="drupal">Drupal</option>
<option value="magento">Magento</option>
</optgroup>
</select>
<div id="appoptions1" class="col-md-3 disabled">
<div style="margin: 25px 0;">
<label><b>Application options</b> <small>(mobile)</small></label></br></br>
<input type="checkbox" name="platform" value="android" disabled class="servico">Android</br>
<input type="checkbox" name="platform" value="apple" disabled class="servico">Apple</br>
<input type="checkbox" name="platform" value="windows" disabled class="servico">Windows Phone</br>
<input type="checkbox" name="platform" value="webapp" disabled class="servico">Web application</br>
</div>
</div>
jQuery
function enable_cb() {
var state = $('.check').attr('disabled');
if ( $('select option:selected').attr() == 'mobile' ) {
$('#addoptions').removeClass('disabled');
} else {
return false;
}
};
A: I suspect you're getting an error on your Javascript console, try the following:
function enable_cb(element) {
var state = $(element).attr('disabled');
$(element).prop('disabled', !state);
}
If you're using jQuery 1.6+, avoid using prop( ) since it has been deprecated in favor of attr( );
| |
doc_23527545
|
Suppose I have a 1st version:
<person version="1.0">
<firstname></firstname>
<lastname></lastname>
</person>
And a 2nd version:
<person version="2.0">
<firstname></firstname>
<lastname></lastname>
<birthdate></birthdate>
</person>
Can I do something like this? What's the best solution to model these two objects in XSD?
A: In XSD 1.1 you can use conditional type attribution (or "type alternatives") where you declare the type of the element based on the value of one of its attributes, using an XPath predicate.
There's no equivalent in XSD 1.0.
| |
doc_23527546
|
How can I get these vars from one external script in my other script?
Example: MyVars.php
<?
$One = "This is one";
$Two = "This is two";
?>
Script on another server: GetVars.php
<?
include 'http://www.MySite.com/MyVars.php';
echo $One . $Two;
?>
The vars are not showing up on the second site. Is there a way I can access them?
Thanks
-Ed
A: You can't include a remote script the way you're trying to, particularly as executable code. The remote .php script will almost certainly be (and should be) executed by the remote server, and only its output (i.e. the stuff it echos) will be returned to the requesting client (i.e. your code).
You should download whatever PHP script you need, upload it to your server, then include it locally.
A: This should work. Including files, basically "smashes" the PHP scripts into one large PHP that the server executes. Try including the file with a relative URL.
UPDATE: Sorry, didn't see the part about you need to pull it from an external site. Hmm... if you own that site, you would need to find someway to access it with a relative URL. For security reasons, you cannot include scripts from another site/server like you are doing.
A: The script is on another server? I would imagine that would cause problems. You wouldn't be able to include anything (if you could, serious security problems would arise). The two files must be on the same server.
A: According to the manual, you may be able to do this, but use Get to retrieve the values of $One and $Two
http://php.net/manual/en/function.include.php
| |
doc_23527547
|
The current user is either an instance of dajngo.contrib.auth.User for logged in people or AnonymousUser for non-logged in people. The serializer is as follows,
class UserSerializer(serializers.HyperlinkedModelSerializer):
comments = serializers.HyperlinkedRelatedField(many = True, view_name = 'comment-detail')
class Meta:
model = User
fields = ('url', 'username', 'comments', 'first_name', 'last_name')
with the following view
class CurrentUserView(APIView):
'''
Returns the current user, logged in or not
'''
def get(self, request, *args, **kwargs):
serializer = serializers.UserSerializer(request.user)
return Response(serializer.data)
This serializer works fine for logged in users i.e. it patches on the 'comments' field and sends it off. However for AnonymousUser it chokes. It claims that there is no method 'comments' (which there isn't but it should be patched on right?) and if I remove the 'comments' requirement from fields it then complains about no 'first_name'.
Is this an issue with AnonymousUser not being an instance of django.contrib.auth.User? If so, how do I remedy it?
I realise I could check at the View level and return a custom data object if it is an instance of AnonymousUser but is there a neater way to do this?
A: It's better to serialize like this, moving authentication check to backend (where it belongs):
{
'is_logged_in': True,
'user': <<serialized user>>,
}
and:
{
'is_logged_in': False,
'user': None, # or something else like this
}
It's common solution in many APIs. Metadata is on top of JSON and possible objects under a key(s). You can check if user is AnonymousUser or User by checking .is_authenticated() - it's been specially created for such purpose (compare with:
AnonymousUser).
A: Modify your view like shown below
class CurrentUserView(APIView):
'''
Returns the current user, logged in or not
'''
def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
serializer = serializers.UserSerializer(request.user)
return Response(serializer.data)
else:
return Response([])`
| |
doc_23527548
|
I've tried to remove server and add it again. It worked for a while but after I restarted my computer it produced a same error.
Below is the error output.
Warning: Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-1, realClassName=org.glassfish.grizzly.http2.Http2AddOn
Info: Shutdown requested
MultiException stack 1 of 2
java.lang.IllegalArgumentException: URI has a query component
at java.io.File.<init>(File.java:427)
at com.sun.enterprise.v3.server.ApplicationLoaderService.processApplication(ApplicationLoaderService.java:370)
at com.sun.enterprise.v3.server.ApplicationLoaderService.postConstruct(ApplicationLoaderService.java:243)
at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:326)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:374)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:228)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:85)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
MultiException stack 2 of 2
java.lang.IllegalStateException: Unable to perform operation: post construct on com.sun.enterprise.v3.server.ApplicationLoaderService
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:392)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:228)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:85)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Severe: Startup service failed to start
MultiException stack 1 of 2
java.lang.IllegalArgumentException: URI has a query component
at java.io.File.<init>(File.java:427)
at com.sun.enterprise.v3.server.ApplicationLoaderService.processApplication(ApplicationLoaderService.java:370)
at com.sun.enterprise.v3.server.ApplicationLoaderService.postConstruct(ApplicationLoaderService.java:243)
at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:326)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:374)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:228)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:85)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
MultiException stack 2 of 2
java.lang.IllegalStateException: Unable to perform operation: post construct on com.sun.enterprise.v3.server.ApplicationLoaderService
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:392)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:228)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:85)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Info: Grizzly Framework 2.3.23 started in: 935ms - bound to [/0.0.0.0:8080]
Warning: Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-2, realClassName=org.glassfish.grizzly.http2.Http2AddOn
Info: Grizzly Framework 2.3.23 started in: 3ms - bound to [/0.0.0.0:8181]
Warning: Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=admin-listener, realClassName=org.glassfish.grizzly.http2.Http2AddOn
Info: HV000001: Hibernate Validator 5.1.2.Final
Info: Grizzly Framework 2.3.23 started in: 7ms - bound to [/0.0.0.0:4848]
Info: Grizzly Framework 2.3.23 started in: 2ms - bound to [/0.0.0.0:3700]
Info: Server shutdown initiated
Severe: Shutdown required
MultiException stack 1 of 1
MultiException stack 1 of 2
java.lang.IllegalArgumentException: URI has a query component
at java.io.File.<init>(File.java:427)
at com.sun.enterprise.v3.server.ApplicationLoaderService.processApplication(ApplicationLoaderService.java:370)
at com.sun.enterprise.v3.server.ApplicationLoaderService.postConstruct(ApplicationLoaderService.java:243)
at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:326)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:374)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:228)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:85)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
MultiException stack 2 of 2
java.lang.IllegalStateException: Unable to perform operation: post construct on com.sun.enterprise.v3.server.ApplicationLoaderService
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:392)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:228)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:85)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Info: Server shutdown initiated
Info: Registered com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishImpl@7b3315a5 as OSGi service registration: org.apache.felix.framework.ServiceRegistrationImpl@29ea78b1.
Info: Unregistered com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishImpl@7b3315a5 from service registry.
Info: FileMonitoring shutdown
Warning: Exception while unregistering:
java.lang.IllegalStateException: Service already unregistered.
at org.apache.felix.framework.ServiceRegistrationImpl.unregister(ServiceRegistrationImpl.java:123)
at com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishImpl.unregisterService(EmbeddedOSGiGlassFishImpl.java:93)
at com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishImpl.stop(EmbeddedOSGiGlassFishImpl.java:81)
at com.sun.enterprise.v3.admin.StopServer.doExecute(StopServer.java:78)
at com.sun.enterprise.v3.admin.StopDomainCommand.execute(StopDomainCommand.java:96)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
at org.glassfish.api.AsyncImpl$1$1.run(AsyncImpl.java:76)
Completed shutdown of Log manager service
Info: Shutdown procedure finished
| |
doc_23527549
|
2020-03-24 08:26:47.590 INFO 1 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.4.10.Final}
2020-03-24 08:26:47.821 INFO 1 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-03-24 08:26:48.015 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-03-24 08:26:48.125 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-03-24 08:26:48.151 INFO 1 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect
or in debug
2020-03-24 08:19:43.856 DEBUG 1 --- [onnection adder] o.p.core.v3.ConnectionFactoryImpl : Send Buffer Size is 43,520
2020-03-24 08:19:43.935 DEBUG 1 --- [onnection adder] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection@7b248da4
2020-03-24 08:19:43.935 DEBUG 1 --- [onnection adder] org.postgresql.Driver : Connecting with URL: jdbc:postgresql://157.46.186.128:62013/db
2020-03-24 08:19:43.935 DEBUG 1 --- [onnection adder] org.postgresql.jdbc.PgConnection : PostgreSQL JDBC Driver 42.2.9
2020-03-24 08:19:43.935 DEBUG 1 --- [onnection adder] org.postgresql.jdbc.PgConnection : setDefaultFetchSize = 0
2020-03-24 08:19:43.935 DEBUG 1 --- [onnection adder] org.postgresql.jdbc.PgConnection : setPrepareThreshold = 5
2020-03-24 08:19:43.935 DEBUG 1 --- [onnection adder] o.p.core.v3.ConnectionFactoryImpl : Trying to establish a protocol version 3 connection to 160.46.186.128:62013
2020-03-24 08:19:43.936 DEBUG 1 --- [onnection adder] o.p.core.v3.ConnectionFactoryImpl : Receive Buffer Size is 186,240
2020-03-24 08:19:43.937 DEBUG 1 --- [onnection adder] o.p.core.v3.ConnectionFactoryImpl : Send Buffer Size is 43,520
2020-03-24 08:19:44.007 DEBUG 1 --- [onnection adder] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection@205272d5
2020-03-24 08:19:44.008 DEBUG 1 --- [onnection adder] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - After adding stats (total=10, active=1, idle=9, waiting=0)
2020-03-24 08:20:10.592 DEBUG 1 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Pool stats (total=10, active=1, idle=9, waiting=0)
2020-03-24 08:20:39.272 DEBUG 1 --- [alina-utility-2] org.apache.catalina.session.ManagerBase : Start expire sessions StandardManager at 1585038039271 sessioncount 0
2020-03-24 08:20:39.272 DEBUG 1 --- [alina-utility-2] org.apache.catalina.session.ManagerBase : End expire sessions StandardManager processingTime 1 expired sessions: 0
2020-03-24 08:20:40.592 DEBUG 1 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Pool stats (total=10, active=1, idle=9, waiting=0)
2020-03-24 08:21:10.593 DEBUG 1 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Pool stats (total=10, active=1, idle=9, waiting=0)
2020-03-24 08:21:39.274 DEBUG 1 --- [alina-utility-2] org.apache.catalina.session.ManagerBase : Start expire sessions StandardManager at 1585038099274 sessioncount 0
2020-03-24 08:21:39.274 DEBUG 1 --- [alina-utility-2] org.apache.catalina.session.ManagerBase : End expire sessions StandardManager processingTime 0 expired sessions: 0
2020-03-24 08:21:40.593 DEBUG 1 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Pool stats (total=10, active=1, idle=9, waiting=0)
2020-03-24 08:22:10.594 DEBUG 1 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Pool stats (total=10, active=1, idle=9, waiting=0)
2020-03-24 08:22:39.277 DEBUG 1 --- [alina-utility-1] org.apache.catalina.session.ManagerBase : Start expire sessions StandardManager at 1585038159277 sessioncount 0
2020-03-24 08:22:39.277 DEBUG 1 --- [alina-utility-1] org.apache.catalina.session.ManagerBase : End expire sessions StandardManager processingTime 0 expired sessions: 0
2020-03-24 08:22:40.594 DEBUG 1 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Pool stats (total=10, active=1, idle=9, waiting=0)
2020-03-24 08:23:10.595 DEBUG 1 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Pool stats (total=10, active=1, idle=9, waiting=0)
I have tried to configure my custom network on docker level, use ip, hostnames and no luck.
has anyone experienced same behavior?
Spring Config:
spring:
flyway:
url: jdbc:postgresql://157.46.186.128:62013/db
user: user
password: xxxxx
locations: classpath:db/migration
schemas: db1
datasource:
db:
jdbcUrl: "jdbc:postgresql://157.46.186.128:62013/db"
username: "user"
password: "xxxxx"
driver-class-name: "org.postgresql.Driver"
dialect: "org.hibernate.dialect.PostgreSQL95Dialect"
ci:
jdbcUrl: "jdbc:postgresql://157.46.186.128:62013/db"
username: "user"
password: "xxxxx"
driver-class-name: "org.postgresql.Driver"
dialect: "org.hibernate.dialect.PostgreSQL95Dialect"
schema: ci
docker network settings:
with host mode
"Bridge": "",
"SandboxID": "49fa5d5e812c816a84efe92156e825151b2dc75a36bb68c399b943e06c26a6f7",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/default",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": "",
"Networks": {
"host": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "d6ecd673f06e15560a16dc5bb38ea4be99e751bfb729d819ab76c50320836443",
"EndpointID": "087b1a6fed2cd5b4de46c6700a9ef7e79de6fc3e58a0ecfdd74a8a851429eaa6",
"Gateway": "",
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "",
"DriverOpts": null
}
}
}
and without
"NetworkSettings": {
"Bridge": "",
"SandboxID": "cf8d68a1b1c61d454ed45eb48f4007591d07414f2147410c1381d60e12b93445",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"7979/tcp": null,
"8080/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "8080"
}
]
},
"SandboxKey": "/var/run/docker/netns/cf8d68a1b1c6",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "49993412f56f7bd29edd55091bd77bba66a40ae566daf8111f891be9aa21d4ce",
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:11:00:02",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "bf5b2dfe32339838a40b351409fb7750f632a3810cb8774db195f49eed8a3ed5",
"EndpointID": "49993412f56f7bd29edd55091bd77bba66a40ae566daf8111f891be9aa21d4ce",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null
}
}
}
A: I had to set docker daemon MTU to be the same as the network card.
ip link show
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> **mtu 1450** qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc
edited /etc/docker/daemon.json
"mtu": 1450
}
Problem solved. Tricky one, when I did remote debugging I notice that it was blocking on socket read, from there google was my friend.
https://mlohr.com/docker-mtu/
| |
doc_23527550
|
Contact& Contact::operator+=(long long phone)
{
if (isValidPhonenumber(phone)) {
long long* tmp = new long long[this->amtNumbers + 1];
for (int i = 0; i < this->amtNumbers; i++) {
tmp[i] = this->m_pNumber[i];
}
tmp[amtNumbers + 1] = phone;
delete[] this->m_pNumber;
this->m_pNumber = tmp;
this->amtNumbers++;
return *this;
}
}
I presume it is the tmp[amtNumbers + 1] = phone; that is causing this. But I dont understand why? I seem to have allocated enough memory. Perhaps I am missing a delete[] tmp; after this->m_pNumber = tmp;?
But even with,
Contact& Contact::operator+=(long long phone)
{
if (isValidPhonenumber(phone)) {
long long* tmp = new long long[this->amtNumbers + 1];
for (int i = 0; i < this->amtNumbers; i++) {
tmp[i] = this->m_pNumber[i];
}
tmp[amtNumbers + 1] = phone;
delete[] this->m_pNumber;
this->m_pNumber = tmp;
delete[] tmp;
this->amtNumbers++;
return *this;
}
}
I run into the overflow error. Thoughts, suggestions? This is a number type, not character; I dont need to allocated anything extra for a null character.
A: You declare long long* tmp = new long long[this->amtNumbers + 1]; and then use tmp[amtNumbers + 1] = phone; which is out of range. The max index is this->amtNumbers since the array is 0-indexed.
| |
doc_23527551
|
(defn eval-arraklisp
"not sure yet"
[tree scope]
(match tree
[:SYM sym] (lookup sym scope)
[:NUM num] (read-string num)
[:FUN & params body] [:FUN & body]
[:CALL [:SYM sym] & args] (call-sym sym scope args)
[:CALL [:FUN & params body] & args]))
I get the following on the (match tree line:
#error {
:cause No method in multimethod 'to-source' for dispatch value: :clojure.core.match/rest
:via
[{:type clojure.lang.Compiler$CompilerException
Can't figure out why.
A: The problem is in following line:
[:FUN & params body] [:FUN & body]
There are two symbols in rest section of match, in particular params and body, but it is not allowed to have more than one. This causes error you are getting.
Probably, you should rewrite this match clause as follows:
[:FUN params & body] [:FUN & body]
Also, as noted by @Andre, you should review the return value of this match, because & symbol is definitely redundant there.
| |
doc_23527552
|
I have almost 200 archival PDFs of a newspaper that I would like to analyse. However I would like to do this analysis specifically on the letters section, yet depending on the layout of adverts and the conversion method (be it pdfbox or pdftotext) there is no real beginning or ending to the section that I could accurately create a regex search with.
Can anyone think of a way to do something like this? I've looked at it for a while and it seems like the only reliable way might be to manually sift through every pdf.
A: Thought i'd just write a little about what i did to get this working:
Following from what @TilmanHausherr said, I was about to start manually, cropping each page individually and then doing the text extraction on those cropped pages.
However I thought I might as well reduce the amount of manual cropping as much as possible by getting rid of the pages that were totally unnecessary (99% of them).
So even if my semi automated selections weren't 100% accurate - they would at least make less manual work for me, which would be helpful either way. So I followed this process:
*
*Using Acrobat, I ran a javascript search to extract any pages with a certain keyword, to a new document. The catch being this has to be a one word keyword, nonetheless I found a pretty unique word 'disclaimer' that appeared on all letter pages. Even if it did catch another page - it didn't matter as all I wanted to do was reduce the ultimate manual work.
*I then wanted to make the pages as easy as possible for me to manually crop, so knowing that all images were irrelevant, I used the program pdftoolbox on the 14 day trial to use this crazy feature which automatically splits, text images and vectors into different layers which can then be deleted or made invisible.
*This is done by going to the fixups menu, searching for the create different layers for vectors..option and clicking fix. Then once it's done - going to the explore layers option under the main menu and deleting everything but the text layer. Which as you can see is super effective in removing any additional junk and almost becomes like adblock for newspapers :)
*There is still some remaining junk, but after removing all the images all I had to do was go through a couple pages and check there was no unrelated text in acrobat editor. The only manual work left to be done.
I think it's pretty funny how I was completely stuck with this when I was trying to automate the entire process. But when I instead tried to reduce as much manual work as possible I had automated like 99% of the process anyway.
Guess I was making the Perfect solution fallacy subconsciously, when I was trying to automate it.
¯\_(ツ)_/¯
| |
doc_23527553
|
I would like to receive a JSON Object from a function, say B, response when I request /test-communication-A.
This is the article I followed to explore how the app deploys on Lambda.
How to deploy a Node.js application to AWS Lambda using Serverless
method in function-A
app.get("/test-communication-A", function (req, res) {
request
.get('https://{endpoint of function-B offered from AWS apiGateway}/test-communication-B')
.on('response', resp => {
return res.send(resp);
})
.on('error', err => {
return res.send('error')
})
});
module.exports.server = sls(app);
method in function-B
app.get("/test-communication-B", function (req, res) {
return res.send({ retCode: 0 });
});
Any input would be appreciated, thank you!
| |
doc_23527554
|
[Fiddle link]http://jsfiddle.net/vineetgnair/pne58wyh/
Thanks for Help
A:
var checkBox = document.querySelectorAll('input[type=checkbox]');
// querySelectorAll returns an array of the matching elements
function selectAll() {
for (i = 0; i < checkBox.length; i++) {
// loop through and set "checked" to TRUE on every element in the checkBox array
checkBox[i].checked = true;
}
}
function deselectAll() {
// loop through and set "checked" to FALSE on every element in the checkBox array
for (i = 0; i < checkBox.length; i++) {
checkBox[i].checked = false;
}
}
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<br>
<input type="button" value="Select All" onclick="selectAll()">
<input type="button" value="Deselect All" onclick="deselectAll()">
A: The HTML is pretty much the same except I added a parameter in the selectAll function
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<br>
<input type="button" value="Select All" onclick="selectAll(true)">
<input type="button" value="Deselect All" onclick="selectAll(false)">
For the javascript, you just needed a loop to set all the items to checked or unchecked
function selectAll(selected) {
var checkBox = document.querySelectorAll('input[type=checkbox]');
for(var i = 0 ; i < checkBox.length ; i++) {
checkBox[i].checked = selected;
}
}
jsFiddle
| |
doc_23527555
|
I'm trying to make a extendable and modular plugin system for my website. I need to be able to access plugin php files that exist in a plugin directory and get access to their classes to call functions such as getting the html content that the plugin should show and more.
Below is a semi-pseudo code example of what I am trying to achieve, but how to actually arbitrarily load the plugins is where I am stuck (PluginLoader.php).
-Max
//BasePlugin.php
abstract class BasePlugin
{
public function displayContent()
{
print "<p>Base Plugin</p>";
}
};
//ExamplePlugin.php -> In specific plugin directory.
require('../BasePlugin.php');
class ExamplePlugin extends BasePlugin
{
public static function Instance()
{
static $inst = null;
if ($inst === null) {
$inst = new ExamplePlugin();
}
return $inst;
}
public function displayContent()
{
print "<p>Example Plugin</p>";
}
}
//PluginLoader.php
foreach($pluginFile : PluginFilesInDirectory) { // Iterate over plugin php files in plugin directory
$plugin = GetPlugin($pluginFile); // Somehow get instance of plugin.
echo plugin->displayContent();
}
A: I'm guessing here, but it seems to me that you need to:
*
*get a list of the plugins in the desired directory.
*include or require the plugin's class file.
*create an instance of the class.
*call the plugin's displayContent() method.
So, you probably want to do something like
$pluginDir = 'your/plugin/directory/' ;
$plugins = glob($pluginDir . '*.php') ;
foreach($plugins as $plugin) {
// include the plugin file
include_once($plugin) ;
// grab the class name from the plugin's file name
// this finds the last occurrence of a '/' and gets the file name without the .php
$className = substr($plugin,strrpos($plugin,'/') + 1, -4) ;
// create the instance and display your test
$aPlugin = $className::Instance() ;
$aPlugin->displayContent() ;
}
There's probably a cleaner way to do it, but that will ready your directory, get the plugins' code, and instantiate each one. How you manage/reference them afterwards depends on how your plugins register with your application.
| |
doc_23527556
|
I am getting a value from a list.
List contains a string values.
I need to check whether that value of list contains a character value or only digits.
<#assign arr =["0-200000", "200001-500000" ,"500001 & above"]/>
<#list arr as prcVal>
<#assign vals= prcVal?split('-')/>
<#assign rangeStart = ""/>
<#assign arrIndex = 0/>
<#list vals as prcVal1>
<#if prcVal1?index_of("& above") gt 0>
<#assign prcVal2 = (prcVal1?split('&')[0])?trim/>
<#if prcVal2?number gt 99>
<#assign rangeStart = prcVal2?number?string[",000"] + ' &' + prcVal1?split('&')[1]/>
</#if>
<#else>
<#if prcVal1?number gt 99>
<#assign rangeStart = rangeStart + prcVal1?number?string[",000"]/>
<#else>
<#assign rangeStart = rangeStart + prcVal1/>
</#if>
<#if arrIndex == 0>
<#assign rangeStart = rangeStart + '-'/>
</#if>
<#assign arrIndex = arrIndex + 1/>
</#if>
</#list>
${rangeStart}
</#list>
Inside list if prcVal1 has '&' it goes under that condition else under "else" condition.
if prcVal1 doesnot contains '&' it goes to "else", but under that i checked "#if prcVal1?number gt 99" because of prcVal1 contains characters it cannot be converted to number, i'l be getting FTL error.
id?is_number or ?is_string
these inbuild conditions i got, but this checks tyoe of a value only.
Eg : prcVal1="100" contains digits, but prcVal1?is_number returns false.
<#assign arr =["0-200000", "200001-500000" ,"500001 & above","test"]/>
<#list arr as prcVal>
<#assign vals= prcVal?split('-')/>
<#assign rangeStart = ""/>
<#assign arrIndex = 0/>
<#list vals as prcVal1>
<#if prcVal1?index_of("& above") gt 0>
<#assign prcVal2 = (prcVal1?split('&')[0])?trim/>
<#if prcVal2?number gt 99>
<#assign rangeStart = prcVal2?number?string[",000"] + ' &' + prcVal1?split('&')[1]/>
</#if>
<#else>
<#if prcVal1?number gt 99>
<#assign rangeStart = rangeStart + prcVal1?number?string[",000"]/>
<#else>
<#assign rangeStart = rangeStart + prcVal1/>
</#if>
<#if arrIndex == 0>
<#assign rangeStart = rangeStart + '-'/>
</#if>
<#assign arrIndex = arrIndex + 1/>
</#if>
</#list>
${rangeStart}
</#list>
Above code throws error because of test in input, i need to check and skip that.
Can anyone suggest me a solution to check whether a value has string values or digits.
Thanks in advance.
A: You can use Freemarker's builtin replace which will remove other characters than number, for example in your case this can fit
<#assign prcVal1 = prcVal1?replace("[a-zA-Z& ]+", "", "r") />
Or replace all not numbers characters using \D:
<#assign prcVal1 = prcVal1?replace("[\\D]+", "", "r") />
A: Currently (2.3.28) you have to use a regular expressions. This will evaluate to true or false depending on if pcVal is a whole number (optionally with a - or + prefix): pcVal?matches(r'[-\+]?[0-9]+'). Note that it doesn't match decimals (like 1.5) though, but I guess you can extend the regular expression further from here if needed.
| |
doc_23527557
|
package transformare1;
import java.io.*;
public class Transformare1 {
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Introduceti un numar natural in baza 10 ");
int n = Integer.parseInt(br.readLine());
System.out.println ("Alegeti in ce baza sa fie convertit numarul: 2, 8, 16 ");
int n1 = Integer.parseInt(br.readLine());
if (n1==2){
String b = "";
while (n!=0){
int r = (int)(n%2);
b = r+b;
n /=2;
}
System.out.println ("Numarul binar este "+b);
}
else if (n1==8){
String b = "";
while (n!=0){
int r = (int)(n%8);
b = r+b;
n /=8;
}
System.out.println ("Numarul octal este "+b);
}
else if (n1==16){
String b ="";
while (n!=0){
int r = (int)(n%16);
b = r+b;
n /=16;
final char A=10;
final char B=11;
final char C=12;
final char D=13;
final char E=14;
final char F=15;
}
System.out.println ("Numarul hexadecimal este "+b);
}}
}
A: There are lots of ways of fixing this. One way is to replace b = r+b in the "hexadecimal" section of the code with b = "0123456789ABCDEF".charAt(r) + b.
| |
doc_23527558
|
http://iamwhitebox.com/staging/arkitek
A: As far as I can see, dynamicpage.js doesn't even contain a jquery plugin. So you might as well go ahead and modify the content of the file directly. It's pretty short.
You could then use jQuery's $.support or even $.browser (not necessarily recommendable) method to split your code depending on the browser. Or even better extract your solution into a function or plugin and call it from within conditional comments as you need it.
Since I'm assuming that the reason you want to do this, are certain issues with IE when it comes to animating the opacity property, you might want to have a look at these
*
*jquery IE Fadein and Fadeout Opacity
*jQuery FadeIn loses transparency on IE
*jQuery fadeIn IE Png Issue when loading from external
as well and maybe just "fix" the code you already have.
UPDATE
By request: You can detect IE using browser like this:
if ($.browser.msie) {
// do something only for IE
} else {
// do something for all other browsers
}
Again — this is not necessarily recommendable, since browser detection has been always problematic. Depending on what exactly it is that you're trying to fix, you might want consider implementing a different approach.
| |
doc_23527559
|
I have an application where i store service requests. Whenever a team value in changed in the service request record, I want to create a team history record in a related teamhistory entity.
I have created the app in MVC using the standard scaffolding for controllers and views.
In the (post)edit task in the controller, the standard logic generated has the following code
if (ModelState.IsValid)
{
db.Entry(serviceRequest).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(serviceRequest);
I have modified that to include the creating of the teamhistory record and an individualhistory record for individual assigned within team. The code for creating these related records work, BUT i want these records only created when the values on team or member(individual) change from what they were previously.
So far the conditions i have specified due not trigger this correctly because I havent gotten the condition right. Below is the current code:
//string teamorig = db.Entry(serviceRequest).Property(u => u.Team).OriginalValue.ToString();
//string teamcurr = db.Entry(serviceRequest).Property(u => u.Team).CurrentValue.ToString();
//if (teamorig != teamcurr)
var TeamIsModified = db.Entry(serviceRequest).Property(u => u.Team).IsModified;
if (TeamIsModified)
{
serviceRequest.TeamAssignmentHistories.Add(new TeamAssignmentHistory()
{
DateAssigned = DateTime.Now,
AssignedBy = User.Identity.Name,
ServiceRequest = serviceRequest.Id,
Team = serviceRequest.Team
});
}
//=========================================================================================
// if individual assigned has changed add individual history record========================
var IndividualIsModified = db.Entry(serviceRequest).Property(u => u.Member).IsModified;
if (IndividualIsModified)
{
serviceRequest.IndividualAssignmentHistories.Add(new IndividualAssignmentHistory()
{
DateAssigned = DateTime.Now,
AssignedBy = User.Identity.Name,
ServiceRequest = serviceRequest.Id,
AssignedTo = serviceRequest.Member.Value,
});
}
//===========================================================================================
The var teamismodified logic doesnt work. When I save the page without making any changes on it- the logic kicks off because in debugging it thinks the field has been modified.
When I comment out that code and uncomment the code above it for original and currentvalues- ie the teamorig and teamcurr logic, teamcurr and teamorig have the same values in debug, even when they have been forced into a change on the save in the MVC view page. Because they have the same values, the if condition is false so the team history record is not created.
The above code has been sandwiched in between
db.Entry(serviceRequest).State = EntityState.Modified;
and
await db.SaveChangesAsync();
statements.
What am I not understanding about entity framework tracking changes in mvc? Why does think its modified when i make not changes to team, and why are teamorig and teamcurr the same when I do make the changes?
Any advice would be welcome. Thanks
| |
doc_23527560
|
I can see the week calendar and manage to hide "all-day" row and all the "hour" rows from it using the below css.
.weekview-allday-table {
display:none;
}
.weekview-normal-event-container{
display:none;
}
.calendar-event-wrap{
display:none;
}
.weekview-normal-event-container {
margin-top: 0;
}
Please find the below snapshot.
I need to move the below activity list next to the calendar header. Could you suggest how that can be done.
A: Try this in scss file
.weekview-container{
height: 12% !important;
}
override the css.
| |
doc_23527561
|
Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.3:run
(deploy) on project xxx.xxx.xxx.xxx: An Ant BuildException has occured:
Could not login to FTP server
This is quite confusing because I am able to log into the FTP server using FileZilla and the same credentials I am using for the Maven Ant build task without any problems (on the same machine). I am also able to transfer files in both directions via FileZilla without any problems either.
This used to work fine before I did a routine server restart recently. My FTP server is a DigitalOcean droplet with the standard Ubuntu OS and VSFTPD installed.
My pom.xml is as follows:
...
<profile>
<id>publish-product</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>deploy</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<ftp
server="${env.DEPLOY_FTP_SERVER}"
remotedir="${env.DEPLOY_FTP_DIR}"
userid="${env.DEPLOY_FTP_USERNAME}"
password="${env.DEPLOY_FTP_PASSWORD}"
umask="002"
passive="yes">
<fileset dir="target/repository">
<include name="**/*" />
</fileset>
</ftp>
</tasks>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-commons-net</artifactId>
<version>1.10.9</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<profile>
...
The Maven build is executed using:
mvn -U -DskipTests clean package -Ppublish-product
Does anyone know what might be happening to prevent the Ant FTP task from running?
The full output of the Ant task is as follows:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.3:run (deploy) on project xxxx.xxxx.xxxx.xxxx: An Ant BuildException has occured: Could not login to FTP server -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.3:run (deploy) on project xxxx.xxxx.xxxx.xxxx: An Ant BuildException has occured: Could not login to FTP server
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:566)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: An Ant BuildException has occured: Could not login to FTP server
at org.apache.maven.plugin.antrun.AbstractAntMojo.executeTasks (AbstractAntMojo.java:131)
at org.apache.maven.plugin.antrun.AntRunMojo.execute (AntRunMojo.java:98)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:566)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.apache.tools.ant.BuildException: Could not login to FTP server
at org.apache.tools.ant.taskdefs.optional.net.FTP.execute (FTP.java:2528)
at org.apache.tools.ant.UnknownElement.execute (UnknownElement.java:288)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:566)
at org.apache.tools.ant.dispatch.DispatchUtils.execute (DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform (Task.java:348)
at org.apache.tools.ant.Target.execute (Target.java:357)
at org.apache.maven.plugin.antrun.AbstractAntMojo.executeTasks (AbstractAntMojo.java:118)
at org.apache.maven.plugin.antrun.AntRunMojo.execute (AntRunMojo.java:98)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:566)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
The detailed log of my FileZilla session is as follows:
Status: Resolving address of myftpserver.xxxx.xxxx
Status: Connecting to 218.86.381.231:21...
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Server does not support non-ASCII characters.
Status: Logged in
Status: Retrieving directory listing...
Status: Directory listing of "/" successful
Status: Connection closed by server
Status: Resolving address of myftpserver.xxxx.xxxx
Status: Connecting to 218.86.381.231:21...
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Server does not support non-ASCII characters.
Status: Logged in
Status: Retrieving directory listing of "/"...
Status: Directory listing of "/" successful
Status: Resolving address of myftpserver.xxxx.xxxx
Status: Connecting to 218.86.381.231:21...
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Server does not support non-ASCII characters.
Status: Logged in
Status: Starting upload of D:\logo.pdf
Status: File transfer successful, transferred 1,260 bytes in 1 second
Status: Retrieving directory listing of "/"...
Status: Calculating timezone offset of server...
Status: Timezone offset of server is 0 seconds.
Status: Directory listing of "/" successful
Status: Deleting "/logo.pdf"
Status: Disconnected from server
Status: Connection closed by server
Status: Resolving address of myftpserver.xxxx.xxxx
Status: Connecting to 218.86.381.231:21...
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Server does not support non-ASCII characters.
Status: Logged in
Status: Retrieving directory listing of "/"...
Status: Directory listing of "/" successful
Status: Connection closed by server
Status: Resolving address of myftpserver.xxxx.xxxx
Status: Connecting to 218.86.381.231:21...
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Server does not support non-ASCII characters.
Status: Logged in
Status: Starting upload of D:\logo.pdf
Status: File transfer successful, transferred 1,260 bytes in 1 second
Status: Retrieving directory listing of "/"...
Status: Directory listing of "/" successful
A: "Could not login to FTP server" error indicates that your credentials are wrong. The error is issued when FTPClient.login fails.
I see that you have validated that you have the correct credentials by authenticating with a GUI FTP client. So chances are that there are some special characters in the credentials that may need some escaping or special treatment.
A: One may face a similar problem when the FTP server is using TLS. The Ant plugin does not support FTPS.
| |
doc_23527562
|
Screenshots:
Code:
<article>
<canvas id="myChart" style="width:676px;height:300px;"></canvas>
<!-- if there is a way It would be cool for it just to fill to the article -->
</article>
var myChart = new Chart(ctx, {
type: "line",
data: {.....},
options: {...}
article {
display: flex;
height: 300px;
background: var(--page-content-blockColor);
border-radius: var(--border-radius);
box-shadow: var(--box-shadow);
}
What I've Tried:
responsive:true,
maintainAspectRatio: false
A: Thanks User: Ezra Siton,
Changing to using VH and VW seemed to work for me!
:)
(posting this so i can close the question)
| |
doc_23527563
|
import mechanize
import re
def price_walmart_match(keyword):
url = "http://www.walmart.com/search/?query="+keyword
br = mechanize.Browser()
br.set_handle_robots(False)
br.open(url)
html = br.response().read()
result_soup = BeautifulSoup(html)
found_results = result_soup.findAll('div' , attrs={'class':'js-tile tile-landscape'})
all_results=[]
for result in found_results:
title = result.find('a' , attrs={'class':'js-product-title'})
links = result.find('a' , href=True)
before_decimal= str(result.find('span', attrs={'class':'price price-display'})).split('<span class="sup">$</span>')[1].split('<span class="visuallyhidden">')[0]
after_decimal= str(result.find('span', attrs={'class':'price price-display'})).split('</span><span class="sup">')[1].split('</span>')[0]
prices = before_decimal+'.'+after_decimal
inArray = [float(prices), "http://www.walmart.com"+links['href']]
all_results.append(inArray)
result = []
minval = all_results[0][0]
for values in all_results:
if minval >= values[0]:
result = values
minval = values[0]
return(result)
| |
doc_23527564
|
Scroll bars - image
As you can see, the little square is always positioned at 0. I need these squares to start at pre-defined values (position). Below is the code I'm using at the moment, but it's not working.
Example of what the scroll bar should look like
Private Sub rng_cbb_IndProd_Change() 'everything changes when I select something (basically).
frmSeg.rng_seg_4.Value = 10
frmSeg.rng_seg_3.Value = 20
frmSeg.rng_seg_2.Value = 30
End Sub
Please note the code is simplified, the necessary variables are all set.
A: I found a solution and it was simpler than I thought.
Nothing was happening even though I was inputting a value, and that's because I didn't set a MIN/MAX value to the scroll bars.
frmSeg.rng_seg_4.Min = 0
frmSeg.rng_seg_4.Max = 100
frmSeg.rng_seg_4.Value = 10
By setting the min and max value, it can know position the scroll bar.
| |
doc_23527565
|
<?php
session_start();
$rand= "SED".rand(10000,99999);
?>
<!doctype>
<html lang="en">
<body>
<form action="result4.php" method="post">
<input type="hidden" name="productid" value="<?=$rand?>">
<button type="submit">submit</button>
</form>
</body>
</html>
and my result4.php
<?php
$cookie_name = "lastview";
$cookie_value = array($_POST['productid']);
$init = json_encode($cookie_value);
setcookie($cookie_name, $init, time() + (86400 * 30));
?>
<?php
echo count($_COOKIE["lastview"]);
echo '<pre>';
print_r($_COOKIE["lastview"]);
echo '</pre>';
?>
output
1
["SED73204"]
i am trying to get this
5
["SED73204"]
["SED73507"]
["SED23207"]
["SED73286"]
["SED23294"]
A: As mentioned, check if a value exists in the cookie already. If it does then extract that first, then add the new value.
$cookie_name = "lastview";
// Set the cookie value from previous (if exists) or else an empty array
$cookie_value = (isset($_COOKIE[$cookie_name])) ?
json_decode($_COOKIE[$cookie_name]) : array();
// Add the new value to the array if one exists
if (isset($_POST['productid']) && is_numeric($_POST['productid'])) {
$cookie_value[] = $_POST['productid'];
}
// Set the cookie
setcookie($cookie_name, json_encode($cookie_value), time() + (86400 * 30));
You may want to replace the call to is_numeric here with a preg_match to check for more specific product ID formats. For example:
if (preg_match('/^[\w]{3}[\d]{5}$/', $_POST['productid'])) { ... }
Also, you won't be able to see any values in the $_COOKIE array in the same execution cycle as setcookie(). You will need to wait for the browser to send the cookie back on the next request before you see the populated value in the $_COOKIE array.
A: You cant direclty store an array into a cookie,
One way to do would be to serialize the data :
setcookie('cookie', serialize($cookie_value), time()+3600);
Then unserialize data:
$data = unserialize($_COOKIE['cookie']);
| |
doc_23527566
|
It's pretty easy using the Parameter Store AWS Systems Manager console, if I type tokens, I retrieve all parameters where the Name contains tokens :
Is there a way to do the same but using AWS CLI or AWS SDK (python or Go preferably) ?
A: I think this is what you are after:
aws ssm describe-parameters --parameter-filters Key=Name,Values=token,Option=Contains
A: Or with Python:
import boto3
response = boto3.client("ssm").describe_parameters(
ParameterFilters=[
{
'Key': 'Name',
'Option': 'Contains',
'Values': [
'token',
]
},
]
)
| |
doc_23527567
|
handleClickOpen = name => event => {
this.setState({
open: true
});
};
handleClose = () => {
this.setState({ open: false });
};
{Developertasklist.map((task, index) => {
return (
<div className={classes.width5}>
<NotesIcon
className={classes.icon}
onClick={this.handleClickOpen()}
/>
<Dialog
onClose={this.handleClose}
aria-labelledby="customized-dialog-title"
open={this.state.open}
>
<DialogTitle
id="customized-dialog-title"
onClose={this.handleClose}
>
Notes
</DialogTitle>
<DialogContent>
<Note />
</DialogContent>
</Dialog>
</div>
)
})}
How to prevent to open popup in loop.
Thanks.
A: Problem is you are using same state for all task, you could set openTask in state and send open = this.state.openTask === task so that only one task dialog will open.
handleClickOpen = task => event => {
this.setState({
openTask: task
});
};
handleClose = () => {
this.setState({ open: false });
};
{Developertasklist.map((task, index) => {
return (
<div className={classes.width5}>
<NotesIcon
className={classes.icon}
onClick={this.handleClickOpen(taks)}
/>
<Dialog
onClose={this.handleClose}
aria-labelledby="customized-dialog-title"
open={this.state.openTask === task }
>
<DialogTitle
id="customized-dialog-title"
onClose={this.handleClose}
>
Notes
</DialogTitle>
<DialogContent>
<Note />
</DialogContent>
</Dialog>
</div>
)
})}
| |
doc_23527568
|
Example:
table -customers
o_id | c_id | name | address | tel_no
table- orders
o_id | starter | rice | gravy | dessert
I want the details to be retrieved as follows
o_id |c_id | name | address | tel_no | starter | rice | gravy | dessert
What type of JOIN should I use and how?
I tried using the below query
SELECT * FROM cms.order inner join cms.menu on cms.order.o_id=cms.menu.o_id
But the problem with the above code is that the o_id column is displayed twice.
A: Try this
SELECT c.o_id, c.c_id, c.name, c.address,
c.tel_no, o.starter, o.rice, o.gravy. o.desserts
FROM order o INNER JOIN customers c
ON o.o_id=c.o_id
Output
o_id |c_id | name | address | tel_no | starter | rice | gravy | dessert
A: If you simply don't want the columns to display twice, then instead of SELECT * you need to specify which columns you want to SELECT.
A: You need to specify the columns that you want to retrieve
SELECT o.o_id, o.c_id, o.name, o.address,
o.tel_no, m.starter, m.rice, m.gravy. m.desserts
FROM order o inner join menu m on o.o_id=m.o_id
By the way, you talk about a customer/order tables but then you use a order/menutable.
This is confusing. However, I hope that the answer is clear enough to highlight the problem
| |
doc_23527569
|
I have run the demo script successfuly with CMD + I in atom, with the demo xlsx file being placed with the text in the cell - no problems there.
As soon as I run this in IDLE however, I get the traceback:
ModuleNotFoundError: No module named 'xlsxwriter'
The module is in the frameworks directory - I'm just baffled as to why IDLE wouldn't be recognising the module when atom does?
I've searched high and low for similar issues but cannot seem to locate a workaround - this is the first itme i've run into this kind of problem with python modules.
Any help would be appreciated!
Edit:
the module is listed in my pip and pip3 list:
pip3 list
Package Version
imageio 2.6.1
numpy 1.17.4
Pillow 7.0.0
pip 19.0.3
progress 1.5
python-xmp-toolkit 2.0.1
pytz 2019.3
rawkit 0.6.0
rawpy 0.13.1
setuptools 40.8.0
tqdm 4.38.0
Wand 0.5.8
XlsxWriter 1.2.8
xlwt 1.3.0
Is there any reason why the IDLE shell would not recognise an installed module?
| |
doc_23527570
|
var lSecurity = lCustomBinding.Elements.Find<TransportSecurityBindingElement>();
lSecurity.LocalClientSettings.DetectReplays = false;
lSecurity.LocalServiceSettings.DetectReplays = false;
lSecurity.LocalClientSettings.TimestampValidityDuration = TimeSpan.FromDays(7);
lSecurity.LocalServiceSettings.TimestampValidityDuration = TimeSpan.FromDays(7);
lSecurity.LocalClientSettings.MaxClockSkew = TimeSpan.FromDays(7);
lSecurity.LocalServiceSettings.MaxClockSkew = TimeSpan.FromDays(7);
Now we find that if we test the above by setting the client back anywhere from now to 7 days back, it works. However, the moment we set the client anything more than 9 hours into the future, we get an exception.
The only thing we found was some obscure reference at the end of another thread:
http://social.msdn.microsoft.com/Forums/en/wcf/thread/7c3a7a7e-b9a5-4198-9a29-c6d4e408d36d
Does anybody have any ideas?
UPDATE:
The Exception we get is now added below. It seems as though the server rejects the client message:
System.ServiceModel.Security.MessageSecurityException occurred
Message=An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation operation, EndpointAddress target, Uri via, SecurityToken currentToken, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.RenewTokenCore(TimeSpan timeout, SecurityToken tokenToBeRenewed)
at System.IdentityModel.Selectors.SecurityTokenProvider.RenewToken(TimeSpan timeout, SecurityToken tokenToBeRenewed)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.RenewKey(TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.SecureOutgoingMessage(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecurityDuplexSessionChannel.Send(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.DuplexClientReliableChannelBinder`1.OnSend(TDuplexChannel channel, Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ReliableChannelBinder`1.Send(Message message, TimeSpan timeout, MaskingMode maskingMode)
at System.ServiceModel.Channels.SendReceiveReliableRequestor.OnRequest(Message request, TimeSpan timeout, Boolean last)
at System.ServiceModel.Channels.ReliableRequestor.Request(TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableSession.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at CompuLoan.Maintenance.IMaintenanceService.IsLicensed(String pHardwareId, Boolean pUseLicense)
at CompuLoan.Maintenance.MaintenanceServiceClient.IsLicensed(String pHardwareId, Boolean pUseLicense) in C:\Development\compuloan\Source\CompuLoan\Service References\Maintenance\Reference.cs:line 5156
at CompuLoan.App.IsLicensed(Boolean pUseLicense) in C:\Development\compuloan\Source\CompuLoan\App.xaml.cs:line 365
InnerException: System.ServiceModel.FaultException
Message=The security context token is expired or is not valid. The message was not processed.
InnerException:
A: This is expiration of the session key, which is different than timestamp. For example of you turn establishSecurityContext off (or not use CreateSecureConversationSecurity) you should not get this exception.
Otherwise try to increase additional values such as InactivityTimeout, IssuedCookieLifetime, NegotiationTimeout, SessionKeyRenewalInterval and SessionKeyRolloverInterval.
If you turn on WCF trace on the server and see the exact stack trace of the error maybe we can dril down to the exact property.
| |
doc_23527571
|
$(R.id.t9_key_0).setOnClickListener(this);
What does the dollar sign mean in front? Is it specifically related to Android resource ids or is more a general Java syntax? Search engine results didn't show any suitable results.
A: It's a method call where the method name is $. The method is defined as follows in the code you linked:
protected <T extends View> T $(@IdRes int id) {
return (T) super.findViewById(id);
}
The method is a helper that removes the need to cast the return type of findViewById(). It's no longer needed as of Android O as the platform findViewById() uses generics to do the same.
The name $ is likely inspired by jQuery.
A: Earlier days we know we needed to cast every return type of findViewById() method. Like
usual way
TextView textView = (TextView) findViewById(R.id.textView);
This guy way
TextView textView = $(R.id.textView);
He ignored typecasting by his generic method.
So the guy used Java generic to ignore type casting all the findViewById();. If you don't understand Generics, please read Why to use generics.
protected <T extends View> T $(@IdRes int id) {
return (T) super.findViewById(id);
}
So now he doesn't need to type cast
TextView textView = $(R.id.textView);
Explanation of this method.
*
*He created a method which accept resource id. So he can pass an Id.
*He annotated this parameter by @IdRes so that Android Studio only allow resource ids in this parameter.
*Then he called super class method findViewById which returns View.
*He returned <T extends View> from method, so you will always have View object in return type.
Important
Now you don't need to make your generic methods. Because Android itself has changed his method. See Android Oreo Changes for findViewById().
All instances of the findViewById() method now return
T instead of View.
Now you also can do same like that guy without typecasting
TextView textView = findViewById(R.id.textView);
| |
doc_23527572
|
public class PaymentLogDAO extends AbstractModel<PaymentLog> {
public PaymentLogDAO() {
super(PaymentLog.class);
}
public BigDecimal sum(String keyword) {
try {
if (!sessionFactory.getCurrentSession().getTransaction().isActive())
sessionFactory.getCurrentSession().getTransaction().begin();
Query query = sessionFactory.getCurrentSession()
.createQuery("select sum(p.Payment) "
+ "from PaymentLog p "
+ "where p.TransId =:TransId");
query.setParameter("TransID", keyword);
return (BigDecimal) query.uniqueResult();
} catch (Exception e) {
System.out.println(e);
return BigDecimal.valueOf(0);
}
}
}
And it got error:
org.hibernate.QueryException: could not resolve property: TransId of: entities.PaymentLog [Select p from entities.PaymentLog p where p.TransId like :TransId]
This is my entities
@Entity
@Table(name="PaymentLog"
,schema="dbo"
,catalog="Project2"
)
public class PaymentLog implements java.io.Serializable {
private int id;
private LoanLog loanLog;
private Date transDate;
private BigDecimal payment;
public PaymentLog() {
}
public PaymentLog(int id) {
this.id = id;
}
public PaymentLog(int id, LoanLog loanLog, Date transDate, BigDecimal payment) {
this.id = id;
this.loanLog = loanLog;
this.transDate = transDate;
this.payment = payment;
}
public PaymentLog(int id, LoanLog loanLog) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="TransId")
public LoanLog getLoanLog() {
return this.loanLog;
}
public void setLoanLog(LoanLog loanLog) {
this.loanLog = loanLog;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="TransDate", length=23)
public Date getTransDate() {
return this.transDate;
}
public void setTransDate(Date transDate) {
this.transDate = transDate;
}
@Column(name="Payment", scale=4)
public BigDecimal getPayment() {
return this.payment;
}
public void setPayment(BigDecimal payment) {
this.payment = payment;
}
}
This is my LoanLog entities TransId in PaymentLog is foreign key of Id in LoanLog
/**
* LoanLog generated by hbm2java
*/
@Entity
@Table(name="LoanLog"
,schema="dbo"
,catalog="Project2"
)
public class LoanLog implements java.io.Serializable {
private int id;
private Account account;
private CustInfo custInfo;
private LoanInfo loanInfo;
private Date loanDate;
private BigDecimal amount;
private Integer duration;
private Integer payingPeriod;
private BigDecimal rate;
private Set<PaymentLog> paymentLogs = new HashSet<PaymentLog>(0);
private Set<FineLog> fineLogs = new HashSet<FineLog>(0);
public LoanLog() {
}
public LoanLog(int id) {
this.id = id;
}
public LoanLog(int id, Account account, CustInfo custInfo, LoanInfo loanInfo, Date loanDate, BigDecimal amount, Integer duration, Integer payingPeriod, BigDecimal rate, Set<PaymentLog> paymentLogs, Set<FineLog> fineLogs) {
this.id = id;
this.account = account;
this.custInfo = custInfo;
this.loanInfo = loanInfo;
this.loanDate = loanDate;
this.amount = amount;
this.duration = duration;
this.payingPeriod = payingPeriod;
this.rate = rate;
this.paymentLogs = paymentLogs;
this.fineLogs = fineLogs;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="EmployId")
public Account getAccount() {
return this.account;
}
public void setAccount(Account account) {
this.account = account;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="CustId")
public CustInfo getCustInfo() {
return this.custInfo;
}
public void setCustInfo(CustInfo custInfo) {
this.custInfo = custInfo;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="LoanId")
public LoanInfo getLoanInfo() {
return this.loanInfo;
}
public void setLoanInfo(LoanInfo loanInfo) {
this.loanInfo = loanInfo;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="LoanDate", length=23)
public Date getLoanDate() {
return this.loanDate;
}
public void setLoanDate(Date loanDate) {
this.loanDate = loanDate;
}
@Column(name="Amount", scale=4)
public BigDecimal getAmount() {
return this.amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
@Column(name="Duration")
public Integer getDuration() {
return this.duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
@Column(name="PayingPeriod")
public Integer getPayingPeriod() {
return this.payingPeriod;
}
public void setPayingPeriod(Integer payingPeriod) {
this.payingPeriod = payingPeriod;
}
@Column(name="Rate", precision=10, scale=4)
public BigDecimal getRate() {
return this.rate;
}
public void setRate(BigDecimal rate) {
this.rate = rate;
}
@OneToMany(fetch=FetchType.LAZY, mappedBy="loanLog")
public Set<PaymentLog> getPaymentLogs() {
return this.paymentLogs;
}
public void setPaymentLogs(Set<PaymentLog> paymentLogs) {
this.paymentLogs = paymentLogs;
}
@OneToMany(fetch=FetchType.LAZY, mappedBy="loanLog")
public Set<FineLog> getFineLogs() {
return this.fineLogs;
}
public void setFineLogs(Set<FineLog> fineLogs) {
this.fineLogs = fineLogs;
}
}
How can I solve it?
Thank you very much
A: Referring to this URL (refer to Select clause) , the fields have to be part of the Entity that you have. So i guess your select must refer to Id field and not TransId (also i think Id has to be mapped to TransId since the names are different)
http://www.tutorialspoint.com/hibernate/hibernate_query_language.htm
A: You didnt post your LoanLog entity but i guess you have an id property of LoanLog or sth similar, so try this
select sum(p.Payment) "
+ "from PaymentLog p "
+ "where p.loanLoag.id =:TransId
you are referencing a transId property inside your PaymentLog entity which doenst exist in java. It exists in database, but since you are not executing a native query, query has to conform to the java rules, which means: find the property inside the entity and transId property doesnt exist.
| |
doc_23527573
|
codebuild environment variables:
buildspec.yml
version: 0.2
env:
exported-variables:
- DB_HOST
- DB_PORT
- DB_DATABASE
- DB_PASSWORD
- DB_USERNAME
phases:
install:
commands:
- echo $DB_HOST
- export DB_HOST=$DB_HOST
pre_build:
commands:
- export DB_HOST=$DB_HOST
artifacts:
files:
- '**/*'
name: myname-$(date +%Y-%m-%d)
my appspec.yml
version: 0.0
os: linux
files:
- source: /
destination: /var/www/html/
hooks:
BeforeInstall:
- location: script/BeforeInstall.sh
runas: root
AfterInstall:
- location: script/AfterInstall.sh
runas: root
AfterInstall.sh
#!/bin/bash
# Set permissions to storage and bootstrap cache
sudo chmod -R 0777 /var/www/html/storage
sudo chmod -R 0777 /var/www/html/bootstrap/cache
#
cd /var/www/html
#
# Run composer
composer install --ignore-platform-reqs
please help me to pass those environment variables from codebuild to codedeploy ec2. or is there any other way to generate .env file for codebuild?
A: You can't do this the way you expect it. The proper way is to pass them through SSM Secrets Manager or SSM Paramter Store.
So in your setup, CodeBuild will populate the SSM Secrets Manager or SSM Paramter Store (or you populate them before hand youself), and CodeDeploy will read these secret stores for the parameters.
A: I found a way to work around with it. here is my solution:
since I'm able to get all the environment variables in build stage. i manage to build a .env file in build stage. I have a few environment variables coming in to build stage from secret manager or as plain text.
first, i created a .env.exmaple file in my project root directory:
...
APP_ENV=local
APP_KEY=
...
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=
DB_USERNAME=root
DB_PASSWORD=
MAIL_MAILER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=apikey
MAIL_PASSWORD=
...
second, i updated my buildspec.yml file and replace each value with environment variable values using sed commands
version: 0.2
env:
exported-variables:
- DB_HOST
- DB_DATABASE
- DB_PASSWORD
- DB_USERNAME
secrets-manager:
MAIL_PASSWORD: "email-token:MAIL_PASSWORD"
AWS_ACCESS_KEY_ID: "aws-token:AWS_ACCESS_KEY_ID"
AWS_SECRET_ACCESS_KEY: "aws-token:AWS_SECRET_ACCESS_KEY"
AWS_DEFAULT_REGION: "aws-token:AWS_DEFAULT_REGION"
AWS_BUCKET : "aws-token:AWS_BUCKET"
AWS_URL : "aws-token:AWS_URL"
phases:
build:
commands:
- cp .env.example .env
- sed -i "s/DB_HOST=127.0.0.1/DB_HOST=$DB_HOST/g" .env
- sed -i "s/DB_DATABASE=/DB_DATABASE=$DB_DATABASE/g" .env
- sed -i "s/DB_USERNAME=root/DB_USERNAME=$DB_USERNAME/g" .env
- sed -i "s/DB_PASSWORD=/DB_PASSWORD=$DB_PASSWORD/g" .env
- sed -i "s/APP_ENV=local/APP_ENV=$APP_ENV/g" .env
- sed -i "s/MAIL_PASSWORD=/MAIL_PASSWORD=$MAIL_PASSWORD/g" .env
...
- sed -i "s@AWS_URL=@AWS_URL=$AWS_URL@g" .env
artifacts:
files:
- '**/*'
name: myname-$(date +%Y-%m-%d)
in this way, i am able to create a .env file for the deploy stage.
one thing to notice here is that if your value contain / (for example url), you need to use @ to instead of / for sed commands
| |
doc_23527574
|
Example request is going to look like this:
POST /mobile?command=doSomething?parameter1=value¶meter2=value HTTP/1.1
Host: {ENDPOINT}
Accept: application/json
I probably can use
routeTemplate: "{controller}"
and somehow handle it manually in controller, but it doesn't look like good solution.
I tried
routeTemplate: "{controller}?command={action}"
but i got ArgumentException, because routeUrl can't contain question marks.
What's the proper routeTemplate here?
A: If the controller is handling different POST requests, I would try setting it up like this:
"{controller}/{action}/{parameter1}/{parameter2}" // will hit url: mobile/MyActionMethod/2/3
the above route will hit a controller with the method:
[HttpPost]
public async Task<IHttpActionResult> MyActionMethod(HttpRequestMessage request, int parameter1, int parameter2)
If you don't want the parameters in the URL then either use a JObject to pass them and pull them from a dynamic, or pass model as a paremter.
"{controller}/{action}/"// will hit url: mobile/MyActionMethod
[HttpPost]
public async Task<IHttpActionResult> MyActionMethod(HttpRequestMessage request, Jobject data){//JObject requires Json.NET
dynamic json = data;
int parameter1 = json.parameter1;
int parameter2 = json.parameter2;
}
or using a model of
public class MyMode{
public int Parameter1{get;set;}
public int Parameter2{get;set;}
}
[HttpPost]
public async Task<IHttpActionResult> MyActionMethod(HttpRequestMessage request, MyModel model){
var parameter1 = model.Parameter1;
var parameter2 = model.Parameter2;
}
| |
doc_23527575
|
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public enum ProductID {
.....
}
with corresponding test
public class ProductIDTest {
@Test
public void test1(){
--
}
@Test
public void test2(){
--
}
@Test
public void test3(){
--
}
}
While using green run button from intelliJ, it is passing,
but while I am running it using mvn test, this is failing with following error
[INFO] Running ProductIDTest
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/**/.m2/**/slf4j/slf4j-reload4j/1.7.36/slf4j-reload4j-1.7.36.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/**/.m2/**/ch/qos/logback/logback-classic/1.2.11/logback-classic-1.2.11.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Detected both log4j-over-slf4j.jar AND bound slf4j-reload4j.jar on the class path, preempting StackOverflowError.
SLF4J: See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details.
[TestNG] Reporter [FailedReporter passed=0 failed=0 skipped=0] failed
java.lang.NullPointerException
java.lang.NullPointerException
at java.util.HashMap.putMapEntries(HashMap.java:501)
at java.util.HashMap.putAll(HashMap.java:785)
at org.testng.xml.XmlClass.setParameters(XmlClass.java:231)
at org.testng.reporters.FailedReporter.createXmlClasses(FailedReporter.java:199)
at org.testng.reporters.FailedReporter.createXmlTest(FailedReporter.java:150)
at org.testng.reporters.FailedReporter.generateXmlTest(FailedReporter.java:124)
at org.testng.reporters.FailedReporter.generateFailureSuite(FailedReporter.java:64)
at org.testng.reporters.FailedReporter.generateReport(FailedReporter.java:49)
at org.testng.TestNG.generateReports(TestNG.java:1069)
at org.testng.TestNG.run(TestNG.java:1012)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:135)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeSingleClass(TestNGDirectoryTestSuite.java:112)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:99)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:146)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:383)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:344)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:125)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:417)
[ERROR] Tests run: 3, Failures: 3, Errors: 0, Skipped: 0, Time elapsed: 0.642 s <<< FAILURE! - in ProductIDTest
[ERROR] test1 on test1(ProductIDTest)(ProductIDTest) Time elapsed: 0.052 s <<< FAILURE!
java.lang.ExceptionInInitializerError
at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:72)
at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:45)
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:388)
at ProductID.<clinit>(ProductID.java:37)
at ProductIDTest.testGetDescription(ProductIDTest.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.testng.junit.JUnit4TestRunner.start(JUnit4TestRunner.java:74)
at org.testng.junit.JUnit4TestRunner.run(JUnit4TestRunner.java:65)
at org.testng.TestRunner$1.run(TestRunner.java:652)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.testng.TestRunner.runJUnitWorkers(TestRunner.java:843)
at org.testng.TestRunner.privateRunJUnit(TestRunner.java:681)
at org.testng.TestRunner.run(TestRunner.java:585)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1109)
at org.testng.TestNG.runSuites(TestNG.java:1039)
at org.testng.TestNG.run(TestNG.java:1007)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:135)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeSingleClass(TestNGDirectoryTestSuite.java:112)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:99)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:146)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:383)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:344)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:125)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:417)
Caused by: java.lang.IllegalStateException: Detected both log4j-over-slf4j.jar AND bound slf4j-reload4j.jar on the class path, preempting StackOverflowError. See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details.
at org.slf4j.impl.Reload4jLoggerFactory.<clinit>(Reload4jLoggerFactory.java:55)
... 56 more
[ERROR] test2 on test2(ProductIDTest)(ProductIDTest) Time elapsed: 0.001 s <<< FAILURE!
java.lang.NoClassDefFoundError: Could not initialize class ProductID
at ProductIDTest.test2(ProductIDTest.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.testng.junit.JUnit4TestRunner.start(JUnit4TestRunner.java:74)
at org.testng.junit.JUnit4TestRunner.run(JUnit4TestRunner.java:65)
at org.testng.TestRunner$1.run(TestRunner.java:652)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.testng.TestRunner.runJUnitWorkers(TestRunner.java:843)
at org.testng.TestRunner.privateRunJUnit(TestRunner.java:681)
at org.testng.TestRunner.run(TestRunner.java:585)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1109)
at org.testng.TestNG.runSuites(TestNG.java:1039)
at org.testng.TestNG.run(TestNG.java:1007)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:135)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeSingleClass(TestNGDirectoryTestSuite.java:112)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:99)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:146)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:383)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:344)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:125)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:417)
[ERROR] test3 on test3(ProductIDTest)(ProductIDTest) Time elapsed: 0 s <<< FAILURE!
java.lang.NoClassDefFoundError: Could not initialize class ProductID
at ProductIDTest.test3(ProductIDTest.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.testng.junit.JUnit4TestRunner.start(JUnit4TestRunner.java:74)
at org.testng.junit.JUnit4TestRunner.run(JUnit4TestRunner.java:65)
at org.testng.TestRunner$1.run(TestRunner.java:652)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.testng.TestRunner.runJUnitWorkers(TestRunner.java:843)
at org.testng.TestRunner.privateRunJUnit(TestRunner.java:681)
at org.testng.TestRunner.run(TestRunner.java:585)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1109)
at org.testng.TestNG.runSuites(TestNG.java:1039)
at org.testng.TestNG.run(TestNG.java:1007)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:135)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeSingleClass(TestNGDirectoryTestSuite.java:112)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:99)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:146)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:383)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:344)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:125)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:417)
[INFO]
A: I added below in my pom.xml
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</exclusion>
I was earlier excluding this from incorrect dependency. I used mvn dependency:tree to determine appropriate dependency it was coming from.
| |
doc_23527576
|
The Media.html file is located in the folder of project.
How can I save this file outer user's local disk?
EDITED
**Sorry for question insufficiently. I mean how copy a resource file like Media.html to disk programatically, in runtime, not VS2010 environment.
A: You may use C#'s file handling techniques, use File.Copy method. Please go here
| |
doc_23527577
|
The domain name is changing for the HTML app only, and I need to be sure that the requests are routed to the new domain name. So, using the rewriteRules sounds like a perfect tool for this, but I'm doing something wrong and need another set of eyes.
The original URL is something like this:
https://example.com/folder1/folder2/app/index.html
The new domain is on an entirely different server and I want all requests from the app folder to go to the new domain name. Here is an example:
https://newdomain.com/folder1/folder2/app/index.html
Unfortunately, I'm doing something wrong that's probably obvious... I keep getting this URL in the redirect.
https://newdomain.com/index.html
Here is the web.config showing what I tried. It's in the app folder.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<customErrors mode="Off" />
</system.web>
<system.webServer>
<rewrite>
<rules>
<rule name="RedirectHtmlApp" stopProcessing="true">
<match url="^(.*)$" ignoreCase="true" />
<conditions logicalGrouping="MatchAny">
<add input="{HTTP_HOST}" pattern="^(www\.)?example\.com$" />
</conditions>
<action type="Redirect" url="https://newdomain.com/{R:0}" redirectType="Permanent" appendQueryString="true" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
{R:0} and {R:1} both return index.html.
A: What is passed to {R:0} is relative. So if your web.config is in /folder1/folder2/app/{here} then "folder1/folder2/app/" are not passed along. If your web.config rule is in the root of the site-app above /folder1, then I am wrong, but if I am right, then you just need to include the path to the root of the app at the destination also. Given what you have above,
<action type="Redirect"
url="https://newdomain.com/folder1/folder2/app/{R:0}"
redirectType="Permanent" appendQueryString="true" />
| |
doc_23527578
|
@objc
func panGesture(_ recognizer: UIPanGestureRecognizer) {
view.endEditing(true)
let translation = recognizer.translation(in: self.view)
let velocity = recognizer.velocity(in: self.view)
// The velocity should have a value when a gesture is happening
//.....
} // End of PanGesture
Is there any patch or some action to make it work properly, same as with the Intel chip? I would please appreciate some suggestions to fix the issue.
FYI: Testing the app on real device, and it still working fine.
| |
doc_23527579
|
I have country states, some int and some another int :
USA -> {{"NY", 100, 100},{"CO", 200, 200},...}
CAN -> {{"Quebec", 100, 100} ...}
There are some countries. I know I need create class, where I will put this data (state, integer, integer), but later I will want provide country and take only this countries data. Data will not change.
Should I put everything into one static variable or split into different vars?
A: As java is Object Oriented Programming, my suggestion would be model it as an object
class State{
int code;
String Name;
int population;
//other info
}
class Country{
int code;
String name
List<State> state;
// Other details
}
Now in a class create a Collection of Country
List<Country> countries;
A: I understand your question as follows:
You want to store associations of country to collection-of-{sate, data1, data2}, and later access the collection that is associated with a specific country.
In this case you can use a HashMap, which provides just such association. Assuming you have a StateData class that captures the {state, data1, data2} triple, you can write:
HashMap<String, Collection<StateData>> countries;
Populate the map with:
List<StateData> stateColl = new LinkedList<StateData>();
Map<String, List<StateData>> countries = new HashMap<String, List<StateData>>();
countries.put("USA", stateColl);
stateColl.add(stateData1);
stateColl.add(stateData2);
//...
where stateData1,... is of type StateData. Note that you can use any collection that fits your needs instead of LinkedList. You could also use a TreeMap instead of the HashMap if you need to store the countries in (alphabetical) order, but that comes with some performance hits.
Then access the state collections as:
List<StateData> stateColl = countries.get("USA");
for (StateData stateData : stateColl)
{
// process the state info
}
A: I suggest you have a class to host the data you need to keep (String,int,int), something like this
class State{
private String name;
private int id,xyz;
//setter and getter methods
}
then you may need two lists/array, one for US, and another for CAN.
public class Foo{
private List<State> usGuys=new ArrayList<>();//you would use State[] instead
private List<State> canGuys=new ArrayList<>();
}
for keeping the instances you would either keep them withing List or arrays, it's up to you and the requirements.
but about your issue, you would keep all the data into one array/list, so in this case you need to add another attribute to State class to indicates the country
private String country
but this may complex/make-it-hard the process in future because for example if you want to get all states in US, you need a for loop in order to check which states are belong to US, having multiple list may give you a better management
but what if the size of the countries is unknown!
simple enough, like you have list for storing states, you will have a list for keeping countries., something like this
class Country{
private List<State> states;
private String name;
}
class Foo{
private List<Countries> countries;
}
I hope I could give some hand.
A: Enum will be ideal for storing this information. They are preferred way of storing constants since Java5.
A: It can be done in one operation by using an initializer block. A minimal implementation to reprsent your data would be:
Create classes for your entities:
class Country {
String shortName;
List<State> states;
Country(String s, State... stateArray) {
shortName = s;
states = Arrays.asList(stateArray);
}
// getters omitted
}
class State {
String code;
int num1, num2:
State(String c, int n1, int n2) {
cude = c;
num1 = n1;
num2 = n2;
}
// getters omitted
}
Then to create the variable:
List<Country> countries = new ArrayList<Country>() {{
add(new Country("USA",
new State("NU", 100, 100),
new State("CO", 200, 200)
);
add(new Country("CAN",
new State("Quebec", 100, 100)
);
}};
A: How about something like this:
static class State {
String name;
int i1, i2;
State(String name, int i1, int i2) {
this.name = name;
this.i1 = i1;
this.i2 = i2;
}
}
final static Map<String, Map<String, State>> countryStateMap;
static {
countryStateMap = new HashMap<>();
Map<String, State> usa = new HashMap<>();
usa.put("NY", new State("NY", 100, 100));
usa.put("CO", new State("CO", 200, 200));
Map<String, State> ca = new HashMap<>();
ca.put("Quebec", new State("Quebec", 100, 100));
// and so on
countryStateMap.put("USA", usa);
countryStateMap.put("CA", ca);
}
This uses a final static Map an initializes it in a static block. The initialization is done a soon as the class is loaded.
Then you can use it like this in your code
Map<String, State> usaStates = countryStateMap.get("USA");
State ny = usaStates.get("NY");
| |
doc_23527580
|
public ActionResult TestView()
{
ViewData["Test"] = "1";
return View("TestView");
}
In TestView.cshtml, I have this line of code
@ViewData["Test"]
It is coming up as null, it is not printing the "1".
Any idea what I am doing wrong?
Thanks.
A: MV3 have ViewBag as a new object that can hold the dynamic properties as Key/Value pair.
So you can directly assign a property using ViewBag. For e.g. -
In your action in controller you can write something like
ViewBag.Message = "1";
Now to retrieve the value you can write in your .cshtml
<h2>@ViewBag.Message</h2>
| |
doc_23527581
|
This is what i have:
8 Ball Script S Caps S S K
This is what i want:
8 Ball Script S Caps SSK
In short i need to correct every abrivations in the string dynamicly. wherever in the string that i can find something like "A B R I V", it needs to remove the spaces "ABRIV" without screwing with everything else in the string. So that i can have a string that is something like "H I, Hello F O O World, i have B A C O N" should become "HI, Hello FOO World, i have BACON".
This is my code so far:
$string = preg_replace("/(?<= )[A-Z](?![a-z]).(?![A-Za-z]+[a-z])/", '$0', $string);
A: This seems to do what you want:
$s = preg_replace('~(?<![A-Za-z])([A-Z]) (?=[A-Z](?![A-Za-z]))~', '$1', $s);
see a demo on ideone.com
| |
doc_23527582
|
$("div#container div.content div.main").load(siteLink+"/"+newloadVal);
It works great, however, I am looking for a way to stop visitors from accessing these included pages THROUGH their actual weblinks such as site.com/pagelink.php.
My main question is, is there a way to do a similar PHP define("THROUGHJS,true); using Javascript, so if the visitor accesses the included page through its actual link, it will redirect to an error page?
Is there an easy way to do this, mainly through JUST PHP?
I have not attempted this, but is this possible:
In the parent page, have DEFINE("mainpage",true),
then in the dynamically loaded page, have:
if(defined("mainpage")){
...}
else { exit; } // Show an error?\
I am not sure if this is possible as the dynamic page is not being loaded via PHP, therefore the defined function in the parent page will not "exist" to the dynamic page?
Thanks for any help in advance. (Sorry if this may seem confusing) :P
A: A possible semi-solution:
Generate a unique key for a user's session and pass it to all requests to the additional pages.
For each request of an additional page through jquery, include this key as a query parameter (or as post data). When the required page is loaded, check if the key matches the user's session. If not, display an error.
Something like this:
$("...").load(siteLink + "/" + newloadVal + "?key=<?php echo $session_key ?>");
This will not actually prevent users from directly accessing your pages, but it will require them to know a valid key. For this the (average user) will have to visit the main page, look at the source, find the key, etc.
A: EDIT: I ended up going with an AJAX request, that way I can use request headers to determine if the page was loaded using AJAX or not.
Thanks for all your help guys :)
| |
doc_23527583
|
$ip = $_SERVER['REMOTE_ADDR'];
I have a geo database with the following tables:
blocks
locations
zipcodes
nations
dma_codes
states
This is the table I'm interested in
blocks
start_ip | end_ip | location_id
-------------------------------
33996344 | 33996351 | 16373
50331648 | 67166463 | 223
etc...
Above are just the first 2 records of the 1,866,401 rows in total in that table. I have no idea which geo database this is. Maybye MaxMind but not sure. I inherited this project from the client's previous developer who uploaded this database but didn't do anything with it yet. So I have no code samples to go on.
Can anyone please explain how I would get the location_id if my ip address happens to be:
72.63.83.41
Also does anyone recognize these table names so maybye I can find out which geo db this is.
A: IPv4 addresses are just 32bit integers, and you can use MySQL to convert a 'string' IP address to/from those ints via inet_ntoa() (number to ascii) and inet_aton() (ascii to number).
SELECT location_id
FROM yourtable
WHERE INET_ATON('70.63.83.41') BETWEEN start_ip AND end_ip
would give you any matching location_id for that particular IP.
| |
doc_23527584
|
1) Filename : lib_mylib.h
int fun();
int fun1(void);
int fun2(void);
2) Filename: lib_mylib.c */
#include <stdio.h>
int fun() {
return 2;
}
int fun1(void) {
return 2;
}
int fun2(void) {
return 2;
}
3) File :my_lib_shared.c
#include "my_lib.h"
int foo(void) {
return fun() + 4;
}
4) File: my_lib_shared.h
int foo();
5) File driver.c
/* filename: driver.c */
#include "my_lib.h"
#include "my_lib_shared.h"
#include <stdio.h>
int main() {
int x = foo() ;
return 0;
}
If I execute following steps
1)gcc -fPIC -fvisibility=hidden -c my_lib.c -o lib_mylib.o
2)gcc -fPIC -fvisibility=hidden -shared -o libMyLibHidden.so lib_mylib.o
3)gcc -fPIC -c my_lib_shared.c -o my_lib_shared.o
4)gcc -shared -o libMyShared2.so my_lib_shared.o
5)gcc -L. -Wall -o test_hidden driver.c -lMyLibHidden -lMyShared2
The output of objdump is as
objdump -T libMyLibHidden.so
libMyLibHidden.so: file format elf64-x86-64
DYNAMIC SYMBOL TABLE:
0000000000000448 l d .init 0000000000000000 .init
0000000000000000 w D *UND* 0000000000000000 __gmon_start__
0000000000000000 w D *UND* 0000000000000000 _Jv_RegisterClasses
0000000000000658 g DF .fini 0000000000000000 Base _fini
0000000000000000 w D *UND* 0000000000000000 _deregisterTMCloneTable
0000000000000000 w D *UND* 0000000000000000 _ITM_registerTMCloneTable
0000000000000000 w DF *UND* 0000000000000126 GLIBC_2.2.5 _cxa_finalize
0000000000200938 g D *ABS* 0000000000000000 Base __bss_start
0000000000200948 g D *ABS* 0000000000000000 Base _end
0000000000200938 g D *ABS* 0000000000000000 Base _edata
0000000000000448 g DF .init 0000000000000000 Base _init
I did not any reference of functions of fun, fun1 and fun2 in the above objdump
and I get following error at final linking step
/tmp/ccMsEpFq.o: In function main':
driver.c:(.text+0xe): undefined reference tofun'
collect2: error: ld returned 1 exit status
When I make static library from lib_mylib.c
1)gcc -g -fvisibility=hidden -c my_lib.c -o lib_mylib.o
2)ar rcs libMylib_static_hidden.a lib_mylib.o
3)gcc -g -fvisibility=hidden -c -fPIC my_lib_shared.c -o my_lib_shared.o
4)gcc -g -shared -o libMyShare.so my_lib_shared.o
5)gcc -g driver.c -L . -Wall -o test_static_hidden -lMyShare -lMylib_static_hidden
and I get following objdump
objdump -t libMylib_static_hidden.a
In archive libMylib_static_hidden.a:
lib_mylib.o: file format elf64-x86-64
SYMBOL TABLE:
0000000000000000 l df *ABS* 0000000000000000 my_lib.c
0000000000000000 l d .text 0000000000000000 .text
0000000000000000 l d .data 0000000000000000 .data
0000000000000000 l d .bss 0000000000000000 .bss
0000000000000000 l d .debug_abbrev 0000000000000000 .debug_abbrev
0000000000000000 l d .debug_info 0000000000000000 .debug_info
0000000000000000 l d .debug_line 0000000000000000 .debug_line
0000000000000000 l d .debug_frame 0000000000000000 .debug_frame
0000000000000000 l d .eh_frame 0000000000000000 .eh_frame
0000000000000000 l d .debug_pubnames 0000000000000000 .debug_pubnames
0000000000000000 l d .debug_aranges 0000000000000000 .debug_aranges
0000000000000000 l d .debug_str 0000000000000000 .debug_str
0000000000000000 l d .note.GNU-stack 0000000000000000 .note.GNU-stack
0000000000000000 l d .comment 0000000000000000 .comment
0000000000000000 g F .text 000000000000000b .hidden fun
000000000000000b g F .text 000000000000000b .hidden fun1
0000000000000016 g F .text 000000000000000b .hidden fun2
When I final link the library
5)gcc -g driver.c -L . -Wall -o test_static_hidden -lMylib_static_hidden -lMyShare
I get following linker error
test_static_hidden:
hidden symbol `fun' in
libMylib_static_hidden.a(lib_mylib.o) is referenced by DSO
/tools/linux64/gcc-4.0.2/bin/ld: final link failed: Nonrepresentable section on output
I need guidance on why hidden visibility does not get applied when I make shared libraries and why I get undefined reference in case of linking shared library libMyLibHidden.so
I
| |
doc_23527585
|
import Button from '@mui/material/Button';
<Button variant="contained" onClick={() => props.chatIDState(chatRoom.chatIDFromTableChats)}>open</Button>
This button is rendered blue, but I want to change the color. I tried creating a css class and I tried setting the color directly, neither worked.
How can I override the default color and give it top render priority?
A: According to the documentation you can have classnames
Css
.Button {
color: black;
}
/* Increase the specificity */
.Button:disabled {
color: white;
}
React
<Button disabled className="Button">Click me</Button>
Update
Inline styling
<Button variant='contained' sx={{ backgroundColor: 'green' }}>HELLO</Button>
You can also add !important (which is NOT encouraged) in your css which will override the native styles.
.Button {
background: red !important;
}
React
<Button className="Button">Click me</Button>
Reference:
https://mui.com/material-ui/customization/how-to-customize/
| |
doc_23527586
|
Connection conn = DriverManager.getConnection(conn_str);
conn.close();
Thread.sleep(30 * 1000);
The above code works pretty fine. The conn will be closed immediately after calling close() and no connection appears during sleep().
After that, I wrote a thin connection wrapper:
public static Connection CreateConnection(String _connectionStr) throws SQLException {
Connection c = null;
c = DriverManager.getConnection(_connectionStr);
return c;
}
the modified code is:
Connection conn = ConnectionWrapper.CreateConnection(conn_str);
conn.close();
Thread.sleep(30 * 1000);
I expect these two have no difference, but with the latter case, the connection had been remain unclosed until the program terminates (here 30 seconds). This does not happen in the former code.
I checked the behavior with mysqladmin extend-status | grep connected, looking at the value of Threads_connected.
I want to use the latter wrapper for code abstraction. Please tell me if you have any idea of the behavior or workaround to close the connection forcibly.
Thanks,
--
Edited: fixed the "wrapper" code. It was my mistake.
Edited: The number of connections from mysqladmin is by default 1 (diagnostic one). The number becomes 2 while the latter code is running, while it is 2 with the former.
A: can you have a try on this codes... and see what will the error output...
try{
con.close();
if (con.isClosed())
System.out.println("Connection closed.");
} catch (java.lang.ClassNotFoundException e) {
System.err.println("ClassNotFoundException: " +e.getMessage());
} catch (SQLException e) {
System.err.println("SQLException: " +e.getMessage());
}
A: I think it is connection pooling (a idea to save time on reconnects...)
Look into this article:
http://dev.mysql.com/tech-resources/articles/connection_pooling_with_connectorj.html
A: ok, sorry for being so numb looking at your code... as you can see... you created a connection inside a method... so it means when you get out of that method... you will not be able to close that connection(the variable c) because you just copied the connection on another variable by using a return(which is your variable conn)... and still the connection remains. Try to create a class for your wrapper and not a method
| |
doc_23527587
|
function submitdata() {
var email = document.getElementById('email');
var password = document.getElementById('password');
let user = localStorage.getItem('user');
var userObj = [];
for (var i = 0; i <= userObj.length; i++) {
if (email.value === userObj[i].useremail) {
alert("already registered")
}
else if (user === null) {
var userObj = [];
}
else {
userObj = JSON.parse(user);
userObj.push({ useremail: email.value, userpw: password.value })
localStorage.setItem("user", JSON.stringify(userObj));
email.value = "";
password.value = "";
}
}
}
A: var userObj = [];
Looks like this is the issue. The length of the userObj is 0.
if (email.value === userObj[i].useremail)
Here the userObj is empty. The 0th index never there in first place.
I tried to simulate the same case. You should have got error something like this.
let users = []
console.log(users[0].email);
VM329:1 Uncaught TypeError: Cannot read property 'email' of undefined
at <anonymous>:1:10
(anonymous) @ VM329:1
Execute this loop only when you have more than one item in your userObj
| |
doc_23527588
|
Today we can buy something like i7 with 8Mb cache
Why cache growing up so slow? It's to hard to implement, or maybe there is no reason to do, or maybe it's different cache?
A: This is a tricky question indeed. The 8 MB you are talking about, is the amount of L3 cache found in some high level CPUs like i7 and some xeons.
The optimal amount of cache is obtained by a calculus between the maximum amount of RAM for the system, the number of physical cores and the CPU cycles.
For instance this Xeon CPU got 45 MB of cache but can handle 8 threads and 1.5TB of memory..
The cache of the CPU is made of multiple types L1, L2, L3 and L4 (Also known as eDram, is a high bandwidth DRAM, first seen in video game consoles (like XBOX 360 and PlayStation 2) and dedicated to the internal GPU. The commercial name for the Intel Chips with internal GPU + eDRAM is Iris PRO. The Haswell microarchitecture was the first Intel microprocessor to propose this graphical enhanced design. This L4 is used as a Victim Cache for the L3 cache).
Look the complete specifications of one of the recent i7 cpu from intel to see an example of the kind of caches you can find internally.
But it's not only the amount of cache that matters but the nature of it. The latest CPUs have level 3 (L3), 8 ways memory type (to be compared with 2 or 4 ways in the past) providing synchronous access to the 8 virtual cores.
The closer the cache is to the cpu, the faster he is.
The L1 cache (the faster and the more expensive) is used per physical core, L2 more or less for the threads and the L3 for DMA channel (buffered) communication with the main memory.
The more cache you have the less 'cache hit misses' you get. The number of misses (errors) is related to the CPU cycles (speed in Mhz) and the amount of cache.
According to the statistics, above a specific limit increasing the amount of cache provides a little or no performance improvement. So the cost of the CPU increases for a very small improvement.
The amount of cache must respect a ratio between performance improvement and cost.
The same reason explains why you can find more ram on high end cpus.
The speed of the ram is also improving over the time, so the amount of cache is less critical for CPU performance has it was in the past.
For a full article on the subject I recommend this very good page.
| |
doc_23527589
|
to_remove pred_0 .... pred_10
0 ['apple'] ['apple','abc'] .... ['apple','orange']
1 ['cd','sister'] ['uncle','cd'] .... ['apple']
On each row, I want to remove the element in pred_0...pred_10 if this element show up in to_remove in the same row.
In this example, the answer should be:
to_remove pred_0 .... pred_10
0 ['apple'] ['abc'].... ['orange'] # remove 'apple' this row
1 ['cd','sister'] ['uncle']....['apple'] # remove 'cd' and 'sister' this row
I am wondering how to associate the code to do so.
To generate the example df:
from collections import OrderedDict
D=pd.DataFrame(OrderedDict({'to_remove':[['apple'],['cd','sister']],'pred_0':[['apple','abc'],['uncle','cd']],'pred_1':[['apple','orange'],['apple']]}))
A: You can try of iterating the each row by row and filter the elements which are not specified in that column
Considered dataframe
pred_0 pred_10 to_remove
0 [apple, abc] [apple, orage] [apple]
1 [uncle, cd] [apple] [cd, sister]
df.apply(lambda x: x[x.index.difference(['to_remove'])].apply(lambda y: [i for i in y if i not in x['to_remove']]),1)
Out:
pred_0 pred_10
0 [abc] [orage]
1 [uncle] [apple]
A: You can use a couple of list comprehensions:
s = df['to_remove'].map(set)
for col in ['pred_0', 'pred_1']:
df[col] = [[i for i in L if i not in S] for L, S in zip(df[col], s)]
print(df)
to_remove pred_0 pred_1
0 [apple] [abc] [orange]
1 [cd, sister] [uncle] [apple]
List comprehensions will likely be more efficient than pd.DataFrame.apply, which has the expensive of constructing and passing a series to a function for each row. As you can see, there's no real leveraging of Pandas / NumPy for your requirement.
As such, unless you can afford to expand your lists into series of strings, dict + list may be a more appropriate choice of data structure.
| |
doc_23527590
|
My system have a timezone setting for everyuser ,User 1 is in UTC+6, User 2 is in UTC , User 3 is in UTC+3, my server is UTC.
When User update / create a record or Get data from record to datatables, Server will automatically convert the timezone and return to User. Or when user post the data to server, server will automatically convert it to UTC depend on the timezone setting of user before saving to database. Anyway to do this ?
I want to do this massive for all class in my project :) Just trying to extend the eloquent class but don't know where to start.
A: In general, you should store data in the database in one timezone (your preferred timezone for example). When you display the data to the user, you can display it based on their timezone easily.
Check out the DateTime class. It will allow you to create a Date object, set the time, then change the timezone (to the users timezone), then output in a given format.
| |
doc_23527591
|
I have a code without error.
I am using multiple functions. But I wonder if I pass the objects and the specific target with one function like dropIt since I have more objects and duplicated functions.
This picture is what I want to implement.
and the code is as follows.
Thanks in advance.
var obj1:Array = [obj_1, obj_10];
var obj2:Array = [obj_2, obj_20];
for each(var redsMC:MovieClip in reds)
{
obj1MC.buttonMode = true;
obj1MC.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
obj1MC.addEventListener(MouseEvent.MOUSE_UP, dropIt);
obj1MC.startX = obj1MC.x;
obj1MC.startY = obj1MC.y;
}
for each(var orangesMC:MovieClip in oranges)
{
obj2MC.buttonMode = true;
obj2MC.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
obj2MC.addEventListener(MouseEvent.MOUSE_UP, dropIt1);
obj2MC.startX = obj2MC.x;
obj2MC.startY = obj2MC.y;
}
function pickUp(event:MouseEvent):void
{
event.target.startDrag(true);
event.target.parent.addChild(event.target);
}
function dropIt(event:MouseEvent):void
{
event.target.stopDrag();
if(event.target.hitTestObject(target1)){
event.target.buttonMode = false;
event.target.x = target1.x;
event.target.y = target1.y;
}else if(event.target.hitTestObject(target10)){
event.target.buttonMode = false;
event.target.x = target10.x;
event.target.y = target10.y;
}
else
{
event.target.x = event.target.startX;
event.target.y = event.target.startY;
event.target.buttonMode = true;
}
}
function dropIt1(event:MouseEvent):void
{
event.target.stopDrag();
if(event.target.hitTestObject(target2)){
event.target.buttonMode = false;
event.target.x = target2.x;
event.target.y = target2.y;
}else if(event.target.hitTestObject(target20)){
event.target.buttonMode = false;
event.target.x = target20.x;
event.target.y = target20.y;
}
else
{
event.target.x = event.target.startX;
event.target.y = event.target.startY;
event.target.buttonMode = true;
}
}
A: You should somehow make your draggable objects know their targets, thus when your SWF registers an end drag event, the object that was being dragged would check against its target and if not colliding, then float/jump back. Since your objects derive from MovieClips, it's possible to add custom properties to them without doing any declarations, but be sure to check if there is something in a custom property before using it. Let's say you have assigned each draggable object a desiredTarget as whatever target you need them to be dragged. Then, you can do like this:
function dropIt(e:MouseEvent):void {
var desiredTarget:MovieClip=e.target.desiredTarget as MovieClip; // get where this should be placed
e.target.stopDrag(); // we still need to release the dragged object
if (!desiredTarget) return; // no target - nothing to do (also helps with debug)
if (e.target.hitTestObject(desiredTarget)) {
e.target.buttonMode=false;
e.target.x=desiredTarget.x;
e.target.y=desiredTarget.y;
} else {
// move dragged object back to starting position
e.target.x=e.target.startX;
e.target.y=e.target.startY;
}
}
A: Despite the fact Vesper's answer is already accepted, I think it to be far too brief and insufficient, on top of that it doesn't actually answer how to design a system where any number of objects could be dropped to any number of targets, without substantial changes to the code.
// Unlike the Object class, that allows String keys only
// the Dictionary class allows you to store and
// access data by the object instance.
var theValids:Dictionary = new Dictionary;
// We'll store the original (x,y) coordinates here.
var theOrigin:Point = new Point;
// The Sprite class is the superclass of MovieClip, furthermore,
// the startDrag method defined for Sprite class, so unless you
// create your own dragging code, you are bound to use Sprites,
// while you cannot drag SimpleButtons and TextFields this way.
// We'll store the current dragged object here.
var theObject:Sprite;
// This first argument is the object you want to be draggable.
// The "...targets:Array" means you can call this method with
// any number of arguments, the first one is mandatory, the
// rest will be passed in a form of Array (empty Array if you
// call this method with a single argument).
function setupDraggable(source:Sprite, ...targets:Array):void
{
// Make the object draggable.
source.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
source.mouseChildren = false;
source.mouseEnabled = true;
source.buttonMode = true;
// Keep the list of the object's targets so it can be
// retrieved later by the key of the object itself.
theValids[source] = targets;
}
// Ok, let's setup the objects and link them to their designated
// targets. The whole point of the rest of the code is to make
// this one part as simple as it possible: you just edit
// these lines to tell which one objects go where.
// This object can be dropped to a single target.
setupDraggable(obj_1 , target1);
// These objects can go to two targets each.
setupDraggable(obj_10, target1, target10);
setupDraggable(obj_2 , target2, target20);
// This one object can be dropped to any of targets.
setupDraggable(obj_20, target1, target10, target2, target20);
// The MOUSE_DOWN event handler.
function onDown(e:MouseEvent):void
{
// Get the reference to the object under the mouse.
theObject = e.currentTarget as Sprite;
// Keep the object's initial position.
theOrigin.x = theObject.x;
theOrigin.y = theObject.y;
// Put the dragged object on top of anything else.
// We are operating in the parent context of all these
// objects here so there's no need to address anObj.parent.
setChildIndex(theObject, numChildren - 1);
// Start dragging.
theObject.startDrag(true);
// Listen to the MOUSE_UP event, which could happen offstage
// and out of the dragged object, so the only reliable
// way is to listen it from the Stage. That's why we
// are keeping theObject reference as an additional
// variable, without relying on event's data.
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
}
// The MOUSE_UP event handler.
function onUp(e:MouseEvent):void
{
// Unsubscribe the MOUSE_UP event handler.
stage.removeEventListener(MouseEvent.MOUSE_UP, onUp);
// Stop the dragging process.
theObject.stopDrag();
// Let's assume there could be more than a single collision.
// We need to figure the one target that is closest.
var theTarget:DisplayObject;
var theDistance:int = 100000;
// Store the dragged object position so we can
// measure distances to the valid collisions, if any.
var thePlace:Point = theObject.localToGlobal(new Point);
// Now, the magic. Lets browse through the
// valid targets and see if there's a collision.
for each (var aTarget:DisplayObject in theValids[theObject])
{
if (theObject.hitTestObject(aTarget))
{
// Let's see if the current collision is closer
// to the dragged object, than the previous one
// (if any, that's what initial 100000 for).
var aPlace:Point = aTarget.localToGlobal(new Point);
var aDistance:int = Point.distance(aPlace, thePlace);
if (aDistance < theDistance)
{
theTarget = aTarget;
theDistance = aDistance;
}
}
}
// If there's at least one collision,
// this variable will not be empty.
if (theTarget)
{
// Make the object non-interactive.
theObject.removeEventListener(MouseEvent.MOUSE_DOWN, onDown);
theObject.mouseEnabled = false;
theObject.buttonMode = false;
// Glue the dragged object to the center of the target.
theObject.x = theTarget.x;
theObject.y = theTarget.y;
}
else
{
// If we're here, that means there was no valid collisions,
// lets return the object to its designated place.
theObject.x = theOrigin.x;
theObject.y = theOrigin.y;
}
// Clean-up. Remove the reference, the object is no longer
// being dragged, so you won't need to keep it.
theObject = null;
}
P.S. I didn't test it, but I think I put enough comments to explain the whole idea.
| |
doc_23527592
|
*
*Add a static method boolean isValidNumber(String aNumber).
*Check whether the number conforms to the template 'ddd-dd-dddd',
where every 'd' in the template stands for a digit and the '-' for a
'-' character.
Can please anybody give a hint how to do it?
A: All you need to do is use the String matches method to compare against a regular expression String.
return aNumber.matches("\\d\\d\\d-\\d\\d-\\d\\d\\d\\d");
A: Check this out:
public static boolean isValidNumber(String aNumber) {
if (aNumber.matches("\\d{3}-\\d{2}-\\d{4}")) {
// Match found
return true;
}
// Not a valid number
return false;
}
A: Do like this
public boolean isValidNumber(String aNumber){
return aNumber.matches("\\d{3}-\\d{2}-\\d{4}")
}
A: Try this Regular Expression for your particular Sequence
^[0-9]{3}\-[0-9]{2}\-[0-9]{4}$
this definitely helps you.
public class Sample
{
public static void main(String ar[])
{
String aNumber= "254-58-3698";
isValidNumber(aNumber);
}
public static Boolean isValidNumber(String aNumber)
{
String pattern = "^[0-9]{3}\\-[0-9]{2}\\-[0-9]{4}$";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Number has Matched");
return true;
} else {
System.out.println("NO MATCH");
return false;
}
}
}
output:
Number has Matched
A: You can use a pre-built Pattern if you call this method a lot.
static final Pattern DDD_DD_DDD = Pattern.compile("\\d{3}-\\d{2}-\\d{4}");
public static boolean isDDD_DD_DDDD(String text) {
return DDD_DD_DDD.matcher(text).matches();
}
public static void main(String... ignored) {
for(String text: "Hello, 123-45-6789, 111-22-3333, 11-222-3333".split(", ")) {
System.out.println(text+" is valid: "+isDDD_DD_DDDD(text));
}
}
prints
Hello is valid: false
123-45-6789 is valid: true
111-22-3333 is valid: true
11-222-3333 is valid: false
| |
doc_23527593
|
I have a set of interfaces/classes as follows. For the sake of simplicity imagine more properties, collections etc.
interface IMaster
{
//Some properties
}
interface IB : IMaster
{
string PropOnA { get; set }
}
interface IC : IMaster
{
string PropOnB { get; set }
}
class B : IB
class C : IC
...
These contracts were designed to store data(which is held in a slightly different format in each case). There is a lot of code that uses these contracts to get the data, format it, process it, write etc.
We have developed an entire library that does not see the concrete implementations(B,C) of any of these contracts by inverting control and allow the user to use our 'default implementations' for each contract or just loading in their own. We have registry where the user can register a different implementation.
To this end I have implemented a kind of strategy pattern where there exists a strategy for each contract type based on the task at hand. For the sake of simplicity lets say the task is writing, in reality it is much more complicated.
interface IWriteStrategy
{
public Write(IMaster thing);
}
class WriterA : IWriteStrategy
class WriterB : IWriteStrategy
etc
The above concrete strategies are also never 'seen' in our library, the client must register their own implementation or our default version.
Design flaw??
I am not liking the cast in every strategy that is now necessary.
public classWriterA : IWriteStrategy
{
public void Write(IMaster thing)
{
if(thing is IA thingA)
//do some work
}
}
public classWriterB : IWriteStrategy
{
public void Write(IMaster thing)
{
if(thing is IB thingB)
//do some work
}
}
What we want to do is be able to loop through a list of IMaster objects and run some operations.
foreach(var thing in Things)
{
var strategy = GetStrategy(thing.GetType()); //this gets the strategy object from our `registry` if one exists
strategy.Execute(thing);
}
The above design allows this but there seems to be a flaw which I cant for the life of me spot a solution to. We have to cast to the specific interface within each strategy implementation.
I have tried with generics, but just cant seem to nail it.
Question
What would be a better way of designing this to avoid the cast but still be able to loop through a list of IMaster things and treat them the same? Or is the cast absolutely necessary here?
I am trying to follow a SOLID design but feel the cast is messing with this as the client implementing the strategies will have to do the cast in order to get anything to work within the Write method.
[Edit]
I have updated the classes implementing the IWriteStrategy.
A: If you rarely add new IMaster specializations, but often add new operations OR need to make sure operation providers (e.g writer) needs to support ALL specializations then the Visitor Pattern is a perfect fit.
Otherwise you basically need some kind of service locator & registration protocol to map operation providers/strategies to IMaster specializations.
One way you could do it is define generic interfaces such as IMasterWriter<T> where T:IMaster which can then be implemented like IBWriter : IMasterWriter<IB> which defines the mapping.
From that point you only need a mechanism that uses reflection to find a specific IMasterWriter implementor for a given type of IMaster and decide what to do if it's missing. You could scan assemblies early to detect missing implementations at boot rather than failing later too.
A: Maybe it is appropriate to use Strategy pattern and just give an implementation and execute it. Let me show an example.
interface IMaster
{
void ExecuteMaster();
}
class MasterOne : IMaster
{
public void ExecuteMaster()
{
Console.WriteLine("Master One");
}
}
class MasterTwo : IMaster
{
public void ExecuteMaster()
{
Console.WriteLine("Master Two");
}
}
and
interface IWriteStrategy
{
void Write(IMaster thing);
}
class WriterA : IWriteStrategy
{
public void Write(IMaster thing)
{
Console.WriteLine("Writer A");
thing.ExecuteMaster();
}
}
class WriterB : IWriteStrategy
{
public void Write(IMaster thing)
{
Console.WriteLine("Writer B");
thing.ExecuteMaster();
}
}
and code to execute:
static void Main(string[] args)
{
List<IWriteStrategy> writeStrategies = new List<IWriteStrategy>()
{
new WriterA(),
new WriterB()
};
List<IMaster> executes = new List<IMaster>()
{
new MasterOne(),
new MasterTwo()
};
for (int i = 0; i < writeStrategies.Count(); i++)
{
writeStrategies[i].Write(executes[i]);
}
}
A: what about this, you will have all your casts in one strategy factory method:
public interface IWriterStrategy
{
void Execute();
}
public class WriterA : IWriterStrategy
{
private readonly IA _thing;
public WriterA(IA thing)
{
_thing = thing;
}
public void Execute()
{
Console.WriteLine(_thing.PropOnA);
}
}
public class WriterB : IWriterStrategy
{
private readonly IB _thing;
public WriterB(IB thing)
{
_thing = thing;
}
public void Execute()
{
Console.WriteLine(_thing.PropOnB);
}
}
public static class WriterFactory
{
public static List<(Type Master, Type Writer)> RegisteredWriters = new List<(Type Master, Type Writer)>
{
(typeof(IA), typeof(WriterA)),
(typeof(IB), typeof(WriterB))
};
public static IWriterStrategy GetStrategy(IMaster thing)
{
(Type Master, Type Writer) writerTypeItem = RegisteredWriters.Find(x => x.Master.IsAssignableFrom(thing.GetType()));
if (writerTypeItem.Master != null)
{
return (IWriterStrategy)Activator.CreateInstance(writerTypeItem.Writer, thing);
}
throw new Exception("Strategy not found!");
}
}
public interface IMaster
{
//Some properties
}
public interface IA : IMaster
{
string PropOnA { get; set; }
}
public interface IB : IMaster
{
string PropOnB { get; set; }
}
public interface IC : IMaster
{
string PropOnC { get; set; }
}
public class ThingB : IB
{
public string PropOnB { get => "IB"; set => throw new NotImplementedException(); }
}
public class ThingA : IA
{
public string PropOnA { get => "IA"; set => throw new NotImplementedException(); }
}
public class ThingC : IC
{
public string PropOnC { get => "IC"; set => throw new NotImplementedException(); }
}
internal static class Program
{
private static void Main(string[] args)
{
var things = new List<IMaster> {
new ThingA(),
new ThingB()//,
//new ThingC()
};
foreach (var thing in things)
{
var strategy = WriterFactory.GetStrategy(thing); //this gets the strategy object from our `registry` if one exists
strategy.Execute();
}
}
}
| |
doc_23527594
|
Is it possible to give them a link or a package from which they can simply install this script and a new button "Stats" will appear in their gmail account?
A: You can have only Contextual Gadgets or Sidebar gadgets in GMail app. You can't make a script or its result appear directly in GMail.
An apps script can be published to a gallery. See Sharing Your Scripts section. It'll have to wait for a Google review though. I tried submitting a script awhile back but it never got a confirmation that it was published at some point.
A couple of fast ways:
*
*You send your customers the source code with instructions (e.g. "Go to Tools => Script Editor", "Paste my code", etc..)
*Share the spreadsheet along with the script itself (you'll need to enabled script code sharing even if the spreadsheet is shared already) and tell them to make a copy, including the script.
| |
doc_23527595
|
now i did validation on onchange event if any validation fail then i raise alert
but when i press press enter button if validation failed then i dont want to execute
keydown event
any suggestion
Thanks,
Nik
A: Not sure what exactly you want but if you want to control an keydown event you can do like this:
<script type="text/javascript">
function onKeyDown()
{
if(event.keyCode == 13 ) // if enter key
{
// your validation-checking code here
if("validationfailed")
return false // prevent the event from happening if validation failed
else return true;// validating ok, allow it.
}
else
{
// another key, alow it.
return true;
}
}
</script>
<input type="text" id="myText" onchange="validateText()" onkeydown="return onKeyDown()">
A: What you need to do is check the value of the key code on keydown for an invalid form.
Also define a local variable, assuming that the 2 functions are defined in the same context, if they are not use apply to call them in the same context.
At that you can have a check if(event.keyCode != 13 && !invalid){ [Your operations] }
You can get more information about keycodes here.
I hope this helps.
A: You would want to create a global variable (boolean) that your onchange event will alter. Auto set that boolean to false, after it has been validated change it to true. After the keydown event is fired you will want to check and see if it was the enter key and that it passed all of your validation before taking any further action.
<script type="text/javascript">
var passedChecks = false;
function validateText(e) {
var src = (window.event) ? window.event.srcElement: e;
if (src.value == b) { // verify your logic is true.
passedChecks = true;
}
}
function validateKey(e) {
var src = (window.event) ? window.event.srcElement: e;
if (src.keyCode == 13) {
if (passedChecks == true) {
// process your code.
}
}
}
</script>
<input type="text" id="myText" onchange="validateText()" onkeydown="validateKey()">
| |
doc_23527596
|
A: You can create a new ios target and delete the ones that you don't want.
Click the + button at the bottom of the Targets List.
Then select ios, filter by "app," and select the iOS app template target.
Once your new target is added, you can select the new target Scheme. The ios devices will be listed in that Scheme.
| |
doc_23527597
|
My code looks like:
class SomeFancyCollection[+A] {
private var root: Node = Branch(0x0, Vector[Node]())
trait Node {
val id: Byte
def put[A1 >: A](ids: Seq[Byte], item: A1): Node
def remove[A1 >: A](ids: Seq[Byte], item: A1): Node
}
case class Branch(id: Byte, subs: Vector[Node]) extends Node {
...
}
case class Leaf[A1 >: A](id: Byte, subs: Vector[A1]) extends Node {
...
}
def add[A1 >: A](item: A1): SomeFancyCollection[A1] = {
val ids: Seq[Byte] = getIds() // doesn't matter
val newRoot = root.put(ids, item)
val newInstance = new SomeFancyCollection[A1]()
newInstance.root = newRoot
newInstance
}
}
A: In your code, there is no obvious reason to make Node and Leaf nested path-dependent classes. Just make them covariant stand-alone classes, then all the problems with path-dependence go away:
trait Node[+A] {
val id: Byte
def put[A1 >: A](ids: Seq[Byte], item: A1): Node[A1]
def remove[A1 >: A](ids: Seq[Byte], item: A1): Node[A1]
}
case class Branch[+A](id: Byte, subs: Vector[Node[A]]) extends Node[A] {
def put[A1 >: A](ids: Seq[Byte], item: A1): Node[A1] = ???
def remove[A1 >: A](ids: Seq[Byte], item: A1): Node[A1] = ???
}
case class Leaf[+A](id: Byte, subs: Vector[A]) extends Node[A] {
def put[A1 >: A](ids: Seq[Byte], item: A1): Node[A1] = ???
def remove[A1 >: A](ids: Seq[Byte], item: A1): Node[A1] = ???
}
class SomeFancyCollection[+A](val root: Node[A] = Branch(0x0, Vector[Node[A]]())) {
def add[A1 >: A](item: A1): SomeFancyCollection[A1] = {
val ids: Seq[Byte] = ???// getIds() // doesn't matter
val newRoot = root.put(ids, item)
new SomeFancyCollection[A1](newRoot)
}
}
If you don't want to pollute the namespace, just declare the Node classes package-private, or even hide all those auxiliary implementation-detail classes inside the companion object of SomeFancyCollection:
class SomeFancyCollection[+A] private[SomeFancyCollection](
val root: SomeFancyCollection.AnnoyingDetails.Node[A]
) {
def add[A1 >: A](item: A1): SomeFancyCollection[A1] = {
val ids: Seq[Byte] = ???// getIds() // doesn't matter
val newRoot = root.put(ids, item)
new SomeFancyCollection[A1](newRoot)
}
}
object SomeFancyCollection {
def empty[A]: SomeFancyCollection[A] = new SomeFancyCollection[A](
AnnoyingDetails.Branch(0x0, Vector[AnnoyingDetails.Node[A]]())
)
private[SomeFancyCollection] object AnnoyingDetails {
trait Node[+A] {
val id: Byte
def put[A1 >: A](ids: Seq[Byte], item: A1): Node[A1]
def remove[A1 >: A](ids: Seq[Byte], item: A1): Node[A1]
}
case class Branch[+A](id: Byte, subs: Vector[Node[A]]) extends Node[A] {
def put[A1 >: A](ids: Seq[Byte], item: A1): Node[A1] = ???
def remove[A1 >: A](ids: Seq[Byte], item: A1): Node[A1] = ???
}
case class Leaf[+A](id: Byte, subs: Vector[A]) extends Node[A] {
def put[A1 >: A](ids: Seq[Byte], item: A1): Node[A1] = ???
def remove[A1 >: A](ids: Seq[Byte], item: A1): Node[A1] = ???
}
}
}
| |
doc_23527598
|
I created two sites in IIS8, Site1 and Site2. I created a single IIS User and I gave permission to access both sites to this user.
I can publish the first site via Web Deploy, but I cannot publish the second site.
When I try to publish the second site, I get this error in Visual Studio
2>Start Web Deploy Publish the Application/package to https://27.147.144.98:8172/msdeploy.axd?site=NSU ...
2>Adding ACL's for path (NSU)
2>C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.targets(4255,5): Error : Web deployment task failed. ((6/30/2015 12:36:37 PM) An error occurred when the request was processed on the remote computer.)
2>
2>(6/30/2015 12:36:37 PM) An error occurred when the request was processed on the remote computer.
2>The server experienced an issue processing the request. Contact the server administrator for more information.
2>Publish failed to deploy.
The first site is published correctly always. The problems occurs only for the second site.
A: I had this error but also had Fiddler2 running which seemed like it was interfering with the deployment. When I closed it, things worked again. Make sure you test the connection beforehand.
| |
doc_23527599
|
I have this model in the edmx
Business Rule:
A Participant can have multiple Roles so I create a relationship table ParticipantRoles that has 1-to-Many relationship on the Participant and the Role table
The Problem:
In order to get the Participant's Role value, I have to drill down through Participant->ParticipantRole->Role (see JSON output below)
The Question:
In EF, how to design the table relationship to bypass the ParticipantsRole table. I want to access the Role in something like this Particant.Role and not Participant.ParticipantsRole.Role
A: You say A Participant can have multiple Roles. And of course, a Role can have multiple Participants. So basically this is a many-to-many association.
Entity Framework will only map pure many-to-many associations (without connecting class) when the junction table only has two foreign keys. In your case, if the table ParticipantsRole only would have had a primary key consisting of ParticipantId and RoleId at the time of generating the model the class ParticipantsRole would not have been created. You would have had Participant.Roles and Role.Participants as navigation properties.
However, the model has been generated with ParticipantsRole and you want to get rid of it. (Or not, I'll get back to that).
This is what you can do:
*
*Remove ParticipantRoles from the class diagram.
*Modify the database table ParticipantRoles so it only has the two FK columns, that both form the primary key.
*Update the model from the database and select ParticipantsRole in the Add tab.
This should give you a model with a pure many-to-many association.
However, think twice before you do this. M2m associations have a way of evolving into 1-m-1association (as you've got now). The reason is that sooner or later the need is felt to record data about the association, so the junction table must have more fields and stops being a pure junction table. In your case I can imagine that one day participant's roles must have a fixed order, or one marked as default. It can be a major overhaul to change a m2m association into 1-m-1 in a production environment. - Something to consider...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.