id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23531600
|
A: The IModelTransformer class in the @bentley/imodeljs-backendpackage has the ability to clone/transform elements from a source iModel into a target iModel. You could either:
*
*Do 2 transformations to combine 2 source iModels into 1 new target or
*Merge a source iModel's contents into an existing target.
Please see the documentation here:
https://www.imodeljs.org/learning/backend/imodeltransformation/
Please note that you may need to set up some structure in the target iModel to transform into and some initial remappings. The unit tests here demonstrate some of the required setup:
https://github.com/imodeljs/imodeljs/blob/master/core/backend/src/test/standalone/IModelTransformer.test.ts
If you describe your scenario a bit more, I may be able to provide additional guidance.
A: Paul Connelly answered already the same question you posted as GitHub issue.
Did you try to use IModelTransformer class recommended by Paul? This class offers common i-model ETL functionality, so using it together with IModelImporter should allow to merge more i-models into new one.
| |
doc_23531601
|
org.h2.jdbc.JdbcSQLSyntaxErrorException: Schema "MySchema" not found; SQL statement:
select batchstatu0_.batch_key as batch_ke1_0_ from myschema.batch_status batchstatu0_ [90079-199]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:573)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:427)
When I run the generated sql from Oracle SQL Developer using the same credentials, the select statement correctly finds the schema and runs the query.
One of the things I initially tried with success but not the solution I would like to go with was to specify a whole new DataSource for the specified schema. That worked but will be a serious headache when we start adding event more schemas. I would much rather use one Datasource and specify the schema in the Table annotations.
@Table(name="BATCH_STATUS", schema ="MySchema")
public class BatchStatus {
...
}
And the properties:
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
hibernate.show_sql=true
spring.datasource.jdbc-url=jdbc:oracle:thin:xxx
spring.datasource.username=xxx
spring.datasource.password=xxx
hibernate.default_schema=MySchema
I would assume this has to be some sort of config issue but I haven't been able to figure it out.
A: you need to specify
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
As per the exception, it is using H2 driver
| |
doc_23531602
|
Now I'm getting EXC_BAD_ACCESS if I define a CGImageRef in the main queue, and use the CGImageRef in the worker queue. Like this:
UIImage *uiimage = [UIImage imageWithContentsOfFile:[aPhoto completeLargeThumbFilePath]];
CGImageRef cgImage = uiimage.CGImage;
dispatch_queue_t dispatchQueue = dispatch_queue_create("mediaInputQueue", NULL);
[writerInput requestMediaDataWhenReadyOnQueue:dispatchQueue usingBlock:^{
// ... unrelated stuff
CVPixelBufferRef buffer = (CVPixelBufferRef)[self pixelBufferFromCGImage:cgImage size:size];
// ... unrelated stuff
}];
If I use uiimage.CGImage directly in the worker queue, then I don't get the exception. I think this is related to the ARC memory management. UIImage is an objective-c object, and CGImageRef is a pointer to an C struct. The UIImage is released before I can use its CGImage in the first case.
My question is how can I directly use a C pointer defined in main queue in another dispatch queue?
A: The reason you have this problem, and the reason that CGImageRetain() fixes it, is because the CGImage is not retained by the block. This is because CGImageRef is not an Objective-C object pointer type. Blocks only automatically retain captured variables when they are Objective-C object pointer types.
So an alternate solution is to simply let the block capture an "object pointer type" version of it (all Core Foundation objects can be treated as Cocoa Objective-C objects, and vice versa):
UIImage *uiimage = [UIImage imageWithContentsOfFile:[aPhoto completeLargeThumbFilePath]];
CGImageRef cgImage = uiimage.CGImage;
id cgImageAsObject = (__bridge id)cgImage;
dispatch_queue_t dispatchQueue = dispatch_queue_create("mediaInputQueue", NULL);
[writerInput requestMediaDataWhenReadyOnQueue:dispatchQueue usingBlock:^{
// ... unrelated stuff
CGImageRef cgImageAgain = (__bridge CGImageRef)cgImageAsObject;
CVPixelBufferRef buffer = (CVPixelBufferRef)[self pixelBufferFromCGImage:cgImageAgain size:size];
// ... unrelated stuff
}];
A: The uiimage is autoreleased. Thus, most likely, the cgImage is being deallocated when the UIImage is autoreleased.
You could try retaining the cgImage and then releasing it in the block. Or you could use the uiimage in the block (add [uiimage self]; to the end of the block -- looks goofy, but works).
The underlying issue is what is called the interior pointer problem. You are grabbing a pointer to something inside an object, but not maintaining a strong reference to the object. When the object goes away, whatever the interior pointer points to is reaped and you are left with a dangling pointer.
I'd go with this:
UIImage *uiimage = [UIImage imageWithContentsOfFile:[aPhoto completeLargeThumbFilePath]];
dispatch_queue_t dispatchQueue = dispatch_queue_create("mediaInputQueue", NULL);
[writerInput requestMediaDataWhenReadyOnQueue:dispatchQueue usingBlock:^{
CGImageRef cgImage = uiimage.CGImage;
// ... unrelated stuff
CVPixelBufferRef buffer = (CVPixelBufferRef)[self pixelBufferFromCGImage:cgImage size:size];
// ... unrelated stuff
}];
| |
doc_23531603
|
#If PRE611 = True Then
'Do Something
#Else
'Something Else
#End If
I am pretty sure the PRE611 has something to do with versioning, but I would like to know what specifically the # sign does.
A: Those are directives, and allows you to do conditional compiling. # sign used for directives.
In this case It will compiled either part of the code based on the evaluation of "PRE611 = True"
You can see this article for some examples :
http://visualbasic.about.com/od/usingvbnet/a/vbdirectives01_2.htm
A: It's a pre-processor directive.
It essentially means if PRE611 is defined as true (in the pre-processor) to compile whatever follows.
| |
doc_23531604
|
A: Your development organization clearly doesn't understand the complexity or best practices of writing installers. I had 7 years of setup under my belt before I started using MSI and it took me 6 months to really get comfortable with out MSI worked and a full year to fully "get it". If it was me I'd first attack this whole concept of you deploying files to both the C: and D: drive and why you have all these custom actions. This is screaming antipattern. I'd want to verify the need for each custom action and understand the reason behind this whole C: and D: thing.
Personally, my gut tells me that for what you are doing you don't really want an MSI installer; you just want a .BAT file or similar.
So basically, you've been sent on a suicide mission and I wish you luck.
A: I completely agree with both Chris and Rob here, getting upto speed on MSI will likely take at least 6 months if you're new to setup. On the plus side, you're new to setup and won't have the same preconceptions and can start using best-practices from day one ;)
Windows Installer (and the Windows Installer API) is very powerful tool. Embarking on WiX without learning the MSI fundamentals is as Chris said, a suicide mission.
If you still insist... here's a list of resources I recently assembled for a new setup developer that provide a baseline understanding for someone completely new to windows development or setup
*
*Read the Tao of the Windows Installer (parts 1-6)
*Read Understanding "UAC in MSI" (parts 1-27)
*Read "The Definitive Guide to Windows Installer" (if you're not dealing with .NET or IIS you can skip those chapters)
*Be prepared to constantly reference the documentation (MSI.CHM and WiX.CHM)
*Add Chris and Rob to your blogroll (and others... I don't have a complete list handy), join the wix-users mailing list and test, test, test before shipping.
Timewise, I'd agree with Rob. 2-4 weeks.. if the CA's are complex and required, then much longer (although most of that time would be pushing back with development and removing the need for them in the first place ideally)
A: Do you understand the Windows Installer (aka: MSI)? If not, then the bulk of your time will be learning MSI. After that, heat.exe can help get your authoring generated pretty quickly. The services will take some time and the custom actions could be simple or complex depending on their complexity.
I'd want at least two weeks dev time to do it... but I know the Windows Installer (and WiX) pretty well. ;) If the custom actions are at all complex I'd want 4 - 8 weeks.
| |
doc_23531605
|
Here I am trying to initiate a component state with values from context. But the state doesnot update when context value changes.
function Parent() {
return (
<ContextProvider>
<Child />
</ContextProvider>
);
}
function Child() {
const mycontext = useContext(Context);
const [items, setItems] = useState(mycontext.users);
console.log(mycontext.users, items); //after clicking fetch, => [Object, Object,...], [] both are not equal. why??????
return (
<>
<button onClick={() => mycontext.fetch()}>fetch</button>
{/* <button onClick={()=>mycontext.clear()} >Clear</button> */}
{items.map(i => (
<p key={i.id}>{i.name}</p>
))}
</>
);
}
/* context.js */
const Context = React.createContext();
function ContextProvider({ children }) {
const [users, setUsers] = useState([]);
function fetchUsers() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(json => setUsers(json));
}
return (
<Context.Provider
value={{ users, fetch: fetchUsers, clear: () => setUsers([]) }}
>
{children}
</Context.Provider>
);
}
The above code can be tested in codesandbox.
I can use context values directly, but I want to maintain state inside the component.
If we cannot initiate state value with a context value, what is the best approach If I want to get data from context and also want to maintain state internally?
A: The argument to useState is only used once.
You do not need to copy context value in state and can directly use it from context.
If however you would like to do it you need to make use of useEffect
const [items, setItems] = useState(mycontext.users);
useEffect(() => {
setItems(mycontext.users);
}, [mycontext.users]);
updated demo
| |
doc_23531606
|
To perform the same cast and also maintain ANSI compatibility, you can cast the function pointer
to a uintptr_t before you cast it to a data pointer:
int ( * pfunc ) ();
int *pdata;
pdata = ( int * ) (uintptr_t) pfunc;
Rationale for C, Revision 5.10, April-2003:
Even with an explicit cast, it is invalid to convert a function pointer to an object pointer
or a pointer to void, or vice versa.
C11:
7.20.1.4 Integer types capable of holding object pointers
Does it mean that pdata = ( int * ) (uintptr_t) pfunc; in invalid?
As Steve Summit says:
The C standard is written to assume that pointers to different object types, and especially pointers to function as opposed to object types, might have different representations.
While pdata = ( int * ) pfunc; leads to UB, it seems that pdata = ( int * ) (uintptr_t) pfunc; leads to IB. This is because "Any pointer type may be converted to an integer type" and "An integer may be converted to any pointer type" and uintptr_t is integer type.
A: Given the definitions
int (*pfunc)();
int *pdata;
, the assignments
pdata = (int *)pfunc;
pdata = (int *)(uintptr_t)pfunc;
are, IMO, equivalent. On a platform where data pointers are of the same size as, or larger than, function pointers, both assignments will work as desired. But on a platform where data pointers are smaller than function pointers, both assignments will inevitably scrape off some of the bits of the function pointer, resulting in a data pointer which can not be converted back to the original function pointer later.
In particular, I believe that both assignments are equivalent despite the presence of the (uintptr_t) cast in the second one. I believe that cast accomplishes precisely nothing.
On a platform where data pointers are smaller than function pointers, and where type uintptr_t is of the same size as data pointers, in the assignment
pdata = (int *)(uintptr_t)pfunc;
, the cast to (uintptr_t) will scrape off some of the bits of pfunc's value.
On a platform where data pointers are smaller than function pointers, and where type uintptr_t is of the same size as function pointers, in the assignment
pdata = (int *)(uintptr_t)pfunc;
, the cast to (int *) will scrape off some of the bits of pfunc's value.
In both cases pdata will end up with only some fraction of pfunc's original value.
(Here I disregard the possibility of architectures with padding bits or the like. On some bizarre, hypothetical platform where function pointers are larger than data pointers, but the extra bits are always 0, both assignments would again work.)
(I've also disregarded the possibility that int * is a different size than void *. I'm not sure whether that would affect the answer, whether a "detour" via void * is more or less un- or necessary when attempting a conversion from int (*)() to int *.)
A: Casting to uintptr_t only works if this type is defined, which may not be the case on legacy systems using ancient compilers. Note however that uintptr_t must be large enough for any object pointer, especially char * or void *, but may be smaller than function pointers. Such architectures are rare today and Microsoft compilers probably no longer support them, but they were common place in the 16-bit world (MS/DOS, Windows 1, 2 and 3.x) where the medium model had 32-bit segmented code pointers and 16-bit data pointers.
Note also that the C Standard allows for int * and void * to have a different size and representation albeit no Microsoft compiler supports such exotic targets.
On current systems with modern compilers, all data pointers and code pointers have almost always the same size and representation. This is actually a requirement for POSIX compatibility, so the recommendation to use an intermediary cast to (uintptr_t) is valid and effective.
For complete portability, if the goal is to pass a function pointer via an opaque void *, you can always allocate an object of the proper function pointer type, initialize it with pfunc and pass its address:
// setting up the void *
int (*pfunc)();
void *pdata = malloc(sizeof pfunc);
memcpy(pdata, &pfunc, sizeof pfunc);
// using the void *
int (**ppfunc)() = pdata;
(*ppfunc)(); // equivalent to (**ppfunc)();
A:
Is conversion of a function pointer to a uintptr_t / intptr_t invalid?
No. It may be valid. It may be undefined behavior.
Conversion of a function pointer to ìnt* is not defined. Nor to any object pointer. Nor to void *.
pdata = ( int * ) pfunc; is undefined behavior.
Conversion of a function pointer to an integer type is allowed, with restrictions:
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type. C17dr 6.3.2.3 6
Also integer to a pointer type is allowed.
An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation. C17dr 6.3.2.3 6
void * to integer to void * is defined. Object pointer to/from void* is defined. Then the optional (u)intptr_t types are sufficient for round-trip success. Yet we are concerned about a function pointer. Often enough function pointers are wider than an int *.
Thus converting a function pointer to int * only makes sense through an integer type, wider the better.
VS may recommend through the optional type uintptr_t and is likely sufficient if information is lossless on other platforms. Yet uintmax_t may afford less loss of information, especially in the function pointer to integer step, so I pedantically suggest:
pdata = ( int * ) (uintmax_t) pfunc;
Regardless of the steps taken, code is likely to become implementation specific and deserves guards.
#ifdef this && that
pdata = ( int * ) (uintmax_t) pfunc;
#else
#error TBD code
#endif
A: Migrating the solution from the question to an answer:
Here is the answer from Microsoft:
Q: How exactly "cast the function pointer to a uintptr_t before you cast it to a data pointer" leads to maintaining "ANSI compatibility"?
A: Without the cast to uintptr_t it’s possible that the code will fail to compile with other compilers, even if they use the same pointer model. For example: https://gcc.godbolt.org/z/9EjTe1s4x - if you add the uintptr_t it compiles without warnings/errors.
| |
doc_23531607
|
A: Before worrying about making installers, you first have to decide on an environment for your application to run in. For this you have a few options:
The most common option is to use Mono, which is an open source, OSX and Linux compatible implementation of .Net Framework.
Recently a new option came up, .Net Core which is a "development platform" created by Microsoft. It is also open source, compatible with Windows, OSX, and Linux, and includes several features which you can read about here. However, there are a few things to consider. The .Net Standard which .Net Core is based on is not feature-complete. That is to say, it lacks certain features that are available in the Windows-only .Net Framework. Also, while quite promising, .Net Core is by no means a mature platform.
Finally, it is worth mentioning that Unity is compatible with OSX out of the box.
Now, as for deployment, I'm afraid that C# you'll never be able to match Swift's level of integration. However, using one of the frameworks I have mentioned you can get quite close.
There are a few proprietary tools that specialize in cross-platform deployment, such as BitRock InstallBuilder or InstallAnywhere, however these aren't free, nor can I vouch for their effectiveness. I am only mentioning them for completeness' sake.
Your best bet, and the option I recommend, would be to use Monoobjc, which is a set of tools for interacting with Objective-C libraries through C#. Note that if you go with Mono you'll need to bundle it with your application.
Additionally, MonoMac used to be a viable option. However, it is currently on ice. You can read about it in this answer by user ruffin.
Finally, Xamarin supports creating standalone packages for your applications, however, it is also proprietary.
A: I believe what you are looking for is Mono.
| |
doc_23531608
|
ex:
'ABCD 123'
'ABCD 123'
A: You can use the replace() trick:
select replace(replace(replace(col, ' ', '><'), '<>', ''), '><', ' ')
This assumes that the string does not contain the characters used for the replacement. (Any pair of characters can be used.)
If your string is always of the form suggested -- two strings with spaces only in the middle, you could also do:
select concat(substring_index(col, ' ', 1), ' ',
substring_index(col, ' ', -1)
)
EDIT:
If you want to remove all spaces, then simply do:
replace(str, ' ', '')
The above is to leave one space.
A: To round off the answers, in MySQL 8+ we can try using REGEXP_REPLACE:
SELECT REGEXP_REPLACE(col, '[ ]+', '') AS col_out
FROM yourTable;
If you want to keep one space in between words, then just make the replacement a single space instead of empty string.
A: Without knowing the larger scope of what you are using this for, I would recommend looking into the replace function.
Microsoft Documentation
MYSQL Documentation
REPLACE('ABCD 123',' ','')
A: Use substring_index
set @str='ABC 123';
select concat(a , b) as "Result String"
from
(
select substring_index(@str,' ',1) a ,substring_index(@str,' ',-1) b
) q;
Result String
-------------
ABC123
| |
doc_23531609
|
category size1 size2 size3
cat1 10 20 30
cat2 20 10 15
cat3 30 20 10
i want two reports/excel outputs as follows
#1)
Category-sizetype-value
cat1 size1 10
cat1 size2 20
cat1 size3 30
cat2 size1 20
...
#2)
Category-size-value-value counts(i.e how many time specific size value appears)
cat1 size1 10 3 times
cat1 size2 20 2 times
cat1 size3 30 1 time
cat2 size1 20 4 times
...
code i have written so far, appreciate some pointers why pd.concat not working here? and not able t
import pandas as pd
path_to_file = 'C:\Users\Niru\Desktop\cat-sizes.xlsx'
xl = pd.ExcelFile(path_to_file)
print(xl.sheet_names)
df = xl.parse('Sheet1')
#print(df.head())
print(df.columns)
frames = []
for i in df.columns:
dfd = "df.loc[:,['Category','" +i+"']]"
frames.append(dfd)
print(pd.concat(frames))
A: Your example data and output confused me a little bit , but I guess this is what you want .
#Q1:
df1=pd.melt(df, id_vars=['category'], value_vars=['size1','size2','size3'])
Out[66]:
category variable value
0 cat1 size1 10
1 cat2 size1 20
2 cat3 size1 30
3 cat1 size2 20
4 cat2 size2 10
5 cat3 size2 20
6 cat1 size3 30
7 cat2 size3 15
8 cat3 size3 10
#Q2:
df1['counts']=df1.groupby(['variable','value']).transform('count')
Out[69]:
category variable value counts
0 cat1 size1 10 1
1 cat2 size1 20 1
2 cat3 size1 30 1
3 cat1 size2 20 2
4 cat2 size2 10 1
5 cat3 size2 20 2
6 cat1 size3 30 1
7 cat2 size3 15 1
8 cat3 size3 10 1
or for Q2
df1['counts']=df1.groupby(['variable']).transform('count')
Out[71]:
category variable value counts
0 cat1 size1 10 3
1 cat2 size1 20 3
2 cat3 size1 30 3
3 cat1 size2 20 3
4 cat2 size2 10 3
5 cat3 size2 20 3
6 cat1 size3 30 3
7 cat2 size3 15 3
8 cat3 size3 10 3
| |
doc_23531610
|
I'm using JNIWrapper, and the JAWT subcomponent of that library.
I'm trying to acquire the lock on a JAWT_DrawingSurface with the following code:
JAWT_DrawingSurface *ds = NULL;
ds = awt.GetDrawingSurface(env, comp);
dsLocked = !(ds->Lock(ds) & JAWT_LOCK_ERROR)
But I keep getting dsLocked to be false.
Details
comp is sent to this JNIWrapper code from Java by the following:
Component panel = new VideoViewport().getDisplay();
panel.setBounds(150,150,150,150);
System.out.println("Handle: " + core.utils.X11.X11Utils.getDrawable(panel));
There's not much done to panel either by running VideoViewport() or by getDisplay(), and I don't know what details would be relevant.
Question
What sort of things would cause acquiring the lock on the surface to fail?
A: The Component must be added to a frame and made visible.
When I added the Component to a AWT Frame object and made it visible before the getDrawable(panel) call, it worked and I was able to acquire the lock on the surface.
| |
doc_23531611
|
The app is based on HTML/CSS/JS and basically just a WebView which loads local web content.
Nothing is being collected as user info or anything else.
The only thing that needs Internet connection is the AdMob banner to be shown.
In order not to get rejected, what are the necessary information I should add to my app?
e.g. Should there be a button to show a pop-up with some text saying no user data is being collected?
e.g. Is there any mandatory GDPR text I should present to the user?
A: Add the info at splash screen and show popup to open settings and open wifi. Most probably apple rejects on webview apps. If got rejected then add push notification feature also.
| |
doc_23531612
|
I recently stumbled upon an interesting as well as a peculiar problem with arrays in js.
As you can see above subtraction is giving me a number but addition gives me a string. I've also tried the same with multiplication and division and got number in both the cases.
Then I became more curious and tried with multi element arrays and here is the result
Now I really want to figure out how and why is this happening. Please help me on this.
Edit: I've added more examples and below are the results
As you can see above "1"+"1" is "11" which seems fine but [] returns an empty array and [1] returns 1 with key 0 and as we know arrays are also objects and that leads to confusion.
A: When operating on elements in an array, the + operator performs a concatenation, not an addition.
For example, if you look at your case in which you try to do [1, 2, 3] + [4, 5, 6], the console treats the arrays as strings and joins the addend directly to the augend, giving a result of "1, 2, 34, 5, 6". The -, /, *, % operators perform arithmetic operations, which are integer operations rather than string or array operations, and cannot be performed on arrays. That is why that returns NaN.
If you're wondering why the numbers are added together as strings, it's because of type coercion. Concatenation is a string operation, not an integer operation, so the numbers are converted to a string.
If you want to append one array to another array, you can use .concat(). If you want to add each element (i.e. [0]1 + [0]2, ...), you can use a for loop. If you want to sum the elements in a list, use reduce with an accumulator.
Links: Explanation, Type conversion docs
Related tags: javascript, arrays, coercion, concatenation, types
A: Javascript arrays are objects, and arithmetic operator does not apply for them; + however performs concatenation. to join array objects, concat()
console.log("1" + "1") // = 11
console.log("1" - "1") // = 0
console.log(parseFloat("1") + parseFloat("1")) // = 2
console.log(parseFloat("1" + "1")) // = 11
console.log(eval("1") + eval("1")) // = 2
console.log(eval("1" + "1")) // = 11
var a = [1, 2, 3],
b = [11, 22, 33, 44];
var c = a.concat(b);
console.log(c)
| |
doc_23531613
|
if ( !username_exists( $user_login_name ) ) {
$user_id = wp_create_user( $user_login_name, md5($user_login_name), "" );
$creds = array();
$creds['user_login'] = $user_login_name;
$creds['user_password'] = md5($user_login_name);
$user = wp_signon( $creds, false );
wp_set_current_user($user_id);
if ( is_wp_error($user) ) {
echo $user->get_error_message();
}
wp_set_auth_cookie( $user_id );
} else {
$user = get_user_by('login', $user_login_name);
$user_id = $user->ID;
$creds = array();
$creds['user_login'] = $user_login_name;
$creds['user_password'] = md5($user_login_name);
$user = wp_signon( $creds, false );
wp_set_current_user($user_id);
if ( is_wp_error($user) ){
echo $user->get_error_message();
}
wp_set_auth_cookie( $user_id );
}
Can anyone tell me what im doing wrong? Ive set the cookie, the current user, etc. But Still a no go.
A: Add 'remember' to the $creds array:
$creds['remember'] = true;
That ought to keep you logged in until the natural WP session expires.
| |
doc_23531614
|
let latestX;
let latestY;
let previousX;
let previousY;
let mouseHasMoved = false;
DEFAULT_INTERVAL = 2000;
onmousemove = () => {
window.addEventListener('mousemove', (e)=> {
latestX = e.x
latestY = e.y
mouseHasMoved = true;
});
};
myInterval = setInterval(()=> {
if (mouseHasMoved) {
mouseHasMoved = false;
console.log(`x: ${latestX}, y: ${latestY}`)
}
}, DEFAULT_INTERVAL);
I want to expand the above code to also show me the previous coordinate, using previousX and previousY.
Let's say my current coordinates are X: 10 and Y: 20.
So, initially previousX and previousY would be undefined and latestX: 10 and latestY: 20. After I change my mouse coordinate; X: 10 and Y: 20 would be assigned to previousX and previousY, and latestX and latestY would have new values.
I have tried assigning the values as below, but it didn't work. Both previous and latest had the same values:
onmousemove = () => {
window.addEventListener('mousemove', (e)=> {
previousX = latestX;
previousY = latestY;
latestX = e.x
latestY = e.y
mouseHasMoved = true;
});
};
A: The problem is that you assign the previousX and previousY values in the mouse move handler. If you move this to the interval handler, it will work as expected:
let latestX;
let latestY;
let previousX;
let previousY;
let mouseHasMoved = false;
DEFAULT_INTERVAL = 2000;
myInterval = setInterval(()=> {
if (mouseHasMoved) {
mouseHasMoved = false;
console.log(`prevX: ${previousX}, prevY: ${previousY}, x: ${latestX}, y: ${latestY}`);
previousX = latestX;
previousY = latestY;
}
}, DEFAULT_INTERVAL);
onmousemove = () => {
window.addEventListener('mousemove', (e)=> {
latestX = e.x
latestY = e.y
mouseHasMoved = true;
});
};
| |
doc_23531615
|
Private Sub_F1_Click()
StringVariableForLaterUse ="F1"
If F1.Value = True Then
'Display Data Relevant to F1
End If
End
I'm wondering if I can use
StringVariableForLaterUse = ThisControl.Name
and
If ThisControl.Value = True Then
I'd then be able to replicate this a further 78 times. Currently pure laziness factor, however I want my Subs to be self sufficient as possible. Any thoughts folks?
A: You can never use a string like an object... But, for an ActiveXcheck box, use the next workaround code.
Public chk1 As Shape
Private Sub CheckBox1_Click()
Set chk1 = ActiveSheet.Shapes(CheckBox1.Name)
MsgBox chk1.OLEFormat.Object.Object.value
End Sub
You can use now chk1 in another Sub inside the sheet module.
You can also refer to it from a module Sub, referencing the sheet, too:
Sub testSheetChk()
Debug.Print Worksheets("Sheet Name").chk1.OLEFormat.Object.Object.value
End Sub
But, this will work only after you firstly run (once) the click event, in order to alocate a value to the object variable.
| |
doc_23531616
|
how many apps are in each group: super light (<2MB) light (2MB;30MB) bulky(>30MB) and 'varies with device'
My dataframe looks something like this:
app category rating reviews size installs type price content-rating genres last-updated current-ver android-ver
Football Wallpapers 4K ENTERTAINMENT 4.7 11661.0 4.0 1000000.0 Free 0.0 Everyone Entertainment 2018-07-14 1.1.3.2 4.0.3 and up
Dr Driving Racer GAME 4.3 183.0 68 10000.0 Free 0.0 Everyone Racing 2018-06-14 2.1 4.1 and up
Dr. B.R.Ambedkar SOCIAL 4.8 1902.0 5.2 100000.0 Free 0.0 Everyone Social 2014-06-05 1.3 2.1 and up
Dr. Battery - Fast Charger - Super Cleaner 2018 TOOLS 4.5 101738.0 10 1000000.0 Free 0.0 Everyone Tools 2018-07-26 2.2.82 4.0 and up
Dr. Booster - Boost Game Speed TOOLS 4.4 138872.0 22 10000000.0 Free 0.0 Everyone Tools 2018-05-15 2.0.1077 4.1 and up
...
Next Launcher 3D Theme Hit-G PERSONALIZATION 4.2 59.0 8.1 1000.0 Paid 1.7 Everyone Personalization 2015-08-16 1.05 2.2 and up
Next Launcher 3D Theme Stun-BW PERSONALIZATION 4.4 2839.0 5.1 100000.0 Free 0.0 Everyone Personalization 2014-01-11 1.00 2.2 and up
Nextdoor - Local neighborhood news & classifieds SOCIAL 4.3 51502.0 20 5000000.0 Free 0.0 Teen Social 2018-07-25 2.69 5.0 and up
Niche: College, K-12, and Neighborhood Search LIFESTYLE 4.0 42.0 26 5000.0 Free 0.0 Everyone Lifestyle 2018-07-06 1.0.1 4.4 and up
+Download 4 Instagram Twitter SOCIAL 4.5 40467.0 Varies with device 1000000.0 Free 0.0 Everyone Social 2018-08-02 5.03 4.1 and up
Length: 7935, dtype: int64
The solution should be a pandas.Series or dataframe that looks like this
ranges count
(0, 2] 43
(2, 30] ...
(30, 10000]
varies_on_device 12
The problem is that I don't know how to use pandas.cut with objects, usually the bins array are numbers that determinate the ranges.
My approach was to:
*
*take out the element of 'varies with device' group
*delete them of the principal dataframe
*later convert all the size elements to float
*make a group by using the cut and the bins ranges
*finally concat the two dataframes
but I think this is not the most optimized and quick way... hope is understandable
| |
doc_23531617
|
The Azure storage account has a storage endpoint, but I noticed that the storage account is not in the same resource group as my Managed Instance. Does that matter at all? Also is there a way to look at the logs for that authorization failure in the Azure Portal or Azure Storage Explorer?
A: Please check if you have set the role permission to access the Azure Storage:
Add role assignment:
*
*Role: choose the role (such as 'Contributor')
*Assign access to: Azure AD users, group, or service princpal
*Select: choose your Azure AD users, group, or service princpal.
Ref:https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-portal
| |
doc_23531618
|
...
SUBJECTS = (('MA8151','Engineering Mathematics'),('PH8151','Physics-1'),...)
subject = models.CharField(max_length=10, choices=SUBJECTS)
What I want is, I want to add another feature to the choice, that each choice has subject name, subject code and a credit point for it. I thought of creating a model
...
subname = models.CharField(max_length=100)
subcode = models.CharField(max_length=6)
credit = models.SmallPositiveInteger()
But since I'm new to Django, I don't know how this will work on linking an object the name of a choice? On the whole, if I assign a subcode for a student, I want his records to be updated with relevant subname and relevant credit points.
Help me out reaching the solution. Thanks in advance!
A: You can use ForeignKey() ManyToManyField OneToOneField you can refer https://docs.djangoproject.com/en/2.2/topics/db/models/#verbose-field-names
| |
doc_23531619
|
#March 27th 2017
#Class
import time
class DayPlanner:
def __init__(self):
self.schedule = []
def add(self, datetime, activity):
tt = time.strptime(datetime, '%Y-%m-%d %H:%M')
self.schedule.append( [time.mktime(tt), activity] )
def delete(self, datetime, activity):
tt = time.mktime(time.strptime(datetime, '%Y-%m-%d %H:%M'))
print("\n")
for i in range(len(self.schedule)):
if activity == self.schedule[i][1] and tt == self.schedule[i][0]:
print("[[Match Found]]")
print("\n")
del self.schedule[i]
break
def show(self):
for i in sorted(self.schedule):
print('{:s} {:s}'.format(time.ctime(i[0]), i[1]) )
#-------
sched = DayPlanner()
while True:
date = input('date and time? ')
if date == '':
break
act = input('activity? ')
sched.add(date, act)
print("\n")
sched.show()
print("\n")
while True:
date = input('Which date and time should I delete? ')
if date == '':
break
act = input('which activity should I delete? ')
sched.delete(date,act)
print("\n")
print("New Schedule")
sched.show()
print("\n")
print("\n")
while True:
date = input('Which Date should I show the schedule for?')
if date == '':
break
print("\n")
print("Schedule for the day")
sched.show()
So, I have a good setup for adding and removing my entries, even though the time format is crazy when typing it all out.
To add to the schedule you need to type the exact format such as 2017-5-5 3:00.
My main question is how would I format that last sched.show to only show the schedule of the day?
I know I would need to make changes to the def show().
Should I create a new def and have it specifically show the day?
I am drawing a blank here and would love some help!
A: def showday(self,day):
for i in sorted(self.schedule):
sec = i[0]
tt1=time.localtime(sec)
stt=time.strptime(day,'%Y-%m-%d')
if stt.tm_year == tt1.tm_year and stt.tm_mon == tt1.tm_mon and stt.tm_mday == tt1.tm_mday:
print(time.ctime(sec), i[1])
I used this def to fix my issue. My greatest resource was jupyter to find some help regarding time. I wont lie it took a bit but I got it all figured out and it works pretty well. Posting my solution for archive just in case someone else comes up with something similar.
| |
doc_23531620
|
all_C_Files = Selected_User_Output_Folder & "*.C"
Shell "cmd /c del /F" & all_C_Files
'Selected_User_Output_Folder = "C:\Users\Berater\Desktop\Config File Generator"
A: Why to use shell command at all when you can use Kill
Sub test()
Selected_User_Output_Folder = "C:\Users\Berater\Desktop\Config File Generator\*.c"
On Error Resume Next
Kill Selected_User_Output_Folder
End Sub
A: Always good practice to quote file/folder paths:
all_C_Files = Selected_User_Output_Folder & "*.C"
Shell "cmd /c del /F """ & all_C_Files & """"
| |
doc_23531621
|
Is this Big data problem ? or any parallel processing required ? Need to use any library ? Currently developing in nodejs. please give me suggestions or help .
| |
doc_23531622
|
The source looks like this:
> <span class="serien-heute-terminblock"><span class="img-wrap"><img
> title="ARD-alpha" alt="ARD-alpha"
> src="https://bilder.fernsehserien.de/logos/svg/10.svg"></span>heute</span>
I have tried the following 2 approaches but neither works:
for sender in doc.findALL("span", {"class":"serien-heute-terminblock"}):
sender_titel = sender.getText("img title")
print(sender_titel)
and
for sender in doc.findALL("span", {"class":"img-wrap"}):
sender_titel = sender.getText("img title")
print(sender_titel)
thanks for your help.
A: find_all or findAll instead of findALL.
import requests
from bs4 import BeautifulSoup
example = """
<span class="serien-heute-terminblock"><span class="img-wrap">
<img title="ARD-alpha" alt="ARD-alpha
src="https://bilder.fernsehserien.de/logos/svg/10.svg"></span>heute</span>"""
soup = BeautifulSoup(example, "lxml")
for sender in soup.find_all("span", {"class":"serien-heute-terminblock"}):
sender_titel = sender.find("img")
if sender_titel is not None:
print (sender_titel["title"])
ARD-alpha
| |
doc_23531623
|
Possible Duplicate:
Localization - Add additional language to localizable.strings file
Localize Localizable.strings with Xcode 4.5
It seems that the small "+" button has disappeared in 4.5.1 in the File Inspector tab
Edit: this is not a duplicate. I think it changed from Xcode 4.5 to 4.5.1 So please reopen.
| |
doc_23531624
|
For some background, I am programming a microcontroller with limited memory, modest processing power, and it is handling serial communication over a network to 36 other microcontrollers sending continuous sensor data which is uploaded to a webserver. The shorter the refresh rate of the data, the better, so I prefer basic program features.
Not that I'm saying the more complicated stuff I've looked in other forums for, like an array of strings, has worked.
In my desperation, I was able to get this to work.
char names_array[] = "Bob\0\0Carl";
printf("%s",names_array); //outputs Bob
printf("%s",names_array + 5); //outputs Carl
This is a horrible solution though. My indexing is dependent on the longest name in the array, so if I added "Megan" to my list of names, I'd have to add a bunch of null characters throughout the entire array.
What I want to do is something like this:
char names_array[2] = {"Bob","Carl"}; //does not compile
printf("%s",names_array[0]);
printf("%s",names_array[1]);
//Error: A value of type "const char *" cannot be used to
//initialize an entity of type "char" in "main.cpp"
but that didn't work.
I want to loop through the names in my list and do something with each name, so at this point, this is my best solution.
char name0[] = "Bob";
loop_code(name0);
char name1[] = "Carl";
loop_code(name1);
.
.
.
I expect there's a reasonable way to make an array of pointers, each to an array of char terminated by null(s). I must be doing something wrong. I refuse to believe that a language like C++ is incapable of such a basic memory allocation.
A: You can, e.g., get an array of pointers to null-terminated strings:
const char* names_array[] = { "Bob", "Carl" };
and then
std::printf("%s", names_array[0]);
std::printf("%s", names_array[1]);
The problem with your attempt
char names_array[2] = {"Bob","Carl"};
is that you declare names_array to be an array of characters. This should never compile because what the = {"Bob","Carl"} essentially attempts to do is initialize each character in that array of characters with an entire array of characters of its own. A character is just a character, you cannot assign an entire array of characters to just an individual character. More precisely, initialization of a character array from a string literal is a special case of initialization [dcl.init.string] that allows a single string literal to be used to initialize an entire character array (because anything else doesn't make sense). What you actually want would be something more like an array of character arrays. However, the problem there is that you'd have to effectively pick a fixed maximum length for all strings in the array:
char names_array[][5] = { "Bob", "Carl" }; // each subarray is 5 characters in length
which would be potentially wasteful. You can flatten a series of multiple strings into one long array and then index into that, like you did with your first approach. The downside of that, as you've found out, is that you then need to know where each string starts in that array…
If you just want an array of string constants, a more modern C++ approach would be something like this:
#include <string_view>
using namespace std::literals;
constexpr std::string_view names[] = {
"Bob"sv,
"Carl"sv
};
The advantage of std::string_view is that it also has information about the length of the string. However, while std::string_view is compatible with most of the C++ standard library facilities that handle strings, it's not so simple to use it together with functions that expect C-style null-terminated strings. If you need null-terminated strings, I'd suggest to simply use an array of pointers to strings as shown at the very beginning of this answer…
A: char can has only one character.
If you want to use char, you can do it like
char name0[3] = "Bob";
char name1[4] = "Carl";
char *nameptr[2] = {&name0[0], &name1[0]};
Acutally, this pretty hard.
I suggest to you, use std::string.
std::string name[2] = {"Bob","Carl"};
this code is acceptable.
| |
doc_23531625
|
But when I import this data into a DB. I do not see French characters instead it shows some other special characters.
Query I am using to import the .csv file is as follows:
--Create Table
Create Table A_test (A_1 VARCHAR(100))
--Bulk Import .csv file with ANSI encoding
BULK INSERT A_Test
FROM 'C:\A_Test.csv'
WITH
( DataFileType = 'widechar',
ROWTERMINATOR ='\n'
);
--Sample Data in C:\A_Test.csv file
Le vieux château
Une fête
Le dîner
L'hôtel
Could anyone help me on this?
A: You can alter the collation of the affected columns by running the following code (I just made up the column name and datatype):
ALTER TABLE dbo.a_test
ALTER COLUMN somecolumn varchar(100) COLLATE French_CI_AS NOT NULL;
Also you could create the original table with the relevant columns pre-collated:
CREATE TABLE dbo.a_test
(
[somecolumn] varchar(100) COLLATE French_CI_AS NOT NULL
)
BULK INSERT like this:
BULK INSERT a_test from 'C:\etc.txt' WITH (DATAFILETYPE = 'widechar')
| |
doc_23531626
|
AddProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent popup = new Intent(SingleVoucher.this, PopUp.class);
if (additionalProduct!=null) {
popup.putExtra("additionalamount", additionalQuantity);
popup.putExtra("additionalprice", additionalPrice);
popup.putExtra("additionalproduct", additionalProduct);
}
startActivity(popup);
}
});
the popup:
public class PopUp extends Activity {
private OnSubmitListener mListener;
@Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.popup_window);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
WindowManager.LayoutParams windowManager = getWindow().getAttributes();
windowManager.dimAmount = 0.75f;
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
TextView SubmitAdditional = (TextView) findViewById(R.id.SubmitAdditional);
final EditText product = (EditText) findViewById(R.id.adittionalTextEdit);
final EditText qty = (EditText) findViewById(R.id.additionalQuantityTE);
final EditText price = (EditText) findViewById(R.id.adittionalPriceTE);
final Intent intent = getIntent();
final Context context = this;
SubmitAdditional.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String additionalProduct = product.getText().toString();
String additionalQuantity = qty.getText().toString();
String additionalPrice = price.getText().toString();
if (additionalProduct!=null && additionalPrice.isEmpty()==false && additionalQuantity.isEmpty()==false) {
intent.putExtra("additionalamount", additionalQuantity);
intent.putExtra("additionalprice", additionalPrice);
intent.putExtra("additionalproduct", additionalProduct);
}
else{
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Missing Details");
alert.setMessage("Some of the required fields are missing. please try again");
alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
}
});
getWindow().setLayout((int) (width * .8), (int) (height * .3));
}
}
and the XML of the poup window is:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/BlueGray">
<TextView
android:id="@+id/AdditionalTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginTop="5dp"
android:layout_alignParentTop="true"
android:paddingTop="2dp"
android:text="Product Name"
android:textSize="18dp"
android:textColor="@color/White">
</TextView>
<EditText
android:id="@+id/adittionalTextEdit"
android:layout_width="260dp"
android:layout_height="50dp"
android:layout_below="@+id/AdditionalTitle"
android:background="@color/White"
android:textSize="12dp"
android:textColor="@color/Black"
android:layout_centerHorizontal="true"
android:gravity="top">
</EditText>
<TextView
android:id="@+id/additionalQuantityTV"
android:layout_marginLeft="12dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/adittionalTextEdit"
android:text="Quantity"
android:textColor="@color/White"
android:textSize="15dp"
android:layout_marginTop="5dp">
</TextView>
<EditText
android:id="@+id/additionalQuantityTE"
android:layout_width="100dp"
android:layout_height="20dp"
android:layout_toRightOf="@+id/additionalQuantityTV"
android:layout_below="@+id/adittionalTextEdit"
android:background="@color/White"
android:layout_marginTop="5dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="14dp"
android:layout_marginLeft="38dp"
android:numeric="integer"
android:textSize="14dp">
</EditText>
<TextView
android:id="@+id/adittionalPriceTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_below="@+id/additionalQuantityTV"
android:text="Overall price"
android:textColor="@color/White"
android:textSize="15dp"
android:layout_marginTop="5dp">
</TextView>
<EditText
android:id="@+id/adittionalPriceTE"
android:layout_width="100dp"
android:layout_height="20dp"
android:layout_toRightOf="@+id/adittionalPriceTV"
android:layout_below="@+id/additionalQuantityTE"
android:background="@color/White"
android:layout_marginTop="5dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="14dp"
android:layout_marginLeft="10dp"
android:numeric="decimal"
android:textSize="14dp">
</EditText>
<TextView
android:id="@+id/popupClose"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_below="@+id/adittionalPriceTE"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="14dp"
android:textColor="@color/White">
</TextView>
<TextView
android:id="@+id/SubmitAdditional"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_below="@+id/adittionalPriceTE"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="14dp"
android:textColor="@color/White">
</TextView>
</RelativeLayout>
I want to get the values from the EditText and send them back to the parent.
How can I send the data back to the view who called the popup?
A: You will have to startActivityForResult()
then return result from PopUp Activity using setResult()
see this good link for statActivityForResult
A: You can use startActivityForResult and setResult methods to achieve this.
In MainActivity start the popup activity like this
startActivityForResult(popup,1);
In popup activity use the setResult method to pass the value back to main activity.
Intent intent = new Intent();
intent.putExtra("data",data); // data is the value you need in parent
setResult(100,data);
In MainActivity use the onActivityResult method to get the data
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { value = data.getBundleExtra("data");
A: Try to use startActivityForResult in order to show the popup.
Here is an example: http://developer.android.com/training/basics/intents/result.html
Then in the main activity you should override onActivityResult in order to have access to the info you sent from popup.
| |
doc_23531627
|
I've tried with delay and various other RPC calls to try to try to synchronize the clients and server, but the clients run out of synchronization, and the program breaks. I think I have to incorporate future or promise, but I'm not sure how.
Every client has a unique ID (from 0 and up), and will store partitions according to that number. One line of data looks like this: AsfAGHM5om 00000000000000000000000000000000 0000222200002222000022220000222200002222000000001111
EDIT: updated code for example
Client
val numberOfClients = 3
var sentPartitionsCounter = 0
while(sentPartitionsCounter < numberOfClients) {
if(sentPartitionsCounter != id){
sendUnwantedPartition("src/main/scala/testFile."+sentPartitionsCounter.toString) //"partition."+client.sentPartitionsCounter
sentPartitionsCounter += 1
}
client.getWantedPartition()
}
def sendUnwantedPartition(filename: String): Unit = {
val dataList = Source.fromFile(filename).getLines.toList
val dataSeq = for {
dataLine <- dataList
dataValues = dataLine.split(" ", 2)
} yield (Data(key = dataValues(0), value = dataValues(1)))
val partitionID = filename takeRight 1
val request = Dataset(data = dataSeq, partitionID = partitionID.toInt)
val response = blockingStub.getUnwantedPartitions(request)
print("sent partitions")
}
def getWantedPartition(): Unit = {
val request = ID(id = id)
val response = blockingStub.sendWantedPartitions(request)
val wantedPartitions = new File("clientFiles/wantedPartitions"+id.toString+".txt")
val printWriter: PrintWriter = new PrintWriter(new FileWriter(wantedPartitions, true));
if(!wantedPartitions.exists()){
wantedPartitions.createNewFile()
}
for {
data <- response.data
} yield (printWriter.append(data.key + " " + data.value + "\n"))
printWriter.close();
}
Server
override def getUnwantedPartitions(req: Dataset) = {
val filename = "serverPartitions/partition"+req.partitionID+".txt"
val partition = new File(filename)
val printWriter: PrintWriter = new PrintWriter(new FileWriter(partition, true));
if(!partition.exists()){
partition.createNewFile()
}
for {
data <- req.data
} yield (printWriter.append(data.key + " " + data.value + "\n"))
printWriter.close();
Future.successful(Text("Got unwanted data"))
}
override def sendWantedPartitions(req: ID) = {
val filename = "serverPartitions/partition"+req.id+".txt"
try {
val dataList = Source.fromFile(filename).getLines.toList
val dataSeq = for {
dataLine <- dataList
dataValues = dataLine.split(" ", 2)
} yield (Data(key = dataValues(0), value = dataValues(1)))
val reply = Dataset(data = dataSeq, partitionID = req.id)
new File(filename).delete()
Future.successful(reply)
} catch {
// Partition hasn't been received yet
case e: FileNotFoundException => Future.successful(Dataset())
}
}
Proto
syntax = "proto3";
package protoPackage;
service DistrSorting {
rpc getUnwantedPartitions(Dataset) returns (Text) {}
rpc sendWantedPartitions(ID) returns (Dataset) {}
}
message ID {
int32 id = 1;
}
message Text {
string text = 1;
}
message Dataset {
repeated Data data = 1;
int32 partitionID = 2;
}
message Data {
string key = 1;
string value = 2;
}
| |
doc_23531628
|
When should an app use the MediaStore? A brief overview of the pros and cons of the MediaStore will be much appreciated.
A: As an avid android user.
I think MediaStore is the "Public Link" between the internal Android Media Scanner Application (You can manually invoke it through Spare Parts) and 3rd party applications, like yours.
I'm guessing MediaStore is this "public link" based on its android.provider packaging.
As providers in android, is how applications provide information to other applications
If MediaStore is a ContentProvider, reading information populated by MediaScanner.
Then MediaStore is for User media, such as music, video, pictures etc.
For ringtones, notifications; I think you are supposed to use android.media.RingtoneManager
Also don't hardcode the path "/sdcard/" There is an api call to get it, Environment.getExternalStorageDirectory()
http://twitter.com/cyanogen/status/13980762583
====
The pro is that Media Scanner runs every time you mount the removable storage to the phone, and it also scans the internal memory (if it has any like the HTC EVO & incredible)
A: I am no expert in this but as far as my common sense goes, well its the easy way to search for certain types of files.
If your app has a library of sorts, then using MediaStore instead of searching all by yourself is more useful, faster and less power consuming. Also you can be assured that those are all the files present in the system.
I hope this helps.
| |
doc_23531629
|
I also have a custom UserCreationForm that prompts users for their email and one password.
Unfortunately, the form doesn't validate the password, aside from min_length.
How do I enable the password validators in settings.AUTH_PASSWORD_VALIDATORS? The object is a list of distc, not Validators, so I'm not sure how to use them.
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(
widget=forms.PasswordInput(attrs=form_attrs.password),
min_length=8,
strip=True,
)
class Meta:
model = User
fields = ('email',)
widgets = {
'email': forms.EmailInput(attrs=form_attrs.email),
}
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data.get('password1'))
if commit:
user.save()
return user
A: As another answerer mentioned, Django uses the django.contrib.auth.password_validation.validate_password method to validate the password. You can create a clean_password1 method and add this to it, like so:
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(
widget=forms.PasswordInput(attrs=form_attrs.password),
min_length=8,
strip=True,
)
class Meta:
model = User
fields = ('email',)
widgets = {
'email': forms.EmailInput(attrs=form_attrs.email),
}
def clean_password1(self):
password1 = self.cleaned_data.get('password1')
try:
password_validation.validate_password(password1, self.instance)
except forms.ValidationError as error:
# Method inherited from BaseForm
self.add_error('password1', error)
return password1
A: The way django applies to it's built-in forms is
def get_password_validators(validator_config):
validators = []
for validator in validator_config:
try:
klass = import_string(validator['NAME'])
except ImportError:
msg = "The module in NAME could not be imported: %s. Check your AUTH_PASSWORD_VALIDATORS setting."
raise ImproperlyConfigured(msg % validator['NAME'])
validators.append(klass(**validator.get('OPTIONS', {})))
return validators
this and after this, the validation is done inside the form manually.
This means you can import password_validation from django.contrib.auth and use
@functools.lru_cache(maxsize=None)
def get_default_password_validators():
return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS)
this function to get the validators and inside your form
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(
widget=forms.PasswordInput(attrs=form_attrs.password),
min_length=8,
strip=True,
)
def clean_password1(self):
# Validate user password
# self.cleaned_data['password1'] has the password put into the field
# if the validation fails
# raise forms.ValidationError with the args and kwargs of your
# validators' error messages.
You can take a look at how the built-in registration form do it.
| |
doc_23531630
|
I used text-align: center; to align the text in the center for x axis.
How can I align it in middle for y axis?
A: Using flexbox you can specify align-items: center; justify-content: center; to center the text in an element.
p {
background: red;
height: 100px;
width: 100px;
display: flex;
align-items: center;
justify-content: center;
}
<p>a tag</p>
| |
doc_23531631
|
I was using v2 and was successful with it - I could get the lat and lng values and insert them into hidden inputs, so later I could insert them into a DB.
With V3, the best thing I could do was to show a map and make the search work, but I can insert the lat and lng to the hidden input and I can't make the ONLY marker change place. If I create a marker to start with the document, when you search and click it'll create another mark.
Here's my code:
function initialize() {
var myLatlng = new google.maps.LatLng(-1.456688, -48.477586);
var mapOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var markers = [];
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable: true,
title: 'Hello World!'
});
// Create the search box and link it to the UI element.
var input = /** @type {HTMLInputElement} */(
document.getElementById('pac-input'));
var searchBox = new google.maps.places.SearchBox(
/** @type {HTMLInputElement} */(input));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location,
draggable: true
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I'm sorry for asking that much, but I really spent all my day on the API documentatation and couldn't get it any better.
A: the SearchBox is not suitable when you search for an address, you better use an Places-Autocomplete.
To change the position of the ONLY marker you only have to set the position-property of the marker.
function initialize() {
var myLatlng = new google.maps.LatLng(-1.456688, -48.477586);
var mapOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable: true,
title: 'Hello World!'
});
//set the value of the hidden inputs when the position changes
google.maps.event.addListener(marker, 'position_changed', function() {
document.getElementById('latitude').value = this.getPosition().lat();
document.getElementById('longitude').value = this.getPosition().lng();
});
// Create an Autocomplete and link it to the UI element.
var input = /** @type {HTMLInputElement} */ (
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(input);
var searchBox = new google.maps.places.Autocomplete(
/** @type {HTMLInputElement} */
(input), {
types: ['geocode']
});
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'place_changed', function() {
var place = this.getPlace();
//when place has been found
if (place.geometry) {
marker.setOptions({
title: place.name,
position: place.geometry.location
});
if (place.geometry.viewport) {
marker.getMap().fitBounds(place.geometry.viewport);
} else {
marker.getMap().setCenter(place.geometry.location);
}
}
//otherwise
else {
marker.setOptions({
title: null
});
alert('place not found');
}
});
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0
}
<script src="//maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>
<input id="pac-input"/>
<input type="hidden" id="latitude"/>
<input type="hidden" id="longitude"/>
<div id="map"></div>
| |
doc_23531632
| ||
doc_23531633
|
$('.the_div_class').each(function(i, obj) {
if("a certain condition") {
$('.the_div_class')[0].toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class;
}
}
However I receive an error saying "$(...)[0].toggleClass is not a function". If I don't specify an index I toogle all the elements of the array... I console.log the "$('.the_div_class')" array and get a structure similar to this:
[div.the_div_class, div.the_div_class, div.the_div_class, div.the_div_class, div.the_div_class, prevObject: r.fn.init[1]]
And if I console.log "$('.the_div_class')[0]" I get this:
<div class="the_div_class">
Why doesn't it work and what should I do in order to make it work?
A: The code $('.the_div_class')[0] will only get the first element that matches that selector in the DOM with that class naively, it doesn't work because it's no longer a jQuery object (hence it doesn't have the method .toggleClass()). Inside .each() you can use this to refer to the current element being iterated:
$('.the_div_class').each(function(i, obj) {
if("a certain condition") {
$(this).toggleClass('other_div_class');
}
}
Note: To get a item by it's index in jQuery you can use .get(). For example:
$('.the_div_class').get(0).toggleClass('other_div_class');
A: Change your code to:
var collection = $('.the_div_class');
collection.each(function(i, obj) {
if("a certain condition") {
$(collection[0]).toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class;
}
}
You need to recreate jQuery object by passing DOM element to $ again, i.e $($('.the_div_class')[0]) for your code.
A: When you specify the index, you're fetching the plain javascript element that was selected with jQuery, not a jQuery object. This is why the toggleClass() method is unavailable to you.
You can wrap it in jQuery like this $($(selector)[i]) to convert it back to a jQuery object. However, the arguments supplied with the each loop are your friend here. That is, you can access the current object in the loop with $(obj).
A: You need to change the code to get element by using this keyword:
$('.the_div_class').each(function(i, obj) {
if("a certain condition") {
$(this).toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class;
}
}
| |
doc_23531634
|
A: You need to use two variables to store Min and Max primary keys. let's say @a and @b.
then using below query you can get your random number
declare @a int,@b int
select @b=max(id),@a=min(id)
from mytbl
SELECT FLOOR(RAND()*(@b-@a)+1)
| |
doc_23531635
|
svn checkout http://xxxx/xxxx --username xxxx
I get the usual:
svn is not recognized as an internal or external command, operable program or batch file
Does anyone know hoe to solve this issue?
A: TortoiseSVN doesn't come with a svn executable, at least not my version.
I think it makes use of the client libraries in DLL form.
Get the original SVN binaries e.g. from CollabNet. The "Command-line client" download should be what you need.
Edit: TortoiseSVN has command line options, too, but they differ massively from svn's ones. See Appendix D. Automating TortoiseSVN
A: actually there is an option while installing TortoiseSVN, whether user would like to the command line features. Be default, it's not installed; however, sure, you can install it at will.
| |
doc_23531636
|
i have this class Appearances, i show a bit of the code of the cpp
Appearances::Appearances(const char* id, float shininess,const char* textureref)
{this->id = id;
setShininess(shininess);
this->textureref = textureref;
}
and i want to join another class "Component" like this
Component(float ambient[4] , float diffuse[4] , float specular[4])
{setAmbient(ambient);
setDiffuse(diffuse);
setSpecular(specular);
}
And what I want is that i can call appearances with all of this joined, for example:
app = new Appearances(idAppearance, vAmb, vDif, vSpec, shininess, txtRef);
im trying to get this on c++
<appearance id="app1" shininess="6.0" textureref="ss" >
<component type="ambient" value="5 5 5 5" />
<component type="diffuse" value="5 5 5 5" />
<component type="specular" value="0.6 0.6 0.6 0.6" />
</appearance>
I dont know if I explained well what i want, but can someone help me? :)
A: To do that you would need to change your constructor to include the data of the component class.
Appearances::Appearances(const char* id,float ambient[4] , float diffuse[4] , float specular[4], float shininess,const char* textureref)
Then in the constructor you call the constructor of Component.
But this raise the question of design. If you can initialize your component, it means it just a logical group you want to do, i suggest to use nomenclature instead like comp_Ambient.
If you want to be able to have more than one component in your class, then you don't want to initialize it in the constructor.
The other reason I see to use this design, is being able to use component on other object, then, don't put it in the class.
A: Do you need full access to components members and functions? If so, I see two possible answers to your question. The simplest way would be to create a derived class which inherits from both Appearances and Component. For example, you could declare class Design: public Appearances, public Component. While multiple inheritance can sometimes complicate design, it seems to be the most straightforward option. See more here.
If you would like to add the functionality to the existing Appearances class, this can be done by making Component a friend class of Appearances. This is done by adding the line friend class Appearances; to your Component class, which allows Appearances to access all members of Component. In this case, you will also need to declare two constructors: one for initializing Appearances without Component, and one for initializing Appearances with the data for Component.
| |
doc_23531637
|
Good day!
A: If it's modal, you can just call [self dismissModalViewControllerAnimated:YES]; in the view's class you want to dismiss.
A: since ios5 dismissModalViewControllerAnimated is deprecated, use this:
[self dismissViewControllerAnimated:TRUE completion:^{
//completion or NULL
}];
A: try this
[self.flipViewOneController.view removeFromSuperview];
| |
doc_23531638
|
def my_func(var1, var2):
my_dict = dict(var1 , var2)
print(my_dict)
my_func("x", "y")
Prints:
{"var1": "x", "var2": "y"}
Edited in order to make it less artificial. The idea is to avoid dict(var1=var1)
A: var1 = "x"
var2 = "y"
my_dict = dict(var1=var1, var2=var2)
print(my_dict)
Prints:
{'var1': 'x', 'var2': 'y'}
A: You can get them from the locals() dict
var1 = "x"
var2 = "y"
my_dict = {k: v for k, v in locals().items() if k in ['var1','var2']}
print(my_dict)
Output
{'var1': 'x', 'var2': 'y'}
| |
doc_23531639
|
func listForName (name: String) -> List {
if let list = listsDict[name] {
return list
} else {
return nil
}
}
It says : error: nil is incompatible with return type 'List'
But I don't want to return something like empty List object, I want to return nothing when optional is empty. How to do that?
A: To fix the error you need to return an Optional: List?
func listForName (name: String) -> List? {
if let list = listsDict[name] {
return list
} else {
return nil
}
}
Or just return listsDict[name] since it will either be optional or have the list itself.
func listForName (name: String) -> List? {
return listsDict[name]
}
But i don't want to return something like empty List object, i want to return nothing when optional is empty. How to do that?
You have several choices:
*
*Return optional List (List?)
*Return an empty list when no data is found
*Return an exception (depends on context)
*Use an enum to represent Either/Result (similar to Optional but could be better depending on your use-case)
| |
doc_23531640
|
main.cpp
#include "baz.h"
int main()
{
foo::bar x;
x.baz();
foo::foo_non_member();
}
baz.h
namespace foo
{
class bar
{
public:
bar() = default;
void baz();
};
void foo_non_member();
};
baz.cpp
#include "baz.h"
#include<iostream>
using namespace foo;
void bar::baz()
{
std::cout << "baz\n";
}
namespace foo
{
void foo_non_member()
{
std::cout << "non-member\n";
}
}
The above code compiles and runs.
$> g++ main.cpp baz.cpp; ./a.out
baz
non-member
If I remove the using namespace foo; from baz.cpp, I get a compiler error.
$> g++ main.cpp baz.cpp
baz.cpp:5:6: error: ‘bar’ has not been declared
void bar::baz()
If I put that using statement back in and move the definition of foo_non_member() outside of the foo namespace, I get a linker error.
$> g++ main.cpp baz.cpp
/tmp/ccHeSwsZ.o: In function `main':
main.cpp:(.text+0x24): undefined reference to `foo::foo_non_member()'
collect2: error: ld returned 1 exit status
Why does the using keyword appear not to have the same effect here for bar::baz() and foo_non_member()?
A: For this part:
using namespace foo;
void bar::baz()
{
std::cout << "baz\n";
}
The using namespace foo; is used for the lookup of the bar:: part, and due to that the compiler is able to tie the definition of void bar::baz() to the declaration in the namespace foo.
And if you remove using namespace foo; it is not able to find bar.
If I put that using statement back in and move the definition of foo_non_member() outside of the foo namespace, I get a linker error.
void foo_non_member()
{
std::cout << "non-member\n";
}
Here foo_non_member not have any relation to bar:: or anything else (according to the specs) that would allow the compiler to figure out that this definition is related to the declaration in the namespace foo.
The standard committee for sure could have added some rules to the specification to allow the compiler to get the foo_non_member definition and the declaration together if the using namespace foo; is present but they decided to don't do so.
The reason for that is likely because you then would have the ambiguity about whether you want to define a new void foo_non_member() outside of the namespace foo or if you want to have a definition for void foo_non_member() of foo.
| |
doc_23531641
|
Attaching the screenshot.
Please help me understand the problem in simpler terms as I am new to Python.
| |
doc_23531642
|
The ICEFaces documentation suggests that I can do this using the focus attribute of the outputBody component. Specifically:
If you setting the initial focus, the focused component must be rendered on first render call, if not then set the focus attribute only when the component gets rendered.
This seems to suggest that I can manipulate the value of the focus attribute at the time that my conditional component gets rendered. However, I don't see any attributes of the inputText component that allow me to change a value at the time the component is rendered.
Am I misreading the documentation? When and where can I alter the value of the focus attribute of outputBody so that my conditionally-rendered field gets the input focus when it appears? Or am I using the wrong tool to solve this problem?
A: Maybe you can use this
JavascriptContext.applicationFocus(FacesContext.getCurrentInstance(), "form:fieldM");
A: You can use some Javascript to set focus on an element.
Here's the Java snippet required to do this:
JavascriptContext.addJavascriptCall(FacesContext.getCurrentInstance(),
"document.getElementById('myForm:myTxtBox').focus();");
myTxtBox is the ID of your form element, and myForm is the ID of your form.
You can use this wherever you are changing certain variables' values to render/hide fields.
A: Due to the fact that I'm using both Seam and ICEFaces, I was not able to invoke Javascript reliably from my server-side Java code. I was, however, able to add the necessary Javascript in-line in my XHTML, within the ui:component that was being conditionally rendered, close to the input field I needed the focus to go to. The relevant section of my XHTML looks like this:
<ice:panelGroup id="textPanelInput" >
<ice:form id="textInputForm" partialSubmit="true" style="vertical-align:middle;">
<ice:inputText id="textInput" valueChangeListener="#{appField.valueChangeListener}"
size="#{appField.fieldDefLengthAsInt}"
value="#{appField.value}"
styleClass="fieldStyle" rendered="#{appField!=null}"
>
</ice:inputText>
<ice:message id="jo" for="textInput" />
</ice:form>
</ice:panelGroup>
<script type="text/javascript">document.getElementById('panelsFields:0:textInputForm:textInput').focus();</script>
The Javascript line at the bottom is the line I added to solve my problem. All of the code above is in a ui:component block that may or may not be rendered, based on other conditions. When this ui:component block is rendered, my Javascript goes with it, and sets the input focus to my desired input field.
A: ICEfaces supports javascript api which has setting focus function. Thus you may use it like in the next excerpt:
<script type="text/javascript">
jQuery(document).ready(function () {
ice.applyFocus(elementId);
});
</script>
elementId is jsf component clientId.
ICEFaces javascript Api
| |
doc_23531643
|
Why second processing takes more time than first one?
A: This doesnt sound like normal SSAS behaviour. I would suspect some external factor.
| |
doc_23531644
|
File "wide_n_deep_feed.py", line 224, in <module>
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
File "/usr/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 48, in run
_sys.exit(main(_sys.argv[:1] + flags_passthrough))
File "wide_n_deep_feed.py", line 185, in main
FLAGS.train_data, FLAGS.test_data)
File "wide_n_deep_feed.py", line 166, in train_and_eval
steps=train_steps)
File "/usr/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 241, in train
loss = self._train_model(input_fn=input_fn, hooks=hooks)
File "/usr/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 686, in _train_model
_, loss = mon_sess.run([estimator_spec.train_op, estimator_spec.loss])
File "/usr/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 534, in __exit__
self._close_internal(exception_type)
File "/usr/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 569, in _close_internal
self._sess.close()
File "/usr/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 811, in close
self._sess.close()
File "/usr/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 908, in close
ignore_live_threads=True)
File "/usr/lib/python2.7/site-packages/tensorflow/python/training/coordinator.py", line 389, in join
six.reraise(*self._exc_info_to_raise)
File "/usr/lib/python2.7/site-packages/tensorflow/python/estimator/inputs/queues/feeding_queue_runner.py", line 94, in _run
sess.run(enqueue_op, feed_dict=feed_dict)
File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 895, in run
run_metadata_ptr)
File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1124, in _run
feed_dict_tensor, options, run_metadata)
File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1321, in _do_run
options, run_metadata)
File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1340, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InternalError: Unable to get element from the feed as bytes.
PS: there are some files generated in my models directory already:
checkpoint, events, graph.pbtxt, model.ckpt-0.data-00000-of-00001,model.ckpt-0.index,model.ckpt-0.meta
Any answers will be appreciated.
A: EDIT:
The error occurred when you use the dataframe with NaN value, so Tensorflow can not convert the columns to tf.Dtype, you can use the line in sample code:
df_data = df_data.dropna(how="any", axis=0)
to remove all NaN samples or you can cast the numeric column and replace all NaN value with empty string like this:
# Cast to numeric column
df_data["numeric_column_title"] = pd.to_numeric(df_data["numeric_column_title"],errors='coerce')
# Replace NaN value with 0
df_data[["numeric_column_title1", "numeric_column_title2"]] = df_data[["numeric_column_title1", "numeric_column_title2"]].fillna(value=0)
# Replace other string columns with empty string
df_data = df_data.fillna(value='')
Hope this help :)
| |
doc_23531645
|
Possible Duplicate:
Java detect changes in filesystem
Can anyone suggest a Java API for tracking events in FileSystem? I found one - JNotify, but it doesn't support 64-bit systems.
Also, the new java.nio.* library is very new to use in a deployment level application, as many JREs don't really support it yet.
One alternative is to poll the FS for changes, which I am sure many do, but my gut feeling says that it's going to be very resource intensive.
| |
doc_23531646
|
def get_total_review(soup):
try:
# total_review1= soup.find("div", attrs={'id': 'filter-info-section'}).string.strip()
total_review1= soup.find("div", attrs={'data-hook': 'cr-filter-info-section'}).string.strip()
total_review = sototal_review1.find("div", attrs={'class':'a-row a-spacing-base a-size-base'}).string.strip()
except AttributeError:
total_review = ""
return total_review
I tried adding every particular id, class but the review count isn't getting displayed ('3,432' in this case, as you can see in the image):
| |
doc_23531647
|
@Html.CheckBox("Completed", new { onclick = "$(this).parent('form:first').submit();" })
It keeps rendering the ' around 'form:first' as html encode values though. Any ideas how to fix this?
Thanks
Nick
A: why not just wire it up with a jquery click event??
@Html.CheckBox("Completed", new { id = "myButtonID" })
then in your js code...
$(function(){
$("#myButtonID").click(function(){
//submit the form here
});
});
| |
doc_23531648
|
<?php
$foundOneMatchingRow = FALSE;
foreach ($arrCSV as $row) {
if (strpos($row['5'], $val) !== FALSE && strlen($row['5']) > 4) {
$foundOneMatchingRow = TRUE;
echo $row['6'];
}
}
?>
The above code outputs from the value of $val = $_GET['menu']; which is done buy the URL.
I would like to make a search if possible please based on words in $row['6'];.
There will be a search on the page which will pass the search to the URL.
Which would look something like http://example.com/search.php?val=dogs
So the code would look for ANYTHING that relates to dog in $row [6]
I hope I have been clear. Any gudiance would be more than welcome. I am testing everything now.
Thank you
A: if (strpos($row['6'], $val) !== FALSE) will evaluate to true if $row['6'] contains "dog" (if $val's value is "dog"). That is, will evaluate to true as well if the string in $row['6'] is "bulldog" or "whateverdogwhatever".
BTW, why do you need this condition: strlen($row['5']) > 4? (which I guess should be at least strlen($row['6']) > 4 if you search on $row['6']).
Something else: aren't you confusing strings and integers? Maybe if (strpos($row['6'], $val) !== FALSE) should be if (strpos($row[6], $val) !== FALSE)?
EDIT
I would suggest to define constants for your CSV columns, for readability.
What about for example:
define('CSV_ID', 5);
define('CSV_TEXT', 6);
//...
foreach ($arrCSV as $row) {
if (strpos($row[CSV_TEXT], $val) !== FALSE && strlen($row[CSV_ID]) > 4) {
//...
echo $row[CSV_TEXT];
}
}
| |
doc_23531649
|
[CreateAssetMenu(fileName = "Map Information", menuName = "Map", order = 0)]
public class Map : ScriptableObject
{
public Terrain[] tiles;
}
Terrain is a class:
public class Terrain
{
//things and functions
}
the problem is that when I get a reference of this SO and pass some of this terrains to other classes and scripts, when I edit those the SO keep those changes, i have tried making Terrain a struct but it doesn't work and keep keeping changes.
A: By default, C# passes objects by reference, meaning all references of an object in your code will be updated when you make changes to one of them, if you'd like a clone of the Terrain then you can add the following function to your Terrain class:
public Terrain Clone()
{
return (Terrain)this.MemberwiseClone();
}
After that, if you need a terrain from the array without having any of the changes affect the original terrain then you can use something like:
Terrain terrain = Terrain[0].Clone();
// the original terrain will remain unaffected if any changes are made to this
| |
doc_23531650
|
I have several .txt files and each one starts with:
<TABLE class="meta-attributes__table" border="0" cellspacing="0"
cellpadding="0">
I need to replace only the first newline in each file so that the result to look like this
but without touching the rest of the newlines in the file.
A: Find: ^([^\n]*)\n
Replace: $1
Use verbatinum mode with @.
| |
doc_23531651
|
And that's exactly what I am doing. I am not having too much trouble on the Sinatra part, however I am having a bit of trouble on the rackup/thin/server part. Apparently there are two ways to deploy the application: using Sinatra itself (using the run! method) and using a rackup file (typically config.ru).
Using Sinatra's run! method is extremely intuitive and works like a charm, but apparently it doesn't work if I want to deploy my app on heroku. As a matter of fact, almost all the Sinatra apps that I have encountered on GitHub use a config.ru file.
Using a rackup file might be equally intuitive, but I can't manage to understand how to pass options from the Sinatra app to the server (ir: the port). I tried to merge options to rackup's default options array:
MyApp::App.default_options.merge!(
:run => false,
:env => :production,
:port => 4567
)
run MyApp::App
by adding options directly to the app:
MyApp::App.set :port, 4567
MyApp::App.set :run, false
MyApp::App.set :env, :production
run MyApp::App
by setting options from within the application class:
module MyApp
class App < Sinatra::Base
set :port, 4567
set :run, false
set :env, :production
# ...
# config.ru
require 'app'
run MyApp::App
All the methods above failed, either by showing error messages or by just not taking any of the options into consideration. So is there any way to pass options to rackup/thin/the sever via a Sinatra app when using a rackup file? Or the options in questions should be passed directly to rackup/thin/the sever via command-line options?
As a reference to the problem, here is the little Sinatra application I am building: https://github.com/AzizLight/Wiki/
A: I know I'm resurrecting an ancient question here, but I came across another useful solution not yet mentioned. As stated in this rack wiki tutorial:
the first line starting with #\ is treated as if it was options, allowing rackup arguments to be specified in the config file.
So if you wanted to set your host to 0.0.0.0 and port to 5656, you would add the following line to the beginning of your config.ru file:
#\ -o 0.0.0.0 -p 5656
A: You're actully going to pass options to thin on the command line directly or via a configuration file. See all options:
$ thin -h
For production, use a configuration file:
$ thin -C thin-production.yml -R config.ru start
Here is an example thin-production.yml file:
---
address: localhost
port: 3020
servers: 4
max_conns: 1024
max_persistent_conns: 512
timeout: 30
environment: production
pid: tmp/pids/thin-production.pid
log: log/thin-production.log
daemonize: true
| |
doc_23531652
|
Thanks
A: Yes, it reads them the same.
But...
Linux uses case-sensitive file-systems.
So if you type:
http://localhost.com/whatever.aspx
and your site is actually called whatever.aspx, then it will work.
However, if you type Whatever.aspx, that will get you a 404.
Also, if your site's codebehind is called Master.cs (with class Master), and you reference it on a aspx file with master.cs (such as the default visual Studio web application template), you will get a "not found" error.
Additionally, if you run mono on mod-mono with Apache, i think it runs on port 8080 or 8082 by Default, so you have to type http://localhost.com:8080/whatever.aspx.
A better idea might be to run servicestack on nginx via fastcgi-mono-server4.
A: It sounds like casing - you should fix that for performance reasons, but in the meantime you can get Mono to ignore-case by setting the MONO_IOMAP environment variable as follows before starting your mono process e.g. I use the following in my service script:
export MONO_IOMAP=all
${MONOSERVER} /applications=${WEBAPPS} /socket=tcp:127.0.0.1:9000 &
It's documented here:
http://www.mono-project.com/IOMap
| |
doc_23531653
|
The code which i am basing mine of comes from this MSDN page
....
object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
//args in this case is an object[]. any way to pass a string?
return mi.Invoke(wsvcClass, args);
I am aware that Newtonsoft provides a way to deserialize strings but can it do so into an object[]? or is there another way to do this?
A: The method signature you are looking at takes an Object[] representing all parameters in your method. For example:
public void DoStuff(string x, string y, int b);
Could be called like this:
methodInfo.Invoke(wscvClass, new object[] { "x", "y string", 500 });
So in your case you should be able to call Invoke using:
string jsonEncodedString = "{ }"; // whatever you need to do to get this value
mi.Invoke(wsvcClass, new object[] { jsonEncodedString });
MethodInfo MSDN Link
| |
doc_23531654
|
https://example.com/en/paths
https://example.com/es/paths
I installed wordpress in /public/blog. It is working successfully.
I also installed WPML plugin in wordpress then url structure was like this,
https://example.com/blog/en/blog-paths
https://example.com/blog/es/blog-paths
So my first URL structure is broken. This is a situation I would not prefer for SEO.
Any advice on how to install wordpress inside Laravel application, keeping the multilingual url structure?
I want to result url structure like this instead of above schemes,
https://example.com/en/blog/blog-paths
https://example.com/es/blog/blog-paths
A: I'd try to install Wordpress inside public folder of your Laravel app that is in charge of responding to example.com via app/public/index.php
Thus, every request to app/public/blog/ will be handled by WordPress.
Imho, this setup save your current url structure and do not interfere in any way.
Probably you have to adjust your Nginx config, but that is another question.
| |
doc_23531655
|
// one dimensional array
public void WorkOnJaggedArray<T>(int rank, int[] dimensions, T[] data)
{
/* code */
}
// two dimensional array
public void WorkOnJaggedArray<T>(int rank, int[] dimensions, T[][] data)
{
/* code */
}
// three dimensional array
public void WorkOnJaggedArray<T>(int rank, int[] dimensions, T[][][] data)
{
/* code */
}
// and so on...
Given that I have the rank and the size of each dimension passed in, I should be able to generalize the code inside my method. Is there a good way to achieve what I'm asking for?
A: You can use "System.Array" to manage parameters of any rank :
Create your array instance by calling Array.CreateInstance.
This will give you an instance of the Array class.
Call SetValue to assign values to your array.
Use GetValue to retrieve any elements of the array.
public void WorkOnJaggedArray<T>(int rank, int[] dimensions, Array data)
{
/* code */
}
| |
doc_23531656
|
SpringDemo.java
public class SpringDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle=(Triangle)context.getBean("triangle");
triangle.draw();
}
}
Triangle.java
package org.amulya.springs;
public class Triangle {
private Point pointA;
private Point pointB;
private Point pointC;
public Point getPointA() {
return pointA;
}
public void setPointA(Point pointA) {
this.pointA = pointA;
}
public Point getPointB() {
return pointB;
}
public void setPointB(Point pointB) {
this.pointB = pointB;
}
public Point getPointC() {
return pointC;
}
public void setPointC(Point pointC) {
this.pointC = pointC;
}
public void draw() {
System.out.println("pointA is (" + getPointA().getX() + "," + getPointA().getY() + ")");
System.out.println("pointB is (" + getPointB().getX() + "," + getPointB().getY() + ")");
System.out.println("pointC is (" + getPointC().getX() + "," + getPointC().getY() + ")");
}
}
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="triangle" class="org.amulya.springs.Triangle">
<property name="pointA" ref="zeropoint"/>
<property name="pointB" ref="point1"/>
<property name="pointC" ref="point2"/>
</bean>
<bean id="zeropoint" class="org.amulya.springs.Point">
<property name="x" value="0"/>
<property name="x" value="0"/>
</bean>
<bean id="point1" class="org.amulya.springs.Point">
<property name="x" value="-20"/>
<property name="x" value="0"/>
</bean>
<bean id="point2" class="org.amulya.springs.Point">
<property name="x" value="20"/>
<property name="x" value="0"/>
</bean>
</beans>
point.java
package org.amulya.springs;
public class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
spring.xml : /SpringDemo/src/spring.xml
Exception:
Error creating bean with name 'triangle' defined in class path
resource [spring.xml]: Could not resolve matching constructor (hint:
specify index/type/name arguments for simple parameters to avoid type
ambiguities)
please help me
A: <bean id="zeropoint" class="org.amulya.springs.Point">
<property name="x" value="0"/>
<property name="x" value="0"/>
</bean>
<bean id="point1" class="org.amulya.springs.Point">
<property name="x" value="-20"/>
<property name="x" value="0"/>
</bean>
<bean id="point2" class="org.amulya.springs.Point">
<property name="x" value="20"/>
<property name="x" value="0"/>
</bean>
in this code change the property name to X and Y
the error comes due to ambiguity
| |
doc_23531657
|
The error message is,
So the question is, if the support for .net framework removed from the Microsoft.Extensions.Configuration 1.0.0?
Is there any particular reasons?
Will the support be added in a future version?
A: You need to update your RC1 project to RTM, many things have changed since.
Shawn Wildermuth has two great blogs about updating.
RC1 -> RC2: https://wildermuth.com/2016/05/17/Converting-an-ASP-NET-Core-RC1-Project-to-RC2
RC2 -> 1.0.0 RTM: https://wildermuth.com/2016/06/27/Converting-ASP-NET-Core-1-0-RC2-to-RTM-Bits
And when your finished don't forget to add "version": "1.0.0-preview2-003121" to your global.json file. This tells Visual Studio which version of ASP.NET Core you are using.
You'll also need Visual Studio update 3 in order to use ASP.NET Core 1.0.0.
| |
doc_23531658
|
It html, what I want would be:
<select class="selectpicker">
<option value="" disabled selected style='display:none;'>Difficulty</option>
<option value="b">Beginner</option>
<option value="i">Intermediate</option>
<option value="a">Advanced</option>
</select>
In rails all I have is:
<%= f.select(:difficulty, [['Beginner', 1], ['Intermediate', 2], ['Advanced', 3]], {}, { :class => 'selectpicker' }) %>
http://jsfiddle.net/chapster82/QL6D7/
Thanks for any help.
A: I think I figured it out but is this correct?
<%= f.select(:difficulty, [['Difficulty', '0'], ['Beginner', 1], ['Intermediate', 2], ['Advanced', 3]], {:disabled => 0, :selected => 0}, { :class => 'selectpicker' }) %>
| |
doc_23531659
|
To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding. Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs.
If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.
Launching lib/main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
FAILURE: Build failed with an exception.
*
*What went wrong:
Execution failed for task ':app:mergeDebugResources'.
Multiple task action failures occurred:
A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
> Android resource compilation failed
/Users/mac/Desktop/main_files/source/news_app/build/app/intermediates/incremental/mergeDebugResources/merged.dir/values-h??????dp-v13/values-h??????dp-v13.xml: error: invalid configuration 'h??????dp-v13'.
A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
> Android resource compilation failed
/Users/mac/Desktop/main_files/source/news_app/build/app/intermediates/incremental/mergeDebugResources/merged.dir/values-sw??????dp-v13/values-sw??????dp-v13.xml: error: invalid configuration 'sw??????dp-v13'.
*
*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
*Get more help at https://help.gradle.org
BUILD FAILED in 18s
Exception: Gradle task assembleDebug failed with exit code 1
A: This is for the new flutter update. There is nothing you can do. Either use an other package or ask the package developer to fix the problem. This error is after version 2.5 of the flutter.
or you can downgrade flutter version.
A: Please check your pubspec.yaml file and make sure you are using the latest version of the facebook_audience_network which is facebook_audience_network: ^0.9.0 then check the documentation if you doing the android configurations correctly.
the do a flutter upgrade.
| |
doc_23531660
|
A: See this
https://jsfiddle.net/wt7wxn8x/1/
var test = new Date("01 January 2016");
console.log((test.getMonth() + 1) + '/' + test.getDate() + '/' + test.getFullYear());
A: You could use a library like moment.js:
moment('01 January 2016').format('DD/MM/YYYY')
A: please add datepicker like this this in your html
<script type="text/javascript">
$('#datepicker').datepicker({
autoclose: true,
format: 'dd/mm/yyyy'
});
</script>
then get your datepicker value
$('#datepicker').val()
A: You can specify the format like so.
$('.datepicker').datepicker({
format: 'mm/dd/yyyy',
startDate: '-3d'
});
A: You have two options,
Set the data-date-format attribute on the input element.
or
Use the format config to set your desired format.
$('.datepicker').datepicker({
format: 'dd/mm/yyyy'
});
$('#submit-btn').on('click', function(e) {
$('#display-area').html($('#datepicker-1').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<form>
<div class="form-group">
<label for="datepicker-1">Start Date</label>
<input class="form-control datepicker" id="datepicker-1" data-date-format="dd/mm/yyyy" aria-describedby="datepickerHelp">
<small id="datepickerHelp" class="form-text text-muted">Select a date.</small>
</div>
<input type="button" id="submit-btn" class="btn btn-primary" value="Show Date" />
</form>
<hr />
<strong>Date Value:</strong> <span id="display-area"></span>
A: We can use Parse to convert string month to corresponding number. please try this one:
let str = "1 January 2016",
str2 = "1 mar 2016",
str3 = "1 au 2016";
function cDate(str) {
if(!(Date.parse(str))) {return 'error';}
let dt = str.split(' ');
let d = new Date(Date.parse(`${dt[1]} ${dt[0]}, ${dt[2]}`));
let result = `${d.getDate()}/${d.getMonth()+1}/${d.getFullYear()}`;
return result;
}
console.log(str, '==', cDate(str));
console.log(str2, '==', cDate(str2));
console.log(str3, '==', cDate(str3));
| |
doc_23531661
|
{"a":""b" c"}
I try to parse it out by json library in python:
js = json.loads(data)
This code shows me an error:
ValueError: Expecting , delimiter
So as it is understood that I need to escape 3rd and 4th quotes or change them by single quotes.
How this operation can be done automatically (meaning that I want to escape that quotes by program)?
thank you
A: If it looks exactly as you described something like this would be a possible way
loop all occurences of ""
replace with "\".
from current position search for next "
replace it with \"
All in all I guess you need to write your own parser.
If the errors are more complicated it might be a good way to use extend the json parser for error correction.
In case an exception gets thrown the parser tries to detect and resolve it. If not possible throw the exception.
| |
doc_23531662
|
When using Apache Cordova, how do I set the priority? The main documentation about Cordova notifications doesn't mention anything about setting priorities.
I need the local code in the app to put up a "normal" Android notification. How is that done?
Edit... I've since found the plugin by katzer that is better than the 'core' plugins. It still doesn't have priorities, but I can live it with.
A: Simply add property priority:{number between -2 to 2} on notification.
example:
cordova.plugins.notification.local.schedule({
id: 1,
title: 'title',
text: 'text',
icon: 'iconfile.png',
priority: 1,
sound: null,
at: new Date(new Date().getTime() + 10)
});
hope this will help u.
| |
doc_23531663
|
bower.json file below
{
"dependencies": {
"angular": "latest",
"requirejs": "latest",
"angularAMD": "latest"
},
"resolutions": {
"angular": "1.5.8"
}
}
and .bowerrc
{
"directory": "bower_components/lib"
}
Also of note is that I installed bower through nuget, which added a .bin folder to the project with the following files in it bower.cmd, git.cmd, and node.cmd. I believe these are mini instanced of git and node to use for fetching, I assume the problem lies somewhere with these as they are the only real difference between intellij and visual studio.
A: Try running the command 'bower -v' in your terminal and see the version of your bower. I have 1.8.0 installed in my system and requirejs does get installed correctly for me with the require.js file inside the requirejs folder installed by bower. Although, I do remember facing such issues at some other point in time for another package which I solved it by cleaning my bower cache, you can do that by running the command 'bower cache clean' and while you are at it you may also try to clear your temp folder by which is by pressing 'windows key + R' typing %temp% in the search and then press enter, delete whatever can be deleted and, restart your terminal and go over the installation again.
The process for clearing the temp folder is for windows, you may want to look for another way to clear it if you are not on a windows machine.
Thanks.
| |
doc_23531664
|
protected void Page_Load(object sender, EventArgs e)
{
Session.Clear();
Session.RemoveAll();
Session.Abandon();
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
}
A: Use following code :-
Request.Params.Clear();
if you want to delete servervariables data according to type use this one
Request.ServerVariables["variableName"].Remove(0);
it will delete all characters from this string
| |
doc_23531665
|
var text = ["Heather", "kfdjsalfjdai", "fdjafhjdksafh", "Heather", "Heather", "fjdiafjdoisfhoids"];
var myName = "Heather";
var hits = [];
for(var i = 0; i < text.length; i++) {
if (text[i] === myName[i]) {
for(var j = i; j < (myName.length + i); j++); {
hits.push(text[j]);
}
}
}
A: You can use array filter function:
var hits = text.filter(function (obj) {
return obj === myName;
});
Snippet
var text = ["Heather", "kfdjsalfjdai", "fdjafhjdksafh", "Heather", "Heather", "fjdiafjdoisfhoids"];
var myName = "Heather";
var hits = text.filter(function (obj) {
return obj === myName;
});
console.log(hits);
A: Obligatory use this library answer. Here I use lodash:
var text = ["Heather", "kfdjsalfjdai", "fdjafhjdksafh", "Heather", "Heather", "something"],
myName = "Heather";
var hits = _.filter(text, _.matches([myName]);
Explanation on what's happening because this isn't intuitive at all. _.filter does the same thing as Array.prototype.filter except it's faster. You can run your own tests below to get an idea:
https://jsperf.com/array-filter-vs-lodash-filter-without-bias/2
The explanation I've heard is that traditional array operations implemented by lodash (map, reduce, filter, etc.) don't have to follow the implementation as detailed by the spec.
Anyways, _.filter takes two arguments: a collection (array or object) and function which returns true or false. If true, it'll return the item.
_.matches is a convenience function which returns a function that takes an argument and matches against the contents of the provided collection.
You could write the above another way:
var hits = _.filter(text, function(str) {
return str === myName
});
In lodash, we create functions all the time that basically executes an equality check. _.matches is just a convenience function to create equality check function.
A: Check against myName variable.
var text = ["Heather", "kfdjsalfjdai", "fdjafhjdksafh", "Heather", "Heather",
"fsomething"];
var myName = "Heather";
var hits = [];
for(var i = 0; i < text.length; i++) {
if (text[i] === myName) {
hits.push(text[i]);
}
}
console.log(hits);
Here is a working sample
A: text[i] will never === myName[i], because text is an array of strings, whereas myName is just one string. So for example, text[1] === "Heather", whereas myName[1] === "H". Any index of myName will just return one character.
| |
doc_23531666
|
However, for the following query the root node is not an SqlSelect, but an SqlOrderBy:
select EventID, Subject
from WorkOrder
where OwnerID = 100 and Active = 1 and Type = 2
order by Subject
If we use "group by" instead of "order by" then the root is an SqlSelect as expected.
Is this the intended behaviour?
A: Yes, this is intended. ORDER BY is not really a clause of SELECT. Consider
SELECT deptno FROM Emp
UNION
SELECT deptno FROM Dept
ORDER BY 1
The ORDER BY clause applies to the whole UNION, not to the second SELECT. Therefore we made it a standalone node.
When you ask Calcite to parse a query, the top-level nodes returned can be a SqlSelect (SELECT), SqlOrderBy (ORDER BY), SqlBasicCall (UNION, INTERSECT, EXCEPT or VALUES) or SqlWith (WITH).
| |
doc_23531667
|
$ cat person.py
class Person:
def __init__(self):
self.age = 22
def __str__(self):
return "my age is {}".format(self.age)
When I try to print it, everything goes fine, but writing Person to file fails:
>>> from person import Person
>>> dan = Person()
>>> print(dan)
my age is 22
>>> fl = open("dan.txt","wt")
>>> fl.write(dan)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: write() argument must be str, not Person
A: That's simply not how the API is designed.
From the definition of object.__str__(self):
Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object.
Beyond those explicitly listed instances, there's no reason to expect that implicit conversion will occur.
And from the definition of io.TextIOBase.write(s):
Write the string s to the stream and return the number of characters written.
So it's explicitly expecting a string, which is confirmed by the error message.
The simplest solution is to perform the conversion by using the str() function before passing it write() as an argument:
fl.write(str(dan))
A:
When I try to print it, everything goes fine, but writing Person to file fails
Why not use print then?
print(dan, file=fl)
That will behave exactly like the print you are expecting (including a trailing newline), but write to a file instead of stdout.
| |
doc_23531668
|
{
field1 => value1
field2 => value2
}
{
field1 => value1
field2 => value2
}
...
This makes millions of logs and gets quite expensive for log ingestors such as aws cloudwatch log insights.
I cannot see an option to turn this off, the log levels for this plugin seems to be set to INFO already. How can we prevent these logs from happening?
A: Looks like I had another config file in the same folder and its output plugin was running for this input, which was simply stdout. I had thought every config file would be isolated in terms of input output but looks like they are all combined. Removing that file fixed the issue.
| |
doc_23531669
|
here is my array:
Array
(
[0] => Array
(
[day] => 2013-04-06
[hour] => 06
[hits] => 4
[executetime] => 10.0000
)
)
I am then dividing them like this:
//### EDIT ###//
$thisHour = date("H", time());
$thisDate = date("Y-m-d", time());
$total_time = 2.5000;
$moveStats = $memcache->get('moveStats');
foreach ($moveStats as $k => $v) {
$moveStats[$k]['hits']=$moveStats[$k]['hits']+1; // UPDATING THE HITS
$moveStats[$k]['executetime'] += $total_time;
$moveStats[$k]['executetime'] = number_format($moveStats[$k]['executetime'] / (++$moveStats[$k]['hits']),4,'.','');
}
$memcache->set('moveStats', $moveStats);
This strangly enough gives me this number: 1.75!
I guess it should be 2.5?
What am I doing wrong. please help and thanks in advance :-)
A: try this
$moveStats[$k]['executetime']=$moveStats[$k]['executetime']+$total_time;
instand of
$moveStats[$k]['executetime']+$total_time;
A: This line has no assignment:
$moveStats[$k]['executetime']+$total_time;
Also, what value does $total_time contain?
A: You can change your code to:
$total_time = 2.5000;
foreach ($moveStats as $k => $v) {
$moveStats[$k]['executetime'] += $total_time;
echo $moveStats[$k]['executetime'] / (++$moveStats[$k]['hits']);
}
| |
doc_23531670
|
A: The easiest thing to do at this point is to go with a Flash based solution. zeroclipboard is a common one (a nice walkthrough is available here).
Browser vendors have over the past few years removed programatic access to the clipboard. Safari / Chrome lost the ability after a change in WebKit, and FireFox for a long time has blocked it. Only IE remains as one that does allow it, however it displays an alert on each page initially.
A: Try this
function myFunc() {
/* Get the text field */
let copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
input {
display: inline-block;
padding: .60rem;
font-size: 1rem;
color: #495057;
background-color: #f1f1f1;
border: 1px solid #ced4da;
border-radius: .25rem;
}
button {
display: inline-block;
font-weight: 400;
color: #ffffff;
cursor: pointer;
text-align: center;
user-select: none;
background-color: #007bff;
border: 1px solid transparent;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
border-radius: .25rem;
outline: 0;
}
<!-- The text field -->
<input type="text" id="myInput" value="Some Random Text">
<!-- The button used to copy the text -->
<button type="button" onclick="myFunc()">Copy</button>
| |
doc_23531671
|
For some reason it appears a the top.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FF0c46a6"
android:orientation="vertical" android:gravity="center_horizontal">
<TextView
android:id="@+id/skypename"
android:layout_width="0dip"
android:layout_height="0dip"
android:layout_weight="1"
android:textColor="#FFFFFF" android:textSize="12pt"/>
</LinearLayout>
<ListView android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false" />
</LinearLayout>
A: You are using LinearLayout with orientation vertical and you have defined TextView before ListView. So first TextView will be drawn after that ListView.
Use RelativeLayout instead and use android:layout_alignParentBottom="true" for TextView to align at the bottom of the parent and android:layout_above="@+id/linearLayout1" for list view to keep the listview to the top of textview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FF0c46a6"
android:orientation="vertical" android:gravity="center_horizontal"
android:layout_alignParentBottom="true">
<TextView
android:id="@+id/skypename"
android:layout_width="0dip"
android:layout_height="0dip"
android:layout_weight="1"
android:textColor="#FFFFFF" android:textSize="12pt"/>
</LinearLayout>
<ListView android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false" android:layout_above="@+id/linearLayout1"/>
</RelativeLayout>
A: Here you can do like this..
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FF0c46a6"
android:orientation="vertical" android:gravity="center_horizontal">
<TextView
android:id="@+id/skypename"
android:layout_width="0dip"
android:layout_height="0dip"
android:layout_weight="1"
android:textColor="#FFFFFF" android:textSize="12pt"/>
</LinearLayout>
<ListView android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
android:layout_above="@+id/bottom" />
<TextView
android:id="@+id/bottom"
android:layout_alignParentBottom="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:textSize="12pt"/>
</RelativeLayout>
A: I re-arranged my LinearLayout to a RelativeLayout but it wasn't as easy as I thought. In my case I had TextViews both above and below the ListView.
In order for the ListView to NOT cover either of the TextViews I had to use "layout_below" and "layout_above" in the layout that contains the ListView. Like this for the list-views layout:
android:layout_below="@+id/top_layout"
android:layout_above="@+id/bottom_layout"
When I wrote this from the bottom TextView:
android:layout_below="@+id/listview_layout"
the list covered it (=doesn't work).
So, the trick seems to be the placement of the layout_below and layout_above tags.
Another solution (that doesn't require a RelativeLayout) is to add a footer view to your list. Like this:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.main_layout, container, false);
myItemAdapter = new ItemAdapter(this, com.example.app.R.layout.listitem, theList);
View footer = inflater.inflate(R.layout.notify_row, null);
mListView.addFooterView(footer);
mListView.setAdapter(myItemAdapter);
return v;
}
For this solution you will have to create a layout file for your bottom view. Also you have to call addFooterView before you call setAdapter.
A: If you provide properties as fillparent for height and width then you will never see the textview below listview.
You can do one thing: supply height as fixed dp and then place your textview below list.
| |
doc_23531672
|
cmake_minimum_required(VERSION 3.13.4)
project(lifter)
find_package(LLVM REQUIRED CONFIG)
message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}")
message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}")
# Set your project compile flags.
# E.g. if using the C++ header files
# you will need to enable C++11 support
# for your compiler.
include_directories(${LLVM_INCLUDE_DIRS})
add_definitions(${LLVM_DEFINITIONS})
# Now build our tools
add_executable(lifter main.cpp BB.cpp Func.cpp Register.cpp Immediate.cpp Instr.cpp Utilities.cpp OpCode.cpp)
# Find the libraries that correspond to the LLVM components
# that we wish to use
llvm_map_components_to_libnames(llvm_libs support core irreader)
# Link against LLVM libraries
target_link_libraries(lifter ${llvm_libs})
I have also included the llvm header files that I want to use in my project
#include "llvm/IR/Value.h"
#include <llvm/Pass.h>
#include <llvm/ADT/SmallVector.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/MathExtras.h>
#include <llvm/IR/IRBuilder.h>
#include <algorithm>
#include "llvm/IR/PassManager.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
when I use this command inside the directory of my project:
cmake -H. -Bbuild
I get this output:
- Found LLVM 13.0.0
-- Using LLVMConfig.cmake in: /usr/lib/llvm-13/cmake
-- Configuring done
-- Generating done
-- Build files have been written to: /home/hany/lifter_master_thesis_final/build
then when I use the next command:
cmake --build build -- -j3
I get this output:
[ 33%] Building CXX object CMakeFiles/lifter.dir/Func.cpp.o
[ 33%] Building CXX object CMakeFiles/lifter.dir/main.cpp.o
[ 33%] Building CXX object CMakeFiles/lifter.dir/BB.cpp.o
In file included from /home/hany/lifter_master_thesis_final/Func.h:2,
from /home/hany/lifter_master_thesis_final/Utilities.h:14,
from /home/hany/lifter_master_thesis_final/main.cpp:1:
/home/hany/lifter_master_thesis_final/Register.h:13:2: error: ‘Value’ does not name a type
13 | Value* register_value;
| ^~~~~
/home/hany/lifter_master_thesis_final/Register.h:17:33: error: ‘Value’ has not been declared
17 | Register(std::string reg_name, Value* reg_value);
| ^~~~~
/home/hany/lifter_master_thesis_final/Register.h:23:2: error: ‘Value’ does not name a type
23 | Value* get_register_value();
| ^~~~~
/home/hany/lifter_master_thesis_final/Register.h:29:20: error: ‘Value’ has not been declared
29 | void insert_value(Value* value);
| ^~~~~
In file included from /home/hany/lifter_master_thesis_final/Func.h:2,
from /home/hany/lifter_master_thesis_final/Utilities.h:14,
from /home/hany/lifter_master_thesis_final/Func.cpp:1:
/home/hany/lifter_master_thesis_final/Register.h:13:2: error: ‘Value’ does not name a type
13 | Value* register_value;
| ^~~~~
/home/hany/lifter_master_thesis_final/Register.h:17:33: error: ‘Value’ has not been declared
17 | Register(std::string reg_name, Value* reg_value);
| ^~~~~
In file included from /home/hany/lifter_master_thesis_final/Func.h:3,
from /home/hany/lifter_master_thesis_final/Utilities.h:14,
from /home/hany/lifter_master_thesis_final/main.cpp:1:
/home/hany/lifter_master_thesis_final/Immediate.h:12:2: error: ‘Value’ does not name a type
12 | Value* immediate_value;
| ^~~~~
/home/hany/lifter_master_thesis_final/Register.h:23:2: error: ‘Value’ does not name a type
23 | Value* get_register_value();
| ^~~~~
/home/hany/lifter_master_thesis_final/Register.h:29:20: error: ‘Value’ has not been declared
29 | void insert_value(Value* value);
| ^~~~~
/home/hany/lifter_master_thesis_final/Immediate.h:24:2: error: ‘Value’ does not name a type
24 | Value* get_immediate_value_long();
| ^~~~~
In file included from /home/hany/lifter_master_thesis_final/Func.h:3,
from /home/hany/lifter_master_thesis_final/Utilities.h:14,
from /home/hany/lifter_master_thesis_final/Func.cpp:1:
/home/hany/lifter_master_thesis_final/Immediate.h:12:2: error: ‘Value’ does not name a type
12 | Value* immediate_value;
| ^~~~~
/home/hany/lifter_master_thesis_final/Immediate.h:24:2: error: ‘Value’ does not name a type
24 | Value* get_immediate_value_long();
| ^~~~~
In file included from /home/hany/lifter_master_thesis_final/Func.h:2,
from /home/hany/lifter_master_thesis_final/Utilities.h:14,
from /home/hany/lifter_master_thesis_final/BB.cpp:1:
/home/hany/lifter_master_thesis_final/Register.h:13:2: error: ‘Value’ does not name a type
13 | Value* register_value;
| ^~~~~
/home/hany/lifter_master_thesis_final/Register.h:17:33: error: ‘Value’ has not been declared
17 | Register(std::string reg_name, Value* reg_value);
| ^~~~~
/home/hany/lifter_master_thesis_final/Register.h:23:2: error: ‘Value’ does not name a type
23 | Value* get_register_value();
| ^~~~~
/home/hany/lifter_master_thesis_final/Register.h:29:20: error: ‘Value’ has not been declared
29 | void insert_value(Value* value);
| ^~~~~
In file included from /home/hany/lifter_master_thesis_final/Func.h:3,
from /home/hany/lifter_master_thesis_final/Utilities.h:14,
from /home/hany/lifter_master_thesis_final/BB.cpp:1:
/home/hany/lifter_master_thesis_final/Immediate.h:12:2: error: ‘Value’ does not name a type
12 | Value* immediate_value;
| ^~~~~
/home/hany/lifter_master_thesis_final/Immediate.h:24:2: error: ‘Value’ does not name a type
24 | Value* get_immediate_value_long();
| ^~~~~
make[2]: *** [CMakeFiles/lifter.dir/build.make:63: CMakeFiles/lifter.dir/main.cpp.o] Error 1
make[2]: *** Waiting for unfinished jobs....
make[2]: *** [CMakeFiles/lifter.dir/build.make:89: CMakeFiles/lifter.dir/Func.cpp.o] Error 1
make[2]: *** [CMakeFiles/lifter.dir/build.make:76: CMakeFiles/lifter.dir/BB.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:79: CMakeFiles/lifter.dir/all] Error 2
make: *** [Makefile:84: all] Error 2
my question is how come llvm classes(llvm:Value or llvm::Instruction for example) arent recognized as I am building my project when I have already included the header files and included llvm in my CMakeLists.txt while in visual studio code I don't get any errors regarding those classes being undefined.
I am new to using llvm and using CMakeLists.txt to include external libraries in my project :).. what could I be doing wrong here, please.
| |
doc_23531673
|
$(document).ready(function () {
var categoryId = $('#<%=hdnCategoryId.ClientID %>').val();
var productName = $('#tags').val();
jQuery("#tblList").jqGrid({
url: 'ArenaProductList.aspx/GroupProductList',
mtype: 'POST',
datatype: 'json',
postData: {
sidx: '',
sord: '',
page: '',
rows: '',
categoryId: categoryId,
productName: productName
},
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (postData) {
var propertyName, propertyValue, dataToSend = {};
for (propertyName in postData) {
if (postData.hasOwnProperty(propertyName)) {
propertyValue = postData[propertyName];
if ($.isFunction(propertyValue)) {
dataToSend[propertyName] = propertyValue();
} else {
dataToSend[propertyName] = propertyValue;
}
}
}
return JSON.stringify(dataToSend);
},
jsonReader: {
root: "d.rows",
page: "d.page",
total: "d.total",
records: "d.records"
},
colNames: ['ArenaProductId', 'Açıklama', 'Ana Kategori', 'Alt Kategori', 'Marka', 'KDV', 'Stok', 'Bayi Fiyatı', 'Son Kullanıcı Fiyatı', 'Para Birimi', 'Yüzde'],
colModel: [
{ name: 'ArenaProductId', index: 'ArenaProductId', hidden: true },
{ name: 'Description1', index: 'Description1', width: 150 },
{ name: 'MainGroupCode', index: 'MainGroupCode', width: 150 },
{ name: 'SubGroupCode', index: 'SubGroupCode', hidden: true },
{ name: 'Brand', index: 'Brand', width: 220 },
{ name: 'Kdv', index: 'Kdv', width: 120 },
{ name: 'Stock', index: 'Stock', width: 100 },
{ name: 'DealerPrice', index: 'DealerPrice', width: 100 },
{ name: 'Price', index: 'Price', width: 100 },
{ name: 'Currency', index: 'Currency', width: 100 },
{ name: 'Rate', index: 'Rate', width: 100 }
],
pager: '#tblPager',
rowList: [10, 20, 30],
sortname: 'UserId',
sortorder: 'desc',
rowNum: 10,
loadtext: "Yukleniyor....",
shrinkToFit: false,
multiselect: false,
emptyrecords: "Kayit Bulunamadi",
autowidth: true,
shrinkToFit: true,
height: "400",
width: "740",
rownumbers: true,
//subGrid: true,
caption: 'Arena Ürünler'
});
jQuery("#tblList").jqGrid('navGrid', '#prod_pager',
{ edit: false, add: false, del: false, excel: false, search: false });
$('#ddlSubCategory').change(function () {
$('#tags').val('');
$('#<%=hdnCategoryId.ClientID %>').val($('#<%=ddlSubCategory.ClientID %>').val());
jQuery("#tblList").trigger('reloadGrid');
});
$('#ddlMainCategory').change(function () {
$('#tags').val('');
$('#<%=hdnCategoryId.ClientID %>').val($('#<%=ddlMainCategory.ClientID %>').val());
jQuery("#tblList").trigger('reloadGrid');
});
});
And I have a submit button. I want to reload grid with different productName value after I click the button. Do you have any suggestion?
A: If you don't want to send sidx, sord, page and rows to the server you should use
prmNames: { page: null, rows: null, sort: null, order: null }
parameter of jqGrid instead of usage
postData: { sidx: '', sord: '', page: '', rows: '' }
To send categoryId and productName parameter always as the actual values of $('#<%=hdnCategoryId.ClientID %>') and $('#tags').val() you can defines categoryId and productName properties of postData as methods:
postData: {
categoryId: function() { return $('#<%=hdnCategoryId.ClientID %>').val(); },
productName: function() { return $('#tags').val(); }
}
See the answer for details. You use already the code of serializeGridData which I suggested in the answer. So the serialization of data will work correctly.
| |
doc_23531674
|
SELECT Count([hrpersnl Without Matching T_Employees].EmpNo) AS [Count]
FROM [hrpersnl Without Matching T_Employees];
The Without Matching clause seems to me to be rather MS-Access specific syntax that differs from ANSI-SQL as a whole, it appears to me to be finding records that have no matches on the EmpNo field of both tables, but the T_Employees table does not have a EmpNo field, so I am probably wrong in my assumption about this.
What does it actually do, and where is the documentation for it?
A: In an Access query, table/query and field names that
*
*contain spaces and "funny characters", or
*are Access reserved words
must be enclosed in [square brackets]. In this case, [hrpersnl Without Matching T_Employees] was a table or query name, not an expression involving the base tables hrpersnl and T-Employees.
| |
doc_23531675
|
I basically want the FCadultseats box to be available only when the movie is in the big cinema (at 9pm).
Thanks a lot for any and all help. I've been trying for ages and dont know why this wont work.
Here's my code:
<form id = "booking" method = "POST" action = "testserver">
Day:
<select id = "dayselector" name = "day">
<option disabled selected> -- Select a Day -- </option>
<option value= "Monday">Monday </option>
<option value = "Tuesday">Tuesday</option>
<option value = "Wednesday">Wednesday</option>
<option value = "Thursday">Thursday</option>
<option value = "Friday">Friday</option>
<option value = "Saturday">Saturday</option>
<option value = "Sunday">Sunday</option>
</select>
<br>
Time and Cinema:
<select id ="timeselector" name ="time">
<option disabled selected> -- Select a Time -- </option>
</select>
First Class Adults: <select id ="FCadultseats">
<option disabled selected> -- Not Available -- </option>
</select>
</form>
$(document).ready(function(){
$("#dayselector").change(function(){
var sel_day = $('option:selected').val();
if (sel_day == "Saturday" || sel_day == "Sunday"){
$("select#timeselector").html('<option disabled selected> -- Select a Time -- </option><option value ="9">9pm - Large Cinema</option><option value ="4">4pm - Small Cinema</option>');
} else {
$("select#timeselector").html('<option disabled selected> -- Select a Time -- </option><option value ="9">9pm - Large Cinema</option>');
}
});
$("#timeselector").change(function(){
var sel_time = $('option:selected').val();
if (sel_time == 9){
$("#FCadultseats").html('<option value ="0">0</option><option value ="1"></option><option value ="2">2</option><option value ="3">3</option><option value ="4">4</option><option value ="5">5</option><option value ="6">6</option><option value ="7">7</option><option value ="8">8</option><option value ="9">9</option><option value ="10">10</option><option value ="11">11</option><option value ="12">12</option>');
}
});
});
A: Try changing
var sel_day = $('option:selected').val();
to
var sel_day = this.value;
and do that in both places.
$('option:selected') selects ALL the selected options on the page, for every select.
| |
doc_23531676
|
<video src="FILE_LOCATION" width="320" height="240" type='video/ogg; codecs="theora, vorbis"' controls></video>
where FILE_LOCATION would be a content type of plone. I can use either 3 ways to acces the file:
1) file.download_url #gives me: http://localhost:8000/a/acervo/testeflv2/at_download/file
2) file.absolute_url #gives me: http://localhost:8000/a/acervo/testeflv2
3) file.getFile() #gives me the file (like if I open the video file on a text editor)
obs: If I click the link returned from the first or the second choice on a browser, it opens the download window from the browser to download the file.
On the zpt, I can do something like this:
<video src="" id="video_play" width="320" height="240" type='video/ogg; codecs="theora, vorbis"' controls
tal:attributes="src python:file.absolute_url()"></video>
where "python: file.absolut_url()" can be changed to that other options.
But any of that options are working. The page shows me a block where the video should be played, but no video is played.
How can I make this work?
A: You will probably need the download link - you want pure data, not a Plone default view.
i.e.
<video src="" id="video_play" width="320" height="240" type='video/ogg; codecs="theora, vorbis"' controls tal:attributes="src file/download_url"></video>
If that doesn't work:
*
*Does your browser support .ogg? (Try with both firefox and chrome)
*is it really ogg?
*what happens if you open the download url directly? Does the browser play anything?
*what does src point to after rendering the template (view-source or inspect element). Does the url look correct?
A: The main problem come from the 'Content-Disposition' header. Here an example with hardcoded ogg/theora format.
Create a script 'inline_download' in your cutom skin with this code inside:
RESPONSE = container.REQUEST.RESPONSE
filename = context.getFilename()
obj = context.getFile()
RESPONSE.setHeader('Content-Disposition', 'inline;filename="%s"' % filename)
RESPONSE.setHeader('Content-Type', 'video/ogg')
return obj
Now http://yourpath/video/inline_download should displayed correctly the video without extra html.
Finally add this code in your view:
<video height="240px" width="320px" type="video/ogg; codecs='theora, vorbis'"
controls="controls" preloas="none"
tal:attributes="src string:${here/absolute_url}/inline_download"/>
| |
doc_23531677
|
However, when I try to get the value in C# 4.0, the value of the parameter is null. Here is my C# code:
using (ConnectionManager<SqlConnection> cn = ConnectionManager<SqlConnection>.GetManager(CultureInfo.CurrentCulture.Name))
{
using (SqlCommand cm = cn.Connection.CreateCommand())
{
cm.CommandText = "Name of proc here";
cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("@ApplicationId", ApplicationId);
cm.Parameters.AddWithValue("@Index", Index);
if (PageSize > 0)
cm.Parameters.AddWithValue("@PageSize", PageSize);
cm.Parameters.Add("@ReturnValue", SqlDbType.Int);
cm.Parameters["@ReturnValue"].Direction = ParameterDirection.ReturnValue;
using (IDataReader dr = cm.ExecuteReader())
{
SafeDataReader sdr = new SafeDataReader(dr);
while (sdr.Read())
{
UserApplicationEntity uae = new UserApplicationEntity();
uae.UserId = sdr.GetGuid("UserId");
uae.ExternalId = sdr.GetString("ExternalId");
Result.Value.Collection.Add(uae);
}
Result.Value.TotalResults = (int)cm.Parameters["@ReturnValue"].Value;
}
}
}
The last line where I call Result.Value.TotalResults = (int)cm.Parameters["@ReturnValue"].Value; is where Value is null. Every tutorial or post I've found, I appear to be doing everything correctly. At this point I think I'm just missing something small and need another set of eyes. I've also tried setting the return parameter before all the others as one post I found on MS site said I needed to, but regardless of where it's at, it returns null.
A: The return value is sent last in the response from the database, so you have to read the result set completely before you can access the return value.
What does the SafeDataReader class do? Is it possible that it prevents the entire result set from being read?
Try to move the code that reads the return value outside the using block for the data reader. That may help to advance the response beyond the result set so that the return value is available.
| |
doc_23531678
|
I wrote a small JavaScript function that I can use to set the white portion of each .png to whatever the header background colour is so that the images blend in with the header and all you see is the transparent cut-away area change on mouse events - it's quite a nice effect.
So the white portion (not the transparent part) of the image should be changed to whatever the header background colour is, and the function works really great on Firefox, but for some reason doesn't work so well on Explorer (11).
Is there something I'm not seeing here? Here's the code that does the image editing - all I need to do is pass the id of the image and the hexadecimal colour string:
function setImageBg(
imageID,
imageColor
) {
var img = document.getElementById(imageID);
var canvas = document.createElement('canvas');
// Get the red, green and blue values from the hex color
// string.
var redMix = parseInt(imageColor.substr(1, 2), 16);
var greenMix = parseInt(imageColor.substr(2, 2), 16);
var blueMix = parseInt(imageColor.substr(5, 2), 16);
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
// Get the image data...
var pixelData = canvas.getContext('2d').getImageData(0, 0, img.width, img.height);
var imgData = pixelData.data;
var ctx = canvas.getContext('2d');
var imgDataURL;
// Edit the image data.
for (imagePos = 0; imagePos < ((img.width * img.height) * 4); imagePos += 4) {
if (pixelData.data[(imagePos + 3)] <= 99)
continue;
imgData[imagePos] = redMix;
imgData[(imagePos + 1)] = greenMix;
imgData[(imagePos + 2)] = blueMix;
}
ctx.putImageData(pixelData, 0, 0);
imgDataURL = canvas.toDataURL();
document.getElementById(imageID).src = imgDataURL;
}
Like I say, it's great on Firefox - on Explorer all I see is the div, which still dutifully changes colour on mouse events. It's as though the entire image has been made transparent.
Any help would be greatly appreciate, much obliged.
UPDATE:
Ok, so I thought I'd cracked this...here's what happened.
The problem was that the image was loading and being edited in both IE and FF, when I noticed the image had loaded and rendered in IE I thought I'd found and fixed the bug...but after a refresh the image again disappeared.
I scratched my head over it for a bit then decided I'd wasted enough time on it and brushed it aside. Now everything else is in place and working, so I'm back to this and it's a proper head scratcher.
So - IE DOES actually load and edit/render the image, when you initially open the page that is. If you refresh the page, the image disappears...or does it?
I made some adjustments to the code, using alert()'s to try and diagnose the problem, I decided what I do was add some code to check the source file - instead of diving in and changing the pixel colours - I decided to check the image before it is being edited.
Seems that, on the second run of my function - the image loaded is completely black and completely transparent. All pixels have a value of 0!
What does this mean? There's definitely something there, but not what should be.
Is htis a cacheing issue? I messed about with it for a bit, it's odd that IE will load and display the image initially but will neglect to do so after a refresh, but Ff is fine. I tried a few tricks to disable cacheing but nothing works...so now I'm thinking, perhaps it's something else.
Any ideas would be greatly appreciated, I mean it's not a deal-breaker. Everything is fine without this single feature but it's a shame if I can't get it to work.
For anyone interested, here's the updated function after various changes/edits:
function setImageBg(
imageSource,
imageSrc,
imageDst,
imageColor
) {
var img = document.getElementById(imageSrc);
var canvas = document.createElement('canvas');
var redMix = parseInt(imageColor.substr(1, 2), 16);
var greenMix = parseInt(imageColor.substr(3, 2), 16);
var blueMix = parseInt(imageColor.substr(5, 2), 16);
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
var pixelData = canvas.getContext('2d').getImageData(0, 0, img.width, img.height);
var imgData = pixelData.data;
var ctx = canvas.getContext('2d');
var imgDataURL;
// Here's a change I made - on the first call of this function
// when the page loads, all is good - on the second call after a
// refresh this always returns on IE - it's as though the loaded
// image (from file) is completely black and transparent
// (everything is 0)...problem is the image file is never actually
// altered - the loaded image is altered but the actual file never
// changed - very odd...
//
if (pixelData.data[0] == redMix) {
if (pixelData.data[1] == greenMix) {
if (pixelData.data[2] == blueMix) {
document.getElementById(imageDst).src = document.getElementById(imageSrc).src;
return;
}
}
}
for (imagePos = 0; imagePos < ((img.width * img.height) * 4); imagePos += 4) {
if (pixelData.data[(imagePos + 3)] <= 99)
continue;
pixelData.data[imagePos] = redMix;
pixelData.data[(imagePos + 1)] = greenMix;
pixelData.data[(imagePos + 2)] = blueMix;
}
ctx.putImageData(pixelData, 0, 0);
document.getElementById(imageDst).src = canvas.toDataURL();
return true;
}
| |
doc_23531679
|
A House class has a field of type Parent which can refer to a Child object. I need to map it to XML using Eclipse Moxy.
Its xsd would be something like:
<xs:complexType name="Parent" abstract="true">
...other fields...
<xs:complexType name="Child" >
<xs:extension base="Parent">
...other fields...
<xs:element name="child" type="Child" substitutionGroup="parent" />
<xs:element name="parent" type="Parent" abstract="true" />
<xs:complexType name="House">
<xs:element ref="parent"/>
House class contains a JAXBElement to point to Parent:
@XmlElementRef(name = "parent", namespace = "abc", type = JAXBElement.class)
protected JAXBElement<? extends Parent> parent;
How do I map House class through House.oxm.xml file so this polymorphic mapping works correctly?
<java-type name="House" xml-accessor-type="NONE">
<java-attributes>
<xml-element-ref java-attribute="?????????"/>
I tried using '@' in the mapping but it doesn't work - it just adds the reference String (@Parent) of the object to XML.
A: The whole issue was because of:
@XmlElementRef(name = "parent", namespace = "abc", type = JAXBElement.class)
protected JAXBElement<? extends Parent> parent;
After many futile attempts to fix it, I came across this defect: https://bugs.eclipse.org/bugs/show_bug.cgi?id=327811
After referring to its code, I saw that it addressed a situation very similar to mine, but used just @XmlElementRef annotation on the supertype, without using anything else like JAXBElement or supplying any other parameters to @XmlElementRef.
I tried that (and removed its mapping from oxm file) and it worked like a charm! I hope this answer helps anybody else who is stuck with the same problem.
| |
doc_23531680
|
ExecutorService service = Executors.newFixedThreadPool(servicesMap.size());
for (Map.Entry entry : servicesMap.entrySet()) {
service.submit(new MyService(conn, serviceID));
// here serviceID is id1 id2 id3 these three job should execute parallel
}
Note : MyTask implements Callable & servicesMap will be 3 always
If i try to use ScheduledExecutorService then i cannot able to achieve it.
It says scheduleService.schedule not accepting Callable type parameterts
ScheduledExecutorService scheduleService = Executors.newScheduledThreadPool(servicesMap.size());
for (Map.Entry entry : servicesMap.entrySet()) {
scheduleService.schedule((new MyService(conn, serviceID)), 0, 60, TimeUnit.SECONDS);
}
Please help to modify ScheduledExecutorService code to achieve this.
A: Your schedule(…) call contains more arguments than the method has parameters.
I’m not sure what exactly you are after, though. If you would like to run your service in one minute in the future, then use the following call:
scheduleService.schedule(new MyService(conn, serviceID), 60, TimeUnit.SECONDS);
If, instead, you would like to run your service every minute (starting immediately), then use one of the following two calls:
scheduleService.scheduleAtFixedRate(new MyService(conn, serviceID), 0, 60, TimeUnit.SECONDS);
scheduleService.scheduleWithFixedDelay(new MyService(conn, serviceID), 0, 60, TimeUnit.SECONDS);
Regarding your followup question in the comments:
How to make, within a minute Service1 Service2 Service3 should run parallel, then next minute do the same.
ScheduledExecutorService scheduleService = …;
Collection<Callable<Void>> services = …;
Runnable svcRunner = new Runnable() {
@Override
public void run() {
Collection<Future<Void>> futures = new ArrayList<>(services.size());
// start all services in parallel
for (Callable<Void> service : services) {
// any ExecutorService would do here, i.e., doesn't have to be a
// ScheduledExecutorService
futures.add(scheduleService.submit(service));
}
// wait for all services to complete
for (Future<Void> future : futures) {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
// TODO do something meaningful
}
}
}
};
// run the scheduler every minute (i.e., one minute after the last service
// has finished), starting now
scheduleService.scheduleWithFixedDelay(svcRunner, 0, 60, TimeUnit.SECONDS);
For simplicity, I have stored the services in a collection. If required, you can also create them anew each time.
| |
doc_23531681
|
Thanks for your help.
A: Here is an example how you can instantiate an ocl query. There exist two environment factories for OCL, one for Ecore which is used in this example and another one for UML. Since UML is implemented with Ecore you can also use the Ecore factory if you want to evaluate UML Models.
private final OCL<?, EClassifier, ?, ?, ?, EParameter, ?, ?, ?, Constraint, EClass, EObject> ocl;
private final OCLHelper<EClassifier, ?, ?, Constraint> helper;
this.ocl = OCL.newInstance(EcoreEnvironmentFactory.INSTANCE);
this.helper = ocl.createOCLHelper();
After you have instantiated the OCL and OCLHelper objects its important to set the context object for the OCL query:
helper.setContext(UMLPackage.eINSTANCE.getClass_());
UMLPackage.eInstance has a couple of getters for Class_, Property, Operation and other UML Classes, there is a similar object for Ecore: EcorePackage.eINSTANCE. Next you need to create an OCLExpression and then from it the query.
OCLExpression<EClassifier> expression = helper.createQuery("self.attribute->size() > 0");
Query<EClassifier, EClass, EObject> query = ocl.createQuery(expression);
Now you can check the query on some element:
boolean success = query.check(myElement);
If the check method returns true, then your query is valid for the given model. In that code myElement would be an object of your ECore model with the type Class. The object that you pass to the check method must match the context type that you have set in the helper.
| |
doc_23531682
|
My immediate need though is for a project where we're using Python and what I need to do is get a script that will average all of the first place numbers in a large set of numbers. For example if the numbers were 101, 503, 695, 1002, 496 - I would need to average 1,3,5,2,6. Would someone be so kind as to show me how this can be done?
A: numbers = [101, 503, 695, 1002, 496]
new_numbers = [int(str(x)[-1]) for x in numbers]
print(new_numbers)
| |
doc_23531683
|
This is what I have so the html page pulls the js code.
<head>
<script src="nav.js" type="text/javascript"></script>
</head>
This is what I have for the navbar. I don't really want the whole navbar to change with scrolldown, just inner. The logo image needs to still be transparent.
<nav class="navbar" >
<img src="images/logo.png" class="logo">
<div id="inner" id="top">
<ul>
<li><a href="index.html" title="Home">HOME</a></li>
<li><a href="about.html" title="About">ABOUT</a></li>
<li><a href="contact.html" title="Contact">CONTACT</a></li>
</ul>
</div>
</nav>
Here is my css (if more is needed I can post).
#inner{
width:140px;
float:right;
margin-right:5px;
text-align:justify;
}
.navbar a {
font-size: 14px;
font-family:SinkinSansLight;
letter-spacing:5px;
line-height: 20px;
border:none;
padding: 2px ;
text-decoration: none;
margin-top: 10px;
}
Finally, my js, which has been simply copy-pasted from other topics on SO, and adjusted with the ID from my css.
function checkScroll(){
var startY = $('#inner').height() * 2; //The point where the navbar changes in px
if($(window).scrollTop() > startY){
$('#inner').addClass("scrolled");
}else{
$('#inner').removeClass("scrolled");
}
}
if($('#inner').length > 0){
$(window).on("scroll load resize", function(){
checkScroll();
});
}
Sorry there is so much, I just see a lot of people needed more code than supplied, and I have been trying a couple of options with js. Thanks for the help!
A: Edit: Found the problem. You're trying to use jQuery but haven't included it in the page. Put jQuery on your site.
I'm not really sure what you're asking because the jQuery code you posted works fine... It adds the class scrolled to #inner when the user scrolls.
Here is a snippet with your code. I added a transition to #inner and a background color to #inner.scrolled and set a height on the body so you can scroll and see it working.
function checkScroll() {
var startY = $('#inner').height() * 2; //The point where the navbar changes in px
if ($(window).scrollTop() > startY) {
$('#inner').addClass("scrolled");
} else {
$('#inner').removeClass("scrolled");
}
}
if ($('#inner').length > 0) {
$(window).on("scroll load resize", function() {
checkScroll();
});
}
body {
height: 1000px;
}
#inner {
width: 140px;
float: right;
margin-right: 5px;
text-align: justify;
position: fixed;
transition: background-color 1s;
}
#inner.scrolled {
background-color: rgba(255, 0, 0, 0.6);
}
.navbar a {
font-size: 14px;
font-family: SinkinSansLight;
letter-spacing: 5px;
line-height: 20px;
border: none;
padding: 2px;
text-decoration: none;
margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar">
<img src="images/logo.png" class="logo">
<div id="inner">
<ul>
<li><a href="index.html" title="Home">HOME</a>
</li>
<li><a href="about.html" title="About">ABOUT</a>
</li>
<li><a href="contact.html" title="Contact">CONTACT</a>
</li>
</ul>
</div>
</nav>
| |
doc_23531684
|
The camera is not using standard v4l/v4l, but we can stream video using GStreamer for its driver (mfw_v4l):
gst-launch mfw_v4lsrc ! autovideosink
I want to use the camera in OpenCV by calling it via GStreamer (GStreamer inside OpenCV).
I asked a question about calling GStreamer inside OpenCV here, and this is the follow up.
If I enable GStreamer support, it's checked in the source code, but OpenCV tries to use standard V4L/V4L2 for GStreamer which I want to change.
The section about calling GStreamer is in cap_gstreamer.cpp:
CvCapture* cvCreateCapture_GStreamer(int type, const char* filename )
{
CvCapture_GStreamer* capture = new CvCapture_GStreamer;
if( capture->open( type, filename ))
return capture;
delete capture;
return 0;
}
I guess this is the section I should work on to somehow point to the camera's driver. ("type" here probably is a number related to the driver(as defined in precomp.hpp), but what's the "filename"?)
Any suggestions about how to access the camera via GStreamer would be helpful and appreciated.
Thanks!
A: Looks like we can call the camera using a proper GStreamer pipeline like below:
VideoCapture cap("mfw_v4lsrc ! ffmpegcolorspace ! video/x-raw-rgb ! appsink")
as the camera output is in YUV, we need to convert that to RGB to pass the frames to OpenCV.
This is where OpenCV makes sure it gets RGB colorspace.
A: Just for reference, this works in OpenCV 3.0:
VideoCapture cap("souphttpsrc location=http://root:admin@192.168.5.123:80/mjpg/video.mjpg ! decodebin ! videoconvert ! appsink")
| |
doc_23531685
|
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# For Chrome
chrome_options = Options()
chrome_options.add_argument(
"--user-data-dir=C:/Users/ajith/AppData/Local/Google/Chrome/User Data")
chrome_options.add_argument('--profile-directory=Profile 1')
browser = webdriver.Chrome(
"C:/Users/ajith/OneDrive/Desktop/bot/chromedriver.exe", chrome_options=chrome_options)
# Bestbuy 3090 Page
browser.get(
"https://www.bestbuy.com/site/nvidia-geforce-rtx-3070-8gb-gddr6-pci-express-4-0-graphics-card-dark-platinum-and-black/6429442.p?skuId=6429442")` ` `
| |
doc_23531686
|
var Box = $(window.parent.document).find("#box"); // works fine
var BoxContent = $(Box+" .bg > .content").text(); // error
console.log(BoxContent);
Error message ("Uncaught Error: Syntax error, unrecognized expression: [object Object] .bg .content")
What is my fail?
A: Box isn't a string, you can't meaningfully concatenate it with a string to create a new selector.
It's a jQuery object, so you can use .find() to search within it.
var BoxContent = Box.find(".bg > .content").text();
A: try this one
var BoxContent = Box.find(".bg > .content").first().text();
// OR
var BoxContent = Box.find(".bg").first().find(".content").first().text();
| |
doc_23531687
|
console.log('Loading function');
exports.bullion = function(event, context) {
//console.log('Received event:', JSON.stringify(event, null, 2));
var message = event.Records[0].Sns.Message;
console.log('From SNS:', message);
context.succeed(message);
};
I zip it up so it looks like this:
bullion $ unzip -l target/bullion-dev-for-lambda.zip
Archive: target/bullion-dev-for-lambda.zip
Length Date Time Name
-------- ---- ---- ----
268 02-05-16 10:39 awslambda.js
-------- -------
268 1 file
I upload it to AWS Lambda and configure the Handler to be
awslambda.bullion
I test the function and I get
{
"errorMessage": "Handler 'bullion' missing on module 'awslambda'"
}
If I type the same code into a Lambda function it works! What's the special case with the zip file upload?
A: The most common mistake with this is that you zip the folder, then instead of this:
zip contains:
- awslambda.js
- otherFiles.js
You now get this:
zip contains:
- foldername/
- awslambda.js
- otherFiles.js
As in, the folder is in the zip (containing the code) instead of the contents of the folder. The folder itself should not be zipped, so that the awslambda.js file is in the root of the zip file.
To fix this: do not compress the folder (right-click -> compress), but open the folder, select all files and then right-click -> compress.
A: The answer seems to be that 'awslambda' is already a module in the Lambda environment. When I change the file from awslambda.js to bullionAwsLambda.js, and change the Handler accordingly, it works.
A sneaky one that lost me a lot of time!
| |
doc_23531688
|
In the REST interface it is returned as a header. I need the same functionality for iOS uploads. How is it returned in the iOS API?
A: Currently, it is not possible to retrieve versionId using AWSS3TransferUtility. You need to use AWSS3 and call - headObject: to retrieve it. We will explore the ways to expose the response object in the transfer utility for the future release.
| |
doc_23531689
|
messages.java
public class messages extends Activity {
TextView mTitle;
List<ConversationsList> conversationsList;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
String HTTP_JSON_URL = "http://xxx.xx/conversate.php";
String GET_JSON_FROM_SERVER_NAME = "my_name";
String GET_JSON_FROM_SERVER_NAME2 = "imageurl";
String GET_JSON_FROM_SERVER_NAME3 = "friend_uid";
String GET_JSON_FROM_SERVER_NAME4 = "friend_name";
String GET_JSON_FROM_SERVER_NAME5 = "time";
String GET_JSON_FROM_SERVER_NAME6 = "my_uid";
String GET_JSON_FROM_SERVER_NAME7 = "message";
JsonArrayRequest jsonArrayRequest ;
ScrollView scrollView;
Context context;
Intent intent;
RequestQueue requestQueue ;
int count = 1;
ArrayList<String> FriendNames;
ImageButton sendbutton;
EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
mTitle = findViewById(R.id.profiletitle);
edit = findViewById(R.id.message);
Typeface face = Typeface.createFromAsset(getAssets(),
"fonts/epimodem.ttf");
Typeface face2 = Typeface.createFromAsset(getAssets(),
"fonts/epimodem2.ttf");
edit.setTypeface(face);
mTitle.setTypeface(face2);
conversationsList = new ArrayList<>();
progressBar = findViewById(R.id.progressBarc);
recyclerView = findViewById(R.id.recyclerViewc);
progressBar.setVisibility(View.VISIBLE);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
// **********************************************************************
FriendNames = new ArrayList<>();
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
JSON_DATA_WEB_CALL();
conversationsList.clear();
}
});
}
} catch (InterruptedException e) {
}
}
};
if(!conversationsList.isEmpty()){
recyclerView.scrollToPosition(conversationsList.size() - 1);
}
t.start();
}
public void JSON_DATA_WEB_CALL() {
jsonArrayRequest = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(final JSONArray array){
try {
recyclerView.getRecycledViewPool().clear();
for (int i = 0; i < array.length(); i++) {
ConversationsList GetDataAdapter1 = new ConversationsList();
JSONObject json;
json = array.getJSONObject(i);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String my_uid = user.getUid();
intent = getIntent();
String check = json.getString(GET_JSON_FROM_SERVER_NAME3);
String check2 = json.getString(GET_JSON_FROM_SERVER_NAME6);
String friend_uid = intent.getExtras().getString("Uid");
if ((check.contains(friend_uid) && my_uid.contains(check2)) || (check.contains(my_uid) && check2.contains(friend_uid)) && !"".equals(json.getString(GET_JSON_FROM_SERVER_NAME7))) {
GetDataAdapter1.setmy_name(json.getString(GET_JSON_FROM_SERVER_NAME));
GetDataAdapter1.setfriend_name(json.getString(GET_JSON_FROM_SERVER_NAME4));
GetDataAdapter1.setmy_uid(json.getString(GET_JSON_FROM_SERVER_NAME6));
GetDataAdapter1.setfriend_uid(json.getString(GET_JSON_FROM_SERVER_NAME3));
GetDataAdapter1.setimageurl(json.getString(GET_JSON_FROM_SERVER_NAME2));
GetDataAdapter1.setmessage(json.getString(GET_JSON_FROM_SERVER_NAME7));
GetDataAdapter1.settime(json.getString(GET_JSON_FROM_SERVER_NAME5));
FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME));
FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME7));
FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME2));
FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME3));
FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME4));
FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME5));
FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME6));
conversationsList.add(GetDataAdapter1);
recyclerViewadapter = new ConversationsRecyclerAdapter(conversationsList, context);
recyclerView.setAdapter(recyclerViewadapter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void send_messages(View v)
{ Intent intent = getIntent();
String imageurl ="";
String friend_name=intent.getExtras().getString("Name");
String friend_uid =intent.getExtras().getString("Uid");
EditText et;
et = findViewById(R.id.message);
String message = et.getText().toString();
String time = DateFormat.getDateTimeInstance().format(new Date());
imageurl =intent.getExtras().getString("Imageurl");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
String my_name = user.getDisplayName();
if("".equals(my_name)){
String mEmail = user.getEmail();
int iend = mEmail.indexOf("@");
if(iend != -1)
{
my_name = mEmail.substring(0,iend);
}
}
String my_uid = user.getUid();
String method = "message";
backgroundtask bgtask = new backgroundtask(this);
bgtask.execute(method,my_name,my_uid,friend_name,friend_uid,imageurl,time,message);
recyclerView.scrollToPosition(conversationsList.size() - 1);
}
}
}
MessagesRecyclerAdapter.java
public class MessagesRecyclerAdapter extends RecyclerView.Adapter<MessagesRecyclerAdapter.ViewHolder1>{
Context context;
Context ctx;
List<MessagesList> MessagesList;
public MessagesRecyclerAdapter(List<MessagesList> getDataAdapter1, Context context){
super();
this.MessagesList = getDataAdapter1;
this.context = context;
}
@Override
public ViewHolder1 onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_messages, parent, false);
return new ViewHolder1(view);
}
@Override
public void onBindViewHolder(final ViewHolder1 holder, int position) {
ImageView ImageUrl1 = holder.ImageUrl;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
MessagesList getDataAdapter1 = MessagesList.get(position);
final String Name = getDataAdapter1.getFriend_name();
final String Uid = getDataAdapter1.getfrienduid();
final String Imageurlserver = getDataAdapter1.getImageurl();
final String Imageurlserve = user.getPhotoUrl().toString();
holder.FriendName.setText(getDataAdapter1.getFriend_name());
if(!"".equals(Imageurlserver))
{Picasso.with(context).load(Imageurlserver).into(ImageUrl1);}
else{
ImageUrl1.setImageResource(R.drawable.profile);
}
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent;
intent = new Intent(context, messages.class);
intent.putExtra("Name", Name);
intent.putExtra("Uid",Uid);
intent.putExtra("Imageurl",Imageurlserve);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return MessagesList.size();
}
class ViewHolder1 extends RecyclerView.ViewHolder{
public TextView FriendName;
public ImageView ImageUrl;
public Button button;
public ViewHolder1(View itemView) {
super(itemView);
Typeface face = Typeface.createFromAsset(itemView.getContext().getAssets(),
"fonts/epimodem.ttf");
Typeface face2 = Typeface.createFromAsset(itemView.getContext().getAssets(),
"fonts/epimodem2.ttf");
FriendName = itemView.findViewById(R.id.MessageCard6); this.FriendName.setTypeface(face);
ImageUrl = itemView.findViewById(R.id.Messagepic);
button = itemView.findViewById(R.id.send_message);
}
}
}
A: clear conversationsList before the call JSON_DATA_WEB_CALL()
public void run() {
conversationsList.clear();
JSON_DATA_WEB_CALL();
}
A: Don't set new adapter everytime you refresh data. Create adapter once and then set conversationsList in this adapter and call notifyDataSetChanged
| |
doc_23531690
|
jsonSchema = StructType([ StructField("State", StringType(), True) \
, StructField("Value", StringType(), True) \
, StructField("SourceTimestamp", StringType(), True) \
, StructField("Tag", StringType(), True)
])
spark = SparkSession \
.builder \
.appName("StructuredStreaming") \
.config("spark.default.parallelism", "100") \
.getOrCreate()
df = spark \
.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", "10.129.140.23:9092") \
.option("subscribe", "SIMULATOR.SUPERMAN.TOTO") \
.load() \
.select(from_json(col("value").cast("string"), jsonSchema).alias("data")) \
.select("data.*")
df = df.withColumn("window",window(current_timestamp(),"4 seconds")).groupBy("window").agg(func.max("Value")).select("window")
query = df \
.writeStream \
.outputMode("update") \
.format("console") \
.start()
query.awaitTermination()
I get the following results in logs:
---------------------------------------------------------------------------
Py4JJavaError Traceback (most recent call last)
/usr/spark/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
62 try:
---> 63 return f(*a, **kw)
64 except py4j.protocol.Py4JJavaError as e:
/usr/spark/spark/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
327 "An error occurred while calling {0}{1}{2}.\n".
--> 328 format(target_id, ".", name), value)
329 else:
Py4JJavaError: An error occurred while calling o165.awaitTermination.
: org.apache.spark.sql.streaming.StreamingQueryException: Writing job aborted.
=== Streaming Query ===
Identifier: [id = b6a5b7f5-59c7-43ac-a6a0-8d27fb3fff6d, runId = ca394e5a-14b1-4ccb-9872-36cf7319ae75]
Current Committed Offsets: {}
Current Available Offsets: {KafkaV2[Subscribe[SIMULATOR.SUPERMAN.TOTO]]: {"SIMULATOR.SUPERMAN.TOTO":{"0":956487}}}
Current State: ACTIVE
Thread State: RUNNABLE
Logical Plan:
Project [window#118]
+- Aggregate [window#118], [window#118, max(Value#111) AS max(Value)#133]
+- Project [State#85, Value#111, SourceTimestamp#87, Tag#88, Source#105, window#119 AS window#118]
+- Filter isnotnull(current_timestamp())
+- Project [named_struct(start, precisetimestampconversion(((((CASE WHEN (cast(CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) as double) = (cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) THEN (CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) + cast(1 as bigint)) ELSE CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) END + cast(0 as bigint)) - cast(1 as bigint)) * 4000000) + 0), LongType, TimestampType), end, precisetimestampconversion((((((CASE WHEN (cast(CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) as double) = (cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) THEN (CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) + cast(1 as bigint)) ELSE CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) END + cast(0 as bigint)) - cast(1 as bigint)) * 4000000) + 0) + 4000000), LongType, TimestampType)) AS window#119, State#85, Value#111, SourceTimestamp#87, Tag#88, Source#105]
+- Project [State#85, cast(Value#86 as double) AS Value#111, SourceTimestamp#87, Tag#88, Source#105]
+- Project [State#85, Value#86, SourceTimestamp#87, Tag#88, cast(Source#99L as timestamp) AS Source#105]
+- Project [State#85, Value#86, SourceTimestamp#87, Tag#88, cast(Source#93 as bigint) AS Source#99L]
+- Project [State#85, Value#86, SourceTimestamp#87, Tag#88, substring(SourceTimestamp#87, 1, 10) AS Source#93]
+- Project [data#83.State AS State#85, data#83.Value AS Value#86, data#83.SourceTimestamp AS SourceTimestamp#87, data#83.Tag AS Tag#88]
+- Project [jsontostructs(StructField(State,StringType,true), StructField(Value,StringType,true), StructField(SourceTimestamp,StringType,true), StructField(Tag,StringType,true), cast(value#70 as string), Some(Etc/UTC)) AS data#83]
+- StreamingExecutionRelation KafkaV2[Subscribe[SIMULATOR.SUPERMAN.TOTO]], [key#69, value#70, topic#71, partition#72, offset#73L, timestamp#74, timestampType#75]
at org.apache.spark.sql.execution.streaming.StreamExecution.org$apache$spark$sql$execution$streaming$StreamExecution$$runStream(StreamExecution.scala:297)
at org.apache.spark.sql.execution.streaming.StreamExecution$$anon$1.run(StreamExecution.scala:193)
Caused by: org.apache.spark.SparkException: Writing job aborted.
at org.apache.spark.sql.execution.datasources.v2.WriteToDataSourceV2Exec.doExecute(WriteToDataSourceV2Exec.scala:92)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
at org.apache.spark.sql.execution.SparkPlan.getByteArrayRdd(SparkPlan.scala:247)
at org.apache.spark.sql.execution.SparkPlan.executeCollect(SparkPlan.scala:296)
at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collectFromPlan(Dataset.scala:3383)
at org.apache.spark.sql.Dataset$$anonfun$collect$1.apply(Dataset.scala:2782)
at org.apache.spark.sql.Dataset$$anonfun$collect$1.apply(Dataset.scala:2782)
at org.apache.spark.sql.Dataset$$anonfun$53.apply(Dataset.scala:3364)
at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1.apply(SQLExecution.scala:78)
at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
at org.apache.spark.sql.Dataset.withAction(Dataset.scala:3363)
at org.apache.spark.sql.Dataset.collect(Dataset.scala:2782)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$org$apache$spark$sql$execution$streaming$MicroBatchExecution$$runBatch$5$$anonfun$apply$17.apply(MicroBatchExecution.scala:540)
at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1.apply(SQLExecution.scala:78)
at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$org$apache$spark$sql$execution$streaming$MicroBatchExecution$$runBatch$5.apply(MicroBatchExecution.scala:535)
at org.apache.spark.sql.execution.streaming.ProgressReporter$class.reportTimeTaken(ProgressReporter.scala:351)
at org.apache.spark.sql.execution.streaming.StreamExecution.reportTimeTaken(StreamExecution.scala:58)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution.org$apache$spark$sql$execution$streaming$MicroBatchExecution$$runBatch(MicroBatchExecution.scala:534)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$runActivatedStream$1$$anonfun$apply$mcZ$sp$1.apply$mcV$sp(MicroBatchExecution.scala:198)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$runActivatedStream$1$$anonfun$apply$mcZ$sp$1.apply(MicroBatchExecution.scala:166)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$runActivatedStream$1$$anonfun$apply$mcZ$sp$1.apply(MicroBatchExecution.scala:166)
at org.apache.spark.sql.execution.streaming.ProgressReporter$class.reportTimeTaken(ProgressReporter.scala:351)
at org.apache.spark.sql.execution.streaming.StreamExecution.reportTimeTaken(StreamExecution.scala:58)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$runActivatedStream$1.apply$mcZ$sp(MicroBatchExecution.scala:166)
at org.apache.spark.sql.execution.streaming.ProcessingTimeExecutor.execute(TriggerExecutor.scala:56)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution.runActivatedStream(MicroBatchExecution.scala:160)
at org.apache.spark.sql.execution.streaming.StreamExecution.org$apache$spark$sql$execution$streaming$StreamExecution$$runStream(StreamExecution.scala:281)
... 1 more
Caused by: org.apache.spark.SparkException: Job aborted due to stage failure: Task 52 in stage 1.0 failed 1 times, most recent failure: Lost task 52.0 in stage 1.0 (TID 200, localhost, executor driver): java.lang.NoSuchMethodError: net.jpountz.lz4.LZ4BlockInputStream.<init>(Ljava/io/InputStream;Z)V
at org.apache.spark.io.LZ4CompressionCodec.compressedInputStream(CompressionCodec.scala:122)
at org.apache.spark.serializer.SerializerManager.wrapForCompression(SerializerManager.scala:163)
at org.apache.spark.serializer.SerializerManager.wrapStream(SerializerManager.scala:124)
at org.apache.spark.shuffle.BlockStoreShuffleReader$$anonfun$3.apply(BlockStoreShuffleReader.scala:50)
at org.apache.spark.shuffle.BlockStoreShuffleReader$$anonfun$3.apply(BlockStoreShuffleReader.scala:50)
at org.apache.spark.storage.ShuffleBlockFetcherIterator.next(ShuffleBlockFetcherIterator.scala:453)
at org.apache.spark.storage.ShuffleBlockFetcherIterator.next(ShuffleBlockFetcherIterator.scala:64)
at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:435)
at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:441)
at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)
at org.apache.spark.util.CompletionIterator.hasNext(CompletionIterator.scala:31)
at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)
at org.apache.spark.sql.execution.streaming.StateStoreRestoreExec$$anonfun$doExecute$1.apply(statefulOperators.scala:243)
at org.apache.spark.sql.execution.streaming.StateStoreRestoreExec$$anonfun$doExecute$1.apply(statefulOperators.scala:242)
at org.apache.spark.sql.execution.streaming.state.package$StateStoreOps$$anonfun$1.apply(package.scala:67)
at org.apache.spark.sql.execution.streaming.state.package$StateStoreOps$$anonfun$1.apply(package.scala:62)
at org.apache.spark.sql.execution.streaming.state.StateStoreRDD.compute(StateStoreRDD.scala:92)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.sql.execution.streaming.state.StateStoreRDD.compute(StateStoreRDD.scala:91)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:121)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:403)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:409)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Driver stacktrace:
at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1889)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1877)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1876)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1876)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
at scala.Option.foreach(Option.scala:257)
at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:926)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2110)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2059)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2048)
at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:737)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:2061)
at org.apache.spark.sql.execution.datasources.v2.WriteToDataSourceV2Exec.doExecute(WriteToDataSourceV2Exec.scala:64)
... 35 more
Caused by: java.lang.NoSuchMethodError: net.jpountz.lz4.LZ4BlockInputStream.<init>(Ljava/io/InputStream;Z)V
at org.apache.spark.io.LZ4CompressionCodec.compressedInputStream(CompressionCodec.scala:122)
at org.apache.spark.serializer.SerializerManager.wrapForCompression(SerializerManager.scala:163)
at org.apache.spark.serializer.SerializerManager.wrapStream(SerializerManager.scala:124)
at org.apache.spark.shuffle.BlockStoreShuffleReader$$anonfun$3.apply(BlockStoreShuffleReader.scala:50)
at org.apache.spark.shuffle.BlockStoreShuffleReader$$anonfun$3.apply(BlockStoreShuffleReader.scala:50)
at org.apache.spark.storage.ShuffleBlockFetcherIterator.next(ShuffleBlockFetcherIterator.scala:453)
at org.apache.spark.storage.ShuffleBlockFetcherIterator.next(ShuffleBlockFetcherIterator.scala:64)
at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:435)
at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:441)
at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)
at org.apache.spark.util.CompletionIterator.hasNext(CompletionIterator.scala:31)
at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)
at org.apache.spark.sql.execution.streaming.StateStoreRestoreExec$$anonfun$doExecute$1.apply(statefulOperators.scala:243)
at org.apache.spark.sql.execution.streaming.StateStoreRestoreExec$$anonfun$doExecute$1.apply(statefulOperators.scala:242)
at org.apache.spark.sql.execution.streaming.state.package$StateStoreOps$$anonfun$1.apply(package.scala:67)
at org.apache.spark.sql.execution.streaming.state.package$StateStoreOps$$anonfun$1.apply(package.scala:62)
at org.apache.spark.sql.execution.streaming.state.StateStoreRDD.compute(StateStoreRDD.scala:92)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.sql.execution.streaming.state.StateStoreRDD.compute(StateStoreRDD.scala:91)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:121)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:403)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:409)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
During handling of the above exception, another exception occurred:
StreamingQueryException Traceback (most recent call last)
<ipython-input-15-382e5f46aca0> in <module>()
2 query = df .writeStream .outputMode("update") .format("console") .start()
3
----> 4 query.awaitTermination()
/usr/spark/spark/python/pyspark/sql/streaming.py in awaitTermination(self, timeout)
101 return self._jsq.awaitTermination(int(timeout * 1000))
102 else:
--> 103 return self._jsq.awaitTermination()
104
105 @property
/usr/spark/spark/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py in __call__(self, *args)
1255 answer = self.gateway_client.send_command(command)
1256 return_value = get_return_value(
-> 1257 answer, self.gateway_client, self.target_id, self.name)
1258
1259 for temp_arg in temp_args:
/usr/spark/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
73 raise ParseException(s.split(': ', 1)[1], stackTrace)
74 if s.startswith('org.apache.spark.sql.streaming.StreamingQueryException: '):
---> 75 raise StreamingQueryException(s.split(': ', 1)[1], stackTrace)
76 if s.startswith('org.apache.spark.sql.execution.QueryExecutionException: '):
77 raise QueryExecutionException(s.split(': ', 1)[1], stackTrace)
StreamingQueryException: 'Writing job aborted.\n=== Streaming Query ===\nIdentifier: [id = b6a5b7f5-59c7-43ac-a6a0-8d27fb3fff6d, runId = ca394e5a-14b1-4ccb-9872-36cf7319ae75]\nCurrent Committed Offsets: {}\nCurrent Available Offsets: {KafkaV2[Subscribe[SIMULATOR.SUPERMAN.TOTO]]: {"SIMULATOR.SUPERMAN.TOTO":{"0":956487}}}\n\nCurrent State: ACTIVE\nThread State: RUNNABLE\n\nLogical Plan:\nProject [window#118]\n+- Aggregate [window#118], [window#118, max(Value#111) AS max(Value)#133]\n +- Project [State#85, Value#111, SourceTimestamp#87, Tag#88, Source#105, window#119 AS window#118]\n +- Filter isnotnull(current_timestamp())\n +- Project [named_struct(start, precisetimestampconversion(((((CASE WHEN (cast(CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) as double) = (cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) THEN (CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) + cast(1 as bigint)) ELSE CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) END + cast(0 as bigint)) - cast(1 as bigint)) * 4000000) + 0), LongType, TimestampType), end, precisetimestampconversion((((((CASE WHEN (cast(CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) as double) = (cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) THEN (CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) + cast(1 as bigint)) ELSE CEIL((cast((precisetimestampconversion(current_timestamp(), TimestampType, LongType) - 0) as double) / cast(4000000 as double))) END + cast(0 as bigint)) - cast(1 as bigint)) * 4000000) + 0) + 4000000), LongType, TimestampType)) AS window#119, State#85, Value#111, SourceTimestamp#87, Tag#88, Source#105]\n +- Project [State#85, cast(Value#86 as double) AS Value#111, SourceTimestamp#87, Tag#88, Source#105]\n +- Project [State#85, Value#86, SourceTimestamp#87, Tag#88, cast(Source#99L as timestamp) AS Source#105]\n +- Project [State#85, Value#86, SourceTimestamp#87, Tag#88, cast(Source#93 as bigint) AS Source#99L]\n +- Project [State#85, Value#86, SourceTimestamp#87, Tag#88, substring(SourceTimestamp#87, 1, 10) AS Source#93]\n +- Project [data#83.State AS State#85, data#83.Value AS Value#86, data#83.SourceTimestamp AS SourceTimestamp#87, data#83.Tag AS Tag#88]\n +- Project [jsontostructs(StructField(State,StringType,true), StructField(Value,StringType,true), StructField(SourceTimestamp,StringType,true), StructField(Tag,StringType,true), cast(value#70 as string), Some(Etc/UTC)) AS data#83]\n +- StreamingExecutionRelation KafkaV2[Subscribe[SIMULATOR.SUPERMAN.TOTO]], [key#69, value#70, topic#71, partition#72, offset#73L, timestamp#74, timestampType#75]\n'
I dont't get any problem in streaming values unless i try to group by window.
Is there a problem im memory or partitions that i'm missing ?? Like we can't process entirely the window in the memory !!!!
A: You are using a version of LZ4 Java which doesn't have constructor LZ4BlockInputStream(InputStream in) which version of this library do you have?
| |
doc_23531691
|
Edit:
I would ideally like to handle this with a max timeout for the request. I have the following:
//ini_set('default_socket_timeout', 1);
$streamOptions = array(
'http'=>array(
'timeout'=>0.01
)
);
$streamContext = stream_context_create($streamOptions);
$wsdl = 'file://' . dirname(__FILE__) . '/Service.wsdl';
try{
if ( file_get_contents( $wsdl ) ) {
$this->_soapClient = new SoapClient($wsdl,
array(
'soap_version' => SOAP_1_2,
'trace' => true,
'stream_context' => $streamContext
)
);
$auth = array('UserName' => $this->_username, 'Password' => $this->_password);
$header = new SoapHeader(self::WEB_SERVICE_URL, "WSUser", $auth);
$this->_soapClient->__setSoapHeaders(array($header));
}//if
}
catch(Exception $e){
echo "we couldnt connect". $e;
}
$this->_soapClient->GetUser();
I set the timeout to 0.01 to try and force the connection to timeout, but the request still seems to fire off. What am I doing wrong here?
A: I have had the same issues and have implemented solution !
I have implemented
SoapClient::__doRequest();
To allow multiple soap calls using
curl_multi_exec();
Have a look at this asynchronous-soap
A: Four solutions:
*
*Use AJAX to do the SOAP -> Simplest SOAP example
*Use AJAX to call a second PHP file on your server which does the SOAP (best solution imo)
*Put the SOAP request to the end of your PHP file(s) (not the deluxe solution)
*Use pcntl_fork() and do everything in a second process (I deprecate that, it might not work with every server configuration)
Depending on the way you implement this, PHP has plenty of timeout configurations,
for example socket_set_timeout(), or stream_set_timeout() (http://php.net/manual/en/function.stream-set-timeout.php)
| |
doc_23531692
|
There is a function in WinAPI
HRESULT WINAPI ConnMgrConnectionStatus(
HANDLE hConnection,
DWORD *pdwStatus
);
but it requires previous connection handle, and in my case it can be established manually.
Is there a way to get connection status without handles or subscribe to break event?
I can just check google.com, but that doesn't look good.
Regards,
A: Why can't you use the ConnMgrQueryDetailedStatus to get all the connections and run through them to check what you have?
| |
doc_23531693
|
from abc import ABC, abstractmethod
class Job(ABC):
pass
class EasyJob(Job):
pass
class HardJob(Job):
pass
class Worker(ABC):
@abstractmethod
def run(self, job: Job) -> None:
raise NotImplementedError()
class EasyWorker(Worker):
def run(self, job: EasyJob) -> None:
pass
class HardWorker(Worker):
def run(self, job: HardJob) -> None:
pass
However, mypy understandably complains about this:
line 14: error: Argument 1 of "run" is incompatible with supertype "Worker"; supertype defines the argument type as "Job"
line 18: error: Argument 1 of "run" is incompatible with supertype "Worker"; supertype defines the argument type as "Job"
Is there any way in Python to facilitate such a structure?
A: You probably want Bounded Parametric Polymorphism. See also this section about bounded type variables.
In Worker, you want to say that your method run is generic in the sense that it takes a value of some unspecified type T whereas T is a subtype of Job. The classes derived from Worker then substitute T for concrete types:
from abc import ABC, abstractmethod
from typing import Generic, TypeVar
class Job(ABC):
pass
class EasyJob(Job):
pass
class HardJob(Job):
pass
T = TypeVar('T', bound=Job)
class Worker(ABC, Generic[T]):
@abstractmethod
def run(self, job: T) -> None:
raise NotImplementedError()
class EasyWorker(Worker[EasyJob]):
def run(self, job: EasyJob) -> None:
pass
class HardWorker(Worker[HardJob]):
def run(self, job: HardJob) -> None:
pass
| |
doc_23531694
|
My question here is that here as per this example I am specifying the password "foo" when i curl this from any ec2 instances, as part of automations, so we want to automated this and codes will come from git:
curl \
--request POST \
--data '{"password": "foo"}' \
http://10.10.218.10:8200/v1/auth/userpass/login/mitchellh
Our policy is that we should NOT store any password in git... How do I run this curl and get authenticated to vault without specify the password for the user? is this possible?
A: Why you don't want to use aws-auth-method?
Also, if you are sure to want to use password authentication I think you can do something like this:
*
*Generate user/password in the Vault, store user passwords in the Vault and set a policy to allow reading specific user password for specific ec2-instance (EC2 auth method);
*In the ec2-instance run consul-template which will authenticate in the Vault with an ec2-instance role;
*This consul-template will generate curl command with specific user name and password
*Use this command
| |
doc_23531695
|
The class Author extends NSManagedObject and Book extends NSManagedObject also. In my Author class, is it OK to create an extension, so that I can do custom searches within author. For example, would it be OK to write:
Author* theAuthor = /* found somewhere else */
NSArray* books = [theAuthor booksWrittenAfter:2009];
where the call to 'booksWrittenAfter:' would do the search in CoreData, returning books written after 2009 for that author?
I have written this in code and it works and compiles, I was just wondering if this was OK to do, or whether all searches in CoreData should be done in another class and the classes Author and Book are kept simpler?
Thank you very much!
Michael
A: Yes, that's fine. You can also do it from within the Core Data GUI interface in Xcode. In Xcode 4, click and hold on the plus sign at the bottom left. Then select Add Fetch Request. Then, you can define the fetch request there.
| |
doc_23531696
|
I've set the wait_for my MySQL server to 180 seconds.
I also have the following parameters set in my hibernate properties file:
properties.put("hibernate.connection.driver_class", JDBC_DRIVER);
properties.put("hibernate.connection.url", JDBC_URL);
properties.put("hibernate.connection.username", JDBC_USER);
properties.put("hibernate.connection.password", JDBC_PASSWORD);
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show_sql", false);
properties.put("hibernate.connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider");
properties.put("hibernate.c3p0.min_size", 1);
properties.put("hibernate.c3p0.max_size", 10);
properties.put("hibernate.c3p0.max_statements", 8 );
I have created a c3p0 properties file and added it to my resources folder. The content of this file is below:
c3p0.testConnectionOnCheckout=true
That is all. This is all that is left in this particular configuration file as I read that some properties can only be set in this file. Upon loading the application c3p0 is initialized I get the following log message printed out:
INFO: Initializing c3p0 pool...
com.mchange.v2.c3p0.PoolBackedDataSource@b014587e [
connectionPoolDataSource ->
com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@5e2902db [
acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay
-> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0,
connectionCustomizerClassName -> null, connectionTesterClassName ->
com.mchange.v2.c3p0.impl.DefaultConnectionTester,
debugUnreturnedConnectionStackTraces -> false, factoryClassLocation ->
null, forceIgnoreUnresolvedTransactions -> false, identityToken ->
1hge17r9d37v2wm1n57lrr|ba81af, idleConnectionTestPeriod -> 0,
initialPoolSize -> 1, maxAdministrativeTaskTime -> 0, maxConnectionAge
-> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 10, maxStatements -> 8, maxStatementsPerConnection -> 0, minPoolSize -> 1, nestedDataSource ->
com.mchange.v2.c3p0.DriverManagerDataSource@d4187fd7 [ description ->
null, driverClass -> null, factoryClassLocation -> null, identityToken
-> 1hge17r9d37v2wm1n57lrr|1434751, jdbcUrl -> jdbc:mysql://localhost:3306/whatever?characterEncoding=UTF-8, properties
-> {user=******, password=******} ], preferredTestQuery -> null, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0,
testConnectionOnCheckin -> false, testConnectionOnCheckout -> true,
unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies ->
false; userOverrides: {} ], dataSourceName -> null,
factoryClassLocation -> null, identityToken ->
1hge17r9d37v2wm1n57lrr|2a237a, numHelperThreads -> 3 ]
It appears everything is being set.
I started configuring this connection pool because I was getting a broken pipe issue on the server 8 hours the first connection was obtained. So as a test, I set the wait_timeout no the server as I mentioned for 180 seconds and after I get the issue when trying to do a database call:
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
The last packet successfully received from the server was xxx
milliseconds ago. The last packet sent successfully to the server was
xxx milliseconds ago. is longer than the server configured
value of 'wait_timeout'. You should consider either expiring and/or
testing connection validity before use in your application, increasing
the server configured values for client timeouts, or using the
Connector/J connection property 'autoReconnect=true' to avoid this
problem.
Caused by: java.net.SocketException: Broken pipe
I am using the following relevant maven dependencies:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.0.0.Final</version>
</dependency>
What is the easiest I set up c3p0 to avoid this broken pipe issue.
I've tried the preferredTestQuery = Select 1 approach played around with the numbers, idleConnectionTestPeriod, nothing seemed to do tha trick.
I might be missing something very simple, I could use some guidance.
Thanks,
Peter
| |
doc_23531697
|
'PURPOSE: Finds and highlight all values in Routing List Adapters that are not found in Summary Adapters
Sub SummaryCheck_1()
Dim RoutingList As Worksheet
Dim Summary As Worksheet
Dim RoutingList_Adapters1 As Range
Dim Summary_Adapters As Range
Dim Adapter As Range
Dim AdapterValue As String
Dim Match As Range
'Sets worksheets
Set RoutingList = ActiveWorkbook.Sheets("Routing List")
Set Summary = ActiveWorkbook.Sheets("Summary")
'Sets Routing List Adapter Fitting (1) range and Summary Adapter range
'Corresponds to Adapter Fitting (1) column
Set RoutingList_Adapters1 = RoutingList.Range(("F3"), RoutingList.Range("F3").End(xlDown))
Set Summary_Adapters = Summary.Range(("A4"), Summary.Range("A4").End(xlDown))
'Finds and highlights all Routing List Adapter Fittings (1) not found in Summary Adapters
For Each Adapter In RoutingList_Adapters1
AdapterValue = Adapter.Value
Set Match = Summary_Adapters.Find(What:=AdapterValue, LookAt:=xlWhole)
If Match Is Nothing Then
Adapter.Interior.Color = RGB(255, 255, 0)
ElseIf Not Match Is Nothing Then
Match.Interior.Color = RGB(0, 255, 0)
ElseIf InStr(AdapterValue, "XXX") > 0 Then
'Here is where I want to insert code to skip cells containing "XXX"
End If
Next Adapter
End Sub
Let me know if this sub needs more explantation. I tried one workaround, which is resetting the interior color to RGB(255,255,255) for all cells containing "XXX," but unfortunately many of the sheet rows are already color-coded, so I need to just skip cells containing "XXX" altogether. Thank you in advance for any insights on how to skip the loop iteration for this single condition!
A: There are better methods, a quick one can be
Match.Interior.Color = Match.Interior.Color
A: Added And InStr(AdapterValue, "XXX") = 0, changed the code to this:
'PURPOSE: Finds and highlight all values in Routing List Adapters that are not found in Summary Adapters
Sub SummaryCheck_1()
Dim RoutingList As Worksheet
Dim Summary As Worksheet
Dim RoutingList_Adapters1 As Range
Dim Summary_Adapters As Range
Dim Adapter As Range
Dim AdapterValue As String
Dim Match As Range
'Sets worksheets
Set RoutingList = ActiveWorkbook.Sheets("Routing List")
Set Summary = ActiveWorkbook.Sheets("Summary")
'Sets Routing List Adapter Fitting (1) range and Summary Adapter range
'Corresponds to Adapter Fitting (1) column
Set RoutingList_Adapters1 = RoutingList.Range(("F3"), RoutingList.Range("F3").End(xlDown))
Set Summary_Adapters = Summary.Range(("A4"), Summary.Range("A4").End(xlDown))
'Finds and highlights all Routing List Adapter Fittings (1) not found in Summary Adapters
For Each Adapter In RoutingList_Adapters1
AdapterValue = Adapter.Value
Set Match = Summary_Adapters.Find(What:=AdapterValue, LookAt:=xlWhole)
If Match Is Nothing And InStr(AdapterValue, "XXX") = 0 Then
Adapter.Interior.Color = RGB(255, 255, 0)
ElseIf Not Match Is Nothing Then
Match.Interior.Color = RGB(0, 255, 0)
End If
Next Adapter
End Sub
A: Why not to skip the XXX ones altogether?
If InStr(AdapterValue, "XXX") = 0 Then
If Match Is Nothing Then
Adapter.Interior.Color = RGB(255, 255, 0)
Else
Adapter.Interior.Color = RGB(0, 255, 0)
End If
End If
I assumed you want to colour in green the cells where you found a match, maybe I misunderstood your code.
| |
doc_23531698
|
function() {nextplease.init();} to behave identically. Is there any possible difference between them (obviously, you can assign something to nextplease.init, but let's exclude that)?
In particular, can there be a difference in behavior between window.addEventListener("load", nextplease.init, false); and window.addEventListener("load", function() {nextplease.init();}, false);?
The bug I'm trying to find is described in Objects in JavaScript defined and undefined at the same time (in a FireFox extension) Someone has suggested that using the first form instead of the second might make a difference.
A: One important difference is the value of the "this" keyword inside the body of the function referenced by nextplease.init.
Assume nextplease is defined as such:
nextplease = {};
nextplease.someCustomProperty = "hello";
nextplease.init = function () { alert(this.someCustomProperty); }
In the first example, the value of "this" would be the DOM object, and the alert would fail:
window.addEventListener("load", nextplease.init, false);
In the second form, the value of "this" would be the nextplease object, and the alert would say, "hello":
window.addEventListener("load", function() {nextplease.init();}, false);
Reference the MDC documentation:
https://developer.mozilla.org/en/DOM/element.addEventListener
A: There are 2 possible differences
window.addEventListener("load", nextplease.init, false);
This will call the function and that is all. If you wanted to add parameters, then this wouldn't be able to set them.
window.addEventListener("load", function() {nextplease.init();}, false);
This, on the other hand, allows you to call more than one function, and allows you to set parameters. It also adds extra overhead of calling a function, and storing a function in memory.
A: These two:
window.addEventListener("load", nextplease.init, false);
window.addEventListener("load", function() {nextplease.init();}, false);?
are almost exactly the same, assuming nextplease.init is a function object.
The one difference is that in the second case, any arguments passed to the outer function (even though its signature doesn't define any, they can still be passed) will not get passed to nextplease.init(). But since this is just going through the addEventListener API, you know what will be passed ahead of time.
| |
doc_23531699
|
// get the current date
$now = date("Y-m-d");
if ($user_id['enddate'] < $now) {
?>
<p>your Licence is out of date</p>
<?php
}
else
{
?>
<p>your licence is in date</p>
<?php
}
The value storing the expiry date is 'enddate'.
It just goes straight to the out of date message, whether the user has a subscription in date or not. I can't get my head around it.
The MYSQL field for enddate is just type 'date', and is generated from the registration script:
$enddate = date("Y-m-d", strtotime("+ 365 day"));
Any ideas? I know i'm working in depreciated MYSQL, but I need to for this project.
Cheers
A: You need to convert to time, date is just a string...
$now = strtotime(date("Y-m-d"));
if (strtotime($user_id['enddate']) < $now) {
?>
<p>your Licence is out of date</p>
<?php
}
else
{
?>
<p>your licence is in date</p>
<?php
}
A: FYI: Solved with the following:
$expirydate = mysql_query("SELECT enddate FROM users WHERE user_id = '".$_SESSION["user_id"]."'"); echo $query;
$expirydate2 = mysql_result($end, 0);
$now = strtotime(date("Y-m-d"));
if (strtotime($expirydate2) < $now) {
Hope this is of help to some of you.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.