id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23527800
|
richTextBox1.AppendText("hello");
somehow the text appears in the richTextBox1.Text but is not shown in the form.
any idea of what might be the problem?
(I checked the forecolor seems ok).
Thanks in advance
Edit:
found the root cause (had by mistake the initializeComponent() twice. )
private void InitializeComponent()
{
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(114, 104);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(100, 96);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
public Form1()
{
InitializeComponent();
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
richTextBox1.AppendText("hello world");
}`
but still curious about why did this cause this weird behavior?
A: Does the same happen when you do richTextBox1.Text = "hello";?
EDIT: trying to explain the problem
Without seeing the entire code it's difficult for me to know for sure.
But my guess is, that something caused your OnLoad event handler to be called from within the first call to InitializeComponent, and then in the second call the RichTextBox was replaced with a new instance, and your text was added to the old instance.
If you post the minimal code that still has behavior (including the content of InitializeComponent), I can try help figure out the reason.
EDIT 2
Well, when you call InitializeComponent twice, you actually create two instances of all the controls on your Form. So what happened was, the first call created one RichTextBox. Then the second call created another RichTextBox in exactly the same location, with the same size. Then you set the text to the second RichTextBox.
The reason you can't see the text is because the first RichTextBox is hiding the second one! To test that, you can add some code to change the location of richTextBox1 after you set its text, and then you'll see that there are two of them...
| |
doc_23527801
|
Example:
http://justfortest.cba.pl/misc/index.html (full content displayed)
http://justfortest.cba.pl/misc/index.html#comment-3 (content is cut to anchor link)
I discovered that when I remove overflow: hidden; from .content>div then content is not overflowed, but then the design is destroyed: problem with background and too long div.
after removing overflow: hidden; (problem with div length and background).
justfortest.cba.pl/misc/index2.html#comment-3
Updated:
Here is the code for content part:
.content {padding: 40px 0; border-top: 5px solid #e3e4e6; border-bottom: 1px solid #d8d8d8; background: url("images/bg.png");}
.content>div { width: 980px; margin: 0 auto; border: 1px solid #d8d8d8; background: #fff;}
.main {float: left; overflow: hidden; width: 610px; margin-bottom: -5000px; padding: 15px 35px 5030px;}
.sidebar {float: right; width: 260px; margin-bottom: -5000px; padding: 15px 19px 5030px; border-left: 1px solid #e8e8e8; background: #fafbfc;}
Could you please help with that problem?
Any help will be appreciated.
Kind regards
A: try this
.main {
float: left;
margin-bottom: 0; /* from -5000px */
overflow: hidden;
padding: 15px 35px 30px; /* from 15px 35px 5030px */
width: 610px;
}
| |
doc_23527802
|
Other than storing the short name of the action in a variable myself or getting it using reflection by finding the ActionName attribute on all actions within the controller type, is there a better way to get this name?
Please consider this example.
class FooController : Controller
{
[ActionName("shortName")]
public ActionResult LongActionNameIDoNotWantToExposeInTheUri()
{
}
public ActionResult AnotherAction()
{
// This make the Uri as
// /Foo/LongActionNameIDoNotWantToExposeInTheUri
// Instead, I want it to be /Foo/shortName
// I can, of course, hardcode or store the short name
// in a variable and get it but is there a better way?
var url = Url.Action("LongActionNameIDoNotWantToExposeInTheUri", "Foo");
}
}
A: Try this
Type controllerType = typeof(FooController);
string actionMethodName = "LongActionNameIDoNotWantToExposeInTheUri";
MethodInfo methodInfo = controllerType.GetMethod(actionMethodName);
var attributes = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), false);
string actionName = string.empty;
if (attributes.Length > 0)
{
actionName = ((ActionNameAttribute)attributes[0]).Name;
}
or if you want to use it with a method
public string GetActionName(Controller controller, string actionMethodName)
{
Type controllerType = controller.GetType();
MethodInfo methodInfo = controllerType.GetMethod(actionMethodName);
var attributes = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), false);
if (attributes.Length > 0)
{
return ((ActionNameAttribute)attributes[0]).Name;
}
else
{
throw new IndexOutOfRangeException("This controller doesnt have Action Name");
}
}
// if you are in the Controller class
string actionName = GetActionName(this, "LongActionNameIDoNotWantToExposeInTheUri");
| |
doc_23527803
|
error: no match for ‘operator<’ (operand types are ‘const KeyA’ and ‘const KeyA’)
some simplified code to show the issue:
#include <map>
using namespace std;
struct KeyA { // defined in somewhere else
int a;
};
namespace NS {
struct config {
using Key = KeyA; // type alias
using Table = map<Key, int>;
};
bool operator <(const config::Key& lhs, const config::Key& rhs) {
return lhs.a <rhs.a ;
}
}
int main()
{
using namespace NS;
config::Table table;
table[{1}]= 2;
return 0;
}
What happens here? and how to solve this (no way to touch KeyA and most probably have to keep the overloaded function in NS)?
A: One simple option is to just define your own comparator and supply that to the std::map template arguments instead:
struct config
{
using Key = KeyA; // type alias
struct KeyLess {
bool operator ()(const Key& lhs, const Key& rhs) const {
return lhs.a < rhs.a;
}
};
using Table = map<Key, int, KeyLess>;
};
You can leave the other comparison function there if you want. I removed it, since it looks like you only defined it for the map anyway.
A: You can use the following complete working program to solve your problem.
#include <map>
using namespace std;
struct KeyA { // defined in somewhere else
int a;
//friend declaration
friend bool operator <(const KeyA& lhs, const KeyA& rhs);
};
bool operator <(const KeyA& lhs, const KeyA& rhs) {
return lhs.a <rhs.a ;
}
namespace NS {
struct config {
using Key = KeyA; // type alias
using Table = map<Key, int>;
};
}
int main()
{
using namespace NS;
config::Table table;
table[{1}]= 2;
return 0;
}
The output of the above program can be seen here.
| |
doc_23527804
|
Can somone tell me what is the plugin used in the below snippet to get suggestions in VS code?
A: Thanks to Alexander for this awesome extensions.
The name of the extension is Error Lens
| |
doc_23527805
|
In other words, how do I implement the following plain HTML when using react-router?
<a href="#faq-1">Question 1</a>
<a href="#faq-2">Question 2</a>
<a href="#faq-3">Question 3</a>
<h3 id="faq-1">Question 1</h3>
<h3 id="faq-2">Question 2</h3>
<h3 id="fa1-3">Question 3</h3>
Currently I intercept clicks on such links, and scroll to the anchor position. This isn't satisfactory, because it means it's impossible to link directly to some section of a page.
A: import { Link } from 'react-router-dom'
Link using
<Link to='/homepage#faq-1'>Question 1</Link>
Then insert the following code inside your target React component (Homepage):
useEffect(() => {
const hash = props.history.location.hash
// Check if there is a hash and if an element with that id exists
const el = hash && document.getElementById(hash.substr(1))
if (el) {
el.scrollIntoView({behavior: "smooth"})
}
}, [props.history.location.hash]) // Fires every time hash changes
A: Using current methods you would use Link from react-router-dom
<a href="#faq-1">Question 1</a>
would be accomplished with
import React from 'react';
import {Link} from 'react-router-dom';
and using
<Link to={{pathname: '/this-view-path', hash: '#faq-1'}}>Question 1</Link>
of course '/this-view-path' could be provided as a variable from your project
A: The problem with anchor links is that react-router's default is to use the hash in the URL to maintain state. Fortunately, you can swap out the default behaviour for something else, as per the Location documentation. In your case you'd probably want to try out "clean URLs" using the HistoryLocation object, which means react-router won't use the URL hash. Try it out like this:
Router.run(routes, Router.HistoryLocation, function (Handler) {
React.render(<Handler/>, document.body);
});
A: React Router Hash Link worked for me. Easy to install and implement:
$ npm install --save react-router-hash-link
In your component.js import it as Link:
import { HashLink as Link } from 'react-router-hash-link';
And instead of using an anchor <a>, use <Link> :
<Link to="#faq-1>Question 1</Link>
<Link to="#faq-2>Question 2</Link>
<Link to="#faq-3>Question 3</Link>
NOTE: I used HashRouter instead of Router
A: For Router 6 use can use the following:
const {hash, key} = useLocation()
useEffect(()=>{
if(hash){
const targetElement = document.getElementById(hash.substring(1))
targetElement?.scrollIntoView({behavior: 'smooth'})
}
}, [key, hash])
| |
doc_23527806
|
Some conflicts were found in the installation area.
Some of the conflicts below do not have a solution, so the patch cannot be applied. Press `Cancel` to exit.
File: Contents/jre/jdk/Contents/Home/jre/lib/jli/libjli.dylib
Action: Validate
Problem: Modified
Solution: NONE
I think this is somewhat related JRE as it shows some issue in file Contents/jre/jdk/Contents/Home/jre/lib/jli/libjli.dylib But not sure what to do to solve this.
| |
doc_23527807
|
It works fine on my test devices, but I'm seeing an issue with a user using Safari/9.0 on iOS/9.3.2 - the link simply does nothing!
Are custom URL schemes no longer supported? Do I need to start using universal links instead?
For those interested, here is the Javascript code I use in iOS browsers (which is working 99% of the time):
var timer;
var heartbeat;
var lastInterval;
window.addEventListener("pageshow", function(evt){
clearTimers();
}, false);
window.addEventListener("pagehide", function(evt){
clearTimers();
}, false);
function getTime() {
return (new Date()).getTime();
}
// For all other browsers except Safari (which do not support pageshow and pagehide properly)
function intervalHeartbeat()
{
var now = getTime();
var diff = now - lastInterval - 200;
lastInterval = now;
if(diff > 1000)
{ // don't trigger on small stutters less than 1000ms
clearTimers();
}
}
function clearTimers()
{
clearTimeout(timer);
clearTimeout(heartbeat);
}
function intervalHeartbeat()
{
if (document.webkitHidden || document.hidden)
{
clearTimers();
}
}
function launch()
{
lastInterval = getTime();
heartbeat = setInterval(intervalHeartbeat, 200);
timer = setTimeout(function ()
{
logErrorToMyServer();
}, 2000);
//Launch app via custom URL scheme
window.location = "myapp://";
}
A: Custom URI schemes have been a not-good option since the introduction of iOS 9.2. Apple has definitely made it clear that Universal Links are the preferred approach to deep linking.
I'm not aware of any retroactive changes that would be causing Safari on 9.0 - 9.3.2 to do nothing in this situation (you should at least be getting an error pop-up), but this will continue to be unsupported for the foreseeable future and you should get Universal Links up and running as soon as possible. More details available in this blog post.
| |
doc_23527808
|
reducers
import { combineReducers } from "redux";
import user from "./user";
import account from "./account";
const allReducers = combineReducers({
user:user
account:account
});
export type RootState = ReturnType<typeof allReducers>
store.js
import { createStore } from "redux";
import {RootState} from '../reducers/index'
function saveToLocalStorage(state) {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem("state", serializedState);
} catch (e) {
console.log(e);
}
}
function loadFromLocalStorage() {
try {
const serializedState = localStorage.getItem("state");
if (serializedState == null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (e) {
console.log(e);
return undefined;
}
}
const savedState = loadFromLocalStorage();
const store = createStore(
RootState,
savedState,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
store.subscribe(() => saveToLocalStorage(store.getState()));
export default store;
I keep on getting this error when I try to compile the code.
Attempted import error: 'RootState' is not exported from '../reducers/index'.
A: I don't have much experience with redux, however by reading the documentation of createStore, I've found:
createStore
Redux's createStore. You should not need to use this directly.
When looking at the arguments for createStore, this documentation says that the first argument should be a
reducing function, while here you're passing an exported typescript type and not an actually callable function.
This leads me to believe that you're using createStore incorrectly, which would explain your error: Attempted import error: 'RootState' is not exported from '../reducers/index'.
I would start from the Typescript Quick Start and use the configureStore as they suggest to setup the RootState.
Also see:
*
*Definte Root State and Dispatch Types
*ConfigureStore
A slightly different and more advanced usage (should you need it) can be found on React & Redux in TypeScript - Complete Guide: Store Configuration, but I would still start with the basic tutorial and work from there.
| |
doc_23527809
|
When checking whether the current settings contain UIUserNotificationsType.None, it returns true for both when the permission was given and denied. Would anyone know why this is?
func registerForAllNotificationTypes()
{
registerNotificationsForTypes([.Badge, .Alert, .Sound])
}
func registerNotificationsForTypes(types:UIUserNotificationType)
{
let settings = UIUserNotificationSettings.init(forTypes:types, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
}
func isRegisteredForAnyNotifications() -> Bool
{
let currentSettings = UIApplication.sharedApplication().currentUserNotificationSettings()
print(currentSettings)
print((currentSettings?.types.contains(.Alert))!)
print((currentSettings?.types.contains(.Badge))!)
print((currentSettings?.types.contains(.Sound))!)
print((currentSettings?.types.contains(.None))!)
return (currentSettings?.types.contains(.Alert))! //Just testing .Alert for now
}
When permission is on:
Optional(<UIUserNotificationSettings: 0x7fabdb719360; types: (UIUserNotificationTypeAlert UIUserNotificationTypeBadge UIUserNotificationTypeSound);>)
true
true
true
true
When permission is off:
Optional(<UIUserNotificationSettings: 0x7f96d9f52140; types: (none);>)
false
false
false
true
A: Funny thing, it just confirms that 0 contains 0 :)
Take a look on enum definition for UIUserNotificationsType:
https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIUserNotificationSettings_class/index.html#//apple_ref/c/tdef/UIUserNotificationType
struct UIUserNotificationType : OptionSetType {
init(rawValue rawValue: UInt)
static var None: UIUserNotificationType { get }
static var Badge: UIUserNotificationType { get }
static var Sound: UIUserNotificationType { get }
static var Alert: UIUserNotificationType { get }
}
But it's more clearly visible in Objective-C:
typedef enum UIUserNotificationType : NSUInteger {
UIUserNotificationTypeNone = 0,
UIUserNotificationTypeBadge = 1 << 0,
UIUserNotificationTypeSound = 1 << 1,
UIUserNotificationTypeAlert = 1 << 2,
} UIUserNotificationType;
| |
doc_23527810
|
For instance, If in column C, we detect, say, cana (note that this is not an exact match, but good enough), then I would want VBA to help me to extract Canary Wharf, its Serial Number and Product next to it, which are 8273615 and Canned Food, to the end of another worksheet, and the loop goes on until the end of Canary Wharf and moves on to Riverdale, which I would type, say, riverd, and repeat the same process. The x's are there to signify that I have a rather large dataset, nothing else.
I have used the code below to carry out the task:
Option Compare Text
Sub DataExtraction()
Dim SrchRng As Range, cel As Range, i As Integer
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
Set SrchRng = ws1.Range("A1:A100")
For Each cel In SrchRng
For i = 1 To 10
For k = 1 To 1
If InStr(1, cel(i, k).Value, "cana") > 0 Then
ActiveCell(i, k).Value = "Canary Wharf"
ActiveCell(i, k + 1).Value = cel(i, k + 1).Value
ActiveCell(i, k + 2).Value = cel(i, k + 2).Value
End If
Next k
Next i
Next cel
End Sub
The code above imported 10 same inputs, namely, Canary Wharf, 8273615, Canned Food, for 10 times, I suspect it was because of my For i = 1 To 10 command. My desired end goal, is to let VBA extract Canary Wharf until there are no Canary Wharf's left, alongside the two inputs to its right. In other words, it would be a 2x3 Matrix that I am looking at. Then, naturally, I would move to Riverdale, and the cycle goes on.
| |
doc_23527811
|
LONGWORD a: 4
LONGWORD b: 4
LONGWORD c: 4
LONGWORD d: 12
LONGWORD e: 8
LONGWORD f: 8
LONGWORD g: 24
A: In an "implementation-defined manner". Per 6.7.2.1 Structure and union specifiers, paragraph 11, of the C Standard:
An implementation may allocate any addressable storage unit large
enough to hold a bit-field. If enough space remains, a bit-field
that immediately follows another bit-field in a structure shall be
packed into adjacent bits of the same unit. If insufficient space
remains, whether a bit-field that does not fit is put into the next
unit or overlaps adjacent units is implementation-defined. The order
of allocation of bit-fields within a unit (high-order to low-order or
low-order to high-order) is implementation-defined. The alignment of
the addressable storage unit is unspecified.
To answer your question But what if I have something more complex? Data like 0x1700581001FFFFFF with the following struct ordering?
The proper answer in that case, if you want portable and reliable code, is to not use bit-fields. The fact that you have failed to provide enough information in your question for anyone to provide an answer as to how that data will be placed into the bit-fields you described should inform you what the problems are when using bit-fields.
For example, given your bit-fields
LONGWORD a: 4
LONGWORD b: 4
LONGWORD c: 4
LONGWORD d: 12
LONGWORD e: 8
LONGWORD f: 8
LONGWORD g: 24
If one assumes 16-bit int-type values are used for bit-fields, it would be perfectly proper to lay out the data thusly:
16-bit `int` with `c`,`b`,`a` - in that order
16-bit `int` with `d`
16-bit `int` with `f`,`e` - in that order
16-bit `int` with first 16 bits of `g`
16-bit `int` with last 8 bits of `g` - **after** 8 bits of padding.
And that's not even getting into endianness of the storage.
A: Questions like (and the point made in a comment about how to "designate, in order, the meaning of bits to data") inevitably boil down to: what are you trying to do with the data?
If you're declaring a data structure so that some C code can write to it, and other C code can read from it, you rarely if ever care about the byte order, or the bitfield order (or the padding, or the alignment, or any of that).
Where it gets tricky -- very tricky -- is when you try to take that data structure, as your C compiler laid it out in memory, and write it out to or read it in from the outside world. When you try to do that, you end up having to worry forever about type sizes, and byte order, and padding, and alignment, and the order in which bitfields are assigned.
In fact there are so many things to worry about, and nailing them all down is such a nuisance, that many people (myself included) recommend simply not trying to define data structures which can be directly read and written in this way, at all.
My memory is that compilers for big-endinan machines tend to lay out the bits in bitfields one way, and for little-endian the other way. But I can never remember which way is which. (And even if I thought I could remember, you shouldn't trust me.) If for some reason you care, you're going to have to do what I always do, which is to write some little test programs to construct some binary data and print it out in hex and figure out how it's done for the machine/compiler combination you're using today. (And of course you also have to decide what you're going to do about the possibility that your machine/compiler combination might change next week.)
A: Upon re-reading the documentation, I do not see any allowance for packing the bitfields in simply any order. There is indeed a specified ordering but it is implementation dependent in which way it is done. But it is still quite determinable. In short, from what I am seeing, it is packing up the bits by groups of 8 IN ORDER. The difference for our Little Endian compiler (or maybe some option somewhere) is that the concatenation of the bits puts the first-defined bits AFTER the next-defined bits (i.e. made the first defined less significant than the next-defined). For example:
a:3 = 111 (binary)
b:4 = 0000 (binary)
c:9 = 011111111 (binary)
Our Little Endian compiler (or, again, perhaps some other option) will take the 3 bits from 'a' and concatenate with b by adding 'a' to the end of 'b'. This, I believe, is opposite what Big Endian compilers would do which would put 'a' before the 'b'. So I'm speculating it's the endianness that does this, but ours would get 7 bits of 0000111 by making ba rather than ab. It then needs one more bit from c to create a full 8. It takes the least significant bit of 'c' which is a 1 and, again, the previous bits get tacked on to the end of that new bit. So we have 10000111. This byte, 0x87, is then stored to memory and it grabs another 8 bits. In this example the next 8 bits is 01111111 and so it stores that byte, 0x7F, after the 0x87. So in memory we now have 0x877F. Another method (likely Big Endian) would have ended up with 0xE0FF. The 0x877F which is now in memory, if interpreted as a word in Little Endian would be a value of 0x7F87 or, in binary, 0111111110000111. This happens to be the exact reverse of the data structure above concatenating 'cba'.
So let's do that same reverse ordering of the data I provided earlier:
(0x1700581001FFFFFF was meant to be parsed as below but I guess that might not have been obvious since it is a Big Endian construct I assumed)
LONGWORD a: 4 = 0x1
LONGWORD b: 4 = 0x7
LONGWORD c: 4 = 0x0
LONGWORD d: 12 = 0x058
LONGWORD e: 8 = 0x10
LONGWORD f: 8 = 0x01
LONGWORD g: 24 = 0xFFFFFF
With the Little Endian configuration we have, this could be interpreted as one giant structure with a value of 0xFFFFFF0110058071 by concatenating in the order gfedcba. If we store this back to memory in Little Endian format, we would get 0x7180051001FFFFFF which is the exact data I said we were seeing. Big Endian, in theory, would have done it in the order I assumed as obvious (0x1700581001FFFFFF) both as interpreted and stored.
Well, it makes sense to me. Hopefully it makes sense to someone else trying to figure out the same thing! I still don't get why they all say LONGWORD before them though...
| |
doc_23527812
|
The packets that I sent to the server had their own encapsulation (packet id and packet size headers. I know that UDP has also a checksum so I didn't add a header for that), but how TCP works, I know that the server may not receive the entire packet, so I gathered and buffered the data received until a full valid packet was received.
Now I have the chance to change my client/server program to UDP, and I know that one difference with TCP is that data is not received in the same order as sent (which is why I added a packet id header).
The thing that I want to know is: If I send multiple packets, will they be received with no guaranteed order but with guaranteed encapsulation? I mean, if I send a packet sized 1000 bytes of data and another packet sized 400 bytes of data later, will the server receive 2 packets, one of 1000 bytes and another one of 400 bytes, or is there a chance to receive 200 of that 1000 bytes, then 400 bytes of that 1000 bytes and later the rest of the bytes like TCP does?
A: UDP is a datagram service. Datagrams may be split for transport, but they will be reassembled before being passed up to the application layer.
A: With small packet sizes you should have no concern that packets will be broken into multiple packets. That generally is only an issue when the packet gets over an Ethernet network.
You ask" will the server receive 2 packets, one of 1000 bytes and another one of 400 bytes, or there's a chance to receive 200 of that 1000 bytes, then 400 bytes of that 1000 bytes and later the rest of the bytes like TCP can do?
With a packet size of under 1492 bytes there is not going to be any partial packets.
UPDATE:
Apparently I see a need to clarify why I say UDP packet lengths 1492 bytes or less will not affect transport robustness.
The maximum UDP length as implicitly specified in RFC 768 is 65535 including the 8 byte Header. Max Payload Frame Length is 65527 bytes.
While this should not be disputed number the UDP data length is often reported incorrectly. This is exemplified in a previous post:
What is the largest Safe UDP Packet Size on the Internet
A data packet is not constrained by the MTU of the underlying network ToS or communications protocol's Frame length (e.g. IP and Ethernet respectively). Discrepancies between MTU and Protocol Lengths are remedied by Fragmentation and Reassembly
At the Transport Layer each network Type of Service (ToS) has a specific Maximum Transmission Unit (MTU). UDP is encapsulated within IP Packets and IP Packets are encapsulated by the transporting Network's ToS. IP packets are often transmitted through networks of various ToS which include Ethernet, PPP, HDLC, and ADCCP.
When the MTU for a receiving Network ToS is less than the sending ToS then the receiving network must Fragment the received packet. When the Network sends a packet to a network with a higher MTU, the receiving Network must reassemble any Fragmented packets.
Ethernet is the defacto mainstream protocol with the lowest MTU. Non-Mainsteam Arcnet the MTU is 507 bytes. The practical lowest MTU is Ethernet's 1500 bytes, minus the overhead makes maximum payload length 1492 bytes.
If the UDP packet has more than 1492 bytes the data packet will likely be Fragmented and Reassembled. The Fragment and Reassembly adds complexity to the already complex process coupling UDP and IP, and therefore should be avoided.
Because UDP is a non-guaranteed datagram delivery protocol it boosts the transport performance. Robustness is left to the originating and terminating Application. RFC 1166 sets the standards for the communication protocol link layer, IP layer, and transport layer, the UDP Application is responsible for packetization, reassembly, and flow control.
The maximum UDP packet size can also be lowered by a Communication Host's Application Layer. The packet length is a balance between performance and robustness.
The Communications Host's Application Layer may set a maximum UDP packet size. The typical UDP max data length at the Application layer will use the maximum allowed by the IP protocol or the Host Data Link Layer, typically Ethernet.
It is the Application's programer that chooses to use the Host Application Layer or the Host Data Link layer. The Host Application Layer will detect UDP packet errors and discard the packet if necessary. When the application communicates directly with the Host Data Link, the application then has the responsibility of detecting packet errors.
Using maximum UDP data packet length of Ethernet's max payload length of 1492 bytes will eliminate the issues of Fragmentation and Delivery Order of multiple Frames.
That is why I said packet length is not a Fragmentation issue with packet lengths of 1000 and 400 bytes.
###
I do not know what you mean by "guaranteed encapsulation", it makes no sense to me.
With IP there is no guarantee of packet delivery of the order whether UDP or TCP.
As long as you control both sides of the conversation, you can work out your own protocol within the data packet to handle ordering and post packets. Reserve the first x bytes of the packet for a sequential order number and total number of packets. (e.g. 1 of 3, 2 of 2, 3 of 3). If the client side is missing a packet then the client must send a request for retransmission. You need to determine to what level you are going to go for data integrity. like maybe the re-transmission packet is lost.
That may be what you meant by "guaranteed encapsulation", Where there is other information within your datagram packet to ensure some integrity. You should add your own CRC for the total data being sent if broken into multiple datagrams. the checksum is not very robust and is only for the one packet.
UDP is much faster then TCP but TCP has flow control and guaranteed delivery.
UDP is good for streaming content like voice where a lost packet is not going to matter.
Network reliability has improved a lot since the days when these issues were a major concern.
| |
doc_23527813
|
I want to implement it like the picture above.
<Grid>
<Border BorderThickness="1" BorderBrush="#eeeeee" Height="200" Width="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="6*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border Background="#55a0c4">
<TextBlock Text="묘도대교 PY1 탑정부" Padding="6" Foreground="White"/>
</Border>
<Border Grid.Column="1" Background="White" Margin="0 0 0 0">
<Path Stroke="#55a0c4" StrokeThickness="1" Stretch="Fill" Margin="0 4 0 0">
<Path.Data>
<LineGeometry StartPoint="1,0" EndPoint="0,1" />
</Path.Data>
</Path>
</Border>
<Border Background="#55a0c4" Grid.Column="2" VerticalAlignment="Top" Height="5"/>
</Grid>
</Border>
</Grid>
The above picture and code are embodied by me, but I cannot fill the background only in the above margin. What should I do?
A: You just need a different geometry. Instead of drawing a line, draw a triangle. This will fill most of the area you want. Then you just need to also include a rectangle to fill the space above the triangle. Here's a version of your code that does what you want:
<Border BorderThickness="1" BorderBrush="#eeeeee" Height="200" Width="300">
<Grid SnapsToDevicePixels="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="6*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border Background="#55a0c4">
<TextBlock Text="묘도대교 PY1 탑정부" Padding="6" Foreground="White"/>
</Border>
<Border Grid.Column="1" Background="White" Margin="0 0 0 0">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Path Fill="#55a0c4" Stretch="Fill" Margin="0 5 0 0" Data="M 0,0 H 1 L 0,1 Z"/>
<Rectangle Fill="#55a0c4" Height="5" HorizontalAlignment="Stretch" VerticalAlignment="Top"/>
</Grid>
</Border>
<Border Background="#55a0c4" Grid.Column="2" VerticalAlignment="Top" Height="5"/>
</Grid>
</Border>
Looks like this:
Please note that I also added SnapsToDevicePixels="True" to the parent Grid element. This is necessary to inhibit antialiasing that would result in faint gaps between the graphical elements.
I also used the "Path Markup Syntax" to define the triangle, instead of building the Path object's data with explicit XAML elements. I find this much more concise, if sometimes not as readable.
| |
doc_23527814
|
When switching to TextInputLayout + AutoCompleteTextView this behaviour is different, clicking on something outside the "spinner" closes the spinner AND the view underneath the touch does get the click event as well - this is very annoying and imho unexpected.
Can I somehow disable this behaviour to get the same behaviour as I get when using an old spinner?
A: Unfortunately no chances to catch the touch outside event using setOnDismissListener or dismissDropDown(); the latter gets called when item is selected.
But that would be possible by registering OnDismissListener on the instance of the inner popup window of the AutoCompleteTextView which is of type ListPopupWindow through reflections:
private fun getPopup(): ListPopupWindow? {
try {
val field = AutoCompleteTextView::class.java.getDeclaredField("mPopup")
field.isAccessible = true
return field.get(this) as ListPopupWindow
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
return null
}
Hopefully, the documentation can solve this to avoid this anti-pattern.
The OnDismissListener callback gets called on any type of dismissal of the menu; either clicking on items, touching outside the AutoCompleteTextView or hitting the soft keyboard back button. This can be distinguished by tagging the ACTT with the appropriate flag for each event; an enum is used for that in the below customized class):
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.ViewTreeObserver
import android.widget.AdapterView
import android.widget.AutoCompleteTextView
import android.widget.ListPopupWindow
import androidx.appcompat.widget.AppCompatAutoCompleteTextView
class TouchOutsideAutoCompleteTextView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : AppCompatAutoCompleteTextView(context, attrs), AdapterView.OnItemClickListener {
init {
super.setOnItemClickListener(this)
viewTreeObserver.addOnGlobalLayoutListener(object :
ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
viewTreeObserver
.removeOnGlobalLayoutListener(this)
else
viewTreeObserver
.removeGlobalOnLayoutListener(this)
// Registering the mPopup window OnDismissListener
adjustTouchOutside()
}
})
}
private var consumerListener: AdapterView.OnItemClickListener? = null
private enum class DismissEvent {
ON_ITEM_CLICK, // Should be set to enable the next touch dispatch event whenever the dismiss is due to a click on the menu item.
ON_TOUCH_OUTSIDE, // Should be set to disable the next touch dispatch event whenever the dismiss is due to a touch outside the menu.
ON_BACK_PRESSED // Should be set to enable the next touch dispatch event whenever the dismiss is due to the software keyboard back button pressed.
}
/*
* Called globally on any touch on the screen to consume the event if it returns true
* */
fun isDismissByTouchOutside() = tag == DismissEvent.ON_TOUCH_OUTSIDE
private fun isDismissByItemClickOrBackPressed() =
tag == DismissEvent.ON_ITEM_CLICK || tag == DismissEvent.ON_BACK_PRESSED
private fun setDismissToItemClick() {
tag = DismissEvent.ON_ITEM_CLICK
}
private fun setDismissToTouchOutside() {
tag = DismissEvent.ON_TOUCH_OUTSIDE
}
private fun setDismissToBackPressed() {
tag = DismissEvent.ON_BACK_PRESSED
}
fun clearDismissEvent() {
tag = null
}
@SuppressLint("DiscouragedPrivateApi")
private fun getPopup(): ListPopupWindow? {
try {
val field = AutoCompleteTextView::class.java.getDeclaredField("mPopup")
field.isAccessible = true
return field.get(this) as ListPopupWindow
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
return null
}
private fun adjustTouchOutside() {
getPopup()?.let {
it.setOnDismissListener {
if (isDismissByItemClickOrBackPressed()) {// Menu dismissal Event of clicking on the menu item or hitting the software back button
clearDismissEvent() // Neutralize the enum to allow the next touch dispatch event & for adding a chance of next dismissal decision
} else { // Menu dismissal Event of touching outside the menu
// Don't allow the next touch dispatch event
setDismissToTouchOutside()
}
}
}
}
override fun onItemClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
setDismissToItemClick()
consumerListener?.onItemClick(p0, p1, p2, p3)
}
override fun setOnItemClickListener(l: AdapterView.OnItemClickListener?) {
// DO NOT CALL SUPER HERE
// super.setOnItemClickListener(l)
consumerListener = l
}
override fun onKeyPreIme(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && isPopupShowing)
setDismissToBackPressed()
return super.onKeyPreIme(keyCode, event)
}
}
The usage
Overriding dispatchTouchEvent() in the activity is required to consume the event for touching outside by checking isTouchOutsideDisabled(); and neutralize the dismissal event:
If the AutoCompleteTextView is in the activity then:
lateinit var autoCTV: TouchOutsideAutoCompleteTextView
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
if (autoCTV.isDismissByTouchOutside()) {
autoCTV.clearDismissEvent()
return true
}
return super.dispatchTouchEvent(ev)
}
If it is in some fragment, then the dispatchTouchEvent() need to have access to it:
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
val fragment = supportFragmentManager.findFragmentByTag("MyFragmentTag") as MyFragment
if (fragment.autoCTV.isDismissByTouchOutside()) {
fragment.autoCTV.clearDismissEvent()
return true
}
return super.dispatchTouchEvent(ev)
}
| |
doc_23527815
|
Example when trying to install R package "tidyverse":
* installing *source* package ‘xml2’ ...
** package ‘xml2’ successfully unpacked and MD5 sums checked
** using staged installation
ERROR: 'configure' exists but is not executable -- see the 'R Installation and Administration Manual'
* removing ‘/home/davidb/R/x86_64-redhat-linux-gnu-library/4.0/xml2’
ERROR: dependency ‘xml2’ is not available for package ‘rvest’
* removing ‘/home/davidb/R/x86_64-redhat-linux-gnu-library/4.0/rvest’
ERROR: dependencies ‘rvest’, ‘xml2’ are not available for package ‘tidyverse’
* removing ‘/home/davidb/R/x86_64-redhat-linux-gnu-library/4.0/tidyverse’
Based on what I found on the internet, I understood that xml2 depends on libxml2, which I installed with the following command:
sudo yum install -y libcurl-devel openssl-devel libxml2-devel
After that, when opening R and trying install.packages("xml2"), I still got an error message:
* installing *source* package ‘xml2’ ...
** package ‘xml2’ successfully unpacked and MD5 sums checked
** using staged installation
ERROR: 'configure' exists but is not executable -- see the 'R Installation and Administration Manual'
* removiError: unexpected '>' in ">"
ng ‘/home/davidb/R/x86_64-redhat-linux-gnu-library/4.0/xml2’```
Any help would be welcome!
R session details:
```> R.Version()
$platform
[1] "x86_64-redhat-linux-gnu"
$arch
[1] "x86_64"
$os
[1] "linux-gnu"
$system
[1] "x86_64, linux-gnu"
$status
[1] ""
$major
[1] "4"
$minor
[1] "0.3"
$year
[1] "2020"
$month
[1] "10"
$day
[1] "10"
$`svn rev`
[1] "79318"
$language
[1] "R"
$version.string
[1] "R version 4.0.3 (2020-10-10)"
$nickname
[1] "Bunny-Wunnies Freak Out"```
| |
doc_23527816
|
public class Product {
public string Barcode { get; set; }
public double Price { get; set; }
public Category Category { get; set; }
}
public class Category {
public string Name { get; set; }
public string department { get; set; }
}
Now issue is I am not able to use subquery in $expand query option. Here I have given simple example but in real I have to execute some complex query as subquery.
Cuurently I am getting this:
"value": [
{
"Price": 500,
"Category": {
"Name": "Cricket bat"
"Department": 235
}
}
]
Expected result:
"value": [
{
"Price": 500,
"Category": {
"Name": "Cricket bat"
"Department": "Sport" //This result I want to get using subquery.
}
}
Table stuct of sub query-
Department Table
--------------------------------------------
DepCode |Id |Seq |ValueData
235 |1 |0 |1
235 |1 |1 |2
235 |2 |0 |Sport
235 |2 |1 |Food
--------------------------------------------
SubQuery:
select d2.ValueData
from department d1
left join department d2 on d2.id=2
and d1.DepCode = d2.DepCode
and d1.Seq = d2.Seq
where d1.DepCode=235
and d1.ValueId=1
and d1.ValueData=1
In DB I'm getting value 1 (d1.ValueData=1) and using above query I need to fetch "Sport".
Odata Query: /odata/Product?$expand=Category&$select=Price
How I can achive this with odata?
A: In case i understood correctly, you can use nested query option in $expand to do sub query as
/odata/Product?$expand=Category($select=Department)&$select=Price
you can get:
"value": [
{
"Price": 500,
"Category": {
"Department": "Sport"
}
}
Be noted:
1) $expand can nest "$filter, $orderby, $top, $skip, $select, $expand..."
2) In the latest version, $select also can nest "$filter, $orderby, $top, $skip, $select".
Thanks, hope it can help you.
| |
doc_23527817
|
/var/log/couchdb contained 2 files. An old (many months!) couch.log.1 and a couch.log with size 0 - which is suspicious. I've deleted the old files and now tried restarting couch, but the log files stubbornly stay absent!
I've restarted couch using
/etc/init.d/couchdb restart
But no joy.
My local.ini file has this entry;
[log]
level = debug
file = /var/log/couchdb/couch.log
And /var/log/couchdb is owned by couchdb and is in group couchdb so I don't think it is a permission issue. There is plenty of disk space on the server too.
I've rebooted the server as well in frustration - no difference.
How do I persuade couchdb to start logging anything again? The reason it has become an issue is that I'm trying to PUT some standalone attachments, but only the small ones are working so I'm trying to look in my (non-existent) log files to see what the problem might be.
Any ideas?
A: There is a possibility that the log file configuration is being set by some other .ini file.
Issue a GET request to http://localhost:5984/_config/log to see what CouchDB has set.
I had stuff like this happen to me because I had installed CouchDB multiple times using different methods. (compiling from source, using apt, the install script that was put out by CouchOne at one point, etc.) It was hard to figure out exactly what local.ini was the real one!
A: OK so it looks as if my LIVE ini files were actually at /usr/local/etc/couchdb/local.ini and not /etc/couchdb/local.ini
And the real logs were in /usr/local as well.
Not quite sure why I had both sets, I guess I had installed couchdb a couple of times in the past and I was looking in the legacy files by mistake!
Hope this helps someone else ... I have been scratching my head for a couple of hours over it now!
| |
doc_23527818
|
There are so much terms thrown around that I can't even connect them into one stable mental model.
For example on MDN page it says:
A block-level box may also be a block container box. A block container
box is a box that contains only other block-level boxes, or creates an
inline formatting context, thus containing only inline boxes.
Then it says:
It is important to note that the notions of a block-level box and
block container box are disjointed. The first, describes how the box
behaves with its parents and sibling. The second, how it interacts
with its descendants. Some block-level boxes, like tables, aren't
block container boxes. Reciprocally, some block container boxes, like
non-replaced inline blocks and non-replaced table cells, aren't
block-level boxes.
Block-level boxes that also are block container boxes are called block
boxes.
Is there some way to explain this so that I get at least some anchor point from where I can expand and include other concepts?
| |
doc_23527819
|
I've been working on a project that is a bunch of different minigames, and I have the menu and games all written up, the problem is, how would I go about writing code to launch these games if the right button is pressed, and then make the menu re-launch when the game is finished?
A: It is actually very simple. Your main loop should have sub loops. Each sub loop is a single game. If you hit button one you run loop 1. If you hit button 2 you run loop 2 etc. something like this..
while mainloop:
select=True
button1 = False
button2 = False
while select:
if button1 == True:
button1 = False
select = False
game1 = True
elif button2 == True:
button2 = False
select = False
game2 = 2
while game1:
# the game loop
if player_die is True:
game1 = False
select = True
while game2:
# the game loop
if player_die is True:
game2 = False
select = True
something like the above should work. You work out the rest. Remember!! Try before asking..
| |
doc_23527820
|
I need to create html/js buttons that onclick assign different values to a variable that is used in node.js for different things and without modules.
A: This should be doable. The click event should trigger an AJAX post to the server, containing the appropriate value. When the server gets that message and parses the JSON, get the value from the payload and set your variable.
A: Buttons need to be created using HTML/CSS. You could use Ajax to send information to the server. When a button is clicked, you could have an ajax call made to the server with the value of the button. When the server recieves that call, the server could assign it to a variable.
A: You can also export server's functions using RPC(runs through websockets) and execute code of server right from browser. There are many libraries for that: https://zerorpc.dotcloud.com/, http://socket.io/
A: It's just something running on localhost and with integrated html. Maybe you can see what I've tried below...
var ID;
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html><head><script')
res.write('function updateVar(){')
res.write('ID = 12;')
res.write('}')
res.write('</script></head>')
res.write('<body><input type="button" value="Show" onclick="updateVar()" />')
if (ID == '12') {
res.write('<svg><rect width="10" height="10" /></svg></body></html>');
}
| |
doc_23527821
|
The following is not a valid fragment (because the union type is not
visible within function f):
struct t1 { int m; };
struct t2 { int m; };
int f(struct t1 *p1, struct t2 *p2)
{
if (p1->m < 0)
p2->m = -p2->m;
return p1->m;
}
int g()
{
union {
struct t1 s1;
struct t2 s2;
} u;
/* ... */
return f(&u.s1, &u.s2);
}
Why does it matter that the union type is visible to the function f?
In reading through the relevant section a couple times, I could not see anything in the containing section disallowing this.
A: It matters because of 6.5.2.3 paragraph 6 (emphasis added):
One special guarantee is made in order to simplify the use of unions:
if a union contains several structures that share a common initial
sequence (see below), and if the union object currently contains one
of these structures, it is permitted to inspect the common initial
part of any of them anywhere that a declaration of the completed type
of the union is visible. Two structures share a common initial
sequence if corresponding members have compatible types (and, for
bit-fields, the same widths) for a sequence of one or more initial
members.
It's not an error that requires a diagnostic (a syntax error or constraint violation), but the behavior is undefined because the m members of the struct t1 and struct t2 objects occupy the same storage, but because struct t1 and struct t2 are different types the compiler is permitted to assume that they don't -- specifically that changes to p1->m won't affect the value of p2->m. The compiler could, for example, save the value of p1->m in a register on first access, and then not reload it from memory on the second access.
A: Note: This answer doesn't directly answer your question but I think it is relevant and is too big to go in comments.
I think the example in the code is actually correct. It's true that the union common initial sequence rule doesn't apply; but nor is there any other rule which would make this code incorrect.
The purpose of the common initial sequence rule is to guarantee the same layout of the structs. However that is not even an issue here, as the structs only contain a single int, and structs are not permitted to have initial padding.
Note that , as discussed here, sections in ISO/IEC documents titled Note or Example are "non-normative" which means they do not actually form a part of the specification.
It has been suggested that this code violates the strict aliasing rule. Here is the rule, from C11 6.5/7:
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
*
*a type compatible with the effective type of the object,
[...]
In the example, the object being accessed (denoted by p2->m or p1->m) have type int. The lvalue expressions p1->m and p2->m have type int. Since int is compatible with int, there is no violation.
It's true that p2->m means (*p2).m, however this expression does not access *p2. It only accesses the m.
Either of the following would be undefined:
*p1 = *(struct t1 *)p2; // strict aliasing: struct t2 not compatible with struct t1
p2->m = p1->m++; // object modified twice without sequence point
A: Given the declarations:
union U { int x; } u,*up = &u;
struct S { int x; } s,*sp = &s;
the lvalues u.x, up->x, s.x, and sp->x are all of type int, but any access to any of those lvalues will (at least with the pointers initialized as shown) will also access the stored value of an object of type union U or struct S. Since N1570 6.5p7 only allows objects of those types to be accessed via lvalues whose types are either character types, or other structs or unions that contain objects of type union U and struct S, it would not impose any requirements about the behavior of code that attempts to use any of those lvalues.
I think it's clear that the authors of the Standard intended that compilers allow objects of struct or union types to be accessed using lvalues of member type in at least some circumstances, but not necessarily that they allow arbitrary lvalues of member type to access objects of struct or union types. There is nothing normative to differentiate the circumstances where such accesses should be allowed or disallowed, but there is a footnote to suggest that the purpose of the rule is to indicate when things may or may not alias.
If one interprets the rule as only applying in cases where lvalues are used in ways that alias seemingly-unrelated lvalues of other types, such an interpretation would define the behavior of code like:
struct s1 {int x; float y;};
struct s2 {int x; double y;};
union s1s2 { struct s1 v1; struct s2 v2; };
int get_x(void *p) { return ((struct s1*)p)->x; }
when the latter was passed a struct s1*, struct s2*, or union s1s2* that identifies an object of its type, or the freshly-derived address of either member of union s1s2. In any context where an implementation would see enough to have reason to care about whether operations on the original and derived lvalues would affect each other, it would be able to see the relationship between them.
Note, however, that that such an implementation would not be required to allow for the possibility of aliasing in code like the following:
struct position {double px,py,pz;};
struct velocity {double vx,vy,vz;};
void update_vectors(struct position *pos, struct velocity *vel, int n)
{
for (int i=0; i<n; i++)
{
pos[i].px += vel[i].vx;
pos[i].py += vel[i].vy;
pos[i].pz += vel[i].vz;
}
}
even though the Common Initial Sequence guarantee would seem to allow for that.
There are many differences between the two examples, and thus many indications that a compiler could use to allow for the realistic possibility of the first code is passed a struct s2*, it might accessing a struct s2, without having to allow for the more dubious possibility that operations upon pos[] in the second examine might affect elements of vel[].
Many implementations seeking to usefully support the Common Initial Sequence rule in useful fashion would be able to handle the first even if no union type were declared, and I don't know that the authors of the Standard intended that merely adding a union type declaration should force compilers to allow for the possibility of arbitrary aliasing among common initial sequences of members therein. The most natural intention I can see for mentioning union types would be that compilers which are unable to perceive any of the numerous clues present in the first example could use the presence or absence of any complete union type declaration featuring two types as an indication of whether lvalues of one such type might be used to access another.
Note neither N1570 P6.5p7 nor its predecessors make any effort to describe all cases where quality implementations should behave predictably when given code that uses aggregates. Most such cases are left as Quality of Implementation issues. Since low-quality-but-conforming implementations are allowed to behave nonsensically for almost any reason they see fit, there was no perceived need to complicate the Standard with cases that anyone making a bona fide effort to write a quality implementation would handle whether or not it was required for conformance.
| |
doc_23527822
|
As I understood from online source, I need to have jdk 1.7 and higher to run application in weblogic 12c. I also getting below error, when I compile EJB 2.1 with JDK 1.7 or higher.
DEPRECATED: The weblogic.ejbc compiler is deprecated and will be removed in a future version of WebLogic Server. Please use weblogic.appc instead.
java.lang.NoSuchMethodError: weblogic.xml.babel.baseparser.BaseParser.setMaxAttrsPerElement(I)V
at weblogic.xml.stax.XMLStreamReaderBase.prime(XMLStreamReaderBase.java:89)
at weblogic.xml.stax.XMLStreamReaderBase.setInput(XMLStreamReaderBase.java:148)
at weblogic.xml.stax.XMLStreamInputFactory.createXMLStreamReader(XMLStreamInputFactory.java:322)
at weblogic.xml.stax.XMLStreamInputFactory.createXMLStreamReader(XMLStreamInputFactory.java:54)
at weblogic.application.descriptor.BasicMunger2.<init>(BasicMunger2.java:96)
at weblogic.application.descriptor.BasicMunger2.<init>(BasicMunger2.java:114)
at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:79)
at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:63)
at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:45)
at weblogic.ejb.container.metadata.EjbJarReader.<init>(EjbJarReader.java:46)
at weblogic.ejb.container.metadata.EjbJarLoader.createXMLStreamReader(EjbJarLoader.java:49)
at weblogic.application.descriptor.AbstractDescriptorLoader2.createDescriptorBean(AbstractDescriptorLoader2.java:438)
at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBeanWithoutPlan(AbstractDescriptorLoader2.java:832)
at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBean(AbstractDescriptorLoader2.java:841)
at weblogic.ejb.container.metadata.EjbDescriptorReaderImpl.processEjbJarXML(EjbDescriptorReaderImpl.java:440)
at weblogic.ejb.container.metadata.EjbDescriptorReaderImpl.createReadOnlyDescriptorFromJarFile(EjbDescriptorReaderImpl.java:263)
at weblogic.ejb.container.metadata.EjbDescriptorReaderImpl.createReadOnlyDescriptorFromJarFile(EjbDescriptorReaderImpl.java:250)
at weblogic.ejb.spi.EjbDescriptorFactory.createReadOnlyDescriptorFromJarFile(EjbDescriptorFactory.java:92)
at weblogic.ejbc20.getDescriptorFromJar(ejbc20.java:683)
at weblogic.ejbc20.runBody(ejbc20.java:455)
at weblogic.utils.compiler.Tool.run(Tool.java:159)
at weblogic.utils.compiler.Tool.run(Tool.java:116)
at weblogic.ejbc.main(ejbc.java:36)
at BuildEjbs.main(BuildEjbs.java:97)
Exception in thread "main" java.lang.NoSuchMethodError: weblogic.xml.babel.baseparser.BaseParser.setMaxAttrsPerElement(I)V
at weblogic.xml.stax.XMLStreamReaderBase.prime(XMLStreamReaderBase.java:89)
at weblogic.xml.stax.XMLStreamReaderBase.setInput(XMLStreamReaderBase.java:148)
at weblogic.xml.stax.XMLStreamInputFactory.createXMLStreamReader(XMLStreamInputFactory.java:322)
at weblogic.xml.stax.XMLStreamInputFactory.createXMLStreamReader(XMLStreamInputFactory.java:54)
at weblogic.application.descriptor.BasicMunger2.<init>(BasicMunger2.java:96)
at weblogic.application.descriptor.BasicMunger2.<init>(BasicMunger2.java:114)
at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:79)
at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:63)
at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:45)
at weblogic.ejb.container.metadata.EjbJarReader.<init>(EjbJarReader.java:46)
at weblogic.ejb.container.metadata.EjbJarLoader.createXMLStreamReader(EjbJarLoader.java:49)
at weblogic.application.descriptor.AbstractDescriptorLoader2.createDescriptorBean(AbstractDescriptorLoader2.java:438)
at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBeanWithoutPlan(AbstractDescriptorLoader2.java:832)
at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBean(AbstractDescriptorLoader2.java:841)
at weblogic.ejb.container.metadata.EjbDescriptorReaderImpl.processEjbJarXML(EjbDescriptorReaderImpl.java:440)
at weblogic.ejb.container.metadata.EjbDescriptorReaderImpl.createReadOnlyDescriptorFromJarFile(EjbDescriptorReaderImpl.java:263)
at weblogic.ejb.container.metadata.EjbDescriptorReaderImpl.createReadOnlyDescriptorFromJarFile(EjbDescriptorReaderImpl.java:250)
at weblogic.ejb.spi.EjbDescriptorFactory.createReadOnlyDescriptorFromJarFile(EjbDescriptorFactory.java:92)
at weblogic.ejbc20.getDescriptorFromJar(ejbc20.java:683)
at weblogic.ejbc20.runBody(ejbc20.java:455)
at weblogic.utils.compiler.Tool.run(Tool.java:159)
at weblogic.utils.compiler.Tool.run(Tool.java:116)
at weblogic.ejbc.main(ejbc.java:36)
at BuildEjbs.main(BuildEjbs.java:97)
Going to the <application> build directory
Deleting JAR files
*****FINISHED JAR AND EJBC FOR ALL THE EJBS*****
Is it possible to compile EJB 2.1 with JDK 1.6 or least version through deprecated way?
A: we are using ejb 3.0 compiled on jdk1.6 and deployed on weblogic 12c jdk 1.7.We have not faced any issue like this.It is working perfectly fine.I think you will require to do changes in your deployment descriptor.
You can try using descriptors defined in weblogic documentation.
https://docs.oracle.com/cd/E13222_01/wls/docs103/ejb/DDreference-ejb-jar.html
| |
doc_23527823
|
When I go to the command-line version of lint and list all available things to check (lint --list), I get a list that does not include all the inspections I see in Android Studio.
For example, I am able to run an inspection with ID ConstantConditions in Android Studio, but am unable to run it on the command-line.
~/app [master] lint --check ConstantConditions --xml results.xml app
Invalid id or category "ConstantConditions".
Is Android Studio using some other version of lint? Here is some info on the command-line version of lint:
~/app [master] which lint
lint is /Users/Mark/android-sdk-macosx/tools/lint
~/app [master] lint --version
lint: version 24.3.3
A: IntelliJ IDEA has a concept of "inspections", and Android Studio inherits this. For any given problem reported by Android Studio's inspection engine, there can be three theoretical sources:
*
*A stock IDEA inspection, one that Android Studio simply adopted.
*An Android Studio-specific inspection, for something that perhaps can only readily be detected from within the IDE versus from external Lint tools.
*Something from Lint.
I have no idea if #2 is actually used by anything, but it's well within the realm of possibility.
In terms of your error, either that's something that is not Lint (e.g., an IDEA inspection) or there is a naming difference between how the inspection is represented and the command-line equivalent. Since this stuff isn't especially well-documented, it's difficult to say what's going on.
However, in general, do not assume that everything that you see Android Studio yelping about is necessarily something from Lint.
| |
doc_23527824
|
final CalendarView calendarView=(CalendarView)layout.findViewById(R.id.calendarView);
calendarView.setClickable(true);
calendarView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("event", "click");
});
calendarView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Log.e("event", "long click");
return false;
}
});
calendarView.setOnDateChangeListener(new OnDateChangeListener(){
@Override
public void onSelectedDayChange(CalendarView view, int year,
int month, int dayOfMonth) {
Log.e("event", "datachanged");
}
});
I need to catch "OnClick" events, but I catch only "OnDataChange" events. I don't understand why. Please, help me. Thank you in advance.
A: I'm guessing there are some subview's of the 'CalendarView' and it is on these that you can register an 'OnClickListener' and not on the 'CalendarView'.
Have a look here and see that it extends 'FrameLayout'.
A: As calendar is a Dialog not view use
DialogInterface.OnClickListener not View.OnclickListener
A: OnGlobalLayoutListener will do the trick.
calendarView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
@Override
public void onGlobalLayout()
{
//your code here
}
});
| |
doc_23527825
|
where has CrmService and MetadataService class gone ?
tried to ref
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Client;
using Microsoft.Crm.Sdk;
A: They are now bundled into one service called the OrganizationService.
| |
doc_23527826
|
This is how the pipe is created:
int fd[2] = {};
const int err (pipe(fd));
if (err)
{
printf("Error creating pipe (%d)\n", errno);
}
int read_fd = fd[0];
int write_fd = fd[1];
Is that behaviour anywhere documented or does anybody know what might cause this?
A: The hypothesis:
*
*you explicitly or implicitly close your standard input (close(0); or fclose(stdin); ) before actual call to pipe()
*as result, descriptor 0 is considered "free" and used as fd[0], i.e. read side of created pipe
*then you once more explicitly or implicitly perform close(0);
*as result, you have pipe with closed read side
*finally, when you try to write to fd[1], you get SIGPIPE as expected in case, when read side is closed.
If this hypothesis is correct, you need to understand who closes periodically (at least twice) descriptor 0 of your current process
| |
doc_23527827
|
docker container exec -it 6903e8589b00 /home/acoppers/google-cloud-sdk/bin/gcloud auth application-default login --no-launch-browser
Since I installed google-cloud-sdk in my home directory. However I am getting the following error when I run this command:
OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "/home/acoppers/google-cloud-sdk/bin/gcloud": stat /home/acoppers/google-cloud-sdk/bin/gcloud: no such file or directory: unknown
Can someone tell me what I am doing wrong? Thank you.
A: Someone might find this useful. I was unable exec into the docker container like above. I got:
OCI runtime exec failed: exec failed: container_linux.go:380:
starting container process caused: setup user: no such file or directory: unknown
Turned out - in my case - NodeJS child process caused /dev/null to disappear as soon as I restored it
mknod /dev/null c 1 3
chmod 666 /dev/null
I was able to log in again (tested with two shells one was in the other out)
| |
doc_23527828
|
A: If it is a single file, the easiest way would be to use ReSharper (you can get a free trial). ReSharper does a pretty good job of understanding when things are not being used and grays them out. You can collapse the document and then expand only the root nodes and just whack the ones that are grayed out.
Without ReSharper, it is a little tougher. You could go through and do a find all in the solution for each Keyed resource and wack those that aren't found. For implicit resources without keys it will be a little tougher to determine (I don't think R# can even handle these well)
| |
doc_23527829
|
there's a section for storing spirometry results in the database. currently i get results
from an Excel file which is exported by WinspiroPro (the application that comes with spirolab devices) and store them in the database.
few days ago i came across the word "HL7" which seems to be a Standard protocol for communicating with these medical devices, so i can directly get the results from the device using Delphi.
also in spirolab device user manual it is mentioned that the device is compatible with this system.
now my question is, how can I implement this system (HL7) in delphi?
Thanks
A: As is usual with these kind of inter-professional standards, you need to pay to get them, at least on http://www.hl7.org in this case.
If I search around on the net, there may be existing tools that you can use, or have a look how they work internally:
*
*http://code.ohloh.net/search?s=HL7
*https://code.google.com/hosting/search?q=HL7&sa=Search
*http://sourceforge.net/directory/?q=HL7
A: HL7 is not bound to a specific transport layer. It is a protocol on the application level, the seventh layer of the ISO 7-layer-model, hence Level 7. It describes messages and the events, when this messages should be send.
It just gives some recommendations how to do message transfer on the subjacent layers, e.g. MLLP with tcp socket communication. But in principle you are free to use any transport layers you want, may it be direct socket communication, file transfer or what ever.
Although most systems now can use tcp, it is also possible to use HL7 with different underlying transport protocols as RS232. If I remember right, there was also an example about message transfer / coupling with RS232 in the implementation guides of the documentation. And yes, the documentation and protocol standard documetation is free after registering.
Did you ask your provider for the WinspiroPRO version with HL7 ability? Maybe it supports already socket communication with tcp.
Otherwise you either need access to the sourcecode of ldTCPCClient and replace the tcp part with an RS232 part or you have to use a software just for parsing/building (unmarshalling/marshalling) of HL7 messages together with a software, that handles the transportation level.
By the way, just from the name, I guess that ldTCPclient is not apt for your need, as you will probably need a host and not a client component.
| |
doc_23527830
|
On the actual site for any word, under "Translations & Examples" there's a little audio button; when I hover over it, it says javascript:babSpeakIt('swedish',52579,'gard'); and so that's what I searched for in the source code, and even though that gets a blue underline like it's a link, it doesn't lead anywhere.
Essentially, this is my question: how can I use python to download that audio that plays on click?
Thank you!
P.S. - I'm using Python 3.6 in Pycharm community edition on Ubuntu 16.04:)
A: You have to examine javascript code that is being called on click event. See what it does and how. You have to find out how do it passes the audio data to the browser.
Then you have to replicate that behaviour in Python. I.e. you must make the right call to the right URL. Or more of them. Then get the data.
| |
doc_23527831
|
I am using RadTreeListView control for loading big amount of data, it seems it doesnt suppot UI Virtualization, UI freezes and not responding at all.
The amount of data is 400 rows.
Do you have any ideas if it supports UI Virtualization?
-Amino
A: The problem is solved, I had to add MinHeight="300" Height="550" to the RadTreeListView control
| |
doc_23527832
|
mod2 depends on mod1 and mod2 pom.xml includes the following dependancy
<dependency>
<groupId>com.project</groupId>
<artifactId>mod1</artifactId>
<version>${project.version}</version>
</dependency>
in mod1, I have defined in src/test/java an abstract test class
public abstract class ServicesAbstractTest {
...
}
in mod2, src/test/java I have defined a test class which inherits this one.
public class Mod2Test extends ServicesAbstractTest {
...
}
These are all Junit 4 tests. It works fine when I run the tests in Eclipse directly. But doesn't work when I do a mvn clean install, there are compilation errors showing that maven doesnt find ServicesAbstractTest when compiling and testing mod2.
I tried to apply what is said on similar questions : Pascal Thivent answer and Duncan Answer with 2 additional problems :
Strange
Could not find goal 'test-jar' in plugin org.apache.maven.plugins:maven-surefire-plugin:2.2 among available goals test -> [Help 1]
And more compilation problems for module 2 : I think I need here to specify additionnal scope, not only test, I am going to do further research on this one.
A: 1337joe 's comment is the one. Pascal Thivent's answer is what I was looking at.
Lessons learned
*
*When finding a problem, begin to ask the question as precisely as
possible. This is the best way to be pointed toward the most
relevant answers to your problem. You might think you are loosing
time in writing your question compare to a single google search with
code error. You are actually finding faster the right answers
*Dont be ashamed to look foolish when it happens that you just did a
typo or equivalent : a second eye is always the best. It took probably 20 seconds to 1337joe to point out my plugin confusion that I could have spent hours on being too deeply involved in the problem.
| |
doc_23527833
|
d = {"A": foo(), "B": bar()}
def foo(arg):
return arg + 1
def bar(arg):
return arg - 1
In this case I want to pass arg to bar() by referencing the function dynamically
d["B"] #<-- pass arg to bar()
A: It's possible, but you have to refer to the function (e.g. foo) without already calling it (e.g. foo()).
def foo(arg):
return arg + 1
def bar(arg):
return arg - 1
d = {"A": foo, "B": bar}
Result:
>>> d['A'](5)
6
| |
doc_23527834
|
while read_new_char_from_file() != (\r or \n or EOF) add it to the buffer, inc bx
then increment bx to account for the linefeed, and return
I ran a few test cases and the byte count is correct, the loop stops when the byte is \n, as expected. However, the bytes don't seem to be added to my string buffer! The subroutine:
(FGETC reads one char from FHANDLE to CBUFF (updating the handle) and is working properly, nevertheless it can be found here).
FGETS PROC NEAR
PUSH AX ; (used by fgetc)
PUSH CX ; (used by fgetc)
XOR BX, BX ; clears our byte counter
CLD ; positive BF (used by STOSB)
LEA DI, SBUFFL ; pointer to the string buffer (used by STOSB)
FGETS_LOOP: ; read loop
CALL FGETC ; read a new char from the file to CBUFF
CMP AX, CX ; partial read (EOF)?
JNE FGETS_RET ; return
CMP CBUFF, 13 ; carriage return?
JE FGETS_RET_I ; return, increment byte count and handle to account for \r\n
CMP CBUFF, 10 ; line feed?
JE FGETS_RET_U ; return, increment byte count and handle to account for \n
MOV AL, CBUFF ; char to be written to buff
STOSB ; store string byte (increments DI)
INC BX ; increment the byte counter
JMP FGETS_LOOP ; loop
FGETS_RET_U: ; account for \n
INC BX ; increment byte counter
JMP FGETS_RET ; return
FGETS_RET_I: ; account for \r and \n
ADD BX, 2 ; increment byte count by 2
CALL FGETC ; increment fhandle (to skip \n)
FGETS_RET: ; return...
MOV AL, '$' ; add 'end of string' char to the buffer
STOSB ; ...
POP CX ; pops
POP AX ; ...
RET ; actually return
FGETS ENDP
The results of a test case:
String buffer (40 size and initialized with 'x's ending at '$' to be able to print it to the stdout and see the results):
SBUFFL DB 40 DUP ('x'),'$' ; 4000 chars (4000 bytes)
File contents (lines ending at \n):
4,5
500,-1000,0,250,-300
4,0,1,2,3
3,4,3,2
5,1,2,3,2,1
2,2,3
Result of printing SBUFFL (via the DOS int to print a string, which is working) after calling FGETS with FHANDLE at the beginning of the file:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Which indicates the bytes read from the file weren't added to the buffer. However, Turbo Debugger shows the byte count (BX) and the stop condition (\n) are correct for a read on the first line:
Comments are slightly different, only difference in code is an unnecessary PUSH/POP DX which was removed, the results are the same
The debugger also shows STOSB incrementing DI at each call, as expected. I tried using LEA DI, [SBUFF + 0], no difference. Not using CLD also made no difference. Kinda lost here.
A: I suspect DS and ES aren't correctly initialised at all. Following test case works here fine (I didn't change your functions):
.MODEL small
.STACK 1000h
.DATA
SBUFFL DB 40 DUP ('x'),'$'
FHANDLE DW ?
CBUFF DB ?
sample_txt db 'sample.txt',0
errtxt db 'Error.', 13, 10, '$'
.CODE
main PROC
mov ax, @data ; Initialise DS & ES
mov ds, ax
mov es, ax
mov ax, 3d00h ; fopen
lea dx, sample_txt
int 21h
jc errexit
mov [FHANDLE], ax
Loop: ; print fgets until "no string"
call FGETS
cmp byte ptr [SBUFFL], '$'
je Endloop
lea dx, SBUFFL
mov ah, 09h
int 21h
call crlf
jmp Loop
Endloop:
mov ah, 3Eh ; fclose
mov bx, [FHANDLE]
int 21h
mov ax, 4C00h
int 21h
errexit:
lea dx, errtxt
mov ah, 09h
int 21h
mov ax, 4C01h
int 21h
main ENDP
crlf PROC ; print line feed
push ds
push '$$'
push 0A0Dh
mov ax, ss
mov ds, ax
mov dx, sp
mov ah, 09h
int 21h
add sp, 4
pop ds
ret
crlf ENDP
FGETC PROC NEAR
PUSH BX ; pushs
PUSH DX
MOV AH, 03Fh ; Read from file
MOV BX, FHANDLE ; Found at fhandle
MOV CX, 1 ; Read 1 byte
LEA DX, CBUFF ; To cbuff
INT 21H ; Do it
POP DX ; pops
POP BX
RET ; return
FGETC ENDP
FGETS PROC NEAR
PUSH AX ; (used by fgetc)
PUSH CX ; (used by fgetc)
XOR BX, BX ; clears our byte counter
CLD ; positive BF (used by STOSB)
LEA DI, SBUFFL ; pointer to the string buffer (used by STOSB)
FGETS_LOOP: ; read loop
CALL FGETC ; read a new char from the file to CBUFF
CMP AX, CX ; partial read (EOF)?
JNE FGETS_RET ; return
CMP CBUFF, 13 ; carriage return?
JE FGETS_RET_I ; return, increment byte count and handle to account for \r\n
CMP CBUFF, 10 ; line feed?
JE FGETS_RET_U ; return, increment byte count and handle to account for \n
MOV AL, CBUFF ; char to be written to buff
STOSB ; store string byte (increments DI)
INC BX ; increment the byte counter
JMP FGETS_LOOP ; loop
FGETS_RET_U: ; account for \n
INC BX ; increment byte counter
JMP FGETS_RET ; return
FGETS_RET_I: ; account for \r and \n
ADD BX, 2 ; increment byte count by 2
CALL FGETC ; increment fhandle (to skip \n)
FGETS_RET: ; return...
MOV AL, '$' ; add 'end of string' char to the buffer
STOSB ; ...
POP CX ; pops
POP AX ; ...
RET ; actually return
FGETS ENDP
END main
| |
doc_23527835
|
Here is my code:
downloadPDF() {
pdfMake.vfs = pdfFonts.pdfMake.vfs;
var docDefination = {
content: [
{
text: "lightHorizontalLines:",
fontSize: 14,
bold: true,
margin: [0, 20, 0, 8],
},
{
style: "tableExample",
table: {
headerRows: 1,
body: [
[{ text: "Details", style: "tableHeader" }],
[{ text: this.observableData }], // observable to pdf data not showing here.
],
},
layout: "lightHorizontalLines",
},
],
};
this.pdfObj = pdfMake.createPdf(docDefination);
if (this.plt.is("cordova")) {
this.pdfObj.getBase64(async (data) => {
try {
let path = `pdf/myletter_${Date.now()}.pdf`;
const result = await Filesystem.writeFile({
path,
data: data,
directory: FilesystemDirectory.Documents,
recursive: true,
});
this.fileOpener.open(`${result.uri}`, "application/pdf");
} catch (error) {
console.log("Unable to write file: ", error);
}
});
} else {
this.pdfObj.download();
}
}
Note: observableData is contain firebase documents value.
A: To get data from an observable, you need to subscribe:
this.observableData.subscribe(data => this.realData = data);
realData should contain needed data (probably you should additionally extract it in some way from the firebase document).
You should keep in mind that subscribe doesn't return data immediately. You can check the documentation about Observables and Subscriptions:
https://rxjs.dev/guide/observable
https://rxjs.dev/guide/subscription
| |
doc_23527836
|
I've started by adding some extra buttons, that add markers with pre-populated data. Then, I click on them so the form is shown, I edit nothing in the form, and press Cancel. Approx half a second to a second after this, I get in browser console:
TypeError: a.url.substr is not a function util.js:202:114
I would very much like to get rid of this error (note it doesn't occur in the original test5.html).
The problem is - first I have no idea what this function is or does; I found Do we have a Uncompressed javascript Library for Google Maps API V3:
There is no uncompressed library. All the API methods are accessed according to the published documentation, so there doesn't need to be an uncompressed version.
Yeah, right - absolutely no need for that, sure! Surely it is not Google keeping a leash on their properties - it's just that nobody would ever need to know what is going on, as it would be impossible to ever get into a problem that bad :)
Anyways, the stack traces that Firefox spits out are:
rz.prototype.load http://maps.googleapis.com/maps-api-v3/api/js/26/17/util.js:202:114
qz.prototype.load http://maps.googleapis.com/maps-api-v3/api/js/26/17/util.js:201:427
_.yz.prototype.load http://maps.googleapis.com/maps-api-v3/api/js/26/17/util.js:204:224
dz.prototype.load http://maps.googleapis.com/maps-api-v3/api/js/26/17/util.js:200:287
cz.prototype.load http://maps.googleapis.com/maps-api-v3/api/js/26/17/util.js:199:133
SS http://maps.googleapis.com/maps-api-v3/api/js/26/17/marker.js:5:217
WS http://maps.googleapis.com/maps-api-v3/api/js/26/17/marker.js:7:482
XS http://maps.googleapis.com/maps-api-v3/api/js/26/17/marker.js:7:116
VS.prototype.Y http://maps.googleapis.com/maps-api-v3/api/js/26/17/marker.js:35:646
_.zf.prototype.L/a.F< http://maps.googleapis.com/maps/api/js:112:4221
... and Chromium outputs this:
util.js:202 Uncaught TypeError: a.url.substr is not a function
rz.load @ util.js:202
cz.load @ util.js:199
oz @ util.js:6
lz @ util.js:6
kz.load @ util.js:201
qz.load @ util.js:201
_.yz.load @ util.js:204
dz.load @ util.js:200
cz.load @ util.js:199
SS @ marker.js:5
WS @ marker.js:7
XS @ marker.js:7
VS.Y @ marker.js:35
(anonymous function) @ js?v=3.26&libraries=drawing,geometry:112
So, apparently the error occurs in rz.prototype.load, and is being initiated by _.zf.prototype.L/a.F< that is (anonymous function); from the Firefox info (...maps/api/js:112:4221), I extracted this for _.zf.prototype...:
...
_.zf.prototype.L=function(){
var a=this;
a.F||(
a.F=window.setTimeout(
function(){
a.F=void 0; // <=== column:4221 here at ;
a.Y()
}
,a.ql)
)
};
...
and this for rz.prototype (which contains util.js:202:114):
...
rz.prototype.load=function(a,b){
var c=this.la;
this.b&&"data:"!=a.url.substr(0,5)||(a=new _.ez(a.url)); // column 114 is right before a.url.substr..
return c.load(a,function(d){
!d&&_.m(a.crossOrigin)?c.load(new _.ez(a.url),b):b(d)
})
};
...
So, the caller _.zf.prototype.L function does a setTimeout which eventually calls rz.prototype, which explains why this error is shown only after some time has expired after I press "Cancel".
But my question is - what is it in the rest of the code, which might call this _.zf.prototype.L function? How can I find that? If _.zf.prototype.L itself was called through a setTimeout, would it have "remembered" the originating caller/call stack, and can that be retrieved for debugging? Or, would it be possible to set a breakpoint, which breaks whenever a function with a name _.zf.prototype.L is about to be called?
I tried looking into How to view JavaScript function calls as they occur (which has no info on how to do a function call trace); and then found https://javascriptweblog.wordpress.com/2010/06/01/a-tracer-utility-in-2kb/ - using this library, I can do:
tracer.traceAll(BlitzMap,true);
tracer.traceAll(BlitzMap.getMapObj(),true);
.... but then it traces the object functions OK, the map obj is a bit weird (there's like 3000+ tracing traceOff messages in the console while the page loads) although it seems to trace some parts too - however, when I do my test case, after pressing "Cancel" all I get are my code traces (which do not crash), and then a second goes by, and I get the error/stacktraces above without any other trace.
So, how to debug a problem like this?
A: Ok, I managed to get somewhere with this problem - even if the close vote claims the problem is "too broad".
First, if the "front-facing" javascript from the API is:
<script src="http://maps.googleapis.com/maps/api/js?v=3.26&libraries=drawing,geometry" type="text/javascript"></script>
... then download it to a file:
wget "http://maps.googleapis.com/maps/api/js?v=3.26&libraries=drawing,geometry" -O gmapsapi.js
... and use this file in your HTML instead of the online one:
<script src="gmapsapi.js" type="text/javascript"></script>
Then open your HTML file in Firefox, have it run, and then do in Firefox: File / Save Page As / Web page, complete.
This will download additional scripts like util.js and such locally in the saved page folder.
Now, open the saved (as Web page, complete) version of the HTML file - it should have also replaced the online links to scripts to the downloaded local ones.
Then, open gmapsapi.js from the saved folder, and introduce linebreaks to _.zf.prototype.L function:
_.zf.prototype.L=function(){
var a=this;
a.F||(a.F=window.setTimeout(function(){a.F=void 0;a.Y()},a.ql))
};
... to be able to set up a breakpoint on a line later.
Now, open the saved HTML file in Firefox, open Firebug, in the Script tab find gmapsapi.js, and set a breakpoint on the var a=this; line.
Now run the stuff - in my case, doing all up to and including pressing Cancel - and the JS engine will break; then you can do console.trace() in Firebug console, and obtain this kind of a trace (after which the error occurs):
_.zf.prototype.L() gmapsapi.js (line 114)
VS.prototype.changed(a="modelIcon") marker.js (line 35)
Bb(a=Object { type="object"}, b="modelIcon") gmapsapi.js (line 37)
Bb(a=Object { type="object"}, b="icon") gmapsapi.js (line 37)
_.k.set(a="icon", b=Object { type="object"}) gmapsapi.js (line 96)
_.vc/<(c=Object { type="object"}) gmapsapi.js (line 47)
_.k.setValues() gmapsapi.js (line 97)
a = Object { type="object"}
BlitzMap</this.updateOverlay() blitz.js (line 545)
BlitzMap</this.closeInfoWindow() blitz.js (line 514)
onclick()input[3] onclick (line 1)
event = Object { type="object"}
... and indeed - this pointed out where the bug is: namely, I had hacked blitz.js and ended up writing an empty string "" for the icon of a marker, which ended up being the cause of the error.
This stack trace reveals one more thing - and that is, why does this error occur only the first time I press cancel, and not subsequent times; well, the answer is, the erring code runs only when VS.prototype.changed(a="modelIcon"), so the second time, the setting of empty string is not a "change" anymore, so no error then.
| |
doc_23527837
|
can anyone explain it, please?
$.fn.extend({
scrollParent: function( includeHidden ) {
var position = this.css( "position" ),
excludeStaticParent = position === "absolute",
/// and the code goes on
A: The code is extending $ (which is the same as the jQuery object), so $.scrollParent is now a function. See here.
Here's an example too, from that very page.
<script>
jQuery.fn.extend({
check: function() {
return this.each(function() {
this.checked = true;
});
},
uncheck: function() {
return this.each(function() {
this.checked = false;
});
}
});
// Use the newly created .check() method
$( "input[type='checkbox']" ).check();
</script>
A: jQuery.fn.extend()
As the documentation states, jQuery.fn.extend() method
Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods.
So, your code extends jQuery's prototype (fn is just an alias to jQuery's prototype) by adding the method scrollParent
You can call this new method to any jQuery object like this:
$('#myElement').scrollParent(includeHidden);
jQuery.extend()
jQuery.extend( object1, object2 ) just merges object2 in to object1
Check the $.extend() documentation for more detail
| |
doc_23527838
|
I'm not sure if it is conceptually possible from looking around but I was hoping to just be able to direct the C to a memory address for a numpy array and use it as though it is an array made by the C. The aim is for the python to initialise the C, build its first array, run the C code until it is ready for the next array which will then be generated by python.
This is some dummy code that I wrote to try and get C to read numpy arrays. At the moment the C just has a segmentation fault and I'm not sure if its because I'm bad at C, it doesn't like reading the numpy arrays or a bit of both.
Front.py
array_interface was from here.
#! /usr/bin/python
import numpy as np
import subprocess as sp
ray = np.array([x*3.14 for x in range(10)])
addr = ray.__array_interface__['data'][0]
pro = sp.Popen(['./back', hex(addr)])
print pro.communicate()[0]
print ray[:5]
quit()
Back.c
#include <stdio.h>
#include <stdlib.h>
int main(char *argv[])
{
float *addr;
int n;
float a[10];
// Hopefully making a pointer to the first float in the np.ndarray
addr = sscanf(argv[1], "%x");
n = 0;
while( n<10 )
{
// Hopefully stepping through the np.ndarray one float at a time.
a[n] = *addr;
addr++;
n++;
}
// Return the first five values to compare with python.
fprintf(stdout, '%f %f %f %f %f\n', a[0], a[1], a[2], a[3], a[4]);
return 0;
}
Is it possible to have C read numpy arrays like this or is this approach fundamentally flawed? Is there a better way of doing it? if this does work, is it possible to use a Ctype bool, that both processes know the address of, to coordinate which process is working and which is waiting? e.g. python sets the value to 1 as it initialises the numpy array -the C is waiting stuck in a while(sp_bool==1) loop. Then when python is finished it changes the value to 0 and the C executes, finally changing the value back to 1 when it finishes.
A: It sounds like your best option might be to call C code from python. Not only is that very much possible, it's actually how NumPy is written. NumPy is mostly written in C so when you do np.add(array1, array2) Python passes array1 and array2 to NumPy's C code, the C code makes an output array for the results, adds the elements of the input arrays putting the result in the output array, and returns the output array.
I think the easiest way for you to make your C code available in Python is to wrap it using Cython. Here are two tutorials that hopefully will get you moving in the right direction. How to call existing C code from Cython and how to use NumPy arrays in Cython.
Also I should mention that you can access NumPy arrays from C code using the NumPy C API, this probably will be harder for you than using Cython because you're new to C, but it's another way to go if you chose that route.
| |
doc_23527839
|
To do this, I am using a List with Song is a class containing the Title of the song, the Singer and the Lyrics (with the chords in it) and everything about that list is written in the C# code-behind.
The problem is that when you write chords with lyrics like I am doing, the chords must be placed exactly above the part of the lyrics where they are played, and aven if I try to write this correctly in my code with spaces and tabulations, the output on the screen isn't the same as in the code.
For example, in C# code-behind I have:
"C B\n" +
"Yesterday all my trouble seemed so far away\n"
but when it shows on the screen it is misplaced like :
C B
Yesterday all my trouble seemed so far away
So to resume I am searching for a way to preserve the numbers of space characters in a string block in a C# file.
| |
doc_23527840
|
In the Categories any category can have n levels of subcategories.
For Ex.:
Category1
-SubCategory1
-SubCategory2
--SubCategor1
---SubCategory1
---SubCategory2
----SubCategory1
----SubCategory2
---SubCategory3
--SubCategory2
-SubCategory3
Category2
-SubCategory1
--SubCategory1
---SubCategory1
----SubCategory1
---SubCategory3
-SubCategory3
...etc and so on.
Language is not a barrier I am just trying to formulate loops/nested loops to create this logic to convert it into a flattened list.
Any help will be highly appreciated.
Thanks in Advance
A: Each entry to your flat List will be a node of your Tree as that is visited according to Depth First Search. For more information please see here
Edit:
The original post was edited a couple of times. Initially, it looked like the OP was after a flat list as that would be the output of BFS but after a later edit it looked like the OP was after a flat list as that would be the output of DFS. The more general case then would be that "Each entry to the flat list will be a node of the Tree as that is visited by some traversal function (such as BFS or DFS)."
A: I don't know what you mean by a flat list, but you can use a stack (implementation wise, it can be STL vector) to store the current progress while recursively visiting the sub categories.
"The current progress" that I mentioned above should store which subcategory that you are currently visiting, so that you can continue to visit other subcategory when you return.
If you can formulate a recursive algorithm, you can rewrite it in this form.
A: You can easily make this using recursion + std::copy function.
| |
doc_23527841
|
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy_splash import SplashRequest
class Listings2Spider(CrawlSpider):
name = 'listings2'
allowed_domains = ['www.realtor.ca']
user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"
script = '''
function main(splash, args)
splash.private_mode_enabled = false
url = args.url
assert(splash:go(url))
assert(splash:wait(3))
return splash:html()
end
'''
def start_requests(self):
yield SplashRequest(url='https://www.realtor.ca/map#ZoomLevel=13&Center=43.686631%2C-79.339824&LatitudeMax=43.75741&LongitudeMax=-79.25894&LatitudeMin=43.61577&LongitudeMin=-79.42071&view=list&Sort=6-D&PGeoIds=g20_dpz8de7m&GeoName=East%20York%2C%20Toronto%2C%20ON&PropertyTypeGroupID=1&PropertySearchTypeId=1&TransactionTypeId=2&Currency=CAD',
headers={'User-Agent': self.user_agent}, callback=self.parse_item, endpoint="execute", args={'lua_source': self.script})
rules = (
Rule(LinkExtractor(restrict_xpaths="//div[@class='cardCon']"), callback='parse_item', follow=True, process_request='set_user_agent'),
)
def set_user_agent(self, request):
request.headers['User-Agent'] = self.user_agent
return request
def parse_item(self, response):
yield {
'Address': response.xpath("//div[@class='listingCardAddress']/text()").get()
}
A: There seems to be a rate limit being applied, I can automate the api calls and avoid using browser automation but the site seems to block requests after a few pages. Note that doing it this way you can get a maximum of 100 results per page which will be (when it works!) much quicker and you get far more details from the json than from the front-end html.
import requests
s = requests.Session()
home_url = 'https://www.realtor.ca/map#ZoomLevel=13&Center=43.686631%2C-79.339824&LatitudeMax=43.75741&LongitudeMax=-79.25894&LatitudeMin=43.61577&LongitudeMin=-79.42071&view=list&Sort=6-D&PGeoIds=g20_dpz8de7m&GeoName=East%20York%2C%20Toronto%2C%20ON&PropertyTypeGroupID=1&PropertySearchTypeId=1&TransactionTypeId=2&Currency=CAD'
step = s.get(home_url)
print(step)
url = 'https://api2.realtor.ca/Listing.svc/PropertySearch_Post'
headers = {
'accept':'*/*',
'accept-encoding':'gzip, deflate, br',
'content-type':'application/x-www-form-urlencoded; charset=UTF-8',
'origin':'https://www.realtor.ca',
'referer':'https://www.realtor.ca/',
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}
output = []
for page in range(1,5):
payload = {
'ZoomLevel':'13',
'LatitudeMax':'43.75741',
'LongitudeMax':'-79.25894',
'LatitudeMin':'43.61577',
'LongitudeMin':'-79.42071',
'Sort':'6-D',
'PropertyTypeGroupID':'1',
'PropertySearchTypeId':'1',
'TransactionTypeId':'2',
'Currency':'CAD',
'RecordsPerPage':'100',
'ApplicationId':'1',
'CultureId':'1',
'Version':'7.0',
'CurrentPage': str(page)
}
post = s.post(url,headers=headers,data=payload).json()
results = len(post['Results'])
print(f'Scraping page: {page}, results: {results}')
for listing in post['Results']:
print(listing['Id'],listing['Property']['Price'])
| |
doc_23527842
|
I have the code:
x = 0.1;
syms y;
S = solve(x+1==(1+y)/(1-y),y);
y = double(S);
val = abs(((2^2)*(y^2))/(2*(y-1)^2))
But val is always rounded off.
I should be getting val = 0.0049999 but instead I am getting val = 0.0050.
Anyone have any idea why?
Thanks.
EDIT: Adding extra code
x = 0.1;
syms y;
S = solve(x+1==(1+y)/(1-y),y);
y = double(S);
val = abs(((2^2)*(y^2))/(2*(y-1)^2))
sprintf('%22.20f',val)
for i=1:2
val= val+((2^i)*(y^i))/(i*(y-1)^i);
sprintf('%22.20f',val)
end
The first sprintf works and shows correct rounding, however the second doesnt!!
A: It has to do with the floating-point representation and how Matlab displays such numbers for readability. If you add this line to the end of your code:
sprintf('%22.20f',val)
you'll get:
ans =
0.00499999999999999924
Edit
Even though it technically deals with Python, this website offers a brief and concise overview on the limitations of floating-point representations.
A: Is it possible that you merely set your preferences for displaying numbers to short rather than long? It would help if you eliminated that as a possibility.
| |
doc_23527843
|
My issue: the SVG includes elements with namespaces, and when I insert it inline, only the non-namespaced elements are rendered. I have tried direct insertion in the html, innerHTML, and the SVGjs library, all give the same result.
Is there a way to render namespaced SVG on the page and interact with it?
For the record, the SVG files come from Visio and I don't have control on the namespaces. Also, I am using Reactjs if that can help.
Sample script (both methods work but strip out namespaced elements):
fetch (fileURL)
.then(response => response.text())
.then((image) => {
let startOfSvg = image.indexOf('<svg')
startOfSvg = startOfSvg >= 0 ? startOfSvg : 0
// innerHTML method
document.getElementById("map").innerHTML = image.slice(startOfSvg);
// svg.js library
const draw = SVG(image.slice(startOfSvg))
.addTo('#map')
.size('100%', 450);
}
A: There is a checkbox to export SVG without visio namespace. Other than that, you could take a look at my exporter (it can export pure svg as well, depending on the template you use): https://unmanagedvisio.com/products/svg-publish
| |
doc_23527844
|
So i am implementing it in exactly same way as answer suggested in the above linked question https://stackoverflow.com/a/18816716/4070142...
I am running it on Android 4.4 (Kitkat). But i am not receiving the QUERY_PACKAGE_RESTART intent in my BroadcastReceiver. I am registering the broadcastreceiver properly in manifest file. Is it problem of android version or something else... Any help?
| |
doc_23527845
|
const getKeys = (intName: string): string[] => {
const project = new Project();
const sourceFile = project.addSourceFileAtPath(`./${path}/${intName}.ts`);
const node = sourceFile.getInterface(intName)!;
const allKeys = node.getProperties().map((p) => p.getName());
return allKeys;
};
But the problem is, that it requires the interface to be the default export of a seperate file. Ideally i want to provide this function not the file address, but the interface itself, something like this
getKeys<interfaceName>()
Is this possible to do with ts-morph?
| |
doc_23527846
|
Online will retrieve requests from end user through UI and
batch processing will send requests in file format.
When the traffic is high in the online server this traffic should not go to the batch nodes.
Both the servers should act independently and process the request.
How to balance the load without hitting the batch servers ?
| |
doc_23527847
|
I've been using the following str_replace_all() code in R, but now I want to specify to ignore "." and "-". I've tried setting it up to include things like [^.-] and ([.-]), but I'm not getting the desired output.
str_replace_all("[APPLE/O.ORANGE*PLUM-11]", regex("[\\W+,[:punct:]]", perl=T)," ")
" APPLE O ORANGE PLUM 11 " #current output
" APPLE O.ORANGE PLUM-11 " #desired output
Any suggestions would be greatly appreciated. Thanks!
A: It's probably easier to use the ^, which means that it is matching everything not referenced within the brackets. By including all letters, numbers, ., and - in the box you don't replace those.
library(stringr)
str_replace_all("[APPLE/O.ORANGE*PLUM-11]", "[^a-zA-Z0-9.-]"," ")
A: Note that str_replace_all does not allow using PCRE patterns, the stringr library is ICU regex powered.
What you need to do can be done with a base R gsub using the following pattern:
> x<-"[APPLE/O.ORANGE*PLUM-11]"
> gsub("[^\\w.-]", " ", x, perl=TRUE)
[1] " APPLE O.ORANGE PLUM-11 "
See the R demo online. Also, see the regex online demo here.
The [^\\w.-] pattern matches any character other than (since [^...] is a negated character class) word char (letter, digit, _), . and -.
| |
doc_23527848
|
I'm learning how to use Renderscript, and I found this part in the docs:
http://developer.android.com/guide/topics/renderscript/advanced.html#mem-allocation
To support this memory allocation system, there are a set of APIs that
allow the Android VM to allocate memory and offer similar
functionality to a malloc call.
...
To better understand how these classes work, it is useful to think of
them in relation to a simple malloc call that can look like this:
array = (int *)malloc(sizeof(int)*10);
The problem
I'm failing to understand something: What if I want to allocate memory within RS itself?
For example, suppose I need to have a calculation that requires a lot of memory compared to the input and output, can I do it all inside RS itself, instead of from Java?
What I've tried
I can't even succeed in creating a new array, even if it's in constant size:
static int array[1024*1024*100] ; //this is ok
void init() {
rsDebug("init called. array check:",(int)(*array));
array[0] = 2; // this is not ok
rsDebug("init called. array check:",(int)(*array));
}
And all I get for this code is this error:
Error:Execution failed for task ':app:compileDebugRenderscript'.
com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command
'D:\android\Sdk\build-tools\22.0.1\llvm-rs-cc.exe'' finished with
non-zero exit value -1073741819
The questions
*
*Is it possible to dynamically allocate memory on RS ? Instead of doing so from Java ?
*If it's possible, is this memory a part of the heap, or a part of the global, available RAM of the device? Will it be auto-GC-ed when the Renderscript object on Java gets GC-ed ?
*What about all the static variables that are set inside RS ? Are they a part of the heap?
*Would all kinds of allocations of RS be automatically freed like on GC , once the Renderscript object on Java gets GC-ed ?
I ask this because of some weird explanations on the docs.
A: There is no way to allocate memory within a .rs file itself. You need to do all of your allocation within Java/C++, and then pass it into RS.
A: No, it's not possible using malloc(); you are mis-reading the documentation.
It doesn't say the API is malloc(), it says it's like malloc(). The very same page you linked goes on to show this example code:
//Create an element manually and allocate memory for the int pointer
intPointer = Allocation.createSized(myRenderScript, Element.I32(myRenderScript), 2);
Which doesn't cast, but also doesn't look like it's C code.
| |
doc_23527849
|
A: Since Python 3.5 (PEP 448) you can do unpacking within a tuple, list set, and dict:
a = ('2',)
b = 'z'
new = (*a, b)
A: #1 form
a = ('x', 'y')
b = a + ('z',)
print(b)
#2 form
a = ('x', 'y')
b = a + tuple('b')
print(b)
A: From tuple to list to tuple :
a = ('2',)
b = 'b'
l = list(a)
l.append(b)
tuple(l)
Or with a longer list of items to append
a = ('2',)
items = ['o', 'k', 'd', 'o']
l = list(a)
for x in items:
l.append(x)
print tuple(l)
gives you
>>>
('2', 'o', 'k', 'd', 'o')
The point here is: List is a mutable sequence type. So you can change a given list by adding or removing elements. Tuple is an immutable sequence type. You can't change a tuple. So you have to create a new one.
A: You need to make the second element a 1-tuple, eg:
a = ('2',)
b = 'z'
new = a + (b,)
A: Bottom line, the easiest way to append to a tuple is to enclose the element being added with parentheses and a comma.
t = ('a', 4, 'string')
t = t + (5.0,)
print(t)
out: ('a', 4, 'string', 5.0)
A: If the comma bugs you, you can specify it's a tuple using tuple().
ex_tuple = ('a', 'b')
ex_tuple += tuple('c')
print(ex_tuple)
A: Tuple can only allow adding tuple to it. The best way to do it is:
mytuple =(u'2',)
mytuple +=(new.id,)
I tried the same scenario with the below data it all seems to be working fine.
>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')
A: >>> x = (u'2',)
>>> x += u"random string"
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
x += u"random string"
TypeError: can only concatenate tuple (not "unicode") to tuple
>>> x += (u"random string", ) # concatenate a one-tuple instead
>>> x
(u'2', u'random string')
A: tup = (23, 2, 4, 5, 6, 8)
n_tup = tuple(map(lambda x: x+3, tup))
print(n_tup)
A: my favorite:
myTuple = tuple(list(myTuple).append(newItem))
Yes, I know it is expensive, but it sure looks cool :)
| |
doc_23527850
|
Why does the API does not expose insertAt?
A: You can create a custom insertAt method (neglecting performance issues) operating on immutable vectors. Just the rough method sketch here
def insertAt[T]( v: Vector[T], elem: T, pos: Int) : Vector[T] = {
val n = v.size
val front = v.take(pos)
val end = v.takeRight(n-pos)
front ++ Vector(elem) ++ end
}
Call:
val x = Vector(1,2,3,5)
println( insertAt( x, 7, 0) )
println( insertAt( x, 7, 1) )
println( insertAt( x, 7, 2) )
Output:
Vector(7, 1, 2, 3, 5)
Vector(1, 7, 2, 3, 5)
Vector(1, 2, 7, 3, 5)
Not handled properly in this sketch
*
*types.
*index checking.
Use the pimp-my-library pattern to add that to the Vector class.
Edit: Updated version of insertAt
def insertAt[T]( v: Vector[T], elem: T, pos: Int) : Vector[T] =
v.take(pos) ++ Vector(elem) ++ v.drop(pos)
A: Having an efficient insertAt is typically not an operation I would expect from a general Vector, immutable or not. That's more the purview of (mutable) linked lists.
Putting an efficient insertAt into the public API of Vector would severely constrain the implementation choices for that API. While at the moment, there is only one implementation of the Scala standard library APIs (which I personally find rather unfortunate, a bit of competition wouldn't hurt, see C++, C, Java, Ruby, Python for examples of how multiple implementations can foster an environment of friendly coopetition), there is no way to know that this will forever be the case. So, you should be very careful what guarantees you add to the public API of the Scala standard library, otherwise you might constrain both future versions of the current single implementation as well as potential alternative implementations in undue ways.
Again, see Ruby for an example, where exposing implementation details of one implementation in the API has led to severe pains for other implementors.
| |
doc_23527851
|
then for have a better performance I used a select into (with data filtered) in a temp table , I did this for the tables I'll use for to have a better performance but now....
In the final result when I need do join between those table (temp table can't have foreign key, isn't it?) do not have foreign key I got "Merge Join" (I understand they are caused because my temp table does not have foreign key)
(If you dont see the pic I reupload it at here)
https://ibb.co/f0XRHv
A: How about using something like suggested in the following answer?
No foreign key restraints on a temporary table? SQL Server 2008
| |
doc_23527852
|
I'm wondering if there is any specific UI for refreshing a list for windows mobile apps other than "pull to refresh".
Please suggest.
Thank you.
A: Many Windows Phone apps now implement pull-to-refresh in lists. The RadDataBoundListBox from Telerik supports it, or you can use some of the implementations available for standard ListBox.
| |
doc_23527853
|
char auxStr[50];
fscanf(f,"%[^\n]s|",auxStr); // HERE IS THE PROBLEM, IT DOES NOT WORK
p->nome = (char*) malloc(sizeof(char)*strlen(auxStr)+1);
strcpy(p->nome,auxStr);
printf(" %s\n\n", p->nome);
I want that auxStr have this value with whitespace "St Charles,961", is it possible to do it using some c function like fscanf or will i have to use a loop and read every character until i found the delimeter '|'?
Ps: Using a loop will solve the problem but i believe it will use the most number of seeks that's possible. I think i can not use fgets cause i don't know the length of the string to be read.
Text File:
85 82|AAAA|BBBB|St Charles,961|Sao Carlos|Sao Paulo|13560-0520|-1|-------------------------
|8585|FFFFFF|RRR| RUA Y, 888|Rio de janeiro|585996-988|-1|---------------------------------
|98 85|ZZZZ|YYYY|AV YYY,889|SP|949845-45354|-23|-----------------------------------------------
A: Here's a suggestion to read all the field from one line.
char field1[50];
char field2[50];
char field3[50];
char field4[50];
char field5[50];
char field6[50];
char field7[50];
char field8[50];
fscanf(f, "%[^|]s|%[^|]s|%[^|]s|%[^|]s|%[^|]s|%[^|]s|%[^|]s|%[^|]s|",
field1, field2, field3, field4,
field5, field6, field7, field8);
| |
doc_23527854
|
Now I tried to delete the second nodepool by removing it from the template.
az deployment group validate --resource-group <rsg-name> --template-file <template-filet.bicep> --parameters <parameterfile.json>
I tried it with both --mode Incremental and --mode Complete, but the nodepool isn't deleted. If I add new node pools to the template they are created like expected. So isn't it possible to delete node pools by editing the template?
A: If I am not mistaken, Node Pools are in a separated Resource Group. Meaning a complete deployment would only cleanup resources within the specified Resource Group - which is not the node pool Resource Group.
| |
doc_23527855
|
I tried online code but not working
can anybody give working code?
I am using windows 10 pro ,Chrome Version 77.0.3865.90 (Official Build) (64-bit) and latest version of selenium
can anybody give code of below and strictly using sendkeys
1) Put some text in google home page
2) refresh
A: You cannot refresh the page with sendkeys. Sendkeys generate the events of keystrokes agasint WebElement - not against your browser window. This is why webdriver has a dedicated method to refresh the page.
| |
doc_23527856
|
C# seems to have everything needed, i.e. co/contravariance and lambdas.
I'm asking this because I recently started working in a company that uses Unity, and I run into a lot of delayed initialization. In an attempt to avoid NullPointerException, I would like to maybe invite them into the monad world. Any ideas on this, or should we simply deal with this in another way?
A: As far as "official" approaches go, remember that if you're using C# 6, you can use the null-conditional operator:
var myVal = possiblyNull?.thisToo?.andThis?.value;
Certain VisualStudio templates (such as the ASP.NET MVC project template) also include the IsNotNull extension method, which is part of the AjaxMinExtensions. If you don't have those in your project, you could copy/paste the implementation into your code.
var myVal = possiblyNull.IfNotNull(v => v.doTheThing())
.IfNotNull(theThing => theThing.TheProperty);
| |
doc_23527857
|
Curl Function
public function global_Curl_payStat($data, $url, $try = 1)
{
//dd($_ENV['API_ENDPOINT_NGINX_IP'] . '/' . $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ($_ENV['API_ENDPOINT_NGINX_IP'] . '/' . $url));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Prevents usage of a cached version of the URL
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
//Listen for HTTP errors
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//dd($statusCode);
$response = json_decode(curl_exec($ch));
dd($response);
curl_close($ch);
if($response == null && $try < 5) {
//Wait a 3 seconds before trying again
sleep(3);
return $this->global_Curl($data, $url, ++$try);
}
return $response;
}
Function calling the curl function below
//Set maximum execution time
ini_set('max_execution_time ', 75);
set_time_limit(75);
//Loop through the code 3 times
for($try=1; $try<=3; $try++) {
sleep(15);
$payStat = $this->global_Curl_payStat($data, 'api/payment/status')->data;
//Call the curl function below
//$payStat = $this->global_Curl($data, 'api/payment/status?cachebuster='. microtime(true))->data;
var_dump($payStat);
dd($payStat);
if ($payStat->status === 1) {
return 'true';
}
}
| |
doc_23527858
|
attr_accessor :sname, :stype, :samount
def initialize (name, type, amount)
#complete initialize() function
@sname = name
@stype = type
@samount = amount
end
end
def main
# create a new array
sale = Array.new
# repeat the following all the 4 sales agents
input = "Yes"
while input == "Yes"||input == "yes"
puts "Input agent name:"
# get input from user
sname = gets.chomp
puts "Input agent type (Junior/Senior):"
# get input from user
stype = gets.chomp
puts "Input sales made by this agent (RM):"
# get input from user (float type)
samount = gets.chomp.to_f
sales = SalesAgent.new(sname, stype, samount)
sale << sales
juniorsum(sales)
puts "Key-in another agent data ? (Yes/No)"
input = gets.chomp
end
# create the new SalesAgent object from the input above
# add the new SalesAgent object into the array
# call display() function
sale.each {|sales| display(sales)}
# call juniorsum() function
juniorsum(sales)
# print total sales made by all the junior sales agents
sleep(1)
puts "Total sales made by junior is RM " + juniorsum(sales).to_s
end
# This function receives an array as parameter
def display(sales)
puts "Name: #{sales.sname}"
puts "Sales: #{sales.samount.to_s}"
puts ""
#display names of all the sales agents and their individual sales amount
end
# This function receives an array as parameter
# It calculates and returns the total sales made by all the junior sales agents
def juniorsum(sales)
if sales.stype =="Junior"||sales.stype == "junior"
total = total = sales.samount
end
return total
end
main
A: It looks like your sales total method is only operating on one entry, not the list as I think you intend. Fixed it looks like:
def juniorsum(sales)
sales.select do |s|
s.stype.downcase == 'junior'
end.inject(0) do |sum, s|
sum + s.samount
end
end
Where that uses select to find all "junior" sales, then inject to sum up the samount values. This filter and reduce pattern is quite common, so it's worth studying and using whenever you're facing problems like this.
Note to call it you'll need to pass in the array, not a single entry:
puts "Total sales made by junior is RM #{juniorsum(sale)}"
Note you call that method twice, once for no reason. If you want to interpolate in a string use the #{...} interpolation method. No to_s required!
| |
doc_23527859
|
vs.
Template.hello.helpers({
'loggedin': function () { return something }
})
The former works (Template.hello.loggedin prints out the function in the console, adding parenthesis returns the something), the latter doesn't (gives undefined).
I thought these were equivalent??
A: They are equivalent except in the case you found. There is an open issue on github about this: https://github.com/meteor/meteor/issues/886.
If you want to call Template.hello.loggedin() use the former.
| |
doc_23527860
|
If (a is 20 more than b) {code code code}
I know you can use the greater than (>) or less than (<) symbols for comparisons similar to this, but I need to say if something is within 20 more than something. How would you do this?
A: Any expression can appear on either side of the comparison, for example:
if (a >= b + 20) {
// code code code
}
A: isn't that something like this ?
if ((a + 20) > b) {
code...
}
| |
doc_23527861
|
image
image2
| |
doc_23527862
|
In my gallery, every 3 images are grouped into a container as
<div class='overlay'>
<a class='next control'>Next</a>
</div>
<div class="container">
<div class="image">
<img src="http://dummyimage.com/100&text=Image1"/>
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image2" />
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image3"/>
</div>
</div>
<div class="container">
<div class="image">
<img src="http://dummyimage.com/100&text=Image4"/>
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image5" />
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image6"/>
</div>
</div>
JQuery
$(document).ready(function () {
var src;
var currentElement;
$(".image").click(function () {
currentElement = $(this);
src = $(currentElement).find("img").attr("src");
$(".overlay").css("background-image", "url('" + src + "')");
$(".overlay").show();
});
$(".next").click(function () {
if ($(currentElement).next().length) {
currentElement = currentElement.next();
src = $(currentElement).find("img").attr("src");
}
else {
currentElement = $(currentElement).parent().next().find(".image:first");
src = $(currentElement).find("img").attr("src");
}
$(".overlay").css("background-image", "url('" + src + "')");
});
});
I am able to get the next image on clicking next. But my problem is How to disable the next button when last image reaches ?.
I am unable to find a logic to get the last image.
Note: the images in last container may vary from 1 to 3
Here is the demo : https://jsfiddle.net/y5fwgz25/1/
A: here is my solution but i do not like this code, but works fine
<div class='overlay'>
<a class='next'></a>
</div>
<div id="gallery">
<div class="container">
<div class="image">
<img src="http://dummyimage.com/100&text=Image1"/>
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image2" />
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image3"/>
</div>
</div>
<div class="container">
<div class="image">
<img src="http://dummyimage.com/100&text=Image4"/>
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image5" />
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image6"/>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var src;
var currentElement;
var last_img = $("#gallery .container:last-child .image:last-child");
$(".image").click(function () {
currentElement = $(this);
src = $(currentElement).find("img").attr("src");
$(".overlay").css("background-image", "url('" + src + "')");
$(".overlay").show();
if ( $(currentElement)[0] == $(last_img)[0] ) {
$(".overlay .next").hide();
}
});
$(".next").click(function () {
if ( $(currentElement).next()[0] == $(last_img)[0] ) {
$(".overlay .next").hide();
}
if ($(currentElement).next().length) {
currentElement = currentElement.next();
src = $(currentElement).find("img").attr("src");
}else {
currentElement = $(currentElement).parent().next().find(".image:first");
src = $(currentElement).find("img").attr("src");
}
$(".overlay").css("background-image", "url('" + src + "')");
});
});
</script>
A: why don't you use jquery last method to get the last sibling and compare any of its attributes with the same attributes of the current element.
If they are the same, hide or disable the next button.
A: You can add one if condition. If the length of currentElement is zero then hide .next.
Updated Fiddle-
$(document).ready(function () {
var src;
var currentElement;
$(".image").click(function () {
currentElement = $(this);
src = $(currentElement).find("img").attr("src");
$(".overlay").css("background-image", "url('" + src + "')");
$(".overlay").show();
});
$(".next").click(function () {
if ($(currentElement).next().length) {
currentElement = currentElement.next();
src = $(currentElement).find("img").attr("src");
}
else {
currentElement = $(currentElement).parent().next().find(".image:first");
src = $(currentElement).find("img").attr("src");
}
if($(currentElement).length==0) {
$(".next").hide();
}
$(".overlay").css("background-image", "url('" + src + "')");
});
});
.overlay {
position: fixed;
top: 0;
left: 0;
display: none;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.9) no-repeat;
background-position: center;
}
.next {
position: absolute;
width: 50px;
height: 50px;
top: 50%;
background-image: url("http://dummyimage.com/50&text=Next");
right: 8em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='overlay'>
<a class='next'></a>
</div>
<div class="container">
<div class="image">
<img src="http://dummyimage.com/100&text=Image1"/>
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image2" />
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image3"/>
</div>
</div>
<div class="container">
<div class="image">
<img src="http://dummyimage.com/100&text=Image4"/>
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image5" />
</div>
<div class="image">
<img src="http://dummyimage.com/100&text=Image6"/>
</div>
</div>
| |
doc_23527863
|
I want iterate through it's contents, so I do:
foreach($options as $option){
print_r( $option);
}
The resulting output gives me an object/array heffalump that starts like this...
Mage_Bundle_Model_Option Object
(
[_defaultSelection:protected] =>
[_eventPrefix:protected] => core_abstract
[_eventObject:protected] => object
[_resourceName:protected] => bundle/option
[_isObjectNew:protected] =>
[_data:protected] => Array
(
[option_id] => 20
[parent_id] => 291
I want to reference values in _data, but I am stumped as to correct syntax to do this...
A: There's no syntax to access them from generic code. The Mage_Bundle_Model_Option class has declared its properties as protected, which means they can only be accessed from the class, its decendants, or its ancestors. You should use the class's public methods to make use of it, not access the properties directly.
A: because the _data object is set as protected, it can only be accessed from inside the Mage_Bundle_Model_Option class or one that extends from it.
so what you would have to do is add a method inside Mage_Bundle_Model_Option along the lines of
function getData(){
return $this->_data;
}
and then instead of your current foreach loop, do:
foreach($options->getData() as $option) {
//do things
}
| |
doc_23527864
|
**AppDelegate.swift**
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// register PFObject subclasses
Task.registerSubclass()
Task.initialize()
Project.registerSubclass()
Project.initialize()
User.registerSubclass()
User.initialize()
**Project.swift**
import UIKit
import Parse
public class Project: PFObject, PFSubclassing
{
// MARK: - Public API
@NSManaged public var projectTitle: String!
@NSManaged public var owner: User!
@NSManaged public var tasks: [Task]
// MARK - Required PFSubclassing Parse setup
override public class func initialize()
{
struct Static {
static var onceToken: dispatch_once_t = 0
}
dispatch_once(&Static.onceToken) {
Task.initialize()
self.registerSubclass()
}
}
public static func parseClassName() -> String {
return "Project"
}
// MARK: Conveinience Init
init(projectTitle: String, owner: User, tasks: [Task])
{
super.init()
self.projectTitle = projectTitle
self.owner = owner
self.tasks = tasks
}
override init() { super.init() }
}
**Task.swift**
import UIKit
import Parse
public class Task: PFObject, PFSubclassing
{
// MARK: - Public API
@NSManaged public var title: String
@NSManaged public var isChecked: Bool
@NSManaged public var projectOwner: Project
@NSManaged public var category: String
@NSManaged public var isImportant: Bool
// MARK - Required PFSubclassing Parse setup
override public class func initialize()
{
struct Static {
static var onceToken: dispatch_once_t = 0
}
dispatch_once(&Static.onceToken) {
self.registerSubclass()
}
}
public static func parseClassName() -> String {
return "Task"
}
// MARK: Conveinience Init
// Create new project
init(title: String, projectOwner: Project, isChecked: Bool, category: String, isImportant: Bool)
{
super.init()
self.title = title
self.projectOwner = projectOwner
self.isChecked = isChecked
self.category = category
self.isImportant = isImportant
}
override init() { super.init() }
}
The error specifically happens when I try to use the tasks array. I load it into a UICollectionView.
Here's possibly relevant code where I grab the tasks from Parse:
// Fetch data from Parse
func fetchProject() {
let isCurrentTab = navigationController?.tabBarItem.title
let tasksQuery = PFQuery(className: Task.parseClassName())
tasksQuery.whereKey("category", equalTo: isCurrentTab!)
tasksQuery.whereKey("projectOwner", equalTo: project)
tasksQuery.findObjectsInBackgroundWithBlock { (tasks, error) -> Void in
if error == nil {
self.project.tasks.removeAll()
print(tasks)
for task in tasks! {
print(task)
let task = task as! Task
self.project.tasks.append(task)
}
self.collectionView?.reloadData()
} else {
print("\(error?.localizedDescription)")
}
}
}
I'm using Xcode 7.1 and Parse v1.8.5
Any help would be much appreciated!
A: I ended up using pointers to access my tasks array instead of having it nested in the projects array. That way, I could make all of the calls directly to that array and not lose anything by trying to go down to the nested level.
| |
doc_23527865
|
I've got a task to add drag & drop functionality to one of lists in the project.
It should bed easy, because it was used in other place in the project.
So I copied the code from the working component and it didn't work. It was the same part of the application so I thought that it's the same module. So I thought that it can be related to MatDialog and AngularJS router that is used by the project.
A: Always remember to check if the component that you want to add drag & drop to is in the module that imports DragDropModule.
| |
doc_23527866
|
:
f1();
f1 = () => { console.log("f1"); }
But the following works:
exports.x = () => {
f1();
}
f1 = () => { console.log("f1"); }
What's the explanation for the second situation?
A: In the first case the function is being called before it is defined, that's why the error occurs:
f1(); // <- function is called before the function expression is evaluated
f1 = () => { console.log("f1"); }
In the second case the function is not called at all, instead it may be called in future by the module consumer.
exports.x = () => {
f1(); // <- it will be called only if a module consumer will execute the module as a function
}
f1 = () => { console.log("f1"); }
In order to call the module as a function, the module consumer will have to import the module. When a module is imported, all the module code is evaluated (including our function expression). Therefore, by the time the module consumer calls the module as a function, the function expression will be evaluated.
A: You can use any undeclared variable inside a function it will not throw error.
In your above second example the exports.x is not called so there is no error. If you will call that it will throw error.
An example is below
function test(){
console.log(x); //x is not defined still no error.
}
Now see what will happen when we call the function.
function test(){
console.log(x);
}
test();
| |
doc_23527867
|
d = {'a': '1', 'b' : 'blank', 'c' : '[1, 2]'}
I want to transform the original type of the matrix 'str' into another type like 'int' .
Is there any easier solution instead of using for loop?
A: I'd say you need to loop thru your dict for doing that.
If there was only string representation for one datatype you could do something like this.
d = {"a": "10", "b":"15", "c":"0"}
d = dict([(x,int(d[x])) for x in d])
# resulting d = {'a': 10, 'b': 15, 'c': 0}
| |
doc_23527868
|
import matplotlib.pyplot as plt
from scipy import optimize
data = np.genfromtxt('NORMAL.txt')
def gaussian(x, height, center, width, offset):
return height*np.exp(-(x - center)**2/(2*width**2)) + offset
def six_gaussians(x, h1, c1, w1, h2, c2, w2, h3, c3, w3, h4, c4, w4, h5, c5,
w5, h6, c6, w6, h7, c7, w7, h8, c8, w8, offset):
return (gaussian(x, h1, c1, w1, offset=0) +
gaussian(x, h2, c2, w2, offset=0) +
gaussian(x, h3, c3, w3, offset=0) +
gaussian(x, h4, c4, w4, offset=0) +
gaussian(x, h5, c5, w5, offset=0) +
gaussian(x, h6, c6, w6, offset=0) +
gaussian(x, h6, c6, w6, offset=0) +
gaussian(x, h6, c6, w6, offset=0) + offset)
errfunc6 = lambda p, x, y: (six_gaussians(x, *p) - y)**2
guess6 = [28.7, 4.3, 0.01, 27.6, 3.5, 0.01, 53.3, 1.0, 0.5, 28.4, -2.67, 0.5,
44.3, -7.32, 0.5, 34.8, -13.5, 0.1, 20, -11, 10, 23, 3.3, 1, 0] # I guess
there are 8 peaks, 6 are clear, but between them there seems to be another
one, based on the change in slope smoothness there
optim3, success = optimize.leastsq(errfunc6, guess6[:], args=(data[:,0],
data[:,1]))
optim3
plt.plot(data[:,0], data[:,1], lw=5, c='g', label='measurement')
plt.gca().invert_xaxis()
plt.plot(data[:,0], six_gaussians(data[:,0], *optim3),
lw=3, c='b', label='fit of 6 Gaussians')
plt.legend(loc='best')
plt.savefig('result_fitting.png')
this is my code for gaussian fitting.
and i got this fitted data.
but I want to draw the gaussians separately from the fit lines and also get the fitting parameters.
Can anybody help me to do that?
A: You just need to call plt.figure:
plt.savefig('without_gausians.png')
plt.figure()
...
plt.savefig('result_fitting.png')
This calling creates a new figure for plotting, so now you need to save two figures one of which should be before creating the new figure.
| |
doc_23527869
|
I want to know if there is a way to access all the documents it's referencing and, if possible, without extracting the content.xml.
What I managed to do so far is to open the document as a XComponent, to open it's XTextDocument interface (and to extract the text belonging to the document but not the one from the included documents). And I'm unable to gather some useful information from that.
Is there an interface that could help? Or some other stuff?
A: You might want to look into the ODF Toolkit, since the easier parts are Java-based.
The ODF Toolkit project is currently moving to an Apache incubator project.
The current site is here: http://odftoolkit.org/
The new project is at http://incubator.apache.org/odftoolkit/
On the other hand, extracting the content.xml of the .odm might be a better way to go. There is probably some XSLT magic you can use to locate the references to the separate parts.
Also, when you open the master document in an OpenOffice.org consumer, doesn't it show clues about how the constituent documents are found? The one time I messed with this, I noticed that the components had software-generated names that were pretty obvious.
| |
doc_23527870
|
I describe my model in a file called 'model.py' like so:
import pymc
import numpy
#constants
r_div=numpy.loadtxt("r_div", comments="#", unpack=False)
map=numpy.loadtxt("map", comments="#", delimiter=",", unpack=False)
M_star=3*10^6;
#data
n=numpy.loadtxt("n")
#priors
alpha_0=pymc.Uniform('alpha_0end',-10,10, value=0)
logA_0=pymc.Uniform('logA_0end',-10,10,value=-6.1246)
#model
@pymc.deterministic(plot=False)
def r(logA_0=logA_0,alpha_0=alpha_0,M_star=M_star,r_div=r_div):
r=r_div*numpy.exp(logA_0)*((numpy.exp(map[:,1])/M_star)**(alpha_0))
return r
#likelihood
Distribution=pymc.Poisson('Distribution',mu=r,value=n,observed=True)
And then I use the following script in ipython to run the MCMC chain:
import pymc
import model
M=pymc.MCMC(model)
M.sample(100000, burn=10000)
M.summary()
Everything seems to work until the final command M.summary() where I get the error:
AttributeError Traceback (most recent call last)
in ()
----> 1 M.summary()
AttributeError: 'MCMC' object has no attribute 'summary'
I am confident the chain has run successfully as the command M.trace('alpha_0end')[:] shows there are chain elements there but I can't get out any information out about the prior, such as a mean or standard deviation. I've tried different permutations of the summary command. For example: M.alpha_0end.summary()
It would be helpful to know if there is an easy way to get out the standard deviation and means of the priors.
A: I can't run your code, but M.summary() works for me in this minimal example:
In [1]: import pymc as pm
In [2]: pm.__version__
Out[2]: '2.3.2'
In [3]: X = pm.Normal('X', 0, 1)
In [4]: M = pm.MCMC(dict(X=X))
In [5]: M.sample(100000, burn=10000)
[-----------------100%-----------------] 100000 of 100000 complete in 5.0 sec
In [6]: M.summary()
X:
Mean SD MC Error 95% HPD interval
------------------------------------------------------------------
-0.0 1.003 0.003 [-1.897 2.026]
Posterior quantiles:
2.5 25 50 75 97.5
|---------------|===============|===============|---------------|
-1.961 -0.673 0.0 0.675 1.964
A: The summary subroutine was added in February 2012 (a04551094a70451a4afee4e11be8b6872e74fe46). At that time, the version number was 2.2-grad.
If your pm.__version__ is 2.2-grad or lower, you have a version of pymc that is too old to use this function. Version 2.2-beta or later should work.
| |
doc_23527871
|
<form [formGroup]="formGroup">
<md-radio>
[value]="one"
[formControlName]="radioButton"
</md-radio>
<md-radio>
[value]="two"
[formControlName]="radioButton"
[disabled]="disabled_flag"
</md-radio>
</form>
and into code, I created form group:
this.formGroup = this.fb.group({
radioButton: [
{ value: "two", disabled: false },
[],
[],
{ updateOn: blur },
],
});
If I changed disabled_flag into code in true, radio button "two" will be disabled, but I got this message in browser;
It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
you. We recommend using this approach to avoid 'changed after checked' errors.
Example:
form = new FormGroup({
first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
last: new FormControl('Drew', Validators.required)
});
So I need to dynamically change this flag and how to do that properly and skip this warning message, or how to disable radio button properly?
A: You can do something like this. This should work.
this.formGroup = this.fb.group({
radioButton: [
{ value: "two", disabled: this.disabled_flag },
[],
[],
{ updateOn: blur },
],
});
A: Yes, that is a good warning to exist, as it is sometimes "misused" with reactive forms... Disabling the form control won't work, as it will disable all buttons...
How to get rid of the error then? The thing I can think of is using ViewChild to access the element and disable it that way.
<input type="radio" formControlName="radioButton" value="two" #radio />
And TS code:
@ViewChild('radio') radio: ElementRef;
and when you want to disable it just set it to false:
this.radio.nativeElement.disabled = true
| |
doc_23527872
|
Any ideas?
View v = inflater.inflate(R.layout.fragment_hello_moon, parent, false);
TableLayout tl = (TableLayout)v.findViewById(R.id.l1);
TableRow tr = new TableRow(getActivity());
tr.setPadding(50, 0, 50, 0);
TableRow.LayoutParams params = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
ImageView imageL = new ImageView(getActivity());
imageL.setImageResource(R.drawable.bell_dl_256);
ImageView imageR = new ImageView(getActivity());
imageR.setImageResource(R.drawable.bell_dr_256);
imageR.setLayoutParams(params);
tr.addView(imageL);
tr.addView(imageR);
tl.addView(tr);
return v;
A: If I were you, I would use RelativeLayout. Only if two ImageView is enough doing what you want, you can use LinearLayout which orientation property is horizontal. And last advice you can do it in xml layout.
| |
doc_23527873
|
For instance, to get the details of post ID 141, I use this:
ws = GET("https://example.com/wp-json/wp/v2/posts/141")
Works fine because the authentication is through cookies I think, and I'm logged into my Wordpress site.
But I can't POST to my wordpress site because (I think) the cookie-type authorization is not allowed.
So this returns a 401 error:
POST ('example.com/wp-json/wp/v2/posts/141',
body = list(title = "My New Title"))
I think I need to send an authorization header, but I'm not sure how to set that up.
| |
doc_23527874
|
I have copied the angular-quick tutorial setup from the github and incorporate with my MVC project.It is running locally without any problem.
Now I want to publish this apps from Visual Studio 2017 into local IIS server. It appears that the IIS server does not know how to read the system.config.js files.
I am not able to run the apps from the server.
Do I need to move all the node_modules files into IIS server?
Thanks in advance.
A: When your all the development part is done, you can publish it under Internet Information Server (IIS).
Need to create a production bundle of the Angular 4 application and add hooks into the publishing pipeline that also publishes the production bundles of the Angular 4 application with the rest of the deployment to IIS.
To create production bundles of the Angular application,.csproj project file should be edited and added a production build command to the AfterBuild target.
<Target Name="AfterBuild">
<Exec Command="ng build --prod --deploy-url http://localhost/yourproject/dist/" WorkingDirectory="$(ProjectDir)" Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " />
<Exec Command="ng build --deploy-url http://localhost:55499/dist/" WorkingDirectory="$(ProjectDir)" Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' " />
</Target>
Please add below command to the project file which will get executed when publishing the application.
<Exec Command="ng build --prod --deploy-url http://localhost/yourproject/dist/" WorkingDirectory="$(ProjectDir)" Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "/>
| |
doc_23527875
|
Is there a way to take the resulted machine bytecode and decompile it back to a Java file that contains the original type parameters in generic types? Does there exist a decompiler that can achieve this? Or this process is simply irreversible due to the nature of compiling process?
A: You are correct that, at the bytecode level, much information gets lost when you define and interact with generic types. Type erasure was nice for preserving compatibility: if you mostly enforce type safety at compile time, you don't need to do much at runtime, so you can reduce generic types to their 'raw' equivalents.
And that's the key: compile time verification. If you want the flexibility and type safety of generics, your compiler has to know a lot about the generic types you interact with. In many cases, you won't have the source code for those classes, so it has to get the information from somewhere. And it does: metadata. Embedded in the .class file alongside the bytecode is wealth of information: everything the compiler needs to know you're using generic library types safely. So what kind of generics information gets preserved?
Type variables and constraints
The most basic thing a compiler needs to know in order to consume a generic type is the list of type variables. For any generic type or generic method, the names and positions of the type variables are preserved. Moreover, any constraints (upper or lower bounds) get included as well.
Generic supertype signatures
Sometimes you write a class that extends a generic class or implements a generic interface. If you write a StringList that extends ArrayList<String>, you inherit a lot of functionality. If someone wants to use your StringList as intended and without the source code, it's not enough for the compiler to know that you extended ArrayList; it has to know you extended ArrayList<String>. This applies transitively up the hierarchy: it has to know ArrayList<> extends AbstractList<>, and so on. So this information gets preserved. Your class file a will include the complete generic signatures of any generic supertypes (classes or interfaces).
Member signatures
The compiler can't verify that you're using a generic type correctly if it doesn't know the full generic types of fields, method parameters and return types. So, you guessed it: that information gets included. If any part of a class member contains a generic type, wildcard, or type variable, that member will get its signature information saved in the metadata.
Local variables
It's not necessary to preserve information about local variable types in order to consume a type. It can be useful for debugging, but that's about it. There are metadata tables that can be used to record the names and types of variables, and the bytecode ranges at which they exist. Depending on the compiler, they may or may not be written by default. You can force javac to emit them by passing -g:vars, but I believe they're omitted by default
Call sites
One of the biggest issues for decompilers, mostly affecting generic inference within method bodies, is that call sites invoking generic methods retain no information about type arguments. That creates huge headaches for APIs like Java 8 Streams, where generic operators get chained together, each one accepting anonymously typed lambdas (which may be contravariant in their argument types and covariant in their return types). That's a type inference nightmare, but it's an issue for any code that happens to interact with generics. That kind of code doesn't become substantially harder to decompile simply because it exists within a generic type.
How this affects decompilation
Modern Java decompilers like Procyon and CFR should be able to reconstruct generic types reasonably well. If the local variable metadata is available, the results should be pretty close to the original code. If not, they'll have to try to infer generic type arguments in method bodies based on data flow analysis. Essentially, the decompiler must look at what data flows in and out of generic instantiations, and use what it knows about the type of that data to guess the type arguments. Sometimes it works really well; other times, not so much (see earlier comment about Java 8 Streams).
At the API level, though—type and member signatures—the results should be spot-on.
Caveats
Strictly speaking, all of the metadata described here is optional: it's only needed at compile time (or decompile time). If someone has run their compiled classes through an obfuscator, optimizer, or some other utility, all of this information could get stripped out. It won't make a difference at runtime.
tldr; Conclusion
Yes, it is certainly possible to decompile generic types and methods with their type parameters intact. Assuming the required metadata is present, getting the type and member signatures right is the 'easy' part. Correctly inferring the type arguments of generic instances and method invocations is the tricky bit, but that's a problem for any code that happens to interact with generics.
As mentioned, Procyon and CFR should both do a pretty decent job of restoring generic types and methods.
A: That depends mostly on whether the code has been obfuscated. While it is true that generics use type erasure, compilers typically include source level information such as generic types as metadata in the classfile for various reasons - reflection, debugging, compilation against closed source libraries, etc.
So for a well behaved classfile, it should be possible to get the information back. Whether there are any off the shelf tools for this, I don't know. A lot of decompilers do try to recover generic types, but I don't know how reliable they are.
If the code has been obfuscated, then all the metadata will be stripped out, so there is no hope of recovering the original generic types.
A: Yes ,this is called as decompilation process to convert machine code or we can say it as byte code to its original source code but till some extent !
There are some decompilers are do exist!
What you need is to get some help of decompilers and put little bit of your efforts in order to convert this byte code to its generic type as you said.
But it's not possible to do such reverse engineering process with high accuracy ratio as the modern compilers are designed in such a way that they go through several steps in order to convert that source code to its machine code so what you can get back after reversing is a just Non human readable form assembly code but the same work can be done easily till some extent with the help of decompilers.
"The java decompiler project " or JD project is the thing what I talk about
http://jd.benow.ca
Hope it makes your concept clear!
| |
doc_23527876
|
function copyData() {
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = spreadSheet.getSheetByName('copiedPausingSheet');
let sourceRange = sourceSheet.getDataRange();
let sourceValues = sourceRange.getValues();
let rowCount = sourceValues.length;
let columnCount = sourceValues[0].length;
let targetSheet = spreadSheet.getSheetByName('collectivePausingData');
let lastrowCount = targetSheet.getLastRow() + 1;
let targetRange = targetSheet.getRange(lastrowCount,1, rowCount,columnCount);
targetRange.setValues(sourceValues);
}
A: Is that what you mean? Paste values on the top of the sheet.
function copyData() {
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = spreadSheet.getSheetByName('copiedPausingSheet');
let sourceRange = sourceSheet.getDataRange();
let sourceValues = sourceRange.getValues();
let rowCount = sourceValues.length;
let columnCount = sourceValues[0].length;
let targetSheet = spreadSheet.getSheetByName('collectivePausingData');
targetSheet.insertRows(1,sourceValues.length);
let targetRange = targetSheet.getRange(1,1,sourceValues.length,sourceValues[0].length);
targetRange.setValues(sourceValues);
}
A: Do you mean this?
function copyDataOnTop() {
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = spreadSheet.getSheetByName('copiedPausingSheet');
let sourceRange = sourceSheet.getDataRange();
let sourceValues = sourceRange.getValues();
let targetSheet = spreadSheet.getSheetByName('collectivePausingData');
var targetValues = targetSheet.getDataRange().getValues();
var allValues = [...sourceValues, ...targetValues];
let targetRange = targetSheet.getRange(1,1,allValues.length,allValues[0].length);
targetRange.setValues(allValues);
}
| |
doc_23527877
|
The significance of the fixed variable is changed with a random structure.
For example, suppose there are 5 variables:
RT(response variable), covariate variable1(C.V.1), C.V.2, I.V.1, I.V.2.
all variables are within-subject variables excepting RT.
What I want to know is the interaction of I.V.2 and I.V.2.
In this situation, I set the two models using lmer().
First is that:
m1 <- lmer(rt ~ C.V.1 + C.V.2 + I.V.1*I.V.2 + (1+C.V.1 + C.V.2 + I.V.1*I.V.2|subject) + (1|word))
and second is that:
m2 <- lmer(rt ~ C.V.1 + C.V.2 + I.V.1*I.V.2 + (1+ I.V.1*I.V.2|subject) + (1|word))
when I analyzed this two models, the significance of fixed variable is different between the two models.
For example, the interaction of I.V.1 and I.V.2 is significant in m1, but not in m2.
I know setting the subject intercept means the responses would be different from each subject and setting the subject slope for I.V.1 means the effect of I.V.1 would be different from each subject.
But I don't know the relationship between fixed effects and random effects.
What is the meaning that considering random effects?
Can I interpret the result of the estimate of fixed variable as a coefficient when controlling the effect of other random effects like covariate variable?
And why the significance of fixed effect is changed with a random structure like the above two models?
Thank you for reading and I hope anyone would explain me these.
| |
doc_23527878
|
//array1 has already been set to "The dog jumps "
//array2 has already been set to "over the log"
append(array2,array1);
cout << array1;
//would output "The dog jumps over the log";
This is a pretty easy function to make I would think, I am just surprised there isn't a built in command for it.
*Edit
I should have been more clear, I didn't mean changing the size of the array. If array1 was set to 50 characters, but was only using 10 of them, you would still have 40 characters to work with. I was thinking an automatic command that would essentially do:
//assuming array1 has 10 characters but was declared with 25 and array2 has 5 characters
int i=10;
int z=0;
do{
array1[i] = array2[z];
++i;
++z;
}while(array[z] != '\0');
I am pretty sure that syntax would work, or something similar.
A: If your arrays are character arrays(which seems to be the case), You need a strcat().
Your destination array should have enough space to accommodate the appended data though.
In C++, You are much better off using std::string and then you can use std::string::append()
A: You should have enough space for array1 array and use something like strcat to contact array1 to array2:
char array1[BIG_ENOUGH];
char array2[X];
/* ...... */
/* check array bounds */
/* ...... */
strcat(array1, array2);
A: If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.
#include <cstring>
#include <iostream>
int main()
{
char array1[] ="The dog jumps ";
char array2[] = "over the log";
char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
std::strcpy(newArray,array1);
std::strcat(newArray,array2);
std::cout << newArray << std::endl;
delete [] newArray;
return 0;
}
This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.
Edit, a safe version with the "enough buffer space" assumption:
#include <cstring>
#include <iostream>
int main()
{
const unsigned BUFFER_SIZE = 50;
char array1[BUFFER_SIZE];
std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
char array2[] = "over the log";
std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
std::cout << array1 << std::endl;
return 0;
}
A: There's no built-in command for that because it's illegal. You can't modify the size of an array once declared.
What you're looking for is either std::vector to simulate a dynamic array, or better yet a std::string.
std::string first ("The dog jumps ");
std::string second ("over the log");
std::cout << first + second << std::endl;
| |
doc_23527879
|
I'm looking for a way to go through sites (basically read the html), using the HttpClient. I'm making an app for windows phone, so some options may be disabled.
I want to make a program that goes to a site, logs in, and then is able to retrieve the access html source code.
So when I log in, a session id is saved in a CookieContainer, so I'll be able to access the sites that require login. How would I do this using the HttpClient :)?
A: HttpClient manages authentication cookies automatically for you. Just make sure you re-use the same HttpClient instance for multiple requests. Under the covers, HttpClient creates an instance of HttpClientHandler which has a CookieContainer.
Here is an example that logs into the NerdDinner site and retrieves a secured page.
var httpClient = new HttpClient();
// Create login payload
var body = new Dictionary<string, string>()
{
{"UserName", "bob"},
{"Password", "xyz"},
{"RememberMe", "false"}
};
var content = new FormUrlEncodedContent(body);
// POST to login form
var response = await httpClient.PostAsync("http://www.nerddinner.com/Account/LogOn?returnUrl=%2F", content);
// Make new request to secured resource
var myresponse = await httpClient.GetAsync("http://www.nerddinner.com/Dinners/My");
var stringContent = await myresponse.Content.ReadAsStringAsync();
| |
doc_23527880
|
I want to create a user-defined command which will insert the word foo before the current word.
(Note: I want it to be a function because I don't trust myself to remember yet another shortcut key. I know how to do it with noremap...)
In my .vimrc I add:
command AddFoo bifoo<esc>w
But when I type :AddFoo I get Not an editor command: bifoow.
Is it possible to have a function which issues normal mode commands?
A: The :normal Ex command allows to issue arbitrary normal mode commands.
command AddFoo normal! bifoo<esc>w
If you want to interpolate expressions etc., you need to use :execute; I'll just show your example again with the use of :help key-notation:
command AddFoo execute "normal! bifoo\<esc>w"
The ! after :normal prevents the use of custom mappings, like :noremap (vs :map).
A: Please make sure you get the difference between a command and a function.
The right hand side of a command definition is supposed to be at least one Ex command like write or bnext:
command! Foo update | tabnext
You can call a function:
command! Bar call Bar()
or execute a normal mode macro:
command! Baz normal ciw"<C-r>""
See :help :normal.
A: Should be simple to get what you want, you just need to switch to normal mode to make your changes:
command AddFoo normal bifoo<esc>w
| |
doc_23527881
|
/home/jenn/web/web-starter-kit/node_modules/browser-sync/node_modules/serve-static/node_modules/send/node_modules/etag/index.js:55
throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
^
TypeError: argument entity must be string, Buffer, or fs.Stats
at etag (/home/jenn/web/web-starter-kit/node_modules/browser-sync/node_modules/serve-static/node_modules/send/node_modules/etag/index.js:55:11)
at SendStream.setHeader (/home/jenn/web/web-starter-kit/node_modules/browser-sync/node_modules/serve-static/node_modules/send/index.js:724:15)
at SendStream.send (/home/jenn/web/web-starter-kit/node_modules/browser-sync/node_modules/serve-static/node_modules/send/index.js:500:8)
at /home/jenn/web/web-starter-kit/node_modules/browser-sync/node_modules/serve-static/node_modules/send/index.js:630:12
at Object.oncomplete (fs.js:93:15)
Please help!
@agconti, you didn't specify which gulpfile.js you wanted so I've included Web Starter Kit's and BrowserSync's in that order:
Web Starter Kit
'use strict';
// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;
var AUTOPREFIXER_BROWSERS = [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.4',
'bb >= 10'
];
// Lint JavaScript
gulp.task('jshint', function () {
return gulp.src('app/scripts/**/*.js')
.pipe(reload({stream: true, once: true}))
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});
// Optimize Images
gulp.task('images', function () {
return gulp.src('app/images/**/*')
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('dist/images'))
.pipe($.size({title: 'images'}));
});
// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
return gulp.src([
'app/*',
'!app/*.html',
'node_modules/apache-server-configs/dist/.htaccess'
], {
dot: true
}).pipe(gulp.dest('dist'))
.pipe($.size({title: 'copy'}));
});
// Copy Web Fonts To Dist
gulp.task('fonts', function () {
return gulp.src(['app/fonts/**'])
.pipe(gulp.dest('dist/fonts'))
.pipe($.size({title: 'fonts'}));
});
// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
// For best performance, don't add Sass partials to `gulp.src`
return gulp.src([
'app/styles/*.scss',
'app/styles/**/*.css',
'app/styles/components/components.scss'
])
.pipe($.changed('styles', {extension: '.scss'}))
.pipe($.rubySass({
style: 'expanded',
precision: 10
}))
.on('error', console.error.bind(console))
.pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
.pipe(gulp.dest('.tmp/styles'))
// Concatenate And Minify Styles
.pipe($.if('*.css', $.csso()))
.pipe(gulp.dest('dist/styles'))
.pipe($.size({title: 'styles'}));
});
// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
var assets = $.useref.assets({searchPath: '{.tmp,app}'});
return gulp.src('app/**/*.html')
.pipe(assets)
// Concatenate And Minify JavaScript
.pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
// Remove Any Unused CSS
// Note: If not using the Style Guide, you can delete it from
// the next line to only include styles your project uses.
.pipe($.if('*.css', $.uncss({
html: [
'app/index.html',
'app/styleguide.html'
],
// CSS Selectors for UnCSS to ignore
ignore: [
/.navdrawer-container.open/,
/.app-bar.open/
]
})))
// Concatenate And Minify Styles
// In case you are still using useref build blocks
.pipe($.if('*.css', $.csso()))
.pipe(assets.restore())
.pipe($.useref())
// Update Production Style Guide Paths
.pipe($.replace('components/components.css', 'components/main.min.css'))
// Minify Any HTML
.pipe($.if('*.html', $.minifyHtml()))
// Output Files
.pipe(gulp.dest('dist'))
.pipe($.size({title: 'html'}));
});
// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));
// Watch Files For Changes & Reload
gulp.task('serve', ['styles'], function () {
browserSync({
notify: false,
// Run as an https by uncommenting 'https: true'
// Note: this uses an unsigned certificate which on first access
// will present a certificate warning in the browser.
// https: true,
server: ['.tmp', 'app']
});
gulp.watch(['app/**/*.html'], reload);
gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
gulp.watch(['app/scripts/**/*.js'], ['jshint']);
gulp.watch(['app/images/**/*'], reload);
});
// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
browserSync({
notify: false,
// Run as an https by uncommenting 'https: true'
// Note: this uses an unsigned certificate which on first access
// will present a certificate warning in the browser.
// https: true,
server: 'dist'
});
});
// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});
// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
// By default, we use the PageSpeed Insights
// free (no API key) tier. You can use a Google
// Developer API key if you have one. See
// http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
url: 'https://example.com',
strategy: 'mobile'
}));
// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
BrowserSync
"use strict";
var gulp = require("gulp");
var jshint = require("gulp-jshint");
var contribs = require("gulp-contribs");
var rubySass = require("gulp-ruby-sass");
var filter = require("gulp-filter");
var browserSync = require("./index");
gulp.task("lint", function () {
gulp.src([
"*.js",
"lib/**/*.js",
"!lib/cli/cli-template.js",
"!lib/public/socket.io.js",
"test/specs/**/*.js",
"!test/fixtures/**"
])
.pipe(jshint("test/specs/.jshintrc"))
.pipe(jshint.reporter("default"))
.pipe(jshint.reporter("fail"));
});
gulp.task("contribs", function () {
gulp.src("README.md")
.pipe(contribs())
.pipe(gulp.dest("./"));
});
gulp.task("default", ["lint"]);
var paths = {
scss: "test/fixtures/scss/*.scss",
css: "test/fixtures/css",
cssGlob: "test/fixtures/assets/*.css",
html: "test/fixtures/*.html"
};
gulp.task("sass", function () {
browserSync.notify("Compiling SCSS files... Please Wait");
return gulp.src(paths.scss)
.pipe(rubySass({sourcemap: true}))
.pipe(gulp.dest(paths.css))
.pipe(filter("**/*.css"))
.pipe(browserSync.reload({stream:true}));
});
/**
* Start BrowserSync
*/
gulp.task("browser-sync", function () {
// var clientScript = require("/Users/shakyshane/Sites/browser-sync-modules/browser-sync-client/index");
//
// browserSync.use("client:script", clientScript.middleware, function (err) {
// console.log(err);
// });
browserSync({
server: {
baseDir: "test/fixtures"
},
startPath: "sass.html"
});
});
/**
* Start BrowserSync
*/
gulp.task("browser-sync-css", function () {
browserSync({
server: {
baseDir: "test/fixtures"
}
});
});
///**
// * Reload task
// */
//gulp.task("bs-reload", function () {
// browserSync.reload();
//});
/**
* Watch stuff
*/
gulp.task("watch", ["browser-sync"], function () {
gulp.watch(paths.scss, ["sass"]);
// gulp.watch(paths.html, ["bs-reload"]);
});
/**
* Watch stuff
*/
gulp.task("watch-css", ["browser-sync-css"], function () {
gulp.watch(paths.cssGlob, function (file) {
browserSync.reload(file.path);
});
gulp.watch(paths.html, browserSync.reload);
});
gulp.task("docs", function () {
var yuidoc = require("gulp-yuidoc");
gulp.src(["./index.js", "./lib/default-config.js"])
.pipe(yuidoc.parser({spaces: 4}))
.pipe(gulp.dest("./doc"));
});
UPDATE
I just tried following these same steps to install Web Starter Kit on a separate Mac computer and was able to successfully get a response from BrowserSync when I ran gulp serve. Does anyone know why I am able to run this without error on a Mac but run into this problem when I try it with Ubuntu 14.04?
A: There's an error with Node 0.11.13 and send & etag dependencies of browser-sync.
I posted a bug:
https://github.com/visionmedia/send/issues/63
For now, you can downgrade to Node 0.11.12 or 0.10.x.
| |
doc_23527882
|
@SuppressWarnings("serial")
public class Ping extends HttpServlet
{
@Override
public void doGet(@SuppressWarnings("unused") HttpServletRequest xiReq,
HttpServletResponse xiResp)
throws IOException
{
xiResp.setContentType("text/plain");
xiResp.getWriter().println("PONG");
}
}
I have then written a java program to make a request every second to this servlet and time how long it takes to complete the request. Fetching the page content uses the following code.
private static String getPageContent(String url) throws IOException {
String result = null;
URL reqURL = new URL(url);
URLConnection connection = reqURL.openConnection();
connection.setConnectTimeout(30 * 1000);
connection.setReadTimeout(30 * 3000);
InputStream webStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(webStream));
result = reader.readLine();
reader.close();
return result;
}
Every 3 minutes my monitor script outputs data in the following format:
date,num_reqs,num_failedreqs,avg_reqtime,num_normreqs,avg_normreqtime,num_latereqs,avg_latereqtime
normrequests are all requests which take less than 500ms to complete
latereqs are all requests which take longer than 500ms to complete
failreqs are any which throw an IO exception during the download or if the content received is not equal to "PONG"
My output for the last ~20 minutes is as follows:
Thu Nov 25 10:04:01 GMT 2010,300,0,186,295,171,5,1093
Thu Nov 25 10:09:28 GMT 2010,300,0,191,292,173,8,842
Thu Nov 25 10:14:52 GMT 2010,300,0,184,295,167,5,1177
Thu Nov 25 10:20:15 GMT 2010,300,0,182,294,168,6,876
Thu Nov 25 10:25:46 GMT 2010,300,0,172,298,167,2,827
This shows that in each 5 minute period there are between 2 and 8 "late" requests taking an average of between 827 and 1177ms to complete.
This compares with the following output from the same period running against the same servlet on a micro instance running on Amazon EC2.
Thu Nov 25 10:03:53 GMT 2010,300,0,177,300,177,0,0
Thu Nov 25 10:09:20 GMT 2010,300,0,179,299,178,1,583
Thu Nov 25 10:14:43 GMT 2010,300,0,176,299,175,1,545
Thu Nov 25 10:20:07 GMT 2010,300,0,176,299,175,1,531
Thu Nov 25 10:25:37 GMT 2010,300,0,181,298,178,2,669
This shows far fewer "late" requests and the response time for these slow requests is much lower.
I am making my requests from a server based in the UK. My Amazon EC2 instance is running in "US East". I don't know where Google is running my AppEngine instance.
Can I do anything to improve the consistency of AppEngine response times or is the variance I am seeing normal for AppEngine?
A: The 'late' requests you're seeing are due to App Engine spinning up a new Java runtime to handle your request. App Engine increases the number of instances of your app it's running on demand, and spins down idle instances after some period of inactivity.
This behaviour is much more visible for low-traffic apps, because even an individual user can cause a spike that requires new runtimes to be spun up, and instances are more likely to be shut down for inactivity. As the traffic to your app increases, the number of warm-up requests you see will decrease in proportion to the traffic.
A: As far as I can tell the variance is simply a property of the network which Google are using.
| |
doc_23527883
|
A: (Spyder maintainer here) Such old Spyder versions don't have support for high resolution screens. Besides, I think PythonXY is unmaintained right now (last release was in 2015).
So you basically have two options: 1. Download and install Anaconda, which comes with Spyder and the most important Python scientific libraries, and it's also is what we recommend; or 2. Download Python 3 from its website and then use pip to install Spyder. However, option 2. is for experts because a lot of things can go wrong with it.
| |
doc_23527884
|
When registering for user update push notification, is it posting to my url, when any of the security parameters are changed? parameters such as Authorized access?
(The case as follows: A new user of my domain installs a new application. I want to get a push notification for that event)
Thank you!
| |
doc_23527885
|
I have already used the Levenshtein distance which could give me a meaningful result in these terms, but I am not fully satisfied.
I am now trying with Cosine Similarity after reading an article which I found interesting.
I have studied the documentation and I read some article but at this point in time, I think I have not understood the algorithm capabilities.
I am able to use it when I have terms as words.
e.g.
docs <- c ("open letters", "closed letters", "letters)
terms <- "open", "closed", "letters")
But I am not able to ask the system to treat every single letter
c ("a", "b", "c", "d")
That would lead to having a string comparison using the Term Document Matrix.
But maybe there is already my mistake.
What would it be to implement in tm a single word string comparison?
Thank you for your help,
P.s. I have not posted code because it is a more general question but I can create an example in case.
Nicola
Here is the working code as per suggestion:
doc <- c( "closed door", "Open door", "door", "doo", "oor", "house" )
doc_corpus <- Corpus( VectorSource(doc) )
control_list <- list(removePunctuation = TRUE, tolower = TRUE)
tdm <- DocumentTermMatrix(doc_corpus, control = character_tokenize(doc))
tf <- as.matrix(tdm)
A: This is what I have understood I can do.
Give a document, in my case "doc" vector of strings, the system will provide me the TDM matrix where the terms will be 1 if the match is fully activated (e.g. closed -> closed door) but door will not match with oor.
Example:
library(tm)
doc <- c( "closed door", "Open door", "door", "doo", "oor", "house" )
doc_corpus <- Corpus( VectorSource(doc) )
control_list <- list(removePunctuation = TRUE, tolower = TRUE)
tdm <- TermDocumentMatrix(doc_corpus, control_list)
tf <- as.matrix(tdm)
The point is that I have read I could also do it something like this, where the terms are the single letters, and I would like to confirm if this is a possibility
so to have a TDM to build then cosine distance to calculate the distance between to strings.
But I could not find anything into the documentation.
Thank you for you help,
Nicola
| |
doc_23527886
|
@def PANEL_BACKGROUND #eaeafc;
This gives the error "Unexpected token HASH found".
I couldn't find a plugin to properly validate GSS. Is there a way to customize this? I found that clicking the little error bubble gives me the option to disable these errors, though if possible, I'd like GSS to validate properly.
| |
doc_23527887
|
A: For UITableView specifically you can use:
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
superview?.endEditing(true)
}
This will end editing when the table view is dragged.
In a more general sense, the endEditing(Bool) function, when called on a UIView, looks through the views entire sub hierarchy and if an editing text element is found will resign it. The parameter is to determine whether the view should be asked to resign as first responder or simply be forced to resign as first responder.
As per documentation: "This method looks at the current view and its subview hierarchy for the text field that is currently the first responder. If it finds one, it asks that text field to resign as first responder. If the force parameter is set to true, the text field is never even asked; it is forced to resign."
This means that you can call endEditing(true) directly within didSelectItemAt, just make sure you call it on a view that has the search bar as a subview. Or just call it on the search bar itself.
| |
doc_23527888
|
A: I can't believe, that it is so.
Change primitive type for object type in your entity(Example: int -> Integer)
A: To differentiate between 0 and NULL you should use ResultSet.wasNull() method, like here:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
st.executeUpdate("create table survey (id int,name varchar(30));");
st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
st.executeUpdate("insert into survey (id,name ) values (2,null)");
st.executeUpdate("insert into survey (id,name ) values (3,'Tom')");
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
while (rs.next()) {
String name = rs.getString(2);
if (rs.wasNull()) {
System.out.println("was NULL");
} else {
System.out.println("not NULL");
}
}
rs.close();
st.close();
conn.close();
}
A: The way I solved it is the following:
Integer id;
Object o = rs.getObject("ID_COLUMN");
if(o!=null){
id = (Integer) o;
} else {
id = null;
}
| |
doc_23527889
|
EDIT: The user has to input the email address it wants to sent to, but it only works with 1, which is why I'm asking for help on how I can edit the code to work with multiple emails/recipients and to be separated with a comma and space.
Here is the code
<?php
if(isset($_POST['email'])) {
$email_to = array($_GET["celebrant_emails"]);
$email_subject = "Email from website Contact Form";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the email you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go <a href='http://celebrantsaustralia.asn.au/celebrants-trial.htm'>back</a> and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['comments']) ||
!isset($_POST['celebrant_emails'])) {
died('We are sorry, but there appears to be a problem with the email you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$comments = $_POST['comments']; // required
$celebrant_emails = $_POST['celebrant_emails']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Message you entered does not appear to be valid.<br />';
}
if(!preg_match($email_exp,$celebrant_emails)) {
$error_message .= 'The Celebrant Email(s) you entered does not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Email details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Message: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
<html>
<head>
<title>Email sent!</title>
</head>
<body>
<b>Thank you for contacting us. We will be in touch with you shortly.</b>
<p>(Page will auto-direct in a moment, if it doesn't click <a href="http://website.com">here</a>)</p>
</body>
</html>
<?php
}
?>
A: There are numerous ways of doing this.
$email_to = "jhewitt@amleo.com,some@other.com,yet@another.net";
$email_to = 'Mary <mary@example.com>, Kelly <kelly@example.com>';
If you need to add emails as CC or BCC, add the following part in the variable you use as for your header :
$headers .= "CC: sombodyelse@noplace.com".PHP_EOL;
$headers .= "BCC: hidden@special.com".PHP_EOL;
Source: PHP form send email to multiple recipients
Also check here: Example #1 Sending mail.
A: $email=$_POST['email']; // write multiple emails with comma's
$emails=explode(',', $email); // explode email with comma's
foreach($emails as $one_email)
{
$touser=$one_email;
$subjectAdmin= "subject";
$headersAdmin = "From: noreply@talentswype.com\r\n";
$headersAdmin .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$messageuser ='msg here';
$emailSenduser = mail($touser,$subjectAdmin,$messageuser,$headersAdmin);
}
A: Write one mail function per email.
mail('example1@example.com', 'My Subject', $message);
mail('example2@example.com', 'My Subject', $message);
mail('example3@example.com', 'My Subject', $message);
mail('example4@example.com', 'My Subject', $message);
mail('example5@example.com', 'My Subject', $message);
or
foreach($mail as $mails ){
mail($mail, 'My Subject', $message);
}
| |
doc_23527890
|
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/tools/ant/launch/Launcher : Unsupported major.minor version 52.0
| |
doc_23527891
|
my structure look something like this:
<nav>
<ul>
<li class="has-children"><a href="#">Home
<span class="arrow arrow-down"></span>
</a>
<ul class="top-menu">
<li class="has-children"><a href="#">Item1
<span class="arrow arrow-down arrow-right"></span>
</a>
<ul class="submenu">
<li><a href="#">SubItem - 1 </a></li>
<li><a href="#">SubItem - 2 </a></li>
<li><a href="#">SubItem - 3</a></li>
<li><a href="#">SubItem - 4 </a></li>
<li><a href="#">SubItem - 5 </a></li>
</ul>
</li>
<li class="has-children"><a href="#">Item - 2
<span class="arrow arrow-down arrow-right"></span>
</a>
<ul class="submenu">
<li><a href="#">SubItem - 1 </a></li>
<li><a href="#">SubItem - 2 </a></li>
<li><a href="#">SubItem - 3</a></li>
<li><a href="#">SubItem - 4 </a></li>
<li><a href="#">SubItem - 5 </a></li>
</ul>
</li>
<li class="has-children"><a href="#">Item - 3
<span class="arrow arrow-down arrow-right"></span>
</a>
<ul class="submenu">
<<li><a href="#">SubItem - 1 </a></li>
<li><a href="#">SubItem - 2 </a></li>
<li><a href="#">SubItem - 3</a></li>
<li><a href="#">SubItem - 4 </a></li>
<li><a href="#">SubItem - 5 </a></li>
</ul>
</li>
<li><a href="#">Item - 4 </a></li>
<li><a href="#">Item - 5 </a></li>
</ul>
</li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
and this is my jQuery:
$('.has-children ul').click(function(e){
e.stopPropagation();
var el = (event.target || event.srcElement);
console.log('clicked');
$(this).find('ul.submenu').slideToggle();
$(el).find('span').toggleClass('arrow-down arrow-up');
});
So if I click on the li with the class of has children, all my uls with class of submenu are opening at the same time.
Perhaps I am doing more than I am supposed to here, all the help would be appreciate it.
A: try this code (i have added more correct span finding)
$('.has-children ul').click(function(e){
e.stopPropagation();
var el = (event.target || event.srcElement);
console.log('clicked');
$(this).find('ul.submenu').slideToggle();
$(this).parent().find('span').toggleClass('arrow-down arrow-up');
});
A: Your event listener should be on .has-children, and you only want to go one level deep in your $.find() which you can do with $.find('> ul')
$('.has-children').click(function(e) {
e.stopPropagation();
var el = (event.target || event.srcElement);
console.log('clicked');
$(this).find('> ul').slideToggle();
$(el).find('span').toggleClass('arrow-down arrow-up');
});
.submenu, .top-menu {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<ul>
<li class="has-children"><a href="#">Home
<span class="arrow arrow-down"></span>
</a>
<ul class="top-menu">
<li class="has-children"><a href="#">Item1
<span class="arrow arrow-down arrow-right"></span>
</a>
<ul class="submenu">
<li><a href="#">SubItem - 1 </a></li>
<li><a href="#">SubItem - 2 </a></li>
<li><a href="#">SubItem - 3</a></li>
<li><a href="#">SubItem - 4 </a></li>
<li><a href="#">SubItem - 5 </a></li>
</ul>
</li>
<li class="has-children"><a href="#">Item - 2
<span class="arrow arrow-down arrow-right"></span>
</a>
<ul class="submenu">
<li><a href="#">SubItem - 1 </a></li>
<li><a href="#">SubItem - 2 </a></li>
<li><a href="#">SubItem - 3</a></li>
<li><a href="#">SubItem - 4 </a></li>
<li><a href="#">SubItem - 5 </a></li>
</ul>
</li>
<li class="has-children"><a href="#">Item - 3
<span class="arrow arrow-down arrow-right"></span>
</a>
<ul class="submenu">
<li><a href="#">SubItem - 1 </a></li>
<li><a href="#">SubItem - 2 </a></li>
<li><a href="#">SubItem - 3</a></li>
<li><a href="#">SubItem - 4 </a></li>
<li><a href="#">SubItem - 5 </a></li>
</ul>
</li>
<li><a href="#">Item - 4 </a></li>
<li><a href="#">Item - 5 </a></li>
</ul>
</li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
A: by using this code toggle sub item when click on Item and when click on sub item it wont toggle item
$('.has-children > a').click(function (e) {
e.stopPropagation();
var el = (event.target || event.srcElement);
console.log('clicked');
$(this).parent().find('ul.submenu').slideToggle();
$(el).find('span').toggleClass('arrow-down arrow-up');
});
| |
doc_23527892
|
.tabs td.line + td.line {
border-left: 1px solid grey;
}
<table cellspacing="0" cellpadding="0" class="tabs" style="border-bottom: 5px solid black" width="100%">
<tr>
<td height="10px">
</td>
</tr>
<tr>
<td valign="center" align="center" style="padding: 10px 0" class="line">
<table>
<tr>
<td>
something
</td>
<td valign="center">
something else
</td>
</tr>
</table>
</td>
<td valign="center" align="center" style="padding: 10px 0" class="line">
<table>
<tr>
<td>
something
</td>
<td valign="center">
something else
</td>
</tr>
</table>
</td>
<td valign="center" align="center" style="padding: 10px 0" class="line">
<table>
<tr>
<td>
something
</td>
<td valign="center">
something else
</td>
</tr>
</table>
</td>
</tr>
</table>
This doesn't work as expected. Was expecting it to go to first table, find direct descendant tr and apply it to direct descendant td.
.tabs > tr > td + td {
border-left: 1px solid grey;
}
<table cellspacing="0" cellpadding="0" class="tabs" style="border-bottom: 5px solid black" width="100%">
<tr>
<td height="10px">
</td>
</tr>
<tr>
<td valign="center" align="center" style="padding: 10px 0" class="line">
<table>
<tr>
<td>
something
</td>
<td valign="center">
something else
</td>
</tr>
</table>
</td>
<td valign="center" align="center" style="padding: 10px 0" class="line">
<table>
<tr>
<td>
something
</td>
<td valign="center">
something else
</td>
</tr>
</table>
</td>
<td valign="center" align="center" style="padding: 10px 0" class="line">
<table>
<tr>
<td>
something
</td>
<td valign="center">
something else
</td>
</tr>
</table>
</td>
</tr>
</table>
Basically wondering only about the css part.
| |
doc_23527893
|
if (RegOpenKeyEx (HKEY_CURRENT_USER,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce",0, KEY_SET_VALUE, &hk1) == ERROR_SUCCESS)
{
RegSetValueEx(hk1, // subkey handle
"", // value name
0, // must be zero
REG_SZ, // value type
(LPBYTE) &path, sizeof(DWORD)); // length of value data
RegCloseKey(hk1);
}
However my application does not start after a system restart.
A: There are a few methods:
*
*Place your application in your start-up folder. This is a very easy method. When your system (PC) will be restarted, the application will get started (You need to login for this);
*Use windows task planner;
*Make the application an service.
I prefer the last option if it always needs to run. But you will need to add service handling.
A: You can create a task using Task Scheduler to run your application when the computer starts.
*
*Open Task Scheduler by clicking the Start button , clicking Control Panel, clicking System and Security, clicking Administrative Tools, and then double-clicking Task Scheduler. If you're prompted for an administrator password or confirmation, type the password or provide confirmation.
*Click the Action menu, and then click Create Basic Task.
*Type a name for the task and an optional description, and then click Next.
*Click When the computer starts, and then click Next.
*To schedule a program to start automatically, click Start a program, and then click Next.
*Click Browse to find the program you want to start, and then click Next.
*Select the Open the Properties dialog for this task when I click Finish check box and click Finish.
*In the Properties dialog box, select Run whether user is logged on or not, and then click OK
Source:
Windows 7 - Schedule a task
PS: You must be logged on as an administrator to perform these steps
A: There are a number of things to keep in mind when using the solution you opted for:
*
*The application does not start when the system starts but rather when the current user logs on.
*If you write to the RunOnce key the operation will be performed only once. If you want your application to always start when the user logs on you should instead use the Run key.
In addition to the above, if you want to create a value you will have to give it a name. From the documentation of the lpValueName parameter for RegSetValueEx:
If lpValueName is NULL or an empty string, "", the function sets the type and data for the key's unnamed or default value.
The default (unnamed) value is the one that shows up as (Default) when using regedit. To get this to work you will have to provide a name for the value. This should be unique so that it does not conflict with other values under that key.
On a less technical note, implementing an auto-start feature for an application should only be done after thorough consideration.
A: You are passing the wrong parameter values to RegSetValueEx(). You need to use it like this instead:
TCHAR path[MAX_PATH+1] = {0}
GetModuleFileName(NULL, path, MAX_PATH);
if (RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce"), 0, KEY_SET_VALUE, &hk1) == ERROR_SUCCESS)
{
RegSetValueEx(hk1, // subkey handle
TEXT("MyApp"), // value name
0, // must be zero
REG_SZ, // value type
(LPBYTE) path,
(lstrlen(path)+1) * sizeof(TCHAR)); // length of value data, in bytes
RegCloseKey(hk1);
}
| |
doc_23527894
|
Would it be possible to use the DSUM function using VBA?
A: You would be better of with a custom function:
Public Function AmountLentSum() As Currency
Dim rs As DAO.Recordset
Dim AmountSum As Currency
Set rs = Me!NameOfSubformControl.Form.RecordsetClone
While Not rs.EOF
If rs!YourCheckBox.Value = True Then
AmountSum = AmountSum + Nz(rs!Amount_Lent.Value, 0)
End If
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
AmountLentSum = AmountSum
End If
Then use as ControlSource: =AmountLenSum()
| |
doc_23527895
|
Is there some universal method for detecting the position of the selected text?
I want to show a tooltip on mouseup or dblclick the selected text.
A: You can use the following code to get the position of selected text:
var selection = window.getSelection();
var getRange = selection.getRangeAt(0);
getRect = getRange.getBoundingClientRect();
A: You can use getSelection api.
After selection a text run below code in console.
var selection = window.getSelection()
var baseOffset = selection.baseOffset
var length = selection.focusOffset -selection.baseOffset
var text = selection.focusNode.data.splice(baseOffset, length)
A: If you just need to get the position where the user doubleclicked, use the following snippet.
$('#thatInput').on('dblclick', function (e) {
alert('Position X: ' + e.clientX + '\nPosition Y: ' + e.clientY);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="thatInput">
A: The question is about getting the position of mouse pointer when selecting text. I am trying a solution that also works with keyboard events (choosed keyup).
I wrote a sample html page with a "vanilla" script inside to test the capabilities of the Selection API. This is the idea:
When selecting on text nodes, getting the position of selected text is done by means of the Range Object.
But when the selected text is a part of an Input Element, using the getBoundingClientRect() of the Range Object does not work (gave me a full zero ClientRect Object.
So, the function getSel() will try to consider both scenarios: selecting text just from the HTML or inside some input elements (just considered input and textarea).
On the bottom of the page there is a div#results element, for displaying data, then getSel() will create a new div#boundy with the coordinates of the ClientRect object or the related input element coordinates.
I wish to finish it, but I'm out of ideas on how to get the actual position of the selected text inside the input objects. It will have to be adding in a relative way to the coordinates of the element itself.
Answering Andrew, if this works, you'll be able to use the coordinates of div#boundy to place the tooltip wherever you want.
I've created a codepen here.
| |
doc_23527896
|
We all know that on web sites we can use normal-roads type, hybrid type, satellite/photo type and, more recently, also the relief type.
this last is the one i'd like to use. I had no problem to insert it in a UIWebView + HTML + standard google API,
but for many reasons now i'd prefer use it with a MKMapView.
But... surprise:
"it seems" we couldn't use tat type of map...
reading in Apple MKMapView Class Reference:
MKMapType
The type of map to display.
enum {
MKMapTypeStandard,
MKMapTypeSatellite,
MKMapTypeHybrid
};
where 0 is for MKMapTypeStandard
1 is MKMapTypeSatellite
and of course 2 is MKMapTypeHybrid...
so we are officially allowed to use just those 3 kind of maps, not the relief type, it seems it doesen't exist at all in the apple framwork...
but i'm curious and so i tried this:
myMKMapView.mapType = 3; // a number not officially declared
and it works perfectly, the apple framweork asks to google the right type of map and then it shows it in my view, both in simulator and iPhone device.
so, that's my question:
Do you think I could use it anyway even if it's not "officially" declared in apple documents?
Would Apple reject my app to use it's framework this way?
thanks in advance,
luca
A: I'm sure Apple would reject your app if they knew you were doing it as they are quite clear that you can only use documented features. I know they have tools which detect calls to undocumented methods and use of private frameworks but whether that extends to checking the value of a property when it's set, I'm not sure.
What I am sure though is that this creates fragile code. If Google introduces other map types and Apple decides to support them all in a future SDK update there's no guarantee that the relief type will remain as 3. Also what if Apple adds a check to this property so that in a future iOS release setting it to 3 will throw an exception? Your app will break for anyone that upgrades their OS and you will be forced to use another map type which may upset your users as the functionality is changing. That's just two examples of changes out of your control that could break this for your users.
In summary, could you use this: Yes, but Apple may reject your app and the only way to find out if they will or not is to do it. You'll also have to stay on your toes to ensure future iOS updates don't break your code.
| |
doc_23527897
|
I deploy it into IIS as website
when call "localhost:9810/api/person" url in browser shows following error
The current identity (IIS APPPOOL\PersonService) does not have write access to
'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files'.
How can i solve this problem ? (step by step guideline needed !)
UPDATE :
I installed all IIS, .NET 3.5, .NET 4.5 features BUT when call http ://localhost/
browser shows this error !!! WHY ?!!!
The current identity (IIS APPPOOL\DefaultAppPool) does not have write access to
'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files'.
and when call (as admin)
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Aspnet_regiis.exe
CMD says :
Microsoft (R) ASP.NET RegIIS version 4.0.30319.33440
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation. All rights reserved.
Start installing ASP.NET (4.0.30319.33440).
This option is not supported on this version of the operating system. Administr
ators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Win
dows Features On/Off" dialog, the Server Manager management tool, or the dism.e
xe command line tool. For more details please see http://go.microsoft.com/fwlin
k/?LinkID=216771.
Finished installing ASP.NET (4.0.30319.33440).
| |
doc_23527898
|
Now I am unable to call it, actually i am unable to fine the url for this controller. I have added static WebApiConfig class in my project and call it in Application_Start method.
//application start.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
//Register web api route
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Web api controller:
public class CitiesController : ApiController
{
CityEntities _entity = new CityEntities();
// GET: api/Cities
[HttpGet]
public IEnumerable<City> Get()
{
return _entity.Cities.ToList();
}
// GET: api/Cities/5
public City Get(int id)
{
return _entity.Cities.Where(x=>x.city_id==id).FirstOrDefault();
}
}
the URL that i did try to call Cities controller are.
*
*http://localhost:56261/api/Cities/Get
*http://localhost:56261/Cities/Get
But not work.
A: If you are not using attribute routing for that action, then action should map to default API route. Take a look at default route template for api routes:
api/{controller}/{id}
Things to consider:
*
*This route has an api path segment. Thus your second url will not match default api route
*This route does not have action parameter. That's because actions of ApiControllers are mapped by HTTP method of the request. You should not specify action name in request url. By convention, for HTTP GET requests name of action should begin with Get word.
So, your actions should be mapped to following HTTP GET requests:
GET http://localhost:56261/api/Cities
GET http://localhost:56261/api/Cities/5
Further reading: Routing in ASP.NET Web API
| |
doc_23527899
|
I have added alert statements which show that userID is stored within hidden-id-field immediately prior to the summoning of the Modify Users page, and thus available for POSTing, but that it is not transported to the Modify Users page.
I have also alert added statements that indicate which Server Request Method is in use at those points in the execution of the page. Other buttons present on my page will similarly need to summon other pages.
My question is this: how do I summon my Modify Users page using POST so that I may transfer my value using POST?
I am capable of using both GET and SESSION variables, but this particular scenario is focussed on POST - GET and SESSION variables are not to be used.
I have consulted my fellow students and all of my lecturers in regards this problem as well as having trawled through over 20 different sites and multiple searches in my search for a solution. None of the "solutions" proposed proved to be at all effective - the people are now just as flummoxed as I and the web-pages used methods that were only suitable for updating the source page rather summoning a new one or just plain wrong.
The following are the files that I have been using for this problem.
RumpUserAdministration.php
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport"
content = "width=device-width, initial-scale=1.0"
>
<meta charset = "utf-8">
<link href = "CSS/RumpIntranetProject.css"
rel = "stylesheet"
type = "text/css"
>
</head>
<body>
<?php
echo "<script>alert( \"" . $_SERVER[ "REQUEST_METHOD" ] . "\" )</script>";
?>
<form id = "entire-page"
action = "RumpUserAdministration.php"
method = "post"
>
<div id = "user-name-list-section">
<div id = "user-name-list">
<div id = "ID15"
class = "list-item row"
name = "ID15"
onclick = "userNameListItemClicked( '15' )"
>
SAMPLE USER 001
</div>
<div id = "ID16"
class = "list-item row"
name = "ID16"
onclick = "userNameListItemClicked( '16' )"
>
SAMPLE USER 002
</div>
</div>
</div>
<input id = "user-administration-button-delete"
name = "delete-submit"
onclick = "loadDeleteUsers()"
type = "submit"
value = "Delete"
>
<input id = "user-administration-button-modify"
name = "modify-submit"
onclick = "loadModifyUsers()"
type = "submit"
value = "Modify"
>
<input id = 'hidden-id-field'
name = 'userID'
type = 'hidden'
value = ''
>
</form>
<?php
if ( $_SERVER[ "REQUEST_METHOD" ] == "POST" )
{
if ( isset( $_POST[ 'modify-submit' ] ) )
{
echo "<script>document.getElementById( 'hidden-id-field' ).value = \"" . $_POST[ 'userID' ] . "\"</script>";
echo "<script>alert( \"hidden-id-field (userID) : \" + document.getElementById( 'hidden-id-field' ).value )</script>";
echo "<script>alert( \"" . $_SERVER[ "REQUEST_METHOD" ] . "\" )</script>";
echo '<script>window.location = "ModifyUsers.php"</script>';
}
else
{
echo "<script>alert( 'Unexpected Administration POST encountered.' )</script>";
}
}
?>
<script>
var existingSelection = null;
function loadModifyUsers()
{
document.getElementById( 'hidden-id-field' ).value = existingSelection;
alert( "Presubmit" );
document.getElementById( 'entire-page' ).submit;
}
function userNameListItemClicked( userID )
{
existingSelection = 'ID' + userID;
document.getElementById( "user-administration-button-modify" ).style.cursor = "pointer";
document.getElementById( "user-administration-button-modify" ).disabled = false;
}
</script>
</body>
</html>
ModifyUsers.php
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport"
content = "width=device-width, initial-scale=1.0"
>
<meta charset = "utf-8">
<link href = "CSS/RumpIntranetProject.css"
rel = "stylesheet"
type = "text/css"
>
</head>
<body>
<?php
echo "<script>alert( 'In further' )</script>";
echo "<script>alert( \"hidden-id-field (userID) : \" + document.getElementById( 'hidden-id-field' ).value )</script>";
echo "<script>alert( \"userID : \" + \"" . $_POST[ 'userID' ] . "\" )</script>";
?>
</body>
</html>
RumpIntranetProject.css
html,
*
{
border : 0;
box-sizing : border-box;
margin : 0;
padding : 0;
}
.list-item
{
display : block;
}
.list-item:hover
{
background-color : #00ffff;
}
.row:after
{
clear : both;
content : "";
display : block;
}
#user-name-list
{
border : 1px;
border-color : black;
border-style : solid;
overflow-y : scroll;
width : 300px;
}
I am not sure if this problem is due to a missed include, typo, wrong command or whichever, I can not say where the fault lies. As such in the interests of completeness I must include the full contents of each minimalised file. I'm working on my definition of "minimal". :)
A: It looks like you are using JavaScript to change the page:
echo '<script>window.location = "ModifyUsers.php"</script>';
What you are doing here is loading ModifyUsers.php, but [as this is a GET] nothing can be passed via POST.
What you need to do instead is change the action of the form to go to ModifyUsers.php: that way your POST data gets passed to the correct page.
A: This is one answer that I just developed. If there are other ways of answering the question, then please post them.
I have placed each Submit button within its own form, including a hidden field in each form.
Each of these buttons successfully summons its form and not something else.
The following is the modified version of RumpUserAdministration.php that I used (ModifyUsers.php and RumpIntranetProject.css are unchanged from the question).
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport"
content = "width=device-width, initial-scale=1.0"
>
<meta charset = "utf-8">
<link href = "CSS/RumpIntranetProject.css"
rel = "stylesheet"
type = "text/css"
>
</head>
<body>
<?php
echo "<script>alert( \"" . $_SERVER[ "REQUEST_METHOD" ] . "\" )</script>";
?>
<div id = "user-name-list-section">
<div id = "user-name-list">
<div id = "ID15"
class = "list-item row"
name = "ID15"
onclick = "userNameListItemClicked( '15' )"
>
SAMPLE USER 001
</div>
<div id = "ID16"
class = "list-item row"
name = "ID16"
onclick = "userNameListItemClicked( '16' )"
>
SAMPLE USER 002
</div>
</div>
</div>
<form id = "form-delete"
action = "Index.php"
method = "post"
>
<input id = 'hidden-id-field-delete'
name = 'userID'
type = 'hidden'
value = ''
>
<input id = "user-administration-button-delete"
name = "delete-submit"
onclick = "loadDeleteUsers()"
type = "submit"
value = "Delete"
>
</form>
<form id = "form-modify"
action = "ModifyUsers.php"
method = "post"
>
<input id = 'hidden-id-field-modify'
name = 'userID'
type = 'hidden'
value = ''
>
<input id = "user-administration-button-modify"
name = "modify-submit"
onclick = "loadModifyUsers()"
type = "submit"
value = "Modify"
>
</form>
<script>
var existingSelection = null;
function loadDeleteUsers()
{
document.getElementById( 'hidden-id-field-delete' ).value = existingSelection;
}
function loadModifyUsers()
{
document.getElementById( 'hidden-id-field-modify' ).value = existingSelection;
}
function userNameListItemClicked( userID )
{
existingSelection = 'ID' + userID;
document.getElementById( "user-administration-button-modify" ).style.cursor = "pointer";
document.getElementById( "user-administration-button-modify" ).disabled = false;
}
</script>
</body>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.