_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d14801 | val | You can use "when" and like in the example bellow, the second question will popup only if "Cassandra" is selected:
const QUESTIONS = [
{
name: 'your-name',
type: 'list',
message: 'Your name:',
choices: ['Batman', 'Superman', 'Ultron', 'Cassandra'],
},
{
name: 'hello-cassandra',
type: 'confirm',
message: 'Oh, hello Cassandra!',
when: (answers) => answers['your-name'] === 'Cassandra',
},
];
inquirer.prompt(QUESTIONS)
.then(answers =>
{
console.log(answers);
}); | unknown | |
d14802 | val | Try this:
f=[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
for i in zip(*f):
print(i)
Output:
(1, 1, 1, 1)
(2, 2, 2, 2)
(3, 3, 3, 3)
A: zip() in conjunction with the * operator can be used to unzip a list and it return iterator of tuples.
Using map() to apply list on the iterator of tuples that we are getting from zip and it return an iterator. And then passing the iterator to list().
a = list(map(list, zip(*f)))
Or
a = []
for i in iter(map(list, zip(*f))):
a.append(i)
A: What you should do in here is to use a for loop.
f=[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
a1=[x[0] for x in f]
a2=[x[1] for x in f]
a3=[x[2] for x in f]
print(a1,a2,a3)
>>>[1, 1, 1, 1] [2, 2, 2, 2] [3, 3, 3, 3]
A: You may do so like the following:
a = [list(i) for i in zip(*f)]
Now:
a[0] will be [1, 1, 1, 1]
a[1] will be [2, 2, 2, 2]
a[2] will be [3, 3, 3, 3] | unknown | |
d14803 | val | You can try it like this
SELECT
l.id,
l.description,
IF(r.type IS NULL, l.type, r.type) AS `Type`
FROM newtable as l
LEFT JOIN (SELECT *
FROM newtable
WHERE type <> 'Special') as r
on r.id = l.id
GROUP BY l.id
SQL Fiddle Demo
A: This could be a solution:
SELECT
newtable.id,
newtable.description,
newtable.type
FROM newtable
INNER JOIN(
SELECT
id,
MAX(CASE WHEN Type!='Special' THEN Type END) type
FROM newtable
GROUP BY id
) mx
ON newtable.id=mx.id
AND newtable.type=COALESCE(mx.type, 'Special')
Fiddle here (thanks to raheel shan for the fiddle!) | unknown | |
d14804 | val | Edit the template for showing categories to only list one post per page. By default it shows the x most recent posts; if x is one, it only shows that one most recent post.
A: I ended up doing it differently. I found this page: http://codex.wordpress.org/Template_Hierarchy
On the page it said this: category-{slug}.php - If the category's slug were news, WordPress would look for category-news.php
This would let me use that page to display any posts in the student of the month category. I'd just program that page to only display the most recent. As for the nav problem, I ended using the "Page Links To" plugin. Thanks for the tips though, they sent me in the correct direction! | unknown | |
d14805 | val | library(dplyr)
df %>% group_by(Group) %>% slice(which.max(Value)) %>% select(-Value)
#Source: local data frame [4 x 2]
#Groups: Group [4]
# Group Year
# <fctr> <int>
#1 A 1933
#2 B 2011
#3 C 1954
#4 D 1978
Note this only keeps one max value per group if ties exist.
A method that keeps tied max values:
library(dplyr)
df %>% group_by(Group) %>% filter(Value == max(Value)) %>% select(-Value)
#Source: local data frame [4 x 2]
#Groups: Group [4]
# Group Year
# <fctr> <int>
#1 A 1933
#2 B 2011
#3 C 1954
#4 D 1978
A: Here is a base R and a data.table solution:
df <- structure(list(Group = c("A", "A", "B", "B", "B", "C", "D", "D"
), Value = c(12L, 10L, 3L, 5L, 6L, 1L, 3L, 4L), Year = c(1933L,
2010L, 1935L, 1978L, 2011L, 1954L, 1933L, 1978L)), .Names = c("Group",
"Value", "Year"), row.names = c(NA, -8L), class = "data.frame")
# Base R - use aggregate to get max Value per group, then merge with df
merge(df, aggregate(Value ~ Group, df, max), by.all = c("Group", "Value"))[
, c("Group", "Year")]
# Group Year
# 1 A 1933
# 2 B 2011
# 3 C 1954
# 4 D 1978
# data.table solution
library(data.table)
dt <- data.table(df)
dt[, .SD[which.max(Value), .(Year)], by = Group]
# Group Year
# 1: A 1933
# 2: B 2011
# 3: C 1954
# 4: D 1978 | unknown | |
d14806 | val | You are correct about the file handle being closed automatically when its variable goes out of scope; the same will happen to contents, though - it will be destroyed at the end of the function, unless you decide to return it as an owned String. In Rust functions can't return references to objects created inside them, only to those passed to them as arguments.
You can fix your function as follows:
fn read(file_name: &str) -> String {
let mut f = File::open(file_name)
.expect(&format!("file not found: {}", file_name));
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect(&format!("cannot read file {}", file_name));
contents
}
Alternatively, you can pass contents as a mutable reference to the read function:
fn read(file_name: &str, contents: &mut String) { ... } | unknown | |
d14807 | val | There are multiple reasons why the C compiler cannot automatically reorder the fields:
*
*The C compiler doesn't know whether the struct represents the memory structure of objects beyond the current compilation unit (for example: a foreign library, a file on disc, network data, CPU page tables, ...). In such a case the binary structure of data is also defined in a place inaccessible to the compiler, so reordering the struct fields would create a data type that is inconsistent with the other definitions. For example, the header of a file in a ZIP file contains multiple misaligned 32-bit fields. Reordering the fields would make it impossible for C code to directly read or write the header (assuming the ZIP implementation would like to access the data directly):
struct __attribute__((__packed__)) LocalFileHeader {
uint32_t signature;
uint16_t minVersion, flag, method, modTime, modDate;
uint32_t crc32, compressedSize, uncompressedSize;
uint16_t nameLength, extraLength;
};
The packed attribute prevents the compiler from aligning the fields according to their natural alignment, and it has no relation to the problem of field ordering. It would be possible to reorder the fields of LocalFileHeader so that the structure has both minimal size and has all fields aligned to their natural alignment. However, the compiler cannot choose to reorder the fields because it does not know that the struct is actually defined by the ZIP file specification.
*C is an unsafe language. The C compiler doesn't know whether the data will be accessed via a different type than the one seen by the compiler, for example:
struct S {
char a;
int b;
char c;
};
struct S_head {
char a;
};
struct S_ext {
char a;
int b;
char c;
int d;
char e;
};
struct S s;
struct S_head *head = (struct S_head*)&s;
fn1(head);
struct S_ext ext;
struct S *sp = (struct S*)&ext;
fn2(sp);
This is a widely used low-level programming pattern, especially if the header contains the type ID of data located just beyond the header.
*If a struct type is embedded in another struct type, it is impossible to inline the inner struct:
struct S {
char a;
int b;
char c, d, e;
};
struct T {
char a;
struct S s; // Cannot inline S into T, 's' has to be compact in memory
char b;
};
This also means that moving some fields from S to a separate struct disables some optimizations:
// Cannot fully optimize S
struct BC { int b; char c; };
struct S {
char a;
struct BC bc;
char d, e;
};
*Because most C compilers are optimizing compilers, reordering struct fields would require new optimizations to be implemented. It is questionable whether those optimizations would be able to do better than what programmers are able to write. Designing data structures by hand is much less time consuming than other compiler tasks such as register allocation, function inlining, constant folding, transformation of a switch statement into binary search, etc. Thus the benefits to be gained by allowing the compiler to optimize data structures appear to be less tangible than traditional compiler optimizations.
A: It would change the semantics of pointer operations to reorder the structure members. If you care about compact memory representation, it's your responsibility as a programmer to know your target architecture, and organize your structures accordingly.
A: If you were reading/writing binary data to/from C structures, reordering of the struct members would be a disaster. There would be no practical way to actually populate the structure from a buffer, for example.
A: Keep in mind that a variable declaration, such as a struct, is designed to be a "public" representation of the variable. It's used not only by your compiler, but is also available to other compilers as representing that data type. It will probably end up in a .h file. Therefore, if a compiler is going to take liberties with the way the members within a struct are organized, then ALL compilers have to be able to follow the same rules. Otherwise, as has been mentioned, the pointer arithmetic will get confused between different compilers.
A: Structs are used to represent physical hardware at the very lowest levels. As such the compiler cannot move things a round to suit at that level.
However it would not be unreasonable to have a #pragma that let the compiler re-arrange purely memory based structs that are only used internally to the program. However I don't know of such a beast (but that doesn't meant squat - I'm out of touch with C/C++)
A: C is designed and intended to make it possible to write non-portable hardware and format dependent code in a high level language. Rearrangement of structure contents behind the back of the programmer would destroy that ability.
Observe this actual code from NetBSD's ip.h:
/*
* Structure of an internet header, naked of options.
*/
struct ip {
#if BYTE_ORDER == LITTLE_ENDIAN
unsigned int ip_hl:4, /* header length */
ip_v:4; /* version */
#endif
#if BYTE_ORDER == BIG_ENDIAN
unsigned int ip_v:4, /* version */
ip_hl:4; /* header length */
#endif
u_int8_t ip_tos; /* type of service */
u_int16_t ip_len; /* total length */
u_int16_t ip_id; /* identification */
u_int16_t ip_off; /* fragment offset field */
u_int8_t ip_ttl; /* time to live */
u_int8_t ip_p; /* protocol */
u_int16_t ip_sum; /* checksum */
struct in_addr ip_src, ip_dst; /* source and dest address */
} __packed;
That structure is identical in layout to the header of an IP datagram. It is used to directly interpret blobs of memory blatted in by an ethernet controller as IP datagram headers. Imagine if the compiler arbitrarily re-arranged the contents out from under the author -- it would be a disaster.
And yes, it isn't precisely portable (and there's even a non-portable gcc directive given there via the __packed macro) but that's not the point. C is specifically designed to make it possible to write non-portable high level code for driving hardware. That's its function in life.
A: Your case is very specific as it would require the first element of a struct to be put re-ordered. This is not possible, since the element that is defined first in a struct must always be at offset 0. A lot of (bogus) code would break if this would be allowed.
More generally pointers of subobjects that live inside the same bigger object must always allow for pointer comparison. I can imagine that some code that uses this feature would break if you'd invert the order. And for that comparison the knowledge of the compiler at the point of definition wouldn't help: a pointer to a subobject doesn't have a "mark" do which larger object it belongs. When passed to another function just as such, all information of a possible context is lost.
A: C [and C++] are regarded as systems programming languages so they provide low level access to the hardware, e.g., memory by means of pointers. Programmer can access a data chunk and cast it to a structure and access various members [easily].
Another example is a struct like the one below, which stores variable sized data.
struct {
uint32_t data_size;
uint8_t data[1]; // this has to be the last member
} _vv_a;
A: Not being a member of WG14, I can't say anything definitive, but I have my own ideas:
*
*It would violate the principle of least surprise - there may be a damned good reason why I want to lay my elements out in a specific order, regardless of whether or not it's the most space-efficient, and I would not want the compiler to rearrange those elements;
*It has the potential to break a non-trivial amount of existing code - there's a lot of legacy code out there that relies on things like the address of the struct being the same as the address of the first member (saw a lot of classic MacOS code that made that assumption);
The C99 Rationale directly addresses the second point ("Existing code is important, existing implementations are not") and indirectly addresses the first ("Trust the programmer").
A: Here's a reason I didn't see so far - without standard rearrangement rules, it would break compatibility between source files.
Suppose a struct is defined in a header file, and used in two files.
Both files are compiled separately, and later linked. Compilation may be at different times (maybe you touched just one, so it had to be recompiled), possibly on different computers (if the files are on a network drive) or even different compiler versions.
If at one time, the compiler would decide to reorder, and at another it won't, the two files won't agree on where the fields are.
As an example, think of the stat system call and struct stat.
When you install Linux (for example), you get libC, which includes stat, which was compiled by someone sometime.
You then compile an application with your compiler, with your optimization flags, and expect both to agree on the struct's layout.
A: suppose you have a header a.h with
struct s1 {
char a;
int b;
char c;
char d;
char e;
}
and this is part of a separate library (of which you only have the compiled binaries compiled by a unknown compiler) and you wish to use this struct to communicate with this library,
if the compiler is allowed to reorder the members in whichever way it pleases this will be impossible as the client compiler doesn't know whether to use the struct as-is or optimized (and then does b go in front or in the back) or even fully padded with every member aligned on 4 byte intervals
to solve this you can define a deterministic algorithm for compacting but that requires all compilers to implement it and that the algorithm is a good one (in terms of efficiency). it is easier to just agree on padding rules than it is on reordering
it is easy to add a #pragma that prohibits the optimization for when you need the layout of to a specific struct be exactly what you need so that is no issue | unknown | |
d14808 | val | Speed efficient deleting rows My solution takes a long time to execute. I have file with 60k rows, and it can be bigger. Can you help me to make this process faster?
Sub kary()
Dim table As Variant
Dim Wb As Workbook
Dim liczba, i As Long
Application.ScreenUpdating = False
Set Wb = Application.ActiveWorkbook
table = Wb.Worksheets("raport").Range("A1").CurrentRegion
i = 8
While Cells(i, 1) <> ""
If Cells(i, 11) <= 0 Or Cells(i, 5) = "FV_K" Or Cells(i, 5) = "KFD" Or Cells(i, 5) = "KR" Then
Rows(i).Delete Shift:=xlUp
Else
i = i + 1
End If
Wend
Application.ScreenUpdating = True
End Sub
A: Can try setting calculation to manual and disabling events
'Optimise code performance
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
.
.
.
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True | unknown | |
d14809 | val | To solve this task you should to use javafx.concurrent.Task , Example.
And simple handle your scroll event, on scroll populate table with additional values. | unknown | |
d14810 | val | Inferring (most general, simple) types for lambda terms is a very simple and highly instructive activity. When you try to decipher a lambda term, starting from guessing its type is a very good approach.
The general idea behind type inference is that you start attributing a generic type (a type variable) to any identifier, and then refine this type according to the use you make of the identifier inside the term. This is very easy in the lambda calculus, since an identifier can only be used in two ways: as an argument for a function or as a function.
For instance, in your example, suppose x: α and y: β. But x is applied to y,
hence it must have a functional type, and moreover its input must be compatible with the type of the argument y, hence we refine α to (β -> γ), where γ is the (so fa unknown) result type of the application (x y).
The term (x y) is in turn applied to y. This implies that γ must actually be a functional type too, that is, say, γ = β -> δ.
This essentially concludes the analysis, in this case.
I report below the type of all subterms, for clarity (please, observe that all applications are well typed):
x : β -> β -> γ
y : β
(x y) : β -> γ
((x y) y) : γ
\y.((x y) y) : β -> γ
\x.\y.((x y) y) : (β -> β -> γ) -> β -> γ
Additionally, we conclude g:β -> β -> γ, and h:β.
The whole expression has type γ.
A slightly more interesting example is provided by the term
\y.\x.(y (y x)).
Suppose x: α. Then y must have type α -> β where β is the type of the result (y x). This term is passed again as an input to y, that means that α=β.
So,
\y.\x.(y (y x)) : (α -> α) -> α -> α
In general, in some cases, when you have multiple uses of a same identifier, you will need need to unify their types, inferring the most general instance between them.
The wikipage about the Damas-Milner type inference algorithm is reasonably fine, but in my opinion exceedingly technical for such a simple and intuitive topic. | unknown | |
d14811 | val | Are you trying to get an array of the dates for each row? Then you want an ARRAY subquery:
SELECT ARRAY(SELECT date FROM UNNEST(event_dim)) AS dates
FROM `table`;
If you are trying to get all dates in separate rows, then you want to cross join with the array:
SELECT event.date
FROM `table`
CROSS JOIN UNNEST(event_dim) AS event;
To filter for a particular date:
SELECT event.date
FROM `table`
CROSS JOIN UNNEST(event_dim) AS event
WHERE event.date = '20170104';
Or you can parse the date string as a date type, which would let you filter on the year or week, for example:
SELECT date
FROM (
SELECT PARSE_DATE('%Y%m%d', event.date) AS date
FROM `table`
CROSS JOIN UNNEST(event_dim) AS event
)
WHERE EXTRACT(YEAR FROM date) = 2017; | unknown | |
d14812 | val | set pointer-events: none in css
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
The pointer-events CSS property specifies under what circumstances (if
any) a particular graphic element can become the target of mouse
events.
*
*Note that while only mouse events are stated, it is in fact valid for all kinds of pointer events - mouse, touch.
From the possible values:
none The element is never the target of mouse events; however, mouse
events may target its descendant elements if those descendants have
pointer-events set to some other value. In these circumstances, mouse
events will trigger event listeners on this parent element as
appropriate on their way to/from the descendant during the event
capture/bubble phases. | unknown | |
d14813 | val | Other ways it can be achieved.
For Adding:
candidate["skills"] = "javascript";
For Deleting:
var skill = "javascript";
delete candidate[skill];
or
delete candidate.skills;
A: Removing a property of an object can be done by using the delete keyword:
candidate.delete("skills");
OR
delete candidate["skills"];
To add a property to an existing object in JS you could do the following.
candidate["skills"] = "javscript";
OR
candidate.skills = "javscript";
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/delete
A: For removing:
How do I remove a property from a JavaScript object?
For adding, just set the new value for that property.
A: You can directly assign "javscript" to "skills" key.
var candidate = {
"name":"lokesh",
"age":26,
"skills":[
"Java",
"Node Js",
"Javascript"
]
};
You can directly do this.
candidate.skills = "javascript";
Or you can delete the "skills" key and add it again.
e.g.
delete candidate["skills"];
candidate["skills"] = "javascript";
A: You should use delete method to delete members of an object.
delete candidate.skills;
Note: You cannot delete objects or functions in the global scope with delete keyword. However you can delete a function which is a member of an object.
A: For removing:
candidate.delete("skills");
For adding:
candidate.skills = "javscript"
A: This piece of coude should do it:
var candidate = {
"name":"lokesh",
"age":26,
"skills":[
"Java",
"Node Js",
"Javascript"
]
};
delete candidate.skills;
console.log(candidate);
candidate["skills"] = "javascript";
console.log(candidate);
A: this is your json object
var candidate = {
"name":"lokesh",
"age":26,
"skills":[
"Java",
"Node Js",
"Javascript"
]
};
to read any prop you can call like:
var name = candidate.name; or candidate[0].name
var age = candidate.age; or candidate[0].age;
var skills = candidate.skills; or candidate[0].skills;
to write any of prop:
candidate.name = 'moaz';
candidate.age = 35;
remove skills value:
candidate.skills = null; or candidate.skills = '';
here skills is list of json if I use as string value or list of string:
candidate.skills = 'javasccript'; //Use skills as string value
candidate.skills.push('javascript'); //Use skills as list of string
to read skills:
for (var i = 0; i < candidate.skills.length; i++) {
var skill = candidate.skills[i];
} | unknown | |
d14814 | val | In the scour download, there is a testscour.py that you could use to see how you can access scour from within the code instead over the cli.
When I was finally solving my mostly similar scour problem, I did it like this:
from scour import scour
import re
with open(svg_file, 'r') as f
svg = f.read()
scour_options = scour.sanitizeOptions(options=None) # get a clean scour options object
scour_options.remove_metadata = True # change any option you like
clean_svg = scour.scourString(svg, options = scour_options) # use scour | unknown | |
d14815 | val | As GoZoner explained, you can't use define in an expression context.
What could you do instead?
Use let:
(if (list? code)
(let ([x '()])
x)
...
Or it would work with an "empty" let and define:
(if (list? code)
(let ()
(define x '())
x)
...
But that's a bit silly.
Or use cond and define:
(cond [(list? code)
(define x '())
x]
...
This last way -- using cond and define -- is closest to what the current Racket style guide recommends.
A: Here's more details, from the Racket docs.
The different contexts are required because macros must expand differently, depending on which language forms are allowed.
As others have said, definitions are not allowed in expression contexts ("expr ..." in the docs), but are ok in other contexts.
In other doc entries, "body ..." indicates an internal-definition context (guide, reference), for example in lambda bodies, and "form ..." indicates all non-expression contexts, like in the docs for begin.
A: Definitions are allowed in a 'body' context, like in lambda and let among others. The consequent and alternate clauses of if are not body contexts; they are expression contexts and therefore definitions are not allowed.
begin is special - begin in a body context allows definitions, but begin in an expression contexts forbids definitions. Your case falls in to the later.
For example:
(define (foo . args) #| body context #|)
(define foo (lambda args #| body context |#))
(define (foo . args)
(let (...)
#| body context |#))
Syntactic keywords that requires expressions: if, cond, case, and, or, when, unless, do, begin. Check out the formal syntax in any Scheme report (r{4,5,6,7}rs); look for <body>, <sequence>, <command>, and <expression>.
Also, if you need a body context in an expression, just wrap a let syntactic form, as such:
(if test
(let ()
(define foo 'foo)
(list foo foo))
alternate)
A: Or you could wrap the expressions in (begin)
e.g.(begin
(define x 10)
(define y 100)
(define z 1000)) | unknown | |
d14816 | val | A very common issue is you forget to trim the string. Try this:
m.final_states.add(Integer.parseInt(scan.next().trim()));
and
t = new Translator(Integer.parseInt(scan.next().trim()), Integer.parseInt(scan.next().trim()));
A: The good thing about Scanner is that it allows to read primitive types w/o explicit casting. You may try the following approach:
try (FileInputStream source = new FileInputStream(PATH)) {
Scanner scanner = new Scanner(source);
Translator translator = new Translator(scanner.nextInt(), scanner.nextInt());
while(scanner.hasNextInt()){
m.final_states.add(scanner.nextInt());
}
}
Please note that with the help of the scanner.hasNextInt() you don't need to count # of your inputs in the second line. | unknown | |
d14817 | val | In VBA and VB6 you can't initialize variables. You must use an executable statement.
However, each variable does have a default initialization value.
From the VB6 documentation:
When variables are initialized, a numeric variable is initialized to
0, a variable-length string is initialized to a zero-length string
(""), and a fixed-length string is filled with zeros. Variant
variables are initialized to Empty. Each element of a user-defined
type variable is initialized as if it were a separate variable.
So actually, in your case,
public i as integer = 0
doesn't work, but the next stement does work, and does just that:
public i as integer
A: I think the issue is that you are attempting to instantiate a public variable at declaration...Dim i As Integer: i = 1 works, but is not public. You can either do this or declare the public variable then instantiate it in the first line of of the sub.
A: Vacip answered it in terms of setting it to 0 like you asked, but to build on it... If you need a public variable to start as something other than the default value you would set it to that value the first time it is called in a sub.
If you have multiple subs that might call it for the first time and then it gets passed back and forth, you need to check to ensure that it hasn't already been set. you can do that with a public boolean.
If you turn on your locals and step through this you can see one way to do it.
Public iTesti As Integer 'defaults to 0
Public bTesti As Boolean 'defaults to FALSE
Public Sub testi()
If bTesti = False Then 'btesti is false and iteseti is 0
iTesti = 1
bTesti = True
End If
iTesti = 2
testi2
End Sub
Public Sub testi2()
If bTesti = False Then 'btesti is true and itesti is 2
iTesti = 1
bTesti = True
End If
iTesti = 3
End Sub | unknown | |
d14818 | val | I think the line should be. From the JSON provided which is not complete, I could only find this error!
sliderCtrlPtr.GetsliderStyle = function() {
if (sliderCtrlPtr.sliderParams != undefined) {
var styleObj = sliderCtrlPtr.sliderParams;
canvas.color = styleObj["styleMapping"]["1"]["StyleMappingCollection"]
["636404903145791477"]["background"]["bgColor"];
canvas.image = styleObj["styleMapping"]["1"]["StyleMappingCollection"]
["636404903145791477"]["background"]["bgImage"];
}
}
A: Dot notation:
First you need to parse the JSON with
obj = JSON.parse(json);
Since the JSON contains objects, you then use the dot notation, e.g.
var backColor = obj.StyleMappingCollection.background.bgcolor;
The thing is, those numeric field names in the JSON could cause problems in using this.
This is en excerpt from a program I've written, in which I have a partners.json file (which contains nested objects in different levels) and I want to store the JSON offices field in an object.
The JSON file is in this form:
[
{
"id": 1,
"urlName": "test-url",
"organization": "Test Organization",
"customerLocations": "Global",
"willWorkRemotely": true,
"website": "http://www.testurl.com/",
"services": "This is a test services string",
"offices": [
{
"location": "Random, Earth",
"address": "Randomness 42, 109 Some St \nRandomville 2000",
"coordinates": "-33.8934219,151.20404600000006"
}
]
}, {"id": 2, ... }]
I import the JSON in my JavaScript code:
/* import partner information from the supplied JSON file */
var partners = require('./partners.json');
And then I parse and stringify the required "offices" fields accordingly:
/* extract all office locations */
var officeLocations = {};
for (var i = 0; i < partners.length; i++) {
officeLocations[i] = JSON.parse(JSON.stringify(partners[i].offices));
}
Hope this helps. | unknown | |
d14819 | val | Try something like this:
public void swapPairwiseIteratively() {
if(first == null || first.next==null) return;
Node one = first, two = first.next, prev = null;
first = two;
while (one != null && two != null) {
// the previous node should point to two
if (prev != null) prev.next = two;
// node one should point to the one after two
one.next = two.next;
// node two should point to one
two.next = one;
// getting ready for next iteration
// one (now the last node) is the prev node
prev = one;
// one is prev's successor
one = prev.next;
// two is prev's successor's successor
if (prev.next != null) two = prev.next.next;
else two = null;
}
}
I am not sure you can do it with only two pointers instead of three. I would work from the solution above (I haven't tested it but it should be correct) and figure out if it can be improved. I don't think the line first = two can be removed.
You could remove the condition if (prev != null) if you move the first pair swapping out of the loop (an optimization that is premature in this example).
A: You can do it either recursively or non-recursively.
public void reverseRecursive(Node startNode)
{
Item tmp;
if(startNode==null || startNode.next ==null)
return;
else
{
tmp = startNode.item;
startNode.item = startNode.next.item;
startNode.next.item = tmp;
reverseRecursive(startNode.next.next);
}
}
Non Recursively
public void reverseNonRecursive()
{
Node startNode = head;
Item temp;
while(startNode != null && startNode.next != null)
{
temp = startNode.item;
startNode.item = startNode.next.item;
startNode.next.item= temp;
startNode = startNode.next.next;
}
} | unknown | |
d14820 | val | Try this:
df_new = df.loc[df['Text'].str.startswith('\n[SPORTS FAN]') | df['Text'].str.startswith('\n[BASEBALL]')]
No regex required | unknown | |
d14821 | val | Try to hide all .description except the current element's linked .description,
$(function () {
$(".trigger").click(function (e) {
e.preventDefault();
$(".description").not($(this).toggleClass('open').next('.description').fadeToggle("slow")).fadeOut('fast');
});
});
DEMO
A: You need to hide the sibling elements like
$(function() {
$(".trigger").click(function(e) {
e.preventDefault();
$(this).toggleClass('open').siblings('.trigger').removeClass('open');
$(this).next('.description').stop().fadeToggle('fast').siblings('.description').stop().fadeOut('fast');
});
});
.description {
display: none;
}
.open {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="trigger">t1</div>
<div class="description">
<p>Here's a description</p>
</div>
<div class="trigger">t2</div>
<div class="description">
<p>Here's a description</p>
</div>
<div class="trigger">t3</div>
<div class="description">
<p>Here's a description</p>
</div> | unknown | |
d14822 | val | You can define your own click event handler and stop propagation of the event there.
$('your selector').click(function (e) {
e.stopPropagation();
});
A: Seems that they haven't given a callback function to call back to. You can modify their JS code to do this -
item.click(function() {
nav.find("." + conf.activeClass).removeClass(conf.activeClass);
item.addClass(conf.activeClass);
self.setPage(item.attr("href"));
if(typeof(clickCallback) != "undefined") clickCallback();
});
So, if you have a function called clickCallback defined on your page, you'll now be able to handle the click event after their click event code has been executed -
function clickCallback() {
//This is the function on your page. This will be called when you click the item.
}
You don't have to call the clickCallback function, the library will itself call that function if its been defined. | unknown | |
d14823 | val | Google's Android Backup Service seems appropriate for this, and is free. | unknown | |
d14824 | val | It's difficult to understand what you're trying to do and what the problem is because the question looks like a mess, but I'll try to help anyway.
Demo:
Here's a working example with your data:
https://codepen.io/AlekseiHoffman/pen/XWJmpod?editors=1010
Template:
<div id="app">
<div v-for="(selection, index) in choice.selections">
<input
type="radio"
:id="selection.id"
:value="selection.selectionId"
v-model="choice.selected"
>
<label>
{{selection.description}}
</label>
</div>
<div>
Selected: {{ choice.selected }}
</div>
</div>
Script:
choice: {
"id": 1,
"selected": 2,
"selections": [
{
"selectionId": 1,
"description": "Radio One"
},
{
"selectionId": 2,
"description": "Radio Two"
}
]
}
I simplified the JSON object since the other properties are not needed there to make it work.
Let me know if you're still having difficulties with your task. | unknown | |
d14825 | val | I guess you are using two different properties of DateTime (or simply Date) class: Now and UtcNow.
Try to use UtcNow, if you use Now, or vice versa. | unknown | |
d14826 | val | The whole point of Sha256 hashing is that you cannot decrypt it. When doing a login check, you should hash the user entered password and match it with the one you've stored in your datalayer.
A: DigestUtils.sha256Hex is not encription it is hash. Main property of hash it is irreversible | unknown | |
d14827 | val | class App extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [
{ firstName: 'John1', middleName: 'Daniel1', lastName: 'Paul1' },
{ firstName: 'John2', middleName: 'Daniel2', lastName: 'Paul2' },
{ firstName: 'John3', middleName: 'Daniel3', lastName: 'Paul3' },
{ firstName: 'John4', middleName: 'Daniel4', lastName: 'Paul4' },
],
};
}
_onChangeUser = (index, field, event) => {
const newValue = event.target.value;
this.setState(state => {
const users = [
...state.users.slice(0, index),
{
...state.users[index],
[field]: newValue,
},
...state.users.slice(index + 1),
];
return {
users,
};
});
};
_onSubmit = event => {
event.preventDefault();
// Do something with this.state.users.
console.log(this.state.users);
};
render() {
return (
<div className="App">
<form onSubmit={this._onSubmit}>
{this.state.users.map((user, index) => (
<div key={index}>
<input
value={user.firstName}
onChange={this._onChangeUser.bind(this, index, 'firstName')}
/>
<input
value={user.middleName}
onChange={this._onChangeUser.bind(this, index, 'middleName')}
/>
<input
value={user.lastName}
onChange={this._onChangeUser.bind(this, index, 'lastName')}
/>
</div>
))}
<button type="submit">Submit</button>
</form>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"><div>
A: Ok. Declare your state variable as an array. Below should fulfill your requirement.
constructor(props){
super(props)
this.state={
firstNameArray:[],
middleNameArray:[],
lastNameArray:[],
fName:” “,
mName:””,
lName:””
}
this.changeFirstName = this.changeFirstName.bind(this);
this.changeMiddleName= this.changeMiddleName.bind(this);
this.changeLastName=this.changeLastName.bind(this);
}
changeFirstName(event){
this.setState({
firstNameArray:event.target.value,
fName: event.target.value
})
changeMiddleName(event){
this.setState({
middleNameArray: event.target.value,
mName: event.target.value
})
}
changeLastName(event){
this.setState({
lastNameArray: event.target.value,
lName: event.target.value
})
Call each function on your input field like below
<input type=‘text’ name=‘fName’ value= {this.state.fName} onChange={this.changeFirstName} />
Do it in the same way for other two input fields as well. Hope this answers your question. | unknown | |
d14828 | val | My first thought: are you sure you have any lines with a lang property?
[EDITED] Also, try decreasing the batch size for each periodic commit. The default is 1000 lines. For example: USING PERIODIC COMMIT 500 to specify a batch size of 500.
Also, I see a probable logic error, but it should not be the cause of your main issue ("nothing" happening).
The logic error is this: even if the MERGE clause found an existing (s:String) node, the CREATE clause will always go ahead and create (yet another) [:name] relationship between i and s (even if one or more already existed).
You probably meant something like this, instead:
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file:///data_ssd/world/test.csv" AS line
WITH line
WHERE line.lang IS NOT NULL
MERGE (i:Item {id: line.id})-[:name]->(s:String {value: line.name, lang: line.lang}) | unknown | |
d14829 | val | I am not an expert in this area, however, I think that 1.) you need to add a handler to your ajax call to determine if the delete was successful & 2.) you may need to add some sort of success status message from the controller's destroy action.
A: The following solved the same problem for me.
respond_to do |format|
format.js { head :ok }
end
I'm unsure if this is better practice than using render :nothing => true or render :text => "". | unknown | |
d14830 | val | As mentioned, you need to change the SQL Task to give a Result Set on a 'Single Row', you can then output that result set to a variable.
From here you can use the constraints within the Control Flow to execute different tasks based upon what the outcome variable will be; for example: | unknown | |
d14831 | val | You need to be distinct if you are using the Memcache class or the Memcached class. Your cache design is a bit strange. You should be checking the cache to first see if the item is there. If the item is not then store it. Also Memcache has some strange behavior on using the boolen type as the third argument. You should MEMCACHE_COMPRESSED. I think you are using Memcache.
To illustrate how to fix your problem:
$in_cache = $memcached->get('test_key');
if($in_cache)
return $in_cache;
else
$valueToStore = time();
$memcached->add('test_key', $valueToStore, MEMCACHE_COMPRESS, 20); | unknown | |
d14832 | val | You could start by closing your HTML containers, and giving a good example of what you've tried.
If you set an explicit width, width: 800px;, that's the width it will be rendered at.
Try setting the container's max-width for that and set the width to expand to that
The way that I usually do it:
.container {
max-width: 800px;
width: 100%;
}
A: Try using percentages instead of pixels. Pixels will give you a fixed width. Percentage with keep thing proportional.
Here is a good article to help you understand what the different measurements mean.
Once you understand what they mean, you should be able to make a better selection depending on the usage you expect.
https://www.w3schools.com/cssref/css_units.asp | unknown | |
d14833 | val | The easy approach is to divide the plane into d-by-d where d > 10 bins and put each point in the bin indexed by floor(x/d), floor(y/d). Then, instead of iterating over all pairs of points,
for bin1 in bins:
for i in bin1:
for bin2 in bins neighboring bin in nine directions (including bin):
for j in bin2:
if(distance(i, j) <= 10) addEdge between i and j
This will make things faster if the points are well spread, but the worst case is still quadratic.
For a guaranteed O(n log n)-time algorithm, compute the Delaunay triangulation and throw away the edges longer than 10. This may remove some direct connections between nodes at distance less than or equal to 10, but they will still be connected indirectly.
A: The binning approach suggested by David Eisenstat's answer works if you expect points to be homogeneously distributed, which is not a property you specified about your data. Additionally, as noted, the Delaunay triangulation still requires local search on the induced graph to ensure that all nodes within the specified distance are found.
One way to get guaranteed performance is with a kd-tree. You can build one in O(2n log n) time (or faster if you don't care as much about guarantees and use randomization) and use it for performing range searches with a total time of O(2n√n).
It's unclear to me whether the Delaunay triangulation or the kd-tree would be faster in practice, but it seems to me that finding and using an appropriate kd-tree library would be a fast and simple solution, if you are worried about development time. | unknown | |
d14834 | val | First, I would just assume that all the file-names are supplied on standard input. E.g., if the file names.txt contains the file-names and check.sh is the script, you can invoke it like
cat names.txt | ./script.sh
to obtain the desired behaviour (i.e., using the file-names from names.txt).
Second, inside script.sh you can loop as follows over all lines of the standard input
while read line
do
... # do your checks on $line here
done
Edit: I adapted my answer to use standard input instead of command line arguments, due to the problem indicated by @rici.
A: while read dirname
do
echo $dirname >> result.txt
while read filename
do
find $dirname -type f -name $filename >> result.txt
done <filenames.txt
done <dirnames.txt | unknown | |
d14835 | val | You need to use either the VLOOKUP or HLOOKUP feature when structuring your results table. For instance in cell C3 (color for head/set1) you would type =HLOOKUP(a2,e2:h5,2,FALSE). It will look horizontally in the first row for whatever is in cell A2 (HEAD) and return the value from the 2nd row (RED). Of flip it around to use HLOOKUP.
https://support.office.com/en-us/article/hlookup-function-a3034eec-b719-4ba3-bb65-e1ad662ed95f
A: Please try this formula, to be entered in row 3 where columns A and B are "category" and "Sets" respectively.
=VLOOKUP(B3,E1:H4,MATCH(A3,E1:H1,0),FALSE)
E1:H4 represents your entire table2 incl captions. You can exclude the caption row - probably better. E1:H4 is the first row of that same range. There is presumed to be only one caption row which is needed, and must be 1 only. If you prefer a neater solution take the data column captions only and adjust the result. Then your formula might look like this.
=VLOOKUP(B2,E2:H4,MATCH(A2,F1:H1,0)+1,FALSE) | unknown | |
d14836 | val | I tried It out by myself and came up with that:
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StackoverflowHelp
{
public partial class Form1 : Form
{
Form2 form = new Form2();
public Form1()
{
InitializeComponent();
form.Show();
}
private void Button1_Click(object sender, EventArgs e)
{
form.DrawCircle(100, 100);
}
}
}
Form2.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StackoverflowHelp
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
DrawCircle(10, 10);
}
public void DrawCircle(int x, int y)
{
Graphics gf = Graphics.FromImage(pictureBox1.Image);
gf.DrawEllipse(new Pen(Color.Red), new Rectangle(x, y, 20, 20));
gf.Dispose();
pictureBox1.Refresh();
pictureBox1.Invalidate();
pictureBox1.Update();
}
}
}
Instead of calling CreateGraphics() on the picturebox I created the graphics object using the current image. | unknown | |
d14837 | val | Welcome to StackOverflow! In the future, you can probably get a good answer faster if you write your question more clearly.
You can use document.getElementById('id_of_text_input').value to get or set the value of any text input. Note that you are using id, not name.
You can use parseFloat to get a read a string as a floating number value.
In order to attach a function to the onblur event, you can use the setAttribute function.
So, for example, if you have a text input with id colA and you want to subtract 100 from the value the user enters and save the result in a text input with id colB.
You could write code like this:
<html>
<head runat="server">
<title></title>
</head>
<body>
<input type='text' id='colA' />
<input type="text" id='colB' />
</body>
<script type="text/javascript">
var colA = document.getElementById('colA');
var colB = document.getElementById('colB');
colA.setAttribute('onblur',
function () {
var value = colA.value;
var number = parseFloat(value)-100;
colB.value = number;
});
</script>
</html>
A: Very useful for me. Thanks, Daniel
If you want to calculate a percentage (5% for example) and use Jquery, you have to
$(function(){
$(".input-valorinicial").blur(function(){
var valorinicial = document.getElementById('valorinicial');
var fee = document.getElementById('fee');
var value = valorinicial.value;
var number = parseFloat(value)*5/100;
fee.value = number;
});
}); | unknown | |
d14838 | val | The problem is the order of your arguments. Try to switch -E and -D. | unknown | |
d14839 | val | I believe you have 2 errors:
1 - your select call is limiting the check to a max of fd 2, where the pipe will probably have larger FDs since 0, 1, and 2 are already opened for stdin, stdout, stderr. The pipe FDs will presumably have fds 3 and 4 so you actually need to determine the larger of the 2 pipe FDs and use that for the limit in the select instead of 2.
int maxfd = pfd[1];
if( pfd[0] > maxfd ) {
maxfd = pfd[0];
}
...
2 - After select returns, you are looking at the wio and pipe write FD when you need to instead look to see if there is anything available to READ:
if (FD_ISSET(pfd[0], &rio)) { | unknown | |
d14840 | val | You should not join your array at all. In your example $json_array['stream']['preview']; is the following:
array(
'small' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-80x50.jpg',
'medium' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-320x200.jpg',
'large' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-640x400.jpg',
'template' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-{width}x{height}.jpg'
);
So you can use either one of the provided images:
*
*$json_array['stream']['preview']['small']
*$json_array['stream']['preview']['medium']
*$json_array['stream']['preview']['large']
If none of the images fit your desired resolution you can use the template:
echo str_replace("{width}", $width, str_replace("{height}", $height,"Hello world!"));
A: In joining the array in to a string you wont have a link for an image, you will have 3 links joined together. Use;
$json_array['stream']['preview'][0]
and change the 0 for which of the images you want. | unknown | |
d14841 | val | *
*$ifNull to check if field is null then return empty array
*$in to check "foo" is in overrides.property array
*$indexOfArray to get index of array element in overrides.property array
*$arrayElemAt to get element by specific index return from above operator
let fooOverrideExists = "foo";
db.collection.find({},
{
overrideOrOriginal: {
$cond: [
{
$in: [
fooOverrideExists,
{ $ifNull: ["$overrides.property", []] }
]
},
{
$arrayElemAt: [
"$overrides.value",
{ $indexOfArray: ["$overrides.property", fooOverrideExists] }
]
},
"$foo"
]
}
})
Playground
A: Query
*
*find the property , key-value(kv) (it works for all property names)
(assumes your schema with only string value the value of that property)
*checks if that it exists in the overrides array
*if it exists, takes the value from the array
*else keeps the original
*checks also cases where override doesnt exists, or its empty array, or property doesn't exist
*in case you want to do it only for a specific "foo" ignore the big first $set and use this code
Test code here
db.collection.aggregate([
{
"$set": {
"kv": {
"$arrayElemAt": [
{
"$filter": {
"input": {
"$objectToArray": "$$ROOT"
},
"cond": {
"$eq": [
{
"$type": "$$this.v"
},
"string"
]
}
}
},
0
]
}
}
},
{
"$set": {
"index": {
"$indexOfArray": [
"$overrides.property",
"$kv.k"
]
}
}
},
{
"$project": {
"_id": 0,
"overrideOrOriginal": {
"$cond": [
{
"$or": [
{
"$eq": [
"$index",
-1
]
},
{
"$not": [
"$overrides"
]
}
]
},
"$kv.v",
{
"$arrayElemAt": [
"$overrides.value",
"$index"
]
}
]
}
}
}
]) | unknown | |
d14842 | val | I have ask Malte Ubl on Twitter. His anwser is:
This controls an experiment on the AMP cache.
A: According to this Google Analytics forum, the said unusual parameter has been removed. Kindly confirm if this has been reflected on yours as well. | unknown | |
d14843 | val | The LruCache is being instantiated in one class. It won't be accessible from another class. You could try the approach mentioned in this answer
https://stackoverflow.com/a/14325075/2931650 | unknown | |
d14844 | val | @amehta, no, 8.4 and 9.0 is not your problem. My naive guess is that your configuration is missing:
adapter: postgresql
The problem is entirely local inside of your Heroku setup. Try manually connecting from Heroku to EC2:
require 'postgres'
conn = PGconn.connect('amazone-host', 5432, '', '', 'dbname', 'username', 'pass')
puts conn.exec('SELECT version()')[0]
to see if you can further isolate the problem.
A: the problem is that heroku overwrites the database.yml....so when you call ActiveRecord::Base.establish_connection(:external_db) there is no .yml definition for that db | unknown | |
d14845 | val | This is not a real code. A real login code should include a lot more, like securing channels, ecryption, etc.
As an exercise to try a few concepts it's ok.
I see you are expecting to save everything to a file, I suggest you to try with logical structures first.
There is always messing with opened files not being able to be updated and the like.
Another recommendation is to keep distinct functions to distinct funcionalities, is easier to maintain and to debug.
I see a perfect use for dictionary, with key (login) and value (password).
Would be good to create a class and put options_menu() in main function.
dict_logs = {'afrank':'xyz123','lcroft':'xpto0007','happy_bird':'123abc'}
#check name and password are in a dictionary
def hello_login():
isUser = False #start as False
print('What is your user name?')
user = str(input())
for u,p in dict_logs.items():
if u == user:
dictpass = p
isUser = True
if isUser:
print('Enter password')
password = str(input())
if dictpass == password:
print('Login Success!')
else:
print('Error: wrong password')
options_menu()
else:
print('Error: wrong user name')
options_menu()
user_info = {392111111:['afrank',2018],392111131:['lcroft',2018],392113005:['happy_bird',2019]}
# check if information is in a dictionary and updates another dict
def reset_password():
isUser = False #start as False
changed = False #start as False
print('What is your student ID?')
sid = int(input())
for ui,data in user_info.items():
if ui == sid:
checksOn = data
isUser = True
if isUser:
print('What is your user name?')
uname = str(input()) #accept parameter user_name
if checksOn[0] == uname:
print('What year were you admitted?')
year = int(input()) #accept parameter year of admission
if checksOn[1] == year:
while not changed: #loop if changed not True
print('Enter a new password')
newPass = str(input()) #accept parameter password
if dict_logs[uname] != newPass: #must be distinct of saved password
print('Confirm password')
confPass = str(input())
if confPass == newPass: #confirmation ok
dict_logs.update({uname:confPass})
changed = True
print('Password changed!')
else:
print('Error:passwords are distincts!')
else:
print('Error. Your password cannot be a previously used password.')
else:
print('Error. Year of addmission is wrong')
else:
print('Error. User name is wrong')
else:
print('Error! Please enter your Student ID Number')
# menu of options
def options_menu():
print('1. Login'+'\n'+'2. Reset Password'+'\n'+'3. Quit'+'\n'+'What would you like to do?')
option = int(input())
if option == 1:
hello_login()
elif option == 2:
reset_password()
elif option == 3:
pass
A: Ok so quick disclaimer all the code in this is sudo code and is for example to give you the idea of my train of thought.
So that out of the way I see your problems as the following.
*
*User Input (Actions)
*DataBase Handling
If I am correct on this I would suggest that you take the following approach.
*
*Take care of the Database, by writing a class to handle the getting and setting of specific user in an out of the database that you are using and into a dictionary or any other data structure allows you to forget the structure of the underlying csv etc and will make you actions clearer and simpler later on. something like below would do the trick.
class UserDataBase(object):
def __init__(self):
self.database = db
def get_user(self, username) -> dict:
return {"Joe": {"password": "uber_secret"}}
def set_user(self, username, user_obj: dict) -> None:
db[username] = user_obj
*Next it would be time to take care of the user input, again this should be an object that would define and execute the actions that you define in your use cases.
class Actions(object):
def __init__(self, database):
self.database = UserDataBase()
def login(self, username, password) -> bool:
if self.database.get_user(username) == password:
return True
return False
def reset_password(self, old_password, new_password, confirmed_password) -> bool:
reset_code
def quit(self):
quit()
This would then leave you with two objects that you can tie together to get anything that you want to do done more simply.
def get_input():
actions = Actions(
database=UserDataBase()
)
i = input(' 1. Login \n 2. Reset Password \n 3. Quit \n What would you like to do? \n ')
if i == 1:
actions.login(username=input('username: '), password=input('password: '))
get_input()
if you have any specific questions about this approach please let me know. | unknown | |
d14846 | val | You need to access the property using square brackets; the way you have it is implying that there's a button that's literally called 'nameOfButton', which is why it's failing. Try the following:
private function makeButtonBigger(ev:MouseEvent):void{
var nameOfButton:String = ev.currentTarget.name;
this.group_btn[nameOfButton].scaleX = 1.2;
trace(nameOfButton);
}
That will use the actual captured string, rather than the variable name itself.
Although, you can also access the button directly from the event's currentTarget property:
private function makeButtonBigger(ev:MouseEvent):void{
ev.currentTarget.scaleX = 1.2;
} | unknown | |
d14847 | val | This should help.
user_choice_port = "23, 80, 44"
print map(int, user_choice_port.split(","))
print [int(n) for n in user_choice_port.split(",")] | unknown | |
d14848 | val | If I understand right, you're looking for scroll down steps by steps on li elements just on clicking on the arrow ?
If that's it :
You could maybe use smooth scroll plugin like ui.kit and trigger a click event in setTimeout or setIntervall which scroll down on every element following an array like
myListEl = ['#first', '#second', etc...];
http://getuikit.com/docs/smooth-scroll.html
A: Do something like : Fiddle
angular.module("testApp", []).controller('ScrollCtrl', ['$scope', function($scope) {
$scope.scrolltoBottom = function() {
var list = $(".verticalCarouselGroup");
list.animate({ "marginTop": "+=50px" }, "slow");
};
$scope.scrolltoTop = function() {
var list = $(".verticalCarouselGroup");
list.animate({ "marginTop": "-=50px" }, "slow");
};
}]);
To stop it from scrolling you can add checks for bottom and top.
Hint : compare bottom top with marginTop : (list.css('marginTop')) | unknown | |
d14849 | val | I got the problem!! the issue is the .htaccess file that i am using to force the http into htpps. I don't know why but with it the Svg does not work and without it the SVG works great. | unknown | |
d14850 | val | 0 13,19 * * * /usr/bin/php path/myphp.php should work, check your log / user mail for errors.
A: Keep in mind that there's a difference in format between a user's crontab (accessed with the command contab -e or what have you) and the system's crontab, managed in files like /etc/cron.d and others.
In a user's personal crontab, the format you used should work.
In the system crontab, (if you place a new file or edit anything under /etc), make sure you specify the user name to run as before the command, for example:
0 13,19 * * * www-data /usr/bin/php path/myphp.php
Will run the command /usr/bin/php path/myphp.php as user www-data every day at 13:00 and 19:00. | unknown | |
d14851 | val | I have had a similar question and I was using signal:
import signal
def signal_handler(signal_number, frame):
print "Proceed ..."
signal.signal(signal.SIGINT, signal_handler)
signal.pause()
So you register a handler for the signal SIGINT and pause waiting for any signal. Now from outside your program (e.g. in bash), you can run kill -2 <python_pid>, which will send signal 2 (i.e. SIGINT) to your python program. Your program will call your registered handler and proceed running.
A: print ("This is how you pause")
input()
A: I use the following for Python 2 and Python 3 to pause code execution until user presses Enter
import six
if six.PY2:
raw_input("Press the <Enter> key to continue...")
else:
input("Press the <Enter> key to continue...")
A: As pointed out by mhawke and steveha's comments, the best answer to this exact question would be:
Python 3.x:
input('Press <ENTER> to continue')
Python 2.x:
raw_input('Press <ENTER> to continue')
For a long block of text, it is best to use input('Press <ENTER> to continue') (or raw_input('Press <ENTER> to continue') on
Python 2.x) to prompt the user, rather than a time delay. Fast readers
won't want to wait for a delay, slow readers might want more time on
the delay, someone might be interrupted while reading it and want a
lot more time, etc. Also, if someone uses the program a lot, he/she
may become used to how it works and not need to even read the long
text. It's just friendlier to let the user control how long the block
of text is displayed for reading.
Anecdote: There was a time where programs used "press [ANY] key to continue". This failed because people were complaining they could not find the key ANY on their keyboard :)
A: Very simple:
raw_input("Press Enter to continue ...")
print("Doing something...")
A: For Windows only, use:
import os
os.system("pause")
A: By this method, you can resume your program just by pressing any specified key you've specified that:
import keyboard
while True:
key = keyboard.read_key()
if key == 'space': # You can put any key you like instead of 'space'
break
The same method, but in another way:
import keyboard
while True:
if keyboard.is_pressed('space'): # The same. you can put any key you like instead of 'space'
break
Note: you can install the keyboard module simply by writing this in you shell or cmd:
pip install keyboard
A: cross-platform way; works everywhere
import os, sys
if sys.platform == 'win32':
os.system('pause')
else:
input('Press any key to continue...')
A: It seems fine to me (or raw_input() in Python 2.X). Alternatively, you could use time.sleep() if you want to pause for a certain number of seconds.
import time
print("something")
time.sleep(5.5) # Pause 5.5 seconds
print("something")
A: So, I found this to work very well in my coding endeavors. I simply created a function at the very beginning of my program,
def pause():
programPause = raw_input("Press the <ENTER> key to continue...")
and now I can use the pause() function whenever I need to just as if I was writing a batch file. For example, in a program such as this:
import os
import system
def pause():
programPause = raw_input("Press the <ENTER> key to continue...")
print("Think about what you ate for dinner last night...")
pause()
Now obviously this program has no objective and is just for example purposes, but you can understand precisely what I mean.
NOTE: For Python 3, you will need to use input as opposed to raw_input
A: I work with non-programmers who like a simple solution:
import code
code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals())
This produces an interpreter that acts almost exactly like the real interpreter, including the current context, with only the output:
Paused. Press ^D (Ctrl+D) to continue.
>>>
The Python Debugger is also a good way to pause.
import pdb
pdb.set_trace() # Python 2
or
breakpoint() # Python 3
A: I assume you want to pause without input.
Use:
time.sleep(seconds)
A: I think I like this solution:
import getpass
getpass.getpass("Press Enter to Continue")
It hides whatever the user types in, which helps clarify that input is not used here.
But be mindful on the OS X platform. It displays a key which may be confusing.
Probably the best solution would be to do something similar to the getpass module yourself, without making a read -s call. Maybe making the foreground color match the background?
A: user12532854 suggested using keyboard.readkey() but the it requires specific key (I tried to run it with no input args but it ended up immediately returning 'enter' instead of waiting for the keystroke).
By phrasing the question in a different way (looking for getchar() equivalent in python), I discovered readchar.readkey() does the trick after exploring readchar package prompted by this answer.
import readchar
readchar.readkey()
A: I think that the best way to stop the execution is the time.sleep() function.
If you need to suspend the execution only in certain cases you can simply implement an if statement like this:
if somethinghappen:
time.sleep(seconds)
You can leave the else branch empty.
A: For cross Python 2/3 compatibility, you can use input via the six library:
import six
six.moves.input( 'Press the <ENTER> key to continue...' ) | unknown | |
d14852 | val | It seems I didn't need to have 'public' in the src url call for anyone who may experience a similar issue in future. The video tag now looks like so:
<video autoPlay loop muted className='w-full h-screen z-10'>
<source src='/assets/bubble-video.mp4' type='video/mp4' />
</video>
A: adding mute attribute to the video tag solved a similar issue for me
<video
preload="auto"
playsInline
autoPlay
muted
loop
>
<source src="/video.mp4" type="video/mp4" />
</video> | unknown | |
d14853 | val | Well, you can extend a JSF component with the regular java extension (extends). You will have to extend a number of classes, depending on the exact component:
*
*UIComponentName/HtmlComponentName
*HtmlComponentNameRenderer
*ComponentNameTag
and you might need to register the renderer in faces-config.xml.
You can take a look at this thread, or google for "Extend JSF component" or "Create custom JSF component". | unknown | |
d14854 | val | You can either check in every route if the session is loggedIn or not in activate hook of route like this..
if you are setting a variable loggedIn true here is how to do it.
App.PostRoute = Ember.Route.extend({
activate: function() {
if (!loggedIn){
this.tansitionTo('login');
}
}
});
If you want to remove totally PostRoute from history you can use replaceWith rather transitionTo.
.or use these for authentication ember-auth or simple-auth | unknown | |
d14855 | val | Now I know Git is very powerful:
1. create a new branch and make change, would not affect other branches.
2. I can create branch with a SHA key (every commit has a unique key)
I have made my first the pullrequest, it's feel good. | unknown | |
d14856 | val | The way I would do it is. Create a filter which would basically receive everything sent from the sequencer and send it to your midi out. Inside this filter create a condition where if the "pause flag" is true all note offs would be received but not sent.
Create a pause() method which when called first sets your "pause flag" to true and then does sequencer.stop().
Of course you would need some way to keep track of the note offs that have been blocked so that you can actually stop them when you eventually do want to or else they will really stay on for ever. | unknown | |
d14857 | val | As an alternate approach, you can split string by space and the merge chunks in batch.
function splitByWordCount(str, count) {
var arr = str.split(' ')
var r = [];
while (arr.length) {
r.push(arr.splice(0, count).join(' '))
}
return r;
}
var a = "This is a test this is a test";
console.log(splitByWordCount(a, 3))
console.log(splitByWordCount(a, 2))
A: your code is good to go. but not with split. split will treat it as a delimitor.
for instance something like this:
var arr = "1, 1, 1, 1";
arr.split(',') === [1, 1, 1, 1] ;
//but
arr.split(1) === [', ', ', ', ', ', ', '];
Instead use match or exec. like this
var x = "This is a test this is a test";
var re = /\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/g
var y = x.match(re);
console.log(y);
A: The String#split method will split the string by the matched content so it won't include the matched string within the result array.
Use the String#match method with a global flag (g) on your regular expression instead:
var sample="This is a test this is a test"
const re = /\b[\w']+(?:\s+[\w']+){0,2}/g;
const wordList = sample.match(re);
console.log(wordList);
Regex explanation here.
A: Use whitespace special character (\s) and match function instead of split:
var wordList = sample.text().match(/\s?(?:\w+\s?){1,3}/g);
Split breaks string where regex matches. Match returns whatever that is matched.
Check this fiddle.
A: You could split like that:
var str = 'This is a test this is a test';
var wrd = str.split(/((?:\w+\s+){1,3})/);
console.log(wrd);
But, you have to delete empty elements from the array. | unknown | |
d14858 | val | SXSSFWorkbook is for streaming-writing, not reading. Did you try with XSSFWorkbook instead? This will still require quite some memory so might still go OOM with 1024m, depending on the size of the workbook.
Another approach is a streamed reading approach, see e.g. https://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api for some description of this approach. There will be some features that are not supported there, though, so it might or might not be applicable for your use case. | unknown | |
d14859 | val | This technically achieves the result you are asking for. However, I am assuming you want everything to be added together if at least 2 of the lists have numbers within 2 indexes of each other. For example [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]] would result in [1, 1, 0, 0, 1] NOT [[1, 1, 0, 0, 0], [0, 0, 0, 0, 1]] despite the last list having its number more than 2 indexes away from any other list.
The code sums the lists together, then finds how far apart the first 2 non-zero number are. If they are <= 2 indexes apart, then the summed list is added to zp_dict, else the list of lists (v) remains unchanged, and added to the zp_dict
The code is on OnlineGDB, if you want to tinker with it
Note: I assumed 'K' in the dct you provided had a typo, in that it was supposed to be a list within a list (like the others) - if not, sum(x) for x in zip(*v) would break. If not, it doesn't take much to fix - just validate the number of lists in v.
dct = {
'T': [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 1, 0]],
'B': [[0, 1, 0, 0, 0], [0, 0, 0, 0, 1]],
'J': [[0, 0, 1, 0, 0], [0, 0, 0, 0, 1]],
'K': [[0, 0, 0, 0, 1]]
}
zp_dict = {}
for k, v in dct.items():
sum_list = [sum(x) for x in zip(*v)]
first_non_zero = next((i for i, n in enumerate(sum_list) if n), 0)
second_non_zero = next((i for i, n in enumerate(sum_list[first_non_zero+1:]) if n), 0)
zp_dict[k] = sum_list if second_non_zero < 2 else v
print(zp_dict)
>>{'T': [2, 1, 0, 1, 0], 'B': [[0, 1, 0, 0, 0], [0, 0, 0, 0, 1]], 'J': [0, 0, 1, 0, 1], 'K',: [0, 0, 0, 0, 1]}
EDIT:
You can also add if statements (with functions inline), if that is what you were looking for.
zp_dict[k] = [sum(x) for x in zip(*v) if conditionTest(v)]
If the conditionTest returns True, it would add the lists together. Although if you were fine with adding functions, I would clean it up and just add the for loop into the function:
zp_dict[k] = sumFunction(v) | unknown | |
d14860 | val | Here is a simple Python 2.7 solution I've cooked for you:
It depends only on the OleFileIO_PL module which is availble from the project page
The good thing with OleFile parser is that it is not aware of the "excel-specific" contents of the file ; it only knows the higher level "OLE storage". So it is quick in analyzing the file, and there is no risk that a potentially harmful macro would execute.
import OleFileIO_PL
import argparse
if __name__=='__main__':
parser = argparse.ArgumentParser(description='Determine if an Excel 97-2007 file contains macros.', epilog='Will exit successfully (0) only if provided file is a valid excel file containing macros.')
parser.add_argument('filename', help="file name to analyse")
args=parser.parse_args()
# Test if a file is an OLE container:
if (not OleFileIO_PL.isOleFile(args.filename)):
exit("This document is not a valid OLE document.")
# Open an OLE file:
ole = OleFileIO_PL.OleFileIO(args.filename)
# Test if known streams/storages exist:
if (not ole.exists('workbook')):
exit("This document is not a valid Excel 97-2007 document.")
# Test if VBA specific streams exist:
if (not ole.exists('_VBA_PROJECT_CUR')):
exit("This document does not contain VBA macros.")
print("Valid Excel 97-2007 workbook WITH macros")
I tested it on a couple of files with success. Let me know if it's suitable for you | unknown | |
d14861 | val | CodeMirror has several Content manipulation methods. You will need to use the setValue method.
doc.setValue(content: string)
Set the editor content.
Please reference the following block of code for my suggestions.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.46.0/codemirror.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.46.0/codemirror.min.css">
</head>
<body>
<!-- File Button -->
<div class="form-group">
<label class="row justify-content-md-center" for="filebutton" style="font-size: 40px">Choose a file to compile:</label>
<div class="row justify-content-md-center">
<input id="filebutton" name="filebutton" class="input-file" type="file">
</div>
</div>
<div class="row justify-content-md-center">
<p style="font-size: 40px;"> or...</p>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="row justify-content-md-center" for="textarea" style="font-size: 40px">Write the file in the text field below: </br>
</label>
<div class="col-md-6 offset-md-3">
<div id="textarea" name="textarea" placeholder="Type your code here!" style="min-height: 250px; min-width: 100%; border-style: solid; border-width: 1px; border-color: gray"></div>
<!-- This is where I think the problem is -->
<script>
let editor = CodeMirror(document.getElementById("textarea"), {
lineNumbers: true,
mode: "cobol",
theme: "colorforth"
});
document.getElementById("filebutton").addEventListener('change', function() {
var fr = new FileReader();
fr.onload = function() {
editor.setValue(this.result); // Need to use the setValue method
//document.getElementById("textarea").textContent = this.result;
}
fr.readAsText(this.files[0]);
})
</script>
<!-- This is where I think the problem is -->
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="row justify-content-md-center" for="singlebutton"></label>
<div class="row justify-content-md-center">
<button id="textareabutton" name="singlebutton" class="btn btn-primary" onclick="main()" style="background-color:red; border-color:red;">Compile</button>
</div>
</div>
</body>
</html>
More specifically, editor.setValue(this.result); is what got it working. Take a look at this JS Bin
In your fileUploadScript.js you must use editor.setValue().
document.getElementById("filebutton").addEventListener('change', function () {
var fr = new FileReader();
fr.onload = function () {
editor.setValue(this.result);
//document.getElementById("textarea").textContent = this.result;
}
fr.readAsText(this.files[0]);
})
You can't force the code into the textarea. It just won' work. You have to use the setValue method as shown above.
CodeMirror: Usage Manual. | unknown | |
d14862 | val | CAS does not set a cookie with the user login. It will set a cookie for your SSO session called a Ticket Granting Cookie (TGC). This token does not provide any information on the logged user.
To retrieve the identity of the user logged you have to validate a Service Ticket. This ticket is appended to the url of your service when CAS/login redirect you back to you application. Then a CAS Client must validate that ticket against CAS/serviceValidate. That client should be in your backend and the username set in the session. Up to you to send it to your frontend the way you want. | unknown | |
d14863 | val | Check the server's connection timeout (on the Web Site properties page).
A better approach would be to send the request, start the calculation on the server, and serve a page with a Javascript timer that keeps sending requests to itself. Upon post-back, this page checks whether the server process has completed. While the process is still running, it responds with another timer. Once it has completed, it redirects to the results.
A: Would you clarify how you fixed this problem? It seems I have the same one. I'm getting .docx report and both browsers (IE10 and Fx37) indefinitely wait for a response (keep on spinning).
But it works great in VS2012's IIS Express and on my localhost IIS7.
Although server has IIS6.1
And when it works on localhost, it's just several minutes to get a report. | unknown | |
d14864 | val | Inside your app module constructor, you can tell what is the default language which you're interested in
export class AppModule {
constructor(translate: TranslateService) {
translate.setDefaultLang('en');
translate.use('en');
}
} | unknown | |
d14865 | val | You probably can, but in the current state of the plugin, it looks like you have to define a separate task that extends from the FindBugs one, but has a different configuration than the standard one.
The problem is that you will run FindBugs twice indeed, and that can be a performance penalty with any decently-sized codebase.
Obviously you can't use tasks.withType(FindBugs) { ... } to configure your tasks, you have to do it by task name explicitly.
Note: if you are running this on e.g. Jenkins, you would want your build.gradle to generate the xml report, and let Jenkins generate the html report from the xml one. That way it is not executed twice in your build.
A: I solved this by configuring my Gradle script so that it generates findbugs tasks for XML and HTML reports then generates a task which depends on the other two.
def findbugsTask = task('findbugs') {
group 'Verification'
}
[ 'Html', 'Xml' ].each { reportType ->
findbugsTask.dependsOn task("findbugs${reportType}", type: FindBugs) {
dependsOn 'compileJavaWithJavac'
reports {
html.enabled = reportType == 'Html'
xml.enabled = reportType == 'Xml'
}
}
}
Note that this will run the Findbugs tool twice, which generally shouldn't be an issue for continuous integration (unless your code base is huge).
A: You can generate both reports without running FindBugs twice, but it isn't intuitive. If you look at how FindBugs generates its html report, you'll find it actually generates the xml first and just uses xslt to transform it into html. Knowing this, and subsequently resourcing a spotbugs issue that documented a workaround, I got the same approach working with FindBugs.
In my build.gradle file I am generating just the xml report, and running a new task afterwards that converts the xml report to html using one of the FindBugs provided stylesheets.
import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource
import static org.gradle.api.tasks.PathSensitivity.NONE
configurations {
findbugsStylesheets { transitive false }
}
dependencies {
findbugsStylesheets 'com.google.code.findbugs:findbugs:3.0.1'
}
tasks.withType(FindBugs) {
maxHeapSize = "6g"
reports {
xml.enabled = true
xml.withMessages true
html.enabled = false
html.stylesheet resources.text.fromArchiveEntry(configurations.findbugsStylesheets, 'fancy.xsl')
}
task "${it.name}HtmlReport" {
def input = reports.xml.destination
inputs.file reports.html.stylesheet.asFile() withPropertyName 'findbugsStylesheet' withPathSensitivity NONE
inputs.files fileTree(input) withPropertyName 'input' withPathSensitivity NONE skipWhenEmpty()
def output = file(input.absolutePath.replaceFirst(/\.xml$/, '.html'))
outputs.file output withPropertyName 'output'
doLast {
def factory = TransformerFactory.newInstance('net.sf.saxon.TransformerFactoryImpl', getClass().classLoader)
def transformer = factory.newTransformer(new StreamSource(reports.html.stylesheet.asFile()));
transformer.transform(new StreamSource(input), new StreamResult(output))
}
}
it.finalizedBy "${it.name}HtmlReport"
} | unknown | |
d14866 | val | These types of record I/O problems are simplified if you use the Perl idiom of changing the record separator. Now each record becomes a line and lines are easy to count.
NOTE: I also removed the last // so we don't count the empty record.
Ok... I'm guessing that you may want something like this
#! /usr/bin/env perl
use strict;
use warnings;
my $cntr = 0;
print "Starting\n";
# change record seperator
$/ = '//';
while ((<DATA>))
{
print"============== Record number $cntr ======================\n";
print "$_\n";
print "========================================================\n";
$cntr++;
}
exit 0;
__DATA__
/
AA r00001
FA tea
OS fskjkterjykjlt
//
AA T00002
FA ACE2
OS coffee
SQ MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY
//
AA T00003
FA Diet coke
OS ewtji34ut893u569
SQ MTSICSSKFQQQHYQLTNSNIFLLQHQHHHQTQQHQLIAPKIPLGTSQLQNMQQSQQSNV
//
AA T00004
FA coke
OS jgerjgkhjetkh
SQ MKNNNNTTKSTTMSSSVLSTNETFPTTINSATKIFRYQHIMPAPSPLIPGGNQNQ
SQ RLRQHIPQSIITDLTKGGGRGPHKKISKVDTLRIAVEYIRSLQDLVDDLNGGSNIGANNA
//
With output like this
Starting
============== Record number 0 ======================
/
AA r00001
FA tea
OS fskjkterjykjlt
//
========================================================
============== Record number 1 ======================
AA T00002
FA ACE2
OS coffee
SQ MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY
//
========================================================
============== Record number 2 ======================
AA T00003
FA Diet coke
OS ewtji34ut893u569
SQ MTSICSSKFQQQHYQLTNSNIFLLQHQHHHQTQQHQLIAPKIPLGTSQLQNMQQSQQSNV
//
========================================================
============== Record number 3 ======================
AA T00004
FA coke
OS jgerjgkhjetkh
SQ MKNNNNTTKSTTMSSSVLSTNETFPTTINSATKIFRYQHIMPAPSPLIPGGNQNQ
SQ RLRQHIPQSIITDLTKGGGRGPHKKISKVDTLRIAVEYIRSLQDLVDDLNGGSNIGANNA | unknown | |
d14867 | val | you don't need to $apply since everything is inside the angular event loop what you need is not to destroy the reference to your binding by reassigning the product object.
when you linked your html product either didn't existed or was pointing to an mem address.
when you did
$scope.product = productResource.get();
you reassigned that variable to a different address so the binding was broken. but your html was not rebinded to the new address, this is more likely your problem, you can try making the variable null before reassigning it, not sure thats going to work, or you could make products initially an empty object and then extend it with
productResource.get(); | unknown | |
d14868 | val | The warnings were caused by the wicked_pdf gem, updating to version 1.1.0 solved the issue | unknown | |
d14869 | val | There is no need to add path of statically served directory. Just remove '/public/img/'
<img class="center" [src]="quizService.rootUrl + quizService.questions[quizService.questionProgress].imageName+'.jpg'">
You can access the all file of your served directory directly. like:
http://localhost:5000/shark.jpg
A: Follow the below steps,
your image is at path Public/img/shark.jpg
in your app.js, this should be before any route is created
app.use(express.static(__dirname + '/public/img'));
create a route as below
app.get('/Image/:id', function (req, res) {
// logic to find image based on id passed, we will assume it results in shark.jpg
const filepath = `${__dirname}/public/img/shark.jpg`;
res.sendFile(filepath);
});
Now consume this endpoint from your angular code
localhost:{PORT_NUMBER}/Image/{ID_FOR_SHARK_IMAGE}
A: I got it working by doing the following:
Nodejs added path:
const path = require("path");
app.use(express.static(path.join(__dirname, 'public/img')));
Then in Angular created a separate assetUrl that omits the "/api" part of the baseUrl:
[src]="quizService.assetUrl+'/'+quizService.questions[quizService.questionProgress].imageName+'.jpg'"
and now my images are served. | unknown | |
d14870 | val | Finally I found it.
So get corresponds to find without any filter.
So the code is:
Foo.on('attached', function() {
Foo.find = function(filter, callback) {
//Whatever you need to do here...
callback(null, {hello: 'hello'});
}
});
Here there is a link for all the PersistedModel methods
I just put 'attached' without exactly knowing why so if someone can comment the reason it would be great. | unknown | |
d14871 | val | I expect that the problem is in function context this.
May be you can try such that:
componentDidMount(){
const setState = this.setState;
fetch('https://snaptok.herokuapp.com/fetchPost/'+this.props.postId,{
method: 'GET'
}).then(response => {
if (response.ok) {
return response;
} else {
var error = new Error('Error ' + response.status + ': ' + response.statusText);
error.response = response;
throw error;
}
},
error => {
throw error;
}).then(res=>res.json()).then(res=>setState({
post: res
})).catch(err=>{console.log(err);})
} | unknown | |
d14872 | val | I have Eclipse 4.6 Neon. In Help > Install New software make sure you installed C/C++ Visual C++ Support. Restart Eclipse after installation.
I can see Microsoft Visual C++ in Toolchains now. | unknown | |
d14873 | val | io.sockets.send(msg);
this worked for me. also make sure you are using the same version of socket.io on both client and server | unknown | |
d14874 | val | I was looking for an IDE. Such as Netbeans. | unknown | |
d14875 | val | You can use Object.values(object.RAW) to get an array of the values inside RAW (assuming RAW is not undefined)
Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values | unknown | |
d14876 | val | Remove the SingleChildScrollView at the top-level of the body and set the scrollPhysics of the GridView to AlwaysScrollableScrollPhysics().
A: Try removing the SingleChildScrollView like this:
Column(
children: <Widget>[
Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading:
image(),
title: Text(updateDate),
subtitle: Text(weatherDetails),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
RichText(
text: TextSpan(
style: new TextStyle(
fontSize: 24.0,
color: Colors.black,
),
children: <TextSpan>[
TextSpan(text: mintemp.toString()+' C - ', style: new TextStyle(color: Colors.lightBlue)),
TextSpan(text: maxtemp.toString()+' C ', style: new TextStyle(color: Colors.red)),
TextSpan(text: ' Update:'+updateTime, style: new TextStyle(color: Colors.black,fontSize: 14)),
],
),
),
],
),
],
),
),
Container(
height: 80,
child: new ListView.builder(
itemCount: 6,
itemBuilder: (context, index){
return new Card(child: new Container(
//width: MediaQuery.of(context).size.width,
width:320,
height: 80,
child: new Text('Hello'),alignment: Alignment.center,));
}, scrollDirection: Axis.horizontal,
),
),
Container(
height: 889,
child:GridView.count(
physics: ScrollPhysics(),
primary: false,
padding: const EdgeInsets.all(10),
crossAxisSpacing: 10,
mainAxisSpacing: 10,
crossAxisCount: 3,
children: <Widget>[
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'images/hkphoto.jpg'),
fit: BoxFit.fill,
),
shape: BoxShape.circle,
),
child: InkWell(
/*onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) =>)
),*/ // handle your onTap here
),
),
InkWell(
child:Container(
padding: const EdgeInsets.all(8),
child: const Text('phs'),
color: Colors.teal[200],
),
/*onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) =>
)
),*/
),
InkWell(
child:Container(
padding: const EdgeInsets.all(8),
child: const Text('whs'),
color: Colors.teal[200],
),
/*onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) =>
),
),*/
),
InkWell(
child:Container(
padding: const EdgeInsets.all(8),
child: const Text('whs'),
color: Colors.teal[200],
),
/*onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) =>
),
),*/
),
InkWell(
child:Container(
padding: const EdgeInsets.all(8),
child: const Text('whs'),
color: Colors.teal[200],
),
/*onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) =>
),
),*/
),
InkWell(
child:Container(
padding: const EdgeInsets.all(8),
child: const Text('whs'),
color: Colors.teal[200],
),
/*onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) =>
),
),*/
),
],
)
Let me know if it doesnt work | unknown | |
d14877 | val | Actually found the solution after hours of trying. Changing $_GET to $_POST did the trick.
if( isset( $_GET['product_' . $term->term_id ] ) && $_GET['product_' . $term->term_id]
Changed to:
if( isset( $_POST['product_' . $term->term_id ] ) && $_POST['product_' . $term->term_id] | unknown | |
d14878 | val | div {
background-color: lightgreen;
max-height: 5em;
overflow-y: scroll;
scrollbar-color: lightgreen lightgreen;
}
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
Using scrollbar-color works (more info here). I think color detection is just really buggy - sometimes one color works with scrollbar-color and applies to both parts of the scrollbar and sometimes you need to repeat it twice. I just think it's a poorly implemented part of the HTML spec. Doesn't have great browser support though so make sure it's not required as part of your interface. | unknown | |
d14879 | val | Check these links. These might be useful for your case
http://extrimity.in/content/enable-ssl-or-https-ubuntu-1104-apache-2
http://wiki.vpslink.com/Enable_SSL_on_Apache2
http://docs.oracle.com/cd/A95431_01/install/ssl.htm
Step by step
https://www.digitalocean.com/community/articles/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-12-04
http://www.digicert.com/ssl-certificate-installation-apache.htm
http://www.debian-administration.org/articles/349 | unknown | |
d14880 | val | I've created several tests and all succeeded with SAS URI.
I think you should check a few places:
*
*According to your screen shot. Maybe your SAS key has expired?
*The URI configuration. We should concat the connect string and the SAS token.
The configuration is as follows:
A: First you need to check the permissions allotted to SAS and also the expiry date, there can be two cases here: one you may not have adequate access to upload and second the SAS might have expired.
If this is a one time activity and then you can use AzCopy tool as well to upload files to blob storage. | unknown | |
d14881 | val | I would suggest you to normalize your database structure, you could have one table like this:
CREATE TABLE bilanci (
id int AUTO_INCREMENT NOT NULL,
medicoid int NOT NULL,
conguagliodic decimal(10,2),
totbilancianno int DEFAULT 0,
totpagato decimal(12,2),
totdapagare decimal(12,2),
conguaglio decimal(10,2),
pvimun decimal(10,4) NOT NULL DEFAULT 9.4432,
PRIMARY KEY (id)
) ENGINE = InnoDB;
and a second table bilanci_month:
create table bilanci_month (
id int auto_increment,
bilanci_id int,
rifanno int NOT NULL,
month int NOT NULL,
value int)
(bilanci_id can be defined as a foreign key of bilanci_month), then your select query would be like this:
select
b.medicoid,
coalesce(bm.value, 0),
b.totdapagare from bilanci
from
bilanci b left join bilanci_month bm
on b.id = bm.bilanci_id and bm.month = month(curdate())-2
also, be careful about month(curdate())-2, what would happen if the month is january or february? You have to implement some logic to get for example november or december of the previous year (and add this logic to your join). | unknown | |
d14882 | val | I use the following method:
crate VTK of lagrangian data
Load data in ParaView
Use the "temporalPaticlesToPathlines" filter
make sure to have a unique identifier for the particles. I used origId and it is not always unique if you have breakup of particles. | unknown | |
d14883 | val | You better hide the navigationBar inside viewDidAppear method.
-(void)viewDidAppear:(BOOL)animated{
[yourNavigationController setNavigationBarHidden:YES animated:YES];
} | unknown | |
d14884 | val | My CSS background wasn't white. Lol.
<div style={{ position: "absolute", width: "400px", height: "400px", backgroundColor: "white"}}> | unknown | |
d14885 | val | Have you tired path like this?
axios.get(`/api/api/categories/categories.php`)
...
A: If you are using create-react-app install http-proxy-middleware as a dev dependency and in your src folder create a file called setupProxy.js (it must be spelt exactly like that).
In that file:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/api', { target: 'http://localhost:80' }));
};
You will need to restart the app for it to take effect.
Your api calls should not need the process.env | unknown | |
d14886 | val | python 3.10 was released after or-tools 9.1.
Next release will contain the 3.10 wheel. | unknown | |
d14887 | val | I fixed the problem by adding the following line before importing the utilities:
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..'))
from utilities.logging_service import LoggingService
from utilities.comparator_utils import Utils
I don't know if this is the correct solution, but it did solve the problem for me. | unknown | |
d14888 | val | Dealing with numpy arrays seems to be a major problem for networkx. The function that converts my image skeleton to the graph G however seems to be using numpy arrays.
Since I prefer not to alter the imported function, a possible workaround that seemed to mitigate the problem when writing the edgelist to file was to change the array type thus:
for (s, e) in G.edges():
G[s][e]['pts'] = G[s][e]['pts'].tolist()
It might not be the most computationally efficient, and doesn't deal with the root of the problem, but will get the job done, in case anybody encounters a similar issue. | unknown | |
d14889 | val | 1) You should create class to represent json data (http://json2csharp.com/)
public class RootObject
{
public string response { get; set; }
public string user_id { get; set; }
public string username { get; set; }
public string current_balance { get; set; }
public string message { get; set; }
public string outh_token { get; set; }
public List<string> lastFiveSpinNumbers { get; set; }
}
2) You should deserialize json data into class (the easiest way is to using Json.NET library - http://www.newtonsoft.com/json)
using (WebResponse jsonResponse = request.GetResponse())
{
// Do something with response
StreamReader streamReader = new StreamReader(jsonResponse.GetResponseStream());
String responseData = streamReader.ReadToEnd();
var myData = JsonConvert.DeserializeObject<List<RootObject>>(responseData);
// process your data
foreach (var rootObject in myData)
{
string response = rootObject.response;
// ...
}
} | unknown | |
d14890 | val | Try adding a 'default' binding (without any name specified).
Add the readerQuota settings to this binding.
You can then even remove the readerQuota settings from the named binding you are actually using.
This worked for me (although I'm not sure why the readerQuotas on the correct named binding are ignored by WCF)
A: 'default' binding option worked for me. I was trying customize maxStringContentLength value in named WebHttpBinding but for some reason it did not picked up by WCF. finally I followed the D.Tiemstra work around then it started working.
<webHttpBinding>
<binding maxReceivedMessageSize="2147483647" >
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
</binding>
</webHttpBinding>
A: This thread explains in detail how to specify the binding settings on server and client correctly in order to change the MaxStringContentLength.
This other thread also provides a clear and efficient answer on using the readerQuotas.
A: I would use this values for the WCF configuration (programmatically):
Security = { Mode = SecurityMode.None},
CloseTimeout = TimeSpan.MaxValue,
OpenTimeout = TimeSpan.MaxValue,
SendTimeout = TimeSpan.FromMinutes(5),
ReceiveTimeout = TimeSpan.FromMinutes(5),
MaxBufferSize = 2147483647,
MaxBufferPoolSize = 524288,
MaxReceivedMessageSize = 2147483647,
ReaderQuotas = new XmlDictionaryReaderQuotas
{
MaxDepth = 32,
MaxStringContentLength = 8192,
MaxArrayLength = 16384,
MaxBytesPerRead = 4096,
MaxNameTableCharCount =1638
} | unknown | |
d14891 | val | There is no support for video player plugin on Windows, MacOS or linux as of now. Hopefully flutter team might add this feature by the end of this year. | unknown | |
d14892 | val | Let me try to rephrase the issue:
*
*You have a model Video
*Video has a virtual attribute my_link
*Video has a before_update callback before_add_to_galerie
*You want this callback to trigger when only my_link was changed
does this look correct?
If so you have 2 options, first - if you have updated_at change it along with my_link
class Video < ApplicationRecord
attr_reader :my_link
# ...
def my_link=(val)
return val if val == my_link
@my_link = val
self.updated_at = Time.zone.now
end
end
or you can use ActiveModel | unknown | |
d14893 | val | if you are using eclipse then right click on project2>properties>java build path>projects> add project 1. | unknown | |
d14894 | val | No, you cannot have a key that dynamically changes. Your best bet is to build the object at the time you need it:
var obj = {};
obj[$scope.value] = 25;
...
A: If you want to use a variable as a property name, then you must create an object first, then assign the data using square bracket notation.
var data = {
'speciality':$scope.speciality,
'field2':'something',
'field3':'something else'
}
data[$scope.value] ='25';
A: var data = {
'field2':'something',
'field3':'something else'
};
$scope.value.forEach(function(value) {
data[value] = '25';
}); | unknown | |
d14895 | val | It appears that you have different installations of PHPUnit mixed up.
For instance, you may have used Composer to install PHPUnit and have configured the autoloader generated by Composer as PHPUnit's bootstrap script but then you invoke PHPUnit using an executable other than vendor/bin/phpunit. | unknown | |
d14896 | val | You can use S3 VirusScan, which is a third-party open source tool.
Some of its features are:
*
*Uses ClamAV to scan newly added files on S3 buckets
*Updates ClamAV database every 3 hours automatically
*Scales EC2 instance workers to distribute workload
*Publishes a message to SNS in case of a finding
*Can optionally delete compromised files automatically
*Logs to CloudWatch Logs
A: If you want to implement the solution by yourself, you can use: https://aws.amazon.com/blogs/developer/virus-scan-s3-buckets-with-a-serverless-clamav-based-cdk-construct/ | unknown | |
d14897 | val | For your example class, and using a bag for an unordered collection:
using Map = NHibernate.Mapping.Attributes;
[Map.Class( 0, Table = "country", NameType=typeof(Country) )]
public class Country
{
[Map.Id( 1, Name = "Id" )]
[Map.Generator( 2, Class = "identity" )]
public virtual int Id { get; set; }
[Map.Property]
public virtual string Name { get; set; }
[Map.Bag( 0, Table = "country_company" )]
[Map.Key( 1, Column = "countryid" )]
[Map.OneToMany( 2, ClassType = typeof( Company ) )]
public virtual IList<Company> Items { get; set; }
}
[Map.Class( 0, Table = "country_company", NameType = typeof( Company ) )]
public class Company
{
[Map.Id( 1, Name = "Id" )]
[Map.Generator( 2, Class = "identity" )]
public virtual Guid Id { get; set; }
[Map.Property]
public virtual string Name { get; set; }
}
produces the following hbm.xml:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="nh.Country, nh" table="country">
<id name="Id">
<generator class="identity" />
</id>
<property name="Name" />
<bag name="Items" table="country_company">
<key column="countryid" />
<one-to-many class="nh.Company, nh" />
</bag>
</class>
<class name="nh.Company, nh" table="country_company">
<id name="Id">
<generator class="identity" />
</id>
<property name="Name" />
</class>
</hibernate-mapping> | unknown | |
d14898 | val | Assuming string structure is constant. You can try this, but it depends on structure.
data = YOUR_STRING_FROM_QUESTION
# This is the delimeter, which will help us to split query on parts
prefix = '& IF (\n'
# define list of allowed tables
allowed_tables = ['Table1[Column_1]', 'Table2[Column_4]', 'Table6[Column_22]']
# split full string on parts by prefix
query_by_part = data.split(prefix)
# build clean list of query parts, where tables in allowed_tables
clean_query_parts = [part for part in query_by_part
if any(table in part for table in allowed_tables)]
# finally join list to string using prefix and print
print(prefix.join(clean_query_parts))
Input:
IF (
ISFILTERED ( Table1[Column_1] ),
VAR ___f = FILTERS ( Table1[Column_1] )
VAR ___r = COUNTROWS ( ___f )
VAR ___t = TOPN ( MaxFilters, ___f, Table1[Column_1])
VAR ___d = CONCATENATEX ( ___t, Table1[Column_1], ", " )
VAR ___x = "Table1[Column_1] = " & ___d & IF(___r > MaxFilters, ", ... [" & ___r & " items selected]") & " "
RETURN ___x & UNICHAR(13) & UNICHAR(10)
)
& IF (
ISFILTERED ( Table1[Column_2] ),
VAR ___f = FILTERS ( Table1[Column_2] )
VAR ___r = COUNTROWS ( ___f )
VAR ___t = TOPN ( MaxFilters, ___f, Table1[Column_2])
VAR ___d = CONCATENATEX ( ___t, Table1[Columnw_1], ", " )
VAR ___x = "Table1[Column_2] = " & ___d & IF(___r > MaxFilters, ", ... [" & ___r & " items selected]") & " "
RETURN ___x & UNICHAR(13) & UNICHAR(10)
)
Output:
IF (
ISFILTERED ( Table1[Column_1] ),
VAR ___f = FILTERS ( Table1[Column_1] )
VAR ___r = COUNTROWS ( ___f )
VAR ___t = TOPN ( MaxFilters, ___f, Table1[Column_1])
VAR ___d = CONCATENATEX ( ___t, Table1[Column_1], ", " )
VAR ___x = "Table1[Column_1] = " & ___d & IF(___r > MaxFilters, ", ... [" & ___r & " items selected]") & " "
RETURN ___x & UNICHAR(13) & UNICHAR(10)
)
A: You can use jinja2 to easily generate the string from scratch in this way:
*
*Add a new file with the double extension 'txt.jinja', e.g., example.txt.jinja2 with the following code inside (this is your template) and save it in the same path of your script:
"
{%- for column in columns_to_add -%}
IF (
ISFILTERED ( Table1[Column_2] ),
VAR ___f = FILTERS ( Table1[Column_2] )
VAR ___r = COUNTROWS ( ___f )
VAR ___t = TOPN ( MaxFilters, ___f, Table1[Column_2])
VAR ___d = CONCATENATEX ( ___t, Table1[Columnw_1], ", " )
VAR ___x = "{{column}} = " & ___d & IF(___r > MaxFilters, ", ... [" & ___r & " items selected]") & " "
RETURN ___x & UNICHAR(13) & UNICHAR(10)
)
&
{% endfor -%}
"
*Execute this Python script:
import os
import jinja2
TEMPLATE_NAME = "example.txt.jinja2"
LIST_OF_TABLES = [
'Table1[Column_1]',
'Table2[Column_4]',
'Table6[Column_22]'
]
template = os.path.join(os.path.dirname(os.path.abspath(__file__)), "")
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template))
template2= jinja_env.get_template(TEMPLATE_NAME)
string = template2.render(columns_to_add=LIST_OF_TABLES)
output = template + TEMPLATE_NAME.split("\\")[-1].replace('.jinja2', '')
with open(output, "w+") as f:
f.write(string)
This will create a new file (in the same path) called example.txt with your string:
"IF (
ISFILTERED ( Table1[Column_2] ),
VAR ___f = FILTERS ( Table1[Column_2] )
VAR ___r = COUNTROWS ( ___f )
VAR ___t = TOPN ( MaxFilters, ___f, Table1[Column_2])
VAR ___d = CONCATENATEX ( ___t, Table1[Columnw_1], ", " )
VAR ___x = "Table1[Column_1] = " & ___d & IF(___r > MaxFilters, ", ... [" & ___r & " items selected]") & " "
RETURN ___x & UNICHAR(13) & UNICHAR(10)
)
&
IF (
ISFILTERED ( Table1[Column_2] ),
VAR ___f = FILTERS ( Table1[Column_2] )
VAR ___r = COUNTROWS ( ___f )
VAR ___t = TOPN ( MaxFilters, ___f, Table1[Column_2])
VAR ___d = CONCATENATEX ( ___t, Table1[Columnw_1], ", " )
VAR ___x = "Table2[Column_4] = " & ___d & IF(___r > MaxFilters, ", ... [" & ___r & " items selected]") & " "
RETURN ___x & UNICHAR(13) & UNICHAR(10)
)
&
IF (
ISFILTERED ( Table1[Column_2] ),
VAR ___f = FILTERS ( Table1[Column_2] )
VAR ___r = COUNTROWS ( ___f )
VAR ___t = TOPN ( MaxFilters, ___f, Table1[Column_2])
VAR ___d = CONCATENATEX ( ___t, Table1[Columnw_1], ", " )
VAR ___x = "Table6[Column_22] = " & ___d & IF(___r > MaxFilters, ", ... [" & ___r & " items selected]") & " "
RETURN ___x & UNICHAR(13) & UNICHAR(10)
)
&
"
This works fine no matter how big your list of desired columns is, and the best part is that you only have to keep this list updated. | unknown | |
d14899 | val | You probably should review this entry: How To: Create custom layouts.
More or less, you can set it via ApplicationController:
class ApplicationController < ActionController::Base
layout :layout_by_resource
protected
def layout_by_resource
if devise_controller?
"layout_name_for_devise"
else
"application"
end
end
end
Or via configuration (config/application.rb):
config.to_prepare do
Devise::SessionsController.layout "devise"
Devise::RegistrationsController.layout proc{ |controller| user_signed_in? ? "application" : "devise" }
Devise::ConfirmationsController.layout "devise"
Devise::UnlocksController.layout "devise"
Devise::PasswordsController.layout "devise"
end | unknown | |
d14900 | val | It seems like the event trigger is within another event's function is causing the crash. In any case, the solution is to remove the listener, then add it back after modifying the other cell.
You do need to global the Listener and the Cell objects to make this work.
This code is simplified to work on C3 and C15 on the first sheet. It would also output some information on C14, which isn't really necessary for your purpose, but I use it to see what's happening. You need to adopt the according to what you need.
global goListener as Object
global goListener2 as Object
global goCellR as Object
global goCellR2 as Object
global goSheet as Object
global giRun as integer
global giUpd as Integer
Sub Modify_modified(oEv)
Dim sCurStr$
Dim sNewStr As String
'xRay oEv
giRun = giRun + 1
sCurStr = oEv.source.string
oCell = goSheet.getCellByPosition(2, 14)
If (oCell.getString() <> sCurStr) Then
' only update if it's different.
giUpd = giUpd + 1
goCellR2.removeModifyListener(goListener2)
oCell.setString(sCurStr)
goCellR2.addModifyListener(goListener2)
End If
sNewStr =sCurStr & " M1 Run=" & giRun & " Upd=" & giUpd
goSheet.getCellByPosition(2, 13).setString(sNewStr)
End Sub
Sub Modify2_modified(oEv)
Dim sCurStr$
Dim sNewStr As String
Dim oCell as Object
'xRay oEv
giRun = giRun + 1
sCurStr = oEv.source.string
oCell = goSheet.getCellByPosition(2, 2)
If (oCell.getString() <> sCurStr) Then
' only update if it's different.
giUpd = giUpd + 1
goCellR.removeModifyListener(goListener)
oCell.setString(sCurStr)
goCellR.addModifyListener(goListener)
End If
sNewStr =sCurStr & " M2 Run=" & giRun & " Upd=" & giUpd
goSheet.getCellByPosition(2, 13).setString(sNewStr)
End Sub
Sub Modify_disposing(oEv)
MsgBox "In Modify_disposing"
End Sub
Sub Modify2_disposing(oEv)
MsgBox "In Modify2_disposing"
End Sub
Sub RmvListener
MsgBox "In RmvListener"
goCellR.removeModifyListener(goListener)
goCellR2.removeModifyListener(goListener2)
End Sub
Sub AddListener
goSheet = ThisComponent.Sheets.getByIndex(0) 'get leftmost goSheet
'servicesSheet = ThisComponent.Sheets.getByIndex(2)
goCellR = goSheet.getCellrangeByName("C3")
goListener = createUnoListener("Modify_","com.sun.star.util.XModifyListener") 'create a listener
goCellR.addModifyListener(goListener) 'register the listener
goCellR2 = goSheet.getCellrangeByName("C15")
goListener2 = createUnoListener("Modify2_","com.sun.star.util.XModifyListener") 'create a listener
goCellR2.addModifyListener(goListener2) 'register the listener
End Sub
Sub Main
giRun = 0
giUpd = 0
AddListener
End Sub | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.