_id stringlengths 2 6 | text stringlengths 4 46k | title stringclasses 1 value |
|---|---|---|
d10201 | because postsRepository is null, you need to initialized it
final PostsRepository postsRepository = PostsRepository();
and remvoe it from constructor | |
d10202 | Instead of using setBackgroundColor, you'll need to use setBackgroundDrawable, and use an xml state list drawable file with pressed/default states.
http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList | |
d10203 | When you use setItem it overwrites the item which was there before it. You need to use getItem to retrieve the old list, append to it, then save it back to localStorage:
function addEntry() {
// Parse any JSON previously stored in allEntries
var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if(existingEntries == null) existingEntries = [];
var entryTitle = document.getElementById("entryTitle").value;
var entryText = document.getElementById("entryText").value;
var entry = {
"title": entryTitle,
"text": entryText
};
localStorage.setItem("entry", JSON.stringify(entry));
// Save allEntries back to local storage
existingEntries.push(entry);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
};
Here is a fiddle which demonstrates the above.
A: adding objects to array in localStorage (Ionic):
var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if(existingEntries == null) existingEntries = [];
var testObject ={username:this.username,
mobile:this.mobile,
email:this.email,
type:this.type,
password:this.password};
localStorage.setItem('testObject', JSON.stringify(testObject));
existingEntries.push(testObject);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
A: Maybe you just need to fetch the entries before pushing the new one:
var allEntries = JSON.parse(localStorage.getItem("allEntries")) || [];
allEntries.push(entry);
//etc...
A:
const object = {
name: 'ayyan',
age: 29,
number: 03070084689,
};
const arr = JSON.parse(localstorage.getItem('key_name')) || [];
arr.push(object);
localstorage.setItem(JSON.stringify('key_name', arr);
A: HTML5 localStorage lets you store key/value pairs of data. Both key and value needs to be a string. To store arrays as a key or value you need to encode the array into a JSON string. And while retrieving you need to decode it back to an array.
const object = {
name: 'ayyan',
age: 29,
number: 03070084689,
};
const arr = JSON.parse(localstorage.getItem('key_name')) || [];
const data = [arr, ...[object]];
localstorage.setitem(JSON.stringify('key', data); | |
d10204 | defaultCenter will only be used by the map for the initial render, so it will not have any effect if you change this value later.
If you use the center prop instead it will work as expected.
const GoogleMapComponent = withScriptjs(
withGoogleMap(props => (
<GoogleMap
defaultZoom={13}
center={props.map_centre}
onDragEnd={props.onDragEnd}
onZoomChanged={props.onZoomChanged}
ref={props.onMapMounted}
/>
))
);
A: Be more specific with the library you are using...you have added the tags "google-maps-react" and "react-google-map" and both are different libraries...
google-maps-react = https://github.com/fullstackreact/google-maps-react
react-google-map = https://tomchentw.github.io/react-google-maps/
Anyway, I can see 2 options:
solution 1:
Add a conditional that renders GoogleMapComponent only if map_centre is not null.
render() {
if(this.state.map_centre){
return (
<div id="map" className="padding-left">
<GoogleMapComponent
townCenters={this.state.townCenters}
schools={this.state.schools}
supermarkets={this.state.supermarkets}
hotels={this.state.hotels}
airports={this.state.airports}
trainStations={this.state.trainStations}
map_centre={this.state.map_centre}
onMapMounted={this.handleMapMounted}
onDragEnd={this.handleMapChange}
onZoomChanged={this.handleMapChange}
onMarkerClick={this.handleAdspaceShow}
googleMapURL={url}
loadingElement={<div style={{ height: `100vh`, width: `100%` }} />}
containerElement={<div style={{ height: `100vh`, width: `100%` }} />}
mapElement={<div style={{ height: `100vh`, width: `100%` }} />}
/>
<img
src={mapSearch}
id="map-search-button"
onClick={this.toggleSearchInput}
/>
<input
id="map-search-input"
className="form-control d-none"
type="search"
placeholder="Enter new location"
aria-label="Search"
onChange={this.handlePostcodeChange}
onKeyPress={this.handleNewSearch}
/>
</div>);
}
return <div> Loading.. </div>;
}
solution 2:
Set a default lat/lng (not null) before you get the response.
constructor(props) {
super(props);
this.state = {
map_centre: { lat: -34.397, lng: 150.644 }
};
} | |
d10205 | It appears that this is as designed. Click-once applications are designed to be deployed to one location. You can specify an update location, but these locations become static once the application is deployed.
The best bet for anyone looking to do this would be some sort of content hosting solution ala Akamai. I tried to come up with a solution similar to that but my IT/Network Admin skills are lacking. | |
d10206 | You may try URL Rewrite if you're using IIS for hosting website. | |
d10207 | use a closure to encapsulate the iterator at the time of adding into a local variable:
for(var i=0;i<10;i++) {
var el = new Element('div').inject($(document.root));
(function(i){
el.addEvent('click',function() {
alert(i);
});
}(i));
}
school of thought says you should not create functions in a loop.
other things you can do is pass the iterator to the constructor and keep it in storage:
var el = new Element('div').store('index', i).inject(document.body);
...
click: function(){
console.log(this.retrieve('index'));
}
you can also use a .each which automatically does an iterator for you:
var a = new Array(10);
a.forEach(function(item, index){
new Element('div', {
events: {
click: function(){
alert(index);
}
}
}).inject(document.body);
});
you could bind it to the callback also... many many patterns.
A: Found a workaround, not sure if it fits what you want.
Check fiddle here
JS/Mootools:
for(var i=0;i<10;i++) {
var el = new Element('div', {onclick: 'alert('+i+')',text:i}).inject(document.body);
} | |
d10208 | Just find select org.telegram.messenegr in spinner of Android Monitor section. | |
d10209 | The reason is that indexing with one integer removes that axis:
>>> X[:, 0].shape
(180,)
That's a one dimensional array, but if you index by giving a start and stop you keep the axis:
>>> X[:, 0:1].shape
(180, 1)
which could be correctly appended to your array:
>>> np.append(a, a[:, 0:1], 1)
array([....])
But all this aside if you find yourself appending and concatenating lots of arrays be warned: These are extremly inefficient. Most of the time it's better to find another way of doing this, for example creating a bigger array in the beginning and then just setting the rows/columns by slicing:
X = np.zeros((180, 361))
X[:, 360] = X[:, 0] # much more efficient than appending or inserting
A: You can create a new axis on X[:,0]:
np.append(X, X[:,0,None], axis=1)
I think the reason why you have to match array shapes is that numpy.append is implemented using concatenate.
A: A key difference is that in MATLAB everything has at least 2 dimensions.
>> size(x(:,1))
ans =
2 1
and as you note, it allows indexing 'beyond-the-end' - way beyond
>> x(:,10)=x(:,1)
x =
1 2 3 1 0 0 0 0 0 1
4 5 6 4 0 0 0 0 0 4
But in numpy indexing reduces the dimensions, without the 2d floor:
In [1675]: x = np.ones((3,4),int)
In [1676]: x.shape
Out[1676]: (3, 4)
In [1677]: x[:,0].shape
Out[1677]: (3,)
That means that if I want to replicate a column I need to make sure it is still a column in the concatenate. There are numerous ways of doing that.
x[:,0][:,None] - use of np.newaxis (alias None) is a nice general purpose method. x[:,[0]], x[:,0:1], x[:,0].reshape(-1,1) also have their place.
append is just concatenate that replaces the list of arguments with 2. It's a confusing imitation of the list append. It is written Python so you can read it (as experienced MATLAB coders do).
insert is a more complicated function (also in Python). Adding at the end it does something like:
In [1687]: x.shape
Out[1687]: (3, 4)
In [1688]: res=np.empty((3,5),int)
In [1689]: res[:,:4] = x
In [1690]: res[:,-1] = x[:,0]
That last assignment works because both sides have the same shape (technically they just have to be broadcastable shapes). So insert doesn't tell us anything about what should or should not work in more basic operations like concatenate. | |
d10210 | If your Linux system has the uncompress command, likely a script that runs gzip, then you can use that to decompress .Z files. | |
d10211 | I would push all async tasks into a promise array and then return them all when all tasks complete:
exports.markDevicesForDownload = functions.database.ref('/UserData/DeviceMgmt/Counters/NumberOfSelected').onUpdate((change) => {
const changeRef = change.after.ref;
const deviceMgmtRef = changeRef.parent.parent; // /UserData/DeviceMgmt
if (change.after.val() === 0) { //NumberOfSelected gets 0 value
return deviceMgmtRef.once('value')
.then((snap) => {
const promises = [];
const devicesRef = snap.child('Devices').ref;
var average;
var numberOfAllDevices;
var totalDownloaded;
numberOfAllDevices = snap.child('Counters/NumberOfAll').val();
totalDownloaded = snap.child('Counters/TotalDownloaded').val();
average = Math.round(totalDownloaded / numberOfAllDevices);
const dR = devicesRef
.orderByChild('signOutTime')
.equalTo(0)
.once('value', (devices) => {
const dW = devices.ref
.orderByChild('downloaded')
.endAt(average)
.once('value', (devices) => {
devices.forEach((device) => {
if (device.child("signOutTime").val() === 0){
promises.push(device.child('toSelect').ref.set(true));
}
});
});
promises.push(dW);
});
promises.push(dR);
return Promise.all(promises);
});
} else {
return false;
}
}); | |
d10212 | You can use a PorterDuffColorFilter with a PorterDuff.Mode.SRC_IN.
This example takes a Drawable and changes every non transparent pixel to green:
drawable.setColorFilter(new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN));
Note: You can easily apply it to a Bitmap converting it into a Drawable using
Drawable drawable = new BitmapDrawable(getResources(), yourBitmap);
A: After some testing I figured out the solution below using a ColorMatrixColorFilter works in an optimal way (applying the matrix takes less than 1/20 of the for-loop).
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
viewMaskPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
viewMaskPaint.setAlpha(maskAlpha);
colorFilterMatrixPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
colorFilterMatrixPaint.setColorFilter(new ColorMatrixColorFilter(new float[] {
0, 0, 0, 255, 0,
0, 0, 0, 255, 0,
0, 0, 0, 255, 0,
0, 0, 0, -255, 255
}));
setWillNotDraw(false);
}
private void setTargetViewLayoutBitmap(final Bitmap viewBmp) {
targetViewLayoutBitmap = Bitmap.createBitmap(viewBmp.getWidth(), viewBmp.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(targetViewLayoutBitmap);
canvas.drawBitmap(viewBmp, 0, 0, colorFilterMatrixPaint);
}
@Override
protected void onDraw(Canvas canvas) {
...
canvas.drawBitmap(targetViewLayoutBitmap, targetViewLeft, targetViewTop, viewMaskPaint);
}
Thank you for @Selvin for pointing me to the right direction (this solution was an interpretation of what you suggested). | |
d10213 | I think you need to call your load mechanism again - since the datasource of your grid isn't updated so it will hold the old data from your last select.
If you have performance issues loading the data again, you could manually alter the data of the edited row.
A: quick fix:
You can try to move this line to Page_Load()
MySQLDataGrid2.DataBind();
Or, after executing the update command, "Refresh" the page by:
Response.Redirect(Request.RawUrl);
A: After Successful Edit.
Try to call your Databind Method.
something like:
private void BindMEthod()
{
//Your code in binding data to your datagridview.
}
protected void MySQLDataGrid2_UpdateCommand(object source, DataGridCommandEventArgs e) {
string newData;
TextBox aTextBox;
aTextBox = (TextBox)(e.Item.Cells[0].Controls[0]);
newData = aTextBox.Text;
decimal comm = Convert.ToDecimal(newData);
string UpdateHiveCommission = "Update tbl_HiveCommission set Commission = '" + Convert.ToDecimal(newData) + "'";
MySqlConnection objMyCon3 = new MySqlConnection(strProvider);
objMyCon3.Open();
MySqlCommand cmd3 = new MySqlCommand(UpdateHiveCommission, objMyCon3);
cmd3.ExecuteNonQuery();
objMyCon3.Close();
// MySQLDataGrid2.EditItemIndex = -1; --
// MySQLDataGrid2.DataBind();
//Replace with this
BindMEthod();
}
Hope this help.
Regards | |
d10214 | Plugins are generally not designed for use with a specific plugin manager. They all use more or less the same mechanisms and standardized file structure and should work the same way whether they are installed manually or "managed" with Vundle, Pathogen or some other script.
You should read Vundle's and your non-working plugin's documentation to see if you can find the why and how of your issue.
Also, what plugins do you have issues with? How did you install them? Are you asking a question with the hope of getting help or just thinking out loud? | |
d10215 | There are several ways to unit test HttpClient, but none are straightforward because HttpClient does not implement a straightforward abstraction.
1) Write an abstraction
Here is a straightforward abstraction and you can use this instead of HttpClient. This is my recommended approach. You can inject this into your services and mock the abstraction with Moq as you have done above.
public interface IClient
{
/// <summary>
/// Sends a strongly typed request to the server and waits for a strongly typed response
/// </summary>
/// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
/// <param name="request">The request that will be translated to a http request</param>
/// <returns>The response as the strong type specified by TResponseBody /></returns>
/// <typeparam name="TRequestBody"></typeparam>
Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(IRequest<TRequestBody> request);
/// <summary>
/// Default headers to be sent with http requests
/// </summary>
IHeadersCollection DefaultRequestHeaders { get; }
/// <summary>
/// Base Uri for the client. Any resources specified on requests will be relative to this.
/// </summary>
AbsoluteUrl BaseUri { get; }
}
Full code reference here. The Client class implements the abstraction.
2) Create a Fake Http Server and Verify the Calls on the Server-Side
This code sets up a fake server, and your tests can verify the Http calls.
using var server = ServerExtensions
.GetLocalhostAddress()
.GetSingleRequestServer(async (context) =>
{
Assert.AreEqual("seg1/", context?.Request?.Url?.Segments?[1]);
Assert.AreEqual("seg2", context?.Request?.Url?.Segments?[2]);
Assert.AreEqual("?Id=1", context?.Request?.Url?.Query);
Assert.AreEqual(headerValue, context?.Request?.Headers[headerKey]);
if (hasRequestBody)
{
var length = context?.Request?.ContentLength64;
if (!length.HasValue) throw new InvalidOperationException();
var buffer = new byte[length.Value];
_ = (context?.Request?.InputStream.ReadAsync(buffer, 0, (int)length.Value));
Assert.AreEqual(requestJson, Encoding.UTF8.GetString(buffer));
}
if (context == null) throw new InvalidOperationException();
await context.WriteContentAndCloseAsync(responseJson).ConfigureAwait(false);
});
Full code reference here.
3) Mock the HttpHandler
You can inject a Mock HttpHandler into the HttpClient. Here is an example:
private static void GetHttpClientMoq(out Mock<HttpMessageHandler> handlerMock, out HttpClient httpClient, HttpResponseMessage value)
{
handlerMock = new Mock<HttpMessageHandler>();
handlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(value)
.Verifiable();
httpClient = new HttpClient(handlerMock.Object);
}
Full code reference. You can then verify the calls from the mock itself. | |
d10216 | If you read Wiki you will see that it only removes duplicates at the same position, which is not the case here. | |
d10217 | No there is no tool for this and this is in general a good thing when it comes to "complex" data in the graph.
Spring Data Neo4j (6) does only fetch the relationships and properties of a node that you define in your model.
If you would map your graph 1:1 you might end up with ones you do not need. They will pollute your code base and create unnecessary long Cypher statements / data transfers.
I would say that there is -in contrast to the usage of RDBMS- a lot of "shared database" usage in the graph world.
The partial match of a domain model in the application to the graph model is no exception here.
Also a tool that blindly converts your data into a model can only make assumptions.
E.g. multiple labels: You can define them in multiple ways depending on your use-case in Spring Data Neo4j.
But which one is the right one for the tool?
This can produce code that is not your desired outcome and you would have to manually refactor it after creation.
Imagine having such a tool in a build chain: You would have to manually fine-tune the resulting model over and over again. | |
d10218 | No, I don't think this is natively supported by git.
May be a local hook like a pre-commit one hook might try to check and checkout the right branch before allowing the commit to proceed. | |
d10219 | Okay so the boto module goes through your boto configuration file to gather your credentials in order to create and edit data in the Google Cloud. If the boto module can not find the configuration file then you will get the errors above. What I did was since, after 3 days straight of trying to figure it out, I literally just put my credentials in the code.
from boto import connect_gs
name = 'the-name-of-your-bucket'
gs_conn = connect_gs(gs_access_key_id='YOUR_ACCESS_KEY_ID',
gs_secret_access_key='YOUR_ACCESS_SECRET_KEY')
"""This is the line that creates the actual bucket"""
gs_conn.create_bucket(name)
It is that simple. Now you can go through and do anything that you want to without the boto configuration file. | |
d10220 | For building your application into a jar file, run mvn clean package which should create a target folder which contains the jar. Also, consider looking into the configuration for maven-jar-plugin maven-shade-plugin and maven-assembly-plugin to customize the jar more.
For creating an installer for your application such as an .exe or .msi file, I'd recommend using Inno Setup (link) or maybe look into jpackage depending on your Java version and environment. | |
d10221 | See this question Pass table as parameter to SQLCLR TV-UDF which has links to other related information. In short, TVP is not currently supported in SQL CLR.
If the result set is small enough you could convert it to an XML type and pass that as a parameter to your SQL CLR function (SqlXml).
You could also have the stored procedures set up temporary tables to share. It's sloppy, but may end up being your only option. | |
d10222 | hg is the executable for Mercurial, you're going to need to download and install Mercurial.
Once you have it installed you can use it to clone the project:
hg clone https://xmppframework.googlecode.com/hg/ xmppframework | |
d10223 | Wow wow, how tortured this is.
def bugged_recursion(inp_value, list_index=0):
# i don't get why you compare list_index here
if list_index == 0:
# you'll get an IndexError if list_index > len(inp_value)
if inp_value[list_index] == 'valid':
status = 'valid inp_value'
else:
status = 'invalid inp'
# there is only one place where you increment list_index
# i suppose there is something wrong here
list_index +=1
# you forgot to return here
return bugged_recursion(inp_value, list_index=list_index)
else:
if inp_value[list_index] == 'valid':
status = 'index {} is a valid inp_value'.format(list_index)
else:
status = 'index is never a valid inp_value'
return (inp_value,status)
That aside, people usually tend to avoid recursion as much as possible (for example on Dive into Python).
Does this cover your needs?
def no_recursion(inp_value):
for i, val in enumerate(inp_value):
# you probably have a good reason to test the index
if i == 0:
if val == 'valid':
yield 'valid inp_value: %s' % val
else:
yield 'invalid inp: %s' % val
else:
yield 'index %s is %s valid inp_value' % (
i,
'a' if val == 'valid' else 'never'
)
print tuple(no_recursion(inp_value))
Gives: ('invalid inp: invalid', 'index 1 is never valid inp_value') | |
d10224 | I'm guessing that the execution context under which your CGI is running is unable to complete the read() from the serial port.
Incidentally the Python standard libraries have MUCH better ways for writing CGI scripts than what you're doing here; and even the basic string handling offers a better way to interpolate your results (assuming you code has the necessary permissions to read() them) into the HTML.
At least I'd recommend something like:
#!/usr/bin/python
import sys, serial
sys.stderr = sys.stdout
ser = serial.Serial('/dev/ttyS0', 2400)
html = """Content-type: text/html
<html><head><title>Real Time Temperature</title></head><body>
<h1>Real Time Temperature:</h1>
<p>%s</p>
</body></html>
""" % ser.readline() # should be cgi.escape(ser.readline())!
ser.close()
sys.exit(0)
Notice we just interpolate the results of ser.readline() into our string using the
% string operator. (Incidentally your HTML was missing <html>, <head>, <body>, and <p> (paragraph) tags).
There are still problems with this. For example we really should at least import cgi wrap the foreign data in that to ensure that HTML entities are properly substituted for any reserved characters, etc).
I'd suggest further reading: [Python Docs]: http://docs.python.org/library/cgi.html
A: one more time:
# Added to allow cgi-bin to execute cgi, python and perl scripts
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
AddHandler cgi-script .cgi .py .pl
<Directory /var/www>
Options +Execcgi
AddHandler cgi-script .cgi .py .pl
</Directory>
A: Michael,
It looks like the issue is definitely permissions, however, you shouldn't try to make your script have the permission of /dev/ttyS0. What you will probably need to do is spawn another process where the first thing you do is change your group to the group of the /dev/ttyS0 device. On my box that's 'dialout' you're may be different.
You'll need to import the os package, look in the docs for the Process Parameters, on that page you will find some functions that allow you to change your ownership. You will also need to use one of the functions in Process Management also in the os package, these functions spawn processes, but you will need to choose one that will return the data from the spawned process. The subprocess package may be better for this.
The reason you need to spawn another process is that the CGI script need to run under the Apache process and the spawn process needs to access the serial port.
If I get a chance in the next few days I'll try to put something together for you, but give it a try, don't wait for me.
Also one other thing all HTTP headers need to end in two CRLF sequences. So your header needs to be:
print "Content-type: text/html\r\n\r\n"
If you don't do this your browser may not know when the header ends and the entity data begins. Read RFC-2616
~Carl | |
d10225 | This isn't really an answer to the "why", but I managed to find out how to fix it myself:
Instead of copying environmental variables from the current process, if I copy them with CreateEnvironmentBlock, then it works.
I still haven't figured out what's causing it, though... | |
d10226 | <my-component (click)="onClick()"></my-component>
Case B:
<my-component></my-component>
Definition:
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
})
export class MyComponent {
@???()
hostHasClickListener: boolean; // I want to know this within my component
}
Thank you!
A: You can achieve this by using an @Output with click as the name. This forces the consumers to bind their function to this click when they use (click)="Blah()" in the HTML.
this.click.observed return true when click is used in the HTML.
mycomponent.component.ts
@Component({
...
})
export MyComponent implements OnInit {
@Output()
public click = new EventEmitter();
private _hasClick = false;
public ngOnInit() {
this._hasClick = this.click.observed;
if(this._hasClick) {
// do something here.
}
}
} | |
d10227 | Add this statement on your header tag:
<style>
a:link{
text-decoration: none!important;
cursor: pointer;
}
</style>
A: a:link{
text-decoration: none!important;
}
=> Working with me :) , good luck
A: You have a block element (div) inside an inline element (a). This works in HTML 5, but not HTML 4. Thus also only browsers that actually support HTML 5.
When browsers encounter invalid markup, they will try to fix it, but different browsers will do that in different ways, so the result varies. Some browsers will move the block element outside the inline element, some will ignore it.
A: Try placing your text-decoration: none; on your a:hover css.
A: if you want a nav bar do
ul{ list-style-type: none; } li{text-decoration: none;
*
*This will make it want to make the style of the list type to None or nothing
with the < a > tag:
a:link {text-decoration: none}
A: I have an answer:
<a href="#">
<div class="widget">
<div class="title" style="text-decoration: none;">Underlined. Why?</div>
</div>
</a>
It works.
A: Add a specific class for all the links :
html :
<a class="class1 class2 noDecoration"> text </a>
in css :
.noDecoration {
text-decoration: none;
}
A: Use CSS Pseudo-classes and give your tag a class, for example:
<a class="noDecoration" href="#">
and add this to your stylesheet:
.noDecoration, a:link, a:visited {
text-decoration: none;
}
A: There are no underline even I deleted 'text-decoration: none;' from your code.
But I had a similar experience.
Then I added a Code
a{
text-decoration: none;
}
and
a:hover{
text-decoration: none;
}
So, try your code with :hover.
A: As a sidenote, have in mind that in other cases a codebase might use a border-bottom css attribute, for example border-bottom: 1px;, that creates an effect very similar to the text-decoration: underline. In that case make sure that you set it to none, border-bottom: none;
A: I had lots of headache when I tried to customize a WordPress theme and the text-decoration didn't help me.
In my case I had to remove the box-shadow as well.
a:hover {
text-decoration: none;
box-shadow: none;
}
A: An old question and still no explanation. The underline is drawn not on your <div class="title"> element but on its parent a, since all browsers set this style for links by default.
If you provide custom decoration style for the inner div - it will be visible instead of the parent style. But if you set none (and it is already set on divs by default), your div will not be decorated, but its parent decoration will become visible instead.
So, as people suggested, in this case to remove all the decoration text-decoration: none; should be set on the parent a element. | |
d10228 | Anonymous class new Something() {...} is not an instance of Something. Instead, it's a subclass/implementation of Something. And so, it's perfectly valid and useful to derive anonymous classes from interfaces.
A: Anonymous class are not instance of a class but just another way to define a class, something similar to a nested class, but less reusable since it's method related.
Since you can define class that implements interfaces
public A implements B {
}
and you can reference the instance of that class, declaring as an interface
B b = new A();
you can do it also with anonymous class.
The only thing to do and to remember (for this exist the compiler), is that you have to implements all method defined in the interface itself.
That solution, is a more concise way to do this:
public EmployeeController {
public Employee getEmployeeById(long id) {
return jdbcTemplate.queryForObject(
"select id, firstname, lastname, salary " +
"from employee where id=?",
new CustomRowMapper(),
id);
}
class CustomRowMapper implements RowMapper<Employee>() {
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee employee = new Employee();
employee.setId(rs.getLong("id"));
employee.setFirstName(rs.getString("firstname"));
employee.setLastName(rs.getString("lastname"));
employee.setSalary(rs.getBigDecimal("salary"));
return employee;
}
}
}
A: The syntax
new SomeInterface() {
// Definition for abstract methods
}
defines an anonymous class. As long as all methods specified in the interface are defined within the braces, this is a valid class which implements the given interface.
Note that this expression defines an anonymous class implicitly and an instance of that class. | |
d10229 | If you run the same application on the same machine, with the same JVM, the heap and GC parameters will be the same.
Ergonomics was a feature introduced way back in JDK 5.0 to try and take some of the guesswork out of GC tuning. A server-class machine (2 or more cores and 2 or more Gb of memory) will use 1/4 of physical memory (up to 1Gb) for both the initial and maximum heap sizes (see https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html). So different machines may have different configurations by default.
To find out exactly what flags you have set, use:
java -XX:+PrintFlagsFinal -version
The difference in memory usage pattern is simply the non-deterministic behaviour of your application. Even with the exact same set of inputs, I doubt you'd see exactly the same memory behaviour just down to so many other OS and hardware effects (cache, core affinity, etc.) | |
d10230 | There is an attribute in your AndroidManifest.xml file, like android:noHistory="true" You must delete this. it solves the problem
A: Do like this
private boolean isAddShown = false;
make this isAddShown = true when the add is visible
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
if(!isAddShown){
super.onBackPressed();
}else{
isAddShown = false;
}
} | |
d10231 | Get LV group name for the item the mouse is down over:
Private thisGroupName As String = ""
Private Sub MouseDown(sender, e As MouseEventArgs)...
If e.Button = MouseButtons.Right Then
thisGroupName = GetLVGroupAt(e.X, e.Y)
End If
End Sub
Private Function GetLVGroupAt(X As Integer, Y as Integer) As String
Dim theGrp As String = ""
Dim ht As ListViewHitTestInfo = myLV.HitTest(X, Y)
' the mouse might be down over a NON item area, like a blank "row"
' AND if the items does not belong to a Group, 'Group' will
' be Nothing:
If (ht.Item IsNot Nothing) AndAlso (ht.Item IsNot Nothing) Then
theGrp = ht.Item.Group.Name
End If
Return theGrp
End Function
Evaluating the Group name is left for the consuming code. | |
d10232 | Answer
Use the colorset argument of chart.CumReturns:
plot_chart <- function(x, col) {
ff <- tempfile()
png(filename = ff)
chart.CumReturns(x, colorset = col)
dev.off()
unlink(ff)
}
par(mar = c(2, 2, 1, 1))
plot_chart(xts1, col = plot_colors)
addSeries(reclass(apply(xts1, 2, runSD), xts1))
par(mar = c(2, 2, 1, 1))
plot_chart(xts2, col = plot_colors)
addSeries(reclass(apply(xts2, 2, runSD), xts2)) | |
d10233 | You get the error for a very valid reason, that is not a valid jsonpath query.
If you go to https://jsonpath.herokuapp.com/ ( which uses jayway ) and enter the same data and path you will see this is not a valid jsonpath query for jayway, or two of the other implementations, the only one that does not fail outright does not return what you are expecting. I think you need to go back and re-read the jsonpath documentation as this syntax clearly is not valid.
The correct syntax is $.response.items[?(@.code=='500')].label as the documentation clearly states.
I would not rely on implementations that do not fail on incorrect syntax. | |
d10234 | Most likely, your screenshot is of an ExpandableListView, or possibly a RecyclerView that uses a library to add expandable contents.
A: Yes, and it's called Expandable List View. | |
d10235 | Try this
let path = GMSMutablePath()
//Change coordinates
path.add(CLLocationCoordinate2D(latitude: -33.85, longitude: 151.20))
path.add(CLLocationCoordinate2D(latitude: -33.70, longitude: 151.40))
path.add(CLLocationCoordinate2D(latitude: -33.73, longitude: 151.41))
let polyline = GMSPolyline(path: path)
polyline.strokeColor = UIColor.blue
polyline.strokeWidth = 3.0
polyline.map = mapView
A: This is my solution with Swift 5.
private var trackLocations: [CLLocation] = []
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
self.trackLocations.append(location)
let index = self.trackLocations.count
if index > 2 {
let path = GMSMutablePath()
path.add(self.trackLocations[index - 1].coordinate)
path.add(self.trackLocations[index - 2].coordinate)
let polyline = GMSPolyline(path: path)
polyline.strokeColor = Global.iOSMapRendererColor
polyline.strokeWidth = 5.0
polyline.map = self.mapView
}
}
} | |
d10236 | You can use the sed utility to parse out just the filenames
sed 's_.*\/__'
A: You can use awk:
The easiest way that I find:
awk -F/ '{print $NF}' file.txt
or
awk -F/ '{print $6}' file.txt
You can also use sed:
sed 's;.*/;;' file.txt
You can use cut:
cut -d'/' -f6 file.txt | |
d10237 | There is a pretty simple fix. In your request-handling functions, where you would have:
return Json(myStuff);
Replace it with the overload that takes a JsonRequestBehavior:
return Json(myStuff, JsonRequestBehavior.AllowGet); | |
d10238 | SELECT A.AUCTION_ID
FROM AUCTION_TABLE A
EXCEPT
SELECT B.AUCTION_ID
FROM BIDS_TABLE B WHERE B.USER_ID='U1'
Could you please try this | |
d10239 | In Scala (and Java), reaching the eof means getting null when trying to read. I don't know how cin.bad translates, but it may be exceptions.
Your example is equivalent to:
def askUser( tries_left: Int = MAX_TRIES ):Int =
Console.readLine match {
case "^Z" | null => -9
case "?V" => {
println( SSVID_ICON + SSVID )
askUser( tries_left )
}
case "?" => {
println( "Enter ? for help, ?V for version, ^Z for exit.")
askUser( tries_left )
}
case response if validate(response) => {
answer_string = response
1
}
case _ => if( tries_left == 0) -9 else askUser( tries_left - 1)
} | |
d10240 | Your R2=0.909 is from the OLS on the train data, while the R2_score=0.68 is based on the correlation of the test data.
Try predicting the train data and use R2_score on the train and predicted train data. | |
d10241 | if you are working with blade, getting a working link this way is bad, you should use laravel helpers like the following:
<form method="POST" action="{{route('site-subscriptions.store')}}" accept-charset="UTF-8" id="form_site_subscription_edit" enctype="multipart/form-data">
this way you are making sure that the links are correct even if you change your APP_URL in the deployment.
what actually done, is calling route helper function to get the URL for you by the route's name.
from the docs:
route():
The route function generates a URL for the given named route:
$url = route('routeName');
If the route accepts parameters, you may pass them as the second argument to the method:
$url = route('routeName', ['id' => 1]);
By default, the route function generates an absolute URL. If you wish to generate a relative URL, you may pass false as the third argument:
$url = route('routeName', ['id' => 1], false); | |
d10242 | Yes, like so:
public string Test { get; set; }
public string AnotherTest
{
get
{
if(_anotherTest != null || Test == null)
return _anotherTest;
int indexLiteryS = Test.IndexOf("S")
return Test.Substring(indexLiteryS, 4);
}
set { _anotherTest = value; }
}
private string _anotherTest;
That getter could also be expressed as
return (_anotherTest != null || Test == null)
? _anotherTest
: Test.Substring(Test.IndexOf("S"), 4);
A: I think this would do what you want it to do:
public sealed class Transaction {
public string Test { get;set; }
public string AnotherTest{
get {
if (_anotherTest != null)
{
return _anotherTest;
}
else
{
int indexLiteryS = Test.IndexOf("S");
return Test.Substring(indexLiteryS, 4);
}
}
set {
_anotherTest = value;
}
}
private string _anotherTest = null;
}
A: I would suggest turning the problem over.
It sounds like you're dealing with a big field and subfields within it. Instead, how about promoting those subfields to fields and constructing/deconstructing the big field when it's accessed. | |
d10243 | You can try with :
@GetMapping(value = '/limit')
@ResponseBody
public Limit limit()
{
return new Limit(1, 10000);
}
A: The following solved my problem:
So yes, just to reiterate, going into my maven repo and deleting the fasterxml folder and re-running maven is what fixed the issue for me. | |
d10244 | Look at @Owl 's answer, it fixes the other problems in your code too.
In your loop the variable key is not defined. You'd have to write it like this:
for (const key in this.colorValues) {
...
}
Although I wouldn't use a for-in loop, since objects have their own prototype properties, which you would also receive in a for-in loop. A better solution would be this:
for (const key of Object.keys(this.colorValues) {
...
}
But since you don't need the keys and just use them to retreive the values in the colorValues object, you could also use this:
for (const color of Object.values(this.colorValues) {
...
}
A: The cannot find name key error is answered by @MrCodingB
A nicer way to write this:
class ResistorColor {
private colors: string[]
public colorValues = {
black: 0,
brown: 1,
red: 2,
orange: 3,
yellow: 4,
green: 5,
blue: 6,
violet: 7,
grey: 8,
white: 9
}
constructor(colors: string[]) {
const colorValues = Object.keys(this.colorValues);
// colorValues is ["black", "brown", "red", ...]
const isValid = colors.every(c => colorValues.includes(c));
// `every` is used to tests whether all elements in the array pass the test implemented by the provided function,
// in this case, we check whether each value exists in `colorValues`
if (isValid) {
this.colors = colors
} else {
throw new Error("Invalid Color(s)");
}
}
}
const resistorColor = new ResistorColor(["black", "brown"]); // correct
console.log("resistorColor has correct color");
const resistorColor2 = new ResistorColor(["black", "brown", "gold"]); // throws error
console.log("resistorColor2 has correct color");
Typescript playground
It's also possible to print out the incorrect colors value by using .filter()
class ResistorColor {
private colors: string[]
public colorValues = {
black: 0,
brown: 1,
red: 2,
orange: 3,
yellow: 4,
green: 5,
blue: 6,
violet: 7,
grey: 8,
white: 9
}
constructor(colors: string[]) {
const colorValues = Object.keys(this.colorValues);
const invalidColors = colors.filter(c => !colorValues.includes(c));
if (invalidColors.length === 0) {
this.colors = colors
} else {
throw new Error(`Invalid Color -> ${invalidColors.join(", ")}`);
}
}
}
const resistorColor = new ResistorColor(["black", "brown"]); // correct
console.log("resistorColor has correct color");
const resistorColor2 = new ResistorColor(["black", "brown", "gold", "foo"]); // throws error "Invalid Color -> gold, foo"
Typescript playground
A: Some of the errors that you are trying to prevent at run-time can be avoided at compile-time with stricter types. You can create a type that only allows specific string literal color names and you can also enforce a minimum length on the colors array using tuple types.
It looks like this.colorValues might just be an enum?
enum COLOR_VALUES {
black = 0,
brown = 1,
red = 2,
orange = 3,
yellow = 4,
green = 5,
blue = 6,
violet = 7,
grey = 8,
white = 9
}
type ColorNames = keyof typeof COLOR_VALUES;
class ResistorColor {
// can have two or more colors
constructor(private colors: [ColorNames, ColorNames, ...ColorNames[]]) {
}
}
Now you can only call the constructor with valid arguments.
const a = new ResistorColor(["black", "blue"]); // ok
const b = new ResistorColor(["black", "blue", "red"]); // ok
const c = new ResistorColor(["black"]); // error: Source has 1 element(s) but target requires 2.
const d = new ResistorColor(["white", "cyan"]); // error: Type '"cyan"' is not assignable to type
Typescript Playground Link
If this.colorValues is an instance variable I would create the initial value outside of the class so that we can use typeof.
const initialValues = {
black: 0,
brown: 1,
red: 2,
orange: 3,
yellow: 4,
green: 5,
blue: 6,
violet: 7,
grey: 8,
white: 9
}
type ColorNames = keyof typeof initialValues;
class ResistorColor {
public colorValues = initialValues;
// can have two or more colors
constructor(private colors: [ColorNames, ColorNames, ...ColorNames[]]) {
}
}
Typescript Playground Link | |
d10245 | You can use a nested FOR JSON subquery, which breaks open the original JSON using OPENJSON and re-aggregates it
SELECT
p.ProductID,
p.ProductName,
(
SELECT
p.ProductID,
p.ProductName,
j.Price,
j.Shipper
FROM OPENJSON(p.Results, '$.Results')
WITH (
Price int,
Shipper varchar(100)
) j
FOR JSON PATH, ROOT('Results')
) AS Results
FROM Product p; | |
d10246 | You can use useState for that as well.
Initialize randNum to '' and then, the place where you are console logging, set the value there. Inside the return function you can access the value by curly braces as {randNum}
Including only relevant part of your code:
function App() {
const [randNum, setRandNumber] = useState(''); // Initialization here
const rollResult = () => {
const min = 1;
const max = parseInt(diceType, 10);
var randNum = 0;
for (let x = 0; x < parseInt(diceNumber, 10); x++){
randNum += min + (Math.round(Math.random() * (max - min)));
}
setRandNumber(randNum) // Set Here
console.log(randNum);
};
return (
<div className="App">
<header className="App-header">
...
<div id="diceRoll">
The result is: {randNum} // Show Here
</div>
...
</header>
</div>
);
}
Hope it helps. Revert for any confusions.
A: Just add another useState variable and populate it within the button onClick handler:
const{ useRef, useState } = React;
function App() {
const [diceType, setDiceType] = useState('');
const [diceNumber, setDiceNumber] = useState('');
const [rollResult, setRollResult] = useState(0);
const handleDiceTypeInput = e => {
setDiceType(e.target.value);
};
const handleDiceNumberInput = e => {
setDiceNumber(e.target.value);
};
const handleButton = () => {
const min = 1;
const max = parseInt(diceType, 10);
var randNum = 0;
for (let x = 0; x < parseInt(diceNumber, 10); x++){
randNum += min + (Math.round(Math.random() * (max - min)));
}
console.log(randNum);
setRollResult(randNum);
}
return (
<div>
<select onChange={handleDiceTypeInput}>
<option value=""></option>
<option value="4">D4</option>
<option value="6">D6</option>
<option value="8">D8</option>
<option value="10">D10</option>
<option value="12">D12</option>
<option value="20">D20</option>
<option value="100">D100</option>
</select>
<select as="select" onChange={handleDiceNumberInput}>
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button onClick={handleButton}>
Roll
</button>
<div id="diceRoll">
The result is: {rollResult}
</div>
</div>
);
}
const app = React.createElement(App);
ReactDOM.render(app, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="app"></div> | |
d10247 | May be try to use http_s_:// when making api requests or opening the web-interface | |
d10248 | You are binding your click events on document ready based on the value of selected - only the first click event in your code will ever be bound to the element as the initial value is zero. You need to move the logic in to the click function so that the value is checked every time the function runs:
$(document).ready(function(){
$(".color").click(function(){
if(selected == 0){
/* do something if value is zero */
} else {
/* do something if value is NOT zero */
}
});
}); | |
d10249 | You're busily waking up and going back to sleep at 100uS intervals -- 10 threads, 1ms, that's 100uS on average. And keep in mind that you have two context switches for each of those 100uS intervals, so you have a context switch every 50uS on average, or 20,000 times per second.
Perhaps that's the answer you're looking for? | |
d10250 | If you're in a saga, simply yield the promise. Redux saga will wait for it to resolve and then resume the saga, much like await would do in an async function:
const foo = () => Promise.resolve('foo');
const resultingPromise = foo();
function* exampleSaga() {
const result = yield resultingPromise;
console.log(result); // 'foo'
}
If the promise might reject, you can wrap it in a try catch:
try {
const result = yield resultingPromise;
console.log(result);
} catch(err) {
console.log('promise rejected', err);
}
A: const myFunc = async () => {
const result = await foo();
return result;
// or just return foo() without await, as it is last statememnt in async func
}
Otherwise you can always do
foo()
.then((result) => console.log('result', result))
.catch((err) => console.error(err)); | |
d10251 | Just #name would be enough to apply the style only to that specific element:
#name {
// your styles here
}
If you want to apply the style to all the elements using the class_name class, then you can use:
.class_name {
// your styles here
}
A: #name .class_name will apply to the children elements of your div with the .class_name class.
There must not be any spaces between.
You should use: #name.class_name because it is the correct syntax.
But, when working with identifiers, it should be enough to use it alone.
#name {
// some properties
}
But let's say you have a unique block, which inherits some generic styles, then you could use #idenifier.class to mix styles.
#comments {
width: 453px;
}
#comments.links
{
border: 0 none;
}
A: If I got your question right you use
#name .class_name
as in
#name .class_name {
color:#000;
}
But actually you don't need to do that.
If #name and .class_name are oly used in that div you can just drop the .class_name. Otherwise, if you use multiple stuff with .class_name that don't share the same properties as div #name, you should separate them.
.class_name {
color:#000;
}
#name {
width:600px;
}
A: ID's should be unique, so there isn't much point in styling both the id of the div and the class_name.
Just using the ID of the div is fine if that's your goal.
#name
{
//styles
}
If you want to style every div that has that class name, then just use
.class_name
{
//styles
}
A: You can read about CSS selectors here:
http://reference.sitepoint.com/css/selectorref
In the CSS you can reference it by class:
.class_name { color: green; }
or by id using #id
#name { color: green; }
or by element type
div { color: green; }
//or by combinations of the above
div.class_name { color: green; }
div#name { color: green; }
A: If you already have #name and .class_name styled, but for some reason you want to style
<div id="name" class="class_name"></div>
(that is, a specific style to the element with an id of "name" AND a class of "class_name"), you can use
#name.class_name {
/* note the absence of space between the id and class selector */
...
}
Bear in mind that this selector is not supported by Internet Explorer 6. | |
d10252 | Unless you have a lot of knowledge of how the compiler works, you cannot know a priori where these variables are stored, or even how they are represented. Each compiler designer makes his own rules for how/where variables are stored.
You might be able to figure out for a specific compiled program, by inspecting the generated code. | |
d10253 | Try this:
total=0
for i in range(5):
num = int(input(f"Please enter number {i+1}: "))
total+=num
print(total) | |
d10254 | You can use NSPredicate to search the text inside your objects, like this
let searchString = "test"
var arr:NSArray =
[["value" : "its a test text to find"],
["value" : "another text"],
["value" : "find this text"],
["value" : "lorem ipsum is a placeholder text commonly"],
["value" : "lorem ipsum is a"]]
var pre:NSPredicate = NSPredicate(format: "value CONTAINS[c] %@", searchString)
var result:NSArray = arr.filtered(using: pre) as NSArray
print(result)
it will return a array with the result based on the text that you search
A: Algolia is probably the best solution right now, and is something Firebase themselves recommend. Just a few things to bear in mind is that you'll need a paid for Firebase plan to implement as you'll need a Cloud Function that sends data over to Algolia for indexing.
Once your data is in Algolia there is a great Swift library you can use to implement the Search Bars / Autocompletion you need. | |
d10255 | The purpose of HWPF subproject is exactly that: process Word files.
http://poi.apache.org/hwpf/index.html
Then, to convert the data to XML you have to build XML by the ususal ways: StAX, JDOM, XStream...
Apache offers a Quick Guide:
http://poi.apache.org/hwpf/quick-guide.html
and I also have found that:
http://sanjaal.com/java/tag/simple-java-tutorial-to-read-microsoft-document-in-java/
If you want to process docx files, you might want to look at the OpenXML4J subproject:
http://poi.apache.org/oxml4j/index.html
A: I'd say you have two options, both powered by Apache POI
One is to use Apache Tika. Tika is a text and metadata extraction toolkit, and is able to extract fairly rich text from Word documents by making appropriate calls to POI. The result is that Tika will give you XHTML style XML for the contents of your word document.
The other option is to use a class that was added fairly recently to POI, which is WordToHtmlConverter. This will turn your word document into HTML for you, and generally will preserve slightly more of the structure and formatting than Tika will.
Depending on the kind of XML you're hoping to get out, one of these should be a good bet for you. I'd suggest you try both against some of your sample files, and see which one is the best fit for your problem domain and needs.
A: package com.govind.service;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.model.StyleDescription;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* DOC to XML converter service
*
* @author govind.sharma
*
*/
public class DocToXmlConverter {
static final Logger logger = Logger.getLogger(DocToXmlConverter.class);
DocumentBuilderFactory docFactory = null;
DocumentBuilder docBuilder = null;
Element rootElement = null;
Document docxml = null;
boolean subHeaders = false;
Element UrlElement = null;
/**
* @param path
* @param fileName
*/
public void processDocxToXml(String path, String fileName) {
XWPFDocument xdoc = null;
FileInputStream fis = null;
String fullPath = path + "/" + fileName + ".docx";
try {
// Read file
fis = new FileInputStream(fullPath);
xdoc = new XWPFDocument(OPCPackage.open(fis));
initializeXml();
// get Document Body Paragraph content
List < XWPFParagraph > paragraphList = xdoc.getParagraphs();
for (XWPFParagraph paragraph: paragraphList) {
String styleName = paragraph.getStyle();
String paraText = paragraph.getParagraphText();
String bulletsPoints = paragraph.getNumFmt();
createXmlTags(styleName, paraText, bulletsPoints);
}
// write the content into XML file
generateXml(path, fileName);
logger.info("Doc to Xml Convertion completed.");
} catch (Exception ex) {
logger.error("Exception while generating XML from DOC" + ex.getMessage());
System.exit(0);
}
}
/**
* @param path
* @param fileName
*/
public void processDocToXml(String path, String fileName) {
HWPFDocument doc = null;
String fullPath = path + "/" + fileName + ".doc";
WordExtractor we = null;
try {
POIFSFileSystem fis = new POIFSFileSystem(new FileInputStream(fullPath));
doc = new HWPFDocument(fis);
} catch (Exception e) {
logger.error("Unable to Read File..." + e.getMessage());
System.exit(0);
}
try {
we = new WordExtractor(doc);
Range range = doc.getRange();
initializeXml();
String[] paragraphs = we.getParagraphText();
for (int i = 0; i < paragraphs.length; i++) {
org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
int j = 0;
while (true) {
CharacterRun run = pr.getCharacterRun(j++);
StyleDescription style = doc.getStyleSheet().getStyleDescription(run.getStyleIndex());
String styleName = style.getName();
String paraText = run.text();
String bulletsPoints = null;
createXmlTags(styleName, paraText, bulletsPoints);
if (run.getEndOffset() == pr.getEndOffset()) {
break;
}
}
}
generateXml(path, fileName);
logger.info("Document to Xml Convertion completed.");
} catch (Exception ex) {
logger.error("Exception while generating XML from DOC" + ex.getMessage());
System.exit(0);
}
}
/**
*
*/
private void initializeXml() {
// initialize XML Document
try {
docFactory = DocumentBuilderFactory.newInstance();
docBuilder = docFactory.newDocumentBuilder();
docxml = docBuilder.newDocument();
rootElement = docxml.createElement("ROOT");
docxml.appendChild(rootElement);
} catch (ParserConfigurationException e) {
logger.error("Exception while initializing XML" + e.getMessage());
}
}
/**
* @param styleName
* @param paragraphText
* @param bulletsPoints
*/
private void createXmlTags(String styleName, String paragraphText, String bulletsPoints) {
// create XML Tags
if (styleName != null && paragraphText.length() > 1) {
if (styleName.equalsIgnoreCase("Style4")) {
Element pragElement = docxml.createElement("TITLE");
pragElement.appendChild(docxml.createTextNode(paragraphText.trim()));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("Default")) {
Element pragElement = docxml.createElement("P");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("Normal")) {
Element pragElement = docxml.createElement("P");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("BodyCopy") && bulletsPoints != null) {
Element pragElement = docxml.createElement("LI");
pragElement.appendChild(docxml.createTextNode(paragraphText));
UrlElement.appendChild(pragElement);
subHeaders = false;
} else if (styleName.equalsIgnoreCase("BodyCopy")) {
Element pragElement = docxml.createElement("PS");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("ListParagraph")) {
Element pragElement = docxml.createElement("LI");
pragElement.appendChild(docxml.createTextNode(paragraphText));
UrlElement.appendChild(pragElement);
subHeaders = false;
} else if (styleName.equalsIgnoreCase("Subheader1")) {
UrlElement = docxml.createElement("UL");
Element pragElement = docxml.createElement("LI");
pragElement.appendChild(docxml.createTextNode(paragraphText));
UrlElement.appendChild(pragElement);
rootElement.appendChild(UrlElement);
subHeaders = false;
} else {
Element pragElement = docxml.createElement("PS");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
}
} else if (paragraphText.trim().length() > 1) {
Element pragElement = docxml.createElement("P");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
}
if (subHeaders) {
Element pragElement = docxml.createElement("NEWLINE");
pragElement.appendChild(docxml.createTextNode(""));
rootElement.appendChild(pragElement);
}
}
/**
* @param path
* @param fileName
*/
private void generateXml(String path, String fileName) {
try {
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
DOMSource source = new DOMSource(docxml);
StreamResult result = new StreamResult(new File(path + "/" + fileName + ".xml"));
transformer.transform(source, result);
} catch (Exception e) {
logger.error("Exception while generating XML" + e.getMessage());
}
}
} | |
d10256 | This should work
$('.quantity').click(function() {
var that = this;
$.post('quantity.php', { quantityId: $(that).attr('id') }, function(data) {
$(that).html(data);
});
});
But this is how i'd write it
<div class="quantity" data-id='<?=$unique_id?>'>
Quantity
</div>
$('.quantity').on('click', function() {
var that = this;
$.post('quantity.php', { quantityId: $(that).data('id') }, function(data) {
$(that).html(data);
});
});
And for dynamic divs
<div class="quantity" data-id='<?=$unique_id?>'>
Quantity
</div>
$(document).on('click', '.quantity', function() {
var that = this;
$.post('quantity.php', { quantityId: $(that).data('id') }, function(data) {
$(that).html(data);
});
});
A: The onclick binding to your div won't work once the div has been refreshed (it binded on document.ready() right?). The solution will be either to rebind the function to your element every time you change it (a bad one) or use the on() function of jquery. Example code:
$(document).on('click', '.quantity', function(){
var id = $(this).attr('id');
$.post('quantity.php', { quantityId: id }, function(data){
$('#'+ id).html(data);
});
});
UPDATE: As discussed in comments, the on method should bind to the document as a whole and not the the class to actually work as the deprecated live() method. | |
d10257 | The correct code:
<form class="" action="insert.php" method="POST">
<input type="range" min="1" max="10" value="5" class="slider" id="myRange" name="myrange">
<p>Value: <span id="demo"></span></p>
<button id="btn1">Click Here</button>
</form>
and in the insert.php:
<?php
$getRangeValue = $_POST['myrange'];
$mysqli = new mysqli("localhost","root","passwd","table_name");
//
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$query = $mysqli->prepare("INSERT INTO ertekek (RangeValue, anotherValue) VALUES (?, 11)");
$query->bind_param('i',$getRangeValue);
$query->execute();
echo "New record has id: " . $mysqli -> insert_id;
$mysqli -> close();
?>
What have I changed?
*
*I changed the method method="POST" instead of method="$_POST"
*Change GET to POST on variable $getRangeValue
*Using prepare statment instead of simple and not secure query
Link that I recommend you to read
*
*What is the difference between POST and GET?
*How can I prevent SQL injection in PHP? | |
d10258 | Using icmp package:
const icmp = require('icmp');
icmp.send('8.8.8.8', "Hey, I'm sending a message!")
.then(obj => {
console.log(obj.open ? 'Done' : 'Failed')
})
.catch(err => console.log(err));
A: if you use nodejs, you could use exec to call system ping command.
const exec = require('child_process').exec;
function process(error, stdout, stderr) {
//TODO: process result or logging.
}
exec("ping -c 3 localhost", process);
Or you can use 3rd party libraries.
https://github.com/nospaceships/node-net-ping | |
d10259 | I believe you need to add certificates information for envoy
tls_context:
common_tls_context:
tls_certificates:
- certificate_chain:
filename: "/etc/ssl/certs/https.crt"
private_key:
filename: "/etc/ssl/certs/key.pem"
And also add trust the certificate used by cluster.
tls_context:
common_tls_context:
validation_context:
trusted_ca:
filename: "/etc/ssl/certs/cluster.crt" | |
d10260 | I was passing the token wrong. Instead of:
get '/me', params: {}, headers: {access_token: token.token}
I had to use:
get '/me', params: {}, headers: { 'Authorization': 'Bearer ' + token.token}
A: You can check your Access Token factory's scopes, It should be same as initializer's default_scopes
e.g.
config/initializers/doorkeeper.rb
default_scopes :read
Below, your Access Token factory's scopes should be
factory :access_token, class: "Doorkeeper::AccessToken" do
sequence(:resource_owner_id) { |n| n }
application
expires_in { 2.hours }
scopes { "read" }
end
Additionally, if you encountered response status: 406 while get '/me'....
It means that the requested format (by default HTML) is not supported. Instead of '.json' you can also send Accept="application/json" in the HTTP header.
get '/me', params: {}, headers: {
'Authorization': 'Bearer ' + token.token,
'Accept': 'application/json'}
I resolved my problem with this solution, maybe you can try it. | |
d10261 | You could do this a few different ways. What I would do is run one query that says "get me all pages ordered by the sum total of their items" then loop through them in php, and for each one, do a "get me the top 3 items for the current page".
Make sense?
Query one (untested, written on my phone):
SELECT p.page_name, (SELECT SUM(item_price) FROM items WHERE page_id = p.page_id) AS cumulative_price FROM pages p ORDER BY cumulative_price DESC;
Query two (also untested) looping through results of query one:
SELECT * FROM items WHERE page_id = '$currentPageId' ORDER BY item_price DESC LIMIT 3;
A: *
*I'm assuming every page_id is equal to item_id, and that's how they're linked together. (If not, please correct me.)
*I'm just going to call the second table "table2" and the item_id I'm looking up "SOME_ITEM_ID"
SELECT * FROM `table2` WHERE `item_id` = 'SOME_ITEM_ID' ORDER BY `item_price` DESC;
In English what this is saying is:
Select everything from table2 where the item_id is this, and order the list by item_price in descending order
This SQL statement will return every hit, but you would just output the first three in your code.
A: My gut tells me that there is probably no faster way to do this than to do a for-loop in the application over all of the pages, doing a little select item_price from item where page_id = ? order by item_price desc limit 3 for each paqe, and possibly sticking the results in something like memcached so you aren't taxing your database too much.
But I like a challenge, so i'll attempt it anyhow.
SELECT p1.*, i1.*,
(SELECT count(*)
FROM items i2
WHERE i1.item_price < i2.item_price
AND p1.page_id = i2.page_id) price_rank,
FROM pages p1
LEFT OUTER JOIN items i1
ON p1.page_id = i1.page_id
WHERE price_rank < 3;
That odd sub-select is going to probably do an awful lot of work for every single row in items. many other RDBMses have a feature called window functions that can do the above much more elegantly. For instance, if you were using PostgreSQL, you could have written:
SELECT p1.*, i1.*,
RANK(i1.item_price)
OVER (PARTITION BY p1.page_id
ORDER BY i1.item_price DESC) price_rank
FROM pages p1
LEFT OUTER JOIN items i1
ON p1.page_id = i1.page_id
WHERE price_rank <= 3;
And the planner would have arranged to visit rows in an order that results in the rank occurring properly. | |
d10262 | For reference, here's an example the doesn't have the problem. It uses a GridLayout(0, 1) with congruent gaps and border. Resize the enclosing frame to see the effect. Experiment with Box(BoxLayout.Y_AXIS) as an alternative.
I suspect the original code (mis-)uses some combination of setXxxSize() or setBounds(), which will display the effect shown if the chosen Look & Feel has different geometry specified by the buttons' UI delegate.
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** @see https://stackoverflow.com/a/31078625/230513 */
public class Buttons {
private void display() {
JFrame f = new JFrame("Buttons");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new GridLayout(0, 1, 10, 10));
p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
for (int i = 0; i < 3; i++) {
p.add(new JButton("Button " + (i + 1)));
}
f.add(p);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Buttons()::display);
}
} | |
d10263 | If you use ember-cli just create a file app/utils/area.js:
export default function () {...};
and then you can import it and use it:
import area from 'myapp/utils/area`;
import Ember from 'ember';
export default Ember.Controller.extend({
area,
});
However if you'r not using ember-cli, this question is not ember specific. Then it depends how you organize your code. But you really should check out ember-cli!
But always remember, this is just javascript. This is valid code:
function area() {
...
}
App.AController=Ember.Controller.Extend({
area
});
App.BController=Ember.Controller.Extend({
area
}); | |
d10264 | I think the only thing, you can do in your case, open all the values of a variable and select all and copy-paste like the Mark pointed out in his comment.
A: Would a print statement work? you could use a global counter to keep track of which pass you are at and then compare the values in the consoles. | |
d10265 | I would recommend you to use background tasks for that. Pausing your PHP script will not help you in speeding up page loading. Apache (or nginx or any other web-server) sends whole HTTP packet back to browser only when PHP script is completed.
You can use some functions related to output stream and if web-server supports chunked transfer then you can see progress while your page is loading. But for this purpose many developers use AJAX-queries. One query for one chunk of data. And store position of chunk in a session.
But as I wrote at first the better way would be using background tasks and workers. There are many ways of implementation this approach. You can use some specialized services like RabbitMQ, Gearman or something like that. And you can just write your own console application that you will start and check by cron-task. | |
d10266 | Did it with.
image = Image.open("./static/img/test.jpg")
img_io = StringIO()
image.save(img_io, 'JPEG', quality=70)
img_io.seek(0)
return send_file(img_io, mimetype='image/jpeg') | |
d10267 | This should be:
object[] attrs = type.GetCustomAttributes(true);
Changing typeof(T) to input type. The GetCustomAttributes method gets attributes ON the called type.
A: This line is the problem:
object[] attrs = typeof(T).GetCustomAttributes(true);
You're calling GetCustomAttributes on Type - not on the type that you're actually interested in. You want:
object[] attrs = type.GetCustomAttributes(true);
Or rather more simply, replace the rest of the method with:
return (T) type.GetCustomAttributes(typeof(T), true).FirstOrDefault();
Note that that will also pick up attributes which are subclasses of T, but I'd expect that to be more useful anyway, in the rare cases where you're actually using inheritance on attributes. | |
d10268 | Exceptions thrown in tasks are always handled by the Task object itself. The exception is later rethrown when you, e.g., access the Task.Result property. This way the handling of the exception is left to the thread creating the Task. If you run the first code snippet and look at the Output pane, you'll see that there are multiple first-chance InvalidOperationException logged there. The exceptions are thrown - the tasks just stash them away for later rethrowing.
Parallel.For actually does the same - it stashes away all exceptions occurring within the delegate and then, when the loop is finished, it rethrows all exceptions that occurred in a single AggregateException. You'll notice that the debugger breaks in the thread calling Parallel.For, not within the delegate passed to it.
To cause the exception in the task to propagate to the calling thread, like Parallel.For does, call Wait/WaitAll on the tasks. | |
d10269 | I would suggest that rather than reload the entire root VC, you have separate data classes which you can reset as necessary - after all, the VC is really for displaying it all. | |
d10270 | Use SimpleDateFormat:
If your date is in 31/12/2014 format.
String my_date = "31/12/2014"
Then you need to convert it into SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(my_date);
if (new Date().after(strDate)) {
your_date_is_outdated = true;
}
else{
your_date_is_outdated = false;
}
or
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(my_date);
if (System.currentTimeMillis() > strDate.getTime()) {
your_date_is_outdated = true;
}
else{
your_date_is_outdated = false;
}
A: I am providing the modern answer.
java.time and ThreeTenABP
Use LocalDate from java.time, the modern Java date and time API.
To take the current date
LocalDate currentDate = LocalDate.now(ZoneId.systemDefault());
System.out.println(currentDate);
When I ran this code just now, the output was:
2020-01-05
To get selected date in your date picker
int year = 2019;
int month = Calendar.DECEMBER; // but don’t use `Calendar`
int dayOfMonth = 30;
LocalDate selectedDate = LocalDate.of(year, month + 1, dayOfMonth);
System.out.println(selectedDate);
2019-12-30
Your date picker is using the same insane month numbering that the poorly designed and long outdated Calendar class is using. Only for this reason, in an attempt to produce readable code, I am using a constant from that class to initialize month. In your date picker you are getting the number given to you, so you have no reason to use Calendar. So don’t.
And for the same reason, just as in your own code I am adding 1 to month to get the correct month number (e.g., 12 for December).
Is the date in the past?
if (selectedDate.isBefore(currentDate)) {
System.out.println("" + selectedDate + " is in the past; not going to next activity");
} else {
System.out.println("" + selectedDate + " is OK; going to next activity");
}
2019-12-30 is in the past; not going to next activity
Converting to String and back
If you need to convert your selected date to a string in order to pass it through the Intent (I don’t know whether this is a requirement), use the toString and parse methods of LocalDate:
String dateAsString = selectedDate.toString();
LocalDate recreatedLocalDate = LocalDate.parse(dateAsString);
System.out.println(recreatedLocalDate);
2019-12-30
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
*
*In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
*In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
*On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
*
*Oracle tutorial: Date Time explaining how to use java.time.
*Java Specification Request (JSR) 310, where java.time was first described.
*ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
*ThreeTenABP, Android edition of ThreeTen Backport
*Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
A: Use below code,
*
*Create a date object using date formator.
*Compare date (There many way out to compare dates and one is mentioned here)
*Open intent or make toast as you said message.
CalendarView cal.setOnDateChangeListener(new OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
String s = (month + 1) + "-" + dayOfMonth + "-" + year;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Date dateSource = null;
Calendar cal = Calendar.getInstance();
Date sysDate = cal.getTime();
try {
dateSource = sdf.parse(s);
if(dateSource.compareTo(sysDate)>0){
Toast.makeToast("Selected worng date",Toast.SHOW_LONG).show();
}else{
Intent in = new Intent(MainActivity.this, sec.class);
in.putExtra("TextBox", s.toString());
startActivity(in);
}
}
catch (ParseException e) {
Loger.log("Parse Exception " + e);
e.printStackTrace();
}
}
}
Edit
*
*You need a view xml having the calender defined in it. It can be a fragment or activity view xml file
*Inflate the view in your Activity or fragment class.
View _rootView = inflater.inflate({your layout file},container, false);
*Get the respective control java object from the xml like
cal = (CalendarView)_rootView.findViewById(R.id.calViewId);
*Now call event listener on this cal object.
A: Try this lines of code, this may help. Cheers!!!
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = sdf.parse(enteredDate);
if (System.currentTimeMillis() > date.getTime()) {
//Entered date is backdated from current date
} else {
//Entered date is updated from current date
}
} catch (ParseException e) {
e.printStackTrace();
} | |
d10271 | you can add the title tag with JavaScript within your condition (if, else, or whatever)
document.getElementById('myID').setAttribute('title', 'your tooltiptext');
dont Forget to set the id of your a-tag.. | |
d10272 | Using a session the way you suggested would screw up cases where (1) a visitor opens several different articles in multiple tabs, and (2) tries to write a reply on any tab other than the one that was opened last. The user might even write two replies simultaneously in different tabs; I sometimes do that on StackOverflow. Web developers so easily forget that today's visitors may have several browser tabs open at the same time. Really, we don't use IE6 anymore.
A solution would be to make $_SESSION['item_id'] an array of recently viewed article IDs, but then you won't be able to stop some Firebug user (or any other tech savvy person) from replying to a previously viewed article. Adding time limits won't change anything, either.
But why would somebody intentionally change the ID of the post to which they're replying, except to troll or spam the site? And if somebody really wanted to screw your site, they can easily get around any protection by making their bot request the appropriate page just before posting a spam comment. You'd be much better off investing in a better CSRF token generator, spam filter, rate limiter, etc.
A: Honestly, you're probably okay using the hidden form element. If you're really concerned about someone changing it, you could always base64() encode it to make it harder to change.
However, you could always set a session variable on the page and then when the form is submitted call that value back.
Form
<?
session_start();
//Make a random ID for this form instance
$form_id = rand(1, 500);
//Set session variable for this form
$_SESSION[$form_id]['item_id'] = $item_id;
?>
<form method="post" action="process.php?n=<?=$form_id?>">
<!-- form data here -->
<input type="submit" name="submit">
</form>
Process
<?
session_start();
//Process only if the number submitted matches the SESSION variable
if(array_key_exists($_GET['n'], $_SESSION) {
//Process tasks
echo $_SESSION[$_GET['n']['item_id'];
//Unset session variable when done processing
unset($_SESSION[$_GET['n']);
}
?>
A: Use the hidden field.
If the user modifies the DOM to say it is a reply to a different comment, so what? It only affects them.
If you want to limit what the user can reply to, then you need to implement a proper access control layer and not try to enforce it in the user interface.
A: As you may have noticed from the angry, pitchfork-wielding mob, neither solution is very satisfying due to issues like multiple tabs.
If there is a genuine concern about people being able to post comments on another object then the one they were initially visiting, consider storing them in $_SESSION using an array, and having them post the ID back using a hidden form. If the value posted back is not in the array, then it is obviously a post that he was not looking at.
To increase tamper-proofness, considering about hashing the ID (of course with a generous salting), and storing those in the array.
Do note that I feel you may be trying to solve the wrong problem here; why not validate if the person has access to make a comment on the post he is commenting on? If you have access, then you should be allowed to comment - if you want to tamper with the ID and make your comment end up under the wrong post.. well, that's basically your problem. I mean, the user could also go to the other post, and make the wrong comment there manually... so what is the issue?
A: You could have a form like this
<?
$saltedhash = md5("MYSEED"+$item_id;)
?>
<form method="post" action="blah">
<!-- form data here -->
<input type="hidden" name="item_id" value="<? echo $item_id ?>">
<input type="hidden" name="item_hash" value="<? echo $saltedhash ?>">
<input type="submit" name="submit">
</form>
This was, you can always check that the passed item_id matches its corresponding hash and see if the user changed it.
However, as pointed by others, this won't prevent the user from posting on different items as if they can get the hash from somewhere... An access control mechanism would be preferable
A: Using $_SESSION to store the post ID is the ideal solution since it does avoid the ability to modify that value.
That being said, what are the benefits to someone doing that? As well, many comment systems have an approval process that requires an admin to approve the comment before posting anyway.
But yes, I would recommend sticking with the session value. | |
d10273 | const arr = ["Foo", " ", "bar", " "];
var str = arr.join(" ");
console.log('"' + str + '"');
console.log("str length: " + str.length);
Works here... although you probably really meant to do arr.join(""); without the space. | |
d10274 | Did the following, instead of WriteLinesToFile Task
<SaveFormattedXml XmlString="%(ExportResult.FileContent)" FilePath="%(ExportResult.XmlFileName).xml"/>
<UsingTask TaskName="SaveFormattedXml" TaskFactory="CodeTaskFactory" AssemblyFile="c:\Program Files (x86)\MSBuild\12.0\Bin\amd64\Microsoft.Build.Tasks.v12.0.dll">
<ParameterGroup>
<XmlString ParameterType="System.String" Required="true" />
<FilePath ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq"/>
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Using Namespace="System.Xml" />
<Using Namespace="System.Xml.Linq" />
<Code Type="Fragment" Language="cs">
<![CDATA[
XDocument doc = XDocument.Parse(XmlString);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
settings.NewLineChars = "\r\n";
settings.NewLineHandling = NewLineHandling.Replace;
using (Stream fileStream = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (XmlWriter writer = XmlWriter.Create(fileStream, settings))
{
doc.Save(writer);
}
}
]]>
</Code>
</Task> | |
d10275 | This is not valid SQL:
CASE WHEN B1.BUSX != ' ' AND S1.S1TV = B1.BTX THEN 1
WHEN S1.S1TV = B1.B2TX THEN 1
ELSE 0
(although some databases do support it). Instead, use OR:
( (B1.BUSX <> ' ' AND S1.S1TV = B1.BTX) OR
(B1.BUSX = ' ')
)
I should point out that you can use CASE, but you need some comparison afterwards:
(CASE WHEN B1.BUSX != ' ' AND S1.S1TV = B1.BTX THEN 1
WHEN S1.S1TV = B1.B2TX THEN 1
ELSE 0) = 1
However, I think the basic boolean operations are simpler. | |
d10276 | Since your token is somewhat dynamic, I would suggest that you shouldn't pass it directly to your view models. Rather, pass the AppState object and retrieve the token when needed.
If you detect an expired token you can call a function on the AppState that obtains a refresh token and updates its token property. | |
d10277 | In fact, in the case of a connection failure, the response object you receive in your error callback is an error one since the value of its type attribute is 3 (ERROR). What is a bit strange is that it seems that the preflighted request is executed and received a response. Could you give us its details from the Network tab in dev tools (by clicking on "OPTIONS http://localhost:...")?
See this question for more details:
*
*Get error message from Angular 2 http | |
d10278 | I think it uses the .ashx to 1.) trigger the use of the ASP.NET isapi filter and 2.) signal that the requests aren't mapped to any physical files, but URLs mapped to logical pages within the Wiki engine.
And I don't think it's dangerous to create ASP.NET page responses on the fly, which is essentially what they do. It's actually a quite brilliant way to let you, the user of the system, build up the hierarchy of the web site.
A: Does it actually really craete pages on the fiy on disc?
An ashx is a handler. It returns output as it wants. You can have a CMS that exposes it's tree thruogh a .ashx in between (/cms.ashx/some/page) but the pages NEVER EXIST. | |
d10279 | That's something you can fix with CSS. However, if you have a proper reference to the jQueryUI CSS file, I don't think you should be seeing this. Make sure that reference is present and correct. | |
d10280 | <div> elements are set to span the width of their parent element, so changing the font size will have no effect on its actual width. Changing your <div> to a <span> should give you what you're looking for.
A: Add float: left; to #holder
#holder which is the test container for width, is defaulting to width: auto;. In other words, it is spanning 100% of the browser window and giving you the mixed results.
You might consider adding white-space: nowrap; as well to #holder should it ever exceed the width of it's container.
Updated fiddle
A: It may look nasty but gives you the width:
http://jsfiddle.net/adaz/YaPcP/43/ | |
d10281 | Like everyone is pointing out
making your own logging system is tricky. it required you to do additional steps to make the content secured. Not only to hackers but you as administrator of the database shouldn't have access to see your customers password in PlainText Most users will use the same password on your site as they used for there email password they registered with on your site..
It is more advisable to create login tools like laravel, Or simply research how to build a secure login system, because what we are seeing here in your code, is BAD, Not syntactically, but from a security stand point.
Me knowing you store passwords like that, I wouldn't register onto your website.
Any how not only that, But you really should have a look into mysqli binding
Or even, and something I like better is PDO_Mysql
Your code will not only be more clear to read, but will bind values directly to a a field within mysql ( no need to use real_escape_string no more )
Now to actually answer your question.
You probably should make some kind of javascript live validator on the field of your form directly.
then on PHP side, You can do a simple condition with REGXP and preg_match()
Have a look at https://regex101.com/r/SOgUIV/1 this is a regex that will validate EMAILs.
With this link, You should then experiment a bit with it, it has not only documentation on the side but also possibles quantifier and such.
if(preg_match("/^((?!\.)[\w-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/i",trim($_POST['Email']))){
//What ever is in here will get process when $_POST['emailpost'] is valid.
}
Edited ----
As some user pointed out in comments.
You would probably be better of using
if(filter_var($_POST['emailpost'],FILTER_VALIDATE_EMAIL){
//What ever is in here will get process when $_POST['emailpost'] is valid
}
Also if you want to make sure user has access to the email address account, You could also add two column within your users table, isConfirmed,ConfirmationCode
When the user register, You create a unique code and put it into ConfirmationCode then send the user an email with something along those line "Please click the following link to activate account www.yourWebSite.com/confirmationPage.php?Code=$TheActualCodeYouCreatedForThatUser"
Then once user get to that page, Change the field isConfirmed to '1' or true.
Once there on your website, you will be able to assume that only emails with isConfirmed is a real user.
A: To validate email you need to check a lot of stuff like
*
*if the email already exists
*if its a real email i.e check for presence of @
*check for funny characters which are not supposed to be in an email.
then always encrypt your password
if ($_POST['submit']) {
$errors = array();
$email = $conn->real_escape_string($_POST['emailpost']);
$password = $conn->real_escape_string($_POST['passpost']);
$firstname = $conn->real_escape_string($_POST['firstnamepost']);
$lastname = $conn->real_escape_string($_POST['lastnamepost']);
$phonenumber = $conn->real_escape_string($_POST['phonenumberpost']);
$education = $conn->real_escape_string($_POST['institutionpost']);
$facebook = $conn->real_escape_string($_POST['facebookpost']);
$twitter = $conn->real_escape_string($_POST['twitterpost']);
$instagram = $conn->real_escape_string($_POST['instagrampost']);
$filename = $_FILES['uploadprofileimg']['name'];
$filename = $ran.$filename;
$filetmp = $_FILES['uploadprofileimg']['tmp_name'];
$filetype = $_FILES['uploadprofileimg']['type'];
move_uploaded_file($filetmp, "../userimages/".$filename);
if (strlen($email) && strlen($password) && strlen($firstname) && strlen($lastname) && strlen($phonenumber) && strlen($education) && strlen($facebook) && strlen($twitter) && strlen($instagram)) {
//check for a valid email
if(preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^",$email))
$errors['email'] = 'invalid email address';
//check for presence of @ in email
if (!stristr($em,"@") OR !stristr($em,".") $errors['email'] = 'please enter an email';
//echeck if email already exists in database
$checkemail = $conn->get_row("SELECT * FROM elmtree_users WHERE email=".$email);
if( $conn->num_rows( $checkemail ) > 0 ) $errors['email'] = "User already exists with the email: " . $email;
//validate password
$minpasslen = 8;
if (strlen($password) < $minpasslen)
$errors['email'] = 'password is too short';
$finalpassword = MD5($password);
if (empty($errors)) {
$insertuser = "INSERT INTO elmtree_users (user, email, pw, firstName, lastName, profileimg, learninginstitute, phone, facebook, twitter, instagram) VALUES
('$username', '$email', '$finalpassword', '$firstname', '$lastname', '$filename', '$education', '$phonenumber', '$facebook', '$twitter', '$instagram')";
$resultinsert = $conn -> query($insertuser);
if(!$resultinsert){
echo $conn->error;
} else {
echo "<h2> Account successfully registered!</h2>
<h4>Please <a href='login.php'> <font class='text-success'><strong>login.</strong></font></a></h4><br><br><br><br>";
} else {
echo implode('<br>', $errors);
}
}
} | |
d10282 | There's probably a more elegant way, but you could use a string template to represent the product/color combination.
Playground Link
interface Order {
orderId: number;
productName: string;
color: string;
quantity: number;
price: number;
link: string;
}
interface Summary {
productName: string;
color: string;
quantity: number;
price: number;
}
const makeKey = (order: Order) => {
return `${order.productName}_${order.color}`;
}
type AggregatedOrders = {
[key: string]: Summary;
};
const orders: Order[] = [
{
color: "blue",
link: "https://savantly.net",
orderId: 123,
price: 999,
productName: "hello",
quantity: 1
},
{
color: "green",
link: "https://savantly.net",
orderId: 345,
price: 999,
productName: "hello",
quantity: 1
},
{
color: "green",
link: "https://savantly.net",
orderId: 234,
price: 999,
productName: "hello",
quantity: 1
}
];
const groups: AggregatedOrders = {};
orders.forEach(o => {
const key = makeKey(o);
if(!groups[key]) {
groups[key] = o;
} else {
groups[key].price += o.price;
groups[key].quantity + o.quantity
}
});
// grouped by product and color
console.log(groups); | |
d10283 | There are two algorithms: restoring and non-restoring. This is very well described in Division Algorithms and Hardware Implementations by Sherif Galal and Dung Pham. And here is about implementation in VHDL. | |
d10284 | The consumer test is analogous to a unit test. It will always pass if your code does what you expect it to in the test. It isn't dependent on prior state (such as a previous generated contract).
The part of the process where you would check for a breaking change is in CI with the can I deploy tool (https://docs.pact.io/pact_broker/can_i_deploy). | |
d10285 | pushAndRemoveUntil:
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) =>
LoginScreen()), (Route<dynamic> route) => false);
This code will route to the login screen and pop all the screens which are in the back stack.
popUntil:
Navigator.of(context).popUntil(ModalRoute.withName('/widget_name'));
This code will pop all the screens till the mentioned screen, here that screen name is widget_name | |
d10286 | Try this code:
$file_dir = "upload/demofiles";
if ($handle = opendir($file_dir)) {
$i = 1;
while (false !== ($entry = readdir($handle))) {
$format = pathinfo($entry, PATHINFO_EXTENSION);
$file_path = $file_dir.'/'.$entry;
switch($format){
case "txt":
$myfile = fopen($file_path, "r") or die("Unable to open file!");
$file_element = '<iframe src="'.$file_path.'" width="80px" style="height:80px" scrolling="no"></iframe>';
break;
case "png":
$myfile = fopen($file_path, "r") or die("Unable to open file!");
$file_element = '<img src="'.$file_path.'" />';
break;
case "zip":
$myfile = fopen($file_path, "r") or die("Unable to open file!");
$file_element = '<img width="64px" class="img" src="icons/zip.png" />';
fclose($myfile);
break;
case "pdf":
$file_element = '<embed src="'.$file_path.'" width="80px" scrolling="no" style="height:80px">';
break;
default:
$file_element = '<img class="img" width="64px" src="icons/file.png">';
break;
}
if ($entry != "." && $entry != "..") {
echo '<label style="display:inline-block; border:solid 1px;">
<div>'.$file_element.'</div>
<div>'.$entry.'</div>
</label>';
}
$i++;
}
} | |
d10287 | It can be done with either html5 canvas or and old trick. If you want to "crop" irregular shapes, create an image and fill the irregular shape transparent and the rest same color as the background, then overlay the shape on top of the portion of the image you want to make irregular and if needed use a higher z-index.
Check out How to generate color variations of the product. | |
d10288 | Yes you would need to implement this using native code or thru the Socket API by implementing the DNS protocol calls.
The InetAddress class can be used in the Android/Desktop ports but other platforms (e.g. iOS) would need the Objective-C/C equivalent of that. | |
d10289 | The above code executes synchronously, therefore you return in the same frame before any promise has the chance to resolve.
We can clean the above code up as follows:
module.exports = app => {
app.get("/api/seMapServerStatus", (req, res) => {
const ports = ["27111", "27112", "27117", "27118", "27119", "27110", "27115", "27116", "27113", "27114"]
function hitServers(port) {
return Gamedig.query({
type: "aGameType",
host: "theServer'sIP",
port: port
})
}
// With error handling
function hitServersSafe(port) {
return hitServers(port)
.then(result => {
return {
success: true,
result: result
}
})
.catch(error => {
return {
success: false,
// you probably need to serialize error
error: error
}
})
}
const promises = ports.map(port => hitServers(port))
// With error handling
// const promises = ports.map(port => hitServersSafe(port))
Promise
.all(promises)
.then(data => res.json(data))
.catch(error => {
// do something with error
})
})
}
We map each port to a promise. After we have a list of X promises we wait for all of them to finish.
The calling Promise.all() returns an array of resolved values, or rejects when any promise rejects.
Only after all of the promises have resolved we can move on and send the result to the client. | |
d10290 | VPC support has now been added for Elasticache in Cloudformation Templates.
To launch a AWS::ElastiCache::CacheCluster in your VPC, create a AWS::ElastiCache::SubnetGroup that defines which subnet in your VPC you want Elasticache and assign it to the CacheSubnetGroupName property of AWS::ElastiCache::CacheCluster.
A: You workaround is a reasonable one (and shows that you seem to be in control of your AWS operations already).
You could improve on your custom solution eventually by means of the dedicated CustomResource type, which are special AWS CloudFormation resources that provide a way for a template developer to include resources in an AWS CloudFormation stack that are provided by a source other than Amazon Web Services. - the AWS CloudFormation Custom Resource Walkthrough provides a good overview of what this is all about, how it works and what's required to implement your own.
The benefit of using this facade for a custom resource (i.e. the Amazon ElastiCache cluster in your case) is that its entire lifecycle (create/update/delete) can be handled in a similar and controlled fashion just like any officially supported CloudFormation resource types, e.g. resource creation failures would be handled transparently from the perspective of the entire stack.
However, for the use case at hand you might actually just want to wait for official support becoming available:
*
*AWS has announced VPC support for ElastiCache in the context of the recent major Amazon EC2 Update - Virtual Private Clouds for Everyone!, which boils down to Default VPCs for (Almost) Everyone.
We want every EC2 user to be able to benefit from the advanced networking and other features of Amazon VPC that I outlined above. To enable this, starting soon, instances for new AWS customers (and existing customers launching in new Regions) will be launched into the "EC2-VPC" platform. [...]
You don’t need to create a VPC beforehand - simply launch EC2
instances or provision Elastic Load Balancers, RDS databases, or
ElastiCache clusters like you would in EC2-Classic and we’ll create a
VPC for you at no extra charge. We’ll launch your resources into that
VPC [...] [emphasis mine]
*This update sort of implies that any new services will likely be also available in VPC right away going forward (else the new EC2-VPC platform wouldn't work automatically for new customers as envisioned).
Accordingly I'd expect the CloudFormation team to follow suit and complete/amend their support for deployment to VPC going forward as well.
A: My solution for this has been to have a controller process that polls a message queue, which is subscribed to the SNS topic which I notify CloudFormation events to (click advanced in the console when you create a CloudFormation stack to send notifications to an SNS Topic).
I pass the required parameters as tags to AWS::EC2::Subnet and have the controller pick them up, when the subnet is created. I execute the set up when a AWS::CloudFormation::WaitConditionHandle is created, and use the PhysicalResourceId to cURL with PUT to satisfy a AWS::CloudFormation::WaitCondition.
It works somewhat, but doesn't handle resource deletion in ElastiCache, because there is no AWS::CloudFormation::WaitCondition analogue for stack deletion. That's a manual operation procedure wth my approach.
The CustomResource approach looks more polished, but requires an endpoint, which I don't have. If you can put together an endpoint, that looks like the way to go. | |
d10291 | To quote the documentation:
The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. To make this search case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation
You can overcome this by explicitly using a case sensitive collation:
select * from names where name='Bill' COLLATE latin1_general_cs
A: There is also another solution to set the collection of the column to utf8mb4_unicode_520 or any case sensitive standard collections. | |
d10292 | The number after image dimensions is supposed to be the maximum value in the image. You have it as '0'. Scanning quickly through the data, the value should be 247. Just replace the 0 with 247, using a text editor. | |
d10293 | Here's what will happen when we run this:
*
*starting from the top, we define three different functions: clunk, thingamajig and display
*then we initialize a variable called clunkCounter and assign to it the number 0
*then we call the thingamajig function, passing in the argument 5 for the size parameter
*in thingamajig, we'll enter the else branch, and we'll end up going through the while loop 4 times, so we're effectively doing facky = 1 * 5 * 4 * 3 * 2, so facky ends up with a value of 120
*then we call clunk(120)
*so we'll call display("clunk") 120 times
*display just logs "clunk", and as a side-effect increments the clunkCounter, to record how many times we've done this
*then finally we log out clunkCounter, which will be 120
Why would we want to do this? I don't know. It's a very contrived example which demonstrates how to use if/else conditionals and incrementing variables. I wouldn't worry too much about what it all "means". If you haven't already, try running it in the browser console, and messing around to see what happens if you change the value you pass in to thingamajig.
Edit: Very well explained. Just to add a little, its calculating the Factorial of a number and printing its value at the end.
A: The main thing to understand for those that still don't get it (like I did not understand when I first looked at this) is that "facky" changes values every time the while loop runs. So if you start with thingamajig(5), facky=5. But then size becomes "size=4" which makes it so you go through the while loop again. THIS TIME facky is going to be "facky=5x4" and therefore it is "facky=20". Then you go through the while loop again with "size=3" which makes it "facky=20x3" and there for it is "facky=60". One last time through the while loop and you get "facky=60x2" and therefore it is "facky=160".
A: it starts with thingamajig(5);
function thingamajig(size) {
var facky = 1;
clunkCounter = 0;
if (size == 0) {
display("clanck");
} else if (size == 1) {
display("thunk");
} else {
while (size > 1) {
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
}
it takes "5" as parameter which means the "size" variable is 5 and starts to check the conditions in if blocks.
now lets see. the size is 5 so it will skip the first 2 part of the if block
`if (size == 0) {
display("clanck");
} else if (size == 1) {
display("thunk");
}`
and execute the else part
else {
while (size > 1) {
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
this while loop will work until the size > 1 that means the size should be 1 to break the loop. there are some calculations in the while loop.
the "facky" variable changes but in the end the "size" variable will be "1" and the "facky" will be 96
when the "while loop" ends it will call clunk(facky);
that means
`function clunk(96) {
var num = 96;
while (96 > 0) {
display("clunck");
num = num - 1;
}
}`
this function will call "display" function 96 times. and display function will console log "clunck" word for 96 times in the console.
in the end the clucnkCounter will be consoled log.
I hope i understand the question right. because answering this question in writing is hard.
A: *
*in thingamajig() function the value is passed 5.
*and its is checked whether its matches with 0 or 1, then its goes to else block,
here is while loop. facky variable initial value is 1 but here its value is
assign again so its become 5, and size is decremented so become 4
*again in while its greater than 1, again 5*4=20, facky become 20.
*while continue until size value is 1. when size value is 1, facky become 120.
*(5)x(4)x(3)x(2) = 120
*now clank function is called and times = 120
*here num = times, so num = 120
*while num > 0, it call another function display, which console.log(output). And
here output = "clunk".
*And increase the value of clunkCounter by 1.
*Its keep on repeating until num = 0, and making clunkCounter = 120
A: -The code starts executing from the else code block in the function thingamajig(size), since the if and else if statement are false.
else {
while (size > 1) {
facky = facky * size;
size = size - 1; }
clunk(facky); }
}
In the else statement we have a while loop with a condition (size > 1), size is 5 inserted as an argument for the size parameter when invoked
thingamajig(5);.
The code loops till size = 1, when the condition becomes false.
*
*LOOP 1,
while size = 5 , facky is = 1, facky = 1 * 5 = 5, size - 1 =size becomes 4.
*LOOP 2,
while size = 4, facky = 5, facky = 4 * 5 = 20, size - 1 = size becomes 3.
*LOOP 3,
while size = 3, facky = 20, facky = 3 * 20 = 60, size - 1 = size becomes 2.
*LOOP 4,
while size = 2, facky = 60, facky = 3 * 60 = 120, size - 1 = size becomes 1.
*
*Before loop stops The clunk() function is invoked and facky is passed as an argument to the times parameter, the function clunk starts executing.
function clunk(times) {
var num = times;
while (num > 0) {
display("clunk");
num = num - 1; }
}
Here, times = facky = 120 = num, The while loop starts executing until num = 0 when the condition becomes false, in this loop the display() function is invoked with the string 'clunk' as an argument.
function display(output) {
console.log(output);
clunkCounter = clunkCounter + 1;
}
*
*The display('clunk') function starts executing.
*'clunk' string is copied into the output parameter and it is logged into the console & clunkCounter variable increments.
-The both continues logging string 'clunk' & incrementing clunckCounter, until num = 0, as num decrements from 120 till it gets to 0.
Results
console.log(output);
*
*'clunk' strings logs into the console 120 times.
console.log(clunkCounter);
-clunkCounter increments till its 120 so 120 is logged into the console. | |
d10294 | db.PersonDetails.aggregate([
{$lookup:{
from: "MotorDetails",
localField:"personId",
foreignField:"personIdEquivalentOnMotorDetails",
as:"PersonToManufacturer"
}}
])
Search on stackoverflow(check existing questions) and Google if you want to learn something new. Do not post direct questions where answers are already present on stackoverflow. https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
You should read , try out yourself and post here only if you stuck at some point.
A: MongoDB being a NoSQL database does not support concept of relationships
Alternatively it facilitates defining relationship using embedded documents.
Also MongoDB has added $lookup operator which is used to perform left outer join operations into MongoDB Database as a part of aggregation pipeline.
For more detailed description regarding $lookup operator please refer documentation as mentioned into following URL
https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ | |
d10295 | I would change the colorList to array containing photoshop hex values and then use it like this:
var nicEditorColorButton = nicEditorAdvancedButton.extend({
addPane : function() {
var colorList = {0 : '000000',1 : 'FFFFFF'}; /* here goes color list */
var colorItems = new bkElement('DIV').setStyle({width: '270px'});
for(var g in colorList) {
var colorCode = '#'+colorList[g];
var colorSquare = new bkElement('DIV').setStyle({'cursor' : 'pointer', 'height' : '15px', 'float' : 'left'}).appendTo(colorItems);
var colorBorder = new bkElement('DIV').setStyle({border: '2px solid '+colorCode}).appendTo(colorSquare);
var colorInner = new bkElement('DIV').setStyle({backgroundColor : colorCode, overflow : 'hidden', width : '11px', height : '11px'}).addEvent('click',this.colorSelect.closure(this,colorCode)).addEvent('mouseover',this.on.closure(this,colorBorder)).addEvent('mouseout',this.off.closure(this,colorBorder,colorCode)).appendTo(colorBorder);
if(!window.opera) {
colorSquare.onmousedown = colorInner.onmousedown = bkLib.cancelEvent;
}
}
this.pane.append(colorItems.noSelect());
}});
Not sure if my code is edited correctly but you get the basic idea. Remove 2 for loops and loop within the colorList directly | |
d10296 | There are two things to consider here. First, if you truly need a delay, it is better to await a promise than use sleep. You can do this via await new Promise (resolve => setTimeout(resolve, DELAY_LENGTH);. I use this frequently in conjunction with typing indicator to give the bot a more natural feeling conversation flow when it sends two or more discrete messages without waiting for user input.
However, as Eric mentioned, it seems like you might want a waterfall dialog instead for your use case. This sample from botbuilder-samples is a good example. Each step would be a prompt, and it will wait for user input before proceeding. I won't try to write an entire bot here, but a single question-answer step would look something like:
async firstQuestion(stepContext) {
return await stepContext.prompt(TEXT_PROMPT, 'Question 1');
}
async secondQuestion(stepContext) {
stepContext.values.firstAnswer = stepContext.result;
return await stepContext.prompt(TEXT_PROMPT, 'Question 2');
}
and so forth. Not sure what you are doing with the responses, but in the example above I'm saving it to stepContext.values so that the answers are all available in later steps as part of the context object.
If you can detail more of what your use case/expected behavior and share what askFirstSetOfQuestions is, we could provide further assistance. | |
d10297 | Fire event on button click like this
$('.clickme').click(function(){
$('.nav-tabs > .active').next('li').find('a').trigger('click');
}); | |
d10298 | Test the type of the variable and branch the code.
json_query filter helps to select the items from the list. Then ternary helps to conditionally select the value. The value of the first item that matches the condition is used. Defaults to 'NOTFOUND'.
For example the play bellow for both versions of ou_reg_list
- hosts: localhost
vars:
ou_reg_list:
- { name: OU1 }
- { name: OU2 }
# ou_reg_list:
# { name: OU1 }
srv_type: 'ou1'
tasks:
- set_fact:
ou_name: "OU={{ (ou_reg_list.name == srv_type|upper)|
ternary( ou_reg_list.name, 'NOTFOUND') }}"
when: ou_reg_list is mapping
- block:
- set_fact:
ou_names: "{{ ou_reg_list|json_query(query) }}"
vars:
query: "[?name=='{{ srv_type|upper }}'].name"
- set_fact:
ou_name: "OU={{ (ou_names|length > 0)|
ternary( ou_names.0, 'NOTFOUND') }}"
when: ou_reg_list is not mapping
- debug:
var: ou_name
gives
"ou_name": "OU=OU1" | |
d10299 | For #2 you could access the sender "if the strategy is declared inside the supervising actor"
If the strategy is declared inside the supervising actor (as opposed to within a companion object) its decider has access to all internal state of the actor in a thread-safe fashion, including obtaining a reference to the currently failed child (available as the sender of the failure message).
The message is not made available so the only option is to catch your exception and throw a custom one with the message that was received.
Here is a quick fiddle
class ActorSO extends Actor {
def _receive: Receive = {
case e =>
println(e)
throw new RuntimeException(e.toString)
}
final def receive = {
case any => try {
_receive(any)
}
catch {
case t:Throwable => throw new ActorException(self,t,any)
}
}
}
Update
A Decider is just a PartialFunction so you can pass it in the constructor.
object SupervisorActor {
def props(decider: Decider) = Props(new SupervisorActor(decider))
}
class SupervisorActor(decider: Decider) extends Actor {
override val supervisorStrategy = OneForOneStrategy()(decider)
override def receive: Receive = ???
}
class MyDecider extends Decider {
override def isDefinedAt(x: Throwable): Boolean = true
override def apply(v1: Throwable): SupervisorStrategy.Directive = {
case t:ActorException => Restart
case notmatched => SupervisorStrategy.defaultDecider.apply(notmatched)
}
}
object Test {
val myDecider: Decider = {
case t:ActorException => Restart
case notmatched => SupervisorStrategy.defaultDecider.apply(notmatched)
}
val myDecider2 = new MyDecider()
val system = ActorSystem("stackoverflow")
val supervisor = system.actorOf(SupervisorActor.props(myDecider))
val supervisor2 = system.actorOf(SupervisorActor.props(myDecider2))
}
By doing so, you won't be able to access supervisor state like the ActorRef of the child that throw the exception via sender() (although we are including this in the ActorException)
Regarding your original question of accessing from the supervisor the child message that cause the exception, you can see here (from akka 2.5.3) that the akka developers choose to not make it available for decision.
final protected def handleFailure(f: Failed): Unit = {
// ¡¡¡ currentMessage.message is the one that cause the exception !!!
currentMessage = Envelope(f, f.child, system)
getChildByRef(f.child) match {
/*
* only act upon the failure, if it comes from a currently known child;
* the UID protects against reception of a Failed from a child which was
* killed in preRestart and re-created in postRestart
*/
case Some(stats) if stats.uid == f.uid ⇒
// ¡¡¡ currentMessage.message is not passed to the handleFailure !!!
if (!actor.supervisorStrategy.handleFailure(this, f.child, f.cause, stats, getAllChildStats)) throw f.cause
case Some(stats) ⇒
publish(Debug(self.path.toString, clazz(actor),
"dropping Failed(" + f.cause + ") from old child " + f.child + " (uid=" + stats.uid + " != " + f.uid + ")"))
case None ⇒
publish(Debug(self.path.toString, clazz(actor), "dropping Failed(" + f.cause + ") from unknown child " + f.child))
}
} | |
d10300 | I'm afraid your code is invalid - the search algorithm requires forward iterators, but istreambuf_iterator is only an input iterator.
Conceptually that makes sense - the algorithm needs to backtrack on a partial match, but the stream may not support backtracking.
The actual behaviour is undefined - so the implementation is allowed to be helpful and make it seem to work, but doesn't have to.
I think you either need to copy the input, or use a smarter search algorithm (single-pass is possible) or a smarter iterator.
(In an ideal world at least one of the compilers would have warned you about this.)
A: Generally, with Microsoft's compiler, if your program compiles and links a main() function rather than a wmain() function, everything defaults to char. It would be wchar_t or WCHAR if you have a wmain(). If you have tmain() instead, then you are at the mercy of your compiler/make settings and it's the UNICODE macro that determines which flavor your program uses. But I doubt that char_t/wchar_t mismatch is actually the issue here because I think you would have got an warning or error if all four of the search parameters didn't use the same the same character width.
This is a bit of a guess, but try this:
if(eof == search(istreambuf_iterator<char>(fin.rdbuf()), eof, term.begin(), term.end()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.