id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_400
|
UPDATE some_table SET
column_1 = param_1,
column_2 = param_2,
column_3 = param_3,
column_4 = param_4,
column_5 = param_5
WHERE id = some_id;
Where param_x is a parameter of my function. Is there a way to NOT update those columns, for which the param is NULL? For example - if param_4 and param_5 are NULL, then update only the first three columns and leave old values for column_4 and column_5.
The way I am doing it now is:
SELECT * INTO temp_row FROM some_table WHERE id = some_id;
UPDATE some_table SET
column_1 = COALESCE(param_1, temp_row.column_1),
column_2 = COALESCE(param_2, temp_row.column_2),
column_3 = COALESCE(param_3, temp_row.column_3),
column_4 = COALESCE(param_4, temp_row.column_4),
column_5 = COALESCE(param_5, temp_row.column_5)
WHERE id = some_id;
Is there a better way?
A: Additionally, to avoid empty updates:
UPDATE some_table SET
column_1 = COALESCE(param_1, column_1),
column_2 = COALESCE(param_2, column_2)
...
WHERE id = some_id;
AND (param_1 IS DISTINCT FROM column_1 OR
param_2 IS DISTINCT FROM column_2 OR
...
);
This assumes target columns to be defined NOT NULL. Else, see Geir's extended version.
A: Neat trick, thanks Przemek, Frank & Erwin!
I suggest a minor edit to Erwin's answer to avoid empty updates. If any parameters were null (meaning: "use the old value"), the row was updated each time even though the row values did not change (after the first update).
By adding "param_x IS NOT NULL", we avoid empty updates:
UPDATE some_table SET
column_1 = COALESCE(param_1, column_1),
column_2 = COALESCE(param_2, column_2),
...
WHERE id = some_id
AND (param_1 IS NOT NULL AND param_1 IS DISTINCT FROM column_1 OR
param_2 IS NOT NULL AND param_2 IS DISTINCT FROM column_2 OR
...
);
A: Drop the SELECT statement, there is no need for, just use the current value:
UPDATE some_table SET
column_1 = COALESCE(param_1, column_1),
column_2 = COALESCE(param_2, column_2),
column_3 = COALESCE(param_3, column_3),
column_4 = COALESCE(param_4, column_4),
column_5 = COALESCE(param_5, column_5)
WHERE id = some_id;
| |
doc_401
|
2016-01-02 2016-01-02 2016-01-03 2016-01-04 2016-01-05 2016-01-06
2016-02-07 2016-02-11 2016-02-13 2016-02-18 2016-02-23 2016-02-28
2016-03-07 2016-03-16 2016-03-21
All of these folders are inside a folder named Files and when i run: scp -r /Users/$username/Files [email protected]:/var/www/html/backups
The folders with the older file names upload first. (example order: 2016-01-02,2016-01-02,2016-01-03) My goal is to reverse this so the folders upload in the opposite order (example: 2016-03-21,2016-03-16,2016-03-07) Is there any trick to do this? **Preferably using #!/usr/bin/expect -f my for my current script I do not have to type in my password everytime I run the command. Here is what I currently use:
#!/usr/bin/expect -f
set username [exec id -un]
spawn scp -r /Users/$username/Files [email protected]:.
#######################
expect {
-re ".*es.*o.*" {
exp_send "yes\r"
exp_continue
}
-re ".*sword.*" {
exp_send "password\r"
}
}
interact
A: Not sure if scp has this feature but you can do it yourself by adding a small logic to it:
for folder in $(ls -t /Users/$username/Files); do
sshpass -p <password> scp -o StrictHostKeyChecking=no -r /Users/$username/Files/$folder [email protected]:/var/www/html/backups
done
| |
doc_402
|
So Here is my problem:
I have an object of type "attribute" that is supposed to be stored in the table "attribute". The owner of this attribute can either be an object of type "Function" or of type "Block" who both have a table on their own. One attribute-object can only be owned by one object (either function or block), making this a 1:n cardinality.
I am however struggling with how to include the owner in the attribute table. If I create a table named "ownerID" and store the ID of the owner (a globally unique ID btw) in it, the Database is missing the information about which table is containing this ID (even though its a GUID).
-Is it okay for example, to include another column containing the name of the table that the owner_ID belongs to ?
-another idea was to include one "functionOwnerID" column and one "blockOwnerID" and leaving one of them empty, but this seems like a rather dirty solution to me.
I hope my description of the problem was clear, and thanks in advance !
best regards,
Moritz
A: "Is it okay for example, to include another column containing the name of the table that the owner_ID belongs to ?"
That's how polymorphic relationships work! :)
Edit: (yes, you can do that and it's actually pretty common)
References:
*
*(Rails/ActiveRecord Docs): http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
*(Laravel/Eloquent Docs): https://laravel.com/docs/5.4/eloquent-relationships#polymorphic-relations
| |
doc_403
|
The string I have is:
<string name="animal">dog</string>
I want to take out "animal" and "dog" from the string so I need two scripts for each word. I have looked into the available options but could not find a better solution. Any help would be highly appreciated.
A: It looks like XML, so XML parser would be the preferred way of handling it. Which parser to use depends on your specific requirements and environment (maybe you already have nokogiri in your Gemfile?). Here's how to proceed with ox suggested by @roo:
string = '<string name="animal">dog</string>'
parsed = Ox.parse(string)
parsed[:name] #=> "animal"
parsed.text #=> "dog"
If you really want to go with a regex for some reason (not really advisable and really fragile) you can use multiple capturing groups:
regex = /\A<string [^>]*name="([^"]+)"[^>]*>([^<]*)<\/string>\z/
_, name, value = regex.match(str)
name #=> "animal"
value #=> "dog"
Note, that regex is very fragile and will just silently stop working if the xml structure changes.
| |
doc_404
|
I'm able to successfully create the instance and call the TerminateInstancesCommand. However, when I use the waitUntilInstanceTerminated function it immediately throws the following error:
Error: {"result":{"state":"FAILURE","reason":{/* output from DescribeInstancesCommand */}}
at checkExceptions (/node_modules/@aws-sdk/client-ec2/node_modules/@aws-sdk/util-waiter/dist-cjs/waiter.js:34:15)
at waitUntilInstanceTerminated (/node_modules/@aws-sdk/client-ec2/dist-cjs/waiters/waitForInstanceTerminated.js:84:46)
What am I doing wrong?
A: When you run an EC2 instance, it takes some time to start up. Check the instance state either with the AWS Management Console or with the SDK using the DescribeInstancesCommand. You'll see this error if your state is still pending when you try to waitUntilInstanceTerminated.
Try implementing waitUntilInstanceRunning before you try and terminate it.
| |
doc_405
|
//I get string error as input parameter
string error = "Hello World!";
string eventHandlerStr = "onmouseover = 'ShowError(" + "event" + ", \"" + error + "\")'";
// result is "onmouseover = 'ShowError(event, \"Hello World!"\)'"
How to get result without \ around "Hello World!"? And I need quotes arround Hello World!
If I do this:
string eventHandlerStr = "onmouseover = 'ShowError(" + "event" + ", " + error + ")'";
I get Hello World! without quotes.
I tried even removing \ character with String.Remove method but \ stayed there after removing.
A: Try verbatim string -> @
Here you are everything you need:
https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
UPDATE 2018/06/07
New documentation from MS:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim (second point)
Cache from WebArchive for original link: https://web.archive.org/web/20170730011023/https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
A: Can you try this?
string format = @"onmouseover = 'ShowError(event, ""{0}"")'";
string error = "HelloWorld";
string pqr = string.Format(format, error);
| |
doc_406
|
If I write:
import functools32
@functools32.lru_cache()
def square(x):
print "Squaring", x
return x*x
I get this behavior:
>>> square(10)
Squaring 10
100
>>> square(10)
100
>>> runfile(...)
>>> square(10)
Squaring 10
100
That is, rerunning the file clears the cache. This works:
try:
safe_square
except NameError:
@functools32.lru_cache()
def safe_square(x):
print "Squaring", x
return x*x
but when the function is long it feels strange to have its definition inside a try block. I can do this instead:
def _square(x):
print "Squaring", x
return x*x
try:
safe_square_2
except NameError:
safe_square_2 = functools32.lru_cache()(_square)
but it feels pretty contrived (for example, in calling the decorator without an '@' sign)
Is there a simple way to handle this, something like:
@non_resetting_lru_cache()
def square(x):
print "Squaring", x
return x*x
?
A: Writing a script to be executed repeatedly in the same session is an odd thing to do.
I can see why you'd want to do it, but it's still odd, and I don't think it's unreasonable for the code to expose that oddness by looking a little odd, and having a comment explaining it.
However, you've made things uglier than necessary.
First, you can just do this:
@functools32.lru_cache()
def _square(x):
print "Squaring", x
return x*x
try:
safe_square_2
except NameError:
safe_square_2 = _square
There is no harm in attaching a cache to the new _square definition. It won't waste any time, or more than a few bytes of storage, and, most importantly, it won't affect the cache on the previous _square definition. That's the whole point of closures.
There is a potential problem here with recursive functions. It's already inherent in the way you're working, and the cache doesn't add to it in any way, but you might only notice it because of the cache, so I'll explain it and show how to fix it. Consider this function:
@lru_cache()
def _fact(n):
if n < 2:
return 1
return _fact(n-1) * n
When you re-exec the script, even if you have a reference to the old _fact, it's going to end up calling the new _fact, because it's accessing _fact as a global name. It has nothing to do with the @lru_cache; remove that, and the old function will still end up calling the new _fact.
But if you're using the renaming trick above, you can just call the renamed version:
@lru_cache()
def _fact(n):
if n < 2:
return 1
return fact(n-1) * n
Now the old _fact will call fact, which is still the old _fact. Again, this works identically with or without the cache decorator.
Beyond that initial trick, you can factor that whole pattern out into a simple decorator. I'll explain step by step below, or see this blog post.
Anyway, even with the less-ugly version, it's still a bit ugly and verbose. And if you're doing this dozens of times, my "well, it should look a bit ugly" justification will wear thin pretty fast. So, you'll want to handle this the same way you always factor out ugliness: wrap it in a function.
You can't really pass names around as objects in Python. And you don't want to use a hideous frame hack just to deal with this. So you'll have to pass the names around as strings. ike this:
globals().setdefault('fact', _fact)
The globals function just returns the current scope's global dictionary. Which is a dict, which means it has the setdefault method, which means this will set the global name fact to the value _fact if it didn't already have a value, but do nothing if it did. Which is exactly what you wanted. (You could also use setattr on the current module, but I think this way emphasizes that the script is meant to be (repeatedly) executed in someone else's scope, not used as a module.)
So, here that is wrapped up in a function:
def new_bind(name, value):
globals().setdefault(name, value)
… which you can turn that into a decorator almost trivially:
def new_bind(name):
def wrap(func):
globals().setdefault(name, func)
return func
return wrap
Which you can use like this:
@new_bind('foo')
def _foo():
print(1)
But wait, there's more! The func that new_bind gets is going to have a __name__, right? If you stick to a naming convention, like that the "private" name must be the "public" name with a _ prefixed, we can do this:
def new_bind(func):
assert func.__name__[0] == '_'
globals().setdefault(func.__name__[1:], func)
return func
And you can see where this is going:
@new_bind
@lru_cache()
def _square(x):
print "Squaring", x
return x*x
There is one minor problem: if you use any other decorators that don't wrap the function properly, they will break your naming convention. So… just don't do that. :)
And I think this works exactly the way you want in every edge case. In particular, if you've edited the source and want to force the new definition with a new cache, you just del square before rerunning the file, and it works.
And of course if you want to merge those two decorators into one, it's trivial to do so, and call it non_resetting_lru_cache.
However, I'd keep them separate. I think it's more obvious what they do. And if you ever want to wrap another decorator around @lru_cache, you're probably still going to want @new_bind to be the outermost decorator, right?
What if you want to put new_bind into a module that you can import? Then it's not going to work, because it will be referring to the globals of that module, not the one you're currently writing.
You can fix that by explicitly passing your globals dict, or your module object, or your module name as an argument, like @new_bind(__name__), so it can find your globals instead of its. But that's ugly and repetitive.
You can also fix it with an ugly frame hack. At least in CPython, sys._getframe() can be used to get your caller's frame, and frame objects have a reference to their globals namespace, so:
def new_bind(func):
assert func.__name__[0] == '_'
g = sys._getframe(1).f_globals
g.setdefault(func.__name__[1:], func)
return func
Notice the big box in the docs that tells you this is an "implementation detail" that may only apply to CPython and is "for internal and specialized purposes only". Take this seriously. Whenever someone has a cool idea for the stdlib or builtins that could be implemented in pure Python, but only by using _getframe, it's generally treated almost the same as an idea that can't be implemented in pure Python at all. But if you know what you're doing, and you want to use this, and you only care about present-day versions of CPython, it will work.
A: There is no persistent_lru_cache in the stdlib. But you can build one pretty easily.
The functools source is linked directly from the docs, because this is one of those modules that's as useful as sample code as it is for using it directly.
As you can see, the cache is just a dict. If you replace that with, say, a shelf, it will become persistent automatically:
def persistent_lru_cache(filename, maxsize=128, typed=False):
"""new docstring explaining what dbpath does"""
# same code as before up to here
def decorating_function(user_function):
cache = shelve.open(filename)
# same code as before from here on.
Of course that only works if your arguments are strings. And it could be a little slow.
So, you might want to instead keep it as an in-memory dict, and just write code that pickles it to a file atexit, and restores it from a file if present at startup:
def decorating_function(user_function):
# ...
try:
with open(filename, 'rb') as f:
cache = pickle.load(f)
except:
cache = {}
def cache_save():
with lock:
with open(filename, 'wb') as f:
pickle.dump(cache, f)
atexit.register(cache_save)
# …
wrapper.cache_save = cache_save
wrapper.cache_filename = filename
Or, if you want it to write every N new values (so you don't lose the whole cache on, say, an _exit or a segfault or someone pulling the cord), add this to the second and third versions of wrapper, right after the misses += 1:
if misses % N == 0:
cache_save()
See here for a working version of everything up to this point (using save_every as the "N" argument, and defaulting to 1, which you probably don't want in real life).
If you want to be really clever, maybe copy the cache and save that in a background thread.
You might want to extend the cache_info to include something like number of cache writes, number of misses since last cache write, number of entries in the cache at startup, …
And there are probably other ways to improve this.
From a quick test, with save_every=1, this makes the cache on both get_pep and fib (from the functools docs) persistent, with no measurable slowdown to get_pep and a very small slowdown to fib the first time (note that fib(100) has 100097 hits vs. 101 misses…), and of course a large speedup to get_pep (but not fib) when you re-run it. So, just what you'd expect.
A: I can't say I won't just use @abarnert's "ugly frame hack", but here is the version that requires you to pass in the calling module's globals dict. I think it's worth posting given that decorator functions with arguments are tricky and meaningfully different from those without arguments.
def create_if_not_exists_2(my_globals):
def wrap(func):
if "_" != func.__name__[0]:
raise Exception("Function names used in cine must begin with'_'")
my_globals.setdefault(func.__name__[1:], func)
def wrapped(*args):
func(*args)
return wrapped
return wrap
Which you can then use in a different module like this:
from functools32 import lru_cache
from cine import create_if_not_exists_2
@create_if_not_exists_2(globals())
@lru_cache()
def _square(x):
print "Squaring", x
return x*x
assert "_square" in globals()
assert "square" in globals()
A: I've gained enough familiarity with decorators during this process that I was comfortable taking a swing at solving the problem another way:
from functools32 import lru_cache
try:
my_cine
except NameError:
class my_cine(object):
_reg_funcs = {}
@classmethod
def func_key (cls, f):
try:
name = f.func_name
except AttributeError:
name = f.__name__
return (f.__module__, name)
def __init__(self, f):
k = self.func_key(f)
self._f = self._reg_funcs.setdefault(k, f)
def __call__(self, *args, **kwargs):
return self._f(*args, **kwargs)
if __name__ == "__main__":
@my_cine
@lru_cache()
def fact_my_cine(n):
print "In fact_my_cine for", n
if n < 2:
return 1
return fact_my_cine(n-1) * n
x = fact_my_cine(10)
print "The answer is", x
@abarnert, if you are still watching, I'd be curious to hear your assessment of the downsides of this method. I know of two:
*
*You have to know in advance what attributes to look in for a name to associate with the function. My first stab at it only looked at func_name which failed when passed an lru_cache object.
*Resetting a function is painful: del my_cine._reg_funcs[('__main__', 'fact_my_cine')], and the swing I took at adding a __delitem__ was unsuccessful.
| |
doc_407
|
I have done up to getting the data of excel sheet in to data table
but i am not able to upload the images of the path mentioned in the Excel to server
Please help me
Manoj
| |
doc_408
|
When i save two employee objects with the same value i.e. "111", I expect to save only one value in the database. However, i end up saving 2 employee records.
The entity code is as below
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "employee_id")
private Long employeeId;
@Column(name = "employeehexa_id")
private String _id;
@Override
public int hashCode() {
HashCodeBuilder hcb = new HashCodeBuilder();
hcb.append(_id);
return hcb.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Employee)) {
return false;
}
Employee that = (Employee) obj;
EqualsBuilder eb = new EqualsBuilder();
eb.append(_id, that._id);
return eb.isEquals();
}
// Required Constructors, getters, setters not shown for brevity
}
And the below is my call to save two object with same _id
@Autowired
private EmployeeRepo employeeRepo;
@RequestMapping("/test")
String Test() throws Exception {
Employee e1 = new Employee("111");
Employee e2 = new Employee("111");
System.out.println(e1.equals(e2)); // prints true, implying hashcode and equals working fine
employeeRepo.save(e1);
employeeRepo.save(e2);//Both e1 and e2 are saved inspite of being equal
return "Completed !";
}
The equality check seems to work fine. Is there something about save() of spring JpaRepository that causes this or is my understanding of how equality/hashcode contract is enforced incorrect ?
I thought i understood equality/hashcode but looks like that is not the case. Any help appreciated. Thx.
A: According to this answer, https://stackoverflow.com/a/11881628/5695673, you probably have 2 records because your fields employeeId are differents for your entities, so for spring-data the two entities are differents.
To test if your equals()/hashCode() works as expected, you can try to put your entities in a collection which check object equality (i.e. a Set) and try to save all the set in one time.
Example:
Set<Employee> employees = new HashSet<Employee>();
employees.add( new Employee("111"));
employees.add( new Employee("111"));
System.out.println(employees.size()); //1
employeeRepo.save(employees); // 1 record
More information here: https://developer.jboss.org/wiki/EqualsandHashCode?_sscc=t
| |
doc_409
|
Here an example:
THE FORM:
<HTML>
<HEAD>
<TITLE>Database Lookup</TITLE>
<script src="basic.js"></script></HEAD>
<BODY>
<H1>Database Lookup</H1>
<FORM action="javascript: submitForm();">
Please enter the ID of the publisher you want to find: <BR>
<INPUT TYPE="TEXT" NAME="id">
<BR>
<INPUT TYPE="SUBMIT" value="Submit" > </FORM>
</BODY>
<HTML>
//HERE JAVASCRIPT Javascript BASIC.js:
function submitForm()
{
var idsearched=document.getElementById("id").innerHTML;
document.write("idsearched");
}
I would like to know what i'm doing wrong, because nothing happen when i click submit. And which is the better solution for handling forms with javascript?? Using "action"? or which of other attributes?
A: <INPUT TYPE="button" value="Submit" onclick="submitForm();" >
do not use document.write use document.getElementById("myID").innerHTML
A: The value of form elements are contained in their value attribute. Try the modified code snippet below.
Note: ("idsearched") should be without quote because it is a variable and not a string.
var idsearched=document.getElementById("id").value;
document.write(idsearched);
You must add an id attribute to the form element.
<INPUT TYPE="TEXT" NAME="id" id="id">
Use this line to manually submit your form
<INPUT TYPE="button" value="Submit" onclick="submitForm();" >
A: a full working example like you wanted is that:
<HTML>
<HEAD>
<TITLE>Database Lookup</TITLE>
<script src="basic.js"></script>
</HEAD>
<BODY>
<H1>Database Lookup</H1>
<FORM action="javascript: submitForm();">
Please enter the ID of the publisher you want to find: <BR>
<INPUT TYPE="TEXT" id="id" NAME="id">
<BR>
<INPUT TYPE="SUBMIT" value="Submit" >
</FORM>
<script type="text/javascript">
function submitForm()
{
var idsearched=document.getElementById("id").innerHTML;
document.write("idsearched");
return false;
}
</script>
</BODY>
<HTML>
| |
doc_410
|
Here is my command
java -cp C:\Users\Admin\Downloads\daily-installer-automation-master\
daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\lib\*;C:\Users\Admin\
Downloads\daily-installer-automation-master\
daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\src\test\resources org.testng.TestNG C:\Users\Admin\Downloads\daily-installer-automation-master\
daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\src\test\resources\CreateUsers.xml
pause
This is what I am getting after execution
C:\Users\Admin\Desktop>java -cp C:\Users\Admin\Downloads\daily-installer-automation-master\daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\lib\*;C:\Users\Admin\Downloads\daily-installer-automation-master\daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\src\test\resources org.testng.TestNG C:\Users\Admin\Downloads\daily-installer-automation-master\daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\src\test\resources\CreateUsers.xml
[TestNG] Running:
C:\Users\Admin\Downloads\daily-installer-automation-master\daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\src\test\resources\CreateUsers.xml
===============================================
Pre-requisite test
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 1
===============================================
C:\Users\Admin\Desktop>pause
Press any key to continue . . .
Here is my XML
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Pre-requisite test" verbose="1" configfailurepolicy="continue">
<!-- yellowfin login credentials -->
<parameter name="yellowfinURL" value="http://10.10.5.77:8082/" />
<parameter name="userName" value="admin" />
<parameter name="passsword" value="test" />
<test name="CreateUsers">
<classes>
<class name="yellow.bi.test.CreateUsers">
<methods>
<include name="ImportUsers"></include>
<!-- <include name=""></include> -->
</methods>
</class>
</classes>
</test>
</suite>
Here is the extended logs
C:\Users\Admin\Desktop>java -cp C:\Users\Admin\Downloads\daily-installer-automation-master\daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\lib\*;C:\Users\Admin\Downloads\daily-installer-automation-master\daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\src\test\resources org.testng.TestNG -log 10 C:\Users\Admin\Downloads\daily-installer-automation-master\daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\src\test\resources\CreateUsers.xml
[TestRunner] Running the tests in 'CreateUsers' with parallel mode:none
[RunInfo] Adding method selector: org.testng.internal.XmlMethodSelector@527740a2 priority: 10
[TestClass] Creating TestClass for [ClassImpl class=yellowfin.bi.test.CreateUsers]
[TestClass] Adding method CreateUsers.ImportUsers(java.lang.String, java.lang.String)[pri:1, instance:null] on TestClass class yellowfin.bi.test.CreateUsers
[XmlMethodSelector] Including method yellowfin.bi.test.setUpTheTest()
[XmlMethodSelector] Including method yellowfin.bi.test.instantiatePages()
[XmlMethodSelector] Including method yellowfin.bi.test.ImportUsers()
[TestNG] Running:
C:\Users\Admin\Downloads\daily-installer-automation-master\daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\src\test\resources\CreateUsers.xml
[Invoker 513169028] Keeping method CreateUsers.setUpTheTest()[pri:0, instance:yellowfin.bi.test.CreateUsers@614ddd49] for class null
[Invoker 513169028] Invoking @BeforeSuite CreateUsers.setUpTheTest()[pri:0, instance:yellowfin.bi.test.CreateUsers@614ddd49]
[TestNG] INVOKING CONFIGURATION: "UNKNOWN" - @BeforeSuite yellowfin.bi.test.CreateUsers.setUpTheTest()
Failed to invoke configuration method yellowfin.bi.test.CreateUsers.setUpTheTest:com.google.common.base.Preconditions.checkState(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V
[TestNG] FAILED CONFIGURATION: "UNKNOWN" - @BeforeSuite yellowfin.bi.test.CreateUsers.setUpTheTest() finished in 0 ms
[TestNG] java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkState(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V
[TestNG] at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
[TestNG] at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
[TestNG] at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
[TestNG] at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:339)
[TestNG] at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
[TestNG] at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
[TestNG] at yellowfin.bi.test.CreateUsers.setUpTheTest(CreateUsers.java:52)
[TestNG] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[TestNG] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
[TestNG] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
[TestNG] at java.lang.reflect.Method.invoke(Unknown Source)
[TestNG] at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
[TestNG] at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:515)
[TestNG] at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:217)
[TestNG] at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:144)
[TestNG] at org.testng.SuiteRunner.privateRun(SuiteRunner.java:326)
[TestNG] at org.testng.SuiteRunner.run(SuiteRunner.java:289)
[TestNG] at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
[TestNG] at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
[TestNG] at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
[TestNG] at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
[TestNG] at org.testng.TestNG.runSuites(TestNG.java:1133)
[TestNG] at org.testng.TestNG.run(TestNG.java:1104)
[TestNG] at org.testng.TestNG.privateMain(TestNG.java:1434)
[TestNG] at org.testng.TestNG.main(TestNG.java:1403)
[SuiteRunner] Created 1 TestRunners
[TestRunner] Running test CreateUsers on 1 classes, included groups:[] excluded groups:[]
===== Test class
yellowfin.bi.test.CreateUsers
@Test CreateUsers.ImportUsers(java.lang.String, java.lang.String)[pri:1, instance:yellowfin.bi.test.CreateUsers@614ddd49]
======
[TestNG] RUNNING: Suite: "CreateUsers" containing "1" Tests (config: C:\Users\Admin\Downloads\daily-installer-automation-master\daily-installer-automation-master-e26d3512b5f2770b8388270ffcc3078e32571d9a\src\test\resources\CreateUsers.xml)
[Invoker 513169028] Keeping method CreateUsers.instantiatePages(java.lang.String)[pri:0, instance:yellowfin.bi.test.CreateUsers@614ddd49] for class null
[TestNG] SKIPPED CONFIGURATION: "CreateUsers" - @BeforeTest yellowfin.bi.test.CreateUsers.instantiatePages(java.lang.String) finished in 0 ms
[Invoker 513169028] No configuration methods found
[Invoker 513169028] No configuration methods found
[TestNG] SKIPPED: "CreateUsers" - yellowfin.bi.test.CreateUsers.ImportUsers(java.lang.String, java.lang.String)(value(s): "admin", "test") finished in 0 ms
[TestNG] java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkState(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V
[TestNG] at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
[TestNG] at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
[TestNG] at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
[TestNG] at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:339)
[TestNG] at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
[TestNG] at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
[TestNG] at yellowfin.bi.test.CreateUsers.setUpTheTest(CreateUsers.java:52)
[TestNG] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[TestNG] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
[TestNG] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
[TestNG] at java.lang.reflect.Method.invoke(Unknown Source)
[TestNG] at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
[TestNG] at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:515)
[TestNG] at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:217)
[TestNG] at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:144)
[TestNG] at org.testng.SuiteRunner.privateRun(SuiteRunner.java:326)
[TestNG] at org.testng.SuiteRunner.run(SuiteRunner.java:289)
[TestNG] at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
[TestNG] at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
[TestNG] at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
[TestNG] at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
[TestNG] at org.testng.TestNG.runSuites(TestNG.java:1133)
[TestNG] at org.testng.TestNG.run(TestNG.java:1104)
[TestNG] at org.testng.TestNG.privateMain(TestNG.java:1434)
[TestNG] at org.testng.TestNG.main(TestNG.java:1403)
[Invoker 513169028] No configuration methods found
[Invoker 513169028] No configuration methods found
===== Invoked methods
CreateUsers.setUpTheTest()[pri:0, instance:yellowfin.bi.test.CreateUsers@614ddd49] 1632492873
CreateUsers.ImportUsers(java.lang.String, java.lang.String)[pri:1, instance:yellowfin.bi.test.CreateUsers@614ddd49]admin test 1632492873
=====
[[Utils]] Attempting to create C:\Users\Admin\Desktop\test-output\Pre-requisite test\CreateUsers.xml
[[Utils]] Directory C:\Users\Admin\Desktop\test-output\Pre-requisite test exists: true
Creating C:\Users\Admin\Desktop\test-output\Pre-requisite test\CreateUsers.xml
FAILED CONFIGURATION: @BeforeSuite setUpTheTest
java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkState(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:339)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
at yellowfin.bi.test.CreateUsers.setUpTheTest(CreateUsers.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:515)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:217)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:144)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:326)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
at org.testng.TestNG.runSuites(TestNG.java:1133)
at org.testng.TestNG.run(TestNG.java:1104)
at org.testng.TestNG.privateMain(TestNG.java:1434)
at org.testng.TestNG.main(TestNG.java:1403)
SKIPPED CONFIGURATION: @BeforeTest instantiatePages
SKIPPED: ImportUsers("admin", "test")
java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkState(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:339)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
at yellowfin.bi.test.CreateUsers.setUpTheTest(CreateUsers.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:515)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:217)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:144)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:326)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
at org.testng.TestNG.runSuites(TestNG.java:1133)
at org.testng.TestNG.run(TestNG.java:1104)
at org.testng.TestNG.privateMain(TestNG.java:1434)
at org.testng.TestNG.main(TestNG.java:1403)
===============================================
CreateUsers
Tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 1
===============================================
[TestNG]
[TestNG] ===============================================
[TestNG] CreateUsers
[TestNG] Tests run: 1, Failures: 0, Skips: 1
[TestNG] Configuration Failures: 1, Skips: 1
[TestNG] ===============================================
===============================================
Pre-requisite test
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 1
===============================================
[TestNG] Time taken by org.testng.reporters.jq.Main@b7f23d9: 33 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@6591f517: 5 ms
[[Utils]] Attempting to create test-output\testng-failed.xml
[[Utils]] Directory test-output exists: true
Creating C:\Users\Admin\Desktop\test-output\testng-failed.xml
[[Utils]] Attempting to create C:\Users\Admin\Desktop\test-output\Pre-requisite test\testng-failed.xml
[[Utils]] Directory C:\Users\Admin\Desktop\test-output\Pre-requisite test exists: true
Creating C:\Users\Admin\Desktop\test-output\Pre-requisite test\testng-failed.xml
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 5 ms
[[Utils]] Attempting to create C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\toc.html
[[Utils]] Directory C:\Users\Admin\Desktop\test-output\old\Pre-requisite test exists: true
Creating C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\toc.html
[[Utils]] Attempting to create C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\CreateUsers.properties
[[Utils]] Directory C:\Users\Admin\Desktop\test-output\old\Pre-requisite test exists: true
Creating C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\CreateUsers.properties
[[Utils]] Attempting to create C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\index.html
[[Utils]] Directory C:\Users\Admin\Desktop\test-output\old\Pre-requisite test exists: true
Creating C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\index.html
[[Utils]] Attempting to create C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\main.html
[[Utils]] Directory C:\Users\Admin\Desktop\test-output\old\Pre-requisite test exists: true
Creating C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\main.html
[[Utils]] Attempting to create C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\groups.html
[[Utils]] Directory C:\Users\Admin\Desktop\test-output\old\Pre-requisite test exists: true
Creating C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\groups.html
[[Utils]] Attempting to create C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\classes.html
[[Utils]] Directory C:\Users\Admin\Desktop\test-output\old\Pre-requisite test exists: true
Creating C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\classes.html
[[Utils]] Attempting to create C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\reporter-output.html
[[Utils]] Directory C:\Users\Admin\Desktop\test-output\old\Pre-requisite test exists: true
Creating C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\reporter-output.html
[[Utils]] Attempting to create C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\methods-not-run.html
[[Utils]] Directory C:\Users\Admin\Desktop\test-output\old\Pre-requisite test exists: true
Creating C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\methods-not-run.html
[[Utils]] Attempting to create C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\testng.xml.html
[[Utils]] Directory C:\Users\Admin\Desktop\test-output\old\Pre-requisite test exists: true
Creating C:\Users\Admin\Desktop\test-output\old\Pre-requisite test\testng.xml.html
[[Utils]] Attempting to create test-output\old\index.html
[[Utils]] Directory test-output\old exists: true
Creating C:\Users\Admin\Desktop\test-output\old\index.html
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@279ad2e3: 37 ms
[[Utils]] Attempting to create test-output\junitreports\TEST-yellowfin.bi.test.CreateUsers.xml
[[Utils]] Directory test-output\junitreports exists: true
Creating C:\Users\Admin\Desktop\test-output\junitreports\TEST-yellowfin.bi.test.CreateUsers.xml
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@4461c7e3: 5 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@1b68b9a4: 7 ms
C:\Users\Admin\Desktop>pause
Press any key to continue . . .
A: You have a problem with your CLASSPATH.
Please take a closer look at the error
[TestNG] java.lang.NoClassDefFoundError:yellowfin/bi/utils/BrowserFactory
Instead of resorting to using java -cp to run TestNG tests, I would strongly recommend that you make use of a build tool such as Ant/Maven/Gradle/Kobalt/Buck for compilation, running tests, managing classpath etc., and then use the build tool to run your tests.
There's nothing wrong with TestNG here. Please fix your java -cp command to include the folder to the jar that contains this class and try again.
| |
doc_411
|
<meta http-equiv="X-UA-Compatible" content="IE=8">
But, as I mentioned, I have no access to that part of the page, so I'm hoping that I can use Javascript... sort of like this:
document.getElementsByTagName('head')[0].appendChild('<meta http-equiv="X-UA-Compatible" content="IE=IEVersion">');
Sadly, this doesn't work.
A: That's a bit of a pickle you're in. What about this?
if (navigator.userAgent.indexOf("MSIE 7.0")) {
// add conditional css in here
} else {
// default css
}
| |
doc_412
|
A: When you download your file you can use path_provider plugin to access device storage and save your file there.
I would recommend the Document directory which can be accessed using getApplicationDocumentsDirectory() to save your file.
Here is the idea of doing it.
String directory = (await getApplicationDocumentsDirectory()).path;
File file = File('$directory/your_file_name');
http.Response response = await http.get(your_url_here);
file.writeAsBytes(response.bodyBytes)
| |
doc_413
|
Python does provide a mechanism for picking up only the desired versions. So I have been trying to keep multiple python package versions in one place. That means packages need to be wrapped up like this to load the right versions:
python3
__requires__ = ['scipy <1.3.0,>=1.2.0', 'anndata <0.6.20', 'loompy <3.0.0,>=2.00', 'h5py <2.10', ]
import pkg_resources
import scipy
print(scipy.__version__)
import anndata
print(anndata.__version__)
import loompy
print(loompy.__version__)
import h5py
print(h5py.__version__)
import scanpy
print(scanpy.__version__)
quit()
#emits
python3
Python 3.6.8 (default, Nov 21 2019, 19:31:34)
[GCC 8.3.1 20190507 (Red Hat 8.3.1-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> __requires__ = ['scipy <1.3.0,>=1.2.0', 'anndata <0.6.20', 'loompy <3.0.0,>=2.00', 'h5py <2.10']
>>> import pkg_resources
>>> import scipy
>>> print(scipy.__version__)
1.2.3
>>> import anndata
/home/common/lib/python3.6/site-packages/anndata-0.6.19-py3.6.egg/anndata/base.py:17: FutureWarning: pandas.core.index is deprecated and will be removed in a future version. The public classes are available in the top-level namespace.
from pandas.core.index import RangeIndex
>>> print(anndata.__version__)
0.6.19
>>> import loompy
>>> print(loompy.__version__)
2.0.17
>>> import h5py
>>> print(h5py.__version__)
2.9.0
>>> import scanpy
>>> print(scanpy.__version__)
1.4.3
So far so good. However if the requires line is changed to:
__requires__ = ['scipy <1.3.0,>=1.2.0', 'anndata <0.6.20', 'loompy <3.0.0,>=2.00', 'h5py <2.10', 'scanpy <1.4.4,>=1.4.2']
then it all completely falls apart. The start of the run becomes instead:
python3
Python 3.6.8 (default, Nov 21 2019, 19:31:34)
[GCC 8.3.1 20190507 (Red Hat 8.3.1-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> __requires__ = ['scipy <1.3.0,>=1.2.0', 'anndata <0.6.20', 'loompy <3.0.0,>=2.00', 'h5py <2.10', 'scanpy <1.4.4,>=1.4.2']
>>> import pkg_resources
Traceback (most recent call last):
File "/usr/common/lib/python3.6/site-packages/pkg_resources/__init__.py", line 584, in _build_master
ws.require(__requires__)
File "/usr/common/lib/python3.6/site-packages/pkg_resources/__init__.py", line 901, in require
needed = self.resolve(parse_requirements(requirements))
File "/usr/common/lib/python3.6/site-packages/pkg_resources/__init__.py", line 792, in resolve
raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.VersionConflict: (scanpy 1.5.1 (/home/common/lib/python3.6/site-packages), Requirement.parse('scanpy<1.4.4,>=1.4.2'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/common/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3261, in <module>
@_call_aside
File "/usr/common/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3245, in _call_aside
f(*args, **kwargs)
File "/usr/common/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3274, in _initialize_master_working_set
working_set = WorkingSet._build_master()
File "/usr/common/lib/python3.6/site-packages/pkg_resources/__init__.py", line 586, in _build_master
return cls._build_from_requirements(__requires__)
File "/usr/common/lib/python3.6/site-packages/pkg_resources/__init__.py", line 599, in _build_from_requirements
dists = ws.resolve(reqs, Environment())
File "/usr/common/lib/python3.6/site-packages/pkg_resources/__init__.py", line 792, in resolve
raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.ContextualVersionConflict: (scipy 1.2.3 (/home/common/lib/python3.6/site-packages/scipy-1.2.3-py3.6-linux-x86_64.egg), Requirement.parse('scipy>=1.3.1'), {'umap-learn'})
>>> import scipy
>>> print(scipy.__version__)
1.4.1
# and numerous other issues
This is very strange because when no limitation was set for scanpy the desired version loaded, but when one was set it choked on 1.5.1.
Why does the extra constraint break everything???
Versions of these packages which are present are
anndata
anndata-0.6.19.dist-info
anndata-0.6.19-py3.6.egg
anndata-0.7.1.dist-info
anndata-0.7.3.dist-info
scipy
scipy-1.2.3.dist-info
scipy-1.2.3-py3.6-linux-x86_64.egg
scipy-1.4.1.dist-info
loompy
loompy-2.0.17.dist-info
loompy-2.0.17-py3.6.egg
loompy-3.0.6.dist-info
h5py
h5py-2.10.0.dist-info
h5py-2.9.0.dist-info
h5py-2.9.0-py3.6-linux-x86_64.egg
scanpy
scanpy-1.4.3.dist-info
scanpy-1.4.3-py3.6.egg
scanpy-1.4.6.dist-info
scanpy-1.5.1.dist-info
scanpy-1.5.2.dev7+ge33a2f33-py3.6.egg
This is actually on CentOS, not Red Hat, but that is probably irrelevant.
Thanks.
| |
doc_414
|
I search solutions but not found something that can help me.
I am using Excel 2016.
My code:
Function CryptoQuote(enteredDate As String)
If IsDate(enteredDate) Then
enteredDate = Format(Date, "yyyy-mm-dd")
Dim strURL As String: strURL = "http://www.x-rates.com/historical/?from=USD&amount=1&date=" & enteredDate
MsgBox strURL
Dim http As Object: Set http = CreateObject("msxml2.xmlhttp")
http.Open "GET", strURL, False
http.Send
Dim strCSV As String
Found = InStr(http.responseText, "/graph/?from=USD&to=ILS") 'find this in the HTML
If Found <> 0 Then
Length = Len(http.responseText) - Found 'check the length of the HTML
strCSV = Right(http.responseText, Length) 'Trim the begining of the String until we get to our value
strCSV = Left(strCSV, Len(strCSV) - (Len(strCSV) - 36)) 'Trim the end of the string to leave only the value we are looking for
strCSV = Replace(strCSV, "graph/?from=USD&to=ILS'>", "") 'replace the original search string with nothing so we are left with numbers only
Else
CryptoQuote = "Could not find the data!"
End If
Else
MsgBox "Please enter a correct date as yyyy-mm-dd"
End If
CryptoQuote = Val(strCSV)
MsgBox strCSV
End Function
A: If what you want is USD to EUR then this will do the job (not the most elegant way of doing things but it will do the task at hand):
Public Sub CryptoQuote()
enteredDate = InputBox("Please enter the search date: ", "Enter Date")
If IsDate(enteredDate) Then
enteredDate = Format(enteredDate, "yyyy-mm-dd")
Dim strURL As String: strURL = "http://www.x-rates.com/historical/?from=USD&amount=1&date=" & enteredDate
Dim http As Object: Set http = CreateObject("msxml2.xmlhttp")
http.Open "GET", strURL, False
http.send
Dim strCSV As String
Found = InStr(http.responsetext, "/graph/?from=USD&to=EUR") 'find this in the HTML
If Found <> 0 Then
Length = Len(http.responsetext) - Found 'check the length of the HTML
strCSV = Right(http.responsetext, Length) 'Trim the begining of the String until we get to our value
strCSV = Left(strCSV, Len(strCSV) - (Len(strCSV) - 36)) 'Trim the end of the string to leave only the value we are looking for
strCSV = Replace(strCSV, "graph/?from=USD&to=EUR'>", "") 'replace the original search string with nothing so we are left with numbers only
Else
MsgBox "Could not find the data!"
End If
Else
MsgBox "Please enter a correct date as yyyy-mm-dd"
End If
MsgBox "The rate for 1 USD in EURO is " & strCSV
End Sub
A: Is this what you want?
Sub gethtmltable()
Dim objWeb As QueryTable
Dim sWebTable As String
'You have to count down the tables on the URL listed in your query
'This example shows how to retrieve the 2nd table from the web page.
sWebTable = 2
'Sets the url to run the query and the destination in the excel file
'You can change both to suit your needs
LValue = Format(Date, "yyyy-mm-dd")
Set objWeb = ActiveSheet.QueryTables.Add( _
Connection:="URL;http://www.x-rates.com/historical/?from=USD&amount=1&date=" & LValue, _
Destination:=Range("A1"))
With objWeb
.WebSelectionType = xlSpecifiedTables
.WebTables = sWebTable
.Refresh BackgroundQuery:=False
.SaveData = True
End With
Set objWeb = Nothing
End Sub
A: They changed to HTTPS, so make sure that you use https://www.x-rates.com over http://www.x-rates.com. The rest works fine without changes.
A: ~~~
Sub UpdateFX()
Dim XML_Object As Object
Dim HTMLResponse As String
Dim ECB_FX_URL As String
Dim FXstring As String, i As Integer, j As Integer
Dim USDVal As Variant, GBPVal As Variant, CADVal As Variant
Dim FXDate As Variant, PrevDate As Variant
Dim FxTable()
Dim MidSt As Integer, MidLen As Integer
Dim MnthEnd As Boolean
Dim FirstRptDate As Date, CurRptDate As Date
Dim DateLoops As Integer
' Modified by ANY1, Feb. 17, 2021
' To run properly, MSXML needs to be referenced in Excel
' To do this, complete the following steps:
' 1. Open Visual Basic Editor (VBE) from Excel
' 2. Select Tool - References
' 3. Scroll through the list of available references and select the latest version of Microsoft XML, v 6.0 (latest as of Feb. 17, 2021)
' 4. You should also select (a) Microsoft Office 16.0 Object Library and (b) Microsoft Internet Controls
' You may also want to select Microsoft HTML Object Library, but this is not strictly required for this code to run
' The URL accesses an XML download of the ECB's daily FX Quotes back to 1999
ECB_FX_URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml?affd3fe4c0ac916ce2e9d1ccfea2327c"
Application.ScreenUpdating = False
'Extract data from website to Excel using VBA
Application.StatusBar = "Downloading XML string from ECB"
Set XML_Object = CreateObject("MSXML2.ServerXMLHTTP")
XML_Object.Open "GET", ECB_FX_URL, False
XML_Object.send
HTMLResponse = XML_Object.responseText
' Find the first and last dates in the XML string
MidSt = InStr(HTMLResponse, "Cube time=") + 11
MidLen = InStr(MidSt, HTMLResponse, Chr(34)) - MidSt
FXstring = Mid(HTMLResponse, MidSt, MidLen)
CurRptDate = Mid(HTMLResponse, MidSt, MidLen)
' Calculate the maximum number of business days between the first and last report dates, ignoring holiday absences
' To find the last date, you need to Truncate the XML string to the last 2000 characters, otherwise, the count will exceed Excel's limits on the size of integers.
FXstring = Right(HTMLResponse, 2000)
MidSt = InStrRev(FXstring, "Cube time=") + 11
MidLen = InStr(MidSt, FXstring, Chr(34)) - MidSt
FirstRptDate = Mid(FXstring, MidSt, MidLen)
DateLoops = Application.WorksheetFunction.NetworkDays(FirstRptDate, CurRptDate)
ReDim FxTable(1 To DateLoops, 1 To 8)
' Clear old data
' I've created a named range in my data worksheet called "FX_Download". This is the top left cell of the range which will hold the target data.
' There should at least two blank rows above the this named range to hold the URL that is pasted into the worksheet and a reference to the source
If Range("FX_Download") <> "" Then
Range(Range("FX_Download"), Range("FX_Download").End(xlDown).Offset(0, 7)).Clear
End If
With Range("FX_Download")
.Offset(-2, 0) = "ECB Web page source:"
.Offset(-1, 0) = ECB_FX_URL
.Offset(0, 0) = "Bus. Date"
.Offset(0, 1) = "Month End"
.Offset(0, 2) = "USD"
.Offset(0, 3) = "GBP"
.Offset(0, 4) = "CAD"
.Offset(0, 5) = "USDGBP"
.Offset(0, 6) = "EURGBP"
.Offset(0, 7) = "CADGBP"
With Range(.Offset(0, 0), .Offset(0, 7))
.Font.Bold = True
.HorizontalAlignment = xlCenter
End With
End With
' Reset the FXstring to the original HTMLResponse
FXstring = HTMLResponse
j = 1
Application.StatusBar = "Parsing XML string to extract USD & GBP quotes for each date"
For i = 1 To DateLoops
if i mod 250 = 0 then Application.StatusBar = "Parsing XML string to extract USD and GBP quotes for each date. Loop Number: " & i & " of " & Format(DateLoops, "0,000") & "."
' Loop through XML response text, looking for each new date. The date is preceded by text which starts with the search text "Cube time="
' Truncate the string by eliminating the portion of the string prior to and including the search text
' Extract all text starting after this occurence and then look for the specific currency quotes
' Adjust the starting point by 9 (length of the search text). Since we're counting from the Right it is -9.
FXstring = Right(FXstring, Len(FXstring) - InStr(1, FXstring, "Cube time=") - 9)
' Now that the FXstring is truncated, extract the date
' Store the date of this quote in the FXDate variable, after extracting any quotes (") from the text.
' Chr(34) is the code for the " symbol
FXDate = Left(FXstring, InStr(FXstring, Chr(34) & ">"))
FXDate = Replace(FXDate, Chr(34), "", 1)
' Data starts from the most recent date and moves to earlier dates.
' Check to see whether the new date is from an earlier month.
' If it is, set the MnthEnd variable to TRUE. Also set to TRUE for the first date in the series
If i = 1 Then
MnthEnd = True
Else
If Month(FXDate) <> Month(PrevDate) Then
MnthEnd = True
Else
MnthEnd = False
End If
End If
If MnthEnd Then
' For new Month Ends, extract the specific currency quotes which follow the text "USD" rate="
' The code Chr(34) is used to place the " symbol in the search string
' MidSt finds the starting point for the FX quote
' MidLen finds the length of the FX quote by searching for the next occurence of the " symbol, starting from the MidSt point
' The the Mid() function extracts that date from the XML string
MidSt = InStr(FXstring, "USD" & Chr(34) & " rate=") + 11
MidLen = InStr(MidSt, FXstring, Chr(34)) - MidSt
USDVal = Mid(FXstring, MidSt, MidLen)
' Repeat with search adapted for GBP
MidSt = InStr(FXstring, "GBP" & Chr(34) & " rate=") + 11
MidLen = InStr(MidSt, FXstring, Chr(34)) - MidSt
GBPVal = Mid(FXstring, MidSt, MidLen)
' Repeat with search adapted for CAD
MidSt = InStr(FXstring, "CAD" & Chr(34) & " rate=") + 11
MidLen = InStr(MidSt, FXstring, Chr(34)) - MidSt
CADVal = Mid(FXstring, MidSt, MidLen)
' Use the value rather than the EoMonth formula to populate the cells for the month-end date.
' If the formula is used the Range.Find function won't work when searching for dates.
' Write data to FxTable array, including the GBP cross rates that are calculated from the original EUR rates
FxTable(j, 1) = FXDate
FxTable(j, 2) = Application.WorksheetFunction.EoMonth(FXDate, 0)
FxTable(j, 3) = USDVal
FxTable(j, 4) = GBPVal
FxTable(j, 5) = CADVal
FxTable(j, 6) = USDVal / GBPVal
FxTable(j, 7) = 1 / GBPVal
FxTable(j, 8) = CADVal / GBPVal
j = j + 1
End If
PrevDate = FXDate
If FXDate = FirstRptDate Then
' Check to see if the FirstRptDate has been reached.
' If it has, set i to end the loops
MidSt = i
i = DateLoops
End If
Next i
With Range(Range("FX_Download").Offset(1, 0), Range("FX_Download").Offset(DateLoops, 7))
.Select
.Value = FxTable
.NumberFormat = "0.0000"
.HorizontalAlignment = xlCenter
End With
With Range(Range("FX_Download").Offset(1, 0), Range("FX_Download").Offset(DateLoops, 1))
.NumberFormat = "dd/mm/yyyy"
End With
Application.ScreenUpdating = True
Application.StatusBar = "FX Update complete. Downloaded " & MidSt & " data points and created " & j - 1 & " month-ends."
End Sub
| |
doc_415
|
It works fine.The problems are 3:
*
*How to change the columns from A to D with the columns C and E.
*The script works only with one row selected, how can I copy multiple rows selected at the same time.
*When the script is terminated, I would that in column H appears the value Sent for the rows copied.
Thanks in advance.
function main() {
transfer("....", "Foglio1", "Foglio1");
}
function transfer(targetId, sourceSheetName, targetSheetName) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = ss.getSheetByName(sourceSheetName);
var last = sourceSheet.getActiveRange().getRow();
var data = sourceSheet.getRange(last, 1, 1, 4).getValues();
// copy data
var ss2 = SpreadsheetApp.openById(targetId);
var targetSheet = ss2.getSheetByName(targetSheetName);
//get last row
var lastRow = targetSheet.getLastRow();
//write data
targetSheet.getRange(lastRow + 1, 1, data.length, data[0].length)
.setValues(data);
}
A: Explanation:
*
*How to change the columns from A to D with the columns C and E?
Please have a look at the arguments of getRange:
Replace
var data = sourceSheet.getRange(last, 1, 1, 4).getValues();
with
var data = sourceSheet.getRange(last, 3, 1, 3).getValues();
*The script works only with one row selected, how can I copy multiple rows selected at the same time?
You can use getHeight to find the number of rows selected and pass it to getRange:
var height = sourceSheet.getActiveRange().getHeight();
var data = sourceSheet.getRange(last, 3, height, 3).getValues();
*When the script is terminated, in column H appears the value "Sent" for the rows copied.
You can just set the values of column H to Sent for the selected rows:
sourceSheet.getRange(last, 8, height).setValue('Sent');
Solution:
function main() {
transfer("....", "Foglio1", "Foglio1");
}
function transfer(targetId, sourceSheetName, targetSheetName) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = ss.getSheetByName(sourceSheetName);
var last = sourceSheet.getActiveRange().getRow();
var height = sourceSheet.getActiveRange().getHeight();
var data = sourceSheet.getRange(last, 3, height, 3).getValues();
// copy data
var ss2 = SpreadsheetApp.openById(targetId);
var targetSheet = ss2.getSheetByName(targetSheetName);
//get last row
var lastRow = targetSheet.getLastRow();
//write data
targetSheet.getRange(lastRow + 1, 3, data.length, data[0].length)
.setValues(data);
sourceSheet.getRange(last, 8, height).setValue('Sent');
}
| |
doc_416
|
{"http.proxy": "http://user@myproxy:port",
"http.proxyStrictSSL": false
}
But if I use it by command as below, it works:
pip install Pylint --proxy=http://user@myproxy:port
Could you please help me? Thank you very much.
A: you can have a try with bellow:
*
*start vscode with below command
code --proxy-server="xxx.xx.xx.xx:port"
*add command in desktop for vscode
/usr/share/applications/code.desktop
Exec=/usr/share/code/code --proxy-server="xx.x.x.xx:xxx" --unity-launch %F
| |
doc_417
|
Edit: 26/10/2016: SOMETHING FOUND: While trying to find the problem, I got a bug that helped me find something .It turns out if I have this in my Firebase database:
Campaigns{
UNQ_KEY: 1 //This is being set in the transaction
}
Rather than this:
Campaigns{
UNQ_KEY:{
count: 1 //this is being set in the transaction
}
}
The problem doesn't happen.
So, in conclusion, it's probably a recursion error.
I have this Firebase transaction:
database.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Long preUserIncrementedInt = Long.parseLong(b.getText().toString());
Long userIncrementedInt = ++preUserIncrementedInt;
mutableData.child("users").child(getUid()).child("count").setValue(userIncrementedInt);
Long preIncrementedTotalCount = mutableData.child("count").getValue(Long.class);
Long incrementedTotalCount = ++preIncrementedTotalCount;
mutableData.child("count").setValue(incrementedTotalCount);
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
if (databaseError != null)
Log.wtf(TAG,databaseError.getMessage());
}
});
This line:
mutableData.child("users").child(getUid()).child("count").setValue(userIncrementedInt);
and this one:
mutableData.child("count").setValue(incrementedTotalCount);
When I run the transaction, the same activity gets created again and opens. When I click the back button, it goes to the previous activity in the backstack. BUT, the previous activity in the backstack is the same activity itself. Like this:
Each time I click the button, a new activity (activity with the problem) is produced in the backstack.
To show you how it looks like, here's a GIF:
Why is this happening?
A: It restarts your activity because it crashes somewhere. Try this code:
public void onClick(View v) {
if (mp == null){
mp = new MediaPlayer();
} else {
mp.reset();
}
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("click.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e){
} catch (IOException e){
} catch (Exception e){
}
v.setEnabled(false);
final View clicked = v;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
clicked.setEnabled(true);
}
};
handler.postAtTime(runnable,System.currentTimeMillis()+100);
handler.postDelayed(runnable,100);
}
A: (I will be posting here as its easier to manage my comments)...
The solution is NOT found.
*UPDATE 4: Solution Found**
After many tries, and lots of comments, the solution was finally found, apparently the OP had the increment method in another class and moving it to the same class it was being used on solved the issue.
As of why this might happened, in my opinion, maybe it had to do with a concurrency issue on the transaction, maybe the problem was that it was creating a cycle on its own. Your activity starts, later you instantiated your FirebaseController which, at some point, fired off the increment method, making an async execution which ends up (failing in some way?) and that starts your activity again
See below for failed (but troubleshooting steps) attempts
I tried to debug. It wasn't activated on any of these lines. It takes
me to a bunch of Android files (such as View.java). When I "Run to
cursor" (skip the next debug breakpoint), it restarts.
Can you try to check whether the clicked view inside the runnable is not null ?
Runnable runnable = new Runnable() {
@Override
public void run() {
// if not null do this
clicked.setEnabled(true);
// if null print some log
// ...
}
};
Are you using Step Into or Step over when debugging (if you get deeper in the hierarchy of classes you might be using Step Into (F5), can you try debugging with Step Over (F6) )?
If we found the answer I will post it here:
UPDATE 1:
MutableData#setValue(java.lang.Object)
The documentation explains how this works:
Set the data at this location to the given value. The native types
accepted by this method for the value correspond to the JSON types:
Boolean
Long
Double
Map<String, Object>
List<Object>
In addition, you can set instances of your own class into this location, provided they satisfy the following constraints:
The class must have a default constructor that takes no arguments The
class must define public getters for the properties to be assigned.
Properties without a public getter will be set to their default value
when an instance is deserialized
Try using another datatype as suggested by fellow developers:
change the #setValue parameter to an object of the list above and #getValue also return an object, try to cast to the correct type, maybe you could use Integer class
UPDATE 2:
Does your data schema look something like this?
{
"campaings": {
"key": {
"count": "1",
"users": {
"-JRHTHaIs-jNPLXOQivY": {
"count": "1",
...
},
...
}
...
},
"other-key": {
...
}
...
}
}
Thats what I infer from the pieces of code there, you can clarify me if I made a mistake.
// here we are searching for the current reference in Campaings/key
DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("Campaigns").child(key);
int preIncrementUserCount = Integer.parseInt(button.getText().toString());
final int incrementedUserCount = ++preIncrementUserCount;
button.setText(String.valueOf(incrementedUserCount));
database.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
// here we are searching for the current count value in
// Campaings/key/count
Integer currentValue = mutableData.child("count").getValue(Integer.class);
if (currentValue == null) {
// do something...
} else {
// here we are setting the count value in Campaings/key/count
mutableData.child("count").setValue(++currentValue);
}
// here we are setting the count value in Campaings/key/users/UUID/count
mutableData.child("users").child(getUid()).child("count").setValue(incrementedUserCount);
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean committed, DataSnapshot dataSnapshot) {
if (databaseError != null) {
Log.e(TAG, "Error: " + databaseError.getMessage());
}
System.out.println("Transaction completed");
}
});
The point of the code example is to illustrate the data schema searches you are doing (again, correct me in any part if I made a mistake), but please put the databaseError log on onComplete for debugging purposes
UPDATE 3
From the documentation:
doTransaction() will be called multiple times and must be able to
handle null data. Even if there is existing data in your remote
database, it may not be locally cached when the transaction function
is run.
Try changing this part:
if (currentValue == null) {
// do something...
} else {
// here we are setting the count value in Campaings/key/count
mutableData.child("count").setValue(++currentValue);
}
To something like:
if (mutableData.child("count").getValue() == null) {
// print something...
// Log.d(TAG,"Value at some point was null");
// or maybe (just to test)
// mutableData.child("count").setValue(1);
} else {
// here we are setting the count value in Campaings/key/count
mutableData.child("count").setValue(++currentValue);
}
P.S: I'm leaving the solutions if any person in the foreseable future might be troubleshooting something similar like this
A: Maybe it is trying to start unprepared mediaplayer. Start it like this:
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
public void onPrepared(MediaPlayer p){
p.start();
}
}
EDIT:
Take a look at Firebase doc MutableData setValue(..) method it only accepts the following types. But u use int which is primitive type.
*
*Boolean
*Long
*Double
*Map
*List
So u should change this
int totalCount = mutableData.child("count").getValue(int.class);
with
Long totalCount = mutableData.child("count").getValue();
A: In this line,
mutableData.child("count").setValue(newTotalCount);
you are passing an 'int' value by setValue() method. It should be a supported Object by this method.
As per the documentation,
public void setValue (Object value)
Set the data at this location to the given value.
The native types accepted by this method for the value correspond to the JSON types:
Boolean
Long
Double
Map<String, Object>
List<Object>
You are passing an 'int' value there. So change that value to corresponding Object.
In this line,
int totalCount = mutableData.child("count").getValue(int.class);
you are getting value with 'int.class'. It is not a Object. It also should be a Object. Change this. I hope it will help you.
| |
doc_418
|
function mail_error($ex) {
$from = "[email protected]";
$to = "[email protected]";
$subject = "ERROR!";
$message = $ex."\n\nwith user: ".$_SESSION['memberid'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
header("Location: error.html");
}
Is there a way to change that last line so that it redirects to error.html?
Here's the JQuery that calls the php:
$.ajax({
url : 'wsviewattendance.php',
type : 'POST',
async : true,
data : {
'fetch' : 1,
'limit' : view,
'id' : nameid
},
success:function(re){
$('#showdata').html(re);
$.ajax({
url : 'wsviewattendance.php',
type : 'POST',
async : true,
data : {
'setheading' : 1
},
success:function(re){
if(re == "1"){
return false;
} else {
$('#showheading').html(re);
}
}
});
}
});
| |
doc_419
|
lambda <-function(ag, gnd, ibmi) {
sel <- ibmi[ibmi$age==ag & ibmi$gender == gnd, ]
out <- boxcox(lm(bmi~1, data = sel), data = sel)
rn <- range(out$x[out$y > max(out$y)-qchisq(0.95,1)/2])
(rn[1] + rn[2])/2
}
This is how I call this function and create the new variable in my data frame
myData$L <- lambda(myData$age, myData$gender, bmi)
I pass age, gender and reference data frame bmi to the function lambda. But I get the following Warning and getting same answer repeated for all the records of different age and gender.
Warning messages:
1: In ibmi$age == ag :
longer object length is not a multiple of shorter object length
2: In ibmi$gender == gnd :
longer object length is not a multiple of shorter object length
Can someone please help me.
| |
doc_420
|
But when something goes wrong, it is not possible to debug, because the library is minimized.
Is there a way to link to some file which contains the full source code?
Some weeks ago, I used to us ol-whitespace.js, but now I can't find it anywhere.
A: Just to clarify Christophe's answer, the OpenLayers Quick Start guide points you to the following minified file:
<script src="http://openlayers.org/en/v3.0.0/build/ol.js" type="text/javascript"></script>
You can replace this with:
<script src="http://openlayers.org/en/v3.0.0/build/ol-debug.js" type="text/javascript"></script>
A: I do not see your link but this file is now called ol-debug.js.
You can find it next to ol.js in the build folder.
| |
doc_421
|
The value comes to ExtJs as a string from database.
The string is created in php.
Since it doesn't support HTML, <br> won't work.
It also seems to ignore \r\n or \n or \ \r\ \n or \ \n - it will simply print it as text.
Is there any workarounds?
A: It seems like ext somehow escaped everything when the datatype in store was string (i guess some ASCII values were set).
Adding string directly to setValue() works with \n.
As a workaround i used a custom palceholder %nl and used js replace to change them to \non setValue().
| |
doc_422
|
Could not locate that index-pattern (id: metricbeat-*), click here to re-create it
I cannot click the text which says "click here to re-create it". It is not a clickable object.
I enabled the apache module with the following command:
metricbeat modules enable apache
I had previously set up the dashboards using:
metricbeat setup --dashboards
I checked the metricbeat log file at /var/log/metricbeat/metricbeat but there were no errors. How can I make the Metricbeat Apache visualizations for the default dashboard display correctly?
A: I found the answer myself:
In my case, I did not have Apache's "server-status" module set up correctly. And since metricbeat's apache module depends on this, it was not working.
I fixed this by making sure I had access to http://www.example.com/server-status
page
To do this I changed (in .htaccess):
RewriteEngine On
to:
RewriteEngine Off
Once I did that, the dashboard started working.
| |
doc_423
|
from sqlalchemy import Column, String, Integer, ForeignKey, create_engine
from sqlalchemy.orm import relationship, Session
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# Define models
class Person(Base):
__tablename__ = "Person"
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
pets = relationship("Pet", backref="person")
def __repr__(self):
return f"<Person: {self.name}>"
class Pet(Base):
__tablename__ = "Pet"
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
person_id = Column(Integer, ForeignKey("Person.id"))
def __repr__(self):
return f"<Pet: {self.name}>"
connection_string = "sqlite:///db.sqlite3"
engine = create_engine(connection_string)
session = Session(
bind=engine, expire_on_commit=False, autoflush=False, autocommit=False
)
# Build tables
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
# Create data
persons = [
Person(name="Johnny"),
Person(name="Steph"),
]
pets = [
Pet(name="Packets", person=persons[0]),
Pet(name="Sally", person=persons[1]),
Pet(name="Shiloh", person=persons[0]),
]
# Populate tables with data
for items in [persons, pets]:
for item in items:
q = session.query(item.__class__).filter_by(name=item.name).one_or_none()
if q:
print(f"Already exists: {item}")
continue
session.add(item)
session.commit()
print(f"Added: {item}")
When I run it, I get the following result:
Added: <Person: Johnny>
Added: <Person: Steph>
Already exists: <Pet: Packets>
Already exists: <Pet: Sally>
Already exists: <Pet: Shiloh>
I would expect the result to look like this:
Added: <Person: Johnny>
Added: <Person: Steph>
Added: <Pet: Packets>
Added: <Pet: Sally>
Added: <Pet: Shiloh>
What's happening that's adding the Pet objects before they're actually added to the session? How can I prevent this so my output is as expected?
A:
What's happening that's adding the Pet objects before they're
actually added to the session?
Inserting <Person: Johnny> implicitly inserts <Pet: Packets> and <Pet: Shiloh>; inserting <Person: Steph> implicitly inserts <Pet: Sally>.
That's because backref creates a bidirectional relationship.
As described here in the docs:
[...] when the backref keyword is used on a single relationship, it’s
exactly the same as if [...] two relationships were created
individually using back_populates [...]
You create Pet instances that relate to Person instances, that do not yet exist in the database. With the default cascading settings, that leads to the implicit inserts of the related objects to represent both directions of the relationship.
This can be observed by creating the engine with echo set to True:
engine = create_engine(connection_string, echo=True)
This enables base engine output:
# Time stamps and log level omitted for brevity
# First iteration of the loop (Johnny):
sqlalchemy.engine.base.Engine INSERT INTO "Person" (name) VALUES (?)
sqlalchemy.engine.base.Engine ('Johnny',)
sqlalchemy.engine.base.Engine INSERT INTO "Pet" (name, person_id) VALUES (?, ?)
sqlalchemy.engine.base.Engine ('Packets', 1)
sqlalchemy.engine.base.Engine INSERT INTO "Pet" (name, person_id) VALUES (?, ?)
sqlalchemy.engine.base.Engine ('Shiloh', 1)
# Second iteration of the loop (Steph):
sqlalchemy.engine.base.Engine INSERT INTO "Person" (name) VALUES (?)
sqlalchemy.engine.base.Engine ('Steph',)
sqlalchemy.engine.base.Engine INSERT INTO "Pet" (name, person_id) VALUES (?, ?)
sqlalchemy.engine.base.Engine ('Sally', 2)
# Third to fifth iteration: the Pets already exist.
The other way round is similar; if you specify the pet list first, your output looks like this:
Added: <Pet: Packets> # implicitly creates Person Johnny and, through Johnny, Pet Shiloh
Added: <Pet: Sally> # implicitly creates Person Steph
Already exists: <Pet: Shiloh>
Already exists: <Person: Johnny>
Already exists: <Person: Steph>
As Ilja Everilä pointed out in the comments, the simplest way to disable the implicit insertion of the Pets is to remove the save-update setting from the relationship's cascades:
pets = relationship("Pet", backref="person", cascade="merge")
Note, that issues a warning:
SAWarning: Object of type <Pet> not in session, add operation along
Person.pets will not proceed
A more verbose way to prevent the pets from being created implicitly through the relationship, is to postpone their instantiation until after the persons have been inserted, e.g.:
# Don't instantiate just yet
# pets = [
# Pet(name="Packets", person=persons[0]),
# Pet(name="Sally", person=persons[1]),
# Pet(name="Shiloh", person=persons[0]),
# ]
pets = {persons[0]: ['Packets', 'Shiloh'],
persons[1]: ['Sally']}
for item in persons:
if session.query(item.__class__).filter_by(name=item.name).one_or_none():
print(f"Already exists: {item}")
continue
session.add(item)
session.commit()
print(f"Added: {item}")
for pet in pets[item]:
p = Pet(name=pet, person=item)
session.add(p)
session.commit()
print(f"Added: {p}")
Output:
Added: <Person: Johnny>
Added: <Pet: Packets>
Added: <Pet: Shiloh>
Added: <Person: Steph>
Added: <Pet: Sally>
However, with the default behavior, you can effectively omit the explicit insertion of the Pets. Just iterating persons, will insert all Pet instances as well; three unnecessary queries are skipped.
| |
doc_424
|
companion object {
private const val PARAMETER_1 = "parameter1"
private const val PARAMETER_2 = "parameter2"
fun newInstance(parameter1: String, parameter2: Int) = MyDialog().apply {
arguments = bundleOf(
PARAMETER_1 to parameter1,
PARAMETER_2 to parameter2)
}
}
And then I add:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val args = arguments ?: return
property1 = args[PARAMETER_1]
property2 = args[PARAMETER_2]
}
This isn't horrific. But it is boilerplate that it would be great to get rid of.
Here's my attempt so far:
abstract class BaseFragment : Fragment() {
abstract val constructorArguments: List<KMutableProperty<*>>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val args = arguments ?: return
constructorArguments.forEach {
val key = keyPrefix + it.name
val argument = args.get(key)
val clazz = it.javaClass
val typedArgument = clazz.cast(argument)
it.setter.call(typedArgument)
}
}
companion object {
const val keyPrefix = "ARGUMENT_"
fun newInstance(fragment: BaseFragment, vararg parameters: Any): BaseFragment {
val constructorArguments = fragment.constructorArguments
val parameterMap = mutableListOf<Pair<String, Any?>>()
constructorArguments.forEachIndexed { index, kMutableProperty ->
val key = keyPrefix + kMutableProperty.name
val parameter = parameters[index]
parameterMap.add(Pair(key, parameter))
}
val args = bundleOf(*parameterMap.toTypedArray())
fragment.arguments = args
return fragment
}
}
}
And then, in the actual fragment I can just have:
class MyFragment : BaseFragment() {
lateinit var myProperty: String
override val constructorArguments = listOf<KMutableProperty<*>>(
::myProperty
)
companion object {
fun newInstance(argument: String) = BaseFragment.newInstance(MyFragment(), argument)
}
}
This approach is far from perfect - especially the:
val parameter = parameters[index]
Does anyone know a better way to do this? Do you have some suggestions for how my approach can be improved? Or is this whole idea doomed to fail, and have I wasted a morning?
A: An 'answer' to this question is to use the Android Jetpack Navigation library. It provides SafeArgs, which greatly simplifies passing arguments to Fragments. See:
https://developer.android.com/guide/navigation/navigation-pass-data#Safe-args
A: You can have a base fragment that defines a common args parameter
abstract class BaseFragment : Fragment() {
companion object {
const val ARGS_KEY = "__ARGS__"
}
fun <T: Parcelable> getArgs(): T = requireArguments().getParcelable(ARGS_KEY)
fun putArgs(args: Parcelable): Bundle = (arguments ?: Bundle()).apply {
putParcelable(ARGS_KEY, args)
}
}
Then
@Parcelize data class Args(val parameter1: String, val parameter2: Int)
companion object {
fun newInstance(args: Args) = MyDialog().apply {
putArgs(args)
}
}
And now you can do it like
class MyFragment: BaseFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val args: Args = getArgs()
args.parameter2
}
}
| |
doc_425
|
For example think about a reaction game, in which the payer has to press a button rapidly after a led is lit.
*
*A led is lit
*The system waits until the button is pressed
*When the button is pressed, the wait ends and something happens (e.g. delta time is calculated)
My first (and working) attempt and the examples I find around work the following way:
def button_not_still_pressed():
return True if "Button has not been still pressed", e.g. voltage is low
# this function does the check (e.g. reads a pin or performs any other test
# depending on the application
while button_not_still_pressed():
pass # Please note: non tome.sleep() here
do_whatever_when_button_is_pressed()
In practice, it seems to work.
My concerns are:
*
*Can an indefinite/long loop cause the system hang?
*What does python do, in general, in a while loop like the one above?
*In particular, regarding devices like those, which is the best way to perform such a task of sending a signal and wait?
A:
Can an indefinite/long loop cause the system hang?
In a more embedded system, yes. In Linux, probably not, since it's not doing anything of consequence.
What does python do, in general, in a while loop like the one above?
Runs its interpreter in a tight loop that consumes CPU.
In particular, regarding devices like those, which is the best way to perform such a task of sending a signal and wait?
If you're using Raspberry Pi's GPIO for your button, use an interrupt to avoid a tight loop:
GPIO.wait_for_edge(channel, GPIO.RISING)
| |
doc_426
|
public virtual async Task<IHttpActionResult> Patch([FromODataUri] int[] ids, Data data)
but I am getting from the server the response 404 not found.
I want to update the data for all entities whose id is in the array ids.
I am calling the service like that: http://localhost/appc/odata/MyEntity(13,10)
MapHttpRoute:
config.Routes.MapHttpRoute(
"DefaultApi",
"api/{controller}/{id}",
new {id = RouteParameter.Optional}
);
Any idea why is the route not found?
| |
doc_427
|
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<ProgressBar
android:id="@+id/fb_progressBar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:maxHeight="5dip"
android:minHeight="5dip"
android:progressDrawable="@drawable/progress_horizontal"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<utilities.ObservableWebView
android:id="@+id/fb_webView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/footerBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/fb_progressBar"
/>
<RelativeLayout
android:id="@+id/footerBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/footerBarBg"
android:paddingBottom="8dp"
android:paddingTop="8dp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
>
<ImageView
android:id="@+id/go_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="16dp"
android:background="?attr/selectableItemBackground"
android:padding="5dp"
android:src="@drawable/ic_arrow_back_black_24dp" />
<ImageView
android:id="@+id/goToTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="16dp"
android:background="?attr/selectableItemBackground"
android:padding="5dp"
android:src="@drawable/ic_arrow_upward_black_24dp" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
A: <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<utilities.ObservableWebView
android:id="@+id/fb_webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/footerBar"
/>
<RelativeLayout
android:id="@+id/footerBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/footerBarBg"
android:backgroundTint="#ff0000"
android:paddingBottom="8dp"
android:paddingTop="8dp"
android:visibility="visible">
<ImageView
android:id="@+id/go_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="16dp"
android:background="?attr/selectableItemBackground"
android:padding="5dp"
android:src="@drawable/ic_arrow_back_black_24dp" />
<ImageView
android:id="@+id/goToTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="16dp"
android:background="?attr/selectableItemBackground"
android:padding="5dp"
android:src="@drawable/ic_arrow_upward_black_24dp" />
</RelativeLayout>
<ProgressBar
android:id="@+id/fb_progressBar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="5dp"
android:maxHeight="5dip"
android:minHeight="5dip"
android:progressDrawable="@drawable/progress_horizontal" />
</RelativeLayout>
this work perfect
or refer to this document
https://stackoverflow.com/a/44778453/7522720
| |
doc_428
|
self.response.write(blobstore.create_upload_url(....))
Everything works fine in production, but when using testbed to unit test this API, I get the following URL back:
http://testbed.example.com/_ah/upload/agx0ZXN0YmVkLXRlc3RyGwsSFV9fQmxvYlVwbG9hZFNlc3Npb25fXxgDDA
Uploading to this URL from the test doesn't work, I get a 404. I should have initialized all stubs properly, amongst others:
self.testbed.init_datastore_v3_stub()
self.testbed.init_blobstore_stub()
self.testbed.init_files_stub()
What am I doing wrong? How do I unit test file uploads using the blobstore create_upload_url API?
A: From the comments and looking at the code, I'm assuming you can't do it out of the box.
My solution to the problem is to implement the uploading myself, using the google.appengine.api.datastore.Get to extract information from the session pointed to by the create_upload_url url.
Below is some test code. It's using post from WebTest, and a stub for GCS, although the latter is probably unnecessary.
from google.appengine.api import datastore
import uuid
import base64
import md5
def testSomething(self):
upload_url = self.testapp.post('/path/to/create_upload_url/handler').body
response = self.upload_blobstore_file(upload_url, "file", "myfile.txt", "MYDATA1").json
# Test something on the response from the success handler and/or backing storage
def upload_blobstore_file(self, upload_url, field, filename, contents, type = "application/octet-stream"):
session = datastore.Get(upload_url.split('/')[-1])
new_object = "/" + session["gs_bucket_name"] + "/" + str(uuid.uuid4())
self.storage_stub.store(new_object, type, contents)
message = "Content-Type: application/octet-stream\r\nContent-Length: " + str(len(contents)) + "\r\nContent-MD5: " + base64.b64encode(md5.new(contents).hexdigest()) + "\r\nX-AppEngine-Cloud-Storage-Object: /gs" + new_object.encode("ascii") + "\r\ncontent-disposition: form-data; name=\"" + field + "\"; filename=\"" + filename + "\"\r\nX-AppEngine-Upload-Creation: 2015-07-17 16:19:55.531719\r\n\r\n"
return self.testapp.post(session["success_path"], upload_files = [
(field, filename, message, "message/external-body; blob-key=\"encoded_gs_file:blablabla\"; access-type=\"X-AppEngine-BlobKey\"")
])
A: Set the http_host in the testbed:
self.testbed.setup_env(
http_host='%s:%s' % (SERVER_NAME, PORT),
overwrite=True,)
A: According to me, you cannot directly create the blob data, instead of it blobs are created indirectly by a submitted web form or HTTP post request. For more details you can go through the document [1].
[1] https://cloud.google.com/appengine/docs/java/blobstore/#Java_Introducing_the_Blobstore
| |
doc_429
|
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
using namespace cv;
int main(int argc, char** argv)
{
Mat image = imread("V2.jpg", 1);
CascadeClassifier face_cascade;
face_cascade.load("haarcascade_frontalface_alt.xml");
vector<Rect> faces;
face_cascade.detectMultiScale(image, faces);
return 0;
}
The following code, according to valgrind, leaks from the detectMultiScale function. Is there a good practice I'm neglecting here? Something to release? Logically, everything is on the stack from my end, so it should be released when the program ends.
valgrind's output is:
==4852== at 0x4C28F9F: malloc (vg_replace_malloc.c:236)
==4852== by 0x4EB1D90: cv::fastMalloc(unsigned long) (in /usr/lib/libopencv_core.so.2.3.1)
==4852== by 0x58F175D: ??? (in /usr/lib/libopencv_objdetect.so.2.3.1)
==4852== by 0x58F8699: cvHaarDetectObjectsForROC(void const*, CvHaarClassifierCascade*, CvMemStorage*, std::vector<int, std::allocator<int> >&, std::vector<double, std::allocator<double> >&, double, int, int, CvSize, CvSize, bool) (in /usr/lib/libopencv_objdetect.so.2.3.1)
==4852== by 0x58EA38B: cv::CascadeClassifier::detectMultiScale(cv::Mat const&, std::vector<cv::Rect_<int>, std::allocator<cv::Rect_<int> > >&, std::vector<int, std::allocator<int> >&, std::vector<double, std::allocator<double> >&, double, int, int, cv::Size_<int>, cv::Size_<int>, bool) (in /usr/lib/libopencv_objdetect.so.2.3.1)
==4852== by 0x58DA6B5: cv::CascadeClassifier::detectMultiScale(cv::Mat const&, std::vector<cv::Rect_<int>, std::allocator<cv::Rect_<int> > >&, double, int, int, cv::Size_<int>, cv::Size_<int>) (in /usr/lib/libopencv_objdetect.so.2.3.1)
This is being run on a VMware VM running 64-bit Kubuntu 11.10 on Windows 7 64-bit. The OpenCV version is the latest - 2.3.1.
A: You must release variable faces
A: Im not sure about the error message of Valgrind, but if there was a leak it sure is not in your code peace. Try to update to 2.4.2 though, it is much faster, too.
| |
doc_430
|
A: It is a known issue. And looks like it is going to be fixed in ReSharper 8.1.
As workaround for R# 8.0:
*
*use any Imported*.vssettings file from here %localappdata%\JetBrains\ReSharper\v8.0\vs11.0\
*Replace all "Текстовый редактор" with "Text Editor"
*save the file and import it here Tools | Import and Export settings.
A: Seriously, I was also a victim of Jetbrain Resharper, VS 2012 was pretty slow, though features are great..but sorry to say it bog down the VS tool terribly! :(. Their support never say their product is slow, instead they would point to Higher version of OS...etc, I have WIN7, 8GB RAM..etc ...still the same...
@Arran Oct 7 '13 at 15:11 - dont write a comment with a "drunk" attitude, people turn to Stackoverflow with a great hope, Help to keep the hope!
| |
doc_431
|
then, a small window opens, this window's title is 'File Upload' and I want write on location input in this window. How can I do this? Thanks !
A: If the file upload option is an input tag and its type is file then you can directly upload the file using send_keys() method in Selenium
e.g.
driver.find_element_by_id("uploadfile").send_keys("D:\test\filename.extension")
Note :enter absolute location of your file
| |
doc_432
|
However I keep getting a "list index out of range" error on the append(0)line.
Obviously I am not understanding how the append works.
grid = []
for row in range(2,12):
# Add an empty array that will hold each cell
# in this row
grid.append([])
for column in range(13,25):
grid[row].append(0) # Append a cell
A: The indices of lists always start at 0. range(2, 12) creates the numbers from 2 to 12. However the indices of the list grid still start at 0. You need to subtract 2 from row:
grid[row].append(0) # Append a cell
grid[row-2].append(0) # Append a cell
Get the index of the next row with len(grid), before appending a new row:
grid = []
for row in range(2, 12):
index_of_next_row = len(grid)
grid.append([])
for column in range(13, 25):
grid[index_of_next_row].append(0)
Alternatively, you can create a roe and append it to the grid when the row is finished:
grid = []
for row in range(2, 12):
new_row = []
for column in range(13, 25):
new_row.append(0)
grid.append(new_row)
Or even shorter:
grid = [[0 for cell in range(13, 25)] for row in range(2, 12)]
| |
doc_433
|
MainClass
private final Form form;
println("Downloading files...");
public void println(String line)
{
System.out.println(line);
form.getConsole().print(line);
}
Form(GUI)
private TabConsole console;
tabbedPane.addTab("Console", console);
public TabConsole getConsole()
{
return console;
}
TabConsole
public void print(final String line) {
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
TabConsole.this.print(line);
}
});
return;
}
Document document = this.console.getDocument();
JScrollBar scrollBar = getVerticalScrollBar();
boolean shouldScroll = false;
if (getViewport().getView() == this.console) {
shouldScroll = scrollBar.getValue() + scrollBar.getSize().getHeight() + MONOSPACED.getSize() * 4 > scrollBar.getMaximum();
}
try
{
document.insertString(document.getLength(), line, null);
} catch (BadLocationException localBadLocationException) {
}
if (shouldScroll)
scrollBar.setValue(2147483647);
}
Is that anything wrong with my codes? Thanks for helping.
A: rethrow the BadLocationException as a RuntimeException, although the code looks correct. What error are you getting?
If the text is not showing up, you are probably updating the wrong Document. Be sure you're updating the Document which is used by your TextArea, or whatever you're using to display the contents.
| |
doc_434
|
Now in an another script lets say GameManager I trigger this animation by anim.SetTrigger("Scaleup") and thats works fine where the cube gameobject scales to the correct values which is (2,2,2).
All i'm after here is: When this cube gets deactivated and then reactivated again the animator does reset to its default state (Idle state) but the size never gets back to its original scale which is (1,1,1) and stays at (2,2,2) no matter what I do which it seems impossible in unity.
How can I reset the values of the animation clip when a gameobject gets deactivated and reactivated again?
I tried doing this anim.enabled = false and anim.enabled = true but it doesn't work. Help Guys.
A: Animator does not change any parameter which is not changed in the animation. In your example, the scale was changed by Scaleup animation and is never mentioned anywhere else.
Add a new simple animation to Idle state, add game object scale to it and make it constant (1.0, 1.0, 1.0). That will effectively reset your object's scale.
| |
doc_435
|
*
*If the cell has an input X I would like font size to be 5 or less (specify) and fill the cell with a style
*If the cell has an input C, G or T then font should be bold, size 11, font color red or/and cell filled yellow
I have no idea how to even start.
A: You can write in Worksheet which you want:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target = Range("B2") Then
'Do some thing
End If
End Sub
A: As @Vityata said - start by recording a macro. Two macros would probably be better - one to add the formatting and one to remove it again. Just start recording and change your cell format to what you want.
This will give you code similar to this:
Sub Macro1()
'
' Macro1 Macro
'
'
Selection.Font.Bold = True
With Selection.Font
.Name = "Calibri"
.Size = 11
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
With Selection.Font
.Color = -16776961
.TintAndShade = 0
End With
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End Sub
and one to remove the formatting:
Sub Macro2()
'
' Macro2 Macro
'
'
Range("B2").Select
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
With Selection.Font
.ColorIndex = xlAutomatic
.TintAndShade = 0
End With
Selection.Font.Bold = False
End Sub
Now, you want to take this code, remove the superfluous bits and join it all together. For this I'd advise further reading on With...End With code blocks and Select Case statements.
When I say superfluous I mean anything that will default to that value anyway. Things like .Strikethrough = False can be removed as it does that anyway.
We end up with code like this placed inside a normal code module:
Public Sub FormatCell(Target As Range)
With Target
Select Case .Value
Case "C", "G", "T"
With .Font
.Bold = True
.Size = 11
.Color = -16776961
End With
.Interior.Color = 65535
Case "X"
'Add code if the cell is X.
Case Else
.Font.ColorIndex = xlAutomatic
.Interior.Pattern = xlNone
End Select
End With
End Sub
I've placed the code in it's own procedure rather than a worksheet event so it can be called from different places. The code will format the cell in the case of it being C, G or T. If it's X it will do nothing (got to add that bit of code), if it's anything else it will remove the formatting.
You can call the code from a worksheet event like this:
Private Sub Worksheet_Change(ByVal Target As Range)
FormatCell Target
End Sub
Target is the cell being changed and you pass this variable to your procedure. You may want to add code that checks a single cell has been selected or that a specific cell address is changing.
Note: Most of what you want can be accomplished with conditional formatting except the font size.
| |
doc_436
|
BTW, I'm using Mac OS X... it's been pointed out that behavior may be different for different OS's.
A: The MidiSystem.getMidiDeviceInfo() gets the full providers list, and extracts the info of the device from each provider.
The MIDIs provider list is recovered from the JDK underlaying class com.sun.media.sound.JDK13Services, through the static method getProviders()
public static synchronized List getProviders(Class serviceClass)
Obtains a List containing installed
instances of the providers for the
requested service. The List of
providers is cached for the period of
time given by cachingPeriod . During
this period, the same List instance is
returned for the same type of
provider. After this period, a new
instance is constructed and returned.
The returned List is immutable.
So, it seems that this class holds thee Providers list in a cache, wich will be reloaded after a certain period. You can set this period to a custom value using the method setCachingPeriod(int seconds). As long as I know, the default caching period is set to 60 seconds.
As an example, to refresh this cache every second, you coud add this line to your code:
com.sun.media.sound.JDK13Services.setCachingPeriod(1);
Please, note that this solution makes use of a Sun propietary class, so it could not be 100% portable.
A: Lacking any MIDI devices on my work PC, or indeed any kind of Mac, I doubt I'll be able to test it properly, but...
The MidiSystem class seems to use com.sun.media.sound.JDK13Services.getProviders(Class providerClass) to find the list of devices on the system. The API docs for this class state that the list is recreated on a successive call outside of a cachingPeriod, which can be conveniently set by calling setCachingPeriod(int seconds).
With any luck you can just call this once at the start of your application and set it to 5 seconds or something, and it'll magically work. However, the docs also state "This method is only intended for testing.", so I'm not sure quite how effective this approach will be.
Hopefully this is enough to get you started, and I'll keep poking around in the meantime to see if I can find a cleaner way to do this.
A: I answered this is Update list of Midi Devices in Java as well, but for folks who wind up here, there's now a library that supports this correctly: https://github.com/DerekCook/CoreMidi4J
The library acts a device provider for the MIDI Subsystem, so it's basically a drop-in and all your existing code will work.
I am not the author, but it works well for my needs, and it took a fair bit of searching to find, so I'm posting it here for others who encounter the problem.
A: I found a solution which uses the JavaFX thread. For some reason this works at least on MacOSX. On a normal thread it doesn't work.
import fx.FX_Platform;
import javafx.embed.swing.JFXPanel;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
public class miditest {
static public void main( String[] args ) {
// **** Just to init FX platform
new JFXPanel();
new Thread( () -> {
for( int ix=0; ix<1000; ix++ ) {
try {
Thread.sleep(2000);
} catch( InterruptedException e ) {
}
FX_Platform.runLater( () -> {
MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
System.out.println("FOUND: " + infos.length);
for( MidiDevice.Info midiinfo : infos ) {
System.out.println(midiinfo);
}
});
}
}).start();
}
}
A: This sounds like is could be an OS specifx bug but I can think of a get around.
In java you can run external commands to the OS. (A quick google, gave me this example http://www.javafaq.nu/java-example-code-186.html it looks OK and gives you the idea).
On checking for new devices you could send an external command to run a simple java program that quickly queries the midi devices using MidiSystem.getMidiDeviceInfo() and outputs the results to a text file or you could grab the output from the BufferedReader object.
Also remember that the external program used to query midi devices doesn't have to be written in Java incase Java causes you more problems. Alternatively you could just query the OS for connected devices and use grep to filter the results.
Hope this helps.
| |
doc_437
|
struct Data {
int a;
int b;
};
shared_ptr<Data> data = make_shared<Data>();
Is it possible to obtain a shared_ptr<int> to data->b which reuses the ref-count of data.
I.e. I want to pass a shared pointer to only a part of a reference-counted structure.
| |
doc_438
|
abstract class Exception {
factory Exception([var message]) => _Exception(message);
}
_Exception class is the implementation of it. As you can see there are no fields or functions declared in this class other than a factory constructor, so what's the significance of having such classes?
A: It's like a marker interface which tells the reader that a subclass is intended to be used as an exception (thrown in a situation where the user is expected to catch and handle the exceptional situation, rather than an error).
Dart, the language, does not treat Exception specially. It's completely unnecessary from a technical point of view since all objects can be thrown. Making your class implement Exception signifies that it's purpose is to be thrown, even though it is not an Error, but you should see it as documentation, not something your program can meaningfully use.
Exceptions, unlike Errors, are intended to be caught and handled, just as much as a return value is. An exception should contain enough information to make the receiver able to do something meaningful.
Because of that, you should never throw a plain Exception in production code (so the constructor is really deprecated except during development, until you have created a proper exception class).
Similarly, you should never catch a plain Exception (no on Exception catch (e) {...}) because then you are not handling the actual problem. If you just want to catch anything, use on Object, because code can throw any class, and not all exception classes need to implement Exception.
| |
doc_439
|
I've put the script below directly in the <head>. I want it first to work before I enqueue it the correct way.
<script>
jQuery(document).ready(function(){
jQuery('#cta-section').waypoint(function() {
jQuery('#cta-section').toggleClass('animate-cta');
}, {offset: '80%'});
});
</script>
I keep getting the following errors:
(index):13 Uncaught TypeError: jQuery(...).waypoint is not a function
at HTMLDocument.<anonymous> ((index):13)
at j (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at Function.ready (jquery.min.js:2)
at HTMLDocument.I (jquery.min.js:2)
(index):963 Uncaught TypeError: jQuery(...).waypoint is not a function
at HTMLDocument.<anonymous> ((index):963)
at i (jquery.js?ver=1.12.4:2)
at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4:2)
at Function.ready (jquery.js?ver=1.12.4:2)
at HTMLDocument.K (jquery.js?ver=1.12.4:2)
A: I found a solution. The only annoying point is that I need to play around with the ShrinkOn numbers.
<
script>
function resizeCTAOnScroll() {
const distanceY = window.pageYOffset || document.documentElement.scrollTop,
shrinkOn = 1850,
headerEl = document.getElementById('cta-section');
if (distanceY > shrinkOn) {
headerEl.classList.add("animate-cta");
} else {
headerEl.classList.remove("animate-cta");
}
}
window.addEventListener('scroll', resizeCTAOnScroll);
</script>
| |
doc_440
|
As seen in the image,
I have an object named O (set of linestripes).Its object-coordinate system is (x',y',z').
I translate,rotate this object in my OpenGL scene using following code snippet:
glPushMatrix();
glTranslatef(Oz, Oy,Oz);
glRotatef(rotationX , 1.0, 0.0, 0.0);
glRotatef(rotationY, 0.0, 1.0, 0.0);
glRotatef(rotationZ, 0.0, 0.0, 1.0);
contour->render();
glPopMatrix()
;
I have a point called H ,which is translated to (hx,hy,hz) world coordinates using
glPushMatrix();
glTranslatef(hx,hy,hz);
glPopMatrix();
If I am correct, (Oz,Oy,Oz) and (hx,hy,hz) are world coordinates.
Now,what I want todo is calculate the position of H (hx,hy,hz) relative to O's object-coordinate system.(x',y',z');
As I understood,I can do this by calculating inverse transformations of object O and apply them to point H.
Any tips on this? Does OpenGL gives any functions for inverse-matrix calculation ? If I somehow found inverse-matrices what the order of multiplying them ?
Note : I want to implement "hammer" like tool where at point H ,I draw a sphere with radius R.User can use this sphere to chop the object O like a hammer.I have implemented this in 2D ,so I can use the same algorithm if I can calculate the hammer position
relative to (x',y',z')
Thanks in advance.
A: Yes, basically you're right that you can perform this operation by the translation matrix
M = O^-1 * H
any like you already guessed you need the inverse of O for this. OpenGL is not a math library though, it only deals with rendering stuff. So you'll have to implement the inversion yourself. Google for "Gauss Jordan" to find one possible algorithm. If you can be absolutely sure, that O consists only of rotation and translation, i.e. no shearing or scaling, then you can shortcut by transposing the upper left 3x3 submatrix and negating the uppermost 3 elements of the rightmost column (this exploits the nature of orthogonal matrices, like rotation matrices, that the transpose is also the inverse, the upper left 3x3 is the rotational part, the inverse of a translation is negating the elements of it's vector which is the rightmost upper 3 elements).
A: Inverting the matrix would be the general solution, but as far as I can see this isn't actually a "general" problem. Rather than undoing an arbitrary transformation, you are trying to do the reverse of a known sequence of transformations, each of which can be inverted very simply. If your object-to-world transformation is:
glTranslatef(Ox, Oy, Oz);
glRotatef(rotationX , 1.0, 0.0, 0.0);
glRotatef(rotationY, 0.0, 1.0, 0.0);
glRotatef(rotationZ, 0.0, 0.0, 1.0);
Then the world-to-object inverse is just:
glRotatef(-rotationZ, 0.0, 0.0, 1.0);
glRotatef(-rotationY, 0.0, 1.0, 0.0);
glRotatef(-rotationX , 1.0, 0.0, 0.0);
glTranslatef(-Ox, -Oy, -Oz);
Basically, just back out each applied transformation in the opposite order originally applied.
| |
doc_441
|
http://www.bryntum.com/examples/gantt-latest/examples/basic/basic.html
When I implement it as JIRA report, the left bar in JIRA gets moved to middle.
Images are for illustrative purposes only.
I researched and found the problem was in Gantt library CSS file:
http://cdn.sencha.io/ext-4.1.0-gpl/resources/css/ext-all.css
Don't try to understand it, it has 10000 lines after beautifying the code. But after debugging I found the solution. When removing this code, the JIRA left bar moved to left and everything looked fine:
.x-border-box,.x-border-box * {
box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-webkit-box-sizing: border-box
}
Except:
Images are for illustrative purposes only.
The footer moved on top of the Gantt Chart. So having the second option is better, but I still prefer having my footer down below.
I tried changing CSS values, but could not produce any other results, than these two shown on screenshots.
So all in all, how do I get the footer down and the JIRA bar to left.
A: The problem is that the Ext JS CSS is global on the page, conflicting with other elements. This post might help, and helps set the 'scope' of the CSS to any element on the page - like your Gantt chart container div etc.
How to scope the reset CSS so that is applied to Ext components using scopeResetCSS property?
Use:
Ext = {buildSettings: {scopeResetCSS: true}};
together with ext-all-scoped.css. Should do it.
| |
doc_442
|
function save(variableL,variable) {
localStorage.setItem(variableL,Number(variable));
}
let points = localStorage.getItem('pointsL');
if (points === null) {
points = 0;
save('pointsL',points);
}
let line_segments = localStorage.getItem('line_segmentsL');
if (line_segments === null) {
line_segments = 0;
save('line_segmentsL',line_segments);
}
let points_per_sec = 0;
let line_segment_price = 10;
function pointClick() {
points = Number(points);
points += 1;
}
function lineSegmentPurchase() {
points = Number(points);
line_segments = Number(line_segments);
if (Number(points) >= line_segment_price) {
points -= line_segment_price;
line_segments += 1;
}
}
function frame() {
points = Number(points);
line_segments = Number(line_segments);
points += points_per_sec / 20;
}
let frame_interval = setInterval(frame, 50);
function saving() {
save('pointsL',points);
save('line_segmentsL',line_segments);
}
let saving_interval = setInterval(saving, 1000);
And I constantly have errors and mistakes. (this is just the most recent, I've been changing it over and over with no avail). Sometimes it reloads and my points are just completely blank, and always when I click my button to buy a line segment, it takes four to five clicks to register, and then it sometimes makes the price go to Infinity or NaN.
As you can see, I've got my code absolutely littered with Number() functions and I feel like it isn't helping and I'm not sure why these glitches keep occurring. I'm certain there's just some method I'm overlooking, but I can't figure it out.
A: You can not. As documentation of Storage.getItem() return value state:
A DOMString containing the value of the key. If the key does not exist, null is returned.
| |
doc_443
|
This is displayed in a <pre> element this way:
<div ng-controller="responseController">
<span class="status-{{response.status}}">{{response.code}} {{response.description}}</span>
<pre>{{response.data}}</pre>
<p id="responseHeaders">Response headers:</p>
<table>
<tr ng-repeat="header in response.headers">
<td><a href="#" ng-click="addToHeaders(header)">{{header.name}}</a></td>
<td><span>{{header.value}}</span></td>
</tr>
</table>
</div>
What I want is to have all the URL's that are received in JSON clickable, so I could hang a ng-click on them and go on with next steps. But I can't do it in a <pre> element.
Any ideas how this can be solved? Every useful answer is highly appreciated and evaluated.
Thank you.
A: You will need to replace all URLs within the response body with links.
Take a look at this answer.
You have some libraries there that will solve your problem.
Autolinker.js seems like a good choice.
A: You can achieve this using a directive (here's an example):
.directive('jsonLink', function() {
var hrefLinks=function (obj, pretty) {
var space = pretty || '';
var html = '';
$.each(obj, function(key, val) {
if ($.isPlainObject(val)) {
html += key + ': <br>';
html += hrefLinks(val, space + ' ');
} else if (key === 'href') {
html += space + 'LINK: <a href="' + val + '">' + val + '</a><br>';
} else {
html += space + key + ': ' + val + '<br>';
}
});
return html;
}
return {
restrict: 'E',
template: '<div></div>',
replace: true,
scope: {
obj: '='
},
link: function(scope, element, attr) {
element.html(hrefLinks(scope.obj));
}
};
})
Then drop this in your HTML
<json-link obj="objWithLinks"></json-link>
| |
doc_444
|
Before submitting Im able to get the values passed in the HTML form using
app.use(express.bodyParser());
var reqBody = req.body;
How can I read the output from the same HTML page after the submit button click.
A: Consider you have the following form:
<form id="register"action="/register" method="post">
<input type="text" name="first_name"/>
<input type="text" name="last_name"/>
<input type="text" name="email"/>
<input type="submit" value="register"/>
</form>
Your client side JavaScript could look like this:
var form = document.getElementById("register");
form.addEventListener("submit", function() {
// ajax call
// prevent the submit
return false;
});
On server side you would be able to access the form data:
app.post("/register", function(req, res) {
var user = {
first_name : req.body.first_name,
last_name : req.body.last_name,
email : req.body.email
};
});
For further reading: How to prevent form from being submitted?
A: You can send the response as json data from node.js to HTML page and use it in AJAX success callback.
node.js:
res.send(resObj);
HTML:
$("#form").submit(function () {
$.ajax({
type: "POST",
url: 'url',
data: formData,
success: function (data) {
data //contains response data
}
});
});
| |
doc_445
|
Xml:
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
Code:
public class Activity_Retailers extends Activity {
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.webview_activity);
WebView webview = (WebView)findViewById(R.id.webview);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDatabaseEnabled(true);
webview.loadUrl("http://www.facebook.com");
webview.setWebViewClient(new WebViewClient());
}
Help me out guys thanks a lot
A: Set WebViewClient to your WebView in java-code and owerride shouldOwerrideUrlLoading() method.
myWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
});
A: Try following code,
public class Main extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.webview = (WebView)findViewById(R.string.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(Main.this, "WebView Example", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl("http://www.google.com");
}
}
| |
doc_446
|
*
*Update a hidden field with the UserID
*Update '#MessageTo' with the full name
I believe I need to use .result, but I can't figure out the syntax. Please note that I'm using ASMX so I must do a post (don't want to enable security risk)
$("#MessageTo").autocomplete({
dataType: "json",
autoFocus: true,
minLength: 3,
source: function (request, response) {
var postParams = "{ pattern: '" + $("#MessageTo").val() + "' }";
return jQuery_1_7_1.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/Services/Users.asmx/GetNames',
data: postParams,
dataType: "json",
success: function (data) {
response($.map(data.d.Users, function (c) {
return {
label: c.FullName,
value: c.UserID
};
}));
}
});
}
});
I see some similar posts but not in conjunction with ASMX.
A: I believe you are interested in updating other HTML elements on the page, when the user selects something from an autocomplete-enabled textbox - is that right?
The code you have above probably works already, to provide autocomplete "suggestions" as the user types. If I understand correctly, You want to update a few fields after the user accepts one of the suggestion.s
To do that, use the select member of the autocomplete options.
$("#MessageTo")
.autocomplete({
dataType: "json",
autoFocus: true,
minLength: 3,
source: function (request, response) {
var postParams = "{ pattern: '" + $("#MessageTo").val() + "' }";
return jQuery_1_7_1.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/Services/Users.asmx/GetNames',
data: postParams,
dataType: "json",
success: function (data) {
response($.map(data.d.Users, function (c) {
return {
label: c.FullName,
value: c.UserID
};
}));
}
});
},
select: function (event, ui) {
var v = ui.item.value;
$('#MessageTo').html("Something here" + v);
$('#Hidden1').html("Something else here" + v);
// update what is displayed in the textbox
this.value = v;
return false;
}
});
Also: your use of ASMX is irrelevant. From the perspective of autocomplete, it's just a source for data. Also, the use of POST is irrelevant. It is possible to configure ASMX on the server side to allow HTTP GET. It's not a security hole if you enable it. It's just a different way of accepting requests.
The autocomplete box cannot tell if the server side is ASMX or Python, or ASP-classic, or PHP, or anything else. If I have understood the question correctly, your comment that I see some similar posts but not in conjunction with ASMX is irrelevant.
A: You are correct that you want to use the select configuration option - the values you want are passed to your custom function as ui.item.value and ui.item.label. You can return false to prevent the default behaviour and access the target element using this. i.e.
$("#MessageTo").autocomplete({
/* Existing code is all OK */
select: function (event, ui) {
// Set autocomplete element to display the label
this.value = ui.item.label;
// Store value in hidden field
$('#hidden_field').val(ui.item.value);
// Prevent default behaviour
return false;
}
});
| |
doc_447
|
A: *
*Check Error Handling
here
*Validation here
*for further help check asp.net/mvc
| |
doc_448
|
When I update my variable with a view and get, post controller, everything is working.
View test.cshtml
...
<form id="frm" method="post">
<input type="hidden" name="foo" value="OK"/>
<button type="submit">Submit</button>
</form>
...
Controller
public ActionResult test()
{
return View();
}
[HttpPost]
public ActionResult test(Formcollection fc)
{
Session["foo"] = "UPDATED AT " + DateTime.Now;
return View();
}
Like this, session["foo"] is readable and reachable in all the project with its updated value. This method works.
The problem is that when I want to POST my DATA with javascript fetch, I can reach my controller HttpPost Test (see above), certify that the variable Session["foo"] is well updated in debugger mode,
but Session["foo"] is not updated in all other part of my project..(other views and controllers).?
It seems as the 2 methods doesnt work on the same variable .
Please can someone help me ?
Here is the js fetch code run by a click button in test view.
async function PostDataFoo() {
fd = new FormData();
fd.append('foo','UPDATED AT ' + Date());
const res = await fetch("/test", {
method: "POST",
body: fd
});
alert('The end');
}
| |
doc_449
| ||
doc_450
|
Log Message:
Dependency on build [esb_build], number [LATEST], pattern [esb-local:/files/develop/SearchAPI_Lib/*.zip] - [0] results found.
The esb_build is the name of the Jenkins Job that build the artifact and pushed it to artifactory.
Resolved Artifact pattern:
esb-local:files/develop/SearchAPI_Lib/*.zip@esb_build#LATEST=>${WORKSPACE}
Any ideas what I am doing wrong as to why it is not being found?
| |
doc_451
|
Update block:
$sql="SELECT * FROM $tbl_name ORDER BY id ASC";
$result=mysql_query($sql);
// Count table rows
$size=mysql_num_rows($result);
$i = 0;
while ($i < $size) {
$name = $_POST['name'][$i];
$phone = $_POST['phone'][$i];
$email = $_POST['email'][$i];
$jan1 = $_POST['jan1'][$i];
.
.
$dues1 = $_POST['dues1'][$i];
.
.
$id = $_POST['id'][$i];
$query = "UPDATE $tbl_name SET name = '$name', phone = '$phone', email = '$email', jan1 = '$jan1', feb2 = '$feb2', mar3 = '$mar3', apr4 = '$apr4', may5 = '$may5', jun6 = '$jun6', jul7 = '$jul7', aug8 = '$aug8', sep9 = '$sep9', oct10 = '$oct10', nov11 = '$nov11', dec12 = '$dec12', dues1 = '$dues1', dues2 = '$dues2', dues3 = '$dues3', dues4 = '$dues4', dues5 = '$dues5', dues6 = '$dues6', dues7 = '$dues7', dues8 = '$dues8', dues9 = '$dues9', dues10 = '$dues10', dues11 = '$dues11', dues12 = '$dues12' WHERE id = '$id'";
//Just to see what's neing updated....
echo "UPDATE $tbl_name SET name = '$name', phone = '$phone', email = '$email', jan1 = '$jan1', feb2 = '$feb2', mar3 = '$mar3', apr4 = '$apr4', may5 = '$may5', jun6 = '$jun6', jul7 = '$jul7', aug8 = '$aug8', sep9 = '$sep9', oct10 = '$oct10', nov11 = '$nov11', dec12 = '$dec12', dues1 = '$dues1', dues2 = '$dues2', dues3 = '$dues3', dues4 = '$dues4', dues5 = '$dues5', dues6 = '$dues6', dues7 = '$dues7', dues8 = '$dues8', dues9 = '$dues9', dues10 = '$dues10', dues11 = '$dues11', dues12 = '$dues12' WHERE id = '$id'";
echo "<hr>";
mysql_query($query) or die ("Error in query: $query");
++$i;
}
//header('Location: allselect.php');
?>
My echo shows good update up to record 57. Record 58 is partially ok. The rest (up to 85) NOTHING.
UPDATE rollcalltest SET name = '*-Wise ', phone = 'XXX-XXX-XXXX', email = '**@gmail.com', jan1 = '1', feb2 = '1', mar3 = '', apr4 = '1', may5 = '1', jun6 = '1', jul7 = '', aug8 = '', sep9 = '', oct10 = '', nov11 = '', dec12 = '', dues1 = '0', dues2 = '0', dues3 = '', dues4 = '', dues5 = '', dues6 = '', dues7 = '', dues8 = '', dues9 = '', dues10 = '', dues11 = '', dues12 = '' WHERE id = '58'
UPDATE rollcalltest SET name = '', phone = '', email = '', jan1 = '', feb2 = '', mar3 = '', apr4 = '', may5 = '', jun6 = '', jul7 = '', aug8 = '', sep9 = '', oct10 = '', nov11 = '', dec12 = '', dues1 = '', dues2 = '', dues3 = '', dues4 = '', dues5 = '', dues6 = '', dues7 = '', dues8 = '', dues9 = '', dues10 = '', dues11 = '', dues12 = '' WHERE id = ''
I am going crazy. Ideas?
| |
doc_452
|
The recommended way to use this utility is by adding an alias (C shell)
or shell function (Bourne shell) like the following:
which()
{
(alias; declare -f) | /usr/bin/which --tty-only --read-alias --read-functions --show-tilde --show-dot $@
}
export -f which
Unlike /usr/bin/which which only finds commands, this function finds commands, aliases and functions. My question is why is (alias; declare -f) being piped into /usr/bin/which $@?
A: /usr/bin/which is not built into the shell. Consequently, it has no way to access shell-internal state (like aliases or function definitions) unless that content is fed into it.
That's what's being done here.
However, that's completely unnecessary on any modern shell. Feeding shell syntax info an external program to be parsed there is innately unreliable compared to having the shell itself give you the output you need.
Don't do this. Use the shell built-in type instead.
| |
doc_453
|
Here is my class.
public class Customer
{
public Customer(int id, string name)
{
ID = id;
Name = name;
}
public Customer(int id, string name, int age)
{
ID = id;
Name = name;
Age = age;
}
int Id {get; set}
string Name {get; set}
int Age {get; set}
}
and here are Apis in the Controller class
Customer GetCustomerById(int id)
{
var customer = GetCustomerData();
// I want to return only Id and Name, but it is returning age also with value 0
return new Customer(customer.id, customer.Name);
}
List<Customer> GetCustomerByName(string name)
{
var customers = GetCustomerDataByName(name);
// Over here I need all three properties, hence I am not using JsonIgnore on Age Property
return customers.Select(x => new Customer(x.id, x.name, x.age)).ToList();
}
A: You can change the age properly to be nullable int?. And then configure the json converter to ignore null params:
services.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});
for more info look here.
| |
doc_454
|
PatientId Payor
0 PAT10000 [Cash, Britam]
1 PAT10001 [Madison, Cash]
2 PAT10002 [Cash]
3 PAT10003 [Cash, Madison, Resolution]
4 PAT10004 [CIC Corporate, Cash]
I want to remove the square brackets and filter all patients who used at least a certain mode of payment eg madison then obtain their ID. Please help.
A: let's say, your data frame variable initialized as "df" and after removing square brackets, you want to filter all elements containing "Madison" under "Payor" column
df.replace({'[':''}, regex = True)
df.replace({']':''}, regex = True)
filteredDf = df.loc[df['Payor'].str.contains("Madison")]
print(filteredDf)
A: This will generate a list of tuples (id, payor). (df is the dataframe)
payment = 'Madison'
ids = [(id, df.Payor[i][1:-1]) for i, id in enumerate(df.PatientId) if payment in df.Payor[i]]
| |
doc_455
|
I'm building a website using Wordpress, and using Elementor. So in this Elementor plugin, there's a function to build form, capture it and sent to our chosen email.
Currently I want to build a registration page that contain a form. The form will contain basic requirement such as name, age, address etc. So when a person fills the form, it will automatically be captured by the system and sent to our chosen email.
The problem is, I want to put numbering to each registration made on the form sent to the email. Example: After a user has fill the form, I got an email stating that there was a new registration. I want in the headline or subject to have a registration number such as 'Registration No 221' , then the next user who gonna fill the form and the system sent it to us, will receive an email at his side stating that 'Your registration No is 222. Please wait for us to call you'. Meanwhile in our email, I want an email stating that 'New Registration Available: Registration No 222'. This is an automated email sent by the system.
I want to have fully control on how the registration number start. So I can change it to start at number 500, then reset it to another number such as 356 or something else.
I know a bit PHP but not too much. Is there any guide here how can I create this features? Thanks in advance.
A: I'm not sure what database you are using but I think would be best for you to create a table with an auto increment field and use that as your registration ID. This way you aren't in danger of re-using the same number for multiple users.
mysql
https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html
sql server
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-2017
postgres
http://www.postgresqltutorial.com/postgresql-serial/
Alternatively you could just create a number var in php and increment it each time registration occurs. That would give you the ability to change it whenever you would like, but could result in duplicates.
$regNum = 356;
function submitForm() {
// code...
$regNum++;
}
| |
doc_456
|
def insert_symbol(self, name, group, internal):
# get the parent object, insert if not existent
group = self.insert_group(group)
# append to list of childs in this parent
group.symbols.append(Symbol(name=name, internal=internal))
# child is correct!
print group.symbols[0]
# nothing in here?!
print self.__session.dirty
# nothing to commit?!
self.__session.commit()
The definition of the relationship is listed here:
class Group(Base):
__tablename__ = 'assets_symbolgroup'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(100), unique=True, nullable=False)
symbols = relationship("Symbol", backref="group")
def __repr__(self):
return "<Group(name='{0}')>".format(self.name)
class Symbol(Base):
__tablename__ = 'assets_symbol'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(100), unique=True, nullable=False)
group_id = Column(Integer, ForeignKey('assets_symbolgroup.id'), nullable=False)
alive = Column(BOOLEAN, default=True, nullable=False)
internal = Column(String(100))
@property
def summary(self):
return {"name": self.name, "group": self.group.name, "internal": self.internal}
def __repr__(self):
return "<Asset(name='{0}', group='{1}')>".format(self.name, self.group)
What's the best way to add a child without rewriting the parent?
Thank you for your help
Thomas
| |
doc_457
|
I think we should use vsto and XML.
Please let me know if you have a sample source to underline.
A: In VBA, you might use:
Dim Rng As Range
For Each Rng In ActiveDocument.Range.SpellingErrors
Rng.Font.Underline = wdUnderlineSingle
Rng.Font.UnderlineColor = wdColorRed
Next
I'll leave you to do any adaptations.
| |
doc_458
|
The introduction to Kung's algorithm I'm referring to can be found here https://engineering.purdue.edu/~sudhoff/ee630/Lecture09.pdf
I'd really appreciate some help with making my code use less memory (it always fails in the "solve" function) and perhaps function better/more correctly. Kung's algorithm is completely recursive by nature, but I'm sure there are better ways than I'm doing it now. Here's what I have!
using PyPlot
function read_graph_data(fname)
f=open(fname)
arr=readdlm(f, ',', Float64, header=true)
close(f)
return arr
end
function solve(data)
if size(data, 1) == 1
return Set(data)
else
T= solve(data[1:convert(Int64, floor(size(data,1)/2))])
B= solve(data[convert(Int64, ceil(size(data,1)/2)): size(data,1)])
for (b in B)
for (t in T)
if (b.>t == all_true)
setdiff!(T, b)
continue
end
if b.>t == all_false
continue
end
end
push!(T, b)
end
return T
end
end
num_obj = 2
all_true = (trues(num_obj))
all_false = transpose(falses(num_obj))
data = first(read_graph_data("Lake-Problem-Reference-Set.csv"))
data[:, 1] *= -1
data = data[:, 1:num_obj]
solve(data)
| |
doc_459
|
const data = {
key1: '1',
key2: '2',
key3: { key4: '4' },
key5: [
{
key6: '6',
key7: '7',
},
{
key8: '8',
key9: '9',
}
]
}
const countKeys = (data) => {
let count = 0;
const helper = (data) => {
for (let value of Object.values(data)) {
if (typeof value === 'object') {
helper(value);
}
// this line is problematic as it counts each object in the array as key.
if (!Array.isArray(value)) count++;
}
}
helper(data)
return count;
}
console.log(countKeys(data)) // 10, correct answer is 9
I try to wrap my head around for many hours but couldn't get the solution. Can anyone explain me what I'm missing here and supposed to add to make it work?
A: For the data provided, there are nine (9) keys. You could use a recursive countKeys(t) and do a type analysis on t's type -
*
*When it's an Object, for all v in Object.values(t), reduce and count one plus the recursive result, countKeys(v)
*When it's an Array, for all v in t, sum countKeys(v)
*Otherwise t is neither an Object nor an Array, return zero
function countKeys(t) {
switch (t?.constructor) {
case Object: // 1
return Object
.values(t)
.reduce((r, v) => r + 1 + countKeys(v), 0)
case Array: // 2
return t
.reduce((r, v) => r + countKeys(v), 0)
default: // 3
return 0
}
}
const data =
{key1:"1",key2:"2",key3:{key4:"4"},key5:[{key6:"6",key7:"7"},{key8:"8",key9:"9"}]}
console.log(countKeys(data))
| |
doc_460
|
Considering all this. I have two 'projects' (a, b). In project 'a', I have a repo called 'arepo'. 'arepo' have a branch 'abranch'. Similarly, there is project 'b'. project 'b' has a repo called 'brepo'. 'brepo' has a branch called 'bbranch'.
The following picture depicts the situation:-
In this situation can we merge "abranch" and "bbranch" using "allow-unrelated-histories" option of GIT Merge?
Thanks in advance.
A: From here it says:
--allow-unrelated-histories By default, git merge command refuses to merge histories that do not share a common ancestor. This option can
be used to override this safety when merging histories of two projects
that started their lives independently. As that is a very rare
occasion, no configuration variable to enable this by default exists
and will not be added.
So it would appear that it is possible to merge unrelated histories by using the --allow-unrelated-histories option.
| |
doc_461
|
client = "192.168.10.1"
server = "192.168.10.5"
client_port = 5061
server_port = 5060
rtp = {
"sequence": 1,
"timestamp": 1,
"marker": 1,
"payload_type": 17
}
pkt= Ether()/IP(src=client, dst=server)/UDP(sport=client_port, dport=server_port)/RTP(**rtp)
wrpcap("rtp_pkt.pcap",pkt)
The problem is that I see the packet as UDP in wireshark and not RTP. I can see it with SIP structures so I don't know where is the problem,
A: In short - Wireshark shows you UDP, because there's no SIP/SDP packets. These packets initiate connection session and Wireshark then can follow the stream and decode UDP to RTP. In SIP/SDP you can find main information: From, To, Media type etc. (RFC 4566 SDP, RFC3621 SIP). So even if you build ideal RTP packet with scapy, without session initiation Wireshark will always decode it as UDP.
EDIT:
By the way, use bind_layers(UDP, RTP, dport=*) in scapy to bind UDP packets with RTP, might help
A: You can tell Wireshark to decode a port number as a particular protocol by using the -d option. e.g to decode the above packet as RTP use:
wireshark -d udp.port==5060,rtp rtp_pkt.pcap
Though if you're going to create an RTP packet you should try to avoid using well know part numbers such as 5060 (which usually maps to the SIP protocol - which is why Wireshark tries to decode it as such).
| |
doc_462
|
A: I would not package the media files in the app itself. It would be better to put the media files on a server and have the app download the media files to the sdcard. This is a common thing for Android apps to do. If you install that large of an app, that means you have much less room to install other apps. If you have users other than yourself, they will despise that the app is so large.
Another option, is to install Froyo on the Nexus One and alter the app so it can be installed on the sd card.
| |
doc_463
|
Here is my click function of first page:
function quiz(){
$("#secondlist").show();
window.location = "second.jsp"
}
This is my list:
<div id="sample" class="content" style="display: none">
<ul class="tabs">
<li id="tab4"><a href="javascript:quiz()">Quiz</a></li>
</ui></div>
and second page div:
<div id="secondlist" style="display: none">
<h3>sample</h3>
</div>
Could you please help anyone:
A: When you change window location you will clear the page.
Instead do
function quiz(){
$("#sample").load("second.jsp #secondlist",function(){
$(#secondlist").show();
});
}
Alternative is this (but then display = none needs to be removed)
window.location="second.jsp#secondlist"; // note the lack of space before #
Lastly please change
<li id="tab4"><a href="javascript:quiz()">Quiz</a></li>
to
<li id="tab4"><a id="quiz" href="second.jsp#secondlist">Quiz</a></li>
and the code to
$(function() {
$("#quiz").on("click",function(e) {
e.preventDefault(); // stop the link from changing page
var href = this.href.split("#"), fragment = href[0]+" #"+href[1];
$("#sample").load(fragment,function(){
$(#secondlist").show();
});
});
});
| |
doc_464
|
o.s.s.c.bcrypt.BCryptPasswordEncoder : Empty encoded password
It seems like an obvious problem, but permit me, I just can't figure it our after many attempts.
My SecurityConfig class is ...
@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
CustomUserDetailsService userDetailsService;
@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
}
This is my UserServiceDetails Service.
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository repo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<Owner> optionalUser = repo.findByUsername(username);
optionalUser
.orElseThrow(() -> new UsernameNotFoundException("Username not
found"));
return optionalUser
.map(CustomUserDetails::new).get();
}
}
I do also have the following bean configured
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}
}
This is my userService.
public class CustomUserDetails extends Owner implements UserDetails {
public CustomUserDetails(final Owner owner) {
super();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_"+getRoles()))
.collect(Collectors.toList());
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
I surely must be missing something, but I can't seem to figure it out. From HttpRequest, I know that the password is being posted to the System, as I logged.
A: I found out that the OptionalUser is not mapping correctly into the UserDetail object, thereby returning a new and empty UserDetail object. the following code is wrong.
return optionalUser
.map(CustomUserDetails::new).get();
}
So I my new UserDetailsService class is ...
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository repo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
Optional<Owner> optionalUser = repo.findByUsername(username);
Owner user = optionalUser.get();
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user));
}
public Collection<? extends GrantedAuthority> getAuthorities(Owner user) {
return user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_"+user.getRoles()))
.collect(Collectors.toList());
}
}
| |
doc_465
|
here i went into my remote repo on my flashdrive to see which branch i was on and looked at the log. Then i went back into my working copy local repo, edited a file, added that file, made a commit and attempted to push it my flashdrive but it didn't work. Can any tell what i'm doing wrong?
David-Adamss-MacBook-Pro:~ davidadams$ cd /volumes/thumbdrive/repo/releventz
David-Adamss-MacBook-Pro:releventz davidadams$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 2 commits.
#
nothing to commit (working directory clean)
David-Adamss-MacBook-Pro:releventz davidadams$ git branch
* master
David-Adamss-MacBook-Pro:releventz davidadams$ git log
commit 65328c9603f62b7a2058f38fb441605b0c4c431e
Author: David Adams <[email protected]>
Date: Wed Jun 29 23:30:40 2011 -0500
third commit
commit b3883fa933609db634b98d747299c1e9c96e8269
Author: David Adams <[email protected]>
Date: Wed Jun 29 23:10:53 2011 -0500
second commit
commit 54832381a6fe898408c9e07bc8409a2982ec6274
Author: David Adams <[email protected]>
Date: Wed Jun 29 22:20:04 2011 -0500
changed checklist.php
commit 1955664689313a589543576477e0a134f26cc313
Author: David Adams <[email protected]>
Date: Wed Jun 29 22:12:53 2011 -0500
first releventz commit
David-Adamss-MacBook-Pro:releventz davidadams$ cd
David-Adamss-MacBook-Pro:~ davidadams$ cd
David-Adamss-MacBook-Pro:~ davidadams$ cd /applications/mamp/htdocs/releventz
David-Adamss-MacBook-Pro:releventz davidadams$ git status
# On branch master
nothing to commit (working directory clean)
David-Adamss-MacBook-Pro:releventz davidadams$ git status
# On branch master
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: application/libraries/calendarclass.php
#
no changes added to commit (use "git add" and/or "git commit -a")
David-Adamss-MacBook-Pro:releventz davidadams$ git add .
David-Adamss-MacBook-Pro:releventz davidadams$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: application/libraries/calendarclass.php
#
David-Adamss-MacBook-Pro:releventz davidadams$ git commit -m 'blah blah'
[master 853232d] blah blah
1 files changed, 1 insertions(+), 1 deletions(-)
David-Adamss-MacBook-Pro:releventz davidadams$ git push flashdrive master
Counting objects: 17, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (12/12), done.
Writing objects: 100% (12/12), 1.89 KiB, done.
Total 12 (delta 8), reused 0 (delta 0)
Unpacking objects: 100% (12/12), done.
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable t
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing int
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in som
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, se
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
gTo /volumes/thumbdrive/repo/releventz
! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to '/volumes/thumbdrive/repo/releventz'
A: You're not allowed to push to another repository that has checked out code. Git is refusing to update it.
If you really need a backup repo on the flash drive and you'll never edit things in it, then make it a bare repo instead.
If you are using it as a second location to edit things, then go into that repo and pull from your disk-based one instead. IE, always pull into an actively used repository, and never push.
[yes you can get around this, but you shouldn't]
A: Today i had the same error.and i fix it whit method like Bill Door's answer.
Maybe you can do like this:
David-Adamss-MacBook-Pro:~ davidadams$ cd /volumes/thumbdrive/repo/releventz
David-Adamss-MacBook-Pro:~ davidadams$ git checkout subbranch
David-Adamss-MacBook-Pro:~ davidadams$ cd /applications/mamp/htdocs/releventz
David-Adamss-MacBook-Pro:~ davidadams$ git push flashdrive master
A: Wes has offered two good answers. Another solution is to create a second branch. Go to your source repository and checkout the second branch. You can now push to the master branch from you work repository.
cd master_repo
git checkout -b stepaside
cd work_repo
git push
Subsequent pushes you can replace with
cd master_repo
git checkout stepaside
cd work_repo
git push
A: Another option is to not have the full non-bare (or even bare) repo on the flashdrive (because it involves being sure that a lot of files are properly copied on a remote storage device), but to have or to update a bundle.
A git bundle is one file (much easier to copy over an USB drive).
And you can pull from that one file, in order to recreate a full-fledged repo anywhere you need to.
See "How to synchronize two git repositories" as an illustration.
| |
doc_466
|
Id A B C D
1 a b c d
2 a b d
2 a c d
3 a d
3 a b c
I want to aggregate the empty values for the columns B-C and D, using the values contained in the other rows, by using the information for the same Id.
The resulting data frame should be the following:
Id A B C D
1 a b c d
2 a b c d
3 a b c d
There can be the possibility to have different values in the first column (A), for the same Id. In this case instead of putting the first instance I prefer to put another value indicating this event.
So for e.g.
Id A B C D
1 a b c d
2 a b d
2 x c d
It becomes:
Id A B C D
1 a b c d
2 f b c d
A: IIUC, you can use groupby_agg:
>>> df.groupby('Id')
.agg({'A': lambda x: x.iloc[0] if len(x.unique()) == 1 else 'f',
'B': 'first', 'C': 'first', 'D': 'first'})
A B C D
Id
1 a b c d
2 f b c d
A: The best way I can think to do this is to iterate through each unique Id, slicing it out of the original dataframe, and constructing a new row as a product of merging the relevant rows:
def aggregate(df):
ids = df['Id'].unique()
rows = []
for id in ids:
relevant = df[df['Id'] == id]
newrow = {c: "" for c in df.columns}
for _, row in relevant.iterrows():
for col in newrow:
if row[col]:
if len(newrow[col]):
if newrow[col][-1] == row[col]:
continue
newrow[col] += row[col]
rows.append(newrow)
return pd.DataFrame(rows)
| |
doc_467
|
*
*set statusline=%{s:MyFunc()}
*set statusline=%!s:MyFunc()
Both produce the following error pair.
*
*E120: Using <SID> not in a script context: <SID>:MyFunc
*E15: Invalid expression: <SID>:MyFunc()
I have s:MyFunc() defined in the same file where I'm trying to set statusline.
When I make the function global (s:MyFunc replaced by MyFunc everywhere in the file), there are no errors, and statusline is set properly. Hence this question.
Note that replacing s: with <SID>: did not help.
A: statusline is not evaluated within the context of a script so trying to use a function from the local script with s: will always fail.
s: means that the given symbol is local to the script, not static, and so you will need to use another way of identifying the function. See :help E738 for a list of the possible symbol modifiers.
This, as you have stated in the question, will indeed work:
function MyFunc()
return "Hello World"
endfunction
set statusline=%!MyFunc()
A: Don Cruickshank's explanation is correct. Here are some possible solutions that are better than defining a global function (though that would work, too, especially if you prefix the name with the script's name to make it unique):
*
*Define and use an autoload function to localize the function; this can also be done in a plugin/myscript.vim, too, not necessarily in autoload/myscript.vim. E.g. function myscript#MyStatuslineFunc()
*To use a script-local function, you need to make the translation of s: into the actual <SNR>NNN_FuncName (what mappings do automatically when you use <SID>) yourself:
function! s:function(name)
return substitute(a:name, '^s:', matchstr(expand('<sfile>'), '<SNR>\d\+_\zefunction$'),'')
endfunction
let &statusline = '%!' . s:function('s:MyFunc()')
| |
doc_468
|
Note: I am using Carl Edward Rasmussen's minimize function for maximization of the negative f.
Note 2: The test data I am using is the Wine dataset available at the UCI Machine Learning repository.
A: With some external help, I've got the answer to the question. The problem was that I was assuming wrongly that vector product of the difference of datapoints i and j should be a row vector by column vector instead of the opposite:
| |
doc_469
|
The data is obtained from an observable stream that is the result of a REST request for projects. The data is obtained as Observable<Project[]>.
const project1: Project = {
id: 1,
title: 'zebra',
rootId: 1,
}
const project2: Project = {
id: 2,
title: 'algebra',
rootId: 2,
}
const project3: Project = {
id: 3,
title: 'Bobcats',
rootId: 1,
}
const project4: Project = {
id: 4,
rootId: 2,
}
const project5: Project = {
id: 5,
title: 'Marigolds',
rootId: 1,
}
const project6: Project = {
id: 6,
title: 'whatever',
rootId: null,
}
const project7: Project = {
id: 7,
title: 'peppercorns',
rootId: null,
}
let groupProjects: Observable<ProjectSummary[]>
= getGroupProjects(of([project1, project2, project3, project4, project5, project6, project7]]));
getGroupProjects(projects$: Observable<ProjectSummary[]>): Observable<ProjectSummary[]> {
const timer$ = timer(5000);
const data = projects$.pipe(takeUntil(timer$), flatMap(projects => projects));
const groupedObservables = data.pipe(
groupBy(projects => projects.rootId),
tap( a => console.log('groupBy:' + a.key))
);
const merged = groupedObservables.pipe(
mergeMap(a => a.pipe(toArray())),
shareReplay(1),
tap( a => console.log('final:' + JSON.stringify(a)))
);
return merged;
}
The desired output is:
Object{ //Root of 1
id: 1,
title: 'zebra',
rootId: null
}
Object{
id: 3, //child of 1
title: 'Bobcats',
rootId: 1
}
Object{
id: 5, //child of 1
title: 'Marigolds',
rootId: 1
}
Object{
id: 2, //root of 2
title: 'algebra',
rootId: 2
}
Object{
id: 4, //child of 2
title: 'dogs',
rootId: 2
}
Object{
id: 6, //unaffiliated
title: 'whatever',
rootId: null
}
Object{
id: 7, //unaffiliated
title: 'peppercorns',
rootId: null
}
The requirement is that groups identified by rootId appear in sequence before their children (children appear after their root) and unaffiliated are listed together. roots are identified when id = rootId, children are identified when rootId != null && id != rootId. Unaffiliated are identified by null root id.
Currently only the last group is emitted. How can I return an observable that emits all groups and in correct sequence? --thanks
A: groupBy takes a stream of objects and emits a single group when the stream completes, it doesn't work with streams of arrays. What you want is a scan. Scan is like a reduce but it emits each time the source stream emits rather than once at the end.
I am not quite understanding what you are trying to achieve from you question but this should get you started
sourceThatEmitsArrays.pipe(
scan(
(results, emittedArray) => functionThatAddsEmittedArrayToResults(results, emittedArray),
[] // Start with an empty array
)
)
This is the same as a normal reduce function on arrays but emits results each time the source emits.
functionThatAddsEmittedArrayToResults would looks something like
(results, array) => array.reduce(
(newResults, current) => {
const group = findCurrentGroupInNewResultsOrCreateNewGroup(newResults, current);
replacePreviousGroupInResultsOrAddTheNewOne(newResults, group);
return newResults;
},
results // Start with previous results
)
| |
doc_470
|
"You'll need to ensure that the form is permanently set with a DreamHost
hosted email address so that this form works properly and isn't rejected.
It may be set so that the person filling out the form is being set as the
'From', which will result in the rejection above.
Just edit the form so that the 'From' is permanently set to a DH user so
that the form is no longer rejected due to policy reasons."
What changes do I need to make to the below code to make this acceptable to Dreamhost? Any help would be greatly appreciated.
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "[email protected]";
$email_subject = "Quiz";
$your_email = "[email protected]";
function died($error) {
// your error code can go here
echo "<p>We are very sorry, but there were error(s) found with the form you submitted.</p> ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "<p>Please go back and fix these errors.<br /><br /></p>";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$address = $_POST['address']; // not required
$city = $_POST['city']; // not required
$state = $_POST['state']; // not required
$vehicleyear = $_POST['vehicleyear']; // not required
$vehiclemake = $_POST['vehiclemake']; // not required
$vehiclemodel = $_POST['vehiclemodel']; // not required
$purchase_or_lease = $_POST['purchase_or_lease']; // not required
$deliverydate = $_POST['deliverydate']; // not required
$mileage_at_delivery = $_POST['mileage_at_delivery']; // not required
$current_mileage = $_POST['current_mileage']; // not required
$seller = $_POST['seller']; // not required
$citystate = $_POST['citystate']; // not required
$Bank_Finance = $_POST['Bank_Finance']; // not required
$dealer_arranged = $_POST['dealer_arranged']; // not required
$employee_discount = $_POST['employee_discount']; // not required
$warranty = $_POST['warranty']; // not required
$length_contract = $_POST['length_contract']; // not required
$comments = $_POST['comments']; // not required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Address: ".clean_string($address)."\n";
$email_message .= "City: ".clean_string($city)."\n";
$email_message .= "State: ".clean_string($state)."\n";
$email_message .= "Vehicle Year: ".clean_string($vehicleyear)."\n";
$email_message .= "Make: ".clean_string($vehiclemake)."\n";
$email_message .= "Model: ".clean_string($vehiclemodel)."\n";
$email_message .= "Purchase or Lease: ".clean_string($purchase_or_lease)."\n";
$email_message .= "Delivery date: ".clean_string($deliverydate)."\n";
$email_message .= "Mileage at Delivery: ".clean_string($mileage_at_delivery)."\n";
$email_message .= "Current Mileage: ".clean_string($current_mileage)."\n";
$email_message .= "Selling Dealer: ".clean_string($seller)."\n";
$email_message .= "Seller City and State: ".clean_string($citystate)."\n";
$email_message .= "Bank or Finance Company: ".clean_string($Bank_Finance)."\n";
$email_message .= "Dealer Arranged: ".clean_string($dealer_arranged)."\n";
$email_message .= "Employee Discount? ".clean_string($employee_discount)."\n";
$email_message .= "Warranty: ".clean_string($warranty)."\n";
$email_message .= "Contract Terms: ".clean_string($length_contract)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: ' . $your_email . "\r\n";
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>
A: According to your hosting provider:
Just edit the form so that the 'From' is permanently set to a DH user
So if I were to guess, I suspect that the change you need to make is to modify the From header. This is where you set it:
$headers = 'From: ' . $your_email . "\r\n";
So set it to something else:
$headers = 'From: [email protected]' . "\r\n";
| |
doc_471
|
Problem: Receiving only None values in que_text_new column although regex pattern is thoroughly tested!
def override(s):
x = re.search(r'(an|frage(\s+ich)?)\s+d(i|ı)e\s+Staatsreg(i|ı)erung(.*)(Dresden(\.|,|\s+)?)?', str(s), flags = re.DOTALL | re.MULTILINE))
if x :
return x.group(5)
return None
df2['que_text_new'] = df2['que_text'].apply(override)
What am i doing wrong? removing return None doesent help. There must be some structural error within my function, i assume.
A: You can use a pattern with a single capturing group and then simpy use Series.str.extract and chain .fillna(np.nan) to fill the non-matched values with NaN:
pattern = r'(?s)(?:an|frage(?:\s+ich)?)\s+d[iı]e\s+Staatsreg[iı]erung(.*)'
df2['que_text_new'] = df2['que_text'].astype(str).str.extract(pattern).fillna(np.nan)
Not sure you need .astype(str), but there is str(s) in your code, so it might be safer with this part.
Here,
*
*Capturing groups with single char alternatives are converted to character classes, e.g. (i|ı) -> [iı]
*Other capturing groups are converted to non-capturing ones, i.e. ( -> (?:.
*To make np.nan work do not forget to import numpy as np.
*(?s) is an in-pattern re.DOTALL option.
| |
doc_472
|
What I need is something similar to the fingerprint identification methods but not as accurate. Since this is intended to run on the iPhone performance is a big issue here.
Example images:
alt text http://img25.imageshack.us/img25/303/294906.jpg
alt text http://img138.imageshack.us/img138/842/40248741fireworkexplosi.jpg
For those I would expect to have a correlation factor of about 0.5 since they are similar but differ in color. There are a number of different dimensions of comparison, but the basic ones are color and shape.
Any help will be greatly appreciated.
A: To answer (sort of) my own question, after days of googling, I found this. The basic idea is to test for images with offset/rotation, the search for a dominant color and so on. So far this is the best information I could find, so I will give it a try.
The code suggested there looks like this:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace BitmapSimilarity
{
public interface IBitmapCompare
{
double GetSimilarity(Bitmap a, Bitmap b);
}
class BitmapCompare: IBitmapCompare
{
public struct RGBdata
{
public int r;
public int g;
public int b;
public int GetLargest()
{
if(r>b)
{
if(r>g)
{
return 1;
}
else
{
return 2;
}
}
else
{
return 3;
}
}
}
private RGBdata ProcessBitmap(Bitmap a)
{
BitmapData bmpData = a.LockBits(new Rectangle(0,0,a.Width,a.Height),ImageLockMode.ReadOnly,PixelFormat.Format24bppRgb);
IntPtr ptr = bmpData.Scan0;
RGBdata data = new RGBdata();
unsafe
{
byte* p = (byte*)(void*)ptr;
int offset = bmpData.Stride - a.Width * 3;
int width = a.Width * 3;
for (int y = 0; y < a.Height; ++y)
{
for (int x = 0; x < width; ++x)
{
data.r += p[0]; //gets red values
data.g += p[1]; //gets green values
data.b += p[2]; //gets blue values
++p;
}
p += offset;
}
}
a.UnlockBits(bmpData);
return data;
}
public double GetSimilarity(Bitmap a, Bitmap b)
{
RGBdata dataA = ProcessBitmap(a);
RGBdata dataB = ProcessBitmap(b);
double result = 0;
int averageA = 0;
int averageB = 0;
int maxA = 0;
int maxB = 0;
maxA = ((a.Width * 3) * a.Height);
maxB = ((b.Width * 3) * b.Height);
switch (dataA.GetLargest()) //Find dominant color to compare
{
case 1:
{
averageA = Math.Abs(dataA.r / maxA);
averageB = Math.Abs(dataB.r / maxB);
result = (averageA - averageB) / 2;
break;
}
case 2:
{
averageA = Math.Abs(dataA.g / maxA);
averageB = Math.Abs(dataB.g / maxB);
result = (averageA - averageB) / 2;
break;
}
case 3:
{
averageA = Math.Abs(dataA.b / maxA);
averageB = Math.Abs(dataB.b / maxB);
result = (averageA - averageB) / 2;
break;
}
}
result = Math.Abs((result + 100) / 100);
if (result > 1.0)
{
result -= 1.0;
}
return result;
}
}
class Program
{
static BitmapCompare SimpleCompare;
static Bitmap searchImage;
static private void Line()
{
for (int x = 0; x < Console.BufferWidth; x++)
{
Console.Write("*");
}
}
static void CheckDirectory(string directory,double percentage,Bitmap sImage)
{
DirectoryInfo dir = new DirectoryInfo(directory);
FileInfo[] files = null;
try
{
files = dir.GetFiles("*.jpg");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Bad directory specified");
return;
}
double sim = 0;
foreach (FileInfo f in files)
{
sim = Math.Round(SimpleCompare.GetSimilarity(sImage, new Bitmap(f.FullName)),3);
if (sim >= percentage)
{
Console.WriteLine(f.Name);
Console.WriteLine("Match of: {0}", sim);
Line();
}
}
}
static void Main(string[] args)
{
SimpleCompare = new BitmapCompare();
Console.Write("Enter path to search image: ");
try
{
searchImage = new Bitmap(Console.ReadLine());
}
catch (ArgumentException)
{
Console.WriteLine("Bad file");
return;
}
Console.Write("Enter directory to scan: ");
string dir = Console.ReadLine();
Line();
CheckDirectory(dir, 0.95 , searchImage); //Display only images that match by 95%
}
}
}
| |
doc_473
|
std::stringstream os;
for (size_t i = 0U; i < len; i++) {
os << static_cast<uint32_t>(src[i]);
}
Warning is: "advisory Rule 14-8-2, Viable set contains both function
and template: std::basic_ostream::operator<<"
for the below line of code
os << static_cast<uint32_t>(src[i]);
Please suggest how to resolve the same, i am new to c++ and sure sure about the same.
A: The Misra warning is being triggered because basic_ostream defines a member operator<< which is a set of non-template overloads, and also a set of free function template versions. As the warning says, the candidate set for overload resolution includes both of these - function templates and non-templates.
Your options are to either suppress the warning for this line, or figure out a way to not use operator<< to perform formatted output. The latter can be done by creating an intermediate string representation of the number, and then using basic_ostream::write to output the characters. If you have a C++11 compiler, you can use std::to_string to do this.
auto s = std::to_string(42U);
std::stringstream ss;
ss.write(s.c_str(), s.size());
If you can't use to_string, or need additional formatting, there's always s(n)printf for creating the string representation.
My personal opinion is to suppress that warning, with the justification being that you're using a well defined and well known type from the standard library.
A: You are using a very general type: std::stringstream. Possible is
template<class charT, class traits, class T>
basic_ostream<charT,traits>& operator<< (basic_ostream<charT,traits>&& os, const T& val);
and also
ostream& operator<< (ostream& os, ...);
A: Herb Sutter has a great article about why this rule makes sense. It has to do with the specific order in which the C++ standard handles overloading resolution between template and non-template functions. The actual function chosen may not always follow the expectation of the programmer. Here is the link:
http://www.gotw.ca/publications/mill17.htm
Seems the STL has some mildly dangerous code in there.
| |
doc_474
|
*
*Which of the code fragments achieves that?
*How can I break my co-worker's code?
*Is a Blacklist just a Whitelist with the condition inverted?
My co-worker's Code:
objRegExp.Pattern= "[^-A-Za-z0-9'&(). ]"
if objRegExp.Test(strInput) then
FoundSpecialChar= true
exit function
end if
FoundSpecialChar= false
Set objRegExp = Nothing
My Code:
objRegExp.Pattern= "^[-A-Za-z0-9\s'&().]+"
if objRegExp.Test(strInput) then
FoundSpecialChar= false
exit function
end if
FoundSpecialChar= true
Set objRegExp = Nothing
A: Your colleague's approach lists the acceptable characters. If it finds even one character not in that list, it sets FoundSpecialChar= true which seems to be what you want. To test the difference between his code and yours, you could try to run both the code fragments with strInput = "ABCD#EFGH".
Running your code once with strInput = "A#" and another time with strInput = "#A" should help as well.
BTW, Set objRegExp = Nothing should be included before Exit Function as well.
A: I am from testing background and I've experienced that Whitelist approach is good from application developer point of view and Blacklist approach is good to test the application. The reason being, as a dev a Whitelist gives you control over the exact input that a user is allowed to enter. On the other hand, as a tester I would use the Blacklist approach more because it will have infinite number of options to test.
Interesting discussion on SO --> blacklisting vs whitelisting in form's input filtering and validation
| |
doc_475
|
Something like this is what I want:
constructor(private _modalApi: ModalApiService) {
_modalApi.isOpen$.subscribe(
modal => {
this.overflow = this.isOpen ? 'hidden' : 'visible';
}
)
}
@HostBinding('body.style.overflow')
overflow: string;
I realise that @HostBinding binds to the host element which in this case would be the modal, but since @HostListener can listen to the document, window etc I thought that there might be a similar use case here.
Is this possible or do I have to make some weird workaround?
Note that I've looked at other questions suggesting to put your app component on the body tag and then doing it via the app component, however, I can't rely on another component since the idea is that this component shouldn't know about any app's structure and still work.
A: This is not supported. As HostBinding indicates it binds to the host element of the component, not some arbitrary element.
The document:xxx, window:xxx, or body:xxx targets of the HostListener decorator is special.
You can use plain DOM access as a workaround or some other way to get an ElementRef and use the Renderer to apply styles or other settings.
| |
doc_476
|
app.ts
import express from 'express'
import bodyParser from 'body-parser'
import cors from 'cors'
import { UserRoute } from './components/user'
const App = () => {
const app = express()
app.use(bodyParser.json({ limit: "50mb" }))
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }))
app.use(cors())
app.use('/api/auth', UserRoute)
return app
}
export default App
user.controller.ts
export const SignUp = async (req: Request, res: Response, next: NextFunction) => {
res.json({ message: "pass!" });
}
user.route.ts
import { Router } from 'express'
import { SignUp } from './user.controller'
const router = Router()
router
.route('/signup')
.get(SignUp)
export default router
user.controller.spec.ts
import App from '../../../app'
import supertest from 'supertest'
const request = supertest(App);
describe('Testing user controller', () => {
it('testing /signup', async () => {
const res = await request.get("/signup");
expect(res.body.message).toBe("pass!");
})
})
My jest timeout is 10000, not sure what is missing here for my controller not to return? Potentially to do with async/await?
| |
doc_477
|
PatchRequest = new JsonPatchRequest
{
new JsonPatchElement
{
op = "replace",
path = "timezone",
value = timezone
},
new JsonPatchElement
{
op = "replace",
path = "language",
value = language
}
}
A: ServiceStack Android client doesn't support JsonPatchRequest ServiceStack's Android client should only be used to call ServiceStack Services.
But you can iterate all cookies with:
CookieManager cookieManager = (CookieManager) CookieHandler.getDefault();
List<HttpCookie> cookies = cookieManager.getCookies();
for (HttpCookie cookie: cookies) {
Log.d(TAG, "cookie name : "+cookie.getName().toString());
}
| |
doc_478
|
I have tried this:
float diffZ1 = lerp(heights[0], heights[2], zOffset);
float diffZ2 = lerp(heights[1], heights[3], zOffset);
float yPosition = lerp(diffZ1, diffZ2, xOffset);
Where z/yOffset is the z/y offset from the first vertex of the tile in percent / 100. This works for flat surfaces but not so well on bumpy terrain.
I expect this has something to do with the terrain being made from triangles where the above may work on flat planes. I'm not sure, but does anybody know what's going wrong?
This may better explain what's going on here:
In the code above "heights[]" is an array of the Y coordinate of surrounding vertices v0-3.
Triangle 1 is made of vertex 0, 2 and 1.
Triangle 2 is made of vertex 1, 2 and 3.
I wish to find coordinate Y of p1 when its x,y coordinates lay between v0-3.
So I have tried determining which triangle the point is between through this function:
bool PointInTriangle(float3 pt, float3 pa, float3 pb, float3 pc)
{
// Compute vectors
float2 v0 = pc.xz - pa.xz;
float2 v1 = pb.xz - pa.xz;
float2 v2 = pt.xz - pa.xz;
// Compute dot products
float dot00 = dot(v0, v0);
float dot01 = dot(v0, v1);
float dot02 = dot(v0, v2);
float dot11 = dot(v1, v1);
float dot12 = dot(v1, v2);
// Compute barycentric coordinates
float invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01);
float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
float v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u >= 0.0f) && (v >= 0.0f) && (u + v <= 1.0f);
}
This isn't giving me the results I expected
I am then trying to find the y coordinate of point p1 inside each triangle:
// Position of point p1
float3 pos = input[0].PosI;
// Calculate point and normal for triangles
float3 p1 = tile[0];
float3 n1 = (tile[2] - p1) * (tile[1] - p1); // <-- Error, cross needed
// = cross(tile[2] - p1, tile[1] - p1);
float3 p2 = tile[3];
float3 n2 = (tile[2] - p2) * (tile[1] - p2); // <-- Error
// = cross(tile[2] - p2, tile[1] - p2);
float newY = 0.0f;
// Determine triangle & get y coordinate inside correct triangle
if(PointInTriangle(pos, tile[0], tile[1], tile[2]))
{
newY = p1.y - ((pos.x - p1.x) * n1.x + (pos.z - p1.z) * n1.z) / n1.y;
}
else if(PointInTriangle(input[0].PosI, tile[3], tile[2], tile[1]))
{
newY = p2.y - ((pos.x - p2.x) * n2.x + (pos.z - p2.z) * n2.z) / n2.y;
}
Using the following to find the correct triangle:
if((1.0f - xOffset) <= zOffset)
inTri1 = true;
And correcting the code above to use the correct cross function seems to have solved the problem.
A: Because your 4 vertices may not be on a plane, you should consider each triangle separately. First find the triangle that the point resides in, and then use the following StackOverflow discussion to solve for the Z value (note the different naming of the axes). I personally like DanielKO's answer much better, but the accepted answer should work too:
Linear interpolation of three 3D points in 3D space
EDIT: For the 2nd part of your problem (finding the triangle that the point is in):
Because the projection of your tiles onto the xz plane (as you define your coordinates) are perfect squares, finding the triangle that the point resides in is a very simple operation. Here I'll use the terms left-right to refer to the x axis (from lower to higher values of x) and bottom-top to refer to the z axis (from lower to higher values of z).
Each tile can only be split in one of two ways. Either (A) via a diagonal line from the bottom-left corner to the top-right corner, or (B) via a diagonal line from the bottom-right corner to the top-left corner.
*
*For any tile that's split as A:
Check if x' > z', where x' is the distance from the left edge of the tile to the point, and z' is the distance from the bottom edge of the tile to the point. If x' > z' then your point is in the bottom-right triangle; otherwise it's in the upper-left triangle.
*For any tile that's split as B: Check if x" > z', where x" is the distance from the right edge of your tile to the point, and z' is the distance from the bottom edge of the tile to the point. If x" > z' then your point is in the lower-left triangle; otherwise it's in the upper-right triangle.
(Minor note: Above I assume your tiles aren't rotated in the xz plane; i.e. that they are aligned with the axes. If that's not correct, simply rotate them to align them with the axes before doing the above checks.)
| |
doc_479
|
My delete from button does not seem to remove my row in my SQL table
products-one-time.php
This is the output of my foreach, the numbers below the delete button are the groupids, just to show they are unique.
this is the code for the delete button, it redirects to clinics_buttons.vc.php on click.
<a href="clinics_buttons.vc.php<?php echo '?delete-coupongroup='.$rowCouponGroup['groupid']; ?>" onclick="return confirm('Delete this group?');">
<button class="btn btn-danger btn-sm full_width" data-toggle="modal">
<i class="fa fa-edit"></i>DELETE
</button>
</a>
<?php echo $rowCouponGroup['groupid']; ?>
clinics_buttons.vc.php
<?php
session_start();
$routePath = "../";
require_once($routePath . "_config/db.php");
$dbConfig = new config_db();
$db = $dbConfig->init();
$delete_coupongroup = $_GET['delete-coupongroup'];
if (isset($_GET['delete-coupongroup'])) {
$stmt = $db->prepare("DELETE FROM `product_onetime` WHERE groupid = $delete_coupongroup");
$stmt->execute();
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
?>
this is the product_onetime table
What I see is that my code seems to look like they are connected, but the delete button does not work. I tried to manually do the SQL in phpmyadmin, for example:
DELETE FROM `product_onetime` WHERE groupid = 5
Doing it manually works, but the php/sql does not. Would like some input.
A: My guess is that the file clinics_buttons.vc.php is not executed at all, because the code we see in the question is inside a <form>. In this case, the button behavior overrides the link behavior and the browser will submit the form instead of following the link.
You should be able to see that in the network tab of your development tools in your browser.
As a quick fix, change the button from a submit button into a push button:
<button type="button" class="btn btn-danger btn-sm full_width" data-toggle="modal">
<i class="fa fa-edit"></i>DELETE
</button>
A better solution would be not to use a button at all. Just make the link look like a button by using CSS styling. Or alternatively, remove the code from outside the outer form tag and give it its own form using clinics_buttons.vc.php as the form action.
| |
doc_480
|
1
cat.domain.com
should go to:
index.php?pet=cat
2
cat.domain.com/orange.html
should go to:
index.php?pet=cat&color=orange
3
cat.domain.com/orange/fluffy.html
should go to:
index.php?pet=cat&color=orange&name=fluffy
I can only get the first to work with:
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.domain\.com$ [NC]
RewriteRule ^$ index.php?pet=%2 [L]
But when I try this for #2 it doesn't seem to work or detect the "color"
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.domain\.com/([a-zA-Z0-9_-]+).html$ [NC]
RewriteRule ^$ index.php?pet=%2&color=%3 [L]
How would I write #2 and #3? Please help!
A: URI data is not part of the HTTP Host field, therefore, you can't match against it in a %{HTTP_HOST} variable. Use the pattern in the rule to match against that:
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.domain\.com$ [NC]
RewriteRule ^$ index.php?pet=%2 [L]
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.domain\.com$ [NC]
RewriteRule ^([^/]+)\.html$ index.php?pet=%2&color=$1 [L]
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.domain\.com$ [NC]
RewriteRule ^([^/]+)/([/]+)\.html$ index.php?pet=%2&color=$1&name=$2 [L]
| |
doc_481
|
I'm trying to make an app which can control the cellular data for all the device, like a cellular data switch
A: No, it's not possible, unless you're talking about a jailbroken device. Apple does not let 3rd party apps control the global functioning of the device.
| |
doc_482
|
This is my working code:
$path = "\\stos-matrix-srv\ablage$\zert_check"
$FileLogdate = Get-Date -format 'dd_MM_yyyy'
$exportpath = "C:\Temp\Cert\$FileLogdate-expordt.csv"
Get-ChildItem $path -filter *.xml |
ForEach-Object {
[xml]$empDetails = Get-Content $_.Fullname
[pscustomobject]@{
'Client' = [string]$empDetails.Objs.Obj.MS.S.innerText;
'CertificateExpire' = [string]$empDetails.Objs.Obj.MS.DT.InnerText;
} | Export-CSV -Append -Path $exportpath -NoTypeInformation
}
Now I have the problem, that there can be multiple entrys at Client and Cerificate like that:
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
<Obj RefId="0">
<TN RefId="0">
<T>Selected.System.Security.Cryptography.X509Certificates.X509Certificate2</T>
<T>System.Management.Automation.PSCustomObject</T>
<T>System.Object</T>
</TN>
<MS>
<DT N="NotAfter">2022-12-31T08:21:10+01:00</DT>
<S N="Subject">Client 01</S>
<S N="Issuer">DOMAIN</S>
</MS>
</Obj>
<Obj RefId="1">
<TNRef RefId="0" />
<MS>
<DT N="NotAfter">2022-12-31T08:21:10+01:00</DT>
<S N="Subject">Client 01</S>
<S N="Issuer">DOMAIN</S>
</MS>
</Obj>
</Objs>
How can i solve that the output is not like:
"Client 01 Client 01", "Client 01 Client 01", "2022-12-31T08:21:10+01:00 2022-12-31T08:21:10+01:00"
A: Iterate over the objects, e.g.:
$empDetails.Objs.Obj |
% {
[pscustomobject] @{
"Client" = $_.ms.s.innertext
"CertificateExpire" = $_.ms.dt.innertext
}
} |
ConvertTo-Csv -NoTypeInformation
Output:
"Client","CertificateExpire"
"Client 01","2022-12-31T08:21:10+01:00"
"Client 01","2022-12-31T08:21:10+01:00"
| |
doc_483
|
i.e.
dim fooArr() as foo;
gv1.datasource = fooArr;
gv1.databind();
On Row Select
Private Sub gv1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv1.RowCommand
If e.CommandName = "Select" Then
'get and use foo(index)
End If
End Sub
A: If you can be sure the order of items in your data source has not changed, you can use the CommandArgument property of the CommandEventArgs.
A more robust method, however,is to use the DataKeys/SelectedDataKey properties of the GridView. The only caveat is that your command must be of type "Select" (so, by default RowCommand will not have access to the DataKey).
Assuming you have some uniqueness in the entities comprising your list, you can set one or more key property names in the GridView's DataKeys property. When the selected item in the GridView is set, you can retrieve your key value(s) and locate the item in your bound list. This method gets you out of the problem of having the ordinal position in the GridView not matching the ordinal position of your element in the data source.
Example:
<asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="True"
DataKeyNames="Name" onrowcommand="GridView1_RowCommand1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
</asp:GridView>
Then the code-behind (or inline) for the Page would be something like:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
// Value is the Name property of the selected row's bound object.
string foo = GridView1.SelectedDataKey.Value as string;
}
Another choice would be to go spelunking in the Rows collection of the GridView, fetching values a column at a time by getting control values, but that's not recommended unless you have to.
Hope this helps.
A: in theory the index of the row, should be the index of foo (maybe +1 for header row, you'll need to test). so, you should be able to do something along these lines
dim x as object = foo(e.row.selectedIndex)
The other alternative is to find a way to databind the index to the commandArgument attribute of the button.
A: There's probably a cleaner way of doing this, but you could set the CommandArgument property of the row to its index. Then something like foo(CInt(e.CommandArgument)) would do the trick.
| |
doc_484
|
The class "Composition" has an attribute of class "Lambda". Class "Composition" can't be created:".Object$initialize(...) : argument "lambda" is missing, with no default"
It works if lambda has a default value in the initialize method : initialize = function(lambda=1){
but I don't want that.
setRefClass(
"Lambda",
fields = c(
lambda = "numeric"
),
methods=list(
initialize = function(lambda){
check_lambda (lambda)
lambda <<- lambda
},
check_lambda = function(new_lambda){
print ("checking...")
return(T)
}
)
)
setRefClass(
"Composition",
fields = c(
object_lambda = "Lambda"
),
methods=list(
initialize = function(object_lambda){
object_lambda <<- object_lambda
}
)
)
Thanks for your help.
A: I found a solution to my question : set the field to "ANY" of my class "Composition" :
setRefClass(
"Composition",
fields = c(
object_lambda = "ANY"
),
methods=list(
initialize = function(object_lambda){
object_lambda <<- object_lambda
}
)
)
| |
doc_485
|
I tried disabling all the plugins in wordpress and ran the same test, but the problem persisted.
I also used some plugins to optimize database like wp-optimize, but no luck. The /var/log/mysql/mysql-slow.log file is also empty.
Result of load testing after only few sec including htop
Datadog's monitoring dashboard of the related test
As shown in pictures above you can comprehend that mysqld is using too much CPU for no reason.
I also ran mysqltuner and this is the result:
>> MySQLTuner 1.7.19 - Major Hayden <[email protected]>
>> Bug reports, feature requests, and downloads at http://mysqltuner.com/
>> Run with '--help' for additional options and output filtering
[--] Skipped version check for MySQLTuner script
[OK] Logged in using credentials passed on the command line
[OK] Currently running supported MySQL version 10.1.44-MariaDB-0ubuntu0.18.04.1
[OK] Operating on 64-bit architecture
-------- Log file Recommendations ------------------------------------------------------------------
[OK] Log file /var/log/mysql/error.log exists
[--] Log file: /var/log/mysql/error.log(7K)
[OK] Log file /var/log/mysql/error.log is readable.
[OK] Log file /var/log/mysql/error.log is not empty
[OK] Log file /var/log/mysql/error.log is smaller than 32 Mb
[!!] /var/log/mysql/error.log contains 8 warning(s).
[!!] /var/log/mysql/error.log contains 3 error(s).
[--] 3 start(s) detected in /var/log/mysql/error.log
[--] 1) 2020-05-09 12:36:17 139638727916672 [Note] /usr/sbin/mysqld: ready for connections.
[--] 2) 2020-05-09 12:28:42 140719406492800 [Note] /usr/sbin/mysqld: ready for connections.
[--] 3) 2020-05-09 10:52:43 139784491093120 [Note] /usr/sbin/mysqld: ready for connections.
[--] 2 shutdown(s) detected in /var/log/mysql/error.log
[--] 1) 2020-05-09 12:32:02 140713171822336 [Note] /usr/sbin/mysqld: Shutdown complete
[--] 2) 2020-05-09 10:53:00 139784442357504 [Note] /usr/sbin/mysqld: Shutdown complete
-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +Aria +CSV +InnoDB +MEMORY +MRG_MyISAM +MyISAM +PERFORMANCE_SCHEMA +SEQUENCE
[--] Data in InnoDB tables: 112.0K (Tables: 4)
[--] Data in MyISAM tables: 38.7M (Tables: 52)
[OK] Total fragmented tables: 0
-------- Analysis Performance Metrics --------------------------------------------------------------
[--] innodb_stats_on_metadata: OFF
[OK] No stat updates during querying INFORMATION_SCHEMA.
-------- Security Recommendations ------------------------------------------------------------------
[OK] There are no anonymous accounts for any database users
[OK] All database users have passwords assigned
[!!] There is no basic password file list!
-------- CVE Security Recommendations --------------------------------------------------------------
[--] Skipped due to --cvefile option undefined
-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 48m 13s (73K q [25.317 qps], 1K conn, TX: 978M, RX: 11M)
[--] Reads / Writes: 96% / 4%
[--] Binary logging is disabled
[--] Physical Memory : 9.8G
[--] Max MySQL memory : 10.6G
[--] Other process memory: 0B
[--] Total buffers: 4.7G global + 6.9M per thread (800 max threads)
[--] P_S Max memory usage: 511M
[--] Galera GCache Max memory usage: 0B
[OK] Maximum reached memory usage: 6.5G (67.07% of installed RAM)
[!!] Maximum possible memory usage: 10.6G (108.28% of installed RAM)
[!!] Overall possible memory usage with other process exceeded memory
[OK] Slow queries: 0% (0/73K)
[OK] Highest usage of available connections: 25% (204/800)
[!!] Aborted connections: 10.65% (193/1812)
[OK] Query cache is disabled by default due to mutex contention on multiprocessor machines.
[OK] Sorts requiring temporary tables: 0% (0 temp sorts / 12K sorts)
[OK] No joins without indexes
[!!] Temporary tables created on disk: 83% (2K on disk / 3K total)
[OK] Thread cache hit rate: 84% (284 created / 1K connections)
[OK] Table cache hit rate: 97% (222 open / 228 opened)
[OK] table_definition_cache(400) is upper than number of tables(303)
[OK] Open file limit used: 6% (304/4K)
[!!] Table locks acquired immediately: 84%
-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 511.6M
[--] Sys schema is installed.
-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is enabled.
[--] Thread Pool Size: 4 thread(s).
[--] Using default value is good enough for your version (10.1.44-MariaDB-0ubuntu0.18.04.1)
-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 18.4% (24M used / 134M cache)
[OK] Key buffer size / total MyISAM indexes: 128.0M/10.0M
[OK] Read Key buffer hit rate: 100.0% (695K cached / 152 reads)
[OK] Write Key buffer hit rate: 100.0% (18 cached / 18 writes)
-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[OK] InnoDB buffer pool / data size: 3.9G/112.0K
[OK] Ratio InnoDB log file size / InnoDB Buffer pool size: 500.0M * 2/3.9G should be equal to 25%
[OK] InnoDB buffer pool instances: 3
[--] InnoDB Buffer Pool Chunk Size not used or defined in your version
[!!] InnoDB Read buffer efficiency: 85.36% (1493 hits/ 1749 total)
[!!] InnoDB Write Log efficiency: 0% (1 hits/ 0 total)
[OK] InnoDB log waits: 0.00% (0 waits / 1 writes)
-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is enabled.
[OK] Aria pagecache size / total Aria indexes: 128.0M/1B
[!!] Aria pagecache hit rate: 89.4% (26K cached / 2K reads)
-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.
-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.
-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.
-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] Binlog format: STATEMENT
[--] XA support enabled: ON
[--] Semi synchronous replication Master: Not Activated
[--] Semi synchronous replication Slave: Not Activated
[--] This is a standalone server
-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
Control warning line(s) into /var/log/mysql/error.log file
Control error line(s) into /var/log/mysql/error.log file
MySQL was started within the last 24 hours - recommendations may be inaccurate
Reduce your overall MySQL memory footprint for system stability
Dedicate this server to your database for highest performance.
Reduce or eliminate unclosed connections and network issues
Temporary table size is already large - reduce result set size
Reduce your SELECT DISTINCT queries without LIMIT clauses
Optimize queries and/or use InnoDB to reduce lock wait
mysql config in /etc/mysqld/my.cnf:
[mysqld]
general_log = on
skip-name-resolve
innodb_read_io_threads=4
innodb_write_io_threads=4
general_log_file = /var/log/mysql/mysql.log
log_error=/var/log/mysql/mysql_error.log
#
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
#log_slow_queries = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
# other settings you may need to change.
#server-id = 1
#log_bin = /var/log/mysql/mysql-bin.log
expire_logs_days = 10
max_binlog_size = 100M
#binlog_do_db = include_database_name
#binlog_ignore_db = include_database_name
#
# * InnoDB
innodb_buffer_pool_size= 4000M
max_connections =800
wait_timeout=100
interactive_timeout=100
query_cache_size=0
query_cache_type=0
query_cache_limit=2M
tmp_table_size=500M
max_heap_table_size=500M
thread_cache_size=4
performance_schema=ON
innodb_log_file_size=500M
innodb_buffer_pool_instances=3
innodb_autoinc_lock_mode = 2
/var/log/mysql/error.log
2020-05-09 12:36:16 139638727916672 [Note] InnoDB: Using mutexes to ref count buffer pool pages
2020-05-09 12:36:16 139638727916672 [Note] InnoDB: The InnoDB memory heap is disabled
2020-05-09 12:36:16 139638727916672 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2020-05-09 12:36:16 139638727916672 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2020-05-09 12:36:16 139638727916672 [Note] InnoDB: Compressed tables use zlib 1.2.11
2020-05-09 12:36:16 139638727916672 [Note] InnoDB: Using Linux native AIO
2020-05-09 12:36:16 139638727916672 [Note] InnoDB: Using SSE crc32 instructions
2020-05-09 12:36:16 139638727916672 [Note] InnoDB: Initializing buffer pool, size = 3.9G
2020-05-09 12:36:16 139638727916672 [Note] InnoDB: Completed initialization of buffer pool
2020-05-09 12:36:16 139638727916672 [Note] InnoDB: Highest supported file format is Barracuda.
2020-05-09 12:36:17 139638727916672 [Note] InnoDB: 128 rollback segment(s) are active.
2020-05-09 12:36:17 139638727916672 [Note] InnoDB: Waiting for purge to start
2020-05-09 12:36:17 139638727916672 [Note] InnoDB: Percona XtraDB (http://www.percona.com) 5.6.46-86.2 started; log sequence number 1832982
2020-05-09 12:36:17 139632989665024 [Note] InnoDB: Dumping buffer pool(s) not yet started
2020-05-09 12:36:17 139638727916672 [Note] Plugin 'FEEDBACK' is disabled.
2020-05-09 12:36:17 139638727916672 [Note] Server socket created on IP: '::'.
2020-05-09 12:36:17 139638727916672 [Warning] 'user' entry 'wp_user@server' ignored in --skip-name-resolve mode.
2020-05-09 12:36:17 139638727916672 [Warning] 'db' entry 'db_name wp_user@server' ignored in --skip-name-resolve mode.
2020-05-09 12:36:17 139638727916672 [Note] /usr/sbin/mysqld: ready for connections.
Version: '10.1.44-MariaDB-0ubuntu0.18.04.1' socket: '/var/run/mysqld/mysqld.sock' port: 3306 Ubuntu 18.04
A: Rate Per Second = RPS
Suggestions to consider for your my.cnf [mysqld] section:
thread_cache_size=256 # from 4 for default minimum
innodb_io_capacity=900 # from 200 to enable higher IOPS
read_rnd_buffer_size=128K # from 256K to reduce handler_read_rnd_next RPS of 256
read_buffer_size=256K # from 128K to reduce handler_read_next RPS of 828
These changes will reduce CPU busy on your server. There are more opportunities available to improve your my.cnf.
Observations:
OS swap space is at 0. 6GB for your 10GB server would be reasonable and avoid Out of memory.
Select_scan RPhr of 1546 could be reduced with appropriate indexes on tables.
At www.mysqlservertuning.com on our FAQ page we have tips on
Q. How can I find JOINS or QUERIES not using indexes?
to improve response time and reduce CPU busy percentage by using indexes.
| |
doc_486
|
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
import numpy as np
import pandas as p
idx = [761, 762, 763, 764]
cols = ['11','12','13','14']
def fit_imputer():
for i in range(len(idx)):
for col in cols:
dfClean.iloc[idx[i], col] = np.nan
print('Index = {} Col = {} Defiled Value is: {}'.format(idx[i], col, dfClean.iloc[idx[i], col]))
# Run Imputer for Individual row
tempOut = imp.fit_transform(dfClean)
print("Imputed Value = ",tempOut[idx[i],col] )
dfClean.iloc[idx[i], col] = tempOut[idx[i],col]
print("new dfClean Value = ",dfClean.iloc[idx[i], col])
origVal.append(dfClean_Orig.iloc[idx[i], col])
I get an error when I try to run this code on Azure Databricks using pyspark or scala. Because the dataframes in spark are immutable also I cannot use iloc as I have used it in pandas dataframe.
Is there a way or better way of implementing such imputation in databricks?
| |
doc_487
|
iif(Format(SUM(Field))='',0,SUM(Field))
SQL code
IsNull(SUM(Field),0) As Amt
In the Access Code statement it is clearly shown that the query has to run SUM function 2 times to get SUM and 0 if records are blank.
But I want to know that internally how many times SQL is running SUM function in the SQL statement? 1 or 2? Please provide some explanation.
A: My copy-pasted comment:
Once, as opposed to COALESCE:
Used with Subqueries
The ISNULL function has an important advantage over COALESCE in that
internally it doesn't evaluate an input expression more than once. In
accordance with standard SQL, COALESCE(v1, v2) is simply internally
translated to CASE WHEN v1 IS NOT NULL THEN v1 ELSE v2 END. As a
result, SQL Server might evaluate the expression v1 more than once,
which can lead to all kinds of surprising results.
| |
doc_488
|
use constant FOO => 'bar';
my $msg = <<EOF;
Foo is currently <whatever goes here to expand FOO>
EOF
A: The problem with a lot of the CPAN modules that do a nicer job of constants than the use constant pragma is that they just aren't part of the standard Perl package. Unfortunately, it can be very difficult to download CPAN modules on machines you might not own.
Therefore, I've just decided to stick to use constant until Perl starts to include something like Readonly as part of its standard modules (and only when distros like RedHat and Solaris decide to update to those versions of Perl. I'm still stuck with 5.8.8 on our production servers.)
Fortunately, you can interpolate constants defined with use constant if you know the arcane and mystical incantations that has been passed down from hacker to hacker.
Put @{[...]} around the constant. This can also work with methods from classes too:
use 5.12.0;
use constant {
FOO => "This is my value of foo",
};
my $data =<<EOT;
this is my very long
value of my variable that
also happens to contain
the value of the constant
'FOO' which has the value
of @{[FOO]}
EOT
say $data;
Output:
this is my very long
value of my variable that
also happens to contain
the value of the constant
'FOO' which has the value
of This is my value of foo
Using a method:
say "The employee's name is @{[$employee->Name]}";
Aside:
There is also another way to use constants that I used to employ before use constant was around. It went like this:
*FOO = \"This is my value of foo";
our $FOO;
my $data =<<EOT;
this is my very long
value blah, blah, blah $FOO
EOT
say $data;
You can use $FOO as any other scalar value, and it can't be modified. You try to modify the value and you get:
Modification of a read-only value attempted at ...
A: Use Const::Fast instead of Readonly or constant. They interpolate without any contortions. See CPAN modules for defining constants:
For conditional compilation, constant is a good choice. It's a mature module and widely used.
...
If you want array or hash constants, or immutable rich data structures, use Const::Fast. It's a close race between that and Attribute::Constant, but Const::Fast seems maturer, and has had more releases.
On the other hand, you seem to be writing your own templating code. Don't. Instead, use something simple like HTML::Template:
use HTML::Template;
use constant FOO => 'bar';
my $tmpl = HTML::Template->new(scalarref => \ <<EOF
Foo is currently <TMPL_VAR VALUE>
EOF
);
$tmpl->param(VALUE => FOO);
print $tmpl->output;
A: Have you considered using "read-only variables" as constants?
perlcritic recomends it at severity level 4 (default is level 5)
use Readonly;
Readonly my $FOO => 'bar';
my $msg = <<"EOF";
Foo is currently <$FOO>
EOF
P.S. Module Const::Fast (inspired by noduleReadonly) seems to be a better choice.
A: There are two kinds of here-docs:
*
*<<'END', which behaves roughly like a single quoted string (but no escapes), and
*<<"END", also <<END, which behaves like a double quoted string.
To interpolate a value in a double quoted string use a scalar variable:
my $foo = "bar";
my $msg = "Foo is currently $foo\n";
Or use the arrayref interpolation trick
use constant FOO => "bar";
my $msg = "Foo is currently @{[ FOO ]}\n";
You could also define a template language to substitute in the correct value. This may or may not be better depending on your problem domain:
my %vars = (FOO => "bar");
my $template = <<'END';
Foo is currently %FOO%;
END
(my $msg = $template) =~ s{%(\w+)%}{$vars{$1} // die "Unknown variable $1"}eg;
A: Late to the party, but another version of the arrayref trick can do this in a scalar context: ${\FOO}. Example, tested in perl 5.22.2 on cygwin:
use constant FOO=>'bar';
print <<EOF
backslash -${\FOO}-
backslash and parens -${\(FOO)}-
EOF
produces
backslash -bar-
backslash and parens -bar-
Thanks to d-ash for introducing me to this technique, which he uses in his perlpp source preprocessor here (see also this answer). (Disclaimer: I am now the lead maintainer of perlpp - GitHub; CPAN.)
| |
doc_489
|
In Java
System.out.println("_".compareTo("0")); // prints 47, "_" is larger than "0"
In C#
Console.WriteLine("_".CompareTo("0")); // prints -1, "_" is smaller than "0"
Does anyone know why C# thinks "_" (underscore) is smaller than "0", while Java does the opposite thing (which makes more sense to me because it matches ASCII order)?
Updates
Thanks guys for pointing out the ordinal comparison.
Console.WriteLine(String.CompareOrdinal("_","0")); // prints 47, ordinal comparison does return the result reflecting ASCII
I checked the docs and realized CompareTo is "culture-sensitive and case-sensitive comparison" and is NOT "ordinal" (https://learn.microsoft.com/en-us/dotnet/api/system.string.compareto?view=net-5.0#remarks). That might be what makes a difference.
A: Java does the same as the 'ordinal' comparision in c#.
The java documentation says 'It compares strings on the basis of Unicode value of each character in the strings.'
For non-surrogate unicode characters this is the same as string.CompareOrdinal in c#, which "Compares two String objects by evaluating the numeric values of the corresponding Char objects in each string."
I'm not sure if they're the same for high unicode codepoints (surrogate pairs) or not, but I suspect they might be, since both Java and c# uses 16 bits char types.
The 'standard' c# string.Compare, on the other hand, performs 'culture-sensitive' comparision. Which means that it 'uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters'.
You can read more about this at the documentation for System.Globalization.CompareOptions.
| |
doc_490
|
My theory is that because of it being in Update() that once I move my finger off the object it detects that I can no longer drag it. I have no idea how to fix this.
public GameObject Bigball;
public GameObject Smallball;
// Update is called once per frame
private void Update ()
{
// lets ball follow finger
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(0).phase == TouchPhase.Stationary)
{
var touch = Input.GetTouch(0);
Vector3 fingerPos = touch.position;
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(fingerPos);
if (Physics.Raycast(ray, out hit) && (hit.collider.tag == "ball"))
{
Smallball.SetActive(false);
Bigball.SetActive(true);
Vector3 pos = new Vector3((Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position)).x,
(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position)).y, 0);
Bigball.transform.position = pos;
}
}
else
{
Bigball.SetActive(false);
Smallball.SetActive(true);
Smallball.transform.position = new Vector3(Bigball.transform.position.x, Bigball.transform.position.y, 0);
}
}
A: It might make more sense to only Raycast once when the finger touches the screen. If that Raycast finds an object to drag, simply store that object and move it to follow the finger every Update(), as long as the finger continues to touch the screen.
Once the finger is released, just forget about the object until the next touch finds a new object to drag.
An alternative would be to use no Raycasts at all but build on IBeginDragHandler, IDragHandler and IEndDragHandler, as Bijan already mentioned.
| |
doc_491
|
is there any good resource or link will help to start working on it.
any existing article like step by step guide for developer would be great !!
I want to develop the plugin based on Python Programming Language.
A: You can refer to the OpenOffice.org's extension development site. This has all the information regarding the development of extensions for openoffice. For how to develop plugin in Python, you can refer to this link.
Also Danny's OOo library would be helpful which makes programming OOo in Python much more like programming OOo in Basic.
| |
doc_492
|
I have seen this on a professional oracle (?) set up. The main advantage is that you have unique id for ALL rows/elements in ALL tables, not just PER TABLE.
A: PostgreSQL can be setup like this with a CREATE SEQUENCE seq_name and using nextval(seq_name) on every insert.
MySQL does not have native support for this, you can simulate the behavior of a PostgreSQL SEQUENCE by creating a table with only one column and an AUTO_INCREMENT on that column.
You always insert into that table first read the LAST_INSERT_ID of that table to get the id you need to insert into your table. It would be transaction safe so not duplicates would ever be generated.
Another way to achieve this is to create a table with one column no AUTO_INCREMENT and only one row holding the current max value.
Every time you need to increment you execute UPDATE seq_table SET seq_column = seq_colum+1; an increment update is in itself atomic but you need to also read the value afterwards which makes two statements and they are not atomic together unless you set a transaction around them and an appropriate isolation level. This approach saves space but also generates locking queries.
Multiple threads trying to INSERT will have to wait for others to update the seq_table before being able to update it themselves and read the new value.
Also you'd have to wrap the UPDATE and the SELECT on seq_table in a transaction with an appropriate ISOLATION LEVEL to avoid reading the value that some other thread incremented after you incremented it.
This means that INSERTS become a transactional issue but normally they aren't, so i wouldn't recommend the second approach.
| |
doc_493
|
So naturally I turn to Shadow DOM. I soon learn that I can't simply attach my shadow DOM to document.body since this will displace the whole page.
It turns out I need one regular element in the body to act as a shadow root:
const shadowHost = document.createElement('div');
document.body.appendChild(shadowHost);
const shadow = shadowHost.attachShadow({mode: 'closed'});
But how can I protect this shadow root from being influenced by the css or js of the website?
A: What have you tried?
shadowRoots are not styled by global CSS, unless they are inheritable styles
*
*https://lamplightdev.com/blog/2019/03/26/why-is-my-web-component-inheriting-styles/
mode:"closed" has nothing to do with CSS, it just doesn't publish the shadowRoot in element.shadowRoot, making it impossible to access the shadow DOM from the outside.
When the mode of a shadow root is "closed", the shadow root’s implementation internals are inaccessible and unchangeable from JavaScript—in the same way the implementation internals of, for example, the <video> element are inaccessible and unchangeable from JavaScript.
document.body
.appendChild(document.createElement('div'))
.attachShadow({mode:'closed'})
.innerHTML = `<style>h1{color:green}</style><h1>Hello</h1><h2>Component</h2>`;
<style>
body {
/* inheritable styles do style shadowRoots */
font: 10px Arial;
color: red;
}
</style>
| |
doc_494
|
I'm building a multiplayer game using socket.io and serving the react app statically using express. The app displays the lobby successifully but the server throws this error as soon as the game starts.
Here is the api
const express = require('express')
const path = require('path')
const api = express.Router()
api.use(express.static(path.join(__dirname, "..", "public")))
module.exports = api
and server.js
const http = require('http')
const io = require('socket.io')
const sockets = require('./sockets')
const apiServer = require('./api')
const httpServer = http.createServer(apiServer)
const socketServer = io(httpServer, {
cors: {
origin: 'http://localhost:3000',
methods: ["GET", "POST"]
}
})
const PORT = 4000
httpServer.listen(4000, () => {
console.log(`Server is running on port: ${PORT}`)
})
sockets.listen(socketServer)
is there something I'm doing wrongly?
This are logs when the server start and connect two users
Server is running on port: 4000
User connected CTmTWswPSNdfhhl2AAAB
{
playerData: {
pid: '53f7bfaf-bbbb-496c-a666-f55a9d574054',
avatar: 11,
name: 'Nyah'
},
players: 1
}
User connected UkfcIX202fDXJ6caAAAD
{
playerData: {
pid: '09b68067-cc0d-460d-b28c-21cde0c54862',
avatar: 9,
name: 'Walter'
},
players: 2
}
Then as soon as game starts:
Game on Guys!!!
/home/aimkeys/Development/projects/card-games/poker-server/node_modules/express/lib/router/index.js:646
return fn.apply(this, arguments);
^
TypeError: Cannot read properties of undefined (reading 'apply')
at Immediate.<anonymous> (/home/aimkeys/Development/projects/card-games/poker-server/node_modules/express/lib/router/index.js:646:15)
at processImmediate (node:internal/timers:468:21)
The app is working correctly when I have started the frontend and the backend at different ports.
| |
doc_495
|
github:
clientId: ${GITHUB_CLIENT_ID}
clientSecret: ${GITHUB_CLIENT_SECRET}
redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
scope:
- read:user
- user:email
To fetch profile data app sends request to https://github.com/login/oauth/authorize with following parameters:
*
*response_type: code
*scope: read:user user:email
*client_id: <client_id>
*state:
*redirect_url:
The problem is that github fetches only public data (as though it ignores scope "user:email")
| |
doc_496
|
que = queue.PriorityQueue()
mst = []
visited = set()
# Generate edge information with tuple and push it to Priority Queue
for outer_key in graph.keys():
for inner_key, inner_cost in graph[outer_key].items():
que.put((inner_cost, outer_key, inner_key))
while que.empty() is False:
edge = que.get()
cost, frm, to = edge
if to in visited:
continue
visited.add(frm)
visited.add(to)
mst.append(edge)
for next_to, cost in graph[to].items():
if next_to not in visited:
que.put((cost, to, next_to))
return mst
Full source code
I'm making very simple Prim's Algorithm with Python. In this code, graph is made with nested dictionary. I pushed all edges(tuple) to Priority Queue, get them one by one from it, check whether is it a visited vertex, and pushed adjacent vertex to Priority Queue.
However, the shape of final spanning tree is like this:
2
[A] [B]-------[C]
|
5 |
|
[D]--------[E] [F]
6 |
+---+
| 3
[G]----+
I want to know where the problem is and how to fix it. Thanks.
A: Prim's algorithm starts from an arbitrary vertex. It then adds all its edges to the priority queue and starts the loop.
You added all the edges to the queue (maybe you got confused with Kruskal which does something else).
A working code is hence:
def prim(graph):
que = queue.PriorityQueue()
mst = []
visited = set()
# Generate edge information with tuple and push it to Priority Queue
#for outer_key in graph.keys():
# for inner_key, inner_cost in graph[outer_key].items():
# que.put((inner_cost, outer_key, inner_key))
starting_vertex = list(graph.keys())[0]
for next_to, cost in graph[starting_vertex].items():
if next_to not in visited:
que.put((cost, starting_vertex, next_to))
while que.empty() is False:
edge = que.get()
cost, frm, to = edge
if to in visited:
continue
visited.add(frm)
visited.add(to)
mst.append(edge)
for next_to, cost in graph[to].items():
if next_to not in visited:
que.put((cost, to, next_to))
return mst
| |
doc_497
|
second mp3 stops when i click to run another audio, i want to run both.
please give me suggestion.
this is what i am using...
<audio autoplay="true" type="audio/mpeg" src="voices/letsdressuptoplay.mp3" id="music4" > </audio>
thanks.
A: We cannot run multiple mp3 or videos in any browser on devices like iPad. There is restriction in tablets.
As an application you can run multiple mp3.
| |
doc_498
|
<select id="country" title="Country">
<option>Argentina ARG</option>
<option>Australia AUS</option>
<option>Austria AUT</option>
<option>Austria AUT</option>
<option>Belgium BEL</option>
<option>Brazil BRA</option>
<option>Canada CAN</option>
</select>
Naturally when a user chooses say 'Brazil' the option displays 'Brazil BRA'. However, I would like to instead use the value 'BRA' is it possible to do this? Am I just being dumb and it can be done in plain HTML?
A: <option value="BRA">Brazil BRA</option>
Side note: I believe IE6 needs that value or things get funky onsubmit.
A: Use the value attribute: http://www.w3schools.com/tags/att_option_value.asp
A: <select id="country" title="Country">
<option value="ARG">Argentina</option>
<option value="AUS">Australia</option>
</select>
A: You can use the options value-attribute. This way the text that is shown to the user is Argentina ARG, but the value that is posted with the form is just ARG.
<select id="country" title="Country">
<option value="ARG">Argentina ARG</option>
<option value="AUS">Australia AUS</option>
...
</select>
| |
doc_499
|
Content content = new Content();
content.execute();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
//What do I put in here??
}
});
return root;
}
private class Content extends AsyncTask<Void,Void,Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
//progressBar.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressBar.setVisibility(View.GONE);
//progressBar.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
adapter.notifyDataSetChanged();
}
@Override
protected Void doInBackground(Void... voids) {
try {
String url = "https://www.mywebsite.com";
Document doc = Jsoup.connect(url).get();
Elements data = doc.select(".thisurl");
int size = data.size();
Log.d("doc", "doc: " + doc);
Log.d("data", "data: " + data);
Log.d("size", "" + size);
for (int i = 0; i < size; i++) {
String date = doc.select(".b-time").eq(i).text();
String league = doc.select(".card-competition-title").eq(i).text();
String homeLogo = data.select(".card-vs-left")
.select("img")
.eq(i)
.attr("src");
String homeTeam = doc.select(".card-vs-left").eq(i).text();
String awayLogo = data.select(".card-vs-right")
.select("img")
.eq(i)
.attr("src");
String awayTeam = doc.select(".card-vs-right").eq(i).text();
String pick = doc.select("span.card-our-prono").eq(i).text();
sportyParseItems.add(new SportyParseItem(date, league, homeLogo, homeTeam, awayLogo, awayTeam, pick));
Log.d("items", "img: " + homeLogo + "img:" + awayLogo + " . title: " + league);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
A: swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
content.execute();
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.